content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def register(*args, cache_default=True): """ Registers function for further caching its calls and restoring source. Example: ``` python @register def make_ohe_pclass(df): ... ``` """ def __register(func): # if source_utils.source_is_saved(func) and not source_ut...
41610d7f3463088f29125fe335a04b9b0292b74f
3,644,716
import re def make_absolute_paths(content): """Convert all MEDIA files into a file://URL paths in order to correctly get it displayed in PDFs.""" overrides = [ { 'root': settings.MEDIA_ROOT, 'url': settings.MEDIA_URL, }, { 'root': settings.STATIC...
4632513f73bf49ec6d1acfef15d632ee980ab345
3,644,717
def social_distancing_start_40(): """ Real Name: b'social distancing start 40' Original Eqn: b'31' Units: b'Day' Limits: (None, None) Type: constant b'' """ return 31
c874afed46a8303ec2d3ad0d571183ddc30059a0
3,644,718
def get_token_auth_header(params): """ Obtains the Access Token from the Authorization Header """ auth = get_token(params) parts = auth.split() if parts[0].lower() != "bearer": raise AuthError({"code": "invalid_header", "description": "Authorization header must start with Bearer"}, 401)...
c48a2306ea76b1b5f611194eb33fa13e40f0e155
3,644,720
from typing import Optional def check_hu(base: str, add: Optional[str] = None) -> str: """Check country specific VAT-Id""" weights = (9, 7, 3, 1, 9, 7, 3) s = sum(int(c) * w for (c, w) in zip(base, weights)) r = s % 10 if r == 0: return '0' else: return str(10 - r)
48f1043eeede4ea0b04eb71685f19901da495195
3,644,721
import requests from bs4 import BeautifulSoup def scrape_headline(news_link): """ function to scrape the headlines from a simple news website :return: a dictionary with key as html link of the source and value as the text in the headline of the news in the html link """ #Headli...
f87453a925ace26a3f848c0ed380b6e4ab7030a7
3,644,722
def read_xml(img_path): """Read bounding box from xml Args: img_path: path to image Return list of bounding boxes """ anno_path = '.'.join(img_path.split('.')[:-1]) + '.xml' tree = ET.ElementTree(file=anno_path) root = tree.getroot() ObjectSet = root.findall('object') bboxes ...
7102edccb5258d88b67476770123e54e1b75a5c1
3,644,723
def a2funcoff(*args): """a2funcoff(ea_t ea, char buf) -> char""" return _idaapi.a2funcoff(*args)
0cac71a4e071bf99bf6777fc35002e48099ecc46
3,644,724
def str(obj): """This function can be used as a default `__str__()` in user-defined classes. Classes using this should provide an `__info__()` method, otherwise the `default_info()` function defined in this module is used. """ info_func = getattr(type(obj), "__info__", default_info) return "{}(...
651e6f3e047a8f7583a39d337d202c09934bc37a
3,644,725
from typing import Union from typing import Optional from typing import Sequence from typing import Any def isin_strategy( pandera_dtype: Union[numpy_engine.DataType, pandas_engine.DataType], strategy: Optional[SearchStrategy] = None, *, allowed_values: Sequence[Any], ) -> SearchStrategy: """Strat...
aecf05b269b7f89b6fea0b5bfbbc98e51d4caddb
3,644,726
def arrToDict(arr): """ Turn an array into a dictionary where each value maps to '1' used for membership testing. """ return dict((x, 1) for x in arr)
3202aac9a6c091d7c98fd492489dbcf2300d3a02
3,644,727
def getPercentGC(img, nbpix) : """Determines if a page is in grayscale or colour mode.""" if img.mode != "RGB" : img = img.convert("RGB") gray = 0 for (r, g, b) in img.getdata() : if not (r == g == b) : # optimize : if a single pixel is no gray the whole page is color...
e8ee682889e0f9284cecfcf57cf260b7056c1879
3,644,728
import ctypes def rotate(angle: float, iaxis: int) -> ndarray: """ Calculate the 3x3 rotation matrix generated by a rotation of a specified angle about a specified axis. This rotation is thought of as rotating the coordinate system. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/rotate_...
035144bdf04b4c39cc4bf1e41ec02d4c71d4d951
3,644,729
def build_categories(semanticGroups): """ Returns a list of ontobio categories or None Parameters ---------- semanticGroups : string a space delimited collection of semanticGroups """ if semanticGroups is None: return None categories = [] for semanticGroup in semant...
5262b62cd5ce8e8c0864f91f43a0925ea991cc83
3,644,730
from x84.bbs import getterminal import time def show_nicks(handles): """ return terminal sequence for /users result. """ term = getterminal() return u''.join(( time.strftime('%H:%M'), u' ', term.blue('-'), u'!', term.blue('-'), u' ', term.bold_cyan('%d' % (len(handles))), u' ', ...
6863b7a67686a337304c9f22eb4bd9488f959a1f
3,644,731
def cvCmp(*args): """cvCmp(CvArr src1, CvArr src2, CvArr dst, int cmp_op)""" return _cv.cvCmp(*args)
ec2b9d8d68083fff3a09a5293e9950a2c67c424b
3,644,732
def convert_to_dtype(data, dtype): """ A utility function converting xarray, pandas, or NumPy data to a given dtype. Parameters ---------- data: xarray.Dataset, xarray.DataArray, pandas.Series, pandas.DataFrame, or numpy.ndarray dtype: str or numpy.dtype A string denoting a...
ec3130311fe9c136707d5afb8f564b4f89067f4e
3,644,733
def process_files(data_path, output_path): """Returns a pipeline which rebalances data shards. Args: data_path: File(s) to read. output_path: Path to which output CSVs are written, if necessary. """ def csv_pipeline(root): _ = ( root | beam.io.ReadFromText(data_path) | bea...
320a66857dfcfa43995226ee20f714f0694c8f8d
3,644,734
def delete_tasklog_cached(dc_id, user_id=None): """ Remove tasklog cache entry. """ if user_id: key = _cache_log_key(user_id, dc_id) else: key = _cache_log_key(settings.TASK_LOG_STAFF_ID, dc_id) return cache.delete(key)
29435d0618850a442a56d4d28e96be5989bca1f5
3,644,735
def strip_headers(data): """ Strips headers from data #depreciate""" try: return data['items'] except (TypeError, KeyError) as e: print(e) return data
2eb044e45043f103fff76bfa47007dbcd4aa49c7
3,644,736
def sns_plot(chart_type: str, df): """ return seaborn plots """ fig, ax = plt.subplots() if chart_type == "Scatter": with st.echo(): sns.scatterplot( data=df, x="bill_depth_mm", y="bill_length_mm", hue="species", ...
8081349e83745167443d76c9be30ee8b884e8d67
3,644,737
def decode_fields(source_str: str, resp_type): """ This is the lower level decode of fields, no automatic guess of type is performed.""" field_decoding = FIELD_MAPPING[resp_type] unpacked_fields = {} for field_name, field_type, field_subtype in field_decoding: search_term = f"{field_name}:".e...
6d1afebcfb377be0ce454f5a1db7b6aad37313c5
3,644,738
def make_egg(a=-1.25, b=7): """ Return x, y points that resemble an egg. Egg equation is: r = cos(2θ) + a * cos(θ) + b @param a: Number. @param b: Number. """ theta = np.linspace(0, 2 * np.pi, 100) r = np.cos(2 * theta) + a * np.cos(theta) + b y = r * np.cos(theta) x =...
b94ca316ba9e8bcfdcc3622205204e322c2bccb8
3,644,739
def test_styling_object_which_implements_str_proto(): """ Test styling an object which implements the str protocol """ class Dummy(object): def __str__(self): return 'I am a dummy object' colorful = core.Colorful(colormode=terminal.ANSI_8_COLORS) assert str(colorful.black(Du...
d14567675db25c66bdc00e28904b721bb3af536d
3,644,740
def determine_auto_approval(financial_aid, tier_program): """ Takes income and country code and returns a boolean if auto-approved. Logs an error if the country of financial_aid does not exist in CountryIncomeThreshold. Args: financial_aid (FinancialAid): the financial aid object to determine au...
280af275564046ed36b8b5442879f8dcc7e515cb
3,644,741
def crustal_model_files(alt = [200, 1000], anomaly = 'Global', lim = [0., 360. -90., 90.], binsize = 0.1): """" Reads the .bin IDL files of the crustal magnetic field model (Langlais) for a range of altitudes and creates a function based on a linear interpolation. Parameters: alt: 2-elements ar...
e5deb36b571c0cc75e738bd0bdce7a2fa6ea8d7a
3,644,742
def f1(y_true, y_pred): """ Function for computing the unweighted f1 score using tensors. The Function handles only the binary case and compute the unweighted f1 score for the positive class only. Args: - y_true: keras tensor, ground truth labels - y_pred: keras tensord, labels esti...
793fbcbd2ddcec2608139174794e94304f69a631
3,644,743
def get_selector_score(key, selector, use_median, best_based_on_final): """ :param key: Thing to measure (e.g. Average Returns, Loss, etc.) :param selector: Selector instance :param use_median: Use the median? Else use the mean :param best_based_on_final: Only look at the final value? Else use all ...
4c9d2e08fcc4f4ee3ecbd2cf67e4db829850707a
3,644,744
import pytz def str_to_timezone(tz): """ 从字符串构建时区 """ return pytz.timezone(tz) if tz else pytz.utc
02c004171f50ceb4b60272769036634f6778c791
3,644,745
def _get_previous_index_search_col( m, col, nested_list, trans_function=None, transformation=False ): """Return previous index of a a key, from a sorted nested list where a key is being seached in the col number.Returns -1 if value is not found. Args: m (comparable): comparable being searched ...
4545395928128ce2858c1d0508e77a47be543dd7
3,644,746
import json def guest_import(hypervisor, host): """ Import a new guest :: POST /:hypervisor/:host/guests """ response.content_type = "application/json" manager = create_manager(hypervisor, host) guest = manager.guest_import( request.environ['wsgi.input'], request.c...
d26ecbac6bce0ab07c365aabb8352ec57719798d
3,644,747
from typing import List def get_doc_count( group_by: List[str] = ["year", "country"], sort_by: List[metadata.SortOn] = [ metadata.SortOn(field="year", order=metadata.SortOrder.desc), metadata.SortOn(field="count", order=metadata.SortOrder.desc)], limit: int = 10): "...
c815d6d9a2746c61d3affbca07e8334c75862030
3,644,748
import re def get_author_list(text): """function to extract authors from some text that will also include associations example input: `J. C. Jan†, F. Y. Lin, Y. L. Chu, C. Y. Kuo, C. C. Chang, J. C. Huang and C. S. Hwang, National Synchrotron Radiation Research Center, Hsinchu, Taiwan, R.O.C` o...
94b7f74ed24be8bb8bbfacca37dfc9f65f1fc99b
3,644,749
def find_matching_format_function(word_with_formatting, format_functions): """ Finds the formatter function from a list of formatter functions which transforms a word into itself. Returns an identity function if none exists """ for formatter in format_functions: formatted_word = formatter(word_with...
3d2ce0956de4c8ca0de6d0d21f8bbd718247caff
3,644,750
from typing import List def mean (inlist:List(float))->float: """ Returns the arithematic mean of the values in the passed list. Assumes a '1D' list, but will function on the 1st dim of an array(!). Usage: lmean(inlist) """ sum = 0 for item in inlist: sum = sum + item return sum/float(len(i...
713bbbec706671043a5b76f142d4f19cfa247c6a
3,644,751
def create_file_download_url(file_path: str) -> str: """ Creates Telegram URL for downloading of file. - contains secret information (bot token)! :param file_path: `file_path` property of `File` object. """ token = environ["TELEGRAM_API_BOT_TOKEN"] return create_url( "https://api....
6395d17520778d6bf4507ba69559b6ef1ba32ba9
3,644,752
import csv from datetime import datetime def convert_to_csv(items): """ Args: items: all arns in a region from the DynamoDB query as a list returns: csv_body: body of the csv file to write out """ fieldnames = ["Package", "Package Version", "Status", "Expiry Date", "Arn"] # sort ...
6e651065f06595e9b964bee1b8dab2965e0076f6
3,644,753
def manhattan(train_X, val_X): """ :param train_X: one record from the training set (type series or dataframe including target (survived)) :param val_X: one record from the validation set series or dataframe include target (survived) :return: the Manhattan distanc...
1989466af70d38a17c2b52dd667733da46bbed0c
3,644,754
def author_idea_list(request, registrant_id): """ Returns author ideas """ registrant = get_object_or_404(Registrant, pk=registrant_id) ideas = Idea.objects.filter(author=registrant) serializer = IdeaSerializer(ideas, many=True) return Response(serializer.data, status=status.HTTP_200_OK)
64ee16535243bfe5414326bed86f5b9efdb97941
3,644,755
import re def match(text: str, pattern: str) -> bool: """ Match a text against a given regular expression. :param text: string to examine. :param pattern: regular expression. :returns: ``True`` if pattern matches the string. """ return re.match(pattern, text) is not None
a59d71283766c5079e8151e8be49501246218001
3,644,756
def _compute_hash_check(input_strings: tf.Tensor, field_size: int, seed: int, dtype: tf.dtypes.DType) -> tf.Tensor: """Returns the hash_check for input_strings modulo field_size.""" hash_check_salt = _get_hash_check_salt(seed) salted_input = tf.strings.join([hash_check_salt, input_strings]...
bff5d9b24f17fd32ea3a5bfbd60a8446f10471aa
3,644,757
import numpy def calc_extinction(radius:float, mosaicity:float, model:str, a:float, b:float, c:float, alpha:float, beta:float, gamma:float, h:float, k:float, l:float, f_sq:float, wavelength:float, flag_derivative_f_sq=False): """ Isotropical extinct...
b0922fde0246ee250033d9ff9eb3fde59c17c343
3,644,759
def smape(y_true: Yannotation, y_pred: Yannotation): """ Calculate the symmetric mean absolute percentage error between `y_true`and `y_pred`. Parameters ---------- y_true : array, `dataframe`, list or `tensor` Ground truth values. shape = `[batch_size, d0, .. dN]`. y_pred : array, `data...
0046481ea6b2ddc3295f9d597d6cc3488b498415
3,644,760
def acosh(rasters, extent_type="FirstOf", cellsize_type="FirstOf", astype=None): """ The ACosH operation The arguments for this function are as follows: :param rasters: array of rasters. If a scalar is needed for the operation, the scalar can be a double or string :param extent_type: one of "First...
593b13639f40c347a27d4fc772d7b2ec2d062a86
3,644,761
from typing import Optional from typing import Dict from typing import Tuple from typing import Any def load_does( filepath: PathType, defaults: Optional[Dict[str, bool]] = None ) -> Tuple[Any, Any]: """Load_does from file.""" does = {} defaults = defaults or {"do_permutation": True, "settings": {}} ...
22cebd75da899bebb092c1c470eabe87e17c41f5
3,644,762
def causal_segment_mask(segment_ids: JTensor, dtype: jnp.dtype = jnp.float32) -> JTensor: """Computes the masks which combines causal masking and segment masks. Args: segment_ids: a JTensor of shape [B, T], the segment that each token belongs to. dtype: data type of the input....
7e16f2a943e19b232fb3f1e55f7b348aa7f56a72
3,644,763
def remove_outliers(peaks: np.ndarray, **kwargs): """ https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.LocalOutlierFactor.html#sklearn.neighbors.LocalOutlierFactor https://scikit-learn.org/stable/modules/outlier_detection.html Parameters ---------- peaks kwargs Retur...
969fe4523e8529edd49a5c0cd81c51949bbe3de5
3,644,764
def powerset(iterable): """ Calcualtes the powerset, copied from https://docs.python.org/3/library/itertools.html#itertools-recipes """ "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" s = list(iterable) return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
3b645848c0810c69685c06b94fee42e5747bb6e8
3,644,765
def get_rotational_vector(skew_symmetric): """Get the rotational vector from a skew symmetric matrix. Parameters ---------- skew_symmetric: numpy.ndarray the skew symmetric matrix. Returns ------- rotational_vector: the rotational vector. """ # make sure that the ...
e63b771f6db93f63d7307a85689d87162208c6ff
3,644,766
def diaperchange_lifetimes(changes): """ Create a graph showing how long diapers last (time between changes). :param changes: a QuerySet of Diaper Change instances. :returns: a tuple of the the graph's html and javascript. """ changes = changes.order_by("time") durations = [] last_change...
4937cff711b8e37e4162a4c7de8cc258c25d2979
3,644,767
def batch_norm_conv(x, n_out, phase_train, scope='bn'): """ Batch normalization on convolutional maps. Args: x: Tensor, 4D BHWD input maps n_out: integer, depth of input maps phase_train: boolean tf.Varialbe, true indicates training phase scope: string, ...
2a08db220f08270a8f2870671ee93278f0c7ddd2
3,644,768
def strip_variants(address): """Return a copy of the given address with the variants (if any) stripped from the name. :rtype: :class:`pants.build_graph.address.Address` """ address, _ = parse_variants(address) return address
a2cc1c68b6032304720b9cae05516535cb9ede22
3,644,769
def deleteIdentifiedStock(bot, update): """Deletes the user's selected stock. If the user's selected stock is valid, proceed to delete it. Returns: Return MENU state with normal keyboard. """ if update.message.chat.username is None: # User has no username update.mess...
7a47579f7e0b9b9388ef0f0f4650cb045cf53570
3,644,770
def z_inc_down(grid): """Return True if z increases downwards in the coordinate reference system used by the grid geometry :meta common: """ if grid.crs is None: assert grid.crs_uuid is not None grid.crs = rqc.Crs(grid.model, uuid = grid.crs_uuid) return grid.crs.z_inc_down
26b05defc1b75ec5a4f3aa9f61c3ba0cb5921bdc
3,644,771
def load_coord_var(prob_data_type): """ Loads a coordinate variable from the source data and returns it. :param prob_data_type: :return: """ fpath = "{}/source_others/a1b_tas_jja_EAW_1961-1990.dat".format(BASEDIR) with open(fpath, 'rb') as reader: data = cPickle.load(reader) k...
46969ac762393c8b7c60d08b543a2fc2f0069b74
3,644,772
import platform def get_os(): """Get the current operating system. :returns: The OS platform (str). """ return platform.system()
307c6c94573733d900b2e31cfc8bcf3db8b6e5b7
3,644,773
def count_hits(space, positions, pi_plus_4_vecs_lab, pi_null_4_vecs_lab, r): """returns a list of hit counts for z values in space""" return [count_double_hits(positions, pi_plus_4_vecs_lab, pi_null_4_vecs_lab, r=r, z_detector=z) for z in space]
66ba0f61d8491ef6687c0fb20761375c6470cae2
3,644,775
import time import math def time_since(since, m_padding=2, s_padding=2): """Elapsed time since last record point.""" now = time.time() s = now - since m = math.floor(s / 60) s -= m * 60 return '{}m:{}s'.format(str(int(m)).zfill(m_padding), str(int(s)).zfill(s_paddin...
62641b723bf286f54280bb5c6fb1d54c9753907c
3,644,776
def record_check(record): """ record dict check --- a dictionary is required as the input --- """ assert isinstance( record, dict), 'record should be dict, while the input is {}'.format(type(record)) cnn_json_struct = JsonFormatSetting.CNN_JSON_STRUCTURE record_struct = cnn_json_stru...
965cced685b45de8083dc1c8e161e9aa100b4cf0
3,644,778
import struct def encrypt_chunk(chunk, password=None): """Encrypts the given chunk of data and returns the encrypted chunk. If password is None then saq.ENCRYPTION_PASSWORD is used instead. password must be a byte string 32 bytes in length.""" if password is None: password = saq.ENCRYPT...
328484205dff850f3857f0a7d19e922ffa230c61
3,644,779
def convert_to_pj_lop_plus(lops): """ Converts the list of PlayerStates to an LOP+ :param lops: The PlayerStates to be converted :type lops: [PlayerState, ...] :return: The LOP+ :rtype: PyJSON """ return [convert_to_pj_player_plus(ps) for ps in lops]
968e0a38b5df2a1ce4bf6106632c31213d278a29
3,644,780
from typing import Tuple import math def euler_to_quaternion(roll: float = 0, pitch: float = 0, yaw: float = 0) -> Tuple[float, float, float, float]: """ Convert Euler to Quaternion Args: roll (float): roll angle in radian (x-axis) pitch (float): pitch angle in radian (y-axis) yaw...
e8346172f07510c377e14827842eb18f1631402e
3,644,781
def create_generic_constant(type_spec, scalar_value): """Creates constant for a combination of federated, tuple and tensor types. Args: type_spec: Instance of `computation_types.Type` containing only federated, tuple or tensor types for which we wish to construct a generic constant. May also be som...
9e1db57d93407eef385c1ac88ba83a4e578f891a
3,644,783
from django_openid.models import UserOpenidAssociation def has_openid(request): """ Given a HttpRequest determine whether the OpenID on it is associated thus allowing caller to know whether OpenID is good to depend on. """ for association in UserOpenidAssociation.objects.filter(user=request.user):...
ad193ae3c299867ed4c29ee059c45fe24a07523c
3,644,784
def get_wordcloud(): """ Generates the wordcloud and sends it to the front end as a png file. :return: generated tag_cloud.png file """ update_tagcloud(path_to_save='storage/tmp', solr_service=solr) return send_from_directory("storage/tmp", "tag_cloud.png", as_attachment=True)
c40cbf95676ac1b3da9c589934bb67a589a80810
3,644,785
def rtc_runner(rtc): """ :type rtc: pbcommand.models.ResolvedToolContract :return: """ return gather_run_main(chunk_json=rtc.task.input_files[0], chunk_key=Constants.CHUNK_KEY, gathered_fn=rtc.task.output_files[0], ln_n...
10aa9c707284a04a0d002b95169d0a28e91213eb
3,644,786
from typing import Tuple def get_matching_axis(shape: Tuple, length: int) -> int: """ Infers the correct axis to use :param shape: the shape of the input :param length: the desired length of the axis :return: the correct axis. If multiple axes match, then it returns the last one...
981e2bb2487cd113ffc5dd19c2a62d581cf38304
3,644,787
def is_paths(maybe_paths, marker='*'): """ Does given object `maybe_paths` consist of path or path pattern strings? """ return ((is_path(maybe_paths) and marker in maybe_paths) or # Path str (is_path_obj(maybe_paths) and marker in maybe_paths.as_posix()) or (is_iterable(maybe_pa...
dc825d7417cb7cb52beaecc4fb6eef333db1514b
3,644,788
import logging def output_numpy_or_asa(obj, data, *, output_type=None, labels=None): """This function returns a numpy ndarray or nelpy.AnalogSignalArray Parameters ---------- obj : numpy.ndarray or a nelpy object data : numpy.ndarray, with shape (n_samples, n_signals) Data is either passe...
2e19de7caa58d4be606fa3c2fef623c32a08a201
3,644,789
def embed_oar(features: Array, action: Array, reward: Array, num_actions: int) -> Array: """Embed each of the (observation, action, reward) inputs & concatenate.""" chex.assert_rank([features, action, reward], [2, 1, 1]) action = jax.nn.one_hot(action, num_classes=num_actions) # [B, A] reward = ...
624b1ca67fa031e548411b4c9cfd9f86765cbd7e
3,644,790
import requests import json def aggregations_terms(query=None): """Get page for aggregations.""" if query is None: # Default query query = "state,config.instance_type" # Remove all white spaces from the str query = query.replace(" ", "") data = {"query": query} end_point = "a...
c69308a007ec4b366129de3c3aa277c96fda2edd
3,644,792
import tqdm import torch def validate_base(model, args, loader, loadername, train=True): """ The validation function. Validates the ELBO + MIL, ELBO, and the accuracy of the given [training, validation or test] loader. Returns ...
85c9558bd484190eb61599509b9c9ec9f4a5cc0a
3,644,793
def parse_person(person): """ https://doc.rust-lang.org/cargo/reference/manifest.html#the-authors-field-optional A "person" is an object with an optional "name" or "email" field. A person can be in the form: "author": "Isaac Z. Schlueter <i@izs.me>" For example: >>> p = parse_person('Bar...
3fe30bf85f3ba4877b2924c5b5778d5a5205b6ee
3,644,794
def _glasstone_surface_cf(y): """Correction factor provided by TEoNW for contact surface bursts (p. 335).""" return np.interp(y, [1.0, 50.0, 100.0, 300.0, 700.0, 2000.0, 5000.0, 5000.0], [0.6666666666666666, 0.6666666666666666, 1.0, 1.25, 1.5, 2.0, 3.0, 3.0])
8ac3b0273e8c8fe218d15a2b89aad994a7413d68
3,644,795
import torch def create_eval_fn(task_id, calculate_gradient=False): """Creates an evaluation function for a given task. Returns an evaluation function that takes in a model, dataloader, and device, and evaluates the model on the data from the dataloader. Returns a dictionary with mean "loss" and "accu...
ac0a7107f695170f2fa6c65dfeae63056b53452d
3,644,796
def naming_style(f): """Decorator for name utility functions. Wraps a name utility function in a function that takes one or more names, splits them into a list of words, and passes the list to the utility function. """ def inner(name_or_names): names = name_or_names if isinstance(name_or_na...
bbcb1b0b06bbb7a24abe60131a9a5ba525ed01db
3,644,798
def is_idaq(*args): """ is_idaq() -> bool Returns True or False depending if IDAPython is hosted by IDAQ """ return _ida_kernwin.is_idaq(*args)
5d18067b31be9c165a847815eb0bab92f89b0381
3,644,801
import requests import yaml def get_stats_yaml(): """grab national stats yaml from scorecard repo""" nat_dict = {} try: nat_yaml = requests.get(COLLEGE_CHOICE_NATIONAL_DATA_URL) if nat_yaml.ok and nat_yaml.text: nat_dict = yaml.safe_load(nat_yaml.text) except AttributeError...
045eeba3bfc42fa9e1821728260fd4d33e216731
3,644,802
def get_original(N: int = 64) -> np.ndarray: """radontea logo base image""" x = np.linspace(-N / 2, N / 2, N, endpoint=False) X = x.reshape(1, -1) Y = x.reshape(-1, 1) z = logo(X, Y, N) return np.array((z) * 255, dtype=np.uint16)
2bab08961d444f6ecfa097258872d02ae185944b
3,644,805
from typing import List def get_sql_update_by_ids(table: str, columns: List[str], ids_length: int): """ 获取添加数据的字符串 :param table: :param columns: :param ids_length: :return: """ # 校验数据 if not table: raise ParamError(f"table 参数错误:table={table}") if not columns or not isin...
ac70aa43aea4fad06ac2fd521239687040143b28
3,644,806
import random import sympy def add_X_to_both_sides(latex_dict: dict) -> str: """ https://docs.sympy.org/latest/gotchas.html#double-equals-signs https://stackoverflow.com/questions/37112738/sympy-comparing-expressions Given a = b add c to both sides get a + c = b + c >>> latex_dict = {} ...
2ab0af9acbb09dcace00575a58afb66cebf2a07c
3,644,808
def init_var_dict(init_args, var_list): """Init var with different methods. """ var_map = {} _, max_val = init_args for i, _ in enumerate(var_list): key, shape, method = var_list[i] if key not in var_map.keys(): if method in ['random', 'uniform']: var_map[...
05a3bece9598426010466c27ce794eb7d2aea937
3,644,809
import warnings def _eval_bernstein_1d(x, fvals, method="binom"): """Evaluate 1-dimensional bernstein polynomial given grid of values. experimental, comparing methods Parameters ---------- x : array_like Values at which to evaluate the Bernstein polynomial. fvals : ndarray Gr...
5561d4099bd07b0fc75dcbf47c53f5ff589e2d9d
3,644,812
def exp_bar(self, user, size=20): """\ Returns a string visualizing the current exp of the user as a bar. """ bar_length = user.exp * size // exp_next_lvl(user.lvl) space_length = size - bar_length bar = '#' * bar_length + '.' * space_length return '[' + bar + ']'
575d475d602d0fdd4ded9eb2a139484c5d78887e
3,644,813
def linear(input_, output_size, scope=None, stddev=0.02, with_w=False): """Define lienar activation function used for fc layer. Args: input_: An input tensor for activation function. output_dim: A output tensor size after passing through linearity. scope: variable scope, if None...
8a5a4b06598d9c3c799c4a82d07a9d3d11962f23
3,644,814
from pathlib import Path import json import hashlib import math def generate_patches(patch_cache_location, axis, image_input_channels, brain_mask_channel, classification_mask, patch_size, k_fo...
d8dc0d1312acff05bfdbc56192ee3c7caeb65c86
3,644,815
from typing import Union from typing import Sequence from typing import List def query_user_joins(user_group: Union[User, Sequence[User], None]) \ -> List[JoinRecord]: """ :param user_group: User or user group as an iterable of users. :return: """ # Input validation user_list = [user_g...
5481e4512b7b28b0832f9fec00ef0cf4e7cfd5de
3,644,817
def rec_test(test_type: str): """ Rec test decorator """ def decorator(f): @wraps(f) def w(*args, **kwargs): return f(*args, **kwargs) # add attributes to f w.is_test = True w.test_type = test_type try: w.test_desc = f.__doc__.lstr...
94eca60bd4d3f96fd3346da5bcc2b70c3a167ace
3,644,819
def display_convw(w, s, r, c, fig, vmax=None, vmin=None, dataset='mnist', title='conv_filters'): """ w2 = np.zeros(w.shape) d = w.shape[1]/3 print w.shape for i in range(w.shape[0]): for j in range(w.shape[1]/3): w2[i, j] = w[i, 3*j] w2[i, j + d] = w[i, 3*j+1] w2[i, j + 2*d] = w[i, 3*j+...
87742ea0831f731e800385134379ce1b786b834f
3,644,820
def get_optional_list(all_tasks=ALL_TASKS, grade=-1, *keys) -> list: """获取可选的任务列表 :param keys: 缩小范围的关键字,不定长,定位第一级有一个键,要定位到第二级就应该有两个键 :param all_tasks: dict,两级, 所有的任务 :param grade: 字典层级 第0层即为最外层,依次向内层嵌套,默认值-1层获取所有最内层的汇总列表 :return: """ optional_list = [] # 按照指定层级获取相应的可选任务列表 if grade ...
ee54e65e724520d8ed9e3d994811c26ed2205add
3,644,821
def process_genotypes(filepath, snp_maf, snp_list=None, **kwargs): """ Process genotype file. :param filepath: :param snp_maf: :param snp_list: get specified snp if provided :param bool genotype_label: True if first column is the label of specimen, default False :param bool skip_none_rs: Tr...
501aa7b648d970b21dff1a4bd98102680e5ea774
3,644,822
def table_exists(conn, table_name, schema=False): """Checks if a table exists. Parameters ---------- conn A Psycopg2 connection. table_name : str The table name. schema : str The schema to which the table belongs. """ cur = conn.cursor() table_exists_sql =...
c9b698afbe795a6a73ddfb87b2725c3c4205f35e
3,644,824
import re def _dict_from_dir(previous_run_path): """ build dictionary that maps training set durations to a list of training subset csv paths, ordered by replicate number factored out as helper function so we can test this works correctly Parameters ---------- previous_run_path : str, Pa...
32d49b6ec6a8472a3864fc95cc52502a63038cdc
3,644,825
def aggregate_pixel(arr,x_step,y_step): """Aggregation code for a single pixel""" # Set x/y to zero to mimic the setting in a loop # Assumes x_step and y_step in an array-type of length 2 x = 0 y = 0 # initialize sum variable s = 0.0 # sum center pixels left = int(ceil(x_step[x]))...
d9cdad36c7eeff3581310d13bedce204e7431560
3,644,826
def simplify_datatype(config): """ Converts ndarray to list, useful for saving config as a yaml file """ for k, v in config.items(): if isinstance(v, dict): config[k] = simplify_datatype(v) elif isinstance(v, tuple): config[k] = list(v) elif isinstance(v, np.ndarr...
f3e8ae76e04479ed9b1b5fbd450edec20342e5a9
3,644,827
def _strict_random_crop_image(image, boxes, labels, is_crowd, difficult, masks=None, sem_seg=None, min_object_...
749107213a8bf34d2b159d38657a9c63af6699c3
3,644,828
def aggregate_by_player_id(statistics, playerid, fields): """ Inputs: statistics - List of batting statistics dictionaries playerid - Player ID field name fields - List of fields to aggregate Output: Returns a nested dictionary whose keys are player IDs and whose values a...
c137fc8820f8898ebc63c54de03be5b919fed97a
3,644,829
import pickle def loadStatesFromFile(filename): """Loads a list of states from a file.""" try: with open(filename, 'rb') as inputfile: result = pickle.load(inputfile) except: result = [] return result
cc2f64a977ff030ec6af94d3601c094e14f5b584
3,644,830
import tkinter def get_configuration_item(configuration_file, item, default_values): """Return configuration value on file for item or builtin default. configuration_file Name of configuration file. item Item in configuation file whose value is required. default_values dict of...
c077989d2d90468a80b27f32a68b827fbdb49b92
3,644,831
def sexa2deg(ra, dec): """Convert sexagesimal to degree; taken from ryan's code""" ra = coordinates.Angle(ra, units.hour).degree dec = coordinates.Angle(dec, units.degree).degree return ra, dec
3a016b1163c6ceda403cfe5c8d24467d1646c7aa
3,644,833