content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import List def vr_persistence_l1( point_cloud: Tensor, max_dimension: int, max_ball_diameter: float = 0.0 ) -> List[List[Tensor]]: """Returns the barcodes of the Vietoris-Rips complex of a given point cloud w.r.t. the l1 (manhatten) distance. Args: point_cloud...
e8e77868f079d36e25efd1634709befe28938bd3
70,700
from typing import Optional from typing import Union from typing import List def list_cube_caches( connection: "Connection", nodes: Optional[Union[List[str], str]] = None, cube_id: Optional[str] = None, loaded: Optional[bool] = False, db_connection_id: Optional[str] = None, project_ids: Option...
3651f51027d047d52b2191301266cc571eaabb12
70,701
import gettext def beforeRequest(): """ Processing of URL before any routing """ # Force https on prod if constants.HTTPS: if not request.url.startswith("https") and "ogn.dev" not in request.url_root: return redirect(request.url.replace("http", "https", 1)) selected_lang = None ...
a8a69a3691101be61bb4fa27141d73f306a00fbd
70,702
from typing import Union from typing import Optional from typing import List from typing import Any from typing import Dict def compute_bivariate( df: Union[pd.DataFrame, dd.DataFrame], col1: Union[str, LatLong], col2: Union[str, LatLong], cfg: Config, dtype: Optional[DTypeDef], ) -> Intermediate:...
ddc0cec853c7aaf0a177eaeb78cd626d04d93e27
70,703
def psd_multitaper(inst, fmin=0, fmax=np.inf, tmin=None, tmax=None, bandwidth=None, adaptive=False, low_bias=True, normalization='length', picks=None, proj=False, n_jobs=1, verbose=None): """Compute the power spectral density (PSD) using multitapers. Cal...
c27e5db06edbba3b64c1317701a0ed3204ee91aa
70,704
def silhouette( adata, group_key, embed, metric='euclidean', scale=True ): """ Wrapper for sklearn silhouette function values range from [-1, 1] with 1 being an ideal fit 0 indicating overlapping clusters and -1 indicating misclassified cells B...
ea23c0d6563af312565948dcd3214de181b845a9
70,705
from re import MULTILINE def parseConfiguration(condition: str) -> tuple: """Extract the config and platform from the condition string. Args: condition (str): The string from the csproj file. Returns: tuple: The config and the platform. """ condition = condition.strip() config_platform_regex = r"^\'\$\(Co...
24506efb3a9a98bc5354a6bd01f9efc0413f2810
70,706
def isostring(dt): """Convert the datetime to ISO 8601 format with no microseconds. """ if dt: return dt.replace(microsecond=0).isoformat()
db7326e53402c0982514c4516971b4460840aa20
70,707
def listAllChats(): """docstring for listAllChats""" all_chats = Message.query.order_by(Message.date).all() sessionIDs = [] sessions = [] # Organize per sessions for chat in all_chats: # Do we already have this session? if chat.session in sessionIDs: sessionIndex = se...
4a8a7fae4b063a2dc04ca1fab4cd83a89dd879ab
70,708
def country(ip_address): """ Return the country code of a given IP Address :param ip_address: IP Address (string) """ return geo.get_country(ip_address)
fe83dcac8bcbbe765c1bfba0eeb3d07c24442ca5
70,709
def read_hadsst4(filename, adjust_clim=False): """ Read data from HadSST4 :param str filename: infile to read :returns: Timeseries object with upper and lower bounds. """ # Colin's global temperature files (observed) indata = np.genfromtxt(filename, dtype=(float), delimiter=",", skip_he...
73f25d76b5c43c8f957433538abd5d25496906a1
70,710
from . import db from . import main import os def create_app(config_class=Config): """ Application factory function. Create and configure the application. :return: app instance """ BASEDIR = os.path.abspath(os.path.dirname(__file__)) app = Flask(__name__, instance_relative_config=True) ...
b809d5d77829ad316e81276e91039312b98af970
70,711
def add_all(application, project_id, control_client, loader=service.Loaders.FROM_SERVICE_MANAGEMENT): """Adds all endpoints middleware to a wsgi application. Sets up application to use all default endpoints middleware. Example: >>> application = MyWsgiApp() # an existing WSGI applicati...
ad164c55def209e15f450ea466f2ab28591a17d0
70,712
import os import tempfile from pathlib import Path def create(path, base_url, version=None, version_dev='master', env=None, registry=None, urls=None): """ Create a new :class:`~aletheia_data.AletheiaPooch` with sensible defaults to fetch data files. If a version string is given, the Pooch will be versione...
e22c75306ab17fa4de90969fd2c6e5b12f033dba
70,713
def standardize(ts,cap,method): """ use cap_weighted mean to standardize the factor Params: ts: pd.Series, cross section factor data cap: pd.Series, cross section cap data, the secID is matched one by one available for cap_weighted method: ...
99451dfa014e83363d05234a2558d4f1422fd72f
70,714
import json def complete_test(data): """Endpoint para calcular los resultados BIG5, los resultados se guardan en `Big Five Results` y buscar que perfil de personalidad se adecua a los resultados""" try: res = json.loads(data) # DEBUG: # with open('respuestas.json', 'w') as f: ...
c14d4bda0a75492a7a368c85ad9469e9b8072cf0
70,715
from typing import Optional def download_one_segment( segment_id: str, start_date: dt.date = dt.datetime.now().date() - dt.timedelta(weeks=1), end_date: dt.date = dt.datetime.now().date(), out_filepath: pl.Path = None, api_token: Optional[str] = None ) -> pd.DataFrame: """R...
5df9d9b98453d323b00f01dc612f389b0877f346
70,716
import base64 def image_encoder(img_path): """Function to verify API status. Parameters ---------- img_path : str The path to the image to be encoded. Returns ------- encoded_img : str A UTF-8 string containing the encoded image. """ with open(img_pat...
7ef4c5c4a0fad340ab50c798e70b0f0c4ceb0d22
70,717
def Make_Soft_RGG_Given_Positions(positions,Kernel,metric="Euclidean",return_connection_probs = False,kernel_params=[],distance_metric_function=None): """ Sample the adjacency matrix of a single Soft RGG given positions in some domain. Parameters --------------- positions : list List of positions in the em...
f1cb87739b73540f56a6847ebcada6ed1d7b62a4
70,718
def gen_TP_mask2(norm_lines, h = 256, w = 256, with_ext=False): """ 1 cengter + 4 dis + 2 return [7, h, w] """ # note that in norm_lines, each line is like: line = [pt[0][0], pt[0][1], pt[1][0], pt[1][1]] # and they are already expressed in the H/2 x W/2 array img_diag = np.sqrt(h**2 + w*...
9571d15f183d45b043b89e27a02d99e350117b5b
70,719
def inject_menu_items() -> dict: """Defines items of navbar""" return dict(menu_items=[ { 'title': '<i class="fa fa-home" aria-hidden="true"></i> Home', 'url': '/', 'function_name': 'home', 'children': None }, { 'title': '<i cla...
dfca070335ed11a60cc721056de6a90f62f66749
70,720
def deblend_segments(image, segm, npixels=None, fwhm=8., kernel_size=4, nlevels=30, contrast=1/1000): """ Deblend overlapping sources labeled in a segmentation image. Parameters ---------- image : array like Input image. segm : `~photutils.segmentation.SegmentationImage` or `None` ...
d47ef9d8c4ed5c0dcfbcb816d297664ead7963f8
70,721
import logging def setup_logger(name): """Return a logger with a default ColoredFormatter.""" formatter = ColoredFormatter( "%(log_color)s%(levelname)s:%(filename)s:%(funcName)s:%(message)s", datefmt=None, reset=True, log_colors={ "DEBUG": "cyan", "INFO"...
5843d3a95b976ce91dc8dd458f13de300e0615ef
70,722
def string_to_xml(text): """Convert XML string into etree.Element.""" try: return etree.XML(text) except Exception: # TODO: # ExpatError: reference to invalid character number: line 1, column 62 # litmus fails, when xml is used instead of lxml # 18. propget..............
5339f40171e9b42086f0be4162ba7364438f9502
70,723
def jobresults_download(jobname,results_file_name): """get the contents of one of the results outputs and iniate a download. If no file name or results type is sent as a parameter, by default just sent the rendered html. """ # sanitize the filename using a method for job module results_file_name ...
5f338ac323cd72a3bfabe5c6db762619d615d9b6
70,724
def ce_metric(probs, labels): """Calculates the loss from the logits and the labels. Args: logits: Logits tensor, float - [batch_size, NUM_CLASSES]. labels: Labels tensor, int32 - [batch_size]. Returns: loss: Loss tensor of type float. """ epsilon = 1e-12 def one_hot(a, num_classes)...
7002b738bb62bce34074e8ec4fc70fd48cef791d
70,725
def compute_field_angles(Su, double_telescope=False): """ | Ref. Paper [LUDW2011]_ eq. [12]-[13] | Return field angles according to eq. [12] :param Su: array with the proper direction in the SRS reference system :param double_telescope: [bool] If true, uses the model with two telescopes :return...
6bdf4809e16cdc5a5468b62c566f4764debea2a0
70,726
def filenameDictForDataPacketType(dataPacketType): """ Return a dict of fileDescriptors for a given DataPacket type. """ foo = dataPacketType(None, None) return foo.filenames
6853add9035e3b7aad86a001ee7f46e5e69336a8
70,727
def git_origin_url(git_repo): # pylint: disable=redefined-outer-name """ A fixture to fetch the URL of the online hosting for this repository. Yields None if there is no origin defined for it, or if the target directory isn't even a git repository. """ if git_repo is None: return None ...
d1f301a31aca6fae2f687d2b58c742ee747c4114
70,728
from typing import Any def argument(*name_or_flags: Any, **kwargs: Any) -> tuple: """Convenience function to properly format arguments to pass to the subcommand decorator. """ return (list(name_or_flags), kwargs)
22b2cbda7a3c2e4113c47896d60290b124cf85f1
70,729
from datetime import datetime def create_virtual_machine(module, azure): """ Create new virtual machine module : AnsibleModule object azure: authenticated azure ServiceManagementService object Returns: True if a new virtual machine and/or cloud service was created, false otherwise ""...
722c88aa17528000c6be4cb1e974992062025bc9
70,730
def viterbi(y, A, B, Pi=None): """ Return the MAP estimate of state trajectory of Hidden Markov Model. Parameters ---------- y : array (T,) Observation state sequence. int dtype. A : array (K, K) State transition matrix. See HiddenMarkovModel.state_transition for detail...
c16f70847efc84140af43950b397c3b0ac54190b
70,731
def home(): """Redirect from root to topologies listing.""" return RedirectResponse(url=app.url_path_for("topologies_page"))
9bdac9a21c7f9b00094b43a4d8804287a4c7b3a9
70,732
import os def plist(item): """Compile plist names and paths.""" name = '.'.join(['com', settings.APP_ROOT.split('/').pop(), item, 'plist']) source = os.path.join(settings.APP_ROOT, 'launchd', name) target = os.path.join(settings.APP_PLIST_ROOT, name) return {'name': name, 'source': source, 'target': target}
cb2c3457085cf3f4a9cafad68350b6b1e223226a
70,733
from typing import Generator import ast from textwrap import dedent def _parse_and_compile_gen( source: str, *, return_mode: str = "last_expr", quiet_trailing_semicolon: bool = True, mode="exec", filename: str = "<exec>", flags: int = 0x0, ) -> Generator[ast.Module, ast.Module, CodeType]: ...
cfd8ebdc792c090b21793de0663aabe52bff900f
70,734
def AuthorYr(r): """ Author yr format Smith et al. 2010 : Smith10 """ tentative_key = Author(r) + Yr(r) return tentative_key
bc03b42ace696d4c72dd4801aeff700182c027c0
70,735
def capture_and_upload_screenshot(user: dict, silence=True, only_get_screenshot: bool = True, debug=False) -> dict: """ 通过模拟登陆的方案获取签到截图,并上传oss :param debug: :param only_get_screenshot:使用Selenium上传已签到截图(若今日签到任务未完成则不能执行) :param user: username and password :param silence: :return: """ p...
87086cb3eafabfe9144a3a0a5955b8baba8f3633
70,736
def parse_mapped_reads_from_bam(reference, bam): """Parse MappedRead mrcects from a bam file and produce a MappedReadCollection. """ mrc = MappedReadCollection(reference) sam = pysam.AlignmentFile(bam, "rb") for alignment in sam.fetch(reference=reference.name): padded_alignment = sam_alignm...
5c9a35325efa35e930a199da215bd33ca0915f6e
70,737
import os def save(path:str, name:str, rgb:np.ndarray, lwir:np.ndarray, label:str, extension:str="") -> tuple: """ Saves image to a path. Params ------ path: str Subset/batch directory to save to name: str Name of the image rgb: np.ndarray RGB image lwir: np.nd...
ab79ea647a50c000e65f14f70e1263868ab6794a
70,738
def is_callback(func: t.Callable[..., t.Any]) -> bool: """Check if function is safe to be called in loop.""" return getattr(func, "__odss-callback__", False) is True
52b10dbf763f6b9d8963346e7f3c74f10de451f4
70,739
import logging def get_online_rps(learner, test_student_idx, test_student_time_idx=None, learn_node_keys=(THETAS_KEY, ), compute_first_interaction_rps=False, copy_learner=True, **test_learner_kwargs): """Compute the probability of correct of the `test response` node's interac...
7141cbf057149081661e8014bbd52606ba77b5c5
70,740
def safe_quote(value): """ Safe encoding of value taking care of unicode value urllib.quote doesn't like unicode values """ return quote(to_utf8(value))
9dd6cfcd58ab7371a8a6282e57df82b51bbadee5
70,741
def get_kde_estimator(samples, N=10000, bandwidth=200, debug=False): """sample(サンプル点のリスト)をKDEでノンパラメトリックにフィッティングして、その識別器を返す""" np.random.seed(0) downsampled = np.random.choice(samples, N) X = downsampled.reshape(-1, 1) kde = KernelDensity(kernel='gaussian', bandwidth=bandwidth).fit(X) if debug: ...
7526804b8ca1670f52eb9357643d23f8f2fa435e
70,742
def as_str_any(value): """Converts to `str` as `str(value)`, but use `as_str` for `bytes`. Args: value: A object that can be converted to `str`. Returns: A `str` object. """ if isinstance(value, (bytes, bytearray)): return as_str(value) else: return str(value)
2e200c4c7b00508c88bdc7c9805d31577f4fe9f3
70,743
import torch def encode(matched, priors, variances=[0.1, 0.2]): """Encode the variances from the priorbox layers into the ground truth boxes we have matched (based on jaccard overlap) with the prior boxes. Args: matched: (tensor) Coords of ground truth for each prior in point-form Shap...
a34cb00a959515537237b937b01e857aaf93245b
70,744
import gzip import json def bin_wikidata_entities_by_popularity( wikidata_info_path: str, num_bins: int, max_ents_per_pop: int = 10 ): """Groups a list of Wikidata entities with the specified entity type into one of `num_bins` equally sized bins based on entitye popularity. We only include entities wi...
69a0c3292ea85003fec764f0e6528979b58741c5
70,745
def get_closest_point(point, node_list): """Get the closest point to each nodes in the list. Args: point (str): Node to evaluate the distance to. node_list (list): List of nodes to search for the closest to the point. Returns: str: The closest node. """ compare = float("inf...
bc653324cd9928a2d5ff08a15bf54840f06f99c8
70,746
def flavor_prjs(my_session, fla, prj_id): """Lists the projects on the access list of the flavor, projects that access the flavor""" # TODO nov = nov_cli.Client(version=2, session=my_session) ks = ks_client.Client(session=my_session, include_metadata=True) print() fla = nov.flavors.list(is_publ...
796c1731a50522d90eae928c83825423708355a0
70,747
def emp_entropy(x, bins=1000): """Computer empirical entropy of array x. Argument is first partitioned into the histogram. Then the entropy is computed over the histogram. Args: x: an array of floats. bins: number of bins in the histogram. Returns: entropy """ if not np.isnan(x).any(): ...
d529fb46a4296a02b7ef2eaf2aa8d0f4d20664f7
70,748
from typing import List def unbiased_evaluator(user_embed: np.ndarray, item_embed: np.ndarray, train: np.ndarray, test: np.ndarray, num_users: int, num_items: int, pscore: np.ndarray, model_n...
3fa96288b699a24f4f77a42a99207c692deee420
70,749
import argparse def parse_config_from_cmdline(config): """ Get analysis parameters from commandline. Args: config (dict): Dict to save parameters to Returns: Filled config dict """ parser = argparse.ArgumentParser() parser.add_argument("sampleID", help="sample ID used as ...
489bc997c073c349491caa65ffb6b85d261b5aa5
70,750
import unicodedata def remove_accents(input_str): """Replaces accented chars by their ascii equivalents.""" nfkd_form = unicodedata.normalize('NFKD', input_str) return u"".join([c for c in nfkd_form if not unicodedata.combining(c)])
21be3562c4a836f1d73dfc07228ef618c9ad68e9
70,751
import re def trim_money_string(s): """Trims excess characters from a monetary value. Only keeps the digits within a monetary value, such as trimming `$123,456` to `123456`. Trims dollar signs and commas. Args: s (:obj:`str`): The monetary amount to trim. Returns: :obj:`str`: The sa...
c85cd8004c5a6ddd2aa883f691adbf3276d709f0
70,752
def build_model(input): """ Nearest Neighbors Model for song suggestions """ df = pd.read_csv('suggestor/clean_US.csv') # configure song index Nearest Neighbor result output mask = ['combined', 'url'] df_result = df[mask] # set up data DataFrame for numerical features only data = df....
f613b95393ddb60b2a0a411bfe1622f39aa2c821
70,753
def unprocess_obs_dict(obs_dict): """ Prepare processed observation dictionary for saving to dataset. Inverse of @process_obs. Args: obs_dict (dict): dictionary mapping observation keys to np.array or torch.Tensor. Leading batch dimensions are optional. Returns: new_dic...
337e5b981b271c8fe084b0e1726ff5daec45e6fc
70,754
def expand_sun_params(new_params, base_result, seed=0): """ Implements the expansion from an existing set cover instance as described in [1]. Parameters ---------- new_params: tuple New params for sun_params base_result: tuple Tuple of (costs, sets) that represent instance param...
fd03e8d809c2726e4a6543e12122f559f20d281e
70,755
import json def create_folder(folder, provider): """ Create a folder on the remote provider :param folder: :param provider: :return: the storage_key of the created folder on the remote provider """ r = _connect(provider) storage_key = _get_key_for_file(folder.rel_path) r.set(stora...
6d64a885fb06e5723ba71860fea54d85f70856f9
70,756
import subprocess import numpy as np def get_free_gpu(): """Selects the gpu with the most free memory """ output = subprocess.Popen('nvidia-smi -q -d Memory |grep -A4 GPU|grep Free', stdout=subprocess.PIPE, shell=True).communicate()[0] output = output.decode("ascii") ...
4432dda1b27cb7c913d9dd20348b9ac86ee39faa
70,757
import os def read_file(filename): """Reading file from filesystem.""" result = '' # Checking if file exists if not os.path.isfile(filename): # If file does not exists, return suitable information return "file '" + filename + "' not found" else: # If ile exists open it. ...
6ef21d08745d302bc1aadeabc0e779a425b1b7f5
70,758
from typing import Union from pathlib import Path from typing import Dict from typing import Any import os import yaml def _load_config( config_parameter: Union[str, Path, FileLikeType, Dict[str, Any], GenerationConfiguration] ) -> GenerationConfiguration: """Load the configuration from either the path (as st...
06c681e88f8b69f1fa7223e4b98360d58979c589
70,759
def convolution_2d( n_H_prev, n_W_prev, n_C_prev, n_C, *, kernel_size, stride=1, padding=0, activation="relu"): """Creates a 2D convulational layer. Args: n_H_prev: height of inputs n_W_prev: width of inputs n_C_prev: number of input channels n_C: number of outpu...
1470fd27630493bf05334de10c3dbfe00d848808
70,760
def drm_get(io_current): """ expects a list of GPIO pins, returns user friendly DRM representation """ if io_current == [1, 0]: return 2 elif io_current == [0, 1]: return 3 elif io_current == [0, 0]: return 0 else: abort("ERROR: unknown pin state: %s" % (io_current))
da3980cd16e4f30d9daacf5f5a17e67a51ca9e76
70,761
def special_len(tup): """ comparison function that will sort a document: (a) according to the number of segments (b) according to its longer segment """ doc = tup[0] if type(tup) is tuple else tup return (len(doc), len(max(doc, key=len)))
81154c8e1b31dc37cffc43dfad608a5cd5281e4c
70,762
def token_required(view_func): """Decorator which ensures the user has provided a correct user and token pair.""" @csrf_exempt @wraps(view_func) def _wrapped_view(request, *args, **kwargs): user = None token = None basic_auth = request.META.get('HTTP_AUTHORIZATION') use...
bce7fbf9f67af27554a2932f1df152fc022b337f
70,763
import re def format_match(card, num): """ Format a match. """ card_unique = ('{} '.format(EMOJIS['[unique]']) if card.get(lotr.CARD_UNIQUE) else '') card_name = card[lotr.CARD_NAME] card_type = card[lotr.CARD_TYPE] sphere = card.get(lotr.CARD_SPHERE, '')...
120be8f3840ab9afb28d487ca4555ea52dde3c86
70,764
import os def assemble_paths_list(): """Returns a list of paths to search for libraries and headers. """ PATHS = [ ("/usr/lib", "/usr/include"), ("/usr/lib64", "/usr/include"), ("/usr/X11/lib", "/usr/X11/include"), ("/usr/X11R6/lib", "/usr/X11R6/include"), ...
9c2f3c1883f241884c5b3b15ee06c8036252ae26
70,765
def opener(wrapped, instance, args, kwargs): """ opener(yaml.load)("conf.yaml") opener(json.load)("conf.json") """ path = args[0] with open(path) as f: return wrapped(f)
05c42f0e668f2419b4e478e8602c056a8cda634b
70,766
def make_header_lines(all_bits): """ Formats header lines """ lines = [] # Bit names bit_names = ["%d_%d" % (b[0], b[1]) for b in all_bits] bit_len = 6 for i in range(bit_len): line = "" for j in range(len(all_bits)): bstr = bit_names[j].ljust(bit_len).replac...
6c48eb125f39ca55ae47c5f6a21732fdb60c9de0
70,767
def _log_prior_trace(trace, model): """ Computes the contribution of the log prior to the log posterior. Parameters ---------- trace : PyMC3 trace object. Trace from the PyMC3 sampling. model : PyMC3 model object Model under which the sampling was performed Returns ----...
08bac37b8e26e7342189aa9361394a4593d79c21
70,768
def _normalize_status(status_id): """ This function will turn one of the standard item status codes into a GoodRelations URI: http://www.w3.org/community/schemabibex/wiki/Holdings_via_Offer Here is a snapshot in time of item_status_ids, their description, and count: 1 Not Charged ...
0a4f6f62ac2ba2646899bf3295b3e8aca1e34e6a
70,769
def elina_abstract0_manager(a): """ Return a reference to the manager contained in an ElinaAbstract0. The reference should not be freed. Parameters ---------- a : ElinaAbstract0Ptr Pointer to the ElinaAbstract0. Returns ------- man : ElinaManagerPtr Pointer to t...
8d19f1317f3844dc0fe49a258744b6fec0b6d13f
70,770
def _pair_product(p, i, j): """Return product of counts of i and j from data.""" try: return sum(p[i].values())*sum(p[j].values()) except KeyError: return 0
7a7a19d62544ee88f6755c64f08438c0ab95033f
70,771
from typing import Union import os import io import fsspec from typing import Optional import pathlib def get_size(file: Union[str, os.PathLike, io.IOBase, fsspec.core.OpenFile]) -> Optional[int]: """Get the size of a file given its path. Return None if the size can't be retrieved. """ if isinstance(...
d70ae37ef136f6c7d4e33c4af97fb0404dbca824
70,772
from typing import Optional def optional_arg_return(some_str: Optional[str]) -> Optional[int]: """Optional type in argument and return value.""" if not some_str: return None # OK # Mypy will infer the type of some_str to be str due to the check against None return len(some_str)
8125965fb1fe1f11f4f5045afc8107bcdfc95fc0
70,773
from typing import List from typing import Dict def launch_jobs_for_sra_ids( sra_import_app: DXApp, sra_ids: List[str], folder ) -> Dict[str, DXJob]: """Launch sra_import_app on a list of sra_ids Args: sra_import_app: app instance sra_ids: list of SRA ids folder: output folder on ...
b540ff4b9d18d5ecf43227b4b8c625dda52448f0
70,774
def get_blob(digest, models_ref): """ Find a blob by its digest. """ Blob = models_ref.Blob return Blob.select().where(Blob.digest == _ensure_sha256_header(digest)).get()
93d00b7bb6a84ef227898c6875277e531286f94a
70,775
from typing import TypeAlias def compare_symbols( symbol: RelevantSymbolNode, reference: RelevantSymbolNode ) -> ComparisonResult: """ Check if the given symbol node is compatible with the reference symbol. Will return a successful comparison if any of the following holds: - the symbols describ...
1c9fbcaafeda9ad0e214b549499545772729ff1a
70,776
import pathlib def stat(path: str): """Gets stat of path `path` e.g j.sals.fs.stat("/home/rafy/test_dir/test") -> os.stat_result(st_mode=33204, st_ino=795348, st_dev=2049, st_nlink=1, st_uid=1000, st_gid=1000, st_size=0, st_atime=1586445434, st_mtime=1586445434, st_ctime=1586445434) Args: ...
49bb135af5895247a5114083e0d6abf99ecffc2b
70,777
def create_array(start: int64, end: int64, step: int64) -> ArrayI64: """ Function that creates an array that contains elements from start (inclusive) to end (non-inclusve) increasing the given steps Note: if It is not possible to go from start to end, an empty array will be returned. For example: create...
c34da8efa683f3cbb5809b99fde97e29c8c3307f
70,778
def fidelity(state, target_state): """ Compute the fidelity between two states. """ return jnp.abs(state.T.conj() @ target_state) ** 2
147a54d19dd043071348359ab88fdc438b0dd51f
70,779
def common_path_prefix(p1, p2): """ Return the common leading path between two posix paths and the number of common path segments. """ return common_segments(p1, p2, common_func=common_prefix)
7269cb78021cb9c13d99ad1eeecf72fde19dfd38
70,780
def run_scatter_2d(c=1500, dc=150, freq=25, dx=(5, 5), dt=0.0001, nx=(50, 50), num_shots=2, num_sources_per_shot=2, num_receivers_per_shot=2, propagator=None, prop_kwargs=None, device=None, dtype=None): """Runs run_scatte...
681ce4c70e954ce9b8a12a16a1a74c5c5b9de4d5
70,781
import matplotlib.pyplot as pyplt def quan_sample(data, biweight_c = 9.0, verbose = True, plotme = False): """ This function calculates the properties that are used to quantify the given sample. Parameters: -`data`: 1d array. This is the sample of data. -`biweight_c`: float. The input arg...
05fcf500e038e86ae382b79d5dd609f519c23554
70,782
def weighted_avg(values, weights): """ Compute weighted average of a masked array. Used in computing mean amplitude vs uv from flagged data. :param values: Input masked array. :param weights: Input weights. :return: average, standard_error, standard_deviation """ average = np.ma.average(val...
da5c52a6726af40af7b90dc5ed50d1679c49efa0
70,783
def _compute_range_weights(guide, grid_shape): """Computes range weights for the given guide image and grid shape. Args: guide: The guide image with shape (h, w). grid_shape: The grid shape, an array-like containing [gh, gw, gd, gc]. Returns: An (image_extent, grid_extent) array with the spatial wei...
e5ed284c1f929440a0f96128c5c24e834128e1c1
70,784
def isActive(level: int): """ Simple function to check if a logging level is active. :return: True if active and false otherwise. note:: Author(s): Mitch """ return activeLevels[level]
529b46c3d2bbafcb8d156b73ea40545ff7a700b8
70,785
def orthoFeats(dfX, varThres=.95): """Given a dataframe dfX of features, compute orthofeatures dfP """ dfZ = dfX.sub(dfX.mean(), axis=1).div(dfX.std(), axis=1) # standardize dot = pd.DataFrame(np.dot(dfZ.T, dfZ), index=dfX.columns, columns=dfX.columns) eVal, ...
a2d51ade9a44bede86b075ed85ec7fcc5b50d516
70,786
def commit(repo, msg): """ commit all staged files to the current branch """ if staged_changes(repo): return ["No stagged changes to commit..."] # there are stagged changes that need to be committed git = ["git", "commit", "-a", "-m", msg] retval, status = run_command(git, repo) ...
dadee748c5673eeca360d56bbc646d236ea8826d
70,787
def unique_equalityset(C, D, b, af, bf, abs_tol=1e-7, verbose=0): """Return equality set E with the following property: P_E = {x | af x = bf} intersection P where P is the polytope C x + D y < b The inequalities have to be satisfied with equality everywhere on the face defined by af and bf. "...
8ea408b6264664ad8381c5cb6063b67eafe0d945
70,788
import os def generate_name_file(kind, path): """ This function allows to generate sequential input file name @param kind: int, 0 if input, 1 if output @param path: string, the path where generate file @return: string, the name file with an incremental number """ global filename i = 0 ...
84132e630b6d74b315981fe0e8e0f45605b0c6f6
70,789
import os def get_failure_report_path(sample_alignment, report_filename): """Returns full path to given report for ExperimentSampleToAlignment. """ return os.path.join(sample_alignment.get_model_data_dir(), report_filename)
2979f8d772633ebbcd1d20895987d52d1efdbf36
70,790
def create_pascal_label_colormap(): """Creates a label colormap used in PASCAL VOC segmentation benchmark. Returns: A Colormap for visualizing segmentation results. """ colormap = np.zeros((256, 3), dtype=int) ind = np.arange(256, dtype=int) for shift in reversed(range(8)): for channel i...
584d42ec89c178c573d94a1e3b7e14df7d1b39da
70,791
import cProfile import time import pstats def profile(fn): """ Profile the decorated function, storing the profile output in /tmp Inspired by https://speakerdeck.com/rwarren/a-brief-intro-to-profiling-in-python """ def profiled_fn(*args, **kwargs): filepath = "/tmp/%s.profile" % fn.__...
aaf1711fefee698ff5456e120dcc06cbb8c22a8f
70,792
from fractions import Fraction def fractions(): """Generates instances of fractions.Fraction.""" return tuples(integers(), integers(min_value=1)).map( lambda t: Fraction(*t) )
5afcfa2042a341f0c7a1945033016954127c759d
70,793
def find_local_group_by_user(user): """ Find approved Local Group for User based on Affiliations and Roles Parameters ---------- user : User User to check for Local Group match Returns ------- LocalGroup Return LocalGroup if a match is found, or None """...
fe1f2c79052163d2b31755dca3f83ac0463ac470
70,794
def instance_metadata_get(context, instance_uuid): """Get all metadata for an instance.""" return IMPL.instance_metadata_get(context, instance_uuid)
03b1ff55df1d0a947e4b3e40441508f969814cc7
70,795
from typing import Optional def _tw_resource(resources: list[Resource]) -> Optional[TWResource]: """ Return the TWResource instance, if any, contained in resources, else return None. """ tw_resources = [ resource for resource in resources if isinstance(resource, TWResource) ] retur...
e199e7e26b96358e39fe13893633fbb3ec6bf61a
70,796
from typing import Dict def collect_format_types(package_names: str) -> Dict[str, FileTypeFormat]: """Finds subclasses of the example_filetype_format.FileTypeFormat from a list of package names. Args: package_names: A list of Python package names as strings. Returns: A mapping of cla...
f910af206d2587ce027b21df114d0b512154fae5
70,797
import hmac def get_signed_params(params): """Sign a url by appending `&_signature=xxxxx` to given params (string or dict). :param params: String or dict of parameters.""" if not isinstance(params, string_types): params = urlencode(params) signature = hmac.new(params) signature.update(get_secret()) return p...
90408c6882c36a59d8840e3f699789d594ca05a4
70,798
def go(): """used to render classification results""" # save user input in query query = request.args.get('query', '') # use model to predict classification for query classification_labels = model.predict([query])[0] classification_results = dict(zip(df.columns[4:], classification_labels)) ...
29921ea0cf7bd928305f8b3096696be11c75234d
70,799