content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def geopad(lon, lat, data, /, nlon=1, nlat=0): """ Return array padded circularly along longitude and over the poles for finite difference methods. """ # Pad over longitude seams if nlon > 0: pad = ((nlon, nlon),) + (data.ndim - 1) * ((0, 0),) data = np.pad(data, pad, mode='wrap'...
8916dde690673b1d278ffab39ee3350f346a4182
3,658,607
def SL_EAKF(N,loc_rad,taper='GC',ordr='rand',infl=1.0,rot=False,**kwargs): """ Serial, covariance-localized EAKF. Ref: Karspeck, Alicia R., and Jeffrey L. Anderson. (2007): "Experimental implementation of an ensemble adjustment filter..." Used without localization, this should be equivalent (full ensemble...
e7ca69f71cf83a4389086d14791902eb5a661b9e
3,658,608
def CalculateNMaxNCharge(mol): """ ################################################################# Most negative charge on N atoms -->QNmin Usage: result=CalculateNMaxNCharge(mol) Input: mol is a molecule object. Output: result is a numeric value. #...
ae63c3f2c6faa8b0d9f7d6ae3b320a9c3b1002d6
3,658,609
def cnn_5l4(image, **kwargs): """ :param in: (TensorFlow Tensor) Image input placeholder :param kwargs: (dict) Extra keywords parameters for the convolutional layers of the CNN :return: (TensorFlow Tensor) The CNN output layer """ activ = tf.nn.relu layer_1 = activ(conv(image, 'c1', n_filter...
af059b9a2899c1adcc9f11f4742ffaac8a971dba
3,658,610
def read_dns_data(dns_fn): """ Read data in from a DNS file :param str dns_fn: The filename of the DNS """ fed = open(dns_fn, 'r') begin_data = False dns_data = {} for line in fed.readlines(): if begin_data: if "t = " in line: ...
2c73289c6284b47901a8f7c91bce6df75849c822
3,658,611
def arithmetic_mean(iterable): """Zero-length-safe arithmetic mean.""" values = np.asarray(iterable) if not values.size: return 0 return values.mean()
3972885d92654d842a163d64c47b585ad6865c98
3,658,612
def play_process(url): """ Create and return process to read audio from url and send to analog output""" return FfmpegProcess(f'ffmpeg -i {url} -f alsa default')
2246f9385e48dda9398752ecd9fa70914d17c55f
3,658,613
from typing import Iterable def iterable_to_wikitext( items: Iterable[object], *, prefix: str = "\n* " ) -> str: """ Convert iterable to wikitext. Pages are converted to links. All other objects use their string representation. :param items: Items to iterate :param prefix: Prefix for eac...
775bed839d890ab40aeace76a82f881e076cafa2
3,658,614
def plot_timeSeries(df, col_name, divide=None, xlabel="Days", line=True, title="Time series values", figsize=(9,9)): """ Plot a column of the given time series DataFrame. Parameters ---------- df: pd.DataFrame DataFrame indexed by days (i.e. the index is a pd.DatetimeIndex). col_name: s...
279f74422ae6b186128347cc971a094c13f22c4b
3,658,615
def is_bv(a): """Return `True` if `a` is a Z3 bit-vector expression. >>> b = BitVec('b', 32) >>> is_bv(b) True >>> is_bv(b + 10) True >>> is_bv(Int('x')) False """ return isinstance(a, BitVecRef)
7c1cd1d3d679cdceb12955e61f54861b248ff4a2
3,658,617
def bgsub_1D(raw_data, energy_axis, edge, **kwargs): """ Full background subtraction function for the 1D case- Optional LBA, log fitting, LCPL, and exponential fitting. For more information on non-linear fitting function, see information at https://docs.scipy.org/doc/scipy/reference/generated/scipy.opti...
a3f273e55f49811ce9af4ee5c23d4078fe83535a
3,658,618
import random def about_garble(): """ about_garble Returns one of several strings for the about page """ garble = ["leverage agile frameworks to provide a robust synopsis for high level overviews.", "iterate approaches to corporate strategy and foster collaborative thinking t...
c391891f97a7bc6df5287173aa160713cdfff675
3,658,619
def parse_term_5_elems(expr_list, idx): """ Try to parse a terminal node from five elements of {expr_list}, starting from {idx}. Return the new expression list on success, None on error. """ # The only 3 items node is pk_h if expr_list[idx : idx + 2] != [OP_DUP, OP_HASH160]: return ...
8c0c365483c44a767b3e254f957af175125da2d6
3,658,620
def display_clusters(): """ Method to display the clusters """ offset = int(request.args.get('offset', '0')) limit = int(request.args.get('limit', '50')) clusters_id_sorted = sorted(clusters, key=lambda x : -len(clusters[x])) batches = chunks(range(len(clusters_id_sorted)), size=limit) r...
e3d578cff54e66ee4b096bcf1e7181a3bac1c845
3,658,621
def densify_sampled_item_predictions(tf_sample_predictions_serial, tf_n_sampled_items, tf_n_users): """ Turns the serial predictions of the sample items in to a dense matrix of shape [ n_users, n_sampled_items ] :param tf_sample_predictions_serial: :param tf_n_sampled_items: :param tf_n_users: :...
e1dbe0e74c791e1d9b7613fbe52b034a60376497
3,658,622
def get_market_book(symbols=None, **kwargs): """ Top-level function to obtain Book data for a symbol or list of symbols Parameters ---------- symbols: str or list, default None A symbol or list of symbols kwargs: Additional Request Parameters (see base class) """ return ...
8b1bc8ed07a611cef490f616996aae05ce445ff1
3,658,623
def ndarange(*args, shape: tuple = None, **kwargs): """Generate arange arrays of arbitrary dimensions.""" arr = np.array([np.arange(*args[i], **kwargs) for i in range(len(args))]) return arr.reshape(shape) if shape is not None else arr.T
42a5070e653386a71a9be7949f5e9341bfbc50c9
3,658,624
def runningSum(self, nums): """ :type nums: List[int] :rtype: List[int] 5% faster 100% less memory """ sum = 0 runningSum = [0] * len(nums) for i in range(len(nums)): for j in range(i+1): runningSum[i] += nums[j] return runningSum
393849c4aa1d23b15717748066e21abceaf6d5d9
3,658,625
def edit_recovery(request, recovery_id): """This view is used to edit/update existing tag recoveries.""" clip_codes = sorted(list(CLIP_CODE_CHOICES), key=lambda x: x[0]) tag_types = sorted(list(TAG_TYPE_CHOICES), key=lambda x: x[0]) tag_origin = sorted(list(TAG_ORIGIN_CHOICES), key=lambda x: x[0]) ...
f9da1a4377efd436e93cf2be0af2c2e09cc3e31d
3,658,628
def e(string, *args): """Function which formats error messages.""" return string.format(*[pformat(arg) for arg in args])
8734d01544211fde3f8ee24f0f91dc06763d4a1f
3,658,629
def membership_ending_task(user): """ :return: Next task that will end the membership of the user """ task = (UserTask.q .filter_by(user_id=user.id, status=TaskStatus.OPEN, type=TaskType.USER_MOVE_OUT) # Casting jsonb -> bool directl...
2043c87eaabbf3360f1bec331a03e1c7db8bc783
3,658,630
import warnings def hmsstr_to_rad(hmsstr): """Convert HH:MM:SS.SS sexigesimal string to radians. """ hmsstr = np.atleast_1d(hmsstr) hours = np.zeros(hmsstr.size) for i,s in enumerate(hmsstr): # parse string using regular expressions match = hms_re.match(s) if match is None...
e57266c43e3b0f8893f9c71cfbea609cf7c93709
3,658,631
def find_optimum_transformations(init_trans, s_pts, t_pts, template_spacing, e_func, temp_tree, errfunc): """ Vary the initial transformation by a translation of up to three times the grid spacing and compute the transformation with the smallest least square error. ...
bbc4786827c22158eee33ff9a5e4aaa2939b9705
3,658,632
def execute_transaction(query): """Execute Transaction""" return Neo4jHelper.run_single_query(query)
51e8e58bb4cad30b9ae9c7b7d7901ee212c9d26a
3,658,633
from scipy.linalg import null_space from angle_set import create_theta, get_n_linear, perturbe_points def generate_linear_constraints(points, verbose=False): """ Given point coordinates, generate angle constraints. """ N, d = points.shape num_samples = get_n_linear(N) * 2 if verbose: print('...
b98354cd6b57d7a33c6e8a43da80b358e358138c
3,658,634
def add_node_to_parent(node, parent_node): """ Add given object under the given parent preserving its local transformations :param node: str :param parent_node: str """ return maya.cmds.parent(node, parent_node, add=True, s=True)
1f264b7e30c6ebc2285faa987ffc6142ec62d87f
3,658,635
def coerce(from_, to, **to_kwargs): """ A preprocessing decorator that coerces inputs of a given type by passing them to a callable. Parameters ---------- from : type or tuple or types Inputs types on which to call ``to``. to : function Coercion function to call on inputs. ...
61ccce8b9ffbec3e76aa9e78face469add28437e
3,658,636
def Binary(value): """construct an object capable of holding a binary (long) string value.""" return value
2a33d858b23ac2d72e17ea8ede294c5311cb74be
3,658,638
def _get_domain_session(token, domain_name=None): """ Return v3 session for token """ domain_name = domain_name or 'default' auth = v3.Token(auth_url=get_auth_url(), domain_id=domain_name, token=token) return session.Session(auth=auth, user_agent=USER_AGEN...
1ad7dcd8a9b6ea12e1a73886581c86252602a438
3,658,639
import six def fix_troposphere_references(template): """"Tranverse the troposphere ``template`` looking missing references. Fix them by adding a new parameter for those references.""" def _fix_references(value): if isinstance(value, troposphere.Ref): name = value.data['Ref'] ...
9570e10262d7293a79b76f78508e57289d9b1e2d
3,658,641
import configparser def parse_config_to_dict(cfg_file, section): """ Reads config file and returns a dict of parameters. Args: cfg_file: <String> path to the configuration ini-file section: <String> section of the configuration file to read Returns: cfg: <dict> configuration param...
021e3594f3130e502934379c0f5c1ecea228017b
3,658,642
def cnn_net(data, dict_dim, emb_dim=128, hid_dim=128, hid_dim2=96, class_dim=2, win_size=3): """ Conv net """ # embedding layer emb = fluid.layers.embedding(input=data, size=[dict_dim, emb_dim]) # convolution layer conv...
47127d5124f48b2be187d15291c2f2bc63f072d7
3,658,643
def FormatRow(Cn, Row, COLSP): """ """ fRow = "" for i, c in enumerate(Row): sc = str(c) lcn = len(Cn[i]) sc = sc[ 0 : min(len(sc), lcn+COLSP-2) ] fRow += sc + " "*(COLSP+lcn-len(sc)) return fRow
53d43fc897d1db5ed3c47d6046d90548939b1298
3,658,645
def handle_release(pin, evt): """ Clears the last tone/light when a button is released. """ if pin > 4: return False pin -= 1 explorerhat.light[pin].off() tone.power_off()
f4833bb289c9dfc45cd572ad754bd270c758ed09
3,658,646
from typing import List def makeRoute(start : str, end : str) -> List[str]: """Find the shortest route between two systems. :param str start: string name of the starting system. Must exist in bbData.builtInSystemObjs :param str end: string name of the target system. Must exist in bbData.builtInSystemObjs...
6045b07ff5ceceacea4ad43ae2d52a67a0f46ec9
3,658,647
def norm_error(series): """Normalize time series. """ # return series new_series = deepcopy(series) new_series[:,0] = series[:,0] - np.mean(series[:,0]) return 2*(new_series)/max(abs(new_series[:,0]))
a7af6be8b8ddc800609c3385a96f5a80dfd02853
3,658,649
def f1d(x): """Non-linear function for simulation""" return(1.7*(1/(1+np.exp(-(x-0.5)*20))+0.75*x))
75e3bd8a90fe41dfded9b6063868b6766351a8b0
3,658,650
def get_field_map(src, flds): """ Returns a field map for an arcpy data itme from a list or dictionary. Useful for operations such as renaming columns merging feature classes. Parameters: ----------- src: str, arcpy data item or arcpy.mp layer or table Source data item containing the de...
18e6bbae491659b7819aa3584eb40242dea93f11
3,658,651
def b32qlc_decode(value): """ Decodes a value in qlc encoding to bytes using base32 algorithm with a custom alphabet: '13456789abcdefghijkmnopqrstuwxyz' :param value: the value to decode :type: bytes :return: decoded value :rtype: bytes >>> b32qlc_decode(b'fxop4ya=') b'okay' """ ...
8b5bbb0f1900a3b89486c81561fd4c253604287e
3,658,652
def createPreProcessingLayers(): """ Creates a model with the initial pre-processing layers. """ model = Sequential() model.add(Lambda(lambda x: (x / 255.0) - 0.5, input_shape=(160, 320, 3))) model.add(Cropping2D(cropping=((50, 20), (0, 0)))) return model
1e087ae4bdd1a942845f4f7554e1b27436c6783e
3,658,653
def get_random_atoms(a=2.0, sc_size=2, numbers=[6, 8], set_seed: int = None): """Create a random structure.""" if set_seed: np.random.seed(set_seed) cell = np.eye(3) * a positions = np.array([[0, 0, 0], [a/2, a/2, a/2]]) unit_cell = Atoms(cell=cell, positions=position...
710592af7db3e24529b68b84e112641b5da63a98
3,658,654
def vgg16_bn(pretrained=False, **kwargs): """VGG 16-layer model (configuration "D") with batch normalization Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ if pretrained: kwargs['init_weights'] = False model = VGG(make_layers(cfg['D'], batch_norm=True),...
34f8e4965555ed4cb046c8ab4e5cde799d887040
3,658,656
import numpy def tau(x, cval): """Robust estimators of location and scale, with breakdown points of 50%. Also referred to as: Tau measure of location by Yohai and Zamar Source: Yohai and Zamar JASA, vol 83 (1988), pp 406-413 and Maronna and Zamar Technometrics, vol 44 (2002), pp. 307-317""" ...
6f75ee23f50e94d1ee2754949f5c102d63ac4cab
3,658,657
def shn_gis_location_represent(id, showlink=True): """ Represent a location given its id """ table = db.gis_location try: location = db(table.id == id).select(table.id, table.name, table.level, ...
758dfb8e32178e864f838a790eadf598f65ae6ec
3,658,658
def de_pearson_dataframe(df, genes, pair_by='type', gtex=True, tcga=True): """ PearsonR scores of gene differential expression between tumor and normal types. 1. Calculate log2FC of genes for TCGA tumor samples with matching TCGA normal types 2. Compare log2fc to tumor type compared to all other normal...
29423402b24acc67a278cbdee03916add4228d7d
3,658,659
def load_YUV_as_dic_tensor(path_img): """ Construct a dic with 3 entries ('y','u', 'v'), each of them is a tensor and is loaded from path_img + key + '.png'. ! Return a dictionnary of 3D tensor (i.e. without a dummy batch index) """ dic_res = {} key = ['y', 'u', 'v'] for k i...
b0fe081b36c70ba8a185f151b13c5f046ef26ad6
3,658,660
def tensor_log10(t1, out_format, dtype=None): """ Takes the log base 10 of each input in the tensor. Note that this is applied to all elements in the tensor not just non-zeros. Warnings --------- The log10 of 0 is undefined and is performed on every element in the tensor re...
ff5c1a2f4cee9bc287ac81d3d3e524c1292fa2a7
3,658,661
def get_file_phenomena_i(index): """ Return file phenomena depending on the value of index. """ if index <= 99: return [phen[0]] elif index >= 100 and index <= 199: return [phen[1]] elif index >= 200 and index <= 299: return [phen[2]] elif index >= 300 and index <= ...
18beac08b59aec18b33f6472866a50decd01db30
3,658,662
def resource_cache_map(resource_id, flush=True): """cache resource info""" if flush: map_resources(resource_ids=[resource_id, ]) if resource_id not in CDNRESOURCE: raise InvalidArgument('Resource not exit') return CDNRESOURCE[resource_id]
5e67546db9008e805b80c1ed7545d3787444c402
3,658,663
def _preprocess_html(table_html): """Parses HTML with bs4 and fixes some glitches.""" table_html = table_html.replace("<br />", "<br /> ") table = bs4.BeautifulSoup(table_html, "html5lib") table = table.find("table") # Delete hidden style annotations. for tag in table.find_all(attrs={"style": "display:none"...
1062c5cdbb058ea36b1c877d7787aebbde87c642
3,658,664
def parse_campus_hours(data_json, eatery_model): """Parses a Cornell Dining json dictionary. Returns 1) a list of tuples of CampusEateryHour objects for a corresponding CampusEatery object and their unparsed menu 2) an array of the items an eatery serves. Args: data_json (dict): a valid dictio...
95e7bbc898f4516b9812d3f68749651a32f3535f
3,658,665
from typing import Dict from typing import Tuple def _change_relationships(edge: Dict) -> Tuple[bool, bool]: """Validate relationship.""" if 'increases' in edge[1]['relation'] or edge[1]['relation'] == 'positive_correlation': return True, True elif 'decreases' in edge[1]['relation'] or edge[1]['re...
b826eb1eb7bd1e7eed7fd8577b5c04d827a75e56
3,658,666
def extract_behaviour_sync(sync, chmap=None, display=False, tmax=np.inf): """ Extract wheel positions and times from sync fronts dictionary :param sync: dictionary 'times', 'polarities' of fronts detected on sync trace for all 16 chans :param chmap: dictionary containing channel index. Default to const...
b02ec14a5714f1387acb12f1ec2d5bbbc1684f67
3,658,667
def is_attr_defined(attrs,dic): """ Check if the sequence of attributes is defined in dictionary 'dic'. Valid 'attrs' sequence syntax: <attr> Return True if single attrbiute is defined. <attr1>,<attr2>,... Return True if one or more attributes are defined. <attr1>+<attr2>+... Return True if all ...
542388846fabc79e126203d80a63db6901a71897
3,658,669
def c_str_repr(str_): """Returns representation of string in C (without quotes)""" def byte_to_repr(char_): """Converts byte to C code string representation""" char_val = ord(char_) if char_ in ['"', '\\', '\r', '\n']: return '\\' + chr(char_val) elif (ord(' ') <= cha...
e7cce729a00a7d2a35addf95eb097a3caa06bedd
3,658,670
def getActiveTeamAndID(): """Returns the Team ID and CyTeam for the active player.""" return getActiveTeamID(), getActiveTeam()
edf58aee8d9126ddc25afd94becf641330e13ca2
3,658,672
from typing import Union from typing import BinaryIO from typing import Tuple from typing import Optional def is_nitf( file_name: Union[str, BinaryIO], return_version=False) -> Union[bool, Tuple[bool, Optional[str]]]: """ Test whether the given input is a NITF 2.0 or 2.1 file. Parameters ...
6e28baa09d6b8e173db00671e1ed08023630110b
3,658,673
def get_xlsx_filename() -> str: """ Get the name of the excel file. Example filename: kesasetelihakemukset_2021-01-01_23-59-59.xlsx """ local_datetime_now_as_str = timezone.localtime(timezone.now()).strftime( "%Y-%m-%d_%H-%M-%S" ) filename = f"kesasetelihakemukset_{local_datetime_now...
fb8715f30bd91f39d9836bf59504ad85c205bdf3
3,658,675
from pathlib import Path def get_content_directory() -> Path: """ Get the path of the markdown `content` directory. """ return get_base_directory() / "content"
2b6f7a9c676e8128fafd43b26cf62aa736aa957c
3,658,676
import math def mag_inc(x, y, z): """ Given *x* (north intensity), *y* (east intensity), and *z* (vertical intensity) all in [nT], return the magnetic inclincation angle [deg]. """ h = math.sqrt(x**2 + y**2) return math.degrees(math.atan2(z, h))
f4036358625dd9d032936afc373e53bef7c1e6e1
3,658,677
import torch def rgb_to_rgba(image, alpha_val): """ Convert an image from RGB to RGBA. """ if not isinstance(image, torch.Tensor): raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}") if len(image.shape) < 3 or image.shape[-3] != 3: raise ValueError(f"Input ...
5bab73c37ff81c431ed88ce7d39743cce6c15c56
3,658,678
def get(identifier): """get the activation function""" if identifier is None: return linear if callable(identifier): return identifier if isinstance(identifier, str): activations = { "relu": relu, "sigmoid": sigmoid, "tanh": tanh, "...
005789e8cdadff97875f002b9776d8d8bdb22d56
3,658,680
def df_add_column_codelines(self, key): """Generate code lines to add new column to DF""" func_lines = df_set_column_index_codelines(self) # provide res_index = ... results = [] for i, col in enumerate(self.columns): col_loc = self.column_loc[col] type_id, col_id = col_loc.type_id, col...
742241d973bb46da2a75b40bf9a76c91ba759d98
3,658,681
import torch def resize_bilinear_nd(t, target_shape): """Bilinear resizes a tensor t to have shape target_shape. This function bilinearly resizes a n-dimensional tensor by iteratively applying tf.image.resize_bilinear (which can only resize 2 dimensions). For bilinear interpolation, the order in which...
005266983cca744437826673ff8dd379afb699e2
3,658,682
def _parse_disambiguate(disambiguatestatsfilename): """Parse disambiguation stats from given file. """ disambig_stats = [-1, -1, -1] with open(disambiguatestatsfilename, "r") as in_handle: header = in_handle.readline().strip().split("\t") if header == ['sample', 'unique species A pairs',...
bb05ec857181f032ae9c0916b4364b772ff7c412
3,658,683
def clean_vigenere(text): """Convert text to a form compatible with the preconditions imposed by Vigenere cipher.""" return ''.join(ch for ch in text.upper() if ch.isupper())
d7c3fc656ede6d07d6e9bac84a051581364c63a0
3,658,684
def select_artist(df_by_artists, df_rate): """This method selects artists which perform the same genre as artists were given :param df_by_artists: :param df_rate: """ # save the indices of artists, which include any of the genres in the genre profile list_of_id = [] for index, row in...
85c09b62553a3257b4f325dd28d26335c9fcb033
3,658,685
import uuid def generate_uuid(class_name: str, identifier: str) -> str: """ Generate a uuid based on an identifier :param identifier: characters used to generate the uuid :type identifier: str, required :param class_name: classname of the object to create a uuid for :type class_name: str, require...
10e85effbce04dec62cc55ee709247afa0fb0da7
3,658,686
def fetch(model, key): """Fetch by ID.""" return db.session.query(model).get(key)
4c3008bec5ed5eac593f2ad8ba2816f121362677
3,658,687
from typing import Optional def construct_filename(prefix: str, suffix: Optional[str] = '.csv') -> str: """Construct a filename containing the current date. Examples -------- .. code:: python >>> filename = construct_filename('my_file', '.txt') >>> print(filename) 'my_file_31...
8269947952d4c8d81cc2855a5776c3677c6a5c57
3,658,688
def make_friedman_model(point1, point2): """ Makes a vtk line source from two set points :param point1: one end of the line :param point2: other end of the line :returns: The line """ line = vtkLineSource() line.SetPoint1(point1) line.SetPoint2(point2) return line
f33046307c7c0c2bfeadfbdb4e0815bc5d42d73f
3,658,689
import re def breadcrumbs_pcoa_plot(pcl_fname, output_plot_fname, **opts): """Use breadcrumbs `scriptPcoa.py` script to produce principal coordinate plots of pcl files. :param pcl_fname: String; file name of the pcl-formatted taxonomic profile to visualize via `scriptPcoa.py`. :...
06fc9511b21ec3c0111ba91cea8c08852eb2bcaf
3,658,690
def _parse_xml(buff): """\ Parses XML and returns the root element. """ buff.seek(0) return etree.parse(buff).getroot()
fa3876f93c0a71b9e4bf6d95dfadbf0714e7c17c
3,658,691
def After(interval): """ After waits for the duration to elapse and then sends the current time on the returned channel. It is equivalent to Timer(interval).c """ return Timer(interval).c
1011151471f839b3e9f7edad369699d76d9f7601
3,658,692
def f_score(r: float, p: float, b: int = 1): """ Calculate f-measure from recall and precision. Args: r: recall score p: precision score b: weight of precision in harmonic mean Returns: val: value of f-measure """ try: val = (1 + b ** 2) * (p * r) / (b *...
d12af20e30fd80cb31b2cc119d5ea79ce2507c4b
3,658,693
def show_inventory(): """Show the user what is in stock.""" context = { 'inventory': [ # Could contain any items {'name': 'apple', 'price': 1.00}, {'name': 'banana', 'price': 1.20}, {'name': 'carrot', 'price': 2.00}, ] } return render_template('sho...
be2b67abb1ebd60bacfad117dab166a08d6915b1
3,658,695
import numpy as np import re def rebuild_schema(doc, r, df): """Rebuild the schema for a resource based on a dataframe""" # Re-get the resource in the doc, since it may be different. try: r = doc.resource(r.name) except AttributeError: # Maybe r is actually a resource name r =...
ed212e5cff26dcfece99e3361df9d61823c2bfde
3,658,697
def compute_similarity(image, reference): """Compute a similarity index for an image compared to a reference image. Similarity index is based on a the general algorithm used in the AmphiIndex algorithm. - identify slice of image that is a factor of 256 in size - rebin image slice down to a (25...
0b49009bfdd0697999e61825390a8f883ae8dd79
3,658,698
def _create_npu_quantization( scale, zero_point, ): """This is a helper function to capture a list of arguments to create Vela NpuQuantization object """ # Scale could be an ndarray if per-channel quantization is available if not isinstance(scale, tvm.tir.expr.Load): if isinstance(sc...
71f7e20a760940e6d46301ccd9130265de140b29
3,658,699
def article_markdown(text): """ 对传入的text文本进行markdown """ renderer = ArticleRenderer() markdown = mistune.Markdown(renderer=renderer) return markdown(text)
32d1edc0d5155c62b0dc0ff18dc9a44f1ec85d7a
3,658,700
def _gen_key(user_id, key_name): """ Tuck this into UserManager """ try: manager = users.UserManager.instance() private_key, fingerprint = manager.generate_key_pair(user_id, key_name) except Exception as ex: return {'exception': ex} return {'private_key': private_key, 'fingerprin...
f5babf523bded37ba624295a7435e2709488d47a
3,658,703
def svhn_loader(size=None,root="./shvn",set="train",batch_size=32,mean=0.5,std=0.5,transform="default",download=True,target_transform=None,**loader_args): """ :param size: :param root: :param set: :param batch_size: :param mean: :param std: :param transform: :param download: :pa...
f40cd95338f4e745cbbb849ac8a9999f98245cf0
3,658,704
import pkg_resources def get_supervisees(): """Pull the supervisor specifications out of the entry point.""" eps = list(pkg_resources.iter_entry_points(ENTRY_POINT_GROUP)) return dict((ep.name, ep.load()) for ep in eps)
6a812bb8422382c6e481bab8b27651786984ea66
3,658,705
async def index(request): """ This is the view handler for the "/" url. **Note: returning html without a template engine like jinja2 is ugly, no way around that.** :param request: the request object see http://aiohttp.readthedocs.io/en/stable/web_reference.html#request :return: aiohttp.web.Respons...
f90ba225055bf77b39942da7fc1b1b2f5b4a7286
3,658,706
def adtg(s, t, p): """ Calculates adiabatic temperature gradient as per UNESCO 1983 routines. Parameters ---------- s(p) : array_like salinity [psu (PSS-78)] t(p) : array_like temperature [℃ (ITS-90)] p : array_like pressure [db] Returns ------- ad...
8d195810ad52215135db4ef8f9825a914b01522c
3,658,707
import re def calculate_ion_mz(seq: str, ion: str = 'M', charge: int = 0 ) -> float: """ given a peptide sequence and ion type, count the number of atoms, accounting for ion type and whether cysteines are measured by IAA - ion type M:...
e032ad439414314511b008d98dadb23b84012798
3,658,708
def hhc_to_int(s): """Parse a number expressed in sortable hhc as an integer (or long). >>> hhc_to_int('-') 0 >>> hhc_to_int('.') 1 >>> hhc_to_int('~') 65 >>> hhc_to_int('.-') 66 >>> hhc_to_int('..') 67 >>> hhc_to_int('.XW') 6700 >>> hhc_to_int('----..') 67 ...
25f6e8097f1fbf0f6ceed08fc8ac0195fb88acb4
3,658,710
def initializeSens(P, B, idxs): """ This function initializes the sensitivities using the bicriteria algorithm, to be the distance between each point to it's closest flat from the set of flats B divided by the sum of distances between self.P.P and B. :param B: A set of flats where each flat is represen...
6726c892311d1590adea62babde6023d4b7d67a3
3,658,711
def fast_knn(data, k=3, eps=0, p=2, distance_upper_bound=np.inf, leafsize=10, idw=util_idw.shepards): """ Impute using a variant of the nearest neighbours approach Basic idea: Impute array with a basic mean impute and then use the resulting complete array to construct a KDTree. Use this KDTree to compute n...
976e51c66878643965b099f764595629b379d440
3,658,712
def role_generator(role): """Closure function returning a role function.""" return lambda *args, **kwargs: role.run(*args, **kwargs)
35dd1a54cb53a6435633c39608413c2d0b9fe841
3,658,713
def pick_slices(img, num_slices_per_view): """ Picks the slices to display in each dimension, skipping any empty slices (without any segmentation at all). """ slices = list() for view in range(len(img.shape)): dim_size = img.shape[view] non_empty_slices = np.array( ...
ed80e4bd53e6a72c6ad7cad899d875ac320b33b7
3,658,714
import json def cate2(request): """ DB에서 Cate2의 분류 이름을 반환 """ cate1 = Cate1.objects.get(cate1_name=request.GET.get('cate1')) cate2 = list(map(lambda cate2 : cate2['cate2_name'], Cate2.objects.filter(cate1=cate1).values('cate2_name'))) json_data = json.dumps({'cate2': cate2}) retu...
ebeca48bb9d6550fb34d68c453ef1fb47225fb4a
3,658,715
def dayChange(): """ Day Change Calculates and stores in a dictionary the total current change in position value since yesterday, which is (current_price - lastday_price)* qty. :return: dictionary """ daychange = dict() for position in portfolio: # Strings are returned from API; ...
f33979f25ffe44a0de8ec0abc1c02284e8fe5427
3,658,717
def look_for_section(line): """Look for one of the sections in a line of text.""" for key in SECTIONS: if line.startswith(key): return key return None
d44ad97312528c4fea856e705be8e6820695fd9a
3,658,718
def SetStrucIdx(sid, index): """ Change structure index @param sid: structure type ID @param index: new index of the structure @return: != 0 - ok @note: See GetFirstStrucIdx() for the explanation of structure indices and IDs. """ s = idaapi.get_struc(sid) if not s: ...
8b246d6e2fb155bdc789536f75e20971a54ddfc3
3,658,719
import json def extract_user_dict_from_tweet( tweet: Tweet ): """Takes the other_data field from a tweet object and extracts the data for the user from it. It returns a dictionary rather than a User model object because we might want to try looking up whether the user exists before creating a new ...
533d8795c652e5c7f1299f3dcc04fc30de644222
3,658,720
def in_scope(repository_data): """Return whether the given repository is in scope for the configuration. Keyword arguments: repository_data -- data for the repository """ if "scope" in repository_data["configuration"] and repository_data["configuration"]["scope"] == "all": return True ...
0e521f805f69a1c6f306700680d42fbe76595c3a
3,658,721
from typing import Union from typing import Tuple from typing import Optional from typing import List from typing import Any def run_image_container_checks( image_container: Union[AICSImage, Reader], set_scene: str, expected_scenes: Tuple[str, ...], expected_current_scene: str, expected_shape: Tup...
a502650fb227aa4425a2501f112603b681b41fbf
3,658,722
from typing import Type def collect_validation_helper(package_names: str) -> Type[ValidationHelper]: """Finds subclasses of the validate.ValidationHelper from a list of package names. Args: package_names: A list of Python package names as strings. Returns: A validator class that are ...
bb38b734641a025a9d7fd26d46ebfb1476879c82
3,658,723
def heartbeat(request): """Test that ElasticSearch is operationnal. :param request: current request object :type request: :class:`~pyramid:pyramid.request.Request` :returns: ``True`` is everything is ok, ``False`` otherwise. :rtype: bool """ indexer = request.registry.indexer try: ...
6acf0b21b6fcc64f70ca75cb6795df0b5109f273
3,658,724