content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def is_anno_end_marker(tag): """ Checks for the beginning of a new post """ text = tag.get_text() m = anno_end_marker_regex.match(text) if m: return True else: return False
28b7d216c38dabedaef33f4d71f9749e72344b65
27,100
async def fetch_and_parse(session, url): """ Parse a fatality page from a URL. :param aiohttp.ClientSession session: aiohttp session :param str url: detail page URL :return: a dictionary representing a fatality. :rtype: dict """ # Retrieve the page. # page = await fetch_text(session...
525bf965854a098507046b3408de5e73bcd4abc9
27,101
def wmt_diag_base(): """Set of hyperparameters.""" hparams = iwslt_diag() hparams.batch_size = 4096 hparams.num_hidden_layers = 6 hparams.hidden_size = 512 hparams.filter_size = 2048 hparams.num_heads = 8 # VAE-related flags. hparams.latent_size = 512 hparams.n_posterior_layers = 4 hparams.n_decod...
384820d2fadc13711968a666a6f4d7b1be0726c5
27,102
def K_axialbending(EA, EI_x, EI_y, x_C=0, y_C=0, theta_p=0): """ Axial bending problem. See KK for notations. """ H_xx = EI_x*cos(theta_p)**2 + EI_y*sin(theta_p)**2 H_yy = EI_x*sin(theta_p)**2 + EI_y*cos(theta_p)**2 H_xy = (EI_y-EI_x)*sin(theta_p)*cos(theta_p) return np.array([ [EA ...
f187b35c5324a0aa46e5500a0f37aebbd2b7cc62
27,103
def get_closest_intersection_pt_dist(path1, path2): """Returns the manhattan distance from the start location to the closest intersection point. Args: path1: the first path (list of consecutive (x,y) tuples) path2: the secong path Returns: int of lowest manhattan distance ...
07bbe3a2d5f817f28b4e077989a89a78747c676f
27,104
def is_voiced_offset(c_offset): """ Is the offset a voiced consonant """ return c_offset in VOICED_LIST
6dfad8859ba8992e2f05c9946e9ad7bf9428d181
27,105
def dc_generator(noise_dim=NOISE_DIM): """Generate images from a random noise vector. Inputs: - z: TensorFlow Tensor of random noise with shape [batch_size, noise_dim] Returns: TensorFlow Tensor of generated images, with shape [batch_size, 784]. """ model = tf.keras.models.Sequenti...
e9298bdb5bf624bd669676d0e7f34f1f606d9cf2
27,106
def add_boundary_label(lbl, dtype=np.uint16): """ Find boundary labels for a labelled image. Parameters ---------- lbl : array(int) lbl is an integer label image (not binarized). Returns ------- res : array(int) res is an integer label image with boundary encoded as 2. ...
31bae32ad08c66a66b19379d30d6210ba2b61ada
27,107
def kmax(array, k): """ return k largest values of a float32 array """ I = np.zeros(k, dtype='int64') D = np.zeros(k, dtype='float32') ha = float_minheap_array_t() ha.ids = swig_ptr(I) ha.val = swig_ptr(D) ha.nh = 1 ha.k = k ha.heapify() ha.addn(array.size, swig_ptr(array)) h...
41037c924ae240636309f272b95a3c9dcfe10c5e
27,108
def adcp_ins2earth(u, v, w, heading, pitch, roll, vertical): """ Description: This function converts the Instrument Coordinate transformed velocity profiles to the Earth coordinate system. The calculation is defined in the Data Product Specification for Velocity Profile and Echo Intensi...
0a51db6b5d6186c4f9208e4fa2425160e8c43925
27,109
import math def strength(data,l): """ Returns the strength of earthquake as tuple (P(z),S(xy)) """ # FFT # https://momonoki2017.blogspot.com/2018/03/pythonfft-1-fft.html # Fast Fourier Transform # fx = np.fft.fft(data[0]) # fy = np.fft.fft(data[1]) # fz = np.fft.fft(data[2]) #...
705b04644002c2cf826ca6a03838cab66ccea1f8
27,110
import sys import os def get_packages_by_commits( repository: str, commits: list, package_limit=1, ecosystem='maven') -> list: """Get package name from git repository and commit hash. A git handler is created and modified files are searched by the given commit. Package is ...
d57c6b6584b03900158135c4cb075f3991434371
27,111
def humanize(tag, value): """Make the metadata value human-readable :param tag: The key of the metadata value :param value: The actual raw value :return: Returns ``None`` or a human-readable version ``str`` :rtype: ``str`` or ``None`` """ for formatter in find_humanizers(tag): human...
42a4e1506b4655a86607495790f555cc318b6d82
27,112
import itertools def cartesian(sequences, dtype=None): """ Generate a cartesian product of input arrays. Parameters ---------- sequences : list of array-like 1-D arrays to form the cartesian product of. dtype : data-type, optional Desired output data-type. Returns ---...
51e6031c568eee425f2ea86c16b472474ae499eb
27,113
def nasa_date_to_iso(datestr): """Convert the day-number based NASA format to ISO. Parameters ---------- datestr : str Date string in the form Y-j Returns ------- Datestring in ISO standard yyyy-mm-ddTHH:MM:SS.MMMMMM """ date = dt.datetime.strptime(datestr, nasa_date_format...
d77114c874fdd41a220aae907ce7eabd6dd239bf
27,114
import googledatastore import atexit def with_cloud_emulators(*emulator_names): """Decorator for starting cloud emulators from a unittest.TestCase.""" def decorator(cls): """Decorator.""" class Wrapped(cls): """Wrapped class.""" @classmethod def setUpClass(cls): """Class setup...
2557d94a6a33c5ff43c4e937b71939d027b1c7dd
27,115
def auto_label_color(labels): """ ???+ note "Create a label->hex color mapping dict." """ use_labels = set(labels) use_labels.discard(module_config.ABSTAIN_DECODED) use_labels = sorted(use_labels, reverse=False) assert len(use_labels) <= 20, "Too many labels to support (max at 20)" pale...
791de575e500bf2c2e0e1d56c390c59a2f62381c
27,116
import re def dedentString(text): """Dedent the docstring, so that docutils can correctly render it.""" dedent = min([len(match) for match in space_re.findall(text)] or [0]) return re.compile('\n {%i}' % dedent, re.M).sub('\n', text)
a384b0c9700a17a7ce621bca16175464192c9aee
27,117
def preprocess(df): """Preprocess the DataFrame, replacing identifiable information""" # Usernames: <USER_TOKEN> username_pattern = r"(?<=\B|^)@\w{1,18}" df.text = df.text.str.replace(username_pattern, "<USERNAME>") # URLs: <URL_TOKEN> url_pattern = ( r"https?://(?:[a-zA-Z]|[0-9]|[$-_@.&...
d592d9e56af9ec17dcebede31d458dfdc001c220
27,118
def mobilenetv3_large_w7d20(**kwargs): """ MobileNetV3 Small 224/0.35 model from 'Searching for MobileNetV3,' https://arxiv.org/abs/1905.02244. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.chainer/model...
550f8273dfe52c67b712f8cd12d1e916f7a917cc
27,119
def random_forest_classifier(model, inputs, method="predict_proba"): """ Creates a SKAST expression corresponding to a given random forest classifier """ trees = [decision_tree(estimator.tree_, inputs, method="predict_proba", value_transform=lambda v: v/len(model.estimators_)) for estimator...
d13e28e05d01a2938116a1bac5ddbd64f7b5438c
27,120
from cowbird.utils import get_settings as real_get_settings import functools def mock_get_settings(test): """ Decorator to mock :func:`cowbird.utils.get_settings` to allow retrieval of settings from :class:`DummyRequest`. .. warning:: Only apply on test methods (not on class TestCase) to ensure t...
8332d08846bcee6e9637f75c5c15fb763d9978a4
27,121
def _convert_to_interbatch_order(order: pd.Series, batch: pd.Series) -> pd.Series: """ Convert the order values from a per-batch order to a interbatch order. Parameters ---------- order: pandas.Series order and batch must share the same index, size and be of...
235e99d8a93ebeecde7bfe274b82fe32980288dd
27,122
def CV_INIT_3X3_DELTAS(*args): """CV_INIT_3X3_DELTAS(double deltas, int step, int nch)""" return _cv.CV_INIT_3X3_DELTAS(*args)
cbcbd6de2593d548c8e5bc02992d1df9a3d66460
27,123
def is_instance_cold_migrated_alarm(alarms, instance, guest_hb=False): """ Check if an instance cold-migrated alarm has been raised """ expected_alarm = {'alarm_id': fm_constants.FM_ALARM_ID_VM_COLD_MIGRATED, 'severity': fm_constants.FM_ALARM_SEVERITY_CRITICAL} return _instanc...
8b6db3498d09d4d538382507ffac249226a2912f
27,124
def precision_macro(y_target, y_predicted): """ y_target: m x n 2D array. {0, 1} real labels y_predicted: m x n 2D array {0, 1} prediction labels m (y-axis): # of instances n (x-axis): # of classes """ average = 'macro' score = precision_score(y_target, y_predicted, ave...
4038eb838f35da93b24301809e5f0c3d5c37e2c9
27,125
def layout(mat,widths=None,heights=None): """layout""" ncol=len(mat[0]) nrow=len(mat) arr=[] list(map(lambda m: arr.extend(m),mat)) rscript='layout(matrix(c(%s), %d, %d, byrow = TRUE),' %(str(arr)[1:-1],nrow,ncol) if widths: rscript+='widths=c(%s),' %(str(widths)[1:-1]) if h...
813fb351b4e09d4762255ecbbe6f9ee7e050efd0
27,126
def get_file_language(filename, text=None): """Get file language from filename""" ext = osp.splitext(filename)[1] if ext.startswith('.'): ext = ext[1:] # file extension with leading dot language = ext if not ext: if text is None: text, _enc = encoding.read(filename) ...
7cfcd49d94cc1c2246f03946cfea1c99b866f941
27,127
import re def _get_output_name(fpattern,file_ind,ind): """ Returns an output name for volumetric image This function returns a file output name for the image volume based on the names of the file names of the individual z-slices. All variables are kept the same as in the original filename, but the...
8ce392acab2984b5012d8de7a0aa205f9a5e5e3b
27,128
import re def MatchNameComponent(key, name_list, case_sensitive=True): """Try to match a name against a list. This function will try to match a name like test1 against a list like C{['test1.example.com', 'test2.example.com', ...]}. Against this list, I{'test1'} as well as I{'test1.example'} will match, but ...
ad522feba9cabb3407e3b8e1e8c221f3e9800e16
27,129
import requests def news_api(): """Uses news API and returns a dictionary containing news """ news_base_url = "https://newsapi.org/v2/top-headlines?" news_api_key = keys["news"] country = location["country"] news_url = news_base_url + "country=" + country + "&apiKey=" + news_api_key n_api = re...
45e8a9d42d64066e2259fc95727d52e6b5bdfc9e
27,130
def compress(mesh, engine_name="draco"): """ Compress mesh data. Args: mesh (:class:`Mesh`): Input mesh. engine_name (``string``): Valid engines are: * ``draco``: `Google's Draco engine <https://google.github.io/draco/>`_ [#]_ Returns: A binary string rep...
67d8ec030d006f6720bacffad7bacd0c36b9df42
27,131
import os def _is_syntax_is_missing(language): """ download the grammar for a specific language if the files is missing @param language language: python, sqlite, ... @return grammar file """ locations = { "R": "https://github.com/antlr/grammars-v4/t...
8e6a51ec1b8b9b886778b961dafe0d9b995fb4c0
27,132
import configparser def get_hotkey_next(config: configparser.RawConfigParser): """ 获取热键:下一个桌面背景 """ return __get_hotkey(config, 'Hotkey', 'hk_next')
3af499c01778a1defb0a440d042538885d829398
27,133
def abs_to_rel_f(vector, cell, pbc): """ Converts a position vector in absolute coordinates to relative coordinates for a film system. """ # TODO this currently only works if the z-coordinate is the one with no pbc # Therefore if a structure with x non pbc is given this should also work. # m...
ccd1cc4282464b2a5bf4bc9110ba219d93a66b06
27,134
def get_soup(url): """ Returns beautiful soup object of given url. get_soup(str) -> object(?) """ req = urllib2.Request(url) response = urllib2.urlopen(req) html = response.read() soup = bs4(html) return soup
8d0bb43ae1d404cef5a3873dfd089b88461bf9fd
27,135
def internal_server_error(error): """ Handles unexpected server error with 500_SERVER_ERROR """ message = error.message or str(error) app.logger.info(message) return make_response(jsonify(status=500, error='Internal Server Error', message=message), 500)
8e80a4502a4656a1ccdb2c720177090dd7bcf53a
27,136
import math def diffsnorms(A, S, V, n_iter=20): """ 2-norm accuracy of a Schur decomp. of a matrix. Computes an estimate snorm of the spectral norm (the operator norm induced by the Euclidean vector norm) of A-VSV', using n_iter iterations of the power method started with a random vector; n_i...
2f446a08c6ff5d8377cca22ffcd1570c68f46748
27,137
from typing import Iterator from typing import Tuple def data_selection(workload: spec.Workload, input_queue: Iterator[Tuple[spec.Tensor, spec.Tensor]], optimizer_state: spec.OptimizerState, current_param_container: spec.ParameterContainer, h...
6daa0950e5ce82da081b71a01572dc29374f17f8
27,138
def graph_cases_factory(selenium): """ :type selenium: selenium.webdriver.remote.webdriver.WebDriver :rtype: callable :return: Constructor method to create a graph cases factory with a custom host. """ return lambda host: GraphCaseFactory(selenium=selenium, host=host)
b41b02c148b340c07859e707cbaf4810db3b6004
27,139
def clean_scene_from_file(file_name): """ Args: file_name: The name of the input sequence file Returns: Name of the scene used in the sequence file """ scene = scenename_from_file(file_name) print('Scene: ', scene) mesh_file = SCENE_PATH + scene + '/10M_clean.ply' return ...
cd706c900ca3e3fce6736ce5c4288cce6079b3e0
27,140
def _non_overlapping_chunks(seq, size): """ This function takes an input sequence and produces chunks of chosen size that strictly do not overlap. This is a much faster implemetnation than _overlapping_chunks and should be preferred if running on very large seq. Parameters ---------- seq : ...
15b5d2b4a7d8df9785ccc02b5369a3f162704e9e
27,141
import sys import torch def load_data(path="/home/bumsoo/Data/Planetoid", dataset="cora"): """ ind.[:dataset].x => the feature vectors of the training instances (scipy.sparse.csr.csr_matrix) ind.[:dataset].y => the one-hot labels of the labeled training instances (numpy.ndarray) ind.[:dataset]...
dab7f3899dec86d849b5ae93ce7f2832edccec98
27,142
import logging def Compute_Error(X_data, pinn, K, mu, Lf, deltamean, epsilon, ndim) : """ Function to determine error for input data X_data :param array X_data: input data for PINN :param PINN pinn: PINN under investigation :param float K: key parameter for using trapezoidal rule and estimating t...
0789d7c52c96aed5cb40aa45c44c4df09f5cffaf
27,143
import itertools def sort_fiducials(qr_a, qr_b): """Sort 2d fiducial markers in a consistent ordering based on their relative positions. In general, when we find fiducials in an image, we don't expect them to be returned in a consistent order. Additionally, the image coordinate may be rotated from...
daa96f12ef2e94fed86970979e4d140f8a3fa3d5
27,144
from pathlib import Path import jinja2 def form_render(path: str, **kwargs) -> str: """ Just jinja2 """ file_text = Path(path).read_text() template = jinja2.Template(file_text) return template.render(**kwargs)
b5da5afdedcac922c164f644eabeae5f038f9169
27,145
def _names(fg, bg): """3/4 bit encoding part c.f. https://en.wikipedia.org/wiki/ANSI_escape_code#3.2F4_bit Parameters: """ if not (fg is None or fg in _FOREGROUNDS): raise ValueError('Invalid color name fg = "{}"'.format(fg)) if not (bg is None or bg in _BACKGROUNDS): raise Va...
50e4dfe9aa56c1f3fc7622c468045b26da9b4175
27,146
def preprocess(code): """Preprocess a code by removing comments, version and merging includes.""" if code: #code = remove_comments(code) code = merge_includes(code) return code
b4ecbf28fa2043559b744e7351f268a2ba1e8200
27,147
import types def _from_schemas_get_model( stay_within_model: bool, schemas: _oa_types.Schemas, schema: _oa_types.Schema ) -> types.ModelArtifacts: """ Get artifacts for a model. Assume the schema is valid. Args: schema: The schema of the model to get artifacts for. schemas: All d...
0c5166c6baaabda64795729554b7bb3444a902c9
27,148
def solution2(inp): """Solves the second part of the challenge""" return "done"
8e20e1a81911b3f2e54fac058df8a44e54945af0
27,149
import math def juld_to_grdt(juld: JulianDay) -> GregorianDateTime: """ユリウス通日をグレゴリオ曆の日時に變換する.""" A = math.floor(juld.julian_day + 68569.5) B = juld.julian_day + 0.5 a = math.floor(A / 36524.25) b = A - math.floor(36524.25 * a + 0.75) c = math.floor((b + 1) / 365.25025) d = b - math.floor(3...
94559bbec7fef45e6c7f6d8594d20c8039b58672
27,150
def users_all(request): """ Returns name + surname and email of all users Note: This type of function can only be justified when considering the current circumstances: An *INTERNAL* file sharing app (used by staff) Hence, all names and emails may be fetched be other authenticated users ...
53302d074ee1bbbc1156ffa2f94da4f834e9cb3c
27,151
def _resolve_categorical_entities(request, responder): """ This function retrieves all categorical entities as listed below and filters the knowledge base using these entities as filters. The final search object containing the shortlisted employee data is returned back to the calling function. """ ...
d6671d030699df1b0400b1d478dc98f86be06c29
27,152
def filter_c13(df): """ Filter predicted formulas with 13C. Returns filtered df and n excluded """ shape_i = df.shape[0] df = df[df['C13'] == 0] df = df.reset_index(drop=True) shape_f = df.shape[0] n_excluded = shape_i - shape_f return df, n_excluded
4f0d3eb6c9de7c07bc2e3f285ad5502bb6d6dd06
27,153
import random import gzip def getContent(url): """ 此函数用于抓取返回403禁止访问的网页 """ random_header = random.choice(HEARDERS) """ 对于Request中的第二个参数headers,它是字典型参数,所以在传入时 也可以直接将个字典传入,字典中就是下面元组的键值对应 """ req = Request(url) req.add_header("User-Agent", random_header) req.add_header("Ho...
da396d664fb23737ea2d87b6548521948adad709
27,154
def neighbour(x,y,image): """Return 8-neighbours of image point P1(x,y), in a clockwise order""" img = image.copy() x_1, y_1, x1, y1 = x-1, y-1, x+1, y+1; return [img[x_1][y], img[x_1][y1], img[x][y1], img[x1][y1], img[x1][y], img[x1][y_1], img[x][y_1], img[x_1][y_1]]
8e645f7634d089a0e65335f6ea3363d4ed66235b
27,155
from typing import Optional from typing import Literal import os import pickle import torch def _load_saved_files( dir_path: str, load_adata: bool, map_location: Optional[Literal["cpu", "cuda"]] = None, ): """Helper to load saved files.""" setup_dict_path = os.path.join(dir_path, "attr.pkl") a...
a65a34ebaba1c9480356b585768ab5b5c63c1269
27,156
def deconv2d(x, kernel, output_shape, strides=(1, 1), border_mode='valid', dim_ordering='default', image_shape=None, filter_shape=None): """2D deconvolution (i.e. transposed convolution). # Arguments x: input tensor. kernel: kernel tensor. output_s...
d1ed452b627764f0f08c669e4bea749886ebd0a6
27,157
def template(m1, m2): """ :param m1: :param m2: :return: """ c_mass = chirp_mass(m1, m2) B = 16.6 # In seconds to - 5/8 t = np.linspace(0, 0.45, 10000) tc = 0.48 gw_frequency = B * c_mass ** (-5 / 8) * (tc - t) ** (-3 / 8) t_h = np.linspace(-450, 0, 10000) t_merge_...
64e81538e8b37472c7142e9c21d047bf10a19bc7
27,158
def _como_hasheable(matriz): """Retorna una copia hasheable (y por tanto inmutable) de `matriz`.""" return tuple(tuple(fila) for fila in matriz)
a6a1c4371536636d45cfabaf0e2d6938b26a8e08
27,159
def diff(*args, **kwargs): """ Return a diff between two hex list :param args: :param kwargs: :return: """ skip_if_same = True if kwargs.get("skip_if_same", False): skip_if_same = kwargs["skip_if_same"] if len(args) != 2: raise NotImplementedError("Only comparison of ...
c7ec1cc92ef3143798e675576dcc2924e24159bb
27,160
def gravity_effect(position, other_position): """Return effect other_position has on position.""" if position == other_position: return 0 elif position > other_position: return -1 return 1
25130c253cb888057e9b52817cac9cf3778a4c69
27,161
def add_task(request): """add new task""" if request.method == "POST": #check whether name is empty or not if request.POST.get('name') != '': name = request.POST.get('name') priority = request.POST.get('priority') task = Task(name=name,priority=priority) ...
c79e9d78367159af544ae011539b449e70bde4be
27,162
from operator import mul def rots(n_phi_pairs): """ From the provided list of (axis,angle) pairs, construct the product of rotations roti(axis0,angle0) *** roti(axis1,angle1) ... Because rotation of q by A is achieved through A***q***conj(A), rotate( A *** B, q ) is the same as ...
743ebb3a7a8a68f1178ef4f9116607f33dcdb9cf
27,163
def n_cr_shell( thickness, radius, length ): """ Critical compressive load for cylindrical shell. Calculates the critical load for a cylindrical shell under pure compression and assumes uniform stress distribution. Calculation according to EN1993-1-6 [1], Annex D. Param...
1210c3f19a801a7ddf3bae7b478c47732c701433
27,164
def unique_slug(s, model, num_chars=50): """ Return slug of num_chars length unique to model `s` is the string to turn into a slug `model` is the model we need to use to check for uniqueness """ slug = slugify(s) slug = slug[:num_chars].strip('-') while True: dup = model.objects...
ef34215722cca23417c9e944f6320dba79188c8c
27,165
def _to_vertexes(data): """create points at every vertex, incl holes""" # create new file outfile = GeoTable() outfile.fields = list(data.fields) # loop points if "LineString" in data.type: for feat in data: if "Multi" in feat.geometry["type"]: for l...
8c82eac68399e10b1cf87155f6c2b9e8318a8205
27,166
import pickle def _load(fname) : """ Load a cached file and return the resulting object @param fname: file name """ try : f = open(fname) return pickle.load(f) finally : f.close()
5fd5496d226c2ff8265b3dafa0b038bb8015ec5d
27,167
import warnings def reale(x, com="error", tol=None, msg=None, xp=None): """Return real part of complex data (with error checking). Parameters ---------- x : array-like The data to check. com : {'warn', 'error', 'display', 'report'} Control rather to raise a warning, an error, or t...
0823cdc3cb989f7b29dc70e010ad0ae0d2132fbd
27,168
def find_less_than_or_equal(series_key, value): """Find the largest value less-than or equal-to the given value. Args: series_key: An E-Series key such as E24. value: The query value. Returns: The largest value from the specified series which is less-than or equal-to the qu...
4bc6f00910c8d5453d7db82869fe37cd3244cd45
27,169
def GetCommentsByMigration(migration): """Get the comments for a migration""" q = db.Query(models.Comment).filter('migration =', migration) return list(q.fetch(1000))
555f5c8d2df5b05c579b8e20d30e54a035056081
27,170
def get_proxy_list(html_response): """ Returns list of proxies scraped from html_response. :param html_response: Raw HTML text :type html_response: unicode :rtype: list[unicode] """ try: tmp = IPS_REGEXP.findall(html_response.replace("\n", ","))[0] proxies = tmp.split("</tex...
38978d1c65022f2575fd9ce94cddb02782fb82fd
27,171
import fnmatch def ignore_paths(path_list, ignore_patterns, process=str): """ Go through the `path_list` and ignore any paths that match the patterns in `ignore_patterns` :param path_list: List of file/directory paths. :param ignore_patterns: List of nukeignore patterns. :param process: Function t...
63196e54eb4505cbe12ebf77d2a42fede68c1d0b
27,172
import requests def check_static(url): """ Check viability of static links on cf.gov home page and sub-pages. Example call to check static assets in production: ./cfgov/scripts/static_asset_smoke_test.py -v /ask-cfpb/ /owning-a-home/ Example of local check of home page: ./cfgov/scripts/stati...
bccc85254c21471447c15c6fd6a9f2aaaa6ce10d
27,173
def validation_error_handler(err): """ Used to parse use_kwargs validation errors """ headers = err.data.get("headers", None) messages = err.data.get("messages", ["Invalid request."]) schema = ResponseWrapper() data = messages.get("json", None) error_msg = "Sorry validation errors occurr...
3b7ef977b0cf4ec892314923e988509f17e7f49c
27,174
def is_element(a, symbol="C"): """ Is the atom of a given element """ return element(a) == symbol
a04068346d8872f2f3d6228c0f862bcc11d0ff1b
27,175
def create_call_status(job, internal_storage): """ Creates a call status class based on the monitoring backend""" monitoring_backend = job.config['lithops']['monitoring'] Status = getattr(lithops.worker.status, '{}CallStatus' .format(monitoring_backend.capitalize())) return Status(j...
63c9903d5facff8512c40b2838b0796869cdb9ff
27,176
from pathlib import Path import logging def file_handler() -> RotatingFileHandler: """Create a file-based error handler.""" handler = RotatingFileHandler( Path("log") / "error.log", maxBytes=50_000, backupCount=5, delay=True, ) handler.setLevel(logging.ERROR) handle...
62de46cf48e99dabc04a0f3c5ed7083f9261ed6a
27,177
def get_additional_node_groups(node_name, deployment_id): """This enables users to reuse hosts in multiple groups.""" groups = [] try: client = get_rest_client() except KeyError: return groups deployment = client.deployments.get(deployment_id) for group_name, group in deployment....
76cc8f8b98adde91a75c6ab6f39fa6ca17ceabe0
27,178
def is_requirement(line): """ Return True if the requirement line is a package requirement. Returns: bool: True if the line is not blank, a comment, a URL, or an included file """ return line and not line.startswith(('-r', '#', '-e', 'git+', '-c'))
2b89ced1920ac136e9437fda2fd2f8841debf847
27,179
def pden(s, t, p, pr=0): """ Calculates potential density of water mass relative to the specified reference pressure by pden = dens(S, ptmp, PR). Parameters ---------- s(p) : array_like salinity [psu (PSS-78)] t(p) : array_like temperature [℃ (ITS-90)] p : array_li...
c2b64dbfc3ed554a8929f420792ea56df3858cc0
27,180
import typing def SWAP(first: int, second: int, control: typing.Union[int, list] = None, power: float = None) -> QCircuit: """ Notes ---------- SWAP gate, order of targets does not matter Parameters ---------- first: int target qubit second: int target qubit contro...
f5a7af3cc4c9618a17465c3890be81d3251750da
27,181
def stable_normalize(x, etha=1.0e-8): """ Numerically stable vector normalization """ n = np.linalg.norm(x, axis=-1, keepdims=True) if n < etha: n = etha return x / n
36428ecde3993c225b19ccc19278d34c4d9bac36
27,182
import time from functools import reduce def Word2VecFeatureGenerator(df): """ Finds and returns word embedding for the head and body and computes cosine similarity. Input: DataFrame Returns list(headlineVec, bodyVec, simVec)""" t0 = time() print("\n---Generating Word2Vector Features...
0ff2c339ed953592173c0d5afafc72daeeef86a2
27,183
def reachable(Adj, s, t): """ Adj is adjacency list rep of graph Return True if edges in Adj have directed path from s to t. Note that this routine is one of the most-used and most time-consuming of this whole procedure, which is why it is passed an adjacency list rep rather than a list of ver...
dc0ea0c6d2314fa1c40c3f3aa257a1c77892141f
27,184
def remove_links( actor: Actor, company: Company, *, facebook=False, linkedin=False, twitter=False ) -> Response: """Remove links to all existing Online Profiles.""" response, _ = update_profiles( actor, company, facebook=facebook, linkedin=linkedin, twitter=twitter, ...
bdfeefa8366031022a3a108c385f244e6fd740bf
27,185
def get_basis_psd(psd_array, notes): """Get avg psd from the training set (will serve as a basis)""" psd_dict = {} psd_basis_list = [] syl_basis_list = [] unique_note = unique(notes) # convert note string into a list of unique syllables # Remove unidentifiable note (e.g., '0' or 'x') if '...
f8b1e596fdda1125159a963d3362e87abe7b4bfe
27,186
def _get_columns(statement): """Get the available columns in the query `statement`. :param statement: A SQL SELECT statement. :returns: A list of columns that are being selected. """ expecting_columns = False for token in statement.tokens: if token.is_whitespace(): pass ...
49db28bd92d05f4d6e35c32f87e0be4a04e80a92
27,187
from pathlib import Path import logging def config_logging(level=logging.INFO, section="main", mp=False) -> Path: """Configures logging to log to a file and screen mp stands for multiprocessing, didn't want to override that package """ # NOTE: it turns out that subprocess calls, pytest, etc # Se...
5c9b12f674f801ce0a2bb0989a5f740513f57ba8
27,188
def create_conv(in_channels, out_channels, kernel_size, order, num_groups, padding=1): """ Create a list of modules with together constitute a single conv layer with non-linearity and optional batchnorm/groupnorm. Args: in_channels (int): number of input channels out_channels (int): numb...
43ccd6342b0598ab0715960cbae8ad9efb7e29ce
27,189
def expand_json(metadata, context=DEFAULT_CONTEXT): """ Expand json, but be sure to use our documentLoader. By default this expands with DEFAULT_CONTEXT, but if you do not need this, you can safely set this to None. # @@: Is the above a good idea? Maybe it should be set to None by # default...
6fa1f5c4f93f75e45c9a535fe56190ea869dfaa0
27,190
import os def prepare_test_data(): """ Load data01.nc and manipulate to create additional test data. Used to load data into data_dict below. """ # Dictionary in which to store data data_dict = {} # Load data01.nc Dataset data01 = xr.open_dataset(os.path.dirname(__file__)+'/data/data01....
cf690ce73fcf46a65a6bdd1b51de11488fbe4461
27,191
import os def path(path_list): """ Returns an absolute path for the given folders structure :path_list: receives a list type object where each element is an folder and it can end in a file name """ path = MAIN_FOLDER for folder in path_list: path = os.path.join(path, folder) re...
826546670e0daece681023c1a8122a4a20bfe6e1
27,192
def get_kubernetes_bearer_token(): """Reads the bearer token required to call the Kubernetes master from a file. The file is installed in every container within a Kubernetes pod by the Kubelet. The path to the file is documented at https://github.com/GoogleCloudPlatform/kubernetes/blob/master/docs/accessing-th...
7de7199a7dbdab68f519a4767f176d0a396c8120
27,193
import os import copy from datetime import datetime def show(c, verbose, config): """Show current position.""" file = os.path.expanduser(config["file"]) move = config["move"] level = int(config["level"]) pointer = config['pointer'] maxtime = int(config['maxtime']) bookmark = config["bookma...
c6c1083a8193171518381cdd439413ebdfb98a17
27,194
def parsemsg(s, encoding="utf-8"): """Parse an IRC Message from s :param s bytes: bytes to parse :param encoding str: encoding to use (Default: utf-8) :returns tuple: parsed message in the form of (prefix, command, args) """ s = s.decode(encoding, 'replace') prefix = u("") trailing =...
b0205609724eb91d6b53fe37cc9be508a640a95a
27,195
def concatenate_unique(la, lb): """Add all the elements of `lb` to `la` if they are not there already. The elements added to `la` maintain ordering with respect to `lb`. Args: la: List of Python objects. lb: List of Python objects. Returns: `la`: The list `la` with missing elements from `lb`. ""...
307fde291233727c59e2211afc3e0eed7c8ea092
27,196
from datetime import datetime def email_last_send_for_sub(sub_id): """Return when an email was last sent for a subscription, or None.""" last_sent = db.get('email_sub_last_sent:{}'.format(sub_id)) if last_sent is not None: return datetime.datetime.strptime(last_sent, '%Y-%m-%dT%H:%M:%SZ')
e44740a38a2af35c92474aa8da92481d439cc94c
27,197
def is_output_op(node): """Return true when the node is the output of the graph.""" return node.WhichOneof("op_type") == "output_conf"
9a20a471a397a480cc2b295cc96961e030f71e43
27,198
import torchvision def plot_samples_close_to_score(ood_dict: dict, dataset_name: str, min_score: float, max_score: float, n: int = 32, do_lesional: bool = True, show_ground_truth: bool = False, print_score: bool = False) -> None: """Arrange slices in...
33149237d3d36cbae04a1902994487107447a5e5
27,199