content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def cal_covered_users(positions, heat_map, radius): """ :param positions: $k$ positions array of !!!(y, x)!!! :param heat_map: grid data with count :param radius: 0(1 grid), 1(8 grids), 2(25 grids) :return: coverage score """ row_num, col_num = heat_map.shape mask = np.zeros(heat_map.sha...
52e3fec6b7aa01c9882c15ca3331b3199fa554a2
3,656,200
from typing import Union import pathlib def certificate_from_file( filename: Union[str, pathlib.Path], format=OpenSSL.crypto.FILETYPE_PEM, ) -> TS.X509: """Load an X509 certificate from ``filename``. :param filename: The path to the certificate on disk. :param format: The format of the certificat...
1cc3cb514454118ed6af9257b35aa39586bce31b
3,656,201
def get_welcome_response(session): """ Welcome the user to my python skill """ card_title = "Welcome" speech_output = "Welcome to my python skill. You can search for GitHub repositories. " # If the user either does not reply to the welcome message or says something # that is not understood...
d90bbd14bef29f1d7400042bbc593e4bb63b8713
3,656,202
import numpy as np def rotate_quaternion ( angle, axis, old ): """Returns a quaternion rotated by angle about axis relative to old quaternion.""" # Note that the axis vector should be normalized and we test for this # In general, the old quaternion need not be normalized, and the same goes for the resul...
ccc67dbcd2153b40a4e4c560d423d4c495912d8e
3,656,203
import os def apogeeSpectroReduxDirPath(dr=None): """ NAME: apogeeSpectroReduxDirPath PURPOSE: returns the path of the spectro dir INPUT: dr= return the path corresponding to this data release OUTPUT: path string HISTORY: 2014-11-25 - Written - Bovy (...
172a9919b0b7aef0dcdd9486f51900a9a8c2b28f
3,656,204
def rochepot_dl(x, y, z, q): """ Dimensionless Roche potential (:math:`\\Phi_n`, synchronous rotation) More massive component (:math:`m_1`) is centered at (x,y,z) = (0,0,0). Less massive component (:math:`m_2`) is at (1,0,0). The unit of length is the distance between the objects. Both objects ...
f3d15ea27e6b4c476d345fa8af254b2a14cbdfbc
3,656,205
def health_check(config): """ Tests the API to ensure it is working. """ itglue = ITGlue(config['api_key'], config['itglue_host']) try: itglue._make_request('organizations', {}) return True except: return False
02b9a582b506f590adcdcdbd661abbc7aec52d26
3,656,206
import io import time def capture_image(resolution=(1024, 768), size=(320, 240), sleep=2): """ Captures image from raspberry pi camera resolution -- resolution of capture size -- size of output sleep -- sleep time in seconds """ stream = io.BytesIO() with picamera.PiCamera() as camera:...
c8967d6bce5f953d11878fb31fa02dbffbe4e283
3,656,207
import numpy def MLVR(XDATA,YDATA,xreference=0,residual=1,xlabel='',ylabel='',title='',alpha = 0.01,iters = 1000,plot=1): """Does Multivariant Linear Regression properties: XDATA = The Feature Dataframe YDATA = The Target Dataframe xreference = 1/0 -> The column index in XDATA for ploting graph xlabel = La...
84509c2e8ccc9b4f52b5d90432e74a18da226b0a
3,656,208
def FilterAndTagWrapper(target, dontRemoveTag=False): """\ Returns a component that wraps a target component, tagging all traffic going into its inbox; and filtering outany traffic coming out of its outbox with the same unique id. """ if dontRemoveTag: Filter = FilterButKeepTag else:...
045cdd4f0716ba187211fbb1a4536f1f4c863bc1
3,656,209
from typing import Union def format_time(seconds: Union[int, float]) -> str: """Convert the seconds to human readable string with days, hours, minutes and seconds.""" s = int(np.rint(seconds)) if s < 60: return "{0}s".format(s) elif s < 60 * 60: return "{0}m {1:02}s".format(s // 60, s...
f50b7d96a91e6e261169f0f0c9d71186e3c208fe
3,656,210
def run_model(df, i, name, gscv, calibrate=True): """Given customercode values in dict_folds, 1. create balanced dataset 2. split into train, test sets 3. run grid search 4. get probability scores 5. calibrate as directed 6. find optimal cutoff from precision-recall 7. return predictions...
0f5513b7e4117580dd297ee5e9b7a88afc691b3a
3,656,211
import os from functools import reduce def prepare_runkos(main_dir, discard_file=None): """Identify the positions with variations between 0.2 to 0.8 in the training population and calculate the mean and std for the variation. """ THRESHOLD_DROPNA = 32 # more than 40 columns should have a value not a...
91ec730e31ea90d47239c00a00d444fbb99e3f69
3,656,212
import re def extract_date(db): """Extract Release Date from metadata and convert it into YYYY MM format""" date_pattern = 'releaseDate\":(\d{9,10})' def format_date(x): """Takes epoch time as argument and returns date in YYYY MM format""" date = re.search(date_pattern, x) if dat...
9d4d8c19846a49967f9e3deb3be8808df9d69812
3,656,213
def split_test_image(aa): """ Separate image created by mk_test_image into x,y components """ if aa.dtype.kind == 'f': y = np.round((aa % 1)*1024) x = np.floor(aa) else: nshift = (aa.dtype.itemsize*8)//2 mask = (1 << nshift) - 1 y = aa & mask x = aa >>...
4a06a0c0fb80dfcb8a58d9509971bfdc0b026d27
3,656,214
def sphdist(ra1, dec1, ra2, dec2): """measures the spherical distance between 2 points Inputs: (ra1, dec1) in degrees (ra2, dec2) in degrees Outputs: returns a distance in degrees """ dec1_r = deg2rad(dec1) dec2_r = deg2rad(dec2) return 2. * rad2deg( arcsin( sqrt( ( sin((dec1_r - dec2_r) / 2)) ** 2 + cos(d...
517f7c67370c6e065c8860b2be59470a2801567d
3,656,215
def parse_kwargs(kwargs, a_list): """ extract values from kwargs or set default """ if a_list is not None: num_colors = len(a_list) default_colors = generate_colors(num_colors) else: num_colors = 1 default_colors = 'k' logscale = kwargs.get('logscale', [False, Fa...
3f1006a8f638b3304ec6aa975346be1a4b6e8189
3,656,216
def talib_WCLPRICE(DataFrame): """WCLPRICE - Weighted Close Price 加权收盘价""" res = talib.WCLPRICE(DataFrame.high.values, DataFrame.low.values, DataFrame.close.values) return pd.DataFrame({'WCLPRICE': res}, index=DataFrame.index)
6e2d4530fcb33d64b9fbe8a3f0a8a5d64c8f8107
3,656,217
def is_pi_parallel(ring1_center: np.ndarray, ring1_normal: np.ndarray, ring2_center: np.ndarray, ring2_normal: np.ndarray, dist_cutoff: float = 8.0, angle_cutoff: float = 30.0) -> bool: """Check if two aromatic rings form a...
def4eaba9e25e9034fce7559041e5142f82fc3c8
3,656,218
def _fetch_alleninf_coords(*args, **kwargs): """ Gets updated MNI coordinates for AHBA samples, as shipped with `alleninf` Returns ------- coords : :class:`pandas.DataFrame` Updated MNI coordinates for all AHBA samples References ---------- Updated MNI coordinates taken from ht...
dae30a0f5404151a3e7d82f129ff36cfec14caa0
3,656,219
from typing import List from typing import Union from typing import DefaultDict from typing import Dict from typing import Tuple def get_classes_for_mol_network(can: canopus.Canopus, hierarchy: List[str], npc_hierarchy: List[str], ...
6808a751ed1873b7fb573bb3ecc55586d94590b1
3,656,220
def list_books(books): """Creates a string that, on each line, informs about a book.""" return '\n'.join([f'+ {book.name}: {book.renew_count}: {book.return_date}' for book in books])
fce770a39def7f40ed12820a578b4e327df7da43
3,656,221
def getHSPLNamespace(): """ Retrieve the namespace of the HSPL XML. @return: The namespace of the HSPL XML. """ return HSPL_NAMESPACE
481db5781ff9d0b4a4e4702cccafb088379e38a4
3,656,222
def add_lead_zero(num,digit,IgnoreDataManipulation=False,RaiseDataManipulationError=False,DigitMustAtLeastTwo=False): """Add leading the letters '0' to inputted integer 'num' according to defined 'digit' and return as string. Required keyword arguments: - num (int) : Integer (can be positive, zero, or negative) ...
ae3cffa2470a2acf5900a41b342366fb7c6e92da
3,656,223
def _attach_monitoring_policy_server(module, oneandone_conn, monitoring_policy_id, servers): """ Attaches servers to a monitoring policy. """ try: attach_servers = [] for _server_id in servers: server_id = get_server(oneandone_conn, _server_id) attach_server = on...
bf096804ec6be47fa4e41c9f4e50d51313f8ef3f
3,656,224
from typing import Union def get_generator_contingency_fcas_availability_term_2(data, trader_id, trade_type, intervention) -> Union[float, None]: """Get generator contingency FCAS term 2""" # Parameters lower_slope_coefficient = get_lower_slope_coefficient(data, trader_id, trade_type) if lower_slope...
8ec9c76c1941713511f8b472c4649954fd725d58
3,656,225
def format_pvalue(p_value, alpha=0.05, include_equal=True): """ If p-value is lower than 0.05, change it to "<0.05", otherwise, round it to two decimals :param p_val: input p-value as a float :param alpha: significance level :param include_equal: include equal sign ('=') to pvalue (e.g., '=0.06') or...
aa6506b14b68746f4fa58d951f246321e8b5a627
3,656,226
def _compute_y(x, ll): """Computes y.""" return np.sqrt(1 - ll ** 2 * (1 - x ** 2))
773a0695676e43984bb0ca8c1d8af2e0bc3bb4fd
3,656,227
def create_axis(length=1.0, use_neg=True): """ Create axis. :param length: :param use_neg: If False, Only defined in Positive planes :return: Axis object """ # Defining the location and colors of each vertex of the shape vertices = [ # positions colors -length...
fe9c9d49de786147a382e1fda1e6ab92d26a1fe9
3,656,228
def genmatrix(list, combinfunc, symmetric=False, diagonal=None): """ Takes a list and generates a 2D-matrix using the supplied combination function to calculate the values. PARAMETERS list - the list of items combinfunc - the function that is used to calculate teh value in a cell. ...
b7d8ebc916f57621a20c371139162cb0504470cd
3,656,229
def get_all_raw_codes_by_area(area: EmisPermArea) -> list: """ Returns a list of code names for all permissions within a logical area, for all possible modes. """ return get_raw_codes_by_area( area, EmisPermMode.CREATE | EmisPermMode.UPDATE | EmisPermMode.VIEW )
d5887af92ba5fb7c373078dca84a8f9e74a089dc
3,656,230
def cartesian_pair(df1, df2, **kwargs): """ Make a cross join (cartesian product) between two dataframes by using a constant temporary key. Also sets a MultiIndex which is the cartesian product of the indices of the input dataframes. See: https://github.com/pydata/pandas/issues/5401 :param df1 dataf...
e4ec1526f7a7906c5349bff20f5d4f83244c8878
3,656,231
def get_cases_by_landkreise_3daysbefore(): """ Return all Hospitals """ hospitals_aggregated = db.session.query(CasesPerLandkreis3DaysBefore).all() return jsonify(__as_feature_collection(hospitals_aggregated)), 200
0442f66ff78549617dd582bc0d1529c0041e7edb
3,656,232
def shape_list(x, out_type=tf.int32): """Deal with dynamic shape in tensorflow cleanly.""" static = x.shape.as_list() dynamic = tf.shape(x, out_type=out_type) return [dynamic[i] if s is None else s for i, s in enumerate(static)]
80eea7ccdd4ebfa5a3318fb6070ec996df5b4972
3,656,233
import ast import os import re import subprocess # noqa import sys def coerce_file(fn): """Coerce content of given file to something useful for setup(), turn : .py into mock object with description and version fields, .md into rst text. Remove images with "nopypi" alt text along the way. :u...
4fdd44f476186c62d704bcf549534f154fb75c35
3,656,234
import json from typing import cast def load_config( config_file: str, print_warnings: bool = False ) -> InfestorConfiguration: """ Loads an infestor configuration from file and validates it. """ try: with open(config_file, "r") as ifp: raw_config = json.load(ifp) except: ...
b1d4a1385bb8855530f7043ddff5cc8d2f48be79
3,656,235
def what_do_you_mean_response(ctx: Context) -> REPLY_TYPE: """Generate response when we are asked about subject of the dialog Returns: template phrase based on previous skill or intent or topic confidence (can be 0.0, DONTKNOW_CONF, UNIVERSAL_RESPONSE_CONF, SUPER_CONF) human attributes (...
694b693d5ed1595781fdfe975f716cca4ff2dcd2
3,656,236
def procrustes(X,Y): """Finds the optimal affine transformation T to minimize ||x-Ty||_F Parameters ---------- x - reference, shape(x)=nxd where n is number of samples and d is dimension y - to be aligned, shape(x)=nxd Returns ------- Z - the transformed y TODO: return...
eae8b396c190286a426e3eed1726c4c0f75f2c49
3,656,237
import warnings def get_market_tops(symbols=None, **kwargs): """ MOVED to iexfinance.iexdata.get_tops """ warnings.warn(WNG_MSG % ("get_market_tops", "iexdata.get_tops")) return TOPS(symbols, **kwargs).fetch()
4c94e35f447762a3d3ed9c076708450f1d1f200b
3,656,238
def get_query_results(query_execution_id): """Retrieve result set from Athena query""" athena_client = SESSION.client('athena') result_set = [] query = athena_client.get_query_execution(QueryExecutionId=query_execution_id) logger.debug(query) query_state = query['QueryExecution']['Status']['Sta...
c0288ceca458a6805c5f8a4e5da5e8e7a1f36b69
3,656,239
from pathlib import Path def reduce_output_path(path=None, pdb_name=None): """Defines location of Reduce output files relative to input files.""" if not path: if not pdb_name: raise NameError( "Cannot save an output for a temporary file without a PDB" "code ...
0add37e0d5b71998112045af34aba4c0a17310f9
3,656,240
import os import requests def get_recommended_meals(): """[summary] Returns: [type]: [description] """ url = "https://themealdb.p.rapidapi.com/randomselection.php" headers = { "x-rapidapi-host": "themealdb.p.rapidapi.com", "x-rapidapi-key": os.getenv("RAPIDAPI"), } ...
6d7376e94f4bad9767d81537b8ddb4808d71ca01
3,656,241
def link_discord(request: HttpRequest): """Page to prompt user to link their discord account to their user account.""" skip_confirmation = request.GET.get("skip-confirm") if skip_confirmation and skip_confirmation == "true": return redirect("discord_register") return render(request, "link_disco...
05aba45b508e5a23cf62f5791a04e2525bbbbae0
3,656,242
import six import functools def rpc(f=None, **kwargs): """Marks a method as RPC.""" if f is not None: if isinstance(f, six.string_types): if 'name' in kwargs: raise ValueError('name option duplicated') kwargs['name'] = f else: return rpc(**kw...
37ac21bd800bb202a78542636e9249ac3519c54e
3,656,243
def fig_fits_h(fig, y): """Lista ut of figuren *fig* far plats pa hojden pa skarmen vid position *x*, *y* """ _, h = _get_max_width() win_h = fig.window.winfo_height() result = (y + win_h) < h return result
4e3254d7a4fad2d8de816b36aacbfd069378c1fc
3,656,244
import os def find_executable(name): """ Find executable by ``name`` by inspecting PATH environment variable, return ``None`` if nothing found. """ for dir in os.environ.get('PATH', '').split(os.pathsep): if not dir: continue fn = os.path.abspath(os.path.join(dir, name)...
dd4b10e4b043715d211bb9be2d2c78d0218f6a86
3,656,245
def index(): """ Handler for the root url. Loads all movies and renders the first page. """ if path_set(): load_movies() return flask.render_template('main.html')
8f5c3295175cfd45b3604d523ac6b7de086702e9
3,656,246
def __hitScore__(srcMZ, targetMZ, srcRT, targetRT, parameters): # type: (float, float, float, float, LFParameters) -> float """Return the hit score of the target frame for the given source frame. Keyword Arguments: srcMZ -- source m/z targetMZ -- target m/z srcRT -- ...
1b35cfbb2f1e028ccbb53d4fed16459d5a469ac1
3,656,247
def compute_propeller_nonuniform_freestream(prop, upstream_wake,conditions): """ Computes the inflow velocities in the frame of the rotating propeller Inputs: prop. SUAVE propeller tip_radius - propeller radius [m...
c7dc48066356e4d79e512812976a3e1a80b16749
3,656,248
def _expect_const(obj): """Return a Constant, or raise TypeError.""" if obj in (0, "0"): return ZERO if obj in (1, "1"): return ONE if obj in ("x", "X"): return LOGICAL if obj == "?": return ILLOGICAL if isinstance(obj, Constant): return obj raise Type...
33aff48ff285b89f36d28a99148afeea97302a05
3,656,249
def _eval_input_receiver_fn(tf_transform_output, schema, label_key): """Build everything needed for the tf-model-analysis to run the model. Args: tf_transform_output: A TFTransformOutput. schema: the schema of the input data. label_key: the name of the transformed label Returns: EvalInputReceiver ...
60f0a6cf9a87894f7e37495b8b4e9f7bd9e85e22
3,656,250
def get_lpar_names(adp): """Get a list of the LPAR names. :param adp: A pypowervm.adapter.Adapter instance for the PowerVM API. :return: A list of string names of the PowerVM Logical Partitions. """ return [x.name for x in pvm_lpar.LPAR.search(adp, is_mgmt_partition=False)]
4009ed95b23ba6a35cbe38e1354f109e29fb7fc7
3,656,251
def init_mlp(in_dim, out_dim, hidden_dim, num_layers, non_linearity=None, bias=True): """Initializes a MultilayerPerceptron. Args: in_dim: int out_dim: int hidden_dim: int num_layers: int non_linearity: differentiable function (tanh by default) bias (bool) R...
a2d5b8535af5d363df459cf0d2138b29b2356f30
3,656,252
def c_grad_curry_regularized(data, target): """A closure constructor with regularization term for functional.""" def loss(layerweight): model = (lambda x: layerweight @ x.t()) reg = 1e-3 * (layerweight**2).sum()/2 return criterion(model(data).t(), target) + reg return loss
4571c8849bb1643b4d27bad7d2d0ed88ed23c2fa
3,656,253
from typing import Counter def convert_examples_to_features_yake(examples, label_list, max_seq_length, tokenizer, output_mode, cls_token_at_end=False, pad_on_left=False, cls_token='[CLS]', sep_token='[SEP]', noi_token='...
4af89357339a2a63ff765f9da8660ca3895ba8b5
3,656,254
def sq_to_hr(bins, rho, S_k, k, axis=1): """ Takes the structure factor s(q) and computes the real space total correlation function h(r) """ # setup scales dr = np.pi / (k[0] * bins) radius = dr * np.arange(1, bins + 1, dtype=np.float) # Rearrange to find total correlation function fr...
870e535ee3cdec3b138da1c205b000292eaee8ba
3,656,255
def scale17(data, factor): """Solution to exercise C-1.17. Had we implemented the scale function (page 25) as follows, does it work properly? def scale(data, factor): for val in data: val *= factor Explain why or why not. --------------------------------------------------...
84ac4012e0c839b78cb8617b6b9b7c2e8c54caa2
3,656,256
import sqlite3 def initialize_database() -> sqlite3.Connection: """Create a sqlite3 database stored in memory with two tables to hold users, records and history. Returns the connection to the created database.""" with sqlite3.connect("bank_buds.db") as conn: conn.execute("""CREATE TABLE IF NOT EXI...
c3e32534de39a53686672c5c537a2c277fa2d06d
3,656,257
def stateless_multinomial(logits, num_samples, seed, output_dtype=dtypes.int64, name=None): """Draws deterministic pseudorandom samples from a multinomial distribution. This is a stateless version of `tf.random....
da750b8a33348b4f6ff0b47897b4421a8099f12e
3,656,258
def calc_kss(tag,vj): """ calculate Kolmogorov-Smirnov statistics as in CMap; Lamb J, Science, 2006 Parameters ---------- tag: tuple tuple of up-/down-gene lists; (up,down) sorted with the values in the descending order vj: dict dictionary corresponding to V(j) in CMap;...
8dbb6233fb82a65a3ffad347f8444d3c16f8f4a9
3,656,259
def encode(elem): """This is the general function to call when you wish to encode an element and all its children and sub-children. Encode in this context means to convert from pymm elements to xml.etree.ElementTree elements. Typically this is called by pymm.write() """ converter = Conversio...
13578267efb0a6e21b61d86a6c60f5ecd9235b05
3,656,260
def register_blueprints(app: "Flask") -> "Flask": """A function to register flask blueprint. To register blueprints add them like the example Example usage: from app.blueprints import blueprint app.register_blueprint(blueprint) Args: app (Flask): Flask Application instance R...
13564aa6f95d995362a56e9be02a51e50475e446
3,656,261
def build_history_class( cls: declarative.DeclarativeMeta, prop: T_PROPS, schema: str = None) -> nine.Type[TemporalProperty]: """build a sqlalchemy model for given prop""" class_name = "%s%s_%s" % (cls.__name__, 'History', prop.key) table = build_history_table(cls, prop, schema) ...
696b379172c57145c215b64e3e3dc4648b42e535
3,656,262
def geo_distance(left, right): """ Compute distance between two geo spatial data Parameters ---------- left : geometry or geography right : geometry or geography Returns ------- distance : double scalar """ op = ops.GeoDistance(left, right) return op.to_expr()
8a7f1bc14eacf38cecda874d8b16d6c38d9d2049
3,656,263
def svn_dirent_local_style(*args): """svn_dirent_local_style(char dirent, apr_pool_t pool) -> char""" return _core.svn_dirent_local_style(*args)
afe170a321713c9d0f671303fa71d86bc93d8167
3,656,264
def make_generator_model(): """ The Generator The generator uses `tf.keras.layers.Conv2DTranspose` (upsampling) tf.keras.layers.to produce an image from a seed (random noise). Start with a `Dense` layer that takes this seed as input, then upsample several times until you reach the desired image ...
e02fa5487805a85aaa5830ce90a6cc26cb2f27a4
3,656,265
def find_simple_cycles(dg): """ Find all simple cycles given a networkx graph. Args: dg (obj): a networkx directed graph Returns: simple_cycles (list of lists): a list of simple cycles ordered by number of segments. """ simple_cycles = [c for c in nx.simple_cycles(dg) if len(c) > 2] ...
4ed18ec26df80631c415086b99e470567e2641ae
3,656,266
from typing import Optional def augment_edge(edge_index: np.ndarray, nodes: np.ndarray, edge_weight: np.ndarray = None, *, nbrs_to_link: Optional[np.ndarray] = None, common_nbrs: Optional[np.ndarray] = None, fill_weight: float = 1.0) -> tuple: ""...
9b128dfd4bcefa7912af857de6998183ef4da3c2
3,656,267
import sys def _get_str(j_data, key, default=None, range_val=None): """ Get data as str :param j_data: Result of loading JSON :param key: The value key to retrieve :param default: Default value if not set :param range_val: Range of values that can be set :return: """ value = j_data...
bdde6d8c223d875c6189bad3e2a79aee297587f6
3,656,268
def status(proc): """Check for processes status""" if proc.is_alive==True: return 'alive' elif proc.is_alive==False: return 'dead' else: return proc.is_alive()
e257385f06979643e19fd9facc2118f4ae07c909
3,656,269
def is_plumed_file(filename): """ Check if given file is in PLUMED format. Parameters ---------- filename : string, optional PLUMED output file Returns ------- bool wheter is a plumed output file """ headers = pd.read_csv(filename, sep=" ", skipinitialspace=True...
b6fca7c82efb2b07779406f06c15bf195bb4b5e9
3,656,270
def detect_llj_xarray(da, inverse=False): """ Identify local maxima in wind profiles. args: - da : xarray.DataArray with wind profile data - inverse : to flip the array if the data is stored upside down returns: : xarray.Dataset with vertical dimension removed containin...
3fbe444e5eed6ff1ec4f525145276e2bc974050c
3,656,271
def gen_blinds(depth, width, height, spacing, angle, curve, movedown): """Generate genblinds command for genBSDF.""" nslats = int(round(height / spacing, 0)) slat_cmd = "!genblinds blindmaterial blinds " slat_cmd += "{} {} {} {} {} {}".format( depth, width, height, nslats, angle, curve) slat...
2e8a2751f2bb2be0c2ffdff8218961b0b1c0191b
3,656,272
def dev_Sonic(Mach, gamma=defg._gamma): """computes the deviation angle for a downstream SONIC Mach number Args: Mach: param gamma: (Default value = defg._gamma) gamma: (Default value = defg._gamma) Returns: """ return deflection_Mach_sigma(Mach, sigma_Sonic(Mach, gamma=gamma), gamm...
a29f90ec1de25a3b86c2dcc1a1a6becedbfbf696
3,656,273
import json def query(request): """传入一个查询字符串,返回匹配到的文章id。 Args: request (GET): queryString:String 查询的字符串 categories:String/Int 文章所属的领域,多个领域使用逗号分隔,例如"math.CO,quant-ph" timeStart:String yyyy-mm 最早发表日期(含),both included timeEnd: S...
33de1daca6d0edb197d2c6caeb69b6596915ea2a
3,656,274
def get_prev_and_next_lexemes(request, current_lexeme): """Get the previous and next lexeme from the same language, ordered by meaning and then alphabetically by form""" lexemes = list(Lexeme.objects.filter( language=current_lexeme.language).order_by( "meaning", "phon_form", "romanised",...
ca33f582049d055d35196595fd0c23a06fb0d791
3,656,275
def _sanitize_and_check(indexes): """ Verify the type of indexes and convert lists to Index. Cases: - [list, list, ...]: Return ([list, list, ...], 'list') - [list, Index, ...]: Return _sanitize_and_check([Index, Index, ...]) Lists are sorted and converted to Index. - [Index, Index, .....
1c158934d49270fb17d99477082c49b7839c1fbb
3,656,276
def get_tetranuc_freqs(given_seq): """ Returns dictionary mapping each of the 4^4 = 256 possible tetranucleotides to its observed frequency in the given sequence. Args: given_seq: Returns: """ return {tetranuc : get_observed_oligonuc_freq(given_seq, tetranuc) for tetranuc in TETRANU...
b2279248961b747526bedb14a7fcddf7015fde45
3,656,277
import math def calculate3_onemetric(pred_ccm, pred_ad, truth_ccm, truth_ad, rnd=0.01, method="orig_nc", verbose=False, full_matrix=True, in_mat=2): """Calculate the score for subchallenge 3 using the given metric :param pred_ccm: predicted co-clustering matrix :param pred_ad: predicted ancestor-descenda...
6655447568d9a7c6a94790c8d52a159874b34b65
3,656,278
from typing import Optional def _prv_keyinfo_from_wif( wif: String, network: Optional[str] = None, compressed: Optional[bool] = None ) -> PrvkeyInfo: """Return private key tuple(int, compressed, network) from a WIF. WIF is always compressed and includes network information: here the 'network, compres...
d9eef56ea212fafcd7aa5af718aa0b1280e9555d
3,656,279
def build_cmake_defines(args, dirs, env_vars, stage): """ Generate cmake defines :param args: The args variable generated by parse_parameters :param dirs: An instance of the Directories class with the paths to use :param env_vars: An instance of the EnvVars class with the compilers/linker to use ...
227fb680e42786356adbace344cea98433a29aab
3,656,280
def server() -> None: """Старт сервера""" class PredictionServicer(predictions_pb2_grpc.PredictionServicer): def PredictIris(self, request, context): response = predictions_pb2.PredictResponse() response.iris_type = predictions.predict_iris(request.sepal_length, ...
eaa71a36763ffee0d6b201e0900b4f1fcf397fe9
3,656,281
def wasLastResponseHTTPError(): """ Returns True if the last web request resulted in an erroneous HTTP code (like 500) """ threadData = getCurrentThreadData() return threadData.lastHTTPError and threadData.lastHTTPError[0] == threadData.lastRequestUID
cbe2a21752387cfb5b0cba41ecc3bdbacbcdcbb3
3,656,282
import select async def update_rates( user_id: str = None, client_id: str = None, new_amount: str = None, session: Session = Depends(get_session), ): """Update a rate.""" statement = ( select(Rate) .where(Rate.user_id == user_id) .where(Rate.client_id == client_id) ...
c5ef142dda27f27217d71ed811ce8b6f049a0d98
3,656,283
import sys def setup_page(choice, pagepanel, frame): """ Creates a :class:`Page` inside a :class:`Notebook`. :Args: - choice (tuple) A tuple of (name, module path, module alias) - pagepanel """ if isinstance(choice.module, str): try: __import__(choi...
6923a44f0a82543ba8ba3be2a4381c7fa56d05ed
3,656,284
def taillight_detect(image): """ Takes in a road image, re-sizes for the model, predicts the lane to be drawn from the model in G color, recreates an RGB image of a lane and merges with the original road image. """ model = load_model('full_CNN_model.h5') #image1=image #image1=np.array(im...
ee8849b59e94f8c395211af3537310ad7d2d8999
3,656,285
def generate_random_number(rng, length): """Return random number with predefined length.""" return crypto.random_generate(rng, length)
2f3f5f290948c3eb063b46353a01a5edc17599e4
3,656,286
import ftplib import tarfile def update_old_names(): """Fetches the list of old tz names and returns a mapping""" url = urlparse(ZONEINFO_URL) log.info('Connecting to %s' % url.netloc) ftp = ftplib.FTP(url.netloc) ftp.login() gzfile = BytesIO() log.info('Fetching zoneinfo database') ...
a10f5985ea6fe6709816e757ee764138735eb077
3,656,287
from typing import Optional def get_namespace(location: Optional[str] = None, namespace_id: Optional[str] = None, project: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetNamespaceResult: """ Gets a namespace. """ ...
70f59b6eb48e4952d19c5b96b9579f13c0e569fd
3,656,288
def build_headers(access_token, client_id): """ :param access_token: Access token granted when the user links their account :param client_id: This is the api key for your own app :return: Dict of headers """ return {'Content-Type': 'application/json', 'Authorization': f'Bearer {acce...
5cd8ae3e06f67b7a4fdb1644ae82c62cb54479cb
3,656,289
import argparse def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='sum numbers', formatter_class=argparse.ArgumentDefaultsHelpFormatter) # Positional arg parser.add_argument('int', metavar='INT', type=int, nargs='+', he...
09a3cec8ac25861c1e04164082a77c2a77c1c703
3,656,290
def odd_subgraph_centrality(i, lam, u): """ Calculates the number of odd length closed walks that a node participates in :cite:`estrada2005spectral`. Used in the calculation of spectral scaling and generalized robustness index. :param i: node index :param lam: largest eigenvalue :param u: large...
eeb141ac56d9b70294bbf62a24739c73f3e4755e
3,656,291
def PolyAreasToModel(polyareas, bevel_amount, bevel_pitch, quadrangulate): """Convert a PolyAreas into a Model object. Assumes polyareas are in xy plane. Args: polyareas: geom.PolyAreas bevel_amount: float - if > 0, amount of bevel bevel_pitch: float - if > 0, angle in radians of bevel ...
c2243bca3d3cfa1168bde94dfe078d6cf3e86ad4
3,656,292
def preprocessing(train_data, test_data): """ * The method at first eliminates constant features from both train and test data. * Then, it splits training data into features and labels. * Finally, the method performs pca on training and testing data sets to reduce the dimension and overcome curse...
9f6c01d64d393c9c9fe51925f11842b63098471f
3,656,293
def generate_videos_from_events(response, video_model): """Creates the video containers/representations for this given response. We should only really invoke this as part of a migration as of right now (2/8/2019), but it's quite possible we'll have the need for dynamic upsertion later. """ seen_id...
f5669fbc6466bf3cf1671d04a48bad4c5975f216
3,656,294
def datetime_at_midnight(dt: DateTime, tz: TimeZone) -> DateTime: """ Returns a DateTime for the requested DateTime at midnight in the specified time zone. Args: dt (DateTime): the DateTime for which the new value at midnight should be calculated tz (TimeZone): the TimeZone to use when interpre...
141988c9943911d165f5f3f8ade5536ae65881f2
3,656,295
import os def count_dcm(logger, top): """ This function recursively walks through a given directory (`top`) using depth-first search (bottom up) and counts the number of .dcm files present. Parameters ---------- path : {str} The directory to count. Returns ------- co...
5da9be183c7a00b3ef3fbc1f7e79d7df0f5502b8
3,656,296
def convert2sametype(dict_, formula): """Utility function for internal use. Convert string/dict/DataFrame to dict Parameters ---------- dict_ : dict formula : string/dict/DataFrame Returns ------- type(formula) """ return convert2type(dict_, type(formula))
d7393668e5bd22e8482bf4b99c6a789d322b80fb
3,656,297
from typing import List import gzip def from_sdf(sdf_content: str = None, file_path: str = None, ignore_hydrogens = False) -> List[Graph]: """ parse graph from_sdf Read chemical files and parses them into instances of `Graph`. As this function is not meant to be called in a loop, inner functions only relative...
5676b98a699cfed00767f4d51dec27a7dc1a94ad
3,656,298
from typing import Callable def dispatcher_connect( opp: OpenPeerPower, signal: str, target: Callable[..., None] ) -> Callable[[], None]: """Connect a callable function to a signal.""" async_unsub = run_callback_threadsafe( opp.loop, async_dispatcher_connect, opp, signal, target ).result() ...
3dca8d6cf1f581a409c2b64e6c9a88e543fe0615
3,656,299