content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import numpy def normal_function( sigma, width ): """ Defaulf fitting function, it returns values from a normal distribution """ log2 = log(2) sigma2 = float(sigma)**2 lo, hi = width, width+1 def normal_func(value, index): return value * exp( -index*index/sigma2 * log2 ) ...
797b4eb00db5a0d4675b547664982f537da9e6ab
23,100
def style_get_url(layer, style_name, internal=True): """Get QGIS Server style as xml. :param layer: Layer to inspect :type layer: Layer :param style_name: Style name as given by QGIS Server :type style_name: str :param internal: Flag to switch between public url and internal url. Publ...
bdc67d562c8e2020374094ce3fb15cd525f4dd37
23,101
def remove_duplicates(l): """ Remove any duplicates from the original list. Return a list without duplicates. """ new_l = l[:] tmp_l = new_l[:] for e in l: tmp_l.remove(e) if e in tmp_l: new_l.remove(e) return new_l
81132e3b23592589c19ddb11f661e80be6984782
23,102
import functools def in_boudoir(callback): """Décorateur : commande utilisable dans un boudoir uniquement. Lors d'une invocation de la commande décorée hors d'un boudoir (enregistré dans :class:`.bdd.Boudoir`), affiche un message d'erreur. Ce décorateur n'est utilisable que sur une commande définie ...
ed086805f2d865331f559406218f9a9ecd4a7194
23,103
import argparse import time def parse_input(): """ Sets up the required input arguments and parses them """ parser = argparse.ArgumentParser() parser.add_argument('log_file', help='CSV file of log data') parser.add_argument('-e, --n_epochs', dest='n_epochs', help='number of tr...
d87a59d31c2face243614ab64b5b08833f0537dd
23,104
def xyz_to_pix(position, bounds, pixel_size): """Convert from 3D position to pixel location on heightmap.""" u = int(np.round((position[1] - bounds[1, 0]) / pixel_size)) v = int(np.round((position[0] - bounds[0, 0]) / pixel_size)) return (u, v)
d38b45d573a689f72fda4a7ed477be831bea26a8
23,105
import random def get_random_lb(): """ Selects a random location from the load balancers file. Returns: A string specifying a load balancer IP. """ with open(LOAD_BALANCERS_FILE) as lb_file: return random.choice([':'.join([line.strip(), str(PROXY_PORT)]) for line in lb_file]...
2f8620a213bfc87dd3eae662ace409a31597931b
23,106
def enlarge(n): """ Multiplies a number by 100 Param: n (numeric) the number to enlarge Return the enlarged number(numeric) """ return n * 100
6685af169c8e321ceabc0086d1835d459a627a59
23,107
import re def ResolveWikiLinks(html): """Given an html file, convert [[WikiLinks]] into links to the personal wiki: <a href="https://z3.ca/WikiLinks">WikiLinks</a>""" wikilink = re.compile(r'\[\[(?:[^|\]]*\|)?([^\]]+)\]\]') def linkify(match): wiki_root = 'https://z3.ca' wiki_name = match.group(1).rep...
bef3e309aa2489e720a1742e327e9dd4edf6d720
23,108
def handle_new_favorite(query_dict): """Does not handle multi-part data properly. Also, posts don't quite exist as they should.""" for required in POST_REQUIRED_PARAMS: if required not in query_dict: return False # not yet safe to use. post_id = str(string_from_interwe...
7caed7d280870cb7a67b1bfd53200ec3486a4f41
23,109
def steam_ratings(html_text): """Tries to get both 'all' and 'recent' ratings.""" return { "overall": steam_all_app_rating(html_text), "recent": steam_recent_app_rating(html_text), }
71cb3e85e9a1f01e5d4b080372b24c2f848bf7cf
23,110
def separation_cos_angle(lon0, lat0, lon1, lat1): """Evaluate the cosine of the angular separation between two direction vectors.""" return (np.sin(lat1) * np.sin(lat0) + np.cos(lat1) * np.cos(lat0) * np.cos(lon1 - lon0))
a7e1a7ecdfd0ab7f1dc58b99190cc9eeab7fcf20
23,111
import sys def getArg(flag): """ Devolve o argumento de uma dada flag """ try: a = sys.argv[sys.argv.index(flag) + 1] except: return "" else: return a
7400d0f449334350910bc5926b5fbf5333d3ea10
23,112
def get_band_params(meta, fmt='presto'): """ Returns (fmin, fmax, nchans) given a metadata dictionary loaded from a specific file format. """ if fmt == 'presto': fbot = meta['fbot'] nchans = meta['nchan'] ftop = fbot + nchans * meta['cbw'] fmin = min(fbot, ftop) ...
61e9b0781559de431e5189b89f69a0763b039d8f
23,113
import functools def logging(f): """Decorate a function to log its calls.""" @functools.wraps(f) def decorated(*args, **kwargs): sargs = map(str, args) skwargs = (f'{key}={value}' for key, value in kwargs.items()) print(f'{f.__name__}({", ".join([*sargs, *skwargs])})...') ...
25822434fe331c59ce64b6f9cd5ec89b70b2542a
23,114
def yandex_mean_encoder(columns=None, n_jobs=1, alpha=100, true_label=None): """ Smoothed mean-encoding with custom smoothing strength (alpha) http://learningsys.org/nips17/assets/papers/paper_11.pdf """ buider = partial( build_yandex_mean_encoder, alpha=alpha, ) return Tar...
b38ac44cb2ff12c33f415d716cc4e13006eabf0b
23,115
from typing import Optional import math from typing import Counter def cure_sample_part( X: np.ndarray, k: int, c: int = 3, alpha: float = 0.3, u_min: Optional[int] = None, f: float = 0.3, d: float = 0.02, p: Optional[int] = None, q: Optional[int] = None, n_rep_finalclust: Opti...
b85d2f23bd1b64a0f17abc5178cfc25e442419b5
23,116
def get_serializer(request): """Returns the serializer for the given API request.""" format = request.args.get('format') if format is not None: rv = _serializer_map.get(format) if rv is None: raise BadRequest(_(u'Unknown format "%s"') % escape(format)) return rv # we...
90c11efea0a8636ef3b6b4ca87f4d377d3e0be52
23,117
from typing import Optional import pickle def deserialize_result(r: bytes, *, deserializer: Optional[Deserializer] = None) -> JobResult: """Given bytes, deserializes them into a JobResult object. :param r: bytes to deserialize. :param deserializer: Optional serializer to use for deserialization. If not ...
049a453a7277f30a38019ca59bedbc458fbaf84c
23,118
def form_symb_dCdU(): """Form a symbolic version of dCdU""" dCdU = form_nd_array("dCdU",[3,3,8*12]) for I in range(3): for J in range(3): for K in range(3,8*12): dCdU[I,J,K] = 0 return dCdU
ec802da453dd7c522bf5725fd70fd16a2406c12e
23,119
import torch def predict(X, y, clf, onehot_encoder, params): """ Runs a forward pass for a SINGLE sample and returns the output prediction. Arguments: X (list[int]) : a list of integers with each integer an input class of step y (list[int]) : a list of integers with each integer an output ...
8e0aa3c687a3ad24e02f730a5dca31f4fd36c6ad
23,120
def parse_modules_and_elabs(raw_netlist, net_manager): """ Parses a raw netlist into its IvlModule and IvlElab objects. Returns a tuple: (modules, elabs) modules is a list of IvlModule objects. elabs is a list of IvlElab objects. """ sections = parse_netlist_to_sections(raw_netlist) mod...
029d5a86de450eb6c104cc2582e21fe854c557e7
23,121
def scrub_dt_dn(dt, dn): """Returns in lowercase and code friendly names of doctype and name for certain types""" ndt, ndn = dt, dn if dt in lower_case_files_for: ndt, ndn = scrub(dt), scrub(dn) return ndt, ndn
853959c073f45be0ffc97dfd8733d2b10a837a32
23,122
def by_uri(uri): """A LicenseSelector-less means of picking a License from a URI.""" if _BY_URI_CACHE.has_key(uri): return _BY_URI_CACHE[uri] for key, selector in cc.license.selectors.SELECTORS.items(): if selector.has_license(uri): license = selector.by_uri(uri) _B...
1dc3dfe4070857984768e1af6462927fd08daf77
23,123
def read_S(nameIMGxml): """ This function extract the images's center from the xml file. Parameters ---------- nameIMGxml : str the name of the file generated by MM3D. Usually, it is "Orientation-Im[n°i].JPG.xml" Returns ------- numpy.ndarray: the center of the IMG ...
f4054827c8ecfa6d81ac752e8ac46e4cccbc5245
23,124
def AddBatchJob(client): """Add a new BatchJob to upload operations to. Args: client: an instantiated AdWordsClient used to retrieve the BatchJob. Returns: The new BatchJob created by the request. """ # Initialize appropriate service. batch_job_service = client.GetService('BatchJobService', versio...
6c48997e4739f05fe6df826654a45b6f7deafc1b
23,125
def bellmanFord(obj,source): """Determination of minimum distance between vertices using Bellman Ford Algorithm.""" validatePositiveWeight(obj) n = CountVertices(obj) minDist = dict() for vertex in obj.vertexList: if vertex == source: minDist[vertex] = 0 else: ...
83cdbab547741a070ef694b4cea8f16355eb4af5
23,126
from typing import Callable import inspect import click def auto_default_option(*param_decls, **attrs) -> Callable[[_C], _C]: """ Attaches an option to the command, with a default value determined from the decorated function's signature. All positional arguments are passed as parameter declarations to :class:`cli...
e1813faf2c0d936333edf4d2a1b111dec6c7a376
23,127
import os def get_filename_from_url(url): """ Convert URL to filename. Example: URL `http://www.example.com/foo.pdf` will be converted to `foo.pdf`. :type url: unicode :rtype: unicode """ name, extension = os.path.splitext(os.path.basename(urlsplit(url).path)) fin = "{filen...
b53ff1d2a8878f3d477e1579a16f9de29af4e6b3
23,128
def zCurve(seq): """Return 3-dimensional Z curve corresponding to sequence. zcurve[n] = zcurve[n-1] + zShift[n] """ zcurve = np.zeros((len(seq), 3), dtype=int) zcurve[0] = zShift(seq, 0) for pos in range(1, len(seq)): zcurve[pos] = np.add(zcurve[pos - 1], zShift(seq, pos)) return zc...
4118274fc3bee084777847553dcfa9c4dc92c6c9
23,129
def getgeo(): """ Grabbing and returning the zones """ data = request.args.get('zone_name', None) print data #Check if data is null - get all zones out = [] if data: rec = mongo.db.zones.find({'zone_name':data}) else: rec = mongo.db.zones.find() for r in rec: r.p...
822e8e995ae47d887340a2750eeda5646dfa9d5b
23,130
def photo_upload(request): """AJAX POST for uploading a photo for any given application.""" response = None if request.is_ajax() and request.method == 'POST': form = PhotoForm( data=request.POST, files=request.FILES, use_required_attribute=False, ) if form.is_valid(): ...
e760570d07f43800c05f4d1d8b36b9cb84804003
23,131
def table_str(bq_target): # type: (BigqueryTarget) -> str """Given a BigqueryTarget returns a string table reference.""" t = bq_target.table return "%s.%s.%s" % (t.project_id, t.dataset_id, t.table_id)
95053c839d2bc1e4d628261d669a73a6b9dcb309
23,132
def any_to_any_translate_back(content, from_='zh-CN', to_='en'): """ 中英,英中回译 :param content:str, 4891个字, 用户输入 :param from_: str, original language :param to_: str, target language :return: str, result of translate """ translate_content = any_to_any_translate(content, from_=from_, to...
def5100d73712fd1f244913aca725328cbe02b4d
23,133
def to_short_site_cname(user, site): """ 订阅源显示名称,最多 10 个汉字,支持用户自定义名称 """ if isinstance(site, dict): site_id = site['id'] site_cname = site['cname'] else: site_id = site.id site_cname = site.cname if user: cname = get_user_site_cname(user.oauth_id, site_id...
70b4874af06e4185a72a45ff82838b2d00cdcec6
23,134
def load_roed_data(full_output=False): """ Load master table with all labels """ mtab = load_master_table() df1 = table.Table.read("roed14_stars.fits").to_pandas() def renamer(x): """ match master table Star with Name """ x = x.strip() if x.startswith("BD") or x.startswith("CD"):...
8698b478abb9a3e617ce9a23feb89fecf220e341
23,135
import math def calculate_distance(p1, p2): """ Calculate distance between two points param p1: tuple (x,y) point1 param p2: tuple (x,y) point2 return: distance between two points """ x1, y1 = p1 x2, y2 = p2 d = math.sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2)) return d
756b609a91e17299eb879e27e83cd663800e46dd
23,136
def statistics(request, network): """ some nice statistics for the whole pool """ # some basic statistics days = 1 current_height, all_blocks, pool_blocks, pool_blocks_percent, bbp_mined = get_basic_statistics(network, days) miners_count = get_miner_count(network, days) graph_days = 7 t...
d44033323bfe041ee53109a9274ff2fd9c9d9df3
23,137
from textwrap import dedent def package_load_instructions(inst_distributions): """Load instructions, displayed in the package notes""" per_package_inst = '' for dist in inst_distributions: if dist.type == 'zip': per_package_inst += dedent( """ # Loadi...
321a7486f27a3cb327ae7556e317bc53c24726ac
23,138
def specialize_transform(graph, args): """Specialize on provided non-None args. Parameters that are specialized on are removed. """ mng = graph.manager graph = transformable_clone(graph, relation=f'sp') mng.add_graph(graph) for p, arg in zip(graph.parameters, args): if arg is not No...
44b892312ff677bdc5bee84bf5df1e1dc4bd5ba5
23,139
from functools import reduce import operator import itertools def Multiplication(k): """ Generate a function that performs a polynomial multiplication and return coefficients up to degree k """ assert isinstance(k, int) and k > 0 def isum(factors): init = next(factors) return redu...
23a663231e44b09cd446e9ba1d269e7b123efc1d
23,140
def safe_divide(a, b): """ Avoid divide by zero http://stackoverflow.com/questions/26248654/numpy-return-0-with-divide-by-zero """ with np.errstate(divide='ignore', invalid='ignore'): c = np.true_divide(a, b) c[c == np.inf] = 0 c = np.nan_to_num(c) return c
104970a64f5d77f674a46f9da08b039345fa546a
23,141
def plot_lc(data=None, model=None, bands=None, zp=25., zpsys='ab', pulls=True, xfigsize=None, yfigsize=None, figtext=None, model_label=None, errors=None, ncol=2, figtextsize=1., show_model_params=True, tighten_ylim=False, fname=None, **kwargs): """Plot light curve data or model l...
b700a03ce9e16cdbcc32d22ac4a9124e70feba70
23,142
def read_image(filepath, gray=False): """ read image :param filepath: :param gray: :return: """ if gray: return cv2.cvtColor(cv2.imread(filepath), cv2.COLOR_BGR2GRAY) else: return cv2.cvtColor(cv2.imread(filepath), cv2.COLOR_BGR2RGB)
d5743c8ad517f5c274e3ac64d6082ea36539cfe3
23,143
from ...hubble.helper import parse_hub_uri def mixin_hub_pull_parser(parser): """Add the arguments for hub pull to the parser :param parser: the parser configure """ def hub_uri(uri: str) -> str: parse_hub_uri(uri) return uri parser.add_argument( 'uri', type=hub_...
9f62462baecc744ab7b7e3e78b5446a3d5347569
23,144
from typing import Tuple from typing import List import yaml from typing import Dict def load_config() -> Tuple[List, List]: """Get configuration from config file. Returns repo_paths and bare_repo_dicts. """ if config_file.exists(): with open(config_file, "r") as ymlfile: config =...
e9f483c6cc3ff1335a5d9866cc577e72a9a8084f
23,145
def deindented_source(src): """De-indent source if all lines indented. This is necessary before parsing with ast.parse to avoid "unexpected indent" syntax errors if the function is not module-scope in its original implementation (e.g., staticmethods encapsulated in classes). Parameters -------...
227d5e8e35b251f02ce5e9237f8120d2dd9c7e4b
23,146
def home(): """Render the home page.""" form = SearchForm() search_results = None if form.validate_on_submit(): search_term = form.username.data cur = conn.cursor() cur.execute(f"SELECT * FROM student WHERE name = '{search_term}';") search_results = cur.fetchall() ...
d578e4ba95af57828dfa6f483ad9aa0aeac8ea92
23,147
def capacity(): """ Returns the raw capacity of the filesystem Returns: filesystem capacity (int) """ return hdfs.capacity()
c9e220b19a1a1a200d2393bb98116be1767370b9
23,148
async def deploy(current_user: User = Depends(auth.get_current_user)): """ This function is used to deploy the model of the currently trained chatbot """ response = mongo_processor.deploy_model(bot=current_user.get_bot(), user=current_user.get_user()) return {"message": response}
cb7d53f605616e8a979dd144b786313c99f7a244
23,149
def find_rocks(img,rgb_thresh=(100, 100, 60)): """ Find rock in given image frame""" color_select = np.zeros_like(img[:,:,0]) # Require that each pixel be above all three threshold values in RGB # above_thresh will now contain a boolean array with "True" # where threshold was met above_thresh = ...
f0bffadfdf826f1f649029f3aaf224d07681589e
23,150
from pathlib import Path def maybe_start_with_home_prefix(p: Path) -> Path: """ If the input path starts with the home directory path string, then return a path that starts with the home directory and points to the same location. Otherwise, return the path unchanged. """ try: return Pa...
6ee4e49e8dfb9bc68a1c10f5ea792715fb5d5336
23,151
def parse_nrc_lexicon(): """Extract National Resource Council Canada emotion lexicon from http://saifmohammad.com/WebPages/lexicons.html Returns: {str: [str]} A defaultdict of emotion to list of associated words """ emotion2words = defaultdict(list) with open(NRC_LEXICON) as lexicon_file: ...
869988934a7ab6a1b0b601f96472ff85a2686975
23,152
def rouge_2_fscore(predictions, labels, **unused_kwargs): """ROUGE-2 F1 score computation between labels and predictions. This is an approximate ROUGE scoring method since we do not glue word pieces or decode the ids and tokenize the output. Args: predictions: tensor, model predictions labels: tensor,...
1c0ab9b514c36cf9947b31624e8a2cf308cdfe6b
23,153
from datetime import datetime def clear_log(): """clear log file""" if MODE == "debug": log_line = f"start {str(datetime.today())} \n\n" with open("temp/log.txt", "w", encoding="latin-1") as myfile: myfile.write(log_line) return ()
9a12f62b2de98ab8ef176ca23b7dbb49ca1486ea
23,154
def enhancedFeatureExtractorDigit(datum): """ Your feature extraction playground. You should return a util.Counter() of features for this datum (datum is of type samples.Datum). ## DESCRIBE YOUR ENHANCED FEATURES HERE... ## """ features = basicFeatureExtractorDigit(datum) "*** YOUR CODE HERE ***"...
564e324cd12b2cb98bd65cb053b5acea2f4d5831
23,155
import sys def query_yes_no(question, default="yes"): """Ask a yes/no question via raw_input() and return their answer. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits <Enter>. It must be "yes" (the default), "no" or None (meaning ...
fae49b63a25c11be8183cff47b36a8dd5b7f2615
23,156
def tested_function(x): """ Testovana funkce Da se sem napsat vselijaka cunarna """ freq = 1 damp_fac = 0.1 val = np.sin(freq * x) damp = np.exp(-1 * damp_fac * abs(x)) return val * damp
95808b55ace5b0536104f02de874344aa02d7033
23,157
def parse_line(line): """ Parses a (non-comment) line of a GFF3 file. The attribute field is parsed into a dict. :param line: line to parse as string :return: dict with for each column (key) the corresponding value """ parts = line.strip().split('\t') output = {} if len(parts) != len(...
0ea071c5a4165fd2bbbe77798bec09b033250c72
23,158
import requests from datetime import datetime def get_time_string(place: str = "Europe/Moscow"): """ Get time data from worldtimeapi.org and return simple string Parameters ---------- place : str Location, i.e. 'Europe/Moscow'. Returns ------- string Time in format '%...
f15ef5a843317c55d3c60bf2ee8c029258e1cd78
23,159
from typing import Type from typing import Dict from typing import Callable def new_worker_qthread( Worker: Type[WorkerProtocol], *args, _start_thread: bool = False, _connect: Dict[str, Callable] = None, **kwargs, ): """This is a convenience function to start a worker in a Qthread. In mos...
f607799bd7abf4b275d90bc4523dc9f0e8d2d200
23,160
import fnmatch def contains(filename, value=None, fnvalue=None): """ If a string is contained within a yaml (and is not a comment or key), return where we found it """ if filename in ALL_STRINGS: for el in ALL_STRINGS[filename]: if (value and value in el[0]) or (fnvalue and fnmatch.fnmatch...
2c21aee4fe7121ad26e588b33dfa2f09f1d4066b
23,161
def plot_with_overview( ds, tn, forcing_vars=["dqdt_adv", "dtdt_adv"], domain_var="q", overview_window_width=4, ): """ Produce a forcing plot with timestep `tn` highlighted together with overview plots of domain data variable `domain_var`. The width over the overview plot is set with...
e02be6157853b5a0a409fe45a02f52d685913e22
23,162
def optimize(nn_last_layer, correct_label, learning_rate, num_classes): """ Build the TensorFLow loss and optimizer operations. :param nn_last_layer: TF Tensor of the last layer in the neural network :param correct_label: TF Placeholder for the correct label image :param learning_rate: TF Placeholde...
b618626f7e458e1ef3ffda74af7532d93668a9cb
23,163
def expanded_indexer(key, ndim): """Given a key for indexing an ndarray, return an equivalent key which is a tuple with length equal to the number of dimensions. The expansion is done by replacing all `Ellipsis` items with the right number of full slices and then padding the key with full slices so tha...
a4fa3b1e4a106350348c128ef5ce8b86dac1f0c0
23,164
def downsample( data, sampling_freq=None, target=None, target_type="samples", method="mean" ): """Downsample pandas to a new target frequency or number of samples using averaging. Args: data: (pd.DataFrame, pd.Series) data to downsample sampling_freq: (float) Sampling frequency of data...
4dca048a77ac1f20d0ee1bac702c48e4311f8900
23,165
def available_commands(mod, ending="_command"): """Just returns the available commands, rather than the whole long list.""" commands = [] for key in mod.__dict__: if key.endswith(ending): commands.append(key.split(ending)[0]) return commands
38a96ca9485e9814ba161550613d3d96db126693
23,166
def retrieve_browse(browse_location, config): """ Retrieve browse image and get the local path to it. If location is a URL perform download. """ # if file_name is a URL download browse first and store it locally validate = URLValidator() try: validate(browse_location) input_filen...
6c5b5e916542db20584205588e5e2929df692b38
23,167
def add_suffix(input_dict, suffix): """Add suffix to dict keys.""" return dict((k + suffix, v) for k,v in input_dict.items())
7dbedd523d24bfdf194c999b8927a27b110aad3e
23,168
from autots.tools.transform import GeneralTransformer from autots.tools.transform import simple_context_slicer from datetime import datetime def ModelPrediction( df_train, forecast_length: int, transformation_dict: dict, model_str: str, parameter_dict: dict, frequency: str = 'infer', predi...
afb3dccc20c2399a50c2564aeb0d1f214d80dd6a
23,169
def make_year_key(year): """A key generator for sorting years.""" if year is None: return (LATEST_YEAR, 12) year = str(year) if len(year) == 4: return (int(year), 12) if len(year) == 6: return (int(year[:4]), int(year[4:])) raise ValueError('invalid year %s' % year)
ced5617772af14a3e438cb268f58ceee3895083d
23,170
def set_stereo_from_geometry(gra, geo, geo_idx_dct=None): """ set graph stereo from a geometry (coordinate distances need not match connectivity -- what matters is the relative positions at stereo sites) """ gra = without_stereo_parities(gra) last_gra = None atm_keys = sorted(atom_keys(gra...
d26248883b90a561c8d70bb8a12be68affe40c2a
23,171
def multiply_MPOs(op0, op1): """Multiply two MPOs (composition along physical dimension).""" # number of lattice sites must agree assert op0.nsites == op1.nsites L = op0.nsites # physical quantum numbers must agree assert np.array_equal(op0.qd, op1.qd) # initialize with dummy tensors and bo...
62e9e250c46d281ccbb39c0ddf1082d45386a1d3
23,172
import json from typing import OrderedDict def build_list_of_dicts(val): """ Converts a value that can be presented as a list of dict. In case top level item is not a list, it is wrapped with a list Valid values examples: - Valid dict: {"k": "v", "k2","v2"} - List of dict: [{"k": "v"...
dfd92f619ff1ec3ca5cab737c74af45c86a263e0
23,173
def add_borders_to_DataArray_U_points(da_u, da_v): """ A routine that adds a column to the "right" of the 'u' point DataArray da_u so that every tracer point in the tile will have a 'u' point to the "west" and "east" After appending the border the length of da_u in x will be +1 (one new colu...
e9b3e057fb56a998821e84a96b77e00bac4e0923
23,174
def arg(prevs, newarg): """ Joins arguments to list """ retval = prevs if not isinstance(retval, list): retval = [retval] return retval + [newarg]
8d591595add095542ad697b4bd54642a4a14a17c
23,175
def quote_plus(s, safe='', encoding=None, errors=None): """Quote the query fragment of a URL; replacing ' ' with '+'""" if ' ' in s: s = quote(s, safe + ' ', encoding, errors) return s.replace(' ', '+') return quote(s, safe, encoding, errors)
e0a5ba9237550856b695e236e7a457c34f053ba0
23,176
def mod(x, y): """Implement `mod`.""" return x % y
f19c019ed3cf072b1b5d3ec851c14a824c14edb5
23,177
from typing import List def _lower_batch_matmul(op: relay.Call, inputs: List[te.Tensor]) -> te.Tensor: """Lower a batch_matmul using cuBLAS.""" return cublas.batch_matmul( inputs[0], inputs[1], transa=op.attrs["transpose_a"], transb=op.attrs["transpose_b"], dtype=op.che...
2fa7be16c558e0edf9233d699139c004b44a93c2
23,178
from re import S def cross_entropy_loss(inputs, labels, rescale_loss=1): """ cross entropy loss with a mask """ criterion = mx.gluon.loss.SoftmaxCrossEntropyLoss(weight=rescale_loss) loss = criterion(inputs, labels) mask = S.var('mask') loss = loss * S.reshape(mask, shape=(-1,)) return S.make_...
7151ace5b1ac93439defe93a4d6e45002cbfb8a6
23,179
def as_wrapping_formatters(objs, fields, field_labels, formatters, no_wrap=None, no_wrap_fields=[]): """This function is the entry point for building the "best guess" word wrapping formatters. A best guess formatter guesses what the best columns widths should be for the table celldata. It does this ...
1f60c9ebaebb919ab8d4478e029aed649931df8a
23,180
import torch def classification_metrics(n_classes: int = 2): """Function to set up the classification metrics""" logger.info(f"Setting up metrics for: {n_classes}") metrics_dict_train = torch.nn.ModuleDict( { "accuracy": Accuracy(), "recall": Recall(), "precisio...
b876c7ac3da006cf54bc04e91f13de5a35103dab
23,181
def ping(device, address, ttl=None, timeout=None, tos=None, dscp=None, size=None, count=None, source=None, rapid=False, do_not_fragment=False, validate=False, vrf=None, command=None, output=None...
1e13d1af7e9678bc8650bc3173858b148fbedc86
23,182
def find_host(connection, sd_name): """ Check if we can preform a transfer using the local host and return a host instance. Return None if we cannot use this host. Using the local host for an image transfer allows optimizing the connection using unix socket. This speeds up the transfer significantl...
462a380a4df1baac2fb45b071d266c3a6cf6b2d7
23,183
import numpy import scipy def _subSquare(vectors, var, full=False): """ given a series of vectors, this function calculates: (variances,vectors)=numpy.linalg.eigh(vectors.H*vectors) it's a seperate function because if there are less vectors than dimensions the process can be accelerated, it j...
8f588d3f64eaf892a1481983436c13d7c5010f12
23,184
def to_pickle(data): """ This prepares data on arbitrary form to be pickled. It handles any nested structure and returns data on a form that is safe to pickle (including having converted any database models to their internal representation). We also convert any Saver*-type objects back to their norm...
e52dddec911b0ac548daed81452d041aee41f548
23,185
import requests def spot_silver_benchmark_sge() -> pd.DataFrame: """ 上海黄金交易所-数据资讯-上海银基准价-历史数据 https://www.sge.com.cn/sjzx/mrhq :return: 历史数据 :rtype: pandas.DataFrame """ url = "https://www.sge.com.cn/graph/DayilyShsilverJzj" payload = {} r = requests.post(url, data=payload) dat...
8bfcc5d24116231835a41447fb284f346586628e
23,186
def requires_all_permissions(permission, login_url=None, raise_exception=False): """ Decorator for views that defines what permissions are required, and also adds the required permissions as a property to that view function. The permissions added to the view function can then be used by the sidebar ...
e2368c7f32185ebe1ee7cec50625a72b0fe9ec03
23,187
def hasTable(cur, table): """checks to make sure this sql database has a specific table""" cur.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='table_name'") rows = cur.fetchall() if table in rows: return True else: return False
dfdb3db0901832330083da8b645ae90e28cfb26d
23,188
def _check_wkt_load(x): """Check if an object is a loaded polygon or not. If not, load it.""" if isinstance(x, str): try: x = loads(x) except WKTReadingError: warn('{} is not a WKT-formatted string.'.format(x)) return x
457a02cffa7f56e05ad7ca3a8df83f5f719346b7
23,189
def _yielddefer(function, *args, **kwargs): """ Called if a function decorated with :func:`yieldefer` is invoked. """ try: retval = function(*args, **kwargs) except: return defer.fail() if isinstance(retval, defer.Deferred): return retval if not (hasattr(ret...
b226984e1b4845783dc47f187d24482e040cc6c0
23,190
import scipy import warnings def dimension_parameters(time_series, nr_steps=100, literature_value=None, plot=False, r_minmin=None, r_maxmax=None, shortness_weight=0.5, literature_weight=1.): """ Estimates parameters r_min and r_max for calculation of correlation ...
abec1b064b42083b9e60bb2cb4827d7fe8f7b2e9
23,191
import logging import os import subprocess def GetAllCmdOutput(args, cwd=None, quiet=False): """Open a subprocess to execute a program and returns its output. Args: args: A string or a sequence of program arguments. The program to execute is the string or the first item in the args sequence. cwd: I...
97d38ab449d7c9237370ba0cc531a2b2790e36c8
23,192
def seir_model_with_soc_dist(init_vals, params, t): """ SEIR infection model with social distancing. rho = social distancing factor. """ S_0, E_0, I_0, R_0 = init_vals S, E, I, R = [S_0], [E_0], [I_0], [R_0] alpha, beta, gamma, rho = params dt = t[1] - t[0] for _ in t[1:]: ...
dae5ace760055f5bbb78f079b660e8d55587b2fe
23,193
import torch def greeq(data, transmit=None, receive=None, opt=None, **kwopt): """Fit a non-linear relaxometry model to multi-echo Gradient-Echo data. Parameters ---------- data : sequence[GradientEchoMulti] Observed GRE data. transmit : sequence[PrecomputedFieldMap], optional Map(...
4190b82de68f6362bf6cec48e4e88419bab7b0da
23,194
import sympy import warnings def _add_aliases_to_namespace(namespace, *exprs): """ Given a sequence of sympy expressions, find all aliases in each expression and add them to the namespace. """ for expr in exprs: if hasattr(expr, 'alias') and isinstance(expr, sympy.FunctionClass): ...
e90e311aacd9c9c41363badc690ad25c18501251
23,195
def rotICA(V, kmax=6, learnrate=.0001, iterations=10000): """ ICA rotation (using basicICA) with default parameters and normalization of outputs. :Example: >>> Vica, W = rotICA(V, kmax=6, learnrate=.0001, iterations=10000) """ V1 = V[:, :kmax].T [W, changes_s] = basicICA(V1, learnrate, i...
2db4bb0d5c5c5f70c9f7cf5a20b27fd2b146e26f
23,196
import socket def getipbyhost(hostname): """ return the IP address for a hostname """ return socket.gethostbyname(hostname)
9556f537e16fd710a566a96a51d4262335967893
23,197
def reduce_mem_usage(df) -> pd.DataFrame: """DataFrameのメモリ使用量を節約するための関数. Arguments: df {DataFrame} -- 対象のDataFrame Returns: [DataFrame] -- メモリ節約後のDataFrame """ numerics = [ 'int8', 'int16', 'int32', 'int64', 'float16', 'float32', 'float64' ] start_mem = df.memory_u...
b317c85aee9f51d221b3895bcc9ac1a6bc3535f6
23,198
import typing def findparam( parameters: _TYPE_FINDITER_PARAMETERS, selector: _TYPE_FINDITER_SELECTOR ) -> typing.Iterator[_T_PARAM]: """ Return an iterator yielding those parameters (of type :class:`inspect.Parameter` or :class:`~forge.FParameter`) that are mached by the selector....
61da9c7e453d04bf2db9c5f923e815e250da4b53
23,199