content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def embedding_sample(name, tensor, sample_type): """ 转换高维数据的样本到potobuf格式 """ if sample_type == 'text': tensor = np.array(tensor) elif sample_type == 'image': tensor = make_np(tensor) assert tensor.ndim in [3, 4], f'the shape of image tensors must be (K,H,W) or (K,H,W,C), ' \ ...
75f4feb07330aa054a16fce1adcb023c1b4e8b8a
55,206
def size_to_bytes(size, largeur=6): """ Convert a size in a bytes with k, m, g, t...""" if size > 1073741824*1024: return b"%*.2fT"%(largeur, size / (1073741824.*1024.)) elif size > 1073741824: return b"%*.2fG"%(largeur, size / 1073741824.) elif size > 1048576: return b"%*.2fM"%(largeur, size / 1048576.) e...
f05e74d89b710936a8253f13b9e6d804f9004b6b
55,207
from bs4 import BeautifulSoup from typing import OrderedDict def query_to_dict(query): """ Parameters ---------- query : Returns ------- """ r = query_epmc(query) soup = BeautifulSoup(r.text, "lxml-xml") results_dict = OrderedDict() for result in soup.resultList: ...
a6c4633dbf4210e9d8fc9be704d5e1da57015369
55,209
from pathlib import Path def phonons_model_1() -> MEGNetProbModel: """Get a model that has been trained to stage 1 on phonons data.""" source = Path(__file__).parents[1] / "static" / "matbench_phonons" / "stage_1" return MEGNetProbModel.load(source)
e8dca65d2f7f6693d080cbb301462981e23d9576
55,210
import math def parse_ham(fname='wannier90_hr.dat',cutoff=None): """ wannier90 hr file phaser. :param cutoff: the energy cutoff. None | number | list (of Emin, Emax). """ with open(fname,'r') as myfile: lines=myfile.readlines() n_wann=int(lines[1].strip()) n_R=int(lines[2].strip(...
55660c6fd26f4be63f003280b881be45cf15c019
55,211
def get_pm_by_id(id): """ function that is called when you visit /portfolio_manager/get/id/<id> that gets a portfolio manager by id """ token = request.headers.get("token") headers = {"Content-type": "application/x-www-form-urlencoded", "token": token} message, info = verify_token(token) if messag...
b32ba764d698660a154b4a57582efab5ccd85921
55,212
def lcm(a: int, b: int) -> int: """ Least Common Multiple. """ return a * b // gcd(a, b)
48ad022bfdc2a45912c3649e3ee06e6cefe0d5c6
55,213
def make_valid_braille() -> BrailleArray: """ Generate a braille character that is valid """ braille=_make_braille() return braille if _is_valid(braille) else make_valid_braille()
69aee83dc97520942cd77f8209a596ea5cd1a538
55,214
def choose_molecule(): """Saves the final choice of molecule for the end of the game as a tuple of the final molecule's R Group IDs. Pass R group IDs as queries: /choose?r1=A01&r2=B10 :returns: Tuple of the R Group IDs as a json dict. Access tuple with 'chosen_mol' key. :rtype: json dict ""...
60ae2672d9bb506713fd8a5032110d6b50b12a19
55,215
def map_trace_to_names(trace, params): """Map trace to parameter names.""" out = {} allnames = list(params.keys()) + ['prob'] for name in trace.keys(): tmp_dict = {} tmp = np.array(trace[name]) for para_name, values in zip(allnames, tmp.T): tmp_dict[para_name] = value...
d1b288b0dcc38d9d45f98f092ed393a8f332bb57
55,216
def _get_array(coords): """ Return an arcpy.Array() object based on an input GeoJSON coordinates list. """ array_obj = arcpy.Array() #print type(coords[0]) for pnt in coords: geom = _get_point(pnt) array_obj.add(geom) return array_obj
f6d1fc67d07c473fb97b4dd4a2a18bb9eb4242dd
55,217
def get_last_applied_membership_fee(): """ Get the last applied membership fee. :rtype: MembershipFee """ return MembershipFee.q.filter( MembershipFee.ends_on <= func.current_timestamp()) \ .order_by(MembershipFee.ends_on.desc()).first()
c093564bd3e13ed197d18caee207b2cf241a1ccb
55,218
import csv def csv_writer(output_file): """ @brief: Get CSV writer @param output_file: Output file handler @return: CSV writer """ return csv.writer(output_file, delimiter=';', quoting=csv.QUOTE_ALL)
70a5d6dca84ef2b60c3fb742a38fd6b27724ecfb
55,219
import configparser def repo_default_config(): """Defines the config file structure and returns the configparser object""" # config files is of microsoft INI format ret = configparser.ConfigParser() ret.add_section("core") ret.set("core", "repositoryformatversion", "0") ret.set("core", "file...
3b1071caaa0efd967cb075c492544435449e1be2
55,220
def home(): """ home page """ content = u.get_content() return render_template( "home.html", html_tab_title="Villoro", portfolio=content["portfolio_main"], blog=content["blog_main"], **u.get_page("home"), )
9b099c0eb82d871374dbf32dec0cd38c2c934a36
55,221
def section(): """ Populates a single text pane via the section.load view (refreshable via ajax) The text is returned by the get_text() generator method as a series of Text objects. Converted to a list, the generated output looks like: [Text(div_path=('Title', '0'), unit_id='1', ...
d72fe1d9e20ed1539915ea8b8fadbd29c750e71f
55,222
def read_data_catl(path_to_file, survey): """ Reads survey catalog from file Parameters ---------- path_to_file: `string` Path to survey catalog file survey: `string` Name of survey Returns --------- catl: `pandas.DataFrame` Survey catalog with grpcz, abs r...
aa149deb0ffc0bed5c91028a69fe7f459390bcb5
55,223
def _make_spc_mess_str(inf_dct): """ makes the main part of the MESS species block for a given species """ mess_writer = getattr(BLOCK_MODULE, inf_dct['writer']) return mess_writer(inf_dct)
00a773a7bc58f75f4fc65ca434c5a8838afaf504
55,225
def calc_fitness_individual(chromosome, video_list, video_data): """Calculate the "fitness" of an individual chromosome Fitness is the determinant of the covariance matrix of the ts data for each emotion Parameters ---------- chromosome : np.ndarray Dummy-coded chromosome of videos ...
d580f5e0ed6423f9c4bc24db1ffea49fc3f44cfb
55,226
def open_ascii_dataset(outdir, iternumber, **kwargs): """ Wrapper that opens simulation outputs from standard mitgcm outputs. Parameters ---------- outdir: string Output directory iternumber: List or integer or None See xmitgcm iters, can be a iterationnumber or 'all' **kwar...
ebd05d55290caa08ce9d57e53aba5736a0ae4d3c
55,227
import re def extractDirective(lineStr: str): """ :param lineStr: :return: (directive, directiveArgs) """ match = re.search(r'\.[a-zA-z][a-zA-z\d_]+', lineStr) return match if not match else match.group()
390331845733d4f6d5f2c4c8318cbac693730026
55,228
def conv1x1(in_planes, out_planes, stride=1): """1x1 convolution""" return nn.Conv2d( in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
266f975e23eed371d16670c5b50dbbae335a495b
55,229
def main(args): """Run the ``hash`` subcommand.""" hash = get_hash(args.task, args.function_type, args.name) return hash
d2b6b71648b5756e5483b7b69b7355d40635d876
55,230
def nb_device_type(model): """ Look up device type by model name and return id """ json = nb_get("dcim/device-types/", {"model": model}) if json["count"] != 1: bail("failed to find device-type {} in netbox".format(model)) return json["results"][0]["id"]
9c01a9967f0a2af865070b523b3c61be28e5ce8a
55,231
def sat2latlon( sx, sy, sz, lon0=-75.0, Re=6378000.0, Rp=6356000.0, h=3600000.0 ): """ Transforma coordenadas cartesianas con origen en el satelite sx,sy,sz en coordenadas de latitud/longitud En base a 5.2.8.1 de PUG3 Parameters ---------- sx : float, float arr coordenada hac...
0b8c2f56f6d7b0c139080c0f50ec6e35313615ff
55,232
def encode_batch(batch, one_hot_dimention=0): """Takes a batch of string as input and encode it to a numerical batch""" batch_new = np.ndarray((len(batch), len(batch[0])), dtype='int') for i in range(len(batch)): for j in range(len(batch[0])): batch_new[i][j] = vocab.index(batch[i][j...
24ebbd1499d3533b34465ae56eb97aafe4962a3e
55,233
def constant_stress_block(segments, stress): """ A function to calculate P,Mx, and My by line integral along given line segments for a constant stress Parameters ---------- segments: List of two tuples/lists of two floats each segment should be of the form [[x1,y1],[x2,y2]] ...
f2704f582480a389e6ba7a5368f839f81989f0ad
55,234
def _maybe_convert_usecols(usecols): """ Convert `usecols` into a compatible format for parsing in `parsers.py`. Parameters ---------- usecols : object The use-columns object to potentially convert. Returns ------- converted : object The compatible format of `usecols`. ...
6f432b58115a5730aa007ded93bffb4702643fe1
55,235
def make_connect_data(one_data): """ 接收数据,使用特定的字符拼接,返回拼接好的数据 :param one_data: :return: """ datas = ['' if elem == None else elem for elem in one_data ] data = "&#@".join([str(elem) for elem in datas]) # print(data) return data
58a64cc50778d419a292e1c6ba5c55cd1030de47
55,236
import requests def get_token(access_key, access_secret, auth_url="https://deviceserver.creatordev.io/oauth/token"): """ Gets device server access token. """ try: # POST Body Payload for Auth payload = { 'grant_type': 'password', 'username': access_key, ...
bc401bf6ff441aa17311d12137250150aadeb686
55,237
def check_rhat(fit, pars=None, verbose=True): """Checks the potential scale reduction factors, i.e., Rhat values Parameters ---------- fit : StanFit4Model object pars : {str, sequence of str}, optional Parameter (or quantile) name(s). Test only specific parameters. Raises an excepti...
5e4b1d0b1a74c979d9c631a49dd3fe69f4955fdc
55,238
import math def Exponential(x, lb=-1., ub=1.): """ Description: ----------- Dimensions: d Input Domain: ------------ xi ∈ [-1, 1], i = 1, ..., d Global Minimum: -------------- f(x) = -1, x = (0, ..., 0) """ y = 0. for i in range(len(x)): y = y + x[i] ** 2 ...
c1391c1820b17ebbd378c7925e40353c13556833
55,239
import re def main(textlines, messagefunc, config): """ KlipChop func """ pattern = re.compile('([0-9A-F]{4,6})', re.IGNORECASE) result = list() count = 0 for line in textlines(): line = line.replace(':', '') m = pattern.findall(line) for ldev in m: if ...
16e763cb5d9b6be04d439d47ace0c7f93d24657e
55,240
import logging def decode(data, *_): """ >>> data = bytes([5, 65, 66, 67, 68, 69, 70, 250, 55, 2, 65, 66, 67, 252, 53, 128]) >>> decode(data) b'ABCDEF7777777ABC55555' >>> data = bytes([5, 65]) >>> decode(data) b'' >>> data = bytes([128]) >>> decode(data) b'' """ res =...
926410ddb43b8e7c2273e38abbde4464d0041ea1
55,242
from datetime import datetime def calc_last_datetime_from_attribution_window(attribution_window_days: int): """Calculates the last datetime from a attribution window based from the current utc date""" return datetime.now(timezone.utc).date() - timedelta(days=attribution_window_days)
4e0e04362ced7e5c2ac388530577b953f3109f5a
55,243
import pyspark def is_spark_below_2_2(): """ Check if spark version is below 2.2. """ if hasattr(pyspark, "version"): full_version = pyspark.version.__version__ # We only need the general spark version (eg, 1.6, 2.2). parts = full_version.split(".") spark_version = part...
14ff26f12a667504ece03db13faff64b20e278fe
55,244
def allow_fully_supported_version(input_func): """Decorate function by ensuring versions are fully supported by pyIATI. In terms of value: * Valid Decimal Versions will remain unchanged. * Invalid Decimal Versions will cause an error to be raised. * Other values will cause an error to be raised. ...
a2188da17e6b039f84e068090a962beb5b022688
55,246
def update_graphs_politicos(data): """ When compute_data() returns the data read from mongo. The plot and wordcloud of "tab-politicos" will be updated. """ global tpm_politicos, datetime_politicos, wc_politicos, graph_politicos tpm_changed, tpm_politicos, datetime_politicos = \ update_tpm_...
e258511a50fbe4eb8e040760ac6ce5c6860f4c73
55,248
def gumbel_softmax(logits, temperature=1.0, hard=False, dim=1): """Sample from the Gumbel-Softmax distribution and optionally discretize. Args: logits: [batch_size, n_class] unnormalized log-probs temperature: non-negative scalar hard: if True, take argmax, but differentiate w.r.t. soft sample...
26ff37447aac5934a06f685e5ba748fd01436781
55,249
def weight_norm_and_equal_lr(m: T_Module, leak: float = 0., mode: str = 'fan_in', init_gain: float = 1., lr_gain: float = 1., name: str = 'weight') -> T_Module: """ Se...
9e77fe88140e2151e0483088343100d4f34b98e9
55,250
def switch_activate_menu(request, pk): """ Switch active status of a :class:`gestion.models.Menu`. """ menu = get_object_or_404(Menu, pk=pk) menu.is_active = 1 - menu.is_active menu.save() messages.success(request, "La disponibilité du menu a bien été changée") return redirect(reverse('g...
b3feea2cf6818fee87f230cc1851ee2feade5a13
55,251
import json def search(): """ Send search results to browser via SSE(Server-sent events)""" def eventStream(): while True: try: data = q.get(timeout=0.5) except: data = {'msg': 'Cloud Run cold start'} yield "event: images\ndata: {}\n\n".format(json.dumps(data)) return Respo...
92b55388d4f9147e2b7efc38df1400d227ae28b7
55,252
from scipy import sparse def to_scipy_sparse_matrix(G, nodelist=None, dtype=None, weight='weight', format='csr'): """Return the graph adjacency matrix as a SciPy sparse matrix. Parameters ---------- G : graph The NetworkX graph used to construct the NumPy matrix. ...
8d29f8349b71f6a08aa3f27d6365bf4d6bd33de8
55,253
def contour_xy(axes, coord, *data, fill=False, xy_limits=None, xy_pad=0.02, add_lines=False, plot_kw=None, line_kw=None, **kwargs): """ Show data as an contour plot in ax, with slices at x and y in the subplots axy and axx. cnt = ax.contour(*data) plot_x = ...
ba9adfcc930e7f27a9223fd036a8becfc114b912
55,254
from typing import Iterable from typing import Any def nth( x: Iterable[Any], n: int, order_by: Iterable[Any] = None, default: Any = NA, base0_: bool = None, ) -> Any: """Get the nth element of x See https://dplyr.tidyverse.org/reference/nth.html Args: x: A collection of elem...
f1debb5ab8bf7c315b5ad86b781f1466c493a5d6
55,255
def get_bookmarks(): """This method is used to obtain browser bookmarks of all available and supported browsers for the system platform. :return: Object of class :py:class:`browser_history.generic.Outputs` with the data member bookmarks set to list(tuple(:py:class:`datetime.datetime`, str, ...
d2df75f8bc7e1d33d69fe26fec87669e2bc58353
55,256
import struct import logging def read_iincal(prefix_files_dic, week_orrun_flag, day_orrun_flag, day_is, y, m): """ LEVER ARM DETERMINATION. Reads the iincal_ pospac binary file and returns a pandas dataframe with columns 'Time', 'X', 'Y', and 'Z', where Time is in adjusted GPS seconds and X, Y, and Z ...
35eb06709e1c6f00b86c02dbd74bab8ee89a678c
55,257
def evaluate(hex_str: str) -> int: """Evaluate a hex string.""" packet = parse(hex_str) return packet.evaluate()
c70646d00d9ee9a5a26c85f50a58182697882dcd
55,258
def excess_entropy_fast(text: str, H_single, H_pair): """ Calculates excess entropy of given string in O(n) time complexity :param text: an input tokenized string :param H_single: a function that calculates H(i, x_i) :param H_pair: a function that calculates H(x_i | x_{i-1}) = H(i, x_{i-1}, x_i) ...
1e590f7577fa9b9185160eea26d3900476f56bf0
55,259
from typing import Set import ast def _h5attr2set(attr: str) -> Set[str]: """Convert an HDF5 attribute to a list of strings""" if not attr or attr == "set()": return set() return ast.literal_eval(attr)
55aa07126efe42fa1f3437ce6206e72db58c7fd3
55,260
def add_maps(sky_map, noise_map): """Check the inputs and return a sum of sky and noise. """ print('Adding maps') if np.atleast_1d(sky_map).size == 1: print(' Sky map is empty, using the noise map') return noise_map if np.atleast_1d(noise_map).size == 1: print(' Noise ma...
e92432f1a87246dc1843879abf90d6dba6c3974c
55,261
def test_base_circle_id_coords_params(): """ Params for test_base_circle_id_coords. """ dfs = [ pd.DataFrame( { "x": [10, 15, 123, -4], "y": [2, 1, 1, -4], "name": ["a", "b", "c", "d"], "radius": [25.0, 25.0, 25.0, 25.0]...
58899b88ccc18345c00b9b2e30382bad6ccb082a
55,262
def velmodellayers_sdsu(ifile): """ Input a SDSU type velocity model file and return number of layers as defined by SDSU. This is designed for use in the SDSU code which required the number of layers in a file. """ lincount = 0 infile = open(ifile, "r") for _ in infile: lincount ...
922f9443b3b30cbe58639ab51ab9f183205d0dec
55,263
def forms_for_user(user_is_clerk, tally_id=None): """Return the forms to display based on whether the user is a clerk or not. Supervisors and admins can view all unreviewed forms in the Audit state, Clerks can only view forms that have not been reviewed by the audit team. :param user_is_clerk: True if...
0765a11600dfdbfe2576a65ca0dad126185f5863
55,264
import warnings def read_cmfgen_density(fname): """ Reading a density file of the following structure (example; lines starting with a hash will be ignored): The first density describes the mean density in the center of the model and is not used. The file consists of a header row and next row contains ...
b1fd91f0015a61dcdcc7b6f3b23a37496fff0b8a
55,265
import math def grid_desired_size( grid, media_info, width=Config.contact_sheet_width, horizontal_margin=Config.grid_horizontal_spacing): """Computes the size of the images placed on a mxn grid with given fixed width. Returns (width, height) """ desired_width = (width -...
e5b6e5b10ab8c3928b315924b105f9d987fade93
55,266
import logging def get_remote_chart_versions(deps: dict, verbose: bool = False) -> dict: """Get dependency versions from the remote hosts Args: deps (dict): The dependencies to check and their host URLs dependency (str): The dependency to get a version for verbose (bool, optional): Pr...
afbd895879a331c9d3d6a93af43aa5022f1d4317
55,268
from typing import Any def to_qualified_name(obj: Any) -> str: """ Given an object, returns its fully-qualified name, meaning a string that represents its Python import path Args: - obj (Any): an importable Python object Returns: - str: the qualified name """ return obj._...
45824d1f84a96f254274e7fe40f2ed9546ccb346
55,269
def factorial(n): """Factorial function implementation.""" return n * factorial(n-1) if n else 1
3ebaa4cd6c38773e8c8a6e1c247e0163f0d7d50a
55,271
def get_index(search, names): """ Find index matching search in names list of 'Key|Value' """ for name_index, name in enumerate(names): if search == name.split('|')[0]: return name_index return None
fbfc6b71b75172e2980a604f53e602c9b3cb9a84
55,272
from typing import Dict from datetime import datetime def pass_objectives(preferences: Dict) -> Dict: """Set all objectives into a passing state""" for bool_obj in BOOL_OBJECTIVES: preferences[bool_obj] = "true" for int_obj, dankvalue in INT_OBJECTIVES.items(): preferences[int_obj] = dankv...
0d04e076e75c76e47875883fc268db74a3577d7b
55,273
def get_signal(prob, num_classes, pred=None): """ SNIPPET 10.1 - FROM PROBABILITIES TO BET SIZE Calculates the given size of the bet given the side and the probability (i.e. confidence) of the prediction. In this representation, the probability will always be between 1/num_classes and 1.0. :param p...
24917d583e89481a89e5f4a65ebcb4da59be1745
55,274
def get_target_sound_definition(sound_key): """ Return the target sound definition as a dictionary for the given sound key. :param sound_key: str key for this target sound definition e.g SND_ANIMAL001_ZONE. Defined in target_sounds.json """ return all_target_sound_definitions()[sound_key]
2d7fbd1426bbc21e0ad51e15484f8882a60c3ab2
55,276
def edit_split_taxonomy( ranks: dict, split_taxa_pd: pd.DataFrame) -> pd.DataFrame: """ Parameters ---------- ranks split_taxa_pd """ if len(ranks) == split_taxa_pd.shape[1]: split_taxa_pd = split_taxa_pd.rename(columns=ranks) else: alpha = 'ABCDEFGHIJKLMN...
e75392c8abf4125a3ff643bf7307ac9d09516b8a
55,277
import numpy import csv def create_low_test_image_from_s3(npixel=16384, polarisation_frame=PolarisationFrame("stokesI"), cellsize=0.000015, frequency=numpy.array([1e8]), channel_bandwidth=numpy.array([1e6]), phasecentre=None, fov=20) -> Image: ""...
17c7cb0367a39c76c328787b6604566554efaca3
55,279
def readtxt(fn, delimiter=None): """ Read in a generic text file containing a 2D flux array as delimited values. Inputs: fn (str): Full file name. Outputs: flux2D (array): Numpy 2D array of proton flux at the detector (counts/bin). flux2D_ref (array): RE...
4ec5f2043498c423c5901d457bf76dd0238227b9
55,280
def compile_opinion_text(name, symbol, sentiment): """Generates an opinion on a tweet.""" return "%s %s %s" % (name, get_sentiment_emoji(sentiment), symbol)
bcc8224b68efa53a8301b5f982c0368547528fd8
55,281
from datetime import datetime import pytz def get_max_timestamps(nwsli): """ Fetch out our max values """ icursor = ISUAG.cursor() data = {'hourly': datetime.datetime(2012, 1, 1, tzinfo=pytz.FixedOffset(-360)), '15minute': datetime.datetime(2012, 1, 1, ...
0c1811da90a15897de868035dc424ba89d656014
55,283
def get_salsa_estimator_from_data_and_hyperparams(X_tr, Y_tr, kernel_type, add_order, kernel_scale, bandwidths, l2_reg): """ Returns an estimator using the data. """ problem_dim = np.array(X_tr).shape[1] kernel = get_salsa_kernel_from_params(kernel_type, add_order...
a056cd3d3ee909a024f15a1597eeaa759ed66b7d
55,284
def create_droid(data): """ This function takes one parameter, a dictionary, represnting a person and returns an instance of the Droid class. Parameters: data (dict): a dictionary representing a person Returns: Droid object: an instance of the Droid class """ return Droid( ...
bbda0aa50d04774fc9b9c5656a8fd7914d0337ff
55,285
from functools import WRAPPER_ASSIGNMENTS def temporarily_replace_context_keys(context, func, assigned=DEFAULT_ASSIGNED): """ Decorate a function - temporarily updates the context keys while running the function Updates the context if the function is marked by @binds decorator. """ binds = getatt...
059dda6b8068395ac6495a7ae927741bbae25a87
55,286
from pathlib import Path def timebin_dur(spect_path, spect_format, timebins_key, n_decimals_trunc=5): """get duration of time bins from a spectrogram file Parameters ---------- spect_path: str, Path path to spectrogram file. spect_format : str format of file containing spectrogram...
21a2a4d8cafb9e396e1729c7d23756da978c844c
55,287
def get_premature_df() -> pd.DataFrame: """Get premature miRNA dataframe.""" return ensure_df( PREFIX, PREMATURE_URL, version=VERSION, names=['premature_key', 'mirbase_id', 'mirna_name'], usecols=[0, 1, 2], index_col=0, dtype=str, )
323a060a2626a27d27d98a75e43c61d2adfd53c8
55,288
def compute_coherence(cross_spec, power_ci, power_ref, mean_rate_ci, mean_rate_ref, meta_dict, n_range): """ Compute the coherence of the cross spectrum. Coherence equation from Uttley et al 2014 eqn 11, bias term equation from footnote 4 on same page. Parameters ---------- cross_spec :...
2c87dc4095a9825670acc0a4a4a61407de5463f9
55,289
from typing import List def pin_name_deannotate(annotated_pin_name: Text) -> Text: """Return only the pin name from an annotated pin name.""" pair: List[Text] = annotated_pin_name.split(':') return pair[0][1:]
0c54119aa255b02f672e008f808ab6c5304aa615
55,290
def getCity(id): """Return all targets --- parameters: - name: id in: path type: integer required: true default: 4 responses: 200: description: Return a specific waypoint """ return datamanger.readTableAsJson(query=SELECTS['waypoint'],data={'id...
b7a74a3582b348f8576b32e6eb8d94d04e171a61
55,291
def whitelist(chain, maximal_number_of_auction_participants): """whitelisted well-funded accounts, accounts[0] is not in the whitelist""" # some other tests do also call add_account and we do not want to # include them (it just takes longer) whitelist = list(chain.get_accounts()[1:10]) + [ chain...
5bc693db2eacb5ab8a98c025e279e464a96453f6
55,292
def separate_callback_data(data): """Separa i dati in entrata""" return [i for i in data.split(";")]
0cfef1abf910193a7ad8015862614f3659dd40d5
55,293
def get_constant_term_design_matrix(data, ids=None): """ Construct the portion of the design matrix relevant for the linear parameters of The Joker beyond the amplitude, ``K``. """ if ids is None: ids = np.zeros(len(data), dtype=int) ids = np.array(ids) unq_ids = np.unique(ids) ...
497ee8f0b51f8a592dcd840e06f16d7945d27cdc
55,295
def _upgrading(version, current_version): """ >>> _upgrading('0.9.2', '1.9.2') False >>> _upgrading('0.11.3', '0.11.2') True >>> _upgrading('0.10.2', '0.9.2') True >>> _upgrading('1.1.3', '1.1.4') False >>> _upgrading('1.1.1', '1.1.1') False >>> _upgrading('0.9.1000', '50...
1ff478ed3c55687ddaa0392f6a071915750f8dfa
55,296
def main(*args): """ Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: list of unicode """ pageName = '' summary = None generator = None options = {} # read command line parameters ...
b1721027ccc0e904b73361b3aa0f2b42ff1f3478
55,298
def home(): """Render the home page which displays the UUID of the day.""" uuid = repository.get_uotd() today = date.today().strftime("%A, %d %B %Y") return render_template("index.html", uuid=uuid, today=today)
47332d553c554f8be73ba64ddd26c348392cf210
55,299
from typing import Optional async def line_notify_redirect(uid: Optional[str] = "") -> RedirectResponse: """轉址至 LINE Notify 綁定頁面 Args: uid (Optional[str], optional): 使用者 LINE ID. Defaults to "". Returns: RedirectResponse: LINE Notify 綁定頁面 """ link = config.lotify_client.get_auth_...
091f991075109ce9ec16e1c4e47061be615887dd
55,300
def get_version(): """ get a comprehensive git version and report it in the package at build-time. :param : :return str: """ return ( get_tag() + "+" + get_commit_count_after_tag() + "." + get_commit() + (".dirty" if dirty() else "") )
926133e4a4c4992601bcd848538a14ab3db83b9b
55,301
def add_x_to_plotting_options(plotting_options: dict, option_cat: str, x: str, defaultvalue): """ don't override given plotting_options, meaning it only add the default value if value not already defined in plotting_options """ if plotting_options is None: plotting_options = {} if option...
48ff564e58b35b8dc38d529fb27188556401c81c
55,302
def get_tendency_name_with_incompatible_units(input_properties, tendency_properties): """ Returns False if there are any keys shared by the two properties dictionaries which indicate units that are incompatible with one another, and True otherwise (if there are no conflicting unit specifications). "...
44dd8dc43a6d89ef897172cf6b0c7894edd98a44
55,304
def register(request): """ return signin.html :param request: None :return: signin.html """ return render(request, "signup.html")
046e0af87604e21547573e49b2e1fcfcbe0c4c61
55,305
def calc_repairs(scenario, years): """RISK: Repairs of equipment on the farm Args: scenario (object): The farm scenario years (int): No. of years for analysis Returns: repair (list): Repair costs taken as a percentage of capital costs for facilities and lighting...
1a56b5154e228ec2c78debc50d1c94f24a595b5c
55,306
def explain_pair(grid,digs,locs): """Concoct explanation for application of pair rule.""" d1,d2 = digs g1 = [g for g in groups if grid.locations[d1] & g.mask == grid.locations[d1] & locs] g2 = [g for g in groups if grid.locations[d2] & g.mask == grid.locations[d2] & locs] for g i...
20edeb5af1af0ce8a3fa6d654894328e77cb59b6
55,307
def decimal_function(number): """ It converts a binary number into a decimal number by using a re and a recursion function. """ decimal_sum = 0 #regular expression substitution transform = re.sub("(]?\w+)(\w{1})", '\g<1>.\g<2>',str(number)) for arg in str(number): if ...
699594a298c75d23594e3c6e7c298df1b76ce4db
55,308
def normalize(x, points): """Min-Max normalization""" x = np.array(x) xmax = get_max(points) xmin = x.min(axis=0) return (x-xmin)/(xmax-xmin)
65fcf471cc161feccfb05cc04d1caa07fbf2d6a6
55,310
def read_data(filepath, channel): """ Read the data file at a specific data channel. Parameters ---------- filepath : path Path to the .mat file. channel : str Name of the channel in the .mat file. Returns ------- dataobject : DataObject The DataObject containing the data from the specific channel. ...
fdd4dbeb442c4c99bddeb146f9113f55d2a84367
55,311
def drivecount(pool_name, count=None, p5_connection=None): """ Syntax: Pool <name> drivecount <count> Description: Sets the drives per stream the pool is allowed to use Return Values: -On Success: the drivecount as string """ method_name = "drivecount" return exec_nsdchat([module_name...
94c4eea8c63790fc76afc2530981677a255b0218
55,312
def divide(a, b): """ Calculates the division of a by b. If the denominator equals 0, then the result is plus infinity. -------------------- args: a (float): the numerator b (float): the denominator -------------------- return: (float): the division of a by b --...
2e7f42ed3c92c6ea95798295030262b746e48653
55,313
def fake_ml_model_data(n_models: int = 1) -> pd.DataFrame: """Generate mock data for raw ML model info from the Augury app.""" return pd.DataFrame( [ { "name": FAKE.company(), "prediction_type": np.random.choice(["margin", "win_probability"]), ...
a8d5485e3869463279ffedcc4b00b31823abd3f7
55,314
def add_plot(df, num_subplots, axes, field="bg", subplot=2): """ Parameters ---------- df: dataframe the dataframe adding data from for the plot num_subplots: int number of subplots (1-indexed) axes: axes object the axes of the matplotlib figure field: basestring ...
86f256afea9b2c0b45b2e248e6cd545055fea30b
55,315
def multi_call(*methods, **kwargs): """ Invoke multiple Netmiko methods at once, and return their output, as list. methods A list of dictionaries with the following keys: - ``name``: the name of the Netmiko method to be executed. - ``args``: list of arguments to be sent to the Netm...
2a82bcffc796a8f137ee3c87126b57d3976b6623
55,316
def color_category(category): """ adds color to a category and puts it in brackets """ if Opts.Print.no_color: return '['+category+']' color = { 'progress':'\033[32m', 'get':'\033[1;33m', 'download':'\033[1;36m', 'convert':'\033[36m', 'parse':'\03...
c8f2aa15b3d4b3c841b6f25d8a66924d89da586b
55,317
from typing import Counter def uniquify(strings): """ Return a list of unique strings. The string at i'th position will have the same prefix as strings[i] with an appended suffix to make the item unique (if necessary). >>> uniquify(["cat", "dog", "cat"]) ["cat 1", "dog", "cat 2"] """ ...
658d0bb16fdca3876be85c2bfbc4da956e35e9b7
55,318
def nominal_values(arr): """ Return the nominal values of the numbers in NumPy array arr. Elements that are not numbers with uncertainties (derived from a class from this module) are passed through untouched (because a numpy.array can contain numbers with uncertainties and pure floats simultane...
f779be5e71db40b35e1a96c2af21adaa66d03e93
55,319