content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def collect_ips(): """Fill IP addresses into people list. Return if all addresses collected or not.""" out, rc, _ = run_cmd('sudo nmap -sn ' + net, log_error=False) if rc: print "Error: nmap is required. Run following command:" print "sudo apt-get -y install nmap" sys.exit(4) #...
52d1369d4af469a62af465b000489ad43f71d2e3
30,186
def roles(*role_list): """ Decorator defining a list of role names, used to look up host lists. A role is simply defined as a key in `env` whose value is a list of one or more host connection strings. For example, the following will ensure that, barring an override on the command line, ``my_func`` ...
2e30be0cb8876085c0c071b61a0a62061904816e
30,187
def stairmaster_mets(setting): """ For use in submaximal tests on the StairMaster 4000 PT step ergometer. Howley, Edward T., Dennis L. Colacino, and Thomas C. Swensen. "Factors Affecting the Oxygen Cost of Stepping on an Electronic Stepping Ergometer." Medicine & Science in Sports & Exercise 24.9 (1992): n...
1d6cc9fc846773cfe82dfacb8a34fb6f46d69903
30,189
from typing import Optional from typing import List from pathlib import Path from typing import Protocol def get_uri_for_directory(directory: str, excludes: Optional[List[str]] = None) -> str: """Get a content-addressable URI from a directory's contents. This function will generate ...
acb7586d9adf210563ba73c3aed46c8ac695be26
30,190
def clean_cancer_dataset(df_training): """ Checks and cleans the dataset of any potential impossible values, e.g. bi-rads columns, the 1st only allows values in the range of 1-5, ordinal Age, 2nd column, cannot be negative, integer Shape, 3rd column, only allows values between 1 and 4, nominal M...
a30f377b48bb665f42f3efa58b15d289f7e7f9b3
30,191
from datetime import datetime def str_to_date(date, form=None): """ Return Date with datetime format :param form: :param date: str date :return: datetime date """ if form is None: form = get_form(date) return datetime.datetime.strptime(date, form)
acda6e393b468ffaf8eceb689c859440a53e486e
30,192
def get_model_results(corpus, texts, ldamodel=None): """function extract model result such as topics, percentage distribution and return it as pandas dataframe in: corpus : encoded features in: text : main text in: ldamodel: the trained model out: dataframe """ topics_df = pd.DataFrame() ...
31aa99db41193d2e25bd723720b68eb30606517f
30,193
def rest_notify(): """Github rest endpoint.""" sdkid = request.args.get("sdkid") sdkbase = request.args.get("sdkbase", "master") sdk_tag = request.args.get("repotag", sdkid.split("/")[-1].lower()) if not sdkid: return {'message': 'sdkid is a required query parameter'} rest_bot = RestAP...
4f7c15186fbb2d0a4a3dd7199045178b62da362f
30,194
def lib_pt_loc(sys_chars_vals, tolerance = 1e-12): """Computes Non-Dimensionalized Libration Points Location for P1-P2 system Parameters ---------- sys_chars_vals: object Object of Class sys_char tolerance: float convergence tolerance for Newton-Raphson Method ...
2ee92c8f6e91353a675236a7f63eed4d7f807846
30,195
def _find_connection_file(connection_file): """Return the absolute path for a connection file - If nothing specified, return current Kernel's connection file - Otherwise, call jupyter_client.find_connection_file """ if connection_file is None: # get connection file from current kernel ...
2e4adfd67e0d2b35545cab1e82def271175b9de3
30,197
from typing import List def _symbols_of_input(label: str) -> List[str]: """Extracts FST symbols that compose complex input label of the rewrite rule. FST symbols of a complex input label is; - Epsilon symbol if the complex input label is an epsilon symbol (e.g. ['<eps>'] for label '<eps>'). - Digit...
8298a242701aa586ba50ffa6059a8e33e4cf01f3
30,198
def preset_select_func(area, preset): """Create preset selection packet.""" return DynetPacket.select_area_preset_packet(area, preset, 0)
9ae5e162cb32c3f3b0ab1d07e1d5cd2961e1e91e
30,199
def init_model(model_name, network_config, classes, word_dict, init_weight=None, log_path=None, learning_rate=0.0001, optimizer='adam', momentum=0.9, weight_decay=0, metr...
c3fae65c54d12b30ef34b79fbe600d60d7837042
30,200
import io def boxed_img(img_data): """return base64 encoded boxed image.""" if isinstance(img_data, str): img_path = img_data else: img_path = img_buffer(img_data) img, result = obj_detect(img_path) boxed_np_image = draw_boxes( img.numpy(), boxes=result["detection_b...
b5dbfaf2297b2faff776550d252b3010350c09db
30,201
def exec(statement, table_name=None, commit=True): """ execute a SQL statement in the database and commit the transaction. If a table_name is passed in, then the query will be checked for proper completion, returning a boolean """ conn = connection() cursor = conn.cursor(buffered=True) if table_nam...
c62ec09961cd4f284497f88d91f3b64100eef1ff
30,202
def isvalid(gridstr, x, y, test_value): """ Check if it would be legal to place a in pos x,y """ sq_indexes = ((0, 1, 2), (3, 4, 5), (6, 7, 8)) group_indexes = [(x_ind, y_ind) for x_ind in sq_indexes[x // 3] for y_ind in sq_indexes[y // 3]] for index in range(9...
a8481bbb18409814e54ad669bbb14b71e32b1139
30,203
def GilmoreEick(R0_in, v0_in, Requ, \ t_start, t_end, t_step, \ T_l=20.): """Run the calculation (Gilmore + Eick) with the given initial conditions and parameters. returns: t, R, R_dot, pg, T, i """ global T global T_gas_0, sc_pvapour T_gas_0 = T0_Ke...
3cd06254a67b5ba76674aa59dff190e99e5e6075
30,205
def gamma(x): """ element-wise gamma function """ return Gamma().forward(x)
73f53c8010974e171ee7a11bdc2ea705dd3c1eb5
30,206
def build_model_with_precision(pp, mm, ii, tt, *args, **kwargs): """Build model with its inputs/params for a specified precision context. This is highly specific to this codebase, and not intended to be general API. Advanced users only. DO NOT use it if you don't know what it does. NOTE: short argument...
2af975ce06560dc0637da8b8e24b1ca3e9213d65
30,207
def bisection(a, b, poly, tolerance): """ Assume that poly(a) <= 0 and poly(b) >= 0. Modify a and b so that abs(b-a) < tolerance and poly(b) >= 0 and poly(a) <= 0. Return (a+b)/2 :param a: poly(a) <= 0 :param b: poly(b) >= 0 :param poly: polynomial coefficients, low order first :param to...
e4068887f41078e00006905512e42645a6bc5405
30,208
from typing import Iterable def get_roc_with_band(quotes: Iterable[Quote], lookback_periods: int, ema_periods: int, std_dev_periods: int): """Get ROCWB calculated. Rate of Change with Bands (ROCWB) is the percent change of Close price over a lookback window with standard deviation bands. Parameters:...
ffed73567f17645fb35e257a69c3ab64002483c4
30,209
from bs4 import BeautifulSoup def get_poetry_page_links(html): """Read in the html from a poetry page and return an array of links""" clean_links = [] html_soup = BeautifulSoup(html, 'html.parser') # remove the table of contents try: [e.extract() for e in html_soup.find("div", {"id": "toc"})] except...
bfa0dc5aa4e63b8aeb42f785dd2afb67e8816474
30,210
def _exponential_rv(t, tau, T): """Generate truncated exponential random variable from uniform [0, 1) random variable. Parameters ---------- t : array-like Uniform [0, 1) random variable. tau : array-like Lifetime. T : array-like Truncation parameter. """ return ...
356e542f83b2a1b78a11b1dcf65c21dcdd2803a6
30,212
from typing import Any import signal def apply_noise_filtering( fully_calibrated_gmr: NDArray[(2, Any), int], scipy_filter_sos_coefficients: NDArray[(Any, Any), float], ) -> NDArray[(2, Any), int]: """Apply the result of an empty plate calibration. Actual empty plate calibration will be performed onc...
f44331ce6286f8c1cbe08d243ee6c52e06d52c11
30,213
from typing import Any import io def read_file(filename: Text, encoding: Text = "utf-8") -> Any: """Read text from a file.""" with io.open(filename, encoding=encoding) as f: return f.read()
de51cb0edd53dbddb3458adbceafddcb5fc3d6e0
30,214
def pattern_note_to_midi_note(pattern_note_byte, octave_offset=0): """ Convert pattern note byte value into midi note value :param pattern_note_byte: GT note value :type pattern_note_byte: int :param octave_offset: Should always be zero unless some weird midi offset exists :type octave_offset:...
372f15e9b8b94ac6f37900b85f7d63d75b256669
30,215
def FileHole(thisMesh, topologyEdgeIndex, multiple=False): """ Given a starting "naked" edge index, this function attempts to determine a "hole" by chaining additional naked edges together until if returns to the start index. Then it triangulates the closed polygon and either adds the faces to the mesh....
1a3da0c9c96147e5a18a228cc01558b4d9daca68
30,216
def wide_to_narrow(X, Y, bins): """ Convert data from predicting a Y(Zbin,Cbin) as a vector to individual predictions of Y(Zbin,Cbin) given a Zbin and Cbin label in the input data. """ varname = "variable" valname = "Y" x_vars = get_xnames() dev = pd.concat([X, Y], axis=1) left ...
3543e2428f4c38eb668428eb68cc1ccdea9fcb0f
30,217
def get_coords(p): """Function to get coordinates of N, Ca, C. It also calculates Cb positions from those. """ nres = pyrosetta.rosetta.core.pose.nres_protein(p) # three anchor atoms to build local reference frame N = np.stack([np.array(p.residue(i).atom('N').xyz()) for i in range(1,nr...
d87eed8793536b7858ad9aa870c9a5c086b6c8d8
30,218
import re import statistics import string import copy import random def expand_dataset(sentences_file, scores_file, category_getter_fn): """ Expands Stanford Sentiment Treebank dataset file by substituting nouns, verbs and adjectives in each sentence with synonyms retrieved from WordNet. Processes into a set ...
9fcfd01769a8330ffd2fe533ff66b699cef637aa
30,219
import io def load_as_hsv(fname: str) -> np.ndarray: """ Load a file into HSV colour space. Takes a file path and opens the image then converts to HSV colour space. returns numpy array dtype float 64. Strips the alpha (fourth) channel if it exists. Input must be colour image. One channel images w...
c71ed010bcce47f756f5d539f73100257dcae2c0
30,220
def get_databases (): """ Returns a list of all Database objects stored. """ return _dbobjects[:]
b5c3d84fc4a58b0a78a3f8f2c4a5a4974a18e337
30,221
def GenomicRegions_FilterToOverlapping( new_name, gr_a, other_grs, summit_annotator=None, sheet_name="Overlaps" ): """Filter to just those that overlap one in *all* other_grs. Note that filtering does not change the coordinates, it only filters, non annotator additional rows are kept, annotators are rec...
192443e04d5bb3be91574e3494248020cf28be37
30,222
def findPowerPlant(mirror, name): """Return power plant agent, if it exists""" if name in mirror.ppDict: return mirror.ppDict[name] else: print("*** Power Plant '%s' not found." % name) return None
35e432c7ab6dbe57488e2d7f84c3b6d077f2079a
30,224
import struct def create_cruise_adjust_msg(spdCtrlLvr_stat, turnIndLvr_Stat, real_steering_wheel_stalk): """Creates a CAN message from the cruise control stalk. Simluates pressing the cruise control stalk (STW_ACTN_RQ.SpdCtrlLvr_Stat) and turn signal stalk (STW_ACTN_RQ.TurnIndLvr_Stat) It is probably best no...
145f5841cebf1db7a80faa36225e9abc92b9ea96
30,225
import logging def get_build_history(build_ids): """Returns build object for the last finished build of project.""" build_getter = BuildGetter() history = [] last_successful_build = None for build_id in reversed(build_ids): project_build = build_getter.get_build(build_id) if project_build['status...
faf833ecd6250d0bd90b3477d99502f1cc7a7597
30,226
def point_translate(point_in, vector_in): """ Translates the input points using the input vector. :param point_in: input point :type point_in: list, tuple :param vector_in: input vector :type vector_in: list, tuple :return: translated point :rtype: list """ try: if point_in ...
3b5346062c47f45736d38dce0219f0543b54da6e
30,227
def pcmh_1_1b__1_2_3_4(): """Clinical advice (telephone encounters)""" telephone_encounter_table_url = URL('init', 'word', 'telephone_log.doc', vars=dict(type="meeting", **request.get_vars), hmac_key=MY_KEY, salt=session.MY_SALT, h...
21d8c9a0a05aef963d858eca572abe4d23566a52
30,228
import math def distance(x1, y1, x2, y2): """ l2 distance """ return math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2))
709c32bb9bad08d0413c7de80019514f75fc739d
30,229
def slice_signal(signal, window_size, stride=0.5): """ Return windows of the given signal by sweeping in stride fractions of window """ assert signal.ndim == 1, signal.ndim n_samples = signal.shape[0] offset = int(window_size * stride) slices = [] for beg_i, end_i in zip(range(0, n_s...
4341fc45df28dd336001252cc8618018257cd257
30,230
def get_railway() -> User: """鉄道用ユーザ情報を取得する Raises: DynamoDBError: 鉄道用ユーザ情報が登録されていない Returns: User: 鉄道用ユーザ情報 """ railway_user = get_user("railway") if railway_user is None: raise DynamoDBError("鉄道用ユーザ情報が登録されていません。") return railway_user
23315e567f8136510a8ee821c3167f53aea9556c
30,231
def check_threshold(service, config_high_threshold, config_low_threshold, curr_util): """ Checks whether Utilization crossed discrete threshold Args: service: Name of the micro/macroservice config_high_threshold: Upper limit threshold to utilization set in config file config_low_thresho...
80bf8ab4f5b2bbac35df7c48764114e213fba580
30,232
import requests import json def is_human(captcha_response): """ Validating recaptcha response from google server. Returns True captcha test passed for the submitted form else returns False. """ secret = RECAPTCHA_KEYS["secret_key"] if secret != "": payload = {'response':captch...
547eca43bf9994539f2e95b4605df24432bf3998
30,233
def ols_data(): """ draper and smith p.8 """ xs = [35.3, 29.7, 30.8, 58.8, 61.4, 71.3, 74.4, 76.7, 70.7, 57.5, 46.4, 28.9, 28.1, 39.1, 46.8, 48.5, 59.3, 70, 70, 74.5, 72.1, 58.1, 44.6, 33.4, 28.6] ys = [10.98, 11.13, 12.51, 8.4, 9.27, 8.73, 6.36, 8.50, 7.82, 9.14, 8.2...
d741195075a51d1485c9f98031ca405cadf1db93
30,235
def get_as_type(obj): """Find the name of ActionScript class mapped to the class of given python object. If the mapping for the given object class is not found, return the class name of the object.""" type = obj.__module__ + '.' + obj.__class__.__name__ if class_mappings: for as_class, py_cla...
83d5019cb9e54a6ad3d8e4e926edb285953ea53d
30,236
def svn_auth_get_ssl_client_cert_pw_file_provider2(*args): """ svn_auth_get_ssl_client_cert_pw_file_provider2(svn_auth_plaintext_passphrase_prompt_func_t plaintext_passphrase_prompt_func, void prompt_baton, apr_pool_t pool) """ return _core.svn_auth_get_ssl_client_cert_pw_file_provider2(*a...
585c3b14505a109908fdb109b0fb4c1f5e3df5cd
30,237
def valid_field(obj, field): """Returns ``True`` if given object (BaseDocument subclass or an instance thereof) has given field defined.""" return object.__getattribute__(obj, 'nanomongo').has_field(field)
32e662c5c0e666b7455aacdd6809e31cd20017fe
30,238
def construct_location_name(location: dict) -> str: """ Constructs a location name based on the supplied dictionary of elements, ensuring that they are in the correct format """ if location["type"] == "location": city_name = capwords(location["city"]) if "country" in location: ...
d5728bf409a4520f0b8a508797d67cd00e6676d1
30,239
def anammox(k_anammox, o2s_dn, nh4, no2, o2): """Anammox: NO2- + NH4+ -> N2 + 2H2O k_anammox - velocity of anammox o2s_dn - half-saturation oxygen inhibitor constant for anammox and denitrification""" return k_anammox*nh4*no2*hyper_inhibitor(o2s_dn, o2, 1)
d65fa90d9aaf83982157811dfb7a30d461da75bd
30,240
def courbe_vers_c(l, l2, n0,CP): #c,C """ B=Bez() B.co=[l[0],l[1],l[2],l[3],l[4],l[5]] B.ha=[0,0] courbes.ITEM[n0].beziers_knot.append(B) """ B=Bez() B.co=[G_move(l[2],0), G_move(l[3],1), G_move(l[4],0), G_move(l[5],1), G_move(l[0],0), G...
3e3577a90a2fca8d0868c2abf0a96ee73ecdd124
30,241
def _synthesize_human_beta_vj_background(ts,fn = None, df = None): """ _build_vj_background Parameters ---------- ts: tcrsampler.TCRsampler() a TCRsampler instance, with gene usage frequencies (ideally computed get_stratified_gene_usage_frequency() fn: str file path to MIRA set...
c4f0126ddeb1f0d3fd2ea05e031316de7c0118b2
30,242
def swissPairings(): """Returns a list of pairs of players for the next round of a match. Args: tournament: the id number of the tournament played Returns: A list of tuples, each of which contains (id1, name1, id2, name2) id1: the first player's unique id name1: the first playe...
ed55ccffc866a9d7bab93dbf5b0989709a31d287
30,243
def double_bin_pharmacophore_graph(distance, bins, delta): """ Assign two bin values to the distance between pharmacophoric points. Parameters ---------- distance : float The distance that will be binned. bins : np.ndarray Array of bins. It h...
b7dedf4f31b5cd08c9875139df837a57a8117001
30,244
def get_help(path): """ Context Sensitive Help (currently not implemented). """ try: helpitem = HelpItem.objects.get(link=path) except HelpItem.DoesNotExist: helpitem = "" return { 'helpitem': helpitem }
f2fc3599c86e408e3341870539e1572412b5c8f4
30,245
def _GKEConnectNamespace(kube_client, project_id): """Returns the namespace into which to install or update the connect agent. Connect namespaces are identified by the presence of the hub.gke.io/project label. If there is one existing namespace with this label in the cluster, its name is returned; otherwise, a...
3a98c72fac0f0ae297f4fb026368c137779eb5f6
30,247
def triplet_loss_compute_semihard(feature1, feature2, labels, margin=1.0): """ triplet loss with semi-hard negative pairs """ batch_size = labels.get_shape().as_list()[0] labels = tf.cast(tf.reshape(labels, [batch_size, 1]), tf.float32) feature1 = tf.nn.l2_normalize(tf.reshape(feature1, [batch_size...
153cb805c3aa7ec2b87d29ae15a7c91a3874c95f
30,249
from typing import List from typing import Type def get_all_markups() -> List[Type[AbstractMarkup]]: """ :returns: list of all markups (both standard and custom ones) """ try: # Python 3.10+ entrypoints = entry_points(group="pymarkups") except TypeError: # Older versions entrypoints = entry_points()["pymar...
78bcdb402f52b7a6d6e1b78816ba0d215f449e83
30,250
def esg_route_list(client_session, esg_name): """ This function return the configured static routes :param client_session: An instance of an NsxClient Session :param esg_name: The name of the ESG of which the routes should be listed :return: returns a tuple, the firt item of the tuple contains a lis...
fc8565aba651dbb452a9cab2d80d774130c08b00
30,251
def create_instance_profile(profile_name, role_name=None): """ Creates IAM instance profile :param profile_name: Name of profile to be created :param role_name: Name of role to attach to instance profile :return: API response """ try: creat...
0088f5b0c7b0ac35cff12b859bc4c27662761705
30,252
def is_primary(flag): """ :return bool: Returns whether the current record is primary alignment """ if flag is None: raise ValueError("No flag associated with this record") return not SamFlag.IS_UNMAPPED & flag and not SamFlag.IS_SECONDARY_ALIGNMENT & flag
09d6cfae6568bd10315f10f5b19790db07d05b58
30,254
from typing import Optional from typing import Set def extract_years(text: str, default: Optional[str] = None) -> Set[str]: """Try to locate year numbers in a string such as 'circa 1990'. This will fail if any numbers that don't look like years are found in the string, a strong indicator that a more preci...
854f62d5c40d3411a7e792c02d7e03db86c68026
30,256
def is_absolute_url(parsed_url): """ check if it is an absolute url """ return all([parsed_url.scheme, parsed_url.netloc])
578c1443ec18f9b741cd205763604cba2242ac48
30,257
import torch def so3_exp_map(log_rot: torch.Tensor, eps: float = 0.0001) -> torch.Tensor: """ Convert a batch of logarithmic representations of rotation matrices `log_rot` to a batch of 3x3 rotation matrices using Rodrigues formula [1]. In the logarithmic representation, each rotation matrix is repre...
e839d6398502e920bbc7841b1a9fe8f48e9cfce9
30,258
import pkg_resources def get_example_summary_file(): """Convenience wrapper to retrieve file path from package data.""" return pkg_resources.resource_filename('tempset', 'data/electric/summary.zip')
a6fcb3a1f9c78f07e3a5861a93ac8f5a2983bf93
30,259
def set_pH(in_smi): """Function to set the pH of a molecule Currently uses OpenBabel to perform protonation (to pH 7.4) Takes a smiles string Returns the protonated smiles string""" # Attempt to use the babel that has been included in the distro try: d = sys._MEIPASS babel_path ...
f815f661efe5f660260f4625d586b81e2cf14d13
30,260
import requests import json def get_hardware_status(ip, port, username, password) -> dict: """Gets CPU memory statuses IOS-XE\n Cisco-IOS-XE-platform-software-oper:cisco-platform-software/control-processes/control-process""" ###### Future Use data = {} try: uri = f"https://{ip}:{por...
e1b305871c773a1bbf69e60681a4b2718a7e0dcd
30,261
def q2_2(df: pd.DataFrame) -> tuple: """ Calculates mean and median for V2 of df, returns tuple of (mean, median) """ V2 = df["V2"] return V2.mean(), V2.median()
3e72b2fe71c4afe2e608c80f7aefc529b9681af8
30,262
def dup_rr_primitive(f, K): """Returns content and a primitive polynomial over a ring. """ cont = dup_content(f, K) if not f or K.is_one(cont): return cont, f else: return cont, dup_exquo_ground(f, cont, K)
7c590daabb04baba51675a3681013434baec87a7
30,263
def mk_png(html: str, folder=None) -> str: """Return generated PNG file path""" folder = (local.path(folder) if folder else local.path('/tmp/ccb_png')) / uuid4() folder.mkdir() png = folder / 'code.png' ( convert['-trim', '-trim', '-', png] << HTML(string=html, media_type='screen').w...
448bbfbfff6184648542af6426f063e6f5adf2e9
30,264
def entry_breadcrumbs(entry): """ Breadcrumbs for an Entry. """ date = entry.publication_date if is_aware(date): date = localtime(date) return [year_crumb(date), month_crumb(date), day_crumb(date), Crumb(entry.title)]
204b061b48622c74bb67e7af90b11b2aa93e3cc7
30,265
def w_desired_supply_line(): """ Real Name: b'W Desired Supply Line' Original Eqn: b'W Delivery Delay*W Expected Customer Orders' Units: b'SKU' Limits: (None, None) Type: component b'' """ return w_delivery_delay() * w_expected_customer_orders()
c71161e4e306bf8aa6d7a1b2ea679a228c5a991c
30,266
def _ShardName(name, number): """Add a shard number to the end of a target. Arguments: name: name of the target (foo#target) number: shard number Returns: Target name with shard added (foo_1#target) """ return _SuffixName(name, str(number))
ce21fb4826fc6626ade140d84195c7db8b616e39
30,267
import math def ReadMartiniMolecules(GroFile, First, Last): """ Generate the normalized coordinates, name, and vector of the Martini molecule Access the Martini3 small molecules library and reads the parameterized coordinates from it, with future view of looking at generating automatically generati...
e9979c5cd82f8ff2a63d6f74bb19db3fced3e89d
30,268
def average_gen_fock(filename, fock_type='plus', estimator='back_propagated', eqlb=1, skip=1, ix=None): """Average AFQMC genralised Fock matrix. Parameters ---------- filename : string QMCPACK output containing density matrix (*.h5 file). fock_type : string Whic...
6e9869663ed0866e8d5ee81e0b1adfc9f4ee6fa2
30,269
def start_ignite(test_context, ignite_version: str, rebalance_params: RebalanceParams) -> IgniteService: """ Start IgniteService: :param test_context: Test context. :param ignite_version: Ignite version. :param rebalance_params: Rebalance parameters. :return: IgniteService. """ node_cou...
5cbd9e6946fcbaf063d9de72074a14794f65d234
30,270
def simplify(expr, *exprs, **kwargs): """Simplify the given expression[s].""" if exprs: return _coconut_tail_call((tuple), (map)(lambda x: x.simplify(**kwargs), (expr,) + exprs)) else: return _coconut_tail_call(expr.simplify, **kwargs)
7982869f98f5296e4e596cfbed909a5c4caa9ba7
30,271
def ratek_fit_info(rxn_dstr): """ Read the information describing features of the fits to the rate constants """ # Read the temperatures and the Errors from the lines pressure_ptt = ( 'Pressure:' + app.SPACES + app.capturing(app.one_of_these([app.FLOAT, 'High'])) ) trang...
dbed1c66b68a6ddbe0d4d8af3e91736131220383
30,272
def ifrt2(a): """Compute the 2-dimensional inverse finite radon transform (iFRT) for an (n+1) x n integer array. Parameters ---------- a : array_like A 2-D (n+1) row x n column integer array. Returns ------- iFRT : 2-D n x n ndarray Inverse Finite Radon Transform array ...
2fa7f3c8fc3b6ed0e7ee9c58d9587644314d6608
30,274
def get_levelized_cost(solution, cost_class='monetary', carrier='power', group=None, locations=None, unit_multiplier=1.0): """ Get the levelized cost per unit of energy produced for the given ``cost_class`` and ``carrier``, optionally for a subset of technologie...
96b8f9a9fceaa932bcee72033e73ad8b9551759d
30,275
def weighting_system_c(): """C-weighting filter represented as polynomial transfer function. :returns: Tuple of `num` and `den`. See equation E.1 of the standard. """ f1 = _POLE_FREQUENCIES[1] f4 = _POLE_FREQUENCIES[4] offset = _NORMALIZATION_CONSTANTS['C'] numerator = np....
02b77bafbbba2671c15667f81bad965383b21f33
30,276
def make_fully_qualified_url(url): """ Ensure url is qualified """ if url.startswith("//"): return "https:" + url if url.startswith("/"): return "https://en.wikipedia.org" + url assert url.startswith("http"), "Bad URL (relative to unknown location): " + url return url
9b87adaa0a30c5a09e81dd73aea3f282af92ac53
30,277
def reduce_range_overlaps(ranges): """Given a list with each element is a 2-tuple of min & max, returns a similar list simplified if possible. """ ranges = [ea for ea in ranges if ea] if len(ranges) < 2: return ranges first, *ranges_ordered = list(reversed(sorted(ranges, key=lambda ea: ea[1] - e...
fe62dd8bbb1fd0a985757cc417c9c230659294c5
30,278
def get_averages_by_addon_from_bigquery(today, exclude=None): """This function is used to compute the 'hotness' score of each add-on (see also `update_addon_hotness()` cron task). It returns a dict with top-level keys being add-on GUIDs and values being dicts containing average values.""" client = c...
5c50f10ffa3c15beab6ae204bbd796050e85e66a
30,279
def main_menu(): """Dialog for the ATM Main Menu.""" # Determines action taken by application. action = questionary.select( "Would you like to check your balance, make a deposit or make a withdrawal?", choices=["check balance", "deposit", "withdrawal"], ).ask() return action
add02dfc371c24e89c73e336c5efe3ff800e6d00
30,280
def load_sentences_from_naf(iteration, root, naf_entity_layer, modify_entities): """Load sentences from a single NAF file (already loaded). Potentially replace entity mentions with their identity.""" if modify_entities: to_replace=map_mentions_to_identity(root, naf_entity_layer) # Create list of l...
054a5adadcd170ac5525bc0bc6d5dd32bcdf14ae
30,281
def get_detection_eff_matrix(summary_table, num): """Computes the detection efficiency matrix for the input detection summary table. Input argument num sets the maximum number of true objects per blend in the test set for which the detection efficiency matrix is to be created for. Detection efficiency ...
8fa28c1f278bc14ee6877f50297f6554bc413392
30,282
def unicode_to_base64(text, strip_newlines=True): """Safe conversion of ``text`` to base64 representation using utf-8 bytes. Strips newlines from output unless ``strip_newlines`` is `False`. """ text = to_unicode(text) if strip_newlines: return text.encode('utf-8').encode('base64').re...
34593c1811dac718bc82f47e590da62d1d704de4
30,283
def _valid_path(g, path, master_nodes): """ Test if path contains masternodes. """ valid = True if path[0] not in master_nodes: valid = False if path[-1] not in master_nodes: valid = False for n in path[1:-1]: if 'pin' in g.node[n]: # if _is_master(g, n): # ...
e91c0a53b994316073f97e854b9e4933d760c078
30,284
import io def usgs_stonecr_call(*, resp, year, **_): """ Convert response for calling url to pandas dataframe, begin parsing df into FBA format :param url: string, url :param resp: df, response from url call :param year: year :return: pandas dataframe of original source data """ df...
41d63f8175eaa0b5a5b2d03e40ea0bfb73ed70d4
30,285
def read_line(**kwargs): """ Gets next line in input. If `skip_empty` is True, only lines with at least one non-whitespace character are returned. :return: str """ tokenizer = _get_tokenizer(kwargs) skip_empty, rstrip = kwargs['skip_empty'], kwargs['rstrip'] try: if skip_empty: ...
82a24906872076afc26193dcd8bfb3be225c70d9
30,286
def _coco17_category(): """ Get class id to category id map and category id to category name map of COCO2017 dataset """ clsid2catid = { 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10, 11: 11, ...
0a242332391c5fbf21be0c434c64c104db1b3055
30,287
def identical_sort(df_true, df_subm): """ Check if 2 DataFrames are sorted the same This check is only conducted whenever a perfect F1 score is achieved. It only verifies whether or not the first and last tuple have the same relative order in both DataFrames. It is thus not an explicit check! ...
94363275f66fe84829f90f49afa57237fa05c1a5
30,288
def bigbird_block_sparse_attention( query_layer, key_layer, value_layer, band_mask, from_mask, to_mask, from_blocked_mask, to_blocked_mask, rand_attn, num_attention_heads, num_rand_blocks, size_per_head, batch_size, from_seq_length, to_seq_length, from_block_size, to_block_size): """BigBird attention ...
73a486a26510137de84017063e624de5379e4fbe
30,289
def color_diff(rgb_x: np.array, rgb_y: np.array) -> float: """ Computes the distance between two colors using Euclidean distance. :param rgb_x: a vector of one rbg color :param rgb_y: a vector of another rgb color :return: the distance between two vectors """ return np.sum((rgb_x - rgb_y) *...
0e9136c68a00f5d85d2a13311f083d8036329b0a
30,290
def functions(node): """:returns: list of function tags for node, or an empty list.""" if not node.source: return [] a = node.source[FUNC] if a == '--' or a == '' or a is None: return [] return a.split('-')
3167ebd1d382b5ac8b46dd4565cd2184844840f1
30,292
def _calibrate_bg_and_psf_im(im, divs=5, keep_dist=8, peak_mea=11, locs=None): """ Run background & PSF calibration for one image. These are typically combined from many fields and for each channel to get a complete calibration. This returns the accepted locs so that a z-stack can be estimated ...
3eb73736470253c72b03875415ea413802470153
30,293
def get_default_database_engine(rm: ResourceManager, database_name: str) -> Engine: """ Get the default engine of the database. If the default engine doesn't exists raise FireboltError """ database = rm.databases.get_by_name(name=database_name) bindings = rm.bindings.get_many(database_id=databa...
c26d7bcac96b0272b38126cae824d7d0f1df0261
30,294
def _execute_onestep(seq, order=2, verbose=False): """ This function runs one full step of the non-sequential recursive window- substitution algorithm. (For pairs or order=2, called NSRPS). For internal use only, as this function does not carry out sanity checks. For general/external usage, refer t...
5f655cc5f67ddbd9ae27b0461a9932e87d2a91b9
30,295
def getModulePower(): """Returns the current power consumption of the entire module in mW.""" return float(readValue(i2cAddr='0041', channel='0', valType='power'))
4bfb362ffdeb9a210cb8bfc5cc203d50f9c28582
30,296
def roots(repo, subset, x): """``roots(set)`` Changesets in set with no parent changeset in set. """ s = set(getset(repo, repo.changelog, x)) subset = [r for r in subset if r in s] cs = _children(repo, subset, s) return [r for r in subset if r not in cs]
2acb2f803966c3024a5d148e4856d44c13287cef
30,297