content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def parse_variable_char(packed): """ Map a 6-bit packed char to ASCII """ packed_char = packed if packed_char == 0: return "" if 1 <= packed_char <= 10: return chr(ord('0') - 1 + packed_char) elif 11 <= packed_char <= 36: return chr(ord('A') - 11 + packed_char) elif 37 <=...
e4ff95bca48ae97a22c20dda4fd82e082c32be27
3,639,800
def get_feature_vector(feature_id, cohort_id_array): """ Fetches the data from BigQuery tables for a given feature identifier and one or more stored cohorts. Returns the intersection of the samples defined by the feature identifier and the stored cohort. Each returned data point is represented as a...
9aee52ef43f964d8d524390fbd5bdc49e91dcdf2
3,639,801
def analyse(tx): """ Analyses a given set of features. Marks the features with zero variance as the features to be deleted from the data set. Replaces each instance of a null(-999) valued feature point with the mean of the non null valued feature points. Also handles the outliers by clipping th...
2bfd46b2cb70da9822a4a86f588e187ab941ea88
3,639,802
import regex def validate_word_syntax(word): """ This function is designed to validate that the syntax for a string variable is acceptable. A validate format is English words that only contain alpha characters and hyphens. :param word: string to validate :return: boolean true or false ...
47b732ffc0c2c91c5a092d7367b49bb8946697be
3,639,803
def next_page(context): """ Get the next page for signup or login. The query string takes priority over the template variable and the default is an empty string. """ if "next" in context.request.GET: return context.request.GET["next"] if "next" in context.request.POST: retu...
6abc1c8ef260366e53f335a27ee42f0356c91b63
3,639,804
import numpy def make_train_test_sets(input_matrix, label_matrix, train_per_class): """Return ((training_inputs, training_labels), (testing_inputs, testing_labels)). Args: input_matrix: attributes matrix. Each row is sample, each column is attribute. label_matrix: labels matrix. Each row is s...
bd71f48ed9405a89dfa42b3cb6cfe45b064a6b4d
3,639,805
def add_coords_table(document: Document, cif: CifContainer, table_num: int): """ Adds the table with the atom coordinates. :param document: The current word document. :param cif: the cif object from CifContainer. :return: None """ atoms = list(cif.atoms()) table_num += 1 headline = "...
6b351138624bd530739d199898fbc4f0cfb56bb1
3,639,806
import numpy def bz(xp, yp, zp, spheres): """ Calculates the z component of the magnetic induction produced by spheres. .. note:: Input units are SI. Output is in nT Parameters: * xp, yp, zp : arrays The x, y, and z coordinates where the anomaly will be calculated * spheres : list o...
16d85978e50de16ab6af91c6ee83392b7fa43e3e
3,639,807
def update_stocks(): """ method to update the data (used by the spark service) :return: """ global stocks body = request.get_json(silent=True) ''' { "data" : [ { "symbol" : "string", "ask_price" : "string", "last_sale_t...
f1db3a9a1ba7cd20aad2e8ddc0bea66997ef11dd
3,639,808
from typing import Iterable from re import T from typing import Sequence import itertools def chunks_from_iterable(iterable: Iterable[T], size: int) -> Iterable[Sequence[T]]: """Generate adjacent chunks of data""" it = iter(iterable) return iter(lambda: tuple(itertools.islice(it, size)), ())
76bf5a8742f082da860caec477c72338fcc4510e
3,639,809
import os def load_ct_phantom(phantom_dir): """ load the CT data from a directory Parameters ---------- phantom_dir : str The directory contianing the CT data to load Returns ------- ndarray the CT data array list the spacing property for this CT """ ...
6344889d0b363062754191282d1c96c29f2bea2d
3,639,810
from typing import Dict def summary_overall(queryset: QuerySet) -> Dict[str, Decimal]: """Summarizes how much money was spent""" amount_sum = sum([value[0] for value in queryset.values_list('amount')]) return {'overall': amount_sum}
6d2d276ca891f99ac171001c99ff0d90b530a5b1
3,639,811
import torch def _get_trained_ann(train_exo: "ndarray", train_meth: "ndarray") -> "QdaisANN2010": """Return trained ANN.""" train_data = BiogasData(train_exo, train_meth) ann = QdaisANN2010(train_data.train_exo.shape[1]) try: ann.load_state_dict(torch.load("./assets/ann.pt")) except IOErro...
08bd38450e217c00643ab7fefe1c1860fc5d1ebf
3,639,812
def pi_float(): """native float""" lasts, t, s, n, na, d, da = 0, 3.0, 3, 1, 0, 0, 24 while s != lasts: lasts = s n, na = n+na, na+8 d, da = d+da, da+32 t = (t * n) / d s += t return s
8a6a6a5942ddd61ecdf65b782bb2fc0f0519ddb5
3,639,813
def iso3_to_country(iso3): """ Take user input and convert it to the short version of the country name """ if iso3 == 'Global': return 'Global' country = coco.convert(names=iso3, to='name_short') return country
2c2904ba8befe802d531b371f046ff4a3ba4db22
3,639,814
def test_bivariate(N, n_neighbors, rng, noise): """Test with bivariate normal variables""" mu = np.zeros(2) cov = np.array([[1., 0.8], [0.8, 1.0]]) xy_gauss = rng.multivariate_normal(mu, cov, size=N) x, y = xy_gauss[:, 0], xy_gauss[:, 1] z = rng.normal(size=N) cmi_analytic = -0.5 * np.log(d...
827b968c6333402066d1fa4282ce90c2cdb175f5
3,639,815
import math def osm_tile_number_to_latlon(xtile, ytile, zoom): """ Returns the latitude and longitude of the north west corner of a tile, based on the tile numbers and the zoom level""" n = 2.0 ** zoom lon_deg = xtile / n * 360.0 - 180.0 lat_rad = math.atan(math.sinh(math.pi * (1 - 2 * ytile / n))) lat_deg = mat...
8afbbb218835311bebcfe6a0d611e0e62bfcffc3
3,639,816
def prodtab_111(): """ produces angular distance from [1,1,1] plane with other planes up to (321) type """ listangles_111 = [anglebetween([1, 1, 1], elemref) for elemref in LISTNEIGHBORS_111] return np.array(listangles_111)
cb49c087e5b5090bca788f9c33862c37c42c2f1c
3,639,817
def cuda_cos(a): """ Trigonometric cosine of GPUArray elements. Parameters: a (gpu): GPUArray with elements to be operated on. Returns: gpu: cos(GPUArray) Examples: >>> a = cuda_cos(cuda_give([0, pi / 4])) array([ 1., 0.70710678]) >>> type(a) <class 'p...
e411bde08f133c8f9109ff5815f44a3ff5262282
3,639,818
from typing import Counter def top_diffs(spect: list, num_acids: int) -> list: """Finds at least num_acids top differences in [57, 200] Accepts ties :param spect: a cyclic spectrum to find differences in :type spect: list (of ints) :type keep: int :returns: the trimmed leaderboard :rtype...
1ca2b08f6ecbf69b1ab2189b1cbbff9b4e1c2e8d
3,639,819
import typing def form_sized_range(range_: Range, substs) -> typing.Tuple[ SizedRange, typing.Optional[Symbol] ]: """Form a sized range from the original raw range. The when a symbol exists in the ranges, it will be returned as the second result, or the second result will be none. """ if not...
ac0d4299198f0e5611acb8167107f56f2b49bb0f
3,639,820
def create_html_app(): # pragma: no cover """Returns WSGI app that serves HTML pages.""" app = webapp2.WSGIApplication( handlers.get_frontend_routes(), debug=utils.is_local_dev_server()) gae_ts_mon.initialize(app, cron_module='backend') return app
c1d9320b9f795466f28a511180f9949ec9c6ecbd
3,639,821
def line_integrals(vs, uloc, vloc, kind="same"): """ calculate line integrals along all islands Arguments: kind: "same" calculates only line integral contributions of an island with itself, while "full" calculates all possible pairings between all islands. """ if kind == "sam...
8808c3afd4374465bd64aa0db658d8843a74a4da
3,639,822
def crop_black_borders(image, threshold=0): """Crops any edges below or equal to threshold Crops blank image to 1x1. Returns cropped image. """ if len(image.shape) == 3: flatImage = np.max(image, 2) else: flatImage = image assert len(flatImage.shape) == 2 rows = np.wh...
77ec884f4f173844f5d5124a29bb94eb641e25ec
3,639,823
def change_password(): """Allows user to change password""" # Forget any user_id session.clear() # User reached route via POST (as by submitting a form via POST) if request.method == "POST": # If password and confirmation don't match, accuse error if request.form.get("new_password...
afff43726d3e30a1ea09af20df1099b00c14b843
3,639,824
def add_placeholders(components): """Add placeholders for missing DATA/INSTANCE components""" headers = [s[:2] for s in components] for prefix in ("CD", "CR"): if prefix not in headers: components.append(prefix + ("C" * 11)) return components
303f1590042acc60aa753e5e317417de01fafafc
3,639,825
from ..items import HieroClipItem def clipsToHieroClipItems(clips): """ @itemUsage hiero.items.HieroClipItem """ clipItems = [] if clips: for c in clips: i = HieroClipItem(c) clipItems.append(i) return clipItems
bf4c6aaff649796cc1a24eb7ba3102fb01178ab3
3,639,826
import hashlib def md5(s, raw_output=False): """Calculates the md5 hash of a given string""" res = hashlib.md5(s.encode()) if raw_output: return res.digest() return res.hexdigest()
238c2a6c6b06a046de86e514698c7ef5622f770b
3,639,827
def new_Q(T, ms, Ps, G): """TODO DOC STRING""" print("==> Tuning Q") SIGMA = np.zeros_like(Ps[0], dtype=np.complex128) PHI = np.zeros_like(Ps[0], dtype=np.complex128) C = np.zeros_like(Ps[0], dtype=np.complex128) shape = (Ps[0].shape[0], 1) for k in range(1, T + 1): m1 = gains_...
a21b96e4be7f1c9f6ba892e54ef75b03e4eb9e42
3,639,828
def _get_pk_message_increase(cache_dict: dict, project_list: list) -> str: """根据项目列表构建增量模式下PK播报的信息. ### Args: ``cache_dict``: 增量计算的基础.\n ``project_list``: PK的项目列表.\n ### Result: ``message``: PK进展的播报信息.\n """ amount_dict = _get_pk_amount(project_list) incr...
9343626fe8208e5e08c39abda9c6b26252ac6b2b
3,639,829
def flatten(dic, keep_iter=False, position=None): """ Returns a flattened dictionary from a dictionary of nested dictionaries and lists. `keep_iter` will treat iterables as valid values, while also flattening them. """ child = {} if not dic: return {} for k, v in get_iter(dic): ...
4597a0330468e955cadda37f89f73bed7db1ecb5
3,639,830
import json def game_get_state(): """The ``/game/state`` endpoint requires authentication and expects no other arguments. It can be reached at ``/game/state?secret=<API_SECRET>``. It is used to retrieve the current state of the game. The JSON response looks like:: { "state_id...
b5b3bda433764413fb6116b5b8f13d6e9dfef866
3,639,831
def new(key, mode, iv=None): """Return a `Cipher` object that can perform ARIA encryption and decryption. ARIA is a block cipher designed in 2003 by a large group of South Korean researchers. In 2004, the Korean Agency for Technology and Standards selected it as a standard cryptographic technique. ...
8906d9f5efe36349fc520c8022bf52d888bd37ea
3,639,832
import logging def keggapi_info(database, verbose=True, force_download=False, return_format = None, return_url = False): """KEGG REST API interface for INFO command Displays information on a given database for further info read https://www.kegg.jp/kegg/rest/keggapi.html Parameters ------...
366e4910d54e725e2f8dc8399e7793604a767449
3,639,833
def round_to_thirty(str_time): """STR_TIME is a time in the format HHMM. This function rounds down to the nearest half hour.""" minutes = int(str_time[2:]) if minutes//30 == 1: rounded = "30" else: rounded = "00" return str_time[0:2] + rounded
37e8473dbb6e91fc47a03491c421967db231d4d0
3,639,834
import os import shutil def mkdir(path, reset=False): """Checks if directory exists and if not, create one. Parameters ---------- reset: erase the content of the directory if exists Returns ------- the path """ if reset and os.path.exists(path): shutil.rmtree(path) try...
64a868231cd3bd7199eef2ad19b2b7296e0c32fe
3,639,835
def remove_uoms(words): """ Remove uoms in the form of e.g. 1000m 1543m3 Parameters ---------- words: list of words to process Returns ------- A list of words where possible uom have been removed """ returnWords=[] for word in words: word=word.replace('.', '', 1) ...
cdb2caf274a58b61c57ebe4fba167ec6275ddf6f
3,639,836
import logging import sys def parse_region(reg: str) -> tuple: """ Return a pair of slices (slice1, slice2) corresponding to the region give as input in numpy slice string format If the region can't be parsed sys.exit() is called """ try: slices = str_to_slices(reg) except ValueErr...
4d2ab5e546c69f6e5a9ee9560052ae395d189e95
3,639,837
from unittest.mock import patch async def create_wall_connector_entry( hass: HomeAssistant, side_effect=None ) -> MockConfigEntry: """Create a wall connector entry in hass.""" entry = MockConfigEntry( domain=DOMAIN, data={CONF_HOST: "1.2.3.4"}, options={CONF_SCAN_INTERVAL: 30}, ...
5aa8fdc08b13d7fe26df50312f736e9ec1d4bfdd
3,639,838
def _normalize(data): """ Normalizes the data (z-score) :param data: Data to be normalized :return: Nomralized data """ mean = np.mean(data, axis=0) sd = np.std(data, axis=0) # If Std Dev is 0 if not sd: sd = 1e-7 return (data - mean) / sd
1fe31f73d9e7fae03997f6caa1a28ebe929e49bd
3,639,839
from typing import Dict from typing import Any import logging def merge_target_airport_configs( weather_flight_features: pd.DataFrame, configs: pd.DataFrame, parameters: Dict[str, Any], )-> pd.DataFrame: """ This function merges actual airport configuration values to the main data fram...
29fbf3a0dc166a5b97bd86fbe4ffd2f7d03efad1
3,639,840
def chunks(chunkable, n): """ Yield successive n-sized chunks from l. """ chunk_list = [] for i in xrange(0, len(chunkable), n): chunk_list.append( chunkable[i:i+n]) return chunk_list
d59c6afd85705aa1954d7cc0631e98f2e9e5cdcf
3,639,841
def pass_generate(): """ Стартовая процедура генератора паролей. """ func = generate_pass_block param = {'min_len': 4, 'max_len': 6} return f'{func(**param)}-{func(**param)}-{func(**param)}'
e0bb5378c308e0c60568bb2b3701ee90d5bf6a8e
3,639,842
from . import analyzer as anl def lineSpectrum(pos, image, data, width, scale=1, spacing=3, mode="dual"): """ Draw sepectrum bars. :param pos: (x, y) - position of spectrum bars on image :param image: PIL.Image - image to draw :param data: 1D array - sound data :param width: int - widht of spectrum on ima...
5ee27565bc83ef275d4882b44b11a3b7cd1407b3
3,639,843
def _unique_arXiv(record, extra_data): """Check if the arXiv ID is unique (does not already exist in Scoap3)""" arxiv_id = get_first_arxiv(record) # search through ES to find if it exists already if arxiv_id: result = current_search_client.search( 'scoap3-records-record', ...
6b19a10400da024c5ad87090c87f6099a4018dab
3,639,844
def profile(username): """ Профиль пользователя. Возможность изменить логин, пароль. В перспективе сохранить свои любимые ссылки. """ if username != current_user.nickname: return redirect(url_for('index')) types = Types.manager.get_by('', dictionary=True) return render_template('au...
84bb1304ef5862efdd54ad2402e09d31a8c151a2
3,639,845
def had_cell_edge(strmfunc, cell="north", edge="north", frac_thresh=0.1, cos_factor=False, lat_str=LAT_STR, lev_str=LEV_STR): """Latitude of poleward edge of either the NH or SH Hadley cell.""" hc_strengths = had_cells_strength(strmfunc, lat_str=lat_str, l...
b666333bb9b0a54d569df96324dbb55747b33a4c
3,639,846
def make_score_fn(data): """Returns a groupwise score fn to build `EstimatorSpec`.""" context_feature_columns, example_feature_columns = data.create_feature_columns() def _score_fn(context_features, group_features, mode, unused_params, unused_config): """Defines the network to score a group of documents...
5f95843413ddeb146c080a30b563b74e863cdb07
3,639,847
def unicode2str(obj): """ Recursively convert an object and members to str objects instead of unicode objects, if possible. This only exists because of the incoming world of unicode_literals. :param object obj: object to recurse :return: object with converted values :rtype:...
62ef4653fd22b58b463dfce62ff83238f47fb9b5
3,639,848
def test_elim_cast_same_dtype(tag): """ test_elim_cast_same_dtype """ fns = FnDict() cast = P.Cast() @fns def fp32_cast_fp32(x, y): return cast(x, y) @fns def after(x, y): return x return fns[tag]
6aa97e39d8bdf4261e212355be85106ee109659f
3,639,849
def getRepository(): """ Determine the SVN repostiory for the cwd """ p = Ptyopen2('svn info') output, status = p.readlinesAndWait() for line in output: if len(line) > 3 and line[0:3] == 'URL': return line[5:].rstrip() raise Exception('Could not determine SVN reposi...
754d2b6a343a4b0283be4ba2846aba80b4d1a95f
3,639,850
import re def replaceInternalLinks(text): """ Replaces internal links of the form: [[title |...|label]]trail with title concatenated with trail, when present, e.g. 's' for plural. See https://www.mediawiki.org/wiki/Help:Links#Internal_links """ # call this after removal of external links, ...
23795baffdaf46883fe08a12861313ed6bc0ee54
3,639,851
from typing import List from typing import Any from typing import Optional def make_table(rows: List[List[Any]], labels: Optional[List[Any]] = None, centered: bool = False) -> str: """ :param rows: 2D list containing objects that have a single-line representation (via `str`). All rows must be of the same ...
ecdc9972dfbb05795556a5ba36b6cf4cd55399f8
3,639,852
def format_value(v): """ Formats a value to be included in a string. @param v a string @return a string """ return ("'{0}'".format(v.replace("'", "\\'")) if isinstance(v, str) else "{0}".format(v))
8b8d5452ecf938b4e9e9956577f1a3f1102e49bc
3,639,853
def worst_solvents(delta_d, delta_p, delta_h, filter_params): """Search solvents on the basis of RED (sorted descending) with given Hansen parameters, and with a formatted string indicating filter parameters. See the function parse_filter_params for details of filter parameters string.""" results_list...
91543a738ef86e77336cedf6edd6175794c4bdcb
3,639,854
import textwrap def log(msg, *args, dialog=False, error=False, **kwargs): """ Generate a message to the console and optionally as either a message or error dialog. The message will be formatted and dedented before being displayed, and will be prefixed with its origin. """ msg = textwrap.dedent...
b204d4205a4fd90b3f0ca7104e3b6dd336b25b46
3,639,855
def build_frustum_lineset(K, l, t, r, b): """Build a open3d.geometry.LineSet to represent a frustum Args: pts_A (np.array or torch.tensor): Point set in form (Nx3) pts_B (np.array or torch.tensor): Point set in form (Nx3) idxs (list of int): marks correspondence between A[i] and B[id...
73236b73692b61a7d7c78005f626d0d6b0f2c84e
3,639,856
import os def _config_file_exists(): """ Checks if the configuration file exists. :return: Returns True if the configuration file exists and False otherwise. :rtype: bool """ if os.path.isfile(DEFAULT_CONFIG_FILE): return True return False
5cbccfd2eb2e87278820e55c23d859cf4644017e
3,639,857
def postagsget(sent): """ sent: Sentence as string """ string = "" ls = pos_tag(list(sent.split())) for i in ls: string += i[1] + " " return string
077e7261e0a0e296381bcb09578557576fe4c86c
3,639,858
def try_convert_to_list_of_numbers(transform_params): """ Args: transform_params: a dict mapping transform parameter names to values This function tries to convert each parameter value to a list of numbers. If that fails, then it tries to convert the value to a number. For example, if transf...
14e33630daab0081d39fd533a606a7b561f5b161
3,639,859
def from_tensorflow(graph): """ Load tensorflow graph which is a python tensorflow graph object into nnvm graph. The companion parameters will be handled automatically. Parameters ---------- graph : GraphDef object Tensorflow GraphDef Returns ------- sym : nnvm.Symbol ...
9547430c05559eb094dbaf3b1528ec071b1c9b50
3,639,860
def isequal(q1, q2, tol=100, unitq=False): """ Test if quaternions are equal :param q1: quaternion :type q1: array_like(4) :param q2: quaternion :type q2: array_like(4) :param unitq: quaternions are unit quaternions :type unitq: bool :param tol: tolerance in units of eps :type t...
6c903bbb547c9015e949e916d0bccda124bad04c
3,639,861
def MMOE(dnn_feature_columns, num_tasks, task_types, task_names, num_experts=4, expert_dnn_units=[32,32], gate_dnn_units=[16,16], tower_dnn_units_lists=[[16,8],[16,8]], l2_reg_embedding=1e-5, l2_reg_dnn=0, seed=1024, dnn_dropout=0, dnn_activation='relu', dnn_use_bn=False): """Instantiates the ...
6be8b400fb58c74d4dc397132327f9ffb819a637
3,639,862
import numpy def greater(self, other): """ Equivalent to the > operator. """ return _PropOpB(self, other, numpy.greater, numpy.uint8)
04d0a6ed3d0023afc3bcea167c67940af9387dc1
3,639,863
def load_translation_data(dataset, src_lang='en', tgt_lang='vi'): """Load translation dataset Parameters ---------- dataset : str src_lang : str, default 'en' tgt_lang : str, default 'vi' Returns ------- """ common_prefix = 'IWSLT2015_{}_{}_{}_{}'.format(src_lang, tgt_lang, ...
f571f8bda3b46dfba7f15f15ac7e46addac6273e
3,639,864
import copy def objective_function(decision_variables, root_model, mode="by_age", country=Region.UNITED_KINGDOM, config=0, calibrated_params={}): """ :param decision_variables: dictionary containing - mixing multipliers by age as a list if mode == "by_age" OR - locati...
81d2aeacdabeb20e2910e3cf42ece12e112e055b
3,639,865
def kick(code, input): """ kick <user> [reason] - Kicks a user from the current channel, with a reason if supplied. """ text = input.group(2).split() if len(text) == 1: target = input.group(2) reason = False else: target = text[0] reason = ' '.join(text[1::]) if not ...
59e8bc095076d9605aaa6b03363894c78d06b730
3,639,866
def check_invalid(string,*invalids,defaults=True): """Checks if input string matches an invalid value""" # Checks string against inputted invalid values for v in invalids: if string == v: return True # Checks string against default invalid values, if defaults=True if defaults ...
6e9e20beebe8e0b0baed680219fd93453d7f4ce3
3,639,867
def sse_content(response, handler, **sse_kwargs): """ Callback to collect the Server-Sent Events content of a response. Callbacks passed will receive event data. :param response: The response from the SSE request. :param handler: The handler for the SSE protocol. """ # An SS...
45e6a1fe058a78e28aeda9e9837a09dce6facd1a
3,639,868
def test_module(client: Client) -> str: """Tests API connectivity and authentication' Returning 'ok' indicates that the integration works like it is supposed to. Connection to the service is successful. Raises exceptions if something goes wrong. :type client: ``Client`` :param client: client t...
c672b29017d415bc3793d6561ed5cd40716c0745
3,639,869
def get_more_spec_pos(tokens): """Return frequencies for more specific POS""" # adverbs and preps, particles adverbs = [t for t in tokens if t.full_pos == 'ADV'] apprart = [t for t in tokens if t.full_pos == 'APPRART'] postpos = [t for t in tokens if t.full_pos == 'APPO'] circum_pos = [t fo...
5ea2ae19d61c84ca8750999aa14a14dd426fe6f7
3,639,870
def reconcile_suggest_property(prefix: str = ""): """Given a search prefix, return all the type/schema properties which match the given text. This is used to auto-complete property selection for detail filters in OpenRefine.""" matches = [] for prop in model.properties: if not prop.schema.is...
655796e8b00f8b36cae9b373e27f11077ccb49d4
3,639,871
def make_boxes(df_data, category, size_factor, x, y, height, width, pad=[1,1], main_cat=None): """Generates the coordinates for the boxes of the category""" totals = df_data[size_factor].groupby(df_data[category]).sum() box_list = totals.sort_values(ascending=False).to_frame() box_list.columns = ['valu...
a4bc28cf13a330863054fa3b5e514c50ba2c9e98
3,639,872
import types import joblib def hash_codeobj(code): """Return hashed version of a code object""" bytecode = code.co_code consts = code.co_consts consts = [hash_codeobj(c) if isinstance(c, types.CodeType) else c for c in consts] return joblib.hash((bytecode, consts))
43d0094ccb5345ca4f8b30b5fb03d167b8e21aa5
3,639,873
def us_census(): """Data Source for the US census. Arguments: None Returns: pandas.DataFrame """ df = us_census_connector() return us_census_formatter(df)
8aba9df470ab17a59437897a2e13a80be2b6e9d9
3,639,874
from pathlib import Path def get_notebook_path(same_config_path, same_config_file_contents) -> str: """Returns absolute value of the pipeline path relative to current file execution""" return str(Path.joinpath(Path(same_config_path).parent, same_config_file_contents["notebook"]["path"]))
4b9f8952bdb7c2308fdfa290ec108d432b6b6a0b
3,639,875
import re import glob def get_path_from_dependency( recipe_dependency_value: str, recipe_base_folder_path: str ) -> str: """ Searches the base folder for a file, that corresponse to the dependency passed. :param recipe_dependency_value: Value of the "From:" section from a ...
79de99c407998193e4ab6b3d760f894d3a5039ab
3,639,876
def about_us(): """ The about us page. """ return render_template( "basic/about_us.html", )
64d94e998855e7c99506ced7b48da36c5cbfa57a
3,639,877
import torch def sfb1d_atrous(lo, hi, g0, g1, mode='periodization', dim=-1, dilation=1, pad1=None, pad=None): """ 1D synthesis filter bank of an image tensor with no upsampling. Used for the stationary wavelet transform. """ C = lo.shape[1] d = dim % 4 # If g0, g1 are not tens...
c977115b311dbe67f0d72d2990fb3d9a9a206506
3,639,878
import torch def preprocess(image, size): """ pre-process images with Opencv format""" image = np.array(image) H, W, _ = image.shape image = nd.zoom(image.astype('float32'), (size / H, size / W, 1.0), order=1) image = image - mean_pixel image = image.transpose([2, 0, 1]) image = np.expand...
c2a928bbebf55587ff83347b572c7d73079cdbae
3,639,879
def delete_notebook(notebook_id: str) -> tuple[dict, int]: """Delete an existing notebook. The user can call this operation only for their own notebooks. This operation requires the following header with a fresh access token: "Authorization: Bearer fresh_access_token" Request parameters: ...
cf7a5074d9814024bc6ed8fa56a8157a0cc4290d
3,639,880
import time def log_time(logger): """ Decorator to log the execution time of a function """ def decorator(func): @wraps(func) def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() _log_time(lo...
a809eb70488338991636912b4eba33bf4aa93acc
3,639,881
import warnings def compute_avg_merge_candidate(catavg, v, intersection_idx): """ Given intersecting deltas in catavg and v, compute average delta one could merge into running average. If one cat is an outlier, picking that really distorts the vector we merge into running average vector. So, effe...
25c50ad0ad98e7a6951bd67cae8dc8fe6c78dbbb
3,639,882
def plot_annotations(img, bbox, labels, scores, confidence_threshold, save_fig_path='predicted_img.jpeg', show=False, save_fig=True): """ This function plots bounding boxes over image with text labels and saves the image to a particualr location. """ # Default colors and mappin...
f32afb61b9f43fe44b9e78896a51d67e52638eab
3,639,883
def get_registry_image_tag(app_name: str, image_tag: str, registry: dict) -> str: """Returns the image name for a given organization, app and tag""" return f"{registry['organization']}/{app_name}:{image_tag}"
16c71f99ff3a3c2514c24cb417b93f3b88f7cf42
3,639,884
import os import shutil def save_wind_generated_waves_to_subdirectory(args): """ Copy the wave height and wave period to the outputs/ directory. Inputs: args['wave_height'][sector]: uri to "sector"'s wave height data args['wave_period'][sector]: uri to "sector"'s wave period data ...
5b203f5237ebd9ac3fbddcecc5b9c609677eb5ae
3,639,885
def process_file(filename): """ Handle a single .fits file, returning the count of checksum and compliance errors. """ try: checksum_errors = verify_checksums(filename) if OPTIONS.compliance: compliance_errors = verify_compliance(filename) else: comp...
36f1723c67ab32a25cd7cba50b9989f00ea3e452
3,639,886
def numeric_summary(tensor): """Get a text summary of a numeric tensor. This summary is only available for numeric (int*, float*, complex*) and Boolean tensors. Args: tensor: (`numpy.ndarray`) the tensor value object to be summarized. Returns: The summary text as a `RichTextLines` object. If the ty...
8499bb79f1869474752cd59fbfdb9a5bc0a23c6a
3,639,887
def solveq(K, f, bcPrescr, bcVal=None): """ Solve static FE-equations considering boundary conditions. Parameters: K global stiffness matrix, dim(K)= nd x nd f global load vector, dim(f)= nd x 1 bcPrescr 1-dim integer array containing prescribed ...
45aedf376f6eb2bdc6ba2a4889628f2584d13db1
3,639,888
def get_output_names(hf): """ get_output_names(hf) Returns a list of the output variables names in the HDF5 file. Args: hf: An open HDF5 filehandle or a string containing the HDF5 filename to use. Returns: A sorted list of the output variable names in the HDF5 file. """ ...
6607197166c9a63d834398b188e996a811b081ce
3,639,889
from typing import Union from typing import Sequence from typing import Optional from typing import List from typing import Tuple from pathlib import Path from typing import Mapping from typing import Any def gene_trends( adata: AnnData, model: _input_model_type, genes: Union[str, Sequence[str]], line...
cda039d6e97d5853b48aaf144cdf4763adac05a8
3,639,890
def create_hostclass_snapshot_dict(snapshots): """ Create a dictionary of hostclass name to a list of snapshots for that hostclass :param list[Snapshot] snapshots: :return dict[str, list[Snapshot]]: """ snapshot_hostclass_dict = {} for snap in snapshots: # build a dict of hostclass+e...
dd568eaeb76fee96a876b5a57d963cd2fc8f870e
3,639,891
from datetime import datetime def refund_order(id): """ List all departments """ check_admin() order = Order.query.filter_by(id=id).first() payment_id = order.payment_id try: payment = Payment.find(payment_id) except ResourceNotFound: flash("Payment Not Found", "d...
d0de52c4f69cb933c4344e4f4534934709a9f7cb
3,639,892
def get_dprime_from_regions(*regions): """Get the full normalized linkage disequilibrium (D') matrix for n regions. This is a wrapper which determines the correct normalized linkage function to call based on the number of regions. Only two-dimensional normalized linkage matrices are currently suppo...
2676c4be712989bf7e1419bf19a83ddf84c0ffec
3,639,893
def get_nav_class_state(url, request, partial=False): """ Helper function that just returns the 'active'/'inactive' link class based on the passed url. """ if partial: _url = url_for( controller=request.environ['pylons.routes_dict']['controller'], action=None, id=...
1ec83fc46fa04868449d8ebaf611cee9ff88fcd5
3,639,894
import htcondor import os import unittest def needs_htcondor(test_item): """ Use a decorator before test classes or methods to only run them if the HTCondor Python bindings are installed. """ test_item = _mark_test('htcondor', test_item) try: htcondor.Collector(os.getenv('TOIL_HTCONDOR_COL...
de778dfde4362cdc9db402dc3c3fac50a6a59a9c
3,639,895
from typing import Tuple import torch from typing import List def tile_image( image: Image.Image, tile_size: Tuple[int, int], overlap: int ) -> Tuple[torch.Tensor, List[Tuple[int, int]]]: """Take in an image and tile it into smaller tiles for inference. Args: image: The input image to tile. ...
c5c9e09a5a95cdd63f8f2082e4c5a87e339f18ef
3,639,896
from datetime import datetime def parse(data): """ Parses the input of the Santander text file. The format of the bank statement is as follows: "From: <date> to <date>" "Account: <number>" "Date: <date>" "Description: <description>" "Amount: <amount>" "Balance...
267e1769553cebcd28f1c3190107712bebafb53a
3,639,897
def solve_duffing(tmax, dt_per_period, t_trans, x0, v0, gamma, delta, omega): """Solve the Duffing equation for parameters gamma, delta, omega. Find the numerical solution to the Duffing equation using a suitable time grid: tmax is the maximum time (s) to integrate to; t_trans is the initial time perio...
b1c246d3eb680852de60c7b9f0c55034d617e71a
3,639,898
def create_prog_assignment_registry(): """Create the registry for course properties.""" reg = FieldRegistry( 'Prog Assignment Entity', description='Prog Assignment', extra_schema_dict_values={ 'className': 'inputEx-Group new-form-layout'}) # Course level settings. course_op...
c2f17e812d30abe851ba9cfd18602ca458acec56
3,639,899