content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import requests def _get_api_key(api_url: str, username: str, password: str, save: bool) -> str: """Get an RGD API Key for the given user from the server, and save it if requested.""" resp = requests.post(f'{api_url}/api-token-auth', {'username': username, 'password': password}) resp.raise_for_status() ...
c0adc024340310d2047d25c73772c530d17d81fe
3,630,337
def fitness_func_large(vector): """ returns a very large number for fitness""" return 9999999999999999999
08e6f43c5f891fe7138dfc7b1d0809ba048bf070
3,630,338
def create_implicit_binary_heap(key_type=float): """Create an implicit (array-based) binary heap. :param key_type: the key type :type key_type: float, int or object :returns: the heap :rtype: :py:class:`.Heap` """ heap_type = _HeapType.HEAP_TYPE_BINARY_IMPLICIT return _create_and_wrap_...
b598a8525b47e65a97578a69d40e22866cf65b4d
3,630,339
def Prob_APD_select_v2( fitness: list, uncertainty: list, vectors: "ReferenceVectors", penalty_factor: float, ideal: list = None, ): """Select individuals for mating on basis of Angle penalized distance. Args: fitness (list): Fitness of the current population. ...
a562c5908d6dab5ca231220dda1eec94f5020d86
3,630,340
def remove_prefix(s, pre): """ Remove prefix from the beginning of the string Parameters: ---------- s : str pre : str Returns: ------- s : str string with "pre" removed from the beginning (if present) """ if pre and s.startswith(pre): return s[len(pre):] ...
6bae14cddd38fcfabfb0fadb9f4dbeaea81ff4ac
3,630,342
def parseString(string, namespaces=True): """Parse a document from a string, returning the resulting Document node. """ if namespaces: builder = ExpatBuilderNS() else: builder = ExpatBuilder() return builder.parseString(string)
bd1da0d0deddd1d09c92979587ffa69e83b54063
3,630,344
def prompt_present(nbwidget): """Check if an In prompt is present in the notebook.""" if WEBENGINE: def callback(data): global html html = data nbwidget.dom.toHtml(callback) try: return ' [ ]:' in html except NameError: re...
9ee7aacf6ad03a22b3b4c002b121e8b61f3649b0
3,630,346
def _search_range(elem, session, query=None): """Perform a range search for DA, DT and TM elements with '-' in them. Parameters ---------- elem : pydicom.dataelem.DataElement The attribute to perform the search with. session : sqlalchemy.orm.session.Session The session we are using ...
57ae970c8864f3c00b1df09d3d490a98f6fa82b3
3,630,347
def is_repo_user(repo_obj, username=None): """ Return whether the user has some access in the provided repo. """ if username: user = username else: if not authenticated(): return False user = flask.g.fas_user.username if is_admin(): return True usergrps ...
1692814dcdf967ce31a75d613958851a2ee9a8ad
3,630,348
def block_distance(p1, p2): """ Returns the Block Distance of a particular point from rest of the points in dataset. """ distance = 0 for i in range(len(p1)-1): distance += abs(p1[i]-p2[i]) return distance
29d7febe0bd8fcdfc16cbc27c7f3490f265c9daf
3,630,349
def display_profiles(): """ Function that returns all save profiles """ return Passwords.display_profiles()
162e5685ccb98c5b962737d2ee2866bc2dca0525
3,630,350
from contextlib import suppress def mutate( _data, *args, _keep="all", _before=None, _after=None, **kwargs, ): """Adds new variables and preserves existing ones The original API: https://dplyr.tidyverse.org/reference/mutate.html Args: _data: A data frame _keep...
d4af5ca1fa9cd423ac3ec036897703e9f636a725
3,630,351
def test_triangular_mesh(): """An example of a cone, ie a non-regular mesh defined by its triangles. """ n = 8 t = np.linspace(-np.pi, np.pi, n) z = np.exp(1j * t) x = z.real.copy() y = z.imag.copy() z = np.zeros_like(x) triangles = [(0, i, i + 1) for i in range(1, n)] x...
4367786b129167223f64f04b989afb79fa536004
3,630,352
def pos_tag(tokenized_text): """ Averaged perceptron tagger from NLTK (originally from @honnibal) """ return pos_tag_sents([tokenized_text])[0]
0405d3090d59260303c82eca46578878246f257d
3,630,353
def cabbeling(SA, CT, p): """ Calculates the cabbeling coefficient of seawater with respect to Conservative Temperature. This function uses the computationally- efficient expression for specific volume in terms of SA, CT and p (Roquet et al., 2015). Parameters ---------- SA : array-lik...
49ea1ce3485b5b4778702c12a17803ba7ef15de0
3,630,354
def _variant_to_dsl_helper(tokens) -> Variant: """Convert variant tokens to DSL objects. :type tokens: ParseResult """ kind = tokens[KIND] if kind == HGVS: return Hgvs(tokens[HGVS]) if kind == GMOD: concept = tokens[CONCEPT] return GeneModification( name=co...
bacb81138e0310a787e9f9d4fb490ad0a4215297
3,630,355
def remove_empty(df): """ Drop all rows and columns that are completely null. Implementation is shamelessly copied from `StackOverflow`_. .. _StackOverflow: https://stackoverflow.com/questions/38884538/python-pandas-find-all-rows-where-all-values-are-nan # noqa: E501 Functional usage example: ...
c2ea9fc13bfa57bc357a83c607bfe9ce9348fb2e
3,630,356
from typing import Optional def calculate_serving_size_weight( weight: Optional[float], number_of_servings: Optional[float] ) -> Optional[float]: """ Given a weight (representing the total weight of the component included in a recipe) and a number of servings (how many servings of the component ar...
b22732a60f1f6000277861a615c78e785b4757bb
3,630,357
def validate_positive(value): """Check if number is positive.""" if value is not None and value <= 0: raise ValidationError(f'Expected a positive number, but got {value}') return value
d4c84a8f8aa476af4e9169b25887f5e5344f22af
3,630,358
import json def start_game(player1, player2, symbols=("O", "X")): """Starts a command line tic tac toe game between 2 players (bot or human)""" assert len(symbols) == 2, "`symbols` must have exactly 2 elements" gstate = TicTacToe("_________", symbols=symbols) with open(GAME_TREE_FILE, "r") as gt_fil...
96e712b399596bd2373c35c4e46e283c7efd8317
3,630,361
def despike_l1b_array(data, dqf, filter_width=7): """ Despike SUVI L1b data and return a despiked `numpy.ndarray`. Parameters ---------- data : `numpy.ndarray` Array to despike. dqf : `numpy.ndarray` Data quality flags array. filter_width: `int`, optional. The filter...
57c3b757856a1c030c245472445f51b33c576cd2
3,630,362
def scrape(query: str, listing_age: int = None, relevance: str = None, job_type: list = None, experience: list = None, locations: list = ['Singapore'], limit: int = None, **kwargs): """ :param query: str Job search query :...
493cd2efff208d49ca5ce0d05814a0f73c872846
3,630,363
def run_command(arguments, parse_stdout=True): """Run a command Args: A list with the arguments to execute. For example ['ls', 'foo'] Returns: stdout, return status. """ try: cmd = sp.Popen(arguments, stdout=sp.PIPE, stderr=sp.STDOUT) stdout, _ = cmd.communicate() ...
a2183d8c588f0e749462c225e62183df46ac04b0
3,630,365
def format_key(key): """ Format the key provided for consistency. """ if key: return key if key[-1] == "/" else key + "/" return "/"
8b5e41bb76c524ec8c45a22ad0dae84c84ed530b
3,630,366
def get_random_parent_asset(instance_id: int, instance_start_id, instance_end_id) -> int: """ get random parent asset not linked to any child assets :param instance_id: asset instance_id """ child_list = [instance_id] child_list = get_child_assets_id(child_list, instance_id) all_list = list...
1f366ec08fdda6cfc8157bb6dc862a9700844409
3,630,367
def logout() -> Response: """API call: logout of the system.""" config = CorporaAuthConfig() client = get_oauth_client(config) params = {"returnTo": config.redirect_to_frontend, "client_id": config.client_id} response = redirect(client.api_base_url + "/v2/logout?" + urlencode(params)) # remove t...
2c9dd72d80ad4a8c27c9da508a932e7dca008ce7
3,630,368
import time def elapsed_printer(func): """ **中文文档** 此包装器可以打印函数的输入参数, 以及运行时间。 """ def _wrapper(*args, **kwargs): print(">>> %s # Running ..." % _text_of_func_args_and_kwargs(func, args, kwargs)) st = time.clock() res = func(*args, **kwargs) elapsed =...
396289476d48e91185eae4f5e88691b2dd0756ec
3,630,369
def get_init_fn(): """Returns a function run by the chief worker to warm-start the training.""" checkpoint_exclude_scopes=["resnet_v1_101/logits","resnet_v1_101/fc","deconv32"] exclusions = [scope.strip() for scope in checkpoint_exclude_scopes] variables_to_restore = [] for var in slim.ge...
b6ca552c9d1b9cbe67e7cb9af16b8676c107124e
3,630,370
def buildings_from_polygon(polygon, retain_invalid=False): """ Get building footprints within some polygon. Parameters ---------- polygon : Polygon retain_invalid : bool if False discard any building footprints with an invalid geometry Returns ------- GeoDataFrame """ ...
85ecf11c5dfe6d717dffb52c80b1195138dfc556
3,630,371
from typing import Dict def _define_problem_with_groups(problem: Dict) -> Dict: """ Checks if the user defined the 'groups' key in the problem dictionary. If not, makes the 'groups' key equal to the variables names. In other words, the number of groups will be equal to the number of variables, which ...
ab29954f3349509a9153219d040feb8fa3125ec7
3,630,372
def ljk(epsilon): """ Calculates ecliptic triad vectors with respect to BCRS-frame. (Lindegren, SAG-LL-35, Eq.1) :param epsilon: obliquity of the equator. :return: np.array, np.array, np.array """ l = np.array([1,0,0]) j = np.array([0, np.cos(epsilon), np.sin(epsilon)]) k = np.arra...
9e7d8ca724c9bfad11e561f5e6873b938b613341
3,630,373
def position_result_list(change_list): """ Returns a template which iters through the models and appends a new position column. """ result = result_list(change_list) # Remove sortable attributes for x in range(0, len(result['result_headers'])): result['result_headers'][x]['sorted'] ...
5608857697c0d6ae46d3d34577f2b4002bacdc28
3,630,375
import re def _build_regex(pattern): """Compile regex pattern turn comma-separated list into | in regex.""" compiled_pattern = None if pattern: # Trip ' " at the beginning and end pattern = re.sub("(^\"|^\'|\"$|\'$)", "", pattern) # Escape pattern = re.sub("/", r"\/", pattern) # Change "a,...
7351f461a867b7c875749c6d88fdd5f2b26da496
3,630,376
def fpSub(rm, a, b, ctx=None): """Create a Z3 floating-point subtraction expression. >>> s = FPSort(8, 24) >>> rm = RNE() >>> x = FP('x', s) >>> y = FP('y', s) >>> fpSub(rm, x, y) fpSub(RNE(), x, y) >>> fpSub(rm, x, y).sort() FPSort(8, 24) """ return _mk_fp_bin(Z3_mk_fpa_sub...
2513a4ee917d1e3a773a3637c519a85df28abd69
3,630,377
def reconstruct_contractility(simulation_folder, d_cyl, l_cyl, r_outer, scalef = 1000, scaleu = 1, scaleb = 1): """ Reconstruct the contractility of a given cylindric simulation. Also calculates residuum forces of Inclusion surface and matrix, which shoould be equal (use to certify simulation and detect ...
f55369580d87e55061934149fad9598c5a29a1fe
3,630,378
def categorical_sample(d): """Randomly sample a value from a discrete set based on provided probabilities. Args: d: A dictionary mapping choices to probabilities. Returns: One of the possible choices. """ choice_probs = list(d.items()) probs = [t[1] for t in choice_probs] ...
e99949ebc6d0314f3c2b791415af30c0fe6ed519
3,630,379
def gaspari_cohn_mid(z,c): """ Gaspari-Cohn correlation function for middle distances (between c and 2*c) Arguments: - z: Points to be evaluated - c: Cutoff value """ return 1./12*(z/c)**5 - 0.5*(z/c)**4 + 5./8*(z/c)**3 \ + 5./3*(z/c)**2 - 5*z/c - 2./3*c/z + 4
0852e84c1ce10856d69420fcc585054488591e73
3,630,380
import click import concurrent def put(local_file, remote_file, outmode, template, recursive, process): """ upload file example: pypssh -t 192.168.31.1 put /etc/yum.conf /etc/yum.conf """ def _progress(filename, size, sent, peername): click.echo("(%s:%s) %s's progress: %.2f%% \r" %...
699bd72c5349609513fdcb45ddd428ad6dfad684
3,630,381
def home_view(request): """ DESCRIPTION: The only FBV to redirect to the original home_view """ # image = {'image': 'https://picsum.photos/1024/756'} image = {} return render(request, 'home.html', image)
24d9602004b696610a69c6f38212db06d272a5c2
3,630,382
import time import six def hparams_pb(hparams, trial_id=None, start_time_secs=None): # NOTE: Keep docs in sync with `hparams` above. """Create a summary encoding hyperparameter values for a single trial. Args: hparams: A `dict` mapping hyperparameters to the values used in this trial. Keys ...
835edf3b8e6a9def39cf33233215801948a20859
3,630,383
def create_agents(nagi, age_all, nr_infec, nr_immucmpr, nr_freeroam, nr_social): """ Creates the array of agents that will be used in the simulation Parameters ---------- nagi : int number of human agents that will be created. age_all : numpy array of ints distribution of the ag...
23b0e92e281521dadcba47f8bfb5b2e8f5de2803
3,630,384
def get_top_level_data(end, start=20, get_fight_card_stats=False, both=True, avg_pause=.6): """ @param end: integer @param start : integer @param get_fight_card_stats : @param both : boolean @param avg_pause : float """ def add_d_set(df_use, name): df = df_use.copy() df...
5d46f67d370b2c9c431f97f132338ca55edf609c
3,630,385
def compute_normalization_binary_search(activations, t, num_iters = 10): """Returns the normalization value for each example (t < 1.0). Args: activations: A multi-dimensional array with last dimension `num_classes`. t: Temperat...
86859bf5834c791e1aa268784a1d353ba192551e
3,630,386
from copy import deepcopy def _match_units(filter_params, fps, fname): """ author: EM The filtering thresholds must match the timeseries units. If the right conversion is not possible, then check_ok is False, and the feature summaries will not be calculated for this file. """ if filter_p...
de260a5570656c3c419c5df96ef6ad7bc75ff114
3,630,387
def squared_jumps(tracks, n_frames=1, start_frame=None, pixel_size_um=0.16, pos_cols=["y", "x"]): """ Given a set of trajectories, return all of the the squared jumps as an ndarray. args ---- tracks : pandas.DataFrame. Must contain the "trajectory" and "f...
4fb75a9c4c65c8e8498156defbd4ea1ebfdd1c25
3,630,389
from typing import get_args def main(): """Change vowels of the text into the one selected ("a" as default)""" args = get_args() new_text = '' for char in args.text: if char in ['a','e','i','o','u']: new_text = args.text.replace(char, args.vowel) ## doesn't work like this, l...
638f00d93f53ac56ea6a6c4c1a1893a7abf8dfc3
3,630,390
def _mt_transpose_ ( self ) : """Transpose the graph: >>> graph = ... >>> graph_T = graph.transpose () >>> graph_T = graph.T() ## ditto """ new_graph = ROOT.TMultiGraph() new_graph._graphs = [] _graphs = mgraph.GetListOfGraps() for g in _graphs : tg = g.T(...
905936ee404551548fdd789489fdba9d9dcc8f3f
3,630,391
import collections def recursive_dictionary_update(d, u): """ Given two dictionaries, update the first one with new values provided by the second. Works for nested dictionary sets. :param d: First Dictionary, to base off of. :param u: Second Dictionary, to provide updated values. :return: Dic...
7a040ee36d8d101ed3ce40f96c21c003c5410803
3,630,392
def uname(space): """ uname() -> (sysname, nodename, release, version, machine) Return a tuple identifying the current operating system. """ try: r = os.uname() except OSError, e: raise wrap_oserror(space, e) l_w = [space.wrap(i) for i in [r[0], r[1], r[2], r[3], r[4]]] retu...
40ba4d2178fd2701d1ebd07e45c88073efd046e3
3,630,393
def load_model( model_path=filepath + "/trained_models/cmu/", model_file_name="model.h5" ): """ loads a pre-trained word boundary model :return: Seq2Seq object """ model_path = ( filepath + "/trained_models/{}/".format(model_path) if model_path in ["cmu"] else model_path ...
27e90f879dd06a840ff5fe4589fd0f98b9786ba1
3,630,394
def _tol_sweep(arr, tol=1e-15, orders=5): """ Find best tolerance 'around' tol to choose nonzero values of arr. # Sweeps over tolerances +- 'orders' orders of magnitude around tol and picks the most # stable one (one corresponding to the most repeated number of nonzero entries). Parameters ---...
6acfce610fe98f4a1aeb4e3417796dd56901f402
3,630,395
def test_coo_attr(): """ Feature: Test COOTensor GetAttr in Graph and PyNative. Description: Test COOTensor.indices, COOTensor.values, COOTensor.shape. Expectation: Success. """ indices = Tensor([[0, 1], [1, 2]]) values = Tensor([1, 2], dtype=mstype.float32) shape = (3, 4) coo = COOT...
17cccc6d45cd2c48d39279d7e7055224fdfb54ec
3,630,396
def get_all_parties(): """this gets all parties""" if not app.api.routes.models.political.parties: return Responses.not_found("No created parties yet"), 404 return Responses.complete_response(app.api.routes.models.political.parties), 200
e212a15d5296bb9ba6e288a582e829d714bf225a
3,630,398
def send(channel, apdu: list) -> bytes: """ Send APDU to the channel and return the data if there are no errors. """ data, sw1, sw2 = channel.transmit(apdu) # success if [sw1, sw2] == [0x90, 0x00]: return bytes(data) # signals that there is more data to read elif sw1 == 0x61: ...
bb3a1e52b6fdb5480b23f0646e768a7f90500acd
3,630,399
def root(): """ Landing page for PaperScraper, takes user input and run parameters """ if request.method == "GET": return render_template("root.html") elif request.method == "POST": error = None source = None try: source = get_source(request.form) ...
2af8b4247b51afb86c71e61199c7d622996cb112
3,630,400
from typing import Optional def ArcSin(input_vertex: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex: """ Takes the inverse sin of a vertex, Arcsin(vertex) :param input_vertex: the vertex """ return Vertex(context.jvm_view().ArcSinVertex, label, cast_to_vertex(input_verte...
68f80b459ae0b235463284cf8db237d3d15751a1
3,630,404
def LSFIR(H,N,tau,f,Fs,Wt=None): """ Least-squares fit of a digital FIR filter to the reciprocal of a given frequency response. Parameters ---------- H: np.ndarray frequency response values N: int FIR filter order tau: float delay of filter f: np.ndarray frequencies Fs: float sampling frequ...
025d3327b985eaf708a61f808e913256c91a911d
3,630,405
import math def DrawTextBar(value, max_value, max_width=53): """Return a simple ASCII bar graph, making sure it fits within max_width. Args: value: integer or float representing the value of this bar. max_value: integer or float representing the largest bar. max_width: How many characters this graph ...
7f4b267527317cbceddadc9f7a0307f8ec430bb4
3,630,406
def dpAdvisorTime(): """ runs dpAdvisor and measures the time required to compute an answer. """ res = {} length = len(subjects) start_time = time.time() res = dpAdvisor(subjects, 24) end_time = time.time() total_time = end_time - start_time print 'It took', total_time, 'to compu...
edd26cb9840de04ea3bca8504ab3a27f0dd4b93b
3,630,407
import ctypes def get_size(ctype, num, il_code): """Return ILValue representing total size of `num` objects of given ctype. ctype - CType of object to count num - Integral ILValue representing number of these objects """ long_num = set_type(num, ctypes.longint, il_code) total = ILValue(ctype...
14a405edb55a14ec408094c5d27995a4c0906ce2
3,630,410
def pe_17(): """Sum the number of characters in the UK words representing the integers from 1 to 1,000. Exclude dashes and spaces. """ total = 0 for number_word in range(1, 1001): number_word = lpe.number_to_word(number_word) number_word = number_word.replace('-', '') number_...
fb55ff73072c50c6b272a2c7f9c9228d5c406b40
3,630,411
def metrics_detection(scores, labels, pos_label=1, max_fpr=FPR_MAX_PAUC, verbose=True): """ Wrapper function that calculates a bunch of performance metrics for anomaly detection. :param scores: numpy array with the anomaly scores. Larger values correspond to higher probability of a point...
854c9a74518bdd09520a47173077bcd7865bef87
3,630,412
def bias_init(shape, name=None, constant=0.0): """Bias Initialization Args: shape : Shape of the variable name : Name of the variable constant: Value of constant to initialize Returns: Initialized bias tensor """ if name is None: name = 'b' b = tf....
a9f9314a3ba896f036e6cd30c88951ec08bbeb68
3,630,413
def _FindBinmanNode(dtb): """Find the 'binman' node in the device tree Args: dtb: Fdt object to scan Returns: Node object of /binman node, or None if not found """ for node in dtb.GetRoot().subnodes: if node.name == 'binman': return node return None
bf924d173a1adf81c1705ad1ea1fae490567a317
3,630,414
def replace_escape_chars(text, which_ones=('\n', '\t', '\r'), replace_by=u'', \ encoding=None): """Remove escape characters. `which_ones` is a tuple of which escape characters we want to remove. By default removes ``\\n``, ``\\t``, ``\\r``. `replace_by` is the string to replace the escape char...
3742e08ed8b657ce1f9379b4e751fae413c19786
3,630,415
def purge_report_from_mobile_ucr(report_config): """ Called when a report is deleted, this will remove any references to it in mobile UCR modules. """ if not toggles.MOBILE_UCR.enabled(report_config.domain): return False did_purge_something = False for app in get_apps_in_domain(repo...
cf9a744772514868a5e0c6a7ec890ca55ecaa82c
3,630,416
def image_color_cluster(image, k=5): """ :param image(numpy array): 추출된 옷 :param k(int) : 군집화할 개수 :return c_list(list) : 각 색의 rgb 값이 담긴 리스트 :return p_list(list) : 각 색의 분포도가 담긴 리스트 """ image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image = image.reshape((image.shape[0] * image.shape[1], 3...
d0fc166cd3465b9f26b4a7bd2e290b1565c77488
3,630,417
def _get_auth_service(app): """Returns an _AuthService instance for an App. If the App already has an _AuthService associated with it, simply returns it. Otherwise creates a new _AuthService, and adds it to the App before returning it. Args: app: A Firebase App instance (or None to use the...
75b6890fb8650e621bd3d668d8704b6c38a76807
3,630,418
def winner_distance(r1, r2, reverse=False): """ Asymmetrical winner distance. This distance is the rank of the winner of r1 in r2, normalized by the number of candidates. (rank(r1 winner)) - 1 / (n - 1) Assuming no ties. Args: r1: 1D vector representing a judge. ...
4f8912165905360aeecd355c68da19a11adf3600
3,630,419
def make_list_accos(): """Return the acco numbers as list Returns: list: List with acco numbers """ list_saharas= list(range(1,23)) list_kalaharis =list(range (637,656)) list_balis = list(range (621,627)) list_waikikis = list(range(627,637)) list_serengeti = list(range(659,668))...
9f2ac7aa4f78588013160f94374e602832b61771
3,630,420
def load_manifest(url, version, manifest_name): """Download and parse manifest.""" manifest_raw = do_curl(f"{url}/{version}/Manifest.{manifest_name}") manifest = {} if not manifest_raw: raise Exception(f"Unable to load manifest {manifest_name}") try: lines = manifest_raw.splitlines(...
f2eb6bb8a9fb3e86a7a87293873f32ae73e2ae62
3,630,421
from typing import List def create_intrusion_set_from_name( name: str, author: Identity, external_references: List[ExternalReference], object_marking_refs: List[MarkingDefinition], ) -> IntrusionSet: """Create intrusion set with given name.""" aliases: List[str] = [] alias = name.replace(...
9e545b78af90acf4ab7e9ab556bd0f66989b5f9a
3,630,422
def _host_is_same(host1: str, host2: str) -> bool: """Check if host1 and host2 are the same.""" return host1.split(":")[0] == host2.split(":")[0]
0bd9393786801d0f69d4982fc9f8edce378e9656
3,630,425
from typing import List def check_chan_xt_three_bi(kline, bi_list: List[ChanObject]): """ 获取指定3分笔得形态 (含有三笔) :param kline: ctaLineBar对象 :param bi_list: 笔列表 :return: """ v = ChanSignals.Other.value if len(bi_list) != 3: return v bi_1, bi_2, bi_3 = bi_list # 最后一笔是下跌...
cf4e9b88abb604ff0646b6513a0cec62e15660dc
3,630,426
def get_filter_type_choices(): """ Get a tuple of filter types :return: tuple with filter types """ return ('', 'Select one'), ('Filter Types', [('storlet', 'Storlet'), ('native', 'Native')])
21f4173b1aafa35b4c877d6f844349c2907932a8
3,630,427
from typing import Optional def get_connected_devices() -> ConnectedDevices: """Returns Mbed Devices connected to host computer. Connected devices which have been identified as Mbed Boards and also connected devices which are potentially Mbed Boards (but not could not be identified in the database) are r...
cb9a3565c7b62f99858ed90e85dd9686c9db9e00
3,630,428
from typing import Union from typing import Optional def my_sqrt_with_local_types(x: Union[int, float]) -> float: """Computes the square root of x, using the Newton-Raphson method""" approx: Optional[float] = None guess: float = x / 2 while approx != guess: approx = guess guess = (appr...
61263b7722ea6becc536e6ccac69063ded41aa92
3,630,429
def get_tempo(h5,songidx=0): """ Get release year from a HDF5 song file, by default the first song in it """ return h5.root.musicbrainz.songs.cols.tempo[songidx]
155d690eb6773cbaf0d06e2cb83ea8976cb0f1d8
3,630,430
def boolstr(value): """Value to bool handling True/False strings.""" if isinstance(value, basestring): if value.lower() == 'false': return False try: value = float(value) except ValueError: pass return bool(value)
ccfaa56e3f5694fad2f94ea53f90379890148181
3,630,431
import math def round_half_up(n: float, decimals: float = 0) -> float: """This function rounds to the nearest integer number (e.g 2.4 becomes 2.0 and 2.6 becomes 3); in case of tie, it rounds up (e.g. 1.5 becomes 2.0 and not 1.0) Args: n (float): number to round decimals (int): number of ...
e0aab5cba456b4ffe6fab11a21b97fe4e17b045a
3,630,432
from typing import Set def _possible_edges(n1: Set, n2: Set, directed: bool, self_loops: bool = False): """Compute the number of possible edges between two sets.""" a = n1.intersection(n2) e = (len(n1) - len(a)) * (len(n2) - len(a)) if directed: e *= 2 if self_loops: e += len(n1) +...
4cf21d9521c3d071d7d1376bd917f2ec39435108
3,630,433
import math def compute_backbone_shapes(config, image_shape): """Computes the width and height of each stage of the backbone network. Returns: [N, (height, width)]. Where N is the number of stages """ if callable(config.BACKBONE): return config.COMPUTE_BACKBONE_SHAPE(image_shape) ...
9af0a10393bf3297a1ac239682d493c0670fcbbd
3,630,434
def coherency_phase_delay_bavg(time_series,lb=0,ub=None,csd_method=None): """ Band-averaged phase delay between time-series Parameters ---------- time_series: float array The time-series data lb,ub : float, optional Lower and upper bounds on the frequency range over which the ph...
62b689d9513c94ab6ad411e485d4e5f3cb9ca125
3,630,435
def write_sale_table( df: DataFrame, output_path: str, filename: str = "sale.csv", ) -> DataFrame: """ Extract a sale transaction (fact) table from the staging data and save it in the csv format. Args: df: Staging dataframe containing source data. output_path: Path to where the resulting...
c567c2a929bbe2676e8ff544398954c0a2926d93
3,630,436
def is_equal_tf(x: tf.Tensor, y: tf.Tensor) -> bool: """return true if two tf tensors are nearly equal""" x = tf.cast(x, dtype=tf.float32) y = tf.cast(y, dtype=tf.float32) return tf.reduce_max(tf.abs(x - y)).numpy() < EPS
f9816cc393689c14e20381f9b0b3651235d40eab
3,630,437
from typing import List def align_dtw_scale( reference: Trace, *traces: Trace, radius: int = 1, fast: bool = True ) -> List[Trace]: """ Align :paramref:`~.align_correlation.traces` to the :paramref:`~.align_correlation.reference` trace. Use fastdtw (Dynamic Time Warping) with scaling as per: Jas...
628e458ce88bebd6b2919fca35b9c4d5cc0782a1
3,630,438
import tensorflow as tf # wanted to circumvent this, but parsing the serialized data cleanly was difficult import sqlite3 import collections def load_stackoverflow_tff(cache_dir="~/data", user_idx=0, split="train"): """Load the tensorflow federated stackoverflow dataset into pytorch.""" if split == "validati...
91c0defba1081c5871c20d09e2ad9e758617906f
3,630,439
def format_string(current_size, total_length, elapsed_time): """ Consistent format to be displayed on the screen. :param current_size: Number of finished object size :param total_length: Total object size :param elapsed_time: number of seconds passed since start """ n_to_mb = current_size /...
8e9df1ede4bcc42aa97c46139453d677703e77dc
3,630,440
import logging def upload_file(src_local_path, dest_s3_path): """ upload file :param src_local_path: :param dest_s3_path: :return: """ try: with open(src_local_path, 'rb') as f: s3.upload_fileobj(f, BUCKET_NAME, dest_s3_path) except Exception as e: logging.e...
bf4f324fc3246d50e41a956e5bed4c2888276dee
3,630,442
import torch def labels_from(distribution): """Takes a distribution tensor and returns a labels tensor.""" nclasses = distribution.shape[0] llist = [[i] * n for i, n in zip(range(nclasses), distribution)] # labels = [l for cl in llist for l in cl] # flatten the list of lists labels = list(chain(*...
7f1cc3fec0b3fe4f2cef963da40087e33c974996
3,630,443
def import_ham_dataset(dataset_root, outf, training=True): """ Returns dataset class instance for DataLoader. Downloads dataset if not present in dataset_root. Args: dataset_root (str): root directory of dataset. outf (str): path to working directory. training (bool): return trainin...
1f9a659a1c13d862fbd32edad2e5ea03860bc3ad
3,630,445
def truncatechars(value, arg): """ Truncates a string after a certain number of letters Argument: Number of letters to truncate after """ def truncate_chars(s, num): "Truncates a string after a certain number of letters." length = int(num) letters = [l for l in s] if...
1a1542504261fcf859edfac01048c8fa817a314b
3,630,446
def default_category_orders() -> dict: """Returns the default dictionary of category orders""" day_order = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] weekend_order = ["Weekday", "Weekend"] season_order = ["Spring", "Summer", "Autumn", "Winter"] month_order = [ "January", "Febr...
4110287bc30445f27c7c3d0c38cb662d769a5217
3,630,447
def argsort(seq, key=None, cmp=None, reverse=False): """Returns the indices corresponding to a sort of the given `seq`. Can optionally pass in `cmp` and `reverse` just as you would to :func:`sorted()`. """ if not seq: return () ukey = key iseq = sorted([(v, i) for i, v in enumerate(seq)], key=la...
eb56870506642928c35e434b2a859d8d4f0bf08a
3,630,448
def new_category(): """ Add new category """ # Check if the user is loged in if 'username' not in login_session: return redirect('/login') if request.method == 'POST': # Get data from the front-end name = request.form['name'] description = request.form['description'] ...
0c108ff1d9cf86ef072ed723c067d94b11b82ddd
3,630,449
def create_densenet(hidden_units, idx_to_cat): """Create a flowernet model based on the Densenet-121 architecture. Args: hidden_units: The number of hidden units in the flowernet classifier. idx_to_cat: A dictionary mapping the internal index numbers provided by the classifier to ...
86643b9ca3b85d1aa940917c8c0fbe8467100ee6
3,630,450
import tokenize def cleanup_string(string, already_lowercase=False): """ Do the following cleanup steps on the provided string: 1. Case Folding 2. Tokenization 3. Give it to cleanup_list() """ if not already_lowercase: # Case folding ...
5e3dccec9306097c5e952f69d883a78507991779
3,630,452
def fscore(mesh1, mesh2, sample_count=100000, tau=1e-04, points1=None, points2=None): """Computes the F-Score at tau between two meshes.""" points1, points2 = get_points(mesh1, mesh2, points1, points2, sample_count) dist12, _ = pointcloud_neighbor_dista...
07707b4ae58d3aa4f559ceb7f2b5f82c9d7fe8a7
3,630,453
def jsonp_ize(dep): """Parse dep as :term:`jsonp` (unless it has been modified with ``jsnop=False``). """ return modify(dep) if "/" in dep and type(dep) is str else dep
0e5ff172a732a9319e7486a67cfd1db6520c8cf1
3,630,454
import re def is_guid(techfin_tenant): """Validate guid arg Args: tenant (str): techfin tenant id Returns: bool: true if is valid guid value """ c = re.compile('[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}', re.I) res = c.match(techfin_tenant) r...
7242f0da279375ab5873670ffef1fd4aa8749546
3,630,455