content
stringlengths
22
815k
id
int64
0
4.91M
def adfuller_test(series, signif=0.05, name='', verbose=False): """Perform ADFuller to test for Stationarity of given series, print report and return if series is stationary""" r = adfuller(series, autolag='AIC') output = {'test_statistic': round(r[0], 4), 'pvalue': round(r[1], 4), 'n_lags': round(r[2], 4),...
5,341,400
def AddRemoveEndpoint(endpoint_group, endpoint_spec, support_global_scope, support_hybrid_neg, support_l4ilb_neg): """Adds remove endpoint argument for updating network endpoint groups.""" help_text = """\ The network endpoint to detach from the network endpoint group. Allo...
5,341,401
def wrhdf(hdf_filename, x, y, z, f): """ Write an HDF4 file. x, y, and z are the scales. f is the data. str: hdf_filename HDF4 filename. """ # Create an HDF file sd_id = SD(hdf_filename, SDC.WRITE | SDC.CREATE | SDC.TRUNC) if f.dtype == np.float32: ftype = SDC.FLOAT32 ...
5,341,402
def datetime_to_timestring(dt_): """ Returns a pretty formatting string from a datetime object. For example, >>>datetime.time(hour=9, minute=10, second=30) ..."09:10:30" :param dt_: :class:`datetime.datetime` or :class:`datetime.time` :returns: :class:`str` """ return pad(dt_.hour)...
5,341,403
def test_invalid_backtest_metrics(catboost_pipeline: Pipeline, metrics: List[Metric], example_tsdf: TSDataset): """Test Pipeline.backtest behavior in case of invalid metrics.""" with pytest.raises(ValueError): _ = catboost_pipeline.backtest(ts=example_tsdf, metrics=metrics, n_folds=2)
5,341,404
def save_eog_model(model): """ Save EOG model to disk using pickle. :param model: EOG model to save to disk """ _save_model(model, EOG_MODEL_DIR)
5,341,405
def get_class_for_name(name: str, module_name: str = __name__) -> Type: """Gets a class from a module based on its name. Tread carefully with this. Personally I feel like it's only safe to use with dataclasses with known interfaces. Parameters ---------- name : str Name of the class we'...
5,341,406
def get_cache_file_static(): """ Helper function to get the path to the VCR cache file for requests that must be updated by hand in cases where regular refreshing is infeasible, i.e. limited access to the real server. To update this server recording: 1) delete the existing recording 2) re-r...
5,341,407
def intervals_where_mask_is_true(mask): """Determine intervals where a 1D boolean mask is True. Parameters ---------- mask : numpy.ndarray Boolean mask. Returns ------- ranges : list List of slice intervals [(low, upp), ...] indicating where the mask has `True` valu...
5,341,408
def get_FAAM_mineral_dust_calibration(instrument='PCASP', rtn_values=True): """ Retrieve FAAM mineral dust calibration """ # Location and name of calibration files? folder = '{}/FAAM/'.format(get_local_folder('ARNA_data')) if instrument == 'PCASP': # NOTE: range ~0.1-4 microns f...
5,341,409
async def cancel_handler(message: types.Message, state: FSMContext): """ @dp.message_handler(state='*', commands='cancel') """ current_state = await state.get_state() if current_state is None: return await state.finish() await message.reply( md.text( md.hbold('Ав...
5,341,410
def load_classifier(path=False): """ Load the ALLSorts classifier from a pickled file. ... Parameters __________ path : str Path to a pickle object that holds the ALLSorts model. Default: "/models/allsorts/allsorts.pkl.gz" Returns __________ allsorts_clf : ALLSort...
5,341,411
def setup_auth_turing(cluster): """ Set up athentication with Turing k8s cluster on Azure. """ # Read in auth info azure_file = os.path.join(ABSOLUTE_HERE, "secrets", "turing-auth-key-prod.json") with open(azure_file, "r") as stream: azure = json.load(stream) # Login in to Azure ...
5,341,412
def get_response(url: str, *, max_attempts=5) -> requests.Response: """Return the response. Tries to get response max_attempts number of times, otherwise return None Args: url (str): url string to be retrieved max_attemps (int): number of request attempts for same url E.g., r = ...
5,341,413
def hamming_distance(lhs, rhs): """Returns the Hamming Distance of Two Equal Strings Usage >>> nt.hamming_distance('Pear','Pearls') """ return len([(x, y) for x, y in zip(lhs, rhs) if x != y])
5,341,414
def get_uleb128(byte_str): """ Gets a unsigned leb128 number from byte sting :param byte_str: byte string :return: byte string, integer """ uleb_parts = [] while byte_str[0] >= 0x80: uleb_parts.append(byte_str[0] - 0x80) byte_str = byte_str[1:] uleb_parts.append(byte_str[...
5,341,415
def expired_response(): """ Expired token callback. Author: Lucas Antognoni Arguments: Response: json { 'error': (boolean), 'message': (str) } Response keys: - 'er...
5,341,416
def test_correct_technologiesPage(client): """Grab the technologies page, check for 200 code(all ok), then check to see if the response is a HTML page. """ response = client.get("/technologies") assert response.status_code == 200 assert "<!DOCTYPE html>" in response.get_data(True)
5,341,417
def check_shots_vs_bounds(shot_dict, mosaic_bounds, max_out_of_bounds = 3): """Checks whether all but *max_out_of_bounds* shots are within mosaic bounds Parameters ---------- shot_dict : dict A dictionary (see czd_utils.scancsv_to_dict()) with coordinates of all shots in a .scancsv file...
5,341,418
def wrap(func, *args, unsqueeze=False): """ Wrap a torch function so it can be called with NumPy arrays. Input and return types are seamlessly converted. :param func: :param args: :param unsqueeze: :return: """ # Convert input types where applicable args = list(args) for i, ...
5,341,419
def iter_schemas(schema: Schema, strict_enums: bool = True) -> Iterable[Tuple[str, Any]]: """ Build zero or more JSON schemas for a marshmallow schema. Generates: name, schema pairs. """ builder = Schemas(build_parameter=build_parameter, strict_enums=strict_enums) return builder.iter_schemas(s...
5,341,420
async def publish_email_message(qsm: QueueServiceManager, # pylint: disable=redefined-outer-name cloud_event_msg: dict): """Publish the email message onto the NATS emailer subject.""" logger.debug('publish to queue, subject:%s, event:%s', APP_CONFIG.EMAIL_PUBLISH_OPTIONS['subjec...
5,341,421
def test_find_datasets_save(df_datasets_ensembl): """Test the available datasets returned by find_datasets(save=True) for the default mart (ENSEMBL_MART_ENSEMBL).""" expect = (df_datasets_ensembl .sort_values(by="Dataset_ID", axis=0) .reset_index(drop=True)) _ = find_datasets...
5,341,422
def deserializer(serialized): """Example deserializer function with extra sanity checking. :param serialized: Serialized byte string. :type serialized: bytes :return: Deserialized job object. :rtype: kq.Job """ assert isinstance(serialized, bytes), "Expecting a bytes" return dill.loads(...
5,341,423
def test_max_none(capsys): """No output.""" a = BST() assert find_maximum_value(a) is None
5,341,424
def sym_auc_score(X, y): """Compute the symmetric auroc score for the provided sample. symmetric auroc score is defined as 2*abs(auroc-0.5) Parameters ---------- X : {array-like, sparse matrix} shape = [n_samples, n_features] The set of regressors that will be tested sequentially. y : ...
5,341,425
def visibility_of_element_wait(driver, xpath, timeout=10): """Checking if element specified by xpath is visible on page :param driver: webdriver instance :param xpath: xpath of web element :param timeout: time after looking for element will be stopped (default: 10) ...
5,341,426
def _read_byte(stream): """Read byte from stream""" read_byte = stream.read(1) if not read_byte: raise Exception('No more bytes!') return ord(read_byte)
5,341,427
def statistic_xls(request): """Генерация XLS""" from directions.models import Issledovaniya import xlwt from collections import OrderedDict wb = xlwt.Workbook(encoding='utf-8') response = HttpResponse(content_type='application/ms-excel') request_data = request.POST if request.method == "PO...
5,341,428
def populate_labels(model_name: str, paths: dict) -> list: """Report full list of object labels corresponding to detection model of choice Args: model_name: name of the model to use paths: dictionary of paths from yml file Returns: labels (list(str)): list of obj...
5,341,429
def get_checkers(): """Get default checkers to run on code. :returns: List of default checkers to run. """ return [function, readability]
5,341,430
def get_token(): """ Get or create token. """ try: token = Token.objects.get(name=settings.TOKEN_NAME) except Token.DoesNotExist: client_id = raw_input("Client id:") client_secret = raw_input("Client secret:") token = Token.objects.create( name=settings.TO...
5,341,431
def test_rmr_set_get(): """ test set functions """ sbuf = rmr.rmr_alloc_msg(MRC_SEND, SIZE) _assert_new_sbuf(sbuf) # test payload pay = b"\x01\x00\x80" rmr.set_payload_and_length(pay, sbuf) summary = rmr.message_summary(sbuf) assert summary["payload"] == pay assert summary["...
5,341,432
def get_labels_from_sample(sample): """ Each label of Chinese words having at most N-1 elements, assuming that it contains N characters that may be grouped. Parameters ---------- sample : list of N characters Returns ------- list of N-1 float on [0,1] (0 represents no split) """ ...
5,341,433
async def test_turn_off(opp): """Test turn on device.""" await common.async_set_hvac_mode(opp, HVAC_MODE_HEAT, ENTITY_CLIMATE) state = opp.states.get(ENTITY_CLIMATE) assert state.state == HVAC_MODE_HEAT await common.async_turn_off(opp, ENTITY_CLIMATE) state = opp.states.get(ENTITY_CLIMATE) ...
5,341,434
def _recarray_from_array(arr, names, drop_name_dim=_NoValue): """ Create recarray from input array `arr`, field names `names` """ if not arr.dtype.isbuiltin: # Structured array as input # Rename fields dtype = np.dtype([(n, d[1]) for n, d in zip(names, arr.dtype.descr)]) return arr....
5,341,435
def pad(mesh: TriangleMesh, *, side: str, width: int, opts: str = '', label: int = None) -> TriangleMesh: """Pad a triangle mesh. Parameters ---------- mesh : TriangleMesh The mesh to pad. side : str Side to pad, must be one of `left`, `right`...
5,341,436
def make_qa_plots(targs, qadir='.', targdens=None, max_bin_area=1.0, weight=True, imaging_map_file=None, truths=None, objtruths=None, tcnames=None, cmx=False, bit_mask=None, mocks=False): """Make DESI targeting QA plots given a passed set of targets. Parameters ---------...
5,341,437
def do_validate(): """ Validate function. print out the config, count the users and print the actions. """ try: # Print config logging.info( "\n====== [RTA] Rest Tenant Automation Configuration ======") for k, v in config.items(): if isinstance(v, dict): ...
5,341,438
def krauss_basis(qubits): """ Helper function to return the Krauss operator basis formed by the Cartesian product of [I, X, Y, Z] for the n-qubit. :param qubits: number of qubits :type qubits: int :return: Krauss operator :rtype: np.ndarray, float """ return [i for i in iterto...
5,341,439
def choose_fun_cov(str_cov: str) -> constants.TYPING_CALLABLE: """ It chooses a covariance function. :param str_cov: the name of covariance function. :type str_cov: str. :returns: covariance function. :rtype: callable :raises: AssertionError """ assert isinstance(str_cov, str) ...
5,341,440
async def error_500(request, error: HTTPException): """ TODO: Handle the error with our own error handling system. """ log.error( "500 - Internal Server Error", exc_info=(type(error), error, error.__traceback__), ) return JSONResponse( status_code=500, content={ ...
5,341,441
def stream_comments(sync_q): """Main task: Starts comment stream from the blockchain""" processed_posts = [] try: blockfile = open(startblock, 'r') starting_point = int(blockfile.read()) blockfile.close() except: try: props = steem.get_dynamic_global_propertie...
5,341,442
def log_sum_exp(x): """Utility function for computing log_sum_exp while determining This will be used to determine unaveraged confidence loss across all examples in a batch. Args: x (Variable(tensor)): conf_preds from conf layers 确定时用于计算的实用函数(log_sum_exp) 这将用于确定批处理中所有示例的不可用信心损失。 参数: x(变量(...
5,341,443
def session_hook(func): """ hook opens a database session do a session_hook(read or write) and closes the connection after the run() func: function that communicates with the database (e.g fun(*args, db: Session)) returns; data: The return from func error: in case of an error...
5,341,444
def float_index_to_time_index(df): """Convert a dataframe float indices to `datetime64['us']` indices.""" df.index = df.index.map(datetime.utcfromtimestamp) df.index = pd.to_datetime(df.index, unit="us", utc=True) return df
5,341,445
def correlated_hybrid_matrix(data_covmat,theory_covmat=None,theory_corr=None,cap=True,cap_off=0.99): """ Given a diagonal matrix data_covmat, and a theory matrix theory_covmat or its correlation matrix theory_corr, produce a hybrid non-diagonal matrix that has the same diagonals as the data matrix b...
5,341,446
def prepare_config(self, config=None): """Set defaults and check fields. Config is a dictionary of values. Method creates new config using default class config. Result config keys are the same as default config keys. Args: self: object with get_default_config method. config: User-provi...
5,341,447
def number_to_block(number, block_number=0): """ Given an address number, normalizes it to the block number. >>> number_to_block(1) '0' >>> number_to_block(10) '0' >>> number_to_block(100) '100' >>> number_to_block(5) '0' >>> number_to_block(53) '0' >>> number_to_bloc...
5,341,448
def pf_active_overlay(ods, ax=None, **kw): """ Plots overlays of active PF coils. INCOMPLETE: only the oblique geometry definition is treated so far. More should be added later. :param ods: OMAS ODS instance :param ax: axes instance into which to plot (default: gca()) :param \**kw: Additional...
5,341,449
def distance_between_vehicles(self_vhc_pos, self_vhc_orientation, self_vhc_front_length, self_vhc_rear_length, self_vhc_width, ext_vhc_pos, ext_vhc_orientation, ext_vhc_width, ext_vhc_rear_length, ext_vhc_front_length): """Only in 2-D space (no z-axis in p...
5,341,450
def _complexity_lyapunov_checklength( n, delay=1, dimension=2, tolerance="default", len_trajectory=20, method="rosenstein1993", matrix_dim=4, min_neighbors="default", ): """Helper function that calculates the minimum number of data points required. """ if method in ["rosenste...
5,341,451
def compute_hits_importance_scores( hits_bed_path, shap_scores_hdf5_path, peak_bed_path, out_path ): """ For each MOODS hit, computes the hit's importance score as the ratio of the hit's average importance score to the total importance of the sequence. Arguments: `hits_bed_path`: path to BED...
5,341,452
def searchlight_dictdata(faces, nrings, vertex_list): """ Function to generate neighbor vertex relationship for searchlight analysis The format of dictdata is [label]:[vertices] Parameters: ----------- faces: nrings: vertex_list: vertex-index relationship, e.g. vertex_list[29696] = 3249...
5,341,453
def parse_resource_uri(resource_uri): """ Parse a resource uri (like /api/v1/prestataires/1/) and return the resource type and the object id. """ match = resource_pattern.search(resource_uri) if not match: raise ValueError("Value %s is not a resource uri." % resource_uri) return mat...
5,341,454
def foldl(func: tp.Callable, acc, lst: List): """ >>> foldl(lambda x, y: x + y, 0, Nil()) 0 >>> foldl(lambda x, y: x + y, 2, from_seq([1, 2, 3])) 8 >>> foldl(lambda x, y: x - y, 1, from_seq([3, 2, 1])) -5 """ return acc if null(lst) else foldl(func, func(acc, head(lst)), tail(lst))
5,341,455
def _print_info_dict(info_dict: Dict[str, str]): """Print the information dictionary""" for key, stat in info_dict.items(): print(f"{key:>10}: {stat}")
5,341,456
def test_expand_substory_protocol_list_with_null(f): """ We expand protocol of composed story, if substory define protocol with list of strings and parent story does not define protocol. """ class T(f.ChildWithList, f.NormalMethod): pass class Q(f.ParentWithNull, f.NormalParentMethod, ...
5,341,457
def generate_rules(F, support_data, min_confidence=0.5, verbose=True): """Generates a set of candidate rules from a list of frequent itemsets. For each frequent itemset, we calculate the confidence of using a particular item as the rule consequent (right-hand-side of the rule). By testing and merging ...
5,341,458
def cond_model(model1, model2): """Conditional. Arguments: model1 {MentalModel} -- antecedent model2 {MentalModel} -- consequent Returns: MentalModel -- the conditional model """ mental = and_model(model1, model2) mental.ell += 1 fully = merge_fullex( and_mo...
5,341,459
def get_pages(): """Select all pages and order them by page_order.""" pages = query_db("SELECT page_order, name, shortname, available FROM pages ORDER BY page_order") return pages
5,341,460
def set_default_interface(etree): """ Sets the default interface that PyAMF will use to deal with XML entities (both objects and blobs). """ global types, ET, modules t = _get_etree_type(etree) _types = set(types or []) _types.update([t]) types = tuple(_types) modules[t] = et...
5,341,461
def atom_site(block): """Handle ATOM_SITE block. Data items in the ATOM_SITE category record details about the atom sites in a macromolecular crystal structure, such as the positional coordinates, atomic displacement parameters, magnetic moments and directions. (source: http://mmcif.wwpdb.org/d...
5,341,462
def return_var_plot(result, attr_name, attr_type, option=0): """Method that generates the corresponding plot for each attribute, based on the type and the selection of the user.""" aval = f'{attr_name}_value' if attr_type == 'NUMBER' or attr_type == 'DATE_TIME': if aval not in result[0].keys():...
5,341,463
def get_inequivalent_sites(sub_lattice, lattice): """Given a sub lattice, returns symmetry unique sites for substitutions. Args: sub_lattice (list of lists): array containing Cartesian coordinates of the sub-lattice of interest lattice (ASE crystal): the total lattice ...
5,341,464
def test_re_mod_search(verbose = None): """ some tests borrowed from cpython testing re.search(), and matobj.group() """ regex_tests = testsuite.search_regex_tests for t in regex_tests: pattern=s=outcome=repl=expected=None if len(t)==5: pattern, s, outcome, repl, expe...
5,341,465
def cone_emline(ra, dec, radius=5, selectcol=['specObjID', 'ra', 'dec', 'z', 'zErr', 'bpt', 'Flux_Ha_6562', 'Flux_NII_6583', 'Flux_Hb_4861', 'Flux_OIII_5006']): """ box search in emissionLinesPort table ra, dec in degrees, size in arcsec. Columns described in http://skyserver.sdss.org/dr16/en/help/browser/b...
5,341,466
def kld(means, var): """KL divergence""" mean = torch.zeros_like(means) scale = torch.ones_like(var) return kl_divergence(Normal(means, torch.sqrt(var)), Normal(mean, scale)).sum(dim=1)
5,341,467
def add(vec_1, vec_2): """ This function performs vector addition. This is a good place to play around with different collection types (list, tuple, set...), :param vec_1: a subscriptable collection of length 3 :param vec_2: a subscriptable collection of length 3 :return vec_3: a subscriptable ...
5,341,468
def generateOrnament(fromMIDINote:int, key:Key, mode:ModeNames, bpm:float) -> Union[List[Any],None]: """ Generate OSC arguments describing ornaments, with the form: [ <ornamentName> <BPM> <beatSubdivision> [<listOfOrnamentNoteMIDIOffsets...>] ] ASSUME This function is called on every beat, or wi...
5,341,469
def ms_to_samples(ms, sampling_rate): """ Convert a duration in milliseconds into samples. Arguments: ms (float): Duration in ms. sampling_rate (int): Sampling rate of of the signal. Returns: int: Duration in samples. """ return int((ms / 1000) ...
5,341,470
def flatten(L): """Flatten a list recursively Inspired by this fun discussion: https://stackoverflow.com/questions/12472338/flattening-a-list-recursively np.array.flatten did not work for irregular arrays and itertools.chain.from_iterable cannot handle arbitrarily nested lists :param L: A list to...
5,341,471
def _has_access_to_course(user, access_level, course_key): """ Returns True if the given user has access_level (= staff or instructor) access to the course with the given course_key. This ensures the user is authenticated and checks if global staff or has staff / instructor access. access_level...
5,341,472
def occupy_region(image, center_x, center_y, buffer, color): """ 'Occupy' a region around (x,y) with the given color """ for x in range((center_x - buffer / 2), (center_x + buffer / 2)): for y in range((center_y - buffer / 2), (center_y + buffer / 2)): try: image.putpixel((...
5,341,473
def recreate_instance(source_instance_name, target_instance_name, instance_class): """ source_instance_nameの最新のスナップショットをもとにtarget_instance_nameで 指定されたインスタンスを再作成する :param str source_instance_name: 作成するインスタンスのものになるDB名 :param str target_instance_name: 再作成するDB名 :param str instance_class: RDSのインスタンスク...
5,341,474
def download_and_mosaic_through_ftps(file_list, tmp_path, cds_url, cds_path, cds_sso, cds_pw, bbox, crs, geoTransform): """ Download Copernicus DEM tiles and create mosaic according to satellite imagery tiling scheme file_list : list with strings list of DEM...
5,341,475
def chi2(observed, expected): """ Return the chi2 sum of the provided observed and expected values. :param observed: list of floats. :param expected: list of floats. :return: chi2 (float). """ if 0 in expected: return 0.0 return sum((_o - _e) ** 2 / _e ** 2 for _o, _e in zip(o...
5,341,476
def purgeThisMessageFromTheAttachments(aMessage): """ this function is recursive, if the message contains multipart message the function is recursively called to purge all the attachments""" partsToDelete = [] #empty list index = 0 list = aMessage.get_payload() #end of recursion, the payload is a string if t...
5,341,477
async def test_smartapp_sync_subscriptions_handles_exceptions( opp, smartthings_mock, device_factory, subscription_factory ): """Test synchronization does nothing when current.""" smartthings_mock.delete_subscription.side_effect = Exception smartthings_mock.create_subscription.side_effect = Exception ...
5,341,478
def range_bearing(p1: LatLon, p2: LatLon, R: float = NM) -> tuple[float, Angle]: """Rhumb-line course from :py:data:`p1` to :py:data:`p2`. See :ref:`calc.range_bearing`. This is the equirectangular approximation. Without even the minimal corrections for non-spherical Earth. :param p1: a :py:class:...
5,341,479
def cf_model_to_life(first_best, update_prod=False, pr_cache=False): """ We simulate the response of several variables to a shock to z and x. We fixed the cross-section distribution of (X,Z) and set rho to rho_start We apply a permanent shock to either X or Z, and fix the employment relationship, as wel...
5,341,480
def kde_interpolation(poi, bw='scott', grid=None, resolution=1, area=None, return_contour_geojson=False): """Applies kernel density estimation to a set points-of-interest measuring the density estimation on a grid of places (arbitrary points regularly spaced). Parameters ---------- poi : GeoDat...
5,341,481
def nums2tcrs(nums): """Converts a list containing lists of numbers to amino acid sequences. Each number is considered to be an index of the alphabet.""" tcrs_letter=[] n=len(nums) for i in range(n): num=nums[i] tcr='' for j in range(len(num)): tcr+=alphabet[num[j]] ...
5,341,482
def extract_columns(data): """ EXTRACTS COLUMNS TO USE IN `DictWriter()` """ columns = [] column_headers = data[0] for key in column_headers: columns.append(key) return columns
5,341,483
def cylindric_grid(dr, dz, origin_z=None, layer=False, material="dfalt"): """ Generate a cylindric mesh as a radial XZ structured grid. Parameters ---------- dr : array_like Grid spacing along X axis. dz : array_like Grid spacing along Z axis. origin_z : scalar, optional, de...
5,341,484
def get_clip_preview_feedback(program, event, classifier, start_time, audio_track, reviewer): """ Gets the feedback provided by a user for a Segment's clip Returns: Feedback if present. Empty Dictionary of no feedback exists. """ event = urllib.parse.unquote(event) program = urllib.par...
5,341,485
def interp(specStr, t): """Return the current value of t using linear interpolation. <specStr> is a string containing a list of pairs e.g. '[[0,20],[30,65],[60,50],[90,75]]' The first element of each pair is DAYS. The second is a NUMBER. <t> is time in seconds""" specList = ast.literal_eva...
5,341,486
def time_is(location): """ Retrieves the time in a location by parsing the time element in the html from Time.is . :param location: str location of the place you want to find time (works for small towns as well). :return: time str or None on failure. """ if BeautifulSoup: header =...
5,341,487
def _generate_template_context(arguments: PackagingResourceArguments, manifest: OdahuProjectManifest, output_folder: str) -> DockerTemplateContext: """ Generate Docker packager context for templates """ logging.info('Building context for temp...
5,341,488
def get_records(fname): """ Read the records of an IRAF database file into a python list Parameters ---------- fname : str name of an IRAF database file Returns ------- A list of records """ f = open(fname) dtb = f.read() f.close() recs = dtb.split('b...
5,341,489
def get_all_clips_matching_filter(fid: int) -> List[Clip]: """ gets all te clips that is part of the project and matches the filter :param fid: The filter the clips should match :return: A list of all clips that is part of the project and matches the filter """ filter = get_filter_by_id(fid) ...
5,341,490
def get_gushim(): """ get gush_id metadata """ detailed = request.args.get('detailed', '') == 'true' gushim = helpers._get_gushim(fields={'gush_id': True, 'last_checked_at': True, '_id': False}) if detailed: # Flatten list of gushim into a dict g_flat = dict((g['gush_id'], {"gush...
5,341,491
def dump_source(buf, id): """Dump BASIC source.""" if id == ID_SP5030: line_end_code = 0x0d src_end_code = 0x0000 kind = "SP-5030" elif id == ID_SBASIC: line_end_code = 0x00 src_end_code = 0x0000 kind = "S-BASIC" elif id == ID_HUBASIC: line_end_co...
5,341,492
def dense_layers(sequences, training, regularizer, initializer, num_layers=3, activation=tf.nn.relu): """ Create a chain of dense (fully-connected) neural network layers. Args: sequences (tf.Tensor): Input sequences. training (bool): Whether the mode is training or not. ...
5,341,493
def apply_cst(im, cst): """ Applies CST matrix to image. Args: im: input ndarray image ((height * width) x channel). cst: a 3x3 CST matrix. Returns: transformed image. """ result = im for c in range(3): result[:, :, c] = (cst[c, 0] * im[:, :, 0] + cst[c, 1] * im[:, :, 1] + ...
5,341,494
def show_binary_classification_accuracy(best_m: nn.Module, local_loader: data_utils.DataLoader, chatty = False) -> Tuple: """ Given the model and dataloader, calculate the classification accuracy. Returns true_positives, true_negatives, false_positives, false_negatives, roc_auc, pr for use elsewhere. :p...
5,341,495
async def test_full_config(opp, mock_client): """Test the full config of component.""" config = { prometheus.DOMAIN: { "namespace": "ns", "default_metric": "m", "override_metric": "m", "component_config": {"fake.test": {"override_metric": "km"}}, ...
5,341,496
def validate_accelerator_count(accel: Accelerator, count: int) -> int: """Raises an error if the count isn't valid for the supplied accelerator, else returns the count. """ is_gpu = accel in GPU ucase = accelerator_name(is_gpu) valid_counts = accelerator_counts(accel) if not _AccelCountMT[accel].get(coun...
5,341,497
def objective(trial: optuna.trial.Trial, log_dir: str, device, backbone) -> Tuple[float, int, float]: """Optuna objective. Args: trial Returns: float: score1(e.g. accuracy) int: score2(e.g. params) """ hyperparams = search_hyperparam(trial) if backbone: model = E...
5,341,498
def block_device_mapping_destroy(context, bdm_id): """Destroy the block device mapping.""" return IMPL.block_device_mapping_destroy(context, bdm_id)
5,341,499