content
stringlengths
22
815k
id
int64
0
4.91M
def test_Highest_Greedy_Score__Single_Placable_Disk(score, max_score): """Function highest_greedy_score: Single disk.""" max_score.value += 6 try: set_up() test_board_6_copy = Board.get_board_copy(test_board_6) disks_to_drop = [visible_disk_value_2_B] disks_to_drop_copy = lis...
5,338,400
def __loadConfig(): """ Load an .ini based config file. """ global __CONFIG, __DEFAULT_CONFIG if not os.path.exists(__USER_CONFIG_FILENAME): # if the user has no config, # copy the default one to the expected location shutil.copy(__DEFAULT_CONFIG_FILENAME, __USER_CONFIG_FILEN...
5,338,401
def model_density_of_sky_fibers(margin=1.5): """Use desihub products to find required density of sky fibers for DESI. Parameters ---------- margin : :class:`float`, optional, defaults to 1.5 Factor of extra sky positions to generate. So, for margin=10, 10x as many sky positions as the d...
5,338,402
def edit_train_mp3(address_mp3, time_first_slice, time_last_slice, num_repeats, break_time, address_folder, name_new_mp3 ): """ Функция создает зацикленный тренировочный mp3 файл ...
5,338,403
def op_finish_word_definition(c: AF_Continuation) -> None: """ WordDefinition(Op_name), OutputTypeSignature(TypeSignature), CodeCompile(Operation') -> (empty) """ op_finish_word_compilation(c) c.stack.pop()
5,338,404
def dice_counts(dice): """Make a dictionary of how many of each value are in the dice """ return {x: dice.count(x) for x in range(1, 7)}
5,338,405
def SynthesizeData(phase, total_gen): """ Phase ranges from 0 to 24 with increments of 0.2. """ x_list = [phase] y_list = [] while len(x_list) < total_gen or len(y_list) < total_gen: x = x_list[-1] y = sine_function(x=x, amp=amp, per=per, shift_h=shift_h, shift_v=shift_v) x_lis...
5,338,406
def compare(): """ Eats two file names, returns a comparison of the two files. Both files must be csv files containing <a word>;<doc ID>;<pageNr>;<line ID>;<index of the word> They may also contain lines with additional HTML code (if the output format is html): ...
5,338,407
def draw_transform(dim_steps, filetype="png", dpi=150): """create image from variable transormation steps Args: dim_steps(OrderedDict): dimension -> steps * each element contains steps for a dimension * dimensions are all dimensions in source and target domain * each step i...
5,338,408
def get_ei_border_ratio_from_exon_id(exon_id, regid2nc_dic, exid2eibrs_dic=None, ratio_mode=1, last_exon_dic=None, last_exon_ratio=2.5, ...
5,338,409
def test_sysparm_input_display_value(mocker, requests_mock): """Unit test Given - create_record_command function - command args, including input_display_value - command raw response When - mock the requests url destination. Then - run the create command using the Client Validate ...
5,338,410
def events(*_events): """ A class decorator. Adds auxiliary methods for callback based event notification of multiple watchers. """ def add_events(cls): # Maintain total event list of both inherited events and events added # using nested decorations. try: all_events = cl...
5,338,411
def test_losers_advantage(client): """ user with the lose_count of 3 and others with that of 0 attempt to apply a lottery test loser is more likely to win target_url: /lotteries/<id>/draw """ users_num = 12 idx = 1 win_count = {i: 0 for i in range(1, users_num + 1)} ...
5,338,412
def print_column_vertically(target_column_name, dataset): """ Prints each variable of a column to a new line in console. :param target_column_name: (str) Header of the column to be printed :param dataset: dataset to column is in :returns: Strings printed to console :example: >>> long_da...
5,338,413
def _find_nearest(array, value): """Find the nearest numerical match to value in an array. Args: array (np.ndarray): An array of numbers to match with. value (float): Single value to find an entry in array that is close. Returns: np.array: The entry in array that is closest to valu...
5,338,414
def download_document(url): """Downloads document using BeautifulSoup, extracts the subject and all text stored in paragraph tags """ r = requests.get(url) soup = BeautifulSoup(r.text, 'html.parser') title = soup.find('title').get_text() document = ' '.join([p.get_text() for p in soup.find_all('p')]) return doc...
5,338,415
def rz_gate(phi: float = 0): """Functional for the single-qubit Pauli-Z rotation-gate. Parameters ---------- phi : float Rotation angle (in radians) Returns ------- rz : (2, 2) np.ndarray """ arg = 1j * phi / 2 return np.array([[np.exp(-arg), 0], [0, np.exp(arg)]])
5,338,416
def test_append_to_history(qtbot, historylog): """ Test the append_to_history method. Test adding text to a history file. Also test the go_to_eof config option for positioning the cursor. """ hl = historylog hw = historylog.get_widget() # Toggle to move to the end of the file after ap...
5,338,417
def dict_to_kvp(dictionary: dict) -> List[tuple]: """ Converts a dictionary to a list of tuples where each tuple has the key and value of each dictionary item :param dictionary: Dictionary to convert :return: List of Key-Value Pairs """ return [(k, v) for k, v in dictionary.items()]
5,338,418
def convert_and_remove_punctuation(text): """ remove punctuation that are not allowed, e.g. / \ convert Chinese punctuation into English punctuation, e.g. from「 to " """ # removal text = text.replace("\\", "") text = text.replace("\\", "") text = text.replace("[", "") text = text.re...
5,338,419
def create_random_context(dialog,rng,minimum_context_length=2,max_context_length=20): """ Samples random context from a dialog. Contexts are uniformly sampled from the whole dialog. :param dialog: :param rng: :return: context, index of next utterance that follows the context """ # sample dia...
5,338,420
def get_video_collection_items(**kwargs): """ Get the contents of video collections """ get( url="/v2/videos/collections/" + kwargs["id"] + "/items", params=kwargs, json_data=None, )
5,338,421
def dev_test_new_schema_version(dbname, sqldb_dpath, sqldb_fname, version_current, version_next=None): """ hacky function to ensure that only developer sees the development schema and only on test databases """ TESTING_NEW_SQL_VERSION = version_current != version_next...
5,338,422
def _get_distance_euclidian(row1: np.array, row2: np.array): """ _get_distance returns the distance between 2 rows (euclidian distance between vectors) takes into account all columns of data given """ distance = 0. for i, _ in enumerate(row1): distance += (row1[i] - row2[i]) ** 2...
5,338,423
def _get_ip_from_response(response): """ Filter ipv4 addresses from string. Parameters ---------- response: str String with ipv4 addresses. Returns ------- list: list with ip4 addresses. """ ip = re.findall(r'\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[...
5,338,424
def create_processor( options: options_pb2.ConvertorOptions, theorem_database: Optional[proof_assistant_pb2.TheoremDatabase] = None, tactics: Optional[List[deephol_pb2.Tactic]] = None) -> ProofLogToTFExample: """Factory function for ProofLogToTFExample.""" if theorem_database and options.theorem_databa...
5,338,425
def adsAddRoute(net_id, ip_address): """ :summary: Establish a new route in the AMS Router. :param pyads.structs.SAmsNetId net_id: net id of routing endpoint :param str ip_address: ip address of the routing endpoint """ add_route = _adsDLL.AdsAddRoute add_route.restype = ctypes.c_long ...
5,338,426
def EscapeShellArgument(s): """Quotes an argument so that it will be interpreted literally by a POSIX shell. Taken from http://stackoverflow.com/questions/35817/whats-the-best-way-to-escape-ossystem-calls-in-python """ return "'" + s.replace("'", "'\\''") + "'"
5,338,427
def secrets(): """interact with secret packages and scripts only""" if not os.path.exists(DOTSECRETS_PATH): print(f"{DOTSECRETS_PATH} does not exist", file=sys.stderr) sys.exit(1)
5,338,428
def login_invalid(request, error_type): """ Displays the index with an error message. """ # TODO - encode authentification error message in URI try: message = INVALID_LOGIN_MESSAGE[error_type] except KeyError: message = "Erreur inconnue" context = {'form': LoginForm(), 'message': m...
5,338,429
def lsh(B_BANDS, docIdList, sig): """ Applies the LSH algorithm. This function first divides the signature matrix into bands and hashes each column onto buckets. :param B_BANDS: Number of bands in signature matrix :param docIdList: List of document ids :param sig: signature matrix :return: List of ...
5,338,430
def langevin_coefficients( temperature, dt, friction, masses): """ Compute coefficients for langevin dynamics Parameters ---------- temperature: float units of Kelvin dt: float units of picoseconds friction: float frequency in picoseconds masse...
5,338,431
def waitpid_handle_exceptions(pid, deadline): """Wrapper around os.waitpid()/waitpid_with_timeout(), which waits until either a child process exits or the deadline elapses, and retries if certain exceptions occur. Args: pid: Process ID to wait for, or -1 to wait for any child process. deadline: If non-...
5,338,432
def tedor_ideal(t_mix, a, dist, t2, j_cc, obs='C13', pulsed='N15', vr=14000, return_t=False): """ Makes a SpinEvolution input file from template file "tedor_ideal_template", calls SpinEvolution, parses the output, and applies phenomenological scaling and exponential relaxation. The tedor_ideal is a cal...
5,338,433
def preprocess(image, image_size): """ Preprocess pre-process the image by to adaptive_treshold, perspectiv_transform, erode, diletate, resize :param image: image of display from cv2.read :return out_image: output image after preprocessing """ # blurr blurred = cv2.GaussianBlur(im...
5,338,434
def download(distributor: Distributor, max_try:int = 4) -> list[TrainInformation]|None: """Download train information from distributor. If response status code was 500-599, this function retries up to max_try times. Parameters ---------- distributor : Distributor Distributor of infomation ...
5,338,435
def add_payloads(prev_layer, input_spikes): """Get payloads from previous layer.""" # Get only payloads of those pre-synaptic neurons that spiked payloads = tf.where(tf.equal(input_spikes, 0.), tf.zeros_like(input_spikes), prev_layer.payloads) print("Using spikes with payloads f...
5,338,436
def read_csv_to_data(path: str, delimiter: str = ",", headers: list = []): """A zero-dependancy helper method to read a csv file Given the path to a csv file, read data row-wise. This data may be later converted to a dict of lists if needed (column-wise). Args: path (str): Path to csv file ...
5,338,437
def main_menu(update, context): """Handling the main menu :param update: Update of the sent message :param context: Context of the sent message :return: Status for main menu """ keyboard = [['Eintragen'], ['Analyse']] update.message.reply_text( 'Was möchtest du mach...
5,338,438
def build_model(inputs, num_classes, is_training, hparams): """Constructs the vision model being trained/evaled. Args: inputs: input features/images being fed to the image model build built. num_classes: number of output classes being predicted. is_training: is the model training or not. ...
5,338,439
def get_test_app_for_status_code_testing(schedule=False): """ :return: Flask Test Application with the right settings """ import flask_monitoringdashboard app = Flask(__name__) @app.route('/return-a-simple-string') def return_a_simple_string(): return 'Hello, world' @app.route...
5,338,440
def current_user(): """Returns the value of the USER environment variable""" return os.environ['USER']
5,338,441
def run_multiple_cases(x, y, z, door_height, door_width, t_amb, HoC, time_ramp, hrr_ramp, num, door, wall, simulation_time, dt_data): """ Generate multiple CFAST input files and calls other functions """ resulting_temps = np.array([]) for i in range(le...
5,338,442
def get_all(): """ Obtiene todas las tuplas de la relación Estudiantes :returns: Todas las tuplas de la relación. :rtype: list """ try: conn = helpers.get_connection() cur = conn.cursor() cur.execute(ESTUDIANTE_QUERY_ALL) result = cur.fetchall() ...
5,338,443
def _create_seqs_name_dict(in_file): """read fasta file and populate dict""" global name_data name = "" with open(in_file) as in_handle: for line in in_handle: if not line.startswith(">"): name_data.update({line.strip(): name}) else: name =...
5,338,444
def load_fgong(filename, fmt='ivers', return_comment=False, return_object=True, G=None): """Given an FGONG file, returns NumPy arrays ``glob`` and ``var`` that correspond to the scalar and point-wise variables, as specified in the `FGONG format`_. .. _FGONG format: https://www.astro.up.p...
5,338,445
def hla_saturation_flags(drizzled_image, flt_list, catalog_name, catalog_data, proc_type, param_dict, plate_scale, column_titles, diagnostic_mode): """Identifies and flags saturated sources. Parameters ---------- drizzled_image : string drizzled filter product image fil...
5,338,446
def dskb02(handle, dladsc): """ Return bookkeeping data from a DSK type 2 segment. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dskb02_c.html :param handle: DSK file handle :type handle: int :param dladsc: DLA descriptor :type dladsc: spiceypy.utils.support_types.SpiceDLADescr ...
5,338,447
def mt_sec(package, db): """ Multithreaded function for security check of packages :param package: package name :param db: vuln db :return: """ all_rep = {} all_rep[package] = {} error_message = None try: _, status, rep = control_vulnerability(package, db) if stat...
5,338,448
def train_node2vec(graph, dim, p, q): """Obtains node embeddings using Node2vec.""" emb = n2v.Node2Vec( graph=graph, dimensions=dim, workers=mp.cpu_count(), p=p, q=q, quiet=True, ).fit() emb = { node_id: emb.wv[str(node_id)] for node_id in...
5,338,449
def approx_match_dictionary(): """Maps abbreviations to the part of the expanded form that is common beween all forms of the word""" k=["%","bls","gr","hv","hæstv","kl","klst","km","kr","málsl",\ "málsgr","mgr","millj","nr","tölul","umr","þm","þskj","þús"] v=['prósent','blaðsíð',\ 'grein','hát...
5,338,450
def matrix2array(M): """ 1xN matrix to array. In other words: [[1,2,3]] => [1,2,3] """ if isspmatrix(M): M = M.todense() return np.squeeze(np.asarray(M))
5,338,451
def test_ap_wps_ie_fragmentation(dev, apdev): """WPS AP using fragmented WPS IE""" ssid = "test-wps-ie-fragmentation" params = { "ssid": ssid, "eap_server": "1", "wps_state": "2", "wpa_passphrase": "12345678", "wpa": "2", "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP", ...
5,338,452
def main(unused_argv): """Convert to Examples and write the result to TFRecords.""" convert_to(FLAGS.name, FLAGS.rt60, FLAGS.inputs, FLAGS.labels, FLAGS.output_dir, FLAGS.apply_cmvn, FLAGS.test)
5,338,453
async def emote(ctx: slash.Context, choice: emote_opt): """Send a premade message.""" # By default, this sends a message and shows # the command invocation in a reply-like UI await ctx.respond(choice, allowed_mentions=discord.AllowedMentions.none())
5,338,454
def expected(data): """Computes the expected agreement, Pr(e), between annotators.""" total = float(np.sum(data)) annotators = range(len(data.shape)) percentages = ((data.sum(axis=i) / total) for i in annotators) percent_expected = np.dot(*percentages) return percent_expected
5,338,455
def maximization_step(num_words, stanzas, schemes, probs): """ Update latent variables t_table, rprobs """ t_table = numpy.zeros((num_words, num_words + 1)) rprobs = numpy.ones(schemes.num_schemes) for i, stanza in enumerate(stanzas): scheme_indices = schemes.get_schemes_for_len(len(stan...
5,338,456
def account_export_mydata_content(account_id=None): """ Export ServiceLinks :param account_id: :return: List of dicts """ if account_id is None: raise AttributeError("Provide account_id as parameter") # Get table names logger.info("ServiceLinkRecord") db_entry_object = Servi...
5,338,457
def indicator_entity(indicator_types: List[str] = None) -> type: """Return custom model for Indicator Entity.""" class CustomIndicatorEntity(IndicatorEntity): """Indicator Entity Field (Model) Type""" @validator('type', allow_reuse=True) def is_empty(cls, value: str, field: 'ModelField...
5,338,458
def z_to_t(z_values, dof): """ Convert z-statistics to t-statistics. An inversion of the t_to_z implementation of [1]_ from Vanessa Sochat's TtoZ package [2]_. Parameters ---------- z_values : array_like Z-statistics dof : int Degrees of freedom Returns -------...
5,338,459
def getInputShape(model): """ Gets the shape when there is a single input. Return: Numeric dimensions, omits dimensions that have no value. eg batch size. """ s = [] for dim in model.input.shape: if dim.value: s.append(dim.value) ...
5,338,460
def get_latest_file(file_paths, only_return_one_match=True): """ Returns the latest created file from a list of file paths :param file_paths: list(str) :param only_return_one_match: bool :return: list(str) or str """ last_time = 0 times = dict() for file_path in file_paths: ...
5,338,461
def get_node_depths(tree): """ Get the node depths of the decision tree >>> d = DecisionTreeClassifier() >>> d.fit([[1,2,3],[4,5,6],[7,8,9]], [1,2,3]) >>> get_node_depths(d.tree_) array([0, 1, 1, 2, 2]) """ def get_node_depths_(current_node, current_depth, l, r, depths): ...
5,338,462
def ihfft(a: numpy.ndarray, n: None, axis: int): """ usage.dask: 3 """ ...
5,338,463
def add_metrics(engine, met): """ add provided metrics to database """ Session = sessionmaker() Session.configure(bind=engine) session = Session() session.add(met) session.commit() session.expunge_all() session.close()
5,338,464
def homo_tuple_typed_attrs(draw, defaults=None, legacy_types_only=False, kw_only=None): """ Generate a tuple of an attribute and a strategy that yields homogenous tuples for that attribute. The tuples contain strings. """ default = attr.NOTHING val_strat = tuples(text(), text(), text()) if d...
5,338,465
def RunSuite(config, files, extra_flags, errors): """Run a collection of benchmarks.""" global ERRORS, CONCURRENCY Banner('running %d tests' % (len(files))) pool = multiprocessing.Pool(processes=CONCURRENCY) # create a list of run arguments to map over argslist = [(num, len(files), config, test, extra_flags...
5,338,466
def test_get_project_info(client): """Test get info on the project""" response = client.get("/api/projects/project-id/info") json_data = response.get_json() assert json_data["authors"] == "asreview team" assert json_data["dataset_path"] == "Hall_2012.csv"
5,338,467
def flatland_env_factory( evaluation: bool = False, env_config: Dict[str, Any] = {}, preprocessor: Callable[ [Any], Union[np.ndarray, Tuple[np.ndarray], Dict[str, np.ndarray]] ] = None, include_agent_info: bool = False, random_seed: Optional[int] = None, ) -> FlatlandEnvWrapper: """L...
5,338,468
def notify_about_update(user, event_type="UPDATED"): """Notify all organisation about changes of the user.""" for org in user.organisations.where( Organisation.webhook_enabled | Organisation.email_notifications_enabled ): if org.webhook_enabled and org.webhook_url: invoke_webhook...
5,338,469
def industry(code, market="cn"): """获取某个行业的股票列表。目前支持的行业列表具体可以查询以下网址: https://www.ricequant.com/api/research/chn#research-API-industry :param code: 行业代码,如 A01, 或者 industry_code.A01 :param market: 地区代码, 如'cn' (Default value = "cn") :returns: 行业全部股票列表 """ if not isinstance(code, six.string_ty...
5,338,470
def kewley_agn_oi(log_oi_ha): """Seyfert/LINER classification line for log([OI]/Ha).""" return 1.18 * log_oi_ha + 1.30
5,338,471
def XGMMLReader(graph_file): """ Arguments: - `file`: """ parser = XGMMLParserHelper() parser.parseFile(graph_file) return parser.graph()
5,338,472
def test_dispatch_request(client, method): """Dispatch request to the `Injector` subclass attributes.""" response = getattr(client, method)("/test_dispatch_request/1/test/") assert response.status_code == 200 assert response.content == b"<h1>OK</h1>"
5,338,473
def pt_encode(index): """pt: Toggle light.""" return MessageEncode(f"09pt{index_to_housecode(index)}00", None)
5,338,474
def normalize_inputspace( x, vmax=1, vmin=0, mean=PYTORCH_IMAGENET_MEAN, std=PYTORCH_IMAGENET_STD, each=True, img_format="CHW", ): """ Args: x: numpy.ndarray format is CHW or BCHW each: bool if x has dimension B then apply each inpu...
5,338,475
def test_authentiaction_the_token_in_the_header_contains_spaces(jwt_token): """ ... """ client = APIClient() client.credentials(HTTP_AUTHORIZATION="Bearer " + jwt_token["VALID"] + " 12") response = client.post("/api/current_user_jwt/") assert ( response.data["detail"] == "I...
5,338,476
def get_load_average() -> Tuple[float, float, float]: """Get load average""" return os.getloadavg()
5,338,477
def test_local_orchestrator(fileutils): """Test launching orchestrator locally""" global first_dir exp_name = "test-orc-launch-local" exp = Experiment(exp_name, launcher="local") test_dir = fileutils.make_test_dir(exp_name) first_dir = test_dir orc = Orchestrator(port=6780) orc.set_path...
5,338,478
def test_insert_table(graph_cases): """ :type graph_cases: qmxgraph.tests.conftest.GraphCaseFactory """ graph = graph_cases('1t') assert len(graph.get_tables()) == 1
5,338,479
def start_file(filename): """ Generalized os.startfile for all platforms supported by Qt This function is simply wrapping QDesktopServices.openUrl Returns True if successfull, otherwise returns False. """ from qtpy.QtCore import QUrl from qtpy.QtGui import QDesktopServices ...
5,338,480
def require_context(f): """Decorator to require *any* user or admin context. This does no authorization for user or project access matching, see :py:func:`authorize_project_context` and :py:func:`authorize_user_context`. The first argument to the wrapped function must be the context. """ d...
5,338,481
def local_launcher(commands): """Launch all of the scripts in commands on the local machine serially. If GPU is available it is gonna use it. Taken from : https://github.com/facebookresearch/DomainBed/ Args: commands (List): List of list of string that consists of a python script call """ ...
5,338,482
def failsafe_hull(coords): """ Wrapper of ConvexHull which returns None if hull cannot be computed for given points (e.g. all colinear or too few) """ coords = np.array(coords) if coords.shape[0] > 3: try: return ConvexHull(coords) except QhullError as e: if '...
5,338,483
def CheckAttribs(a, b, attrs, assertEquals): """Checks that the objects a and b have the same values for the attributes given in attrs. These checks are done using the given assert function. Args: a: The first object. b: The second object. attrs: The list of attribute names (strings). assertEqual...
5,338,484
def list_closed_poll_sessions(request_ctx, **request_kwargs): """ Lists all closed poll sessions available to the current user. :param request_ctx: The request context :type request_ctx: :class:RequestContext :return: List closed poll sessions :rtype: requests.Response (with voi...
5,338,485
def _wrap_apdu(command: bytes) -> List[bytes]: """Return a list of packet to be sent to the device""" packets = [] header = struct.pack(">H", len(command)) command = header + command chunks = [command[i : i + _PacketData.FREE] for i in range(0, len(command), _PacketData.FREE)] # Create a packe...
5,338,486
def build_dtree(bins): """ Build the directory tree out of what's under `user/`. The `dtree` is a dict of: string name -> 2-list [inumber, element] , where element could be: - Raw bytes for regular file - A `dict` for directory, which recurses on """ def next_inumber(): ...
5,338,487
def noisify_image(image_to_noisify, secret, indices_used, original_distribution, printf=None, process_count=None): """Encode all pixels not containing secret with noise with its distribution matching source image. Notes: This method modifies passed image object - encoding is done in-place. Args: ...
5,338,488
def dataframe_to_rows(df, index=True, header=True): """ Convert a Pandas dataframe into something suitable for passing into a worksheet. If index is True then the index will be included, starting one row below the header. If header is True then column headers will be included starting one column to the ...
5,338,489
def _compose_image(digit, background): """Difference-blend a digit and a random patch from a background image.""" w, h, _ = background.shape dw, dh, _ = digit.shape x = np.random.randint(0, w - dw) y = np.random.randint(0, h - dh) bg = background[x:x+dw, y:y+dh] return np.abs(bg - digit).as...
5,338,490
def permissions_vsr(func): """ :param func: :return: """ def func_wrapper(name): return "<p>{0}</p>".format(func(name)) return func_wrapper
5,338,491
def upgrade(profile, validator, writeProfileToFileFunc): """ Upgrade a profile in memory and validate it If it is safe to do so, as defined by shouldWriteProfileToFile, the profile is written out. """ # when profile is none or empty we can still validate. It should at least have a version set. _ensureVersionP...
5,338,492
def tri_interpolate_zcoords(points: np.ndarray, triangles: np.ndarray, mesh_points: np.ndarray, is_mesh_edge: np.ndarray, num_search_tris: int=10): """ Interpolate z-coordinates to a set of 2D points using 3D point coordinates and a triangular mesh. If point is along a mesh bound...
5,338,493
def getServiceTypes(**kwargs) -> List: """List types of services. Returns: List of distinct service types. """ services = getServices.__wrapped__() types = [s['type'] for s in services] uniq_types = [dict(t) for t in {tuple(sorted(d.items())) for d in types}] return uniq_types
5,338,494
def train_model(train_data, test_data, model, model_name, optimizer, loss='mse', scale_factor=1000., batch_size=128, max_epochs=200, early_stop=True, plot_history=True): """ Code to train a given model and save out to the designated path as given by 'model_name' Parameters ---------- train_data : 2-tup...
5,338,495
def get_pipeline_storage_es_client(session, *, index_date): """ Returns an Elasticsearch client for the pipeline-storage cluster. """ secret_prefix = f"elasticsearch/pipeline_storage_{index_date}" host = get_secret_string(session, secret_id=f"{secret_prefix}/public_host") port = get_secret_stri...
5,338,496
def cqcc_resample(s, fs_orig, fs_new, axis=0): """implement the resample operation of CQCC Parameters ---------- s : ``np.ndarray`` the input spectrogram. fs_orig : ``int`` origin sample rate fs_new : ``int`` new sample rate axis : ``int`` the resample axis ...
5,338,497
def weights_init(): """ Gaussian init. """ def init_fun(m): classname = m.__class__.__name__ if (classname.find("Conv") == 0 or classname.find("Linear") == 0) and hasattr(m, "weight"): nn.init.normal_(m.weight, 0.0, 0.02) if hasattr(m, "bias") and m.bias is not...
5,338,498
def dozier_2d(dem, number_of_sectors, distance): """ :param dem: :param number_of_sectors: :param distance: :return: """ pass
5,338,499