content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def real_time(buoy, dataset="txt"): """Get realtime data from the NDBC. There are six different data sources to pull from: - data_spec: Raw Spectral Wave Data - ocean: Oceanographic Data - spec: Spectral Wave Summary Data - supl: Supplemental Measurements Data - swdir: Spectral Wave Data (a...
81cf144bf4e13f89624fdb0ccdd3523e80d1d5fb
55,091
def GetBPM_FromMIDI(midiFileName): """ returns list of [bpm, pos] floats """ mid = MidiFile(midiFileName, clip = True) bpms = [[round(tempo2bpm(msg.tempo), 2), msg.time] for msg in mid.tracks[0] if msg.type == "set_tempo"] # this one replicates the extra bpm added in the box files ...
10b115ccdbee6308ff1c542007ce049436dbaf17
55,092
from typing import Any def make_execution_engine( engine: Any = None, conf: Any = None, **kwargs: Any ) -> ExecutionEngine: """Create :class:`~fugue.execution.execution_engine.ExecutionEngine` with specified ``engine`` :param engine: it can be empty string or null (use the default execution eng...
ddba690eb05b84c51756432f9cc969f5397fe876
55,093
def get_nice_levels(variable, center_on_zero=False, nlevel=11, min_percentile=0.1, max_percentile=99.9): """ Create levels for contour plots Parameters ---------- variable : xarray.DataArray or np.ndarray the values for which the levels should be created nlevel : int nu...
f1636c41872573ea3172257526053f1bb31d2ca3
55,094
from typing import Tuple from typing import Optional def parse_proxy( proxy: bytes, default_scheme: bytes = b"http", default_port: int = 1080 ) -> Tuple[bytes, bytes, int, Optional[ProxyCredentials]]: """ Parse a proxy connection string. Given a HTTP proxy URL, breaks it down into components and chec...
3ea90f90b4eb1d16adfc57babe28035d67610213
55,095
import logging def _get_logger(): """ Generate a logger with a stream handler. """ logger = logging.getLogger('epc') hndlr = logging.StreamHandler() hndlr.setLevel(logging.INFO) hndlr.setFormatter(logging.Formatter(logging.BASIC_FORMAT)) logger.addHandler(hndlr) return logger
8c96d2395e1d907a389346e5e3b94f41c0b62fe3
55,096
def split_matrix_to_train_and_test(mat, true_labels, train_indexes, test_indexes, print_stat=False): """ """ train_mat = mat[train_indexes,:] true_train_labels = true_labels[train_indexes] test_mat = mat[test_indexes,:] true_test_labels = true_labels[test_indexes] if print_stat: ...
67cceeaba8733a8692c38775527ea93b4aae2d33
55,097
def move_item( client: EWSClient, item_id, target_folder_path, target_mailbox=None, is_public=None ): """ Moves an item within the same mailbox :param client: EWS Client :param item_id: item id :param target_folder_path: target folder path :param (Optional) target_mailbox: mailbox contai...
8b214d331559d6223b7c15bc257f42cffff0fd78
55,098
def assign_dose_on_position_with_constraint( source_genome: np.ndarray, destination_genome: list, index: int, interval_in_indices: int, last_index_with_non_zero_dose: int = None, ): """ Przypisuje niezerową dawkę w dozwolonym czasie z uwagi na obostrzenia czasowe. Do użytku z: * nor...
779420afc9489099ee2648fcb360d4d50a6a2f9b
55,099
import numpy import sympy def solution_conductivity(I, gamma, conc_vals, charges, cond_molar_zero): """ Solution non-ideal conductivity calculation Ref: http://www.aqion.de/site/77#fn:Appelo Parameters ---------- I : [float] Ionic strength in mol/L gamma : [np.ndarray] Ac...
49581e10b0048f372c22ef21e23b76cb7b6c715c
55,100
import inspect def is_mod_class(mod, cls): """Checks if a class in a module was declared in that module. Args: mod: the module cls: the class """ return inspect.isclass(cls) and inspect.getmodule(cls) == mod
7a9b228995d2bf46467ef75823a1aad26d16df0e
55,101
from datetime import datetime def getDateTime(timestamp): """ Converts to datetime from timestamp :param timestamp: string (or integer) value :return: datetime value """ return datetime.fromtimestamp(int(timestamp)/1e3)
2197806bf7372305cd048295c8c63a0269625262
55,103
def is_heavy_usage_item_scription(item_description): """ CNN1-HeavyUsage:m4.2xlarge :param item_description: :return: """ return len(item_description.split(";")) == 2
dd67d8fc192d663bf9e09c4b6325ad3afe09fd0b
55,105
def _generate_sample_indices(random_state, y, target_imbalance_ratio, verbose=0): """Private function used to _parallel_build_trees function.""" random_instance = check_random_state(random_state) class_idxs = _generate_class_indices(y) class_len = [len(class_idx) for class_idx in class_idxs] minori...
0e58e31433da26d71e41ca9985197767db15c1c1
55,106
def getcollision() -> Collision: """Return the in-progress collision. Category: Gameplay Functions """ return _collision
621323e7e00282e5b5df3b83c93150389e1996f2
55,107
def manufacturer(addr): """ Gets the name of the manufacturer of the device. """ for t in manufacturers: for pfx in manufacturers[t]: if addr.startswith(pfx): return t return "Unknown"
5313aa7e6bdf0ec12f64df8f1011de296d7aa6ca
55,108
def adjacent_down(p, target, mid): """Performs linear search to find adjacent pair left side Args: p: integer indicating the index of player in list of players looking for matches target: integer indicating height of player to look for mid: index of match found, to search in ...
77176cf6d4ace1f8953980825503b9e6f8ac0f88
55,109
def quiet_spark_logger(sc: SparkSession) -> Logger: """Removes warnings from pyspark logger""" logger = sc._jvm.org.apache.log4j logger.LogManager.getLogger("org").setLevel(logger.Level.ERROR) logger.LogManager.getLogger("akka").setLevel(logger.Level.ERROR) return logger
8bdfe342b45d3f0b48694f20239afc8eb0d79a57
55,110
from .pv_pythreejs import convert_plotter def show_pythreejs(plotter, return_viewer, **kwargs): """Show a pyvista plotting scene using pythreejs.""" renderer = convert_plotter(plotter) if return_viewer: return renderer display.display_html(renderer)
02b341977cf3a7a937dcf93f3a7671ed71e6a1a2
55,111
def swapWordCount(wordToFreq): """ wordToFreq: the dict linking word to count return freqToWord: the dict linking count to word """ freqToWord = {} for wdKey in wordToFreq: if wordToFreq[wdKey] in freqToWord: freqToWord[wordToFreq[wdKey]].append(wdKey) else: ...
a1569f20a11303e0aa986a2ae5a1377f0bd1b14a
55,112
from typing import List def split_paragraphs(s: str) -> List[str]: """ .. versionadded:: 0.3.0 Split a string into paragraphs, each one terminated by one or more blank lines (i.e., lines containining only a line ending). Trailing and embedded line endings in each paragraph are retained. Onl...
98a468c9acd1aeb309d18af943d4423c791e127a
55,113
def resource_not_found(e): """Returns a HTTP 404 error to the Client""" return jsonify(error=str(e)), 404
a296185ebd27b7649c8a49b614b67eb37a7a6e73
55,114
def calc_ibs_kinship(snps, snps_data_format='binary', snp_dtype='int8', dtype='single', chunk_size=None, scaled=True): """ Calculates IBS kinship data_format: two are currently supported, 'binary', and 'diploid_int' """ num_snps = len(snps) # print 'Allocating K matrix'...
75cab6053eafb9801704273b0cb4b6f508f7e338
55,116
def _prepare_quote(quote, author, max_len=78): """This function processes a quote and returns a string that is ready to be used in the fancy prompt. """ quote = quote.split(' ') max_len -= 6 lines = [] cur_line = [] def _len(line): return sum(len(elt) for elt in line) + len(line) -...
7669af2c1dd5de482740944937229f5e87c527b5
55,117
def get_status(agent_ip): """Get the list of agents in the current node.""" agent = app.agents[agent_ip] # aggiungere blocked return jsonify(agents=[app.agents[ip].state for ip in app.ring.get_node(agent.node).agents if ip != agent_ip], blocked=app.ring.blocked(agent))
fae3ce9cdb67e91e1d5b30c3e67fe387c07e3656
55,118
import urllib def download_file(url, target_pkg_dir=None, filename=None): """ Wrapper function for downloading a file. File can be downloaded to path specified by arguments: target_pkg_dir and filename or return as an output. :param str url: url to a file :param (str, optional) target_pkg_dir: th...
85b7931f83798d760d8e2f9cc34bcd9f27351769
55,119
def cov(d1, w1, d2=None, w2=None, conj_1=False, conj_2=True): """ Computes an empirical covariance matrix from data vectors. If d1 is of size (M,N), then the output is M x M. In other words, the second axis is the axis that is averaged over in forming the covariance (e.g. a time axis). If d2 is pro...
e68e4e44763b95fceb4258b67756ea05bdf66b5f
55,120
import re def url_check(addr): """检测UrlAddr是否为有效格式,例如 http://ip:port https://abc.com """ regex = re.compile( r'^(?:http)s?://' # http:// or https:// r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain... r'localhost|' # localhost...
4804b98a0b43e1637275eae51e1179a91a239b6f
55,121
import requests def search_direct(docketnum, court): """ Takes in the name of a party and the docket number as a parameter, returns the Docket Alarm search results. You can make calls to the /getdocket endpoint with these results to get more detailed information on the docket you are looki...
629c994190b26dc0106d1c071084573011c702a7
55,124
def get_raw_txt_file_path(data_dir: str, data_type: str, text_type: str, split: str = '1.0') -> str: """ Call as get_raw_txt_file_path(data_dir=data_dir, data_type=data_type, text_type="questions") :param data_dir: :param data_type: :param split: :param te...
1cf28e183ecb1145d2dd7b401c45f02a5ccb70a0
55,125
from datetime import datetime async def new_game_create(request: Request) -> dict: """ Make a new chess game and send link to game room. A user can only make a room if they don't have one existing already, so it first verifies if the user is in a game or not and then creates one for them. ##...
35e9fe704b77a2edd43bd7cc5cefbb03dba0e5ba
55,126
def data_context_connectivity_context_connectivity_serviceuuid_end_pointlocal_id_namevalue_name_delete(uuid, local_id, value_name): # noqa: E501 """data_context_connectivity_context_connectivity_serviceuuid_end_pointlocal_id_namevalue_name_delete removes tapi.common.NameAndValue # noqa: E501 :param uuid:...
6f02fdbad77150a445fc6f3ed4b8235bd72b0fcd
55,127
def normalized_root_mean_squared_error(y_true, y_pred): """Compute normalized mean squared error Cf. missForest Returns: NMRSE -- Result """ mse = mean_squared_error(y_true, y_pred) var = np.var(y_true) if var != 0: nrmse = np.sqrt(mse / var) else: nrmse = np...
898d5098d4ded563522d63637cd1442b03955e83
55,128
import network import gc def ifconfig(): """ Return Ifconfig data """ try: data=network.WLAN(network.STA_IF).ifconfig() ifco_data={'IP':data[0],'Mask':data[1],'Gateway':data[2],'DNS':data[3]} return ifco_data except Exception as e: print(e) finally: gc.c...
e49a3b130601b819f3feebc488ae9a67e3a47479
55,129
def publish_web_map_service(request): """[summary] Parameters ---------- request : [type] [description] """ # publish geoserver wms layer workspace = 'interpo' service_url = 'http://ec2-18-232-162-21.compute-1.amazonaws.com:8080/geoserver/rest' service = WebMap...
6a8a84e32595148dd33bdc0721fdd7933f67b666
55,131
from typing import List from typing import Mapping def build_runtime_parameter_spec( pipeline_params: List[dsl.PipelineParam] ) -> Mapping[str, pipeline_spec_pb2.PipelineSpec.RuntimeParameter]: """Converts pipeine parameters to runtime parameters mapping. Args: pipeline_params: The list of pipeline param...
5a86cf5ac03cfb530f9f7ca289d7c31f5fcd1fd7
55,132
def do_list(args): """ List all simulations that can be run """ excludes = read_excludes_file(args.excludes) for (name, path) in gather_target_sims(args.basedir, args.target, excludes): print(name) return 0
8379c1204c2a112bc08feb09dd737201400531b4
55,133
import json def predict() -> str: """ Creates a route to return the prediction given the user inputs. :return: list of predictions of the price """ user_input = request.data # try process the data and catch errors try: inputs = process_input(user_input) # catch json decoding-...
833244f25c45517e95acdd473061c2caf94f1d0a
55,134
def xldate_from_time_tuple(time_tuple): """ Convert a time tuple ``(hour, minute, second)`` to an Excel "date" value (fraction of a day). :param hour: ``0 <= hour < 24`` :param minute: ``0 <= minute < 60`` :param second: ``0 <= second < 60`` :raises xlrd.xldate.XLDateBadTuple: Out-of-range ...
a6acf37a9e740e5c3c781bc4b711cdd170301d74
55,135
def answer_question(): """ View to answer question the user was assigned to by a friend. Adds answer to database and notifies friend :return: answer_question.html from get :return: redirect to /to_answer from post """ if request.method == "POST": question_id = request.form.get("id") ...
adda1a69a9e575daa7db8f4a3cce14fcfcbf71a2
55,137
def get_job_obj(name, namespace=defaults.ROOK_CLUSTER_NAMESPACE): """ Get the job instance for the given job name Args: name (str): The name of the job namespace (str): The namespace to look in Returns: OCS: A job OCS instance """ ocp_obj = OCP(kind=constants.JOB, names...
39c8082a0ffc30180545583273363d589f3ad54c
55,138
import json def verify_user_login(): """ returns true if the username and passwordhash match the database false otherwise Input {"email": email, "password": password} Output {"status": true/false, "usid": userid of logged in user, "isstudent": true/false} status is true if login was sucessful usid...
0ba0b9ec866f1e05dad384713599cad183390aec
55,139
def tf_super(A): """Superoperator from both sides of matrix A.""" superA = tf.matmul( tf_spre(A), tf_spost(tf.linalg.matrix_transpose(A, conjugate=True)) ) return superA
66d6e76319561665f6480ba538961f6f17affd1e
55,140
def create_badge(request): """Create a badge """ if request.method == "POST": form = CreateBadgeForm(request.POST,request.FILES) if form.is_valid(): name = form.cleaned_data['name'].capitalize() badge_description = form.cleaned_data['badge_description'] badge_image = form.cleaned_data['badge_image'] ...
0e2803ff7c2abe6450e3f7aebc213e96ea03dc22
55,141
def MakeRenewedExpiredResponse(): """Returns a response for a subscription which expired after at least one renewal. """ return kVerifyResponseRenewedExpired
d65b3ccdd5d912574e7f8cee5421b01de45020bb
55,142
def bt2_out(): """Static equilibrium results from braced tower 2d.""" output = {} output["xyz"] = {0: [0.11891271935545733, 0.04623304043571308, 0.0], 1: [-0.14550216351451895, 1.0106420665842952, 0.0], 2: [0.0, 2.0, 0.0], 3: [1.5829003695589805...
1f5e1ebaea1abb5bd6072f29dca68598a0366905
55,143
def mstep(X: np.ndarray, post: np.ndarray, mixture: GaussianMixture, min_variance: float = .25) -> GaussianMixture: """M-step: Updates the gaussian mixture by maximizing the log-likelihood of the weighted dataset Args: X: (n, d) array holding the data, with incomplete entries (set to 0) ...
f2971bed4ce38b3c30ee8a1a1e1d96a8c686733e
55,144
import random def random_str(num_chars, alphabet=base32.ENCODING, msb_alphabet=MSB_ASCII_ALPHABET, not_in=(-1,)): """ Helper function that returns a string with the specified number of random characters, optionally excluding those of a specific length. """ num_chars = num_chars + 1 if num_chars in...
ce5a46cf63644977f172955e2df438bc9c8a7671
55,145
def _get_mass_dict(factor=1000000000, type=int): """ Return a Dictionary containing the masses of each aminoacid We explicitly convert them by a factor of 1 000 000 000 (default) into integers The values are taken from: https://proteomicsresource.washington.edu/protocols06/masses.php """ return...
fabdf445765acb1bde082ba63df9b22b06669ab9
55,146
async def connection_absent( hub, ctx, name, resource_group, connection_auth=None, **kwargs ): """ .. versionadded:: 1.0.0 Ensure a virtual network gateway connection does not exist in the specified resource group. :param name: Name of the virtual network gateway connection. :param re...
b7572c7c36c3b3f040e341a8a9cbf43ac97518b2
55,149
def inner_product(u0,u1,ds): """inner product which makes use of orthogonality relation of Zernikes as defined in this file""" return np.sum(u0*u1) * ds * ds / np.pi
b476682f163632c2a1646e7abc17aacecbc127f2
55,150
def RemoveUnusedFunctions(entry_functions=None): """Remove unused global relay functions in a relay module. Parameters ---------- entry_functions: list[string] The set of entry functions to start from. Returns ------- ret : tvm.relay.Pass The registered pass to remove unuse...
fca8a243552e98728cbae3543937dd966d63076c
55,151
def get_summary_df(maxageh=1, force_today=False): """Get summary dataframe with cache handling and csv update. Dataframe layout: Multiindex: Date_file, Date_statistics Columns: - DON: total 'date of notification' for this date - DOO: total 'date of disease onset' for this date - DPL: tot...
62062ce496ff3db2fa8aaf5afa5a2578902ae5fd
55,153
import re def pattern2re(pattern): """Makes a unicode regular expression from a pattern. Returns ``(start, full_re, int_re)`` where: * `start` is either empty or the subdirectory in which to start searching, * `full_re` is a regular expression object that matches the requested files, i.e. a...
4ae9afed68a2625528f88ebbdbc8f66ab1340230
55,154
def my_distance(x, y, metric='eu', squared=False, w=None): """only calculate pairwise distance between matrix x and y. """ dim = x.shape[1] if w is not None: if w.ndim == 1: # different weights for different feature x = x * w y = y * w elif w.ndim...
b07dd3a8630f5a9017ee299544ba278d235a0014
55,155
import hmac def is_authenticated(request, secret): """ Verify whether the user is authenticated Args: request (tornado.httputil.HTTPRequest): The request secret (str): The secret to use for authentication """ # See https://api.slack.com/authentication/verifying-requests-from-slack...
4d8915018f5d4e97934a581a79bb935533714817
55,156
from datetime import datetime def is_valid_saml_assertion(saml_xml): """ Validates that a SAML assertion has not expired by checking the 'NotBefore' and 'NotOnOrAfter' attributes. Arguments: saml_xml (str): SAML assertion XML as a string. Returns: bool: True if assertion is not yet exp...
2383430acf547ebad69e9d130a65a8de3b8f9967
55,157
from typing import Union from typing import Tuple def subplots_create(nrows:int=1, ncols:int=1, sharex:Union[bool,str]=False, sharey:Union[bool,str]=False, style:str="matplotlib", **kwargs) -> Union[Tuple[mplFigure,Axes],plotlyFigure]: """Create subplots for each plot style. Args: ...
e10fbf0abf641bed17925dd4545a2b498163f16b
55,158
from typing import Optional from typing import Dict def postprocess_trajectory( policy: Policy, sample_batch: SampleBatch, other_agent_batches: Optional[Dict[AgentID, SampleBatch]] = None, episode: Optional[MultiAgentEpisode] = None) -> SampleBatch: """Postprocesses a trajectory an...
dc97de9b1ceda52d41b08b7bb88db85d3cbc0c27
55,159
def insert(event: SportEvent) -> bool: """ Inserts a single SportInfo object in Unibrowser's persistent storage. :param info: the SportInfo to insert :returns: true if the insert succeeds, false otherwise """ mongodb = UnibrowserDAO(host=__host, port=__port) result = mongodb.insert(collectio...
a94ac66a45dd5e1725175a0d2ff1051e591dfc9c
55,160
import pytz def timezone_list(): """Returns a list of timezone choices, expressed as text.""" return sorted([tz for tz in pytz.all_timezones])
1f3aea741e5be43599b4ac9cc8369c24587e602b
55,161
from typing import Iterable from typing import Set from typing import Tuple def all_symmetry_sets(perms: Iterable[Perm]) -> Set[Tuple[Perm, ...]]: """Given a collection of perms, return all possible collections formed by applying symmetric operations on all perms. Each group has their permutation sorted. ...
556695bcf4bd09a69eb33d6bb31cabcb2df08000
55,163
def unlike(request, pk): """Remove a user from those who liked the post. Only authenticated users are able to unlike a post. """ if request.method == 'POST': # query the post in question try: post = Post.objects.get(pk=pk) except Post.DoesNotExist: retur...
5ec954a8e5506df7dbd1558c2985480837357539
55,164
def xoai_abstract(source, *args, **kwargs): """ CZ: EN: """ value = [] for lang_vers in source: lang = lang_vers["@name"] field = lang_vers["element"]["field"] if isinstance(field, list): for abstract in field: value.append( ...
e4aa320e9c9364ad1f990130c83466fcd9e66f36
55,165
def get_missing_housenumbers_txt(ctx: context.Context, relation: areas.Relation) -> str: """Gets the cached plain text of the missing housenumbers for a relation.""" output = "" if is_missing_housenumbers_txt_cached(ctx, relation): with relation.get_files().get_housenumbers_txtcache_read_stream(ctx)...
033e46204c9e0541a53ac323e612d51b6d5ca38c
55,167
def chi2_fun(theta, parameters_to_fit, event): """ Calculate chi2 for given values of parameters Keywords : theta: *np.ndarray* Vector of parameter values, e.g., `np.array([5380., 0.5, 20.])`. parameters_to_fit: *list* of *str* List of names of parameter...
14f74f3cf64770dc1cb7e335880f445eb75ca007
55,168
def compute_warped_image_multiNC(I0, phi, spacing, spline_order, zero_boundary=False, use_01_input=True): """Warps image. :param I0: image to warp, image size BxCxXxYxZ :param phi: map for the warping, size BxdimxXxYxZ :param spacing: image spacing [dx,dy,dz] :return: returns the warped image of si...
490d9944c7fa9d2f61822253611acf0ca4c08010
55,170
def link(content, target): """Corresponds to ``[content](target)`` in the markup. :param content: HTML that will go inside the tags. :param target: a full URL, or a local ``filename.html#subtitle`` URL """ return '<a href="%s">%s</a>' % (target, content)
c0355f78db31edccf7e904b3696a169980fa796b
55,171
def normalizeComponentScale(value): """ Normalizes component scale. * **value** must be a `tuple`` or ``list``. * **value** must have exactly two items. These items must be instances of :ref:`type-int-float`. * Returned value is a ``tuple`` of two ``float``\s. """ if not isinstance(va...
061f127b03942df58cfe3bf42eaa7319a93172fc
55,172
def normalize_array(data_list, min_close_value, max_close_value): """Normalise list of values between 0 and 1 Args: data_list (list of float): [description] min_close_value (float): [description] max_close_value (float): [description] Returns: list of float: [description] ...
459a9d971966cc6810a9e7a1adf5f7c741a97320
55,174
def batch(proxy): """convenience method to get a batch proxy adapter""" return proxy._pyroBatch()
36faa7977976c65cf0a549065fe41e5c7589213b
55,175
def elon_periods(dpos_len, dneg_len, pos_crit=1, neg_crit=1, zer_pos_c=2, zer_neg_c=2, n_min=1, m_min=1): """ Determination of periods of elongation for positive and negative ribbons from time series. Parameters ---------- dpos_len : list Time derivative of positive rib...
c5d74b0435944a4e229e565024183ec98015fa13
55,176
def convex_hull_collide(nodes1, nodes2): """Determine if the convex hulls of two curves collide. .. note:: This is a helper for :func:`from_linearized`. Args: nodes1 (numpy.ndarray): Control points of a first curve. nodes2 (numpy.ndarray): Control points of a second curve. Ret...
98e812d6a0c2de9118e3462b6f96869f7991a963
55,177
def solve(R, C, grid, N, given_words): """ Args: R: int, number of rows in grid. C: int, number of cols in grid. grid: 2d list of characters, N: int, number of words words: list of str, words to place in the puzzle. Returns: list of str, with words place, ot...
220f2476b5127c8cf4ec9f377ed0b8b07fc6021a
55,178
from typing import Dict from typing import List import logging from typing import OrderedDict import tqdm def mean_average_ndcg( gold: Dict[str, Dict[str, float]], predicted: Dict[str, List[str]], rating_threshold: int, use_tqdm: bool ) -> float: """Calculate the Mean Average NDCG Args: ...
c98f03ec5e5d29fef6aaf0817f4c248a584bad84
55,179
from typing import List from typing import Dict def agg_evaluations( evaluations: List[Dict[str, Dict[str, float]]] ) -> Dict[str, Dict[str, List[float]]]: """ aggregates error metrics from models fit on different CV folds Arguments: evaluations {List[Dict[str, Dict[str, float]]]} -- list of ...
c567519de71ea6487cca5a582752670dac774e3d
55,180
def bbox_transform_rotated( boxes, deltas, weights=(1.0, 1.0, 1.0, 1.0), angle_bound_on=True, angle_bound_lo=-90, angle_bound_hi=90, ): """ Similar to bbox_transform but for rotated boxes with angle info. """ if boxes.shape[0] == 0: return np.zeros((0, deltas.shape[1]), d...
5822dfe89d9d3118f7ca4604959a7c74137c98b8
55,181
from pathlib import Path import re import shutil def landsat_harmonize(satsen, productdir, target_dir=None): """ Prepare Landsat-7 NBAR. Parameters: productdir (str): path to directory containing angle bands. target_dir (str): path to output result images. Returns:...
fe780c313850a359d93164f026749af7988f5ac8
55,182
def is_float(s): """ Checks whether string s is a number""" try: float(s) return True except ValueError: return False
25ed4e0dd3870897f2a379db282b8879c8fefb75
55,183
import PIL from typing import Dict from typing import Optional from typing import List def fill_annotation_list( draw: PIL.ImageDraw.Draw, parser: SimpleAnnotationParser, label_color_dict: Dict[str, RGB], label_name_list: Optional[List[str]] = None, ) -> PIL.ImageDraw.Draw: """ 1個の入力データに属するアノテ...
3142d2ee1751bedb37c5dc209f250f934eb24d4d
55,184
import typing def calculate_default_layout_uvs( texture_size: typing.Tuple[int, int], box_size: typing.Tuple[int, int, int], offset: typing.Tuple[int, int], ): """ Util method for calculating uv's Cache result whenever possible! WARNING: currently may not work correctly :param texture...
9a9c49711c8dd9ec19e8fd3830e951778aa28737
55,185
def _safe_get(value: dict, *keys: str) -> str: """Look up a nested key in the given dict, or return "UNKNOWN" on KeyError.""" for key in keys: try: value = value[key] except KeyError: return "UNKNOWN" return str(value)
afcc3e20a68af87f74cedd2f5ebcb1a5f049563d
55,186
import string import random def randomString(stringLength=10): """Generate a random string of fixed length """ letters = string.ascii_lowercase+"0123456789"+"""£$%^&*""" return ''.join(random.choice(letters) for i in range(stringLength))
81f0a6004da3bdb5fd5bbdd3450449f72dd9704e
55,187
from typing import List def find_patterns_idx(pattern, target_tokens: List, parse_character=False) -> List: """ 리스트에서 단어 패턴을 찾아서 반환하는 함수 :param pattern: 찾고자 하는 패턴 :param target_tokens: 찾아야 하는 토큰 리스트 :param parse_character: 캐릭터 단위로 분해 :return: 저장되어 있는 리스트 반환 """ if parse_character: ...
33084599386dde6d36c31e99247fdb5de6179e72
55,188
def compute_scg_coverage_across_chunks(species_id): """ Extract gene depth for mapped centroids_99 that are markers and Compute the median marker coverage """ global dict_of_species sp = dict_of_species[species_id] number_of_chunks = sp.num_of_genes_chunks _, list_of_markers = fetch_genes_are_mark...
626e231653829c48aa199fd1e516ba62976f226e
55,189
def read_ntrajs(input_string): """ """ pattern = ('NTrajs' + one_or_more(SPACE) + capturing(INTEGER)) block = _get_directory_info_section(input_string) keyword = first_capture(pattern, block) assert keyword is not None return keyword
8d5243c6a4f786fc5628e906e7b490d984e33711
55,190
import struct def far_read_directory_entry(byte_stream): """ Unpacks a directory entry which holds its name and file offset. """ far_dir_entry_bytes = byte_stream.read(FAR_DIR_ENTRY_LEN) if len(far_dir_entry_bytes) != FAR_DIR_ENTRY_LEN: raise FarFormatError("Unexpected EOF parsing FAR directory entr...
df47461e13713f3bc9b624a05f1c380684b02bb5
55,191
def get_group(group_name): """Get group by name.""" for group in groups: if group.name == group_name: return group return None
bb0d475f11c82806ad321c0393398ac552c6a9a4
55,192
def bic_real(self): """Chisqr + np.log(ndata) * nvarys.""" try: _neg2_log_likel = self.chisqr # fallback incase nvarys or ndata not defined. nvarys = getattr(self, "nvarys", len(self.init_vals)) ndata = getattr(self, "ndata", len(self.residual)) return _neg2_log_likel + n...
a06f3ecfcd62c95e29141a58262d81320f521b84
55,193
import six from typing import Container def create_popup_window(title, body): """ Return the layout for a pop-up window. It consists of a title bar showing the `title` text, and a body layout. The window is surrounded by borders. """ assert isinstance(title, six.text_type) assert isinstance(bo...
83016d449c6d53f5e383d6d24de557e22e1f370d
55,194
def get_version_details(path): """Parses version file :param path: path to version file :return: version details """ with open(path, "r") as reader: lines = reader.readlines() data = { line.split(" = ")[0].replace("__", ""): line.split(" = ")[1].strip()....
6ea7019e4e39b5c315e085369c6ab2bd6729d6bb
55,195
def delete_resource(collection, key): """Return the appropriate *Response* for deleting an existing resource in *collection*. :param string collection: a :class:`sandman.model.Model` endpoint :param string key: the primary key for the :class:`sandman.model.Model` :rtype: :class:`flask.Response` ...
d2bfd77f353025e468f4d46a3d144d4ab713e2cc
55,196
def _pandas_df_to_dendropy_tree( df, taxon_col='uid', taxon_annotations=[], node_col='uid', node_annotations=[], branch_lengths=True, ): """Turn a phylopandas dataframe into a dendropy tree. Parameters ---------- df : DataFrame DataFrame containing tree data. ta...
c87c80bc4772f225d5fb3f9942f6194fee6e5ed9
55,197
def fourier_spectrum(signal, fps, return_spectrum=False, produce_plot=False, out_plot_name='tmp.pdf', out_plot_title=''): """finds fourier spectrum of signal time series as numpy array, has functionality to return and/or plot the sectrum (both default off), built from code originally fo...
5258b98cf48f5864580c52361912f513f77cd55a
55,198
def dithering(data, noiselevel=1e-3): """ % y = dithering(x, noiselevel) % Add low-level noise to x to avoid digital zeros % noiselevel is scaling factor below SD of signal at which % noise is added (default 1e-3). """ # Ensure consistent random sequence (in dither() np.random.s...
91dfc40e4d9804c984e61d32af4e30737eb58e7b
55,199
def watershed_aggregation(grid, field, outlet_id, method, **kwds): """Aggregate a field value over a watershed. ``watershed_aggregation`` calculates aggregate values on the nodes in a watershed that drain to *outlet_id*. It supports all methods in the `numpy`_ namespace that reduce an array to a scalar...
1d98123f8a8979ef5a0caf3c7294ed745cf34de4
55,200
import hashlib import zlib def object_write(obj, actually_write=True): """Creates the vcs object of input data and writes it to a file in compressed form if actually_write is True""" # Serialize object data if obj.fmt == b'commit': data = obj.serialize(obj.commitData) # get the content in byte str...
7eddbbc06c465277d5df9685ea83cb7a2f58aaea
55,201
def _mask_with_shp(cube, shapefilename): """Apply a Natural Earth land/sea mask""" # Create the region region = _get_geometry_from_shp(shapefilename) # Create a mask for the data mask = np.zeros(cube.shape, dtype=bool) # Create a set of x,y points from the cube # 1D regular grids if cu...
59b015959c184b578f6517faea3b75311bdb3c72
55,203
def delete_term(*, db_session: Session = Depends(get_db), term_id: int): """ Update a term. """ term = get(db_session=db_session, term_id=term_id) if not term: raise HTTPException(status_code=404, detail="The term with this id does not exist.") return delete(db_session=db_session, term_i...
43d23e9e0382ebb27802664f1f959d865291064a
55,204
import torch from typing import Optional from typing import Union def send_backward_recv_forward( input_tensor_grad: torch.Tensor, tensor_shape: Shape, *, dtype: Optional[torch.dtype] = None, timers: _Timers = None, ) -> Union[None, torch.Tensor]: """Batched send and recv w...
f3d96ce8fe75a9a3b4ed6b27914c143924147364
55,205