content
stringlengths
22
815k
id
int64
0
4.91M
def extract_features(data: typing.Union[list, np.ndarray], attributes: list = None, nvd_attributes: list = None, nltk_feed_attributes: list = None, share_hooks=True, **kwargs): """Extract data by fitting the ext...
5,318,900
def load_json(path, api_version=None): """ Loads JSON to the given path, ignoring any C-style comments. """ path = os.path.abspath(path) with open(path, 'r') as fd: content = fd.read() content = minify_json.json_minify(content) d = json.loads(content) if api_version is not Non...
5,318,901
def wrap(get_io_helper_func): """A decorator that takes one argument. The argument should be an instance of the helper class returned by new_helper(). This decorator wraps a method so that is may perform asynchronous IO using the helper instance. The method being wrapped should take a keyword argumen...
5,318,902
def loads(fn, sdata=None): """ Load compressed pickle """ print " loading", fn fhd = gzip.open(fn, 'rb') print " loading", fn, 'opened' data = cPickle.load( fhd ) print " loading", fn, 'loaded' fhd.close() #print " loading", fn, 'closed', len(data), data.keys() if sdata ...
5,318,903
def copy_to_build_dir(variables: dict) -> Set[int]: """ Copy files from the source directory and paste them in the destination directory. Args: `variables` dict keys used: workspace_path: The path of the workspace we are working within (absolute). build_path: The path of ...
5,318,904
def internal_superset_url(): """The URL under which the Superset instance can be reached by from mara (usually circumventing SSOs etc.)""" return 'http://localhost:8088'
5,318,905
def temp(): """ Create a temporary file Returns ------- str Path of temporary file """ handle, name = tempfile.mkstemp() return name
5,318,906
def ignoreNamePath(path): """ For shutil.copytree func :param path: :return: """ path += ['.idea', '.git', '.pyc'] def ignoref(directory, contents): ig = [f for f in contents if (any([f.endswith(elem) for elem in path]))] return ig return ignoref
5,318,907
def erase_display(method=EraseMethod.ALL_MOVE, file=sys.stdout): """ Clear the screen or part of the screen, and possibly moves the cursor to the "home" position (1, 1). See `method` argument below. Esc[<method>J Arguments: method: One of these possible values: ...
5,318,908
def cos_np(data1,data2): """numpy implementation of cosine similarity for matrix""" print("warning: the second matrix will be transposed, so try to put the simpler matrix as the second argument in order to save time.") dotted = np.dot(data1,np.transpose(data2)) norm1 = np.linalg.norm(data1,axis=1) n...
5,318,909
def rebootTeensy(): """reboot the TeensyDuino. Reflashing Teensyduino is required given that no remote soft reset is provided besides the bootloader""" print("Resetting Teensy...") os.system('/home/pi/Desktop/teensy_loader_cli -mmcu=mk20dx256 -s -v ' + '/home/pi/Desktop/node*.hex')
5,318,910
def log_scale_dataset(df, add_small_value=1, set_NaNs_to=-10): """ Takes the log10 of a DF + a small value (to prevent -infs), and replaces NaN values with a predetermined value. Adds the new columns to the dataset, and renames the original ones. """ number_columns = get_number_columns(df) ...
5,318,911
def isoparse(s: str) -> tzdatetime: """ Parses timestamps formatted like 2020-05-01T10:32:02.925961Z """ # TODO could use dateutil? but it's quite slow as far as I remember.. # TODO support non-utc.. somehow? assert s.endswith('Z'), s s = s[:-1] + '+00:00' return fromisoformat(s)
5,318,912
def ul_model_evaluation(classifier, train_set, test_set, attack_set, beta=20): """ Evaluates performance of supervised and unsupervised learning algorithms """ y_pred_test = classifier.predict(test_set).astype(float) y_pred_outliers = classifier.predict(attack_set).astype(float) n_accurate_test...
5,318,913
def generate_hdp_slds_groundtrouth(folder, num_traces, num_steps, model): """This method generates a groundtrouth package and saves it. The parameters have to be adjusted below in order to get different outcomes. :param root: This represents the root folder of the data packages, which should be saved. ...
5,318,914
def config_path(*args, **kwargs): """ Join multiple paths from configuration and always use config['path']['base'] as base path. Use as follows: ```python config_path('model.train') ``` :param args: Lists of keys to load. :param kwargs: Keyword arguments. Currently available key: `base_p...
5,318,915
def receive_after_create(target, connection, tables, **kw): """listen for the 'after_create' event""" logger.info('A table was created' if tables else 'No table was created') print('A table was created' if tables else 'No table was created')
5,318,916
async def generate_data(q: asyncio.Queue, rate: float = 1.0): """ :param: items per second """ idx = 0 while True: idx += 1 item = idx*idx await q.put((item, time.time())) print("-->> Generated item {}".format(idx)) await asyncio.sleep(1 / rate)
5,318,917
def get_one_hot_predictions(tcdcn, x, dim): """ This method gets a model (tcdcn), passes x through it and gets it's prediction, then it gets one_hot matrix representation of the predictions. depending on whether tcdcn is RCN or a structured model, x can be an image (in the former case) and a one...
5,318,918
def delete(ctx, iface, resource_config, **_): """Deletes an KMS Key Alias""" # Create a copy of the resource config for clean manipulation. params = \ dict() if not resource_config else resource_config.copy() alias_name = params.get(RESOURCE_NAME) if not alias_name: params[RESOURCE...
5,318,919
def run_multi_lsp(x, y, err, fts, fmin=0.1, fmax=150, k_band=1, m_base=1, mode='fast', dt_cut=365, k_term_base=0): """Run all methods of multiband gatspy Lomb-Scargle Periodogram. Input ------ x, y, err, fts: phase, magnitudes/flux, error, filter list fmin, fmax: minimum and maximum...
5,318,920
def docs(c): # type: ignore """ Generate documentation """ c.run("sphinx-build -b html {} {}".format(DOCS_DIR, DOCS_BUILD_DIR)) webbrowser.open(DOCS_INDEX.as_uri())
5,318,921
def render_tablet_screen(): """ Serves the page for the tablet backend. :return: The tablet html file. """ return app.send_static_file('tablet.html')
5,318,922
def cli(ctx, provider, credentials_file, blueprint_dir): """ Test utility for testing blueprints. """ ctx.obj['PROVIDER'] = provider if credentials_file: with open(credentials_file) as credentials: ctx.obj['CREDENTIALS'] = json.loads(credentials.read()) else: ctx.obj[...
5,318,923
def add_content(resp, param, value): """Adds content/body of the response. ecocnt_html: html body, ecocnt_css: css body, ecocnt_js: js body, ecocnt_img: img body, ecocnt_vid: video body, ecocnt_audio: audio body, """ if param == "ecocnt_html": t = loader.get_template("echo/t...
5,318,924
def intersection_over_union(box1, box2): """Returns the IoU critera for pct of overlap area box = (left, right, bot, top), same as matplotlib `extent` format >>> box1 = (0, 1, 0, 1) >>> box2 = (0, 2, 0, 2) >>> print(intersection_over_union(box1, box2)) 0.25 >>> print(intersection_over_union...
5,318,925
def refresh_stream_for_entity( session: db.Session, entity_id: int, entity_type: str, source_entity_id: int ): """Creates or updates the Stream entry for the given entity **Please note:** this method does not commit the changes! You must flush the session in the invoking method. """ if entity_t...
5,318,926
def fpsol(nu,u): """ reads the vector normal and slip vector returning strike, rake, dip """ dip=np.arccos(-1*nu[2]) if nu[0] ==0. and nu[1] == 0.: str=0. else: str=np.arctan2(-1*nu[0],nu[1]) sstr=np.sin(str) cstr=np.cos(str) sdip=np.sin(dip) cdip=...
5,318,927
def p_unary_0(p): """ unary_func : BOUND """ p[0] = p[1]
5,318,928
def create_short_ticket(access_token, expire_seconds=2592000, scene_id=0): """ 创建临时二维码 :param access_token: 微信access_token :param expire_seconds: 二维码过期时间 :param scene_id: 场景值ID :return: """ target_url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=%s' % access_token ...
5,318,929
def test_getitem_nokey(testchannel): """Raise error if key not found in channel with a few added callables""" key = testchannel.add(list) for i in range(5): testchannel.add(list) testchannel.remove(key) with pytest.raises(KeyError) as err: testchannel.__getitem__(key) assert er...
5,318,930
def gen_compound(name, N=50, nP=10): """ (1) Alkane vs Alcohol N: the #carbon atom in compound, ex: N=50 generates compounds of different length from 1 to 50 carbons P: # of permutation to relabeling the vertex order for each generated compound ---------------------------------------------- ...
5,318,931
def unzip_file(path,extract_path=None): """ Unzip a zip file in a certain directory args: path -- path of the zip file extract_path -- directory to extract the file (default: None) """ with zipfile.ZipFile(path,"r") as zip_ref: zip_ref.extractall(extract_path) print('{}...
5,318,932
def build_youtube_search_request(): """ Building a query based on the following API - https://developers.google.com/youtube/v3/docs/search/list """ video_search_params = { "part": "id,snippet", "type": "video", "maxResults": 50, "publishedAfter": (datetime.now() - timedel...
5,318,933
def deploy(arguments): """Create resources required for Chalice demo.""" logging.info('Deploying Chalice app...') create_s3_bucket(arguments) create_ssm_param(arguments) update_chalice_config(arguments) chalice_command(arguments) logging.info('Complete')
5,318,934
def request_add_gateway(session, param): """ 请求加入一个GateServer """ server = PyServer.get_server() server.connect_to(param, 'GateServer')
5,318,935
def get_screen_size(): """Get **available** screen size/resolution.""" if mpl.get_backend().startswith('Qt'): # Inspired by spyder/widgets/shortcutssummary.py from qtpy.QtWidgets import QDesktopWidget # noqa widget = QDesktopWidget() sg = widget.availableGeometry(widget.primaryS...
5,318,936
def potential_bond_keys(mgrph): """ neighboring radical sites of a molecular graph """ ridxs = radical_sites(mgrph) return tuple(frozenset([ridx1, ridx2]) for ridx1, ridx2 in combinations(ridxs, 2) if ridx2 in atom_neighborhood_indices(mgrph, ridx1))
5,318,937
def convolve(signal,kernel): """ This applies a kernel to a signal through convolution and returns the result. Some magic is done at the edges so the result doesn't apprach zero: 1. extend the signal's edges with len(kernel)/2 duplicated values 2. perform the convolution ('same' mode) ...
5,318,938
def makemebv(gmat, meff): """Set up family-specific marker effects (GEBV).""" qqq = np.zeros((gmat.shape)) for i in range(gmat.shape[0]): for j in range(gmat.shape[1]): if gmat[i, j] == 2: qqq[i, j] = meff[j]*-1 elif gmat[i, j] == 1: qq...
5,318,939
def run_activity( input_path: Path, output_path: Path, activity_path: Path, verbose: bool, include_web_output: bool, config: Optional[Path] = None, ): """Run activity integration from standard input format.""" if not output_path.exists(): output_path.mkdir(parents=True) setup...
5,318,940
def _define_property_shape( prop: intermediate.Property, cls: intermediate.ClassUnion, url_prefix: Stripped, class_to_rdfs_range: rdf_shacl_common.ClassToRdfsRange, constraints_by_property: infer_for_schema.ConstraintsByProperty, ) -> Tuple[Optional[Stripped], Optional[Error]]: """Generate the s...
5,318,941
def row2string(row, sep=', '): """Converts a one-dimensional numpy.ndarray, list or tuple to string Args: row: one-dimensional list, tuple, numpy.ndarray or similar sep: string separator between elements Returns: string representation of a row """ return sep.join("{0}".form...
5,318,942
def download_profile_picture(user_id, discriminator, avatar_hash=None, cache_dir="cache", default_dir="default", cert_file=None, game_name=None, game_version=None, game_url=None): """ Download a discord user's profile picture. :param user_id: The discord user's ID :p...
5,318,943
def apply_kNNO(Xs, Xt, ys=None, yt=None, scaling=True, k=10, contamination=0.1): """ Apply kNNO. k-distance is the distance of its k-th nearest neighbour in the dataset KNNO ranks all instances in a dataset by their k-distance, with higher distances signifying more anomalous instances Parameter...
5,318,944
def _tenant_update(name, new_name=None, description=None, default_datastore=None): """ API to update a tenant """ logging.debug("_tenant_update: name=%s, new_name=%s, descrption=%s, default_datastore=%s", name, new_name, description, default_datastore) error_info, tenant = get_tenant_from_...
5,318,945
def pagination_menu(returned): """Search results pagination menu Arguments required: dictionary of database query search results """ len_returned = len(returned) print('RESULTS OUTPUT\n', "{} matching entries\n".format(len_returned), "-" * 30, "\nTo page through entries...
5,318,946
def evaluate_metrics(): """Evaluates metrics specified in the gin config.""" # Parse gin config. gin.parse_config_files_and_bindings([p.gin_file], []) for algo in p.algos: for task in p.tasks: run_paths = _get_run_paths(algo, task) # Evaluate metrics. outfile_prefix = os.path.join(p.metr...
5,318,947
def loans(sources, fail_on_exceptions): """Migrate loans from CDS legacy.""" for idx, source in enumerate(sources, 1): import_loans_from_json(source, fail_on_exceptions)
5,318,948
def _clone_all(urls: Iterable[str], cwd: str): """Attempts to clone all urls, sequentially. If a repo is already present, it is skipped. If any one clone fails (except for fails because the repo is local), all cloned repos are removed Args: urls: HTTPS urls to git repositories. cwd: Wo...
5,318,949
def write_text_tup(tup): """ Dump SQL command to a text file. :param tup: SQL command, text file path tuple """ # Unpack tuple, clean command and dump to text file _command, txt_file = tup write_text(_command, txt_file)
5,318,950
def set_input_file(input_file: str): """ Sets global input file as one as you put in parameters. Args: input_file: input file to read from (str). """ global INPUT_FILE INPUT_FILE = input_file
5,318,951
def build_aggregation(facet_name, facet_options, min_doc_count=0): """Specify an elasticsearch aggregation from schema facet configuration. """ exclude = [] if facet_name == 'type': field = 'embedded.@type' exclude = ['Item'] elif facet_name.startswith('audit'): field = facet...
5,318,952
def recover_marker_rbt(itf, tgt_mkr_name, cl_mkr_names, log=False): """ Recover the trajectory of a marker by rbt(rigid body transformation) using a group (cluster) markers. The number of cluster marker names is fixed as 3. This function extrapolates the target marker coordinates for the frames whe...
5,318,953
def csrf_token(remainder, params): """ Create and set CSRF token in preparation for subsequent POST request. This decorator is used to set the token. It also sets the ``'Cache-Control'`` header in order to prevent caching of the page on which the token appears. The POST handler must use the :py...
5,318,954
def set_seed(seed: int) -> None: """ Sets random seed across `random`, `numpy`, and `torch` for experiment replicability. Parameters ---------- seed: int seed number """ np.random.seed(seed) random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) ...
5,318,955
def route_wrap_01_version(request_mapping: str): """ flask 路由映射包裹器 增加API_VERSION :param request_mapping: :return: """ return '{}/{}'.format(API_VERSION, request_mapping)
5,318,956
def spawn(pool): """spawn a greenlet it will be automatically killed after the test run """ return pool.spawn
5,318,957
def test_encrypt_decrypt_password(): """Tests incorrect password sizes (should be handled automatically)""" salt = _generate_random_string(Crypt.get_salt_length()) crypt = Crypt(salt) password = _generate_random_string(AES.key_size[0] - 1) original_text =_generate_random_string(DEFAULT_CLEAR_TEXT_L...
5,318,958
def from_json_util(json_str: str) -> Any: """Load an arbitrary datatype from its JSON representation. The Out-of-proc SDK has a special JSON encoding strategy to enable arbitrary datatypes to be serialized. This utility loads a JSON with the assumption that it follows that encoding method. Par...
5,318,959
def bootstrap(environment: Environment): """ UCTT_Kubernetes bootstrap We dont't take any action. Our purpose is to run the above factory decorators to register our plugins. """ pass
5,318,960
def min_row_dist_sum_idx(dists): """Find the index of the row with the minimum row distance sum This should return the index of the row index with the least distance overall to all other rows. Args: dists (np.array): must be square distance matrix Returns: int: index of row wit...
5,318,961
def main(argv): """ """ ui = dcase_util.ui.FancyPrinter() ui.section_header('sed_visualizer') parameters = process_arguments(argv) if parameters['spectrogram']: mode = 'spectrogram' elif parameters['time_domain']: mode = 'time_domain' else: mode = None if ...
5,318,962
def rollbackto(ctx, # Mandatory main parameter volumeid, # Mandatory main parameter snapshotid, # Mandatory main parameter savecurrentstate, # Optional main parameter name = None, # Optional main parameter attr...
5,318,963
def inline(text): """ Convert all newline characters to HTML entities: &#10; This can be used to prevent Hypertag from indenting lines of `text` when rendering parent nodes, and to safely insert `text` inside <pre>, <textarea>, or similar elements. """ return text.replace('\n', '&#10;')
5,318,964
def align_pos(xyz, test_crd, ref_crd, ind=None): """Translates a set of atoms such that two positions are coincident. Parameters ---------- xyz : (N, 3) array_like The atomic cartesian coordinates. test_crd : (3,) array_like Cartesian coordinates of the original position. test_c...
5,318,965
def get_orderable_db_instance(availability_zone_group: Optional[str] = None, engine: Optional[str] = None, engine_version: Optional[str] = None, instance_class: Optional[str] = None, license_model: Op...
5,318,966
def _request_reach_curve( client, customer_id, product_mix, location_id, currency_code): """Creates a sample request for a given product mix. Args: client: A google.ads.google_ads.client.GoogleAdsClient instance. customer_id: The customer ID for the reach forecast. product_mix: The pr...
5,318,967
def test_main_gpio_wrb(caplog, capsys): """Test --gpio_wrb with a named gpio channel""" sys.argv = ['', '--gpio-wrb', '4', '1', '--dest', '!1234'] Globals.getInstance().set_args(sys.argv) channel = Channel(index=1, role=1) channel.settings.modem_config = 3 channel.settings.psk = b'\x01' pa...
5,318,968
def publish_channel_url(): """open_channel_url: returns url to publish channel Args: None Returns: string url to publish channel """ return PUBLISH_CHANNEL_URL.format(domain=DOMAIN)
5,318,969
def hist_counts(df_acts=None, lst_acts=None, df_ac=None, y_scale="linear", idle=False, figsize=None, color=None, file_path=None): """ Plot a bar chart displaying how often activities are occurring. Parameters ---------- df_acts : pd.DataFrame, optional recorded activities fr...
5,318,970
def random_dense(shape, fortran): """Generate a random qutip Dense matrix of the given shape.""" return qutip.core.data.Dense(random_numpy_dense(shape, fortran))
5,318,971
def bo_step(X, y, objective, bounds, GP=None, acquisition=None, q=1, state_dict=None, *GP_args, **GP_kwargs): """ One iteration of Bayesian optimization: 1. Fit GP model using (X, y) 2. Create acquisition function 3. Optimize acquisition function to obtain candidate point ...
5,318,972
def main(): """Main method for running upsidedown.py from the command line.""" import sys import locale _, default_encoding = locale.getdefaultlocale() output = [] line = sys.stdin.readline().decode(default_encoding) while line: line = line.strip("\n") output.append(transfo...
5,318,973
def validate_inputs(input_data): """Check prediction inputs against schema.""" # set many=True to allow passing in a list schema = InsuranceDataRequestSchema(strict=True, many=True) errors = None try: schema.load(input_data) except ValidationError as exc: errors = exc.messages ...
5,318,974
def published_stats_list(request): """ List cumulative stats about projects published. The request may specify the desired resource type """ resource_type = None # Get the desired resource type if specified if 'resource_type' in request.GET and request.GET['resource_type'] in ['0', '1']: ...
5,318,975
def test_authholder_credentials_save_notreally(auth_holder): """Save does not really save if cookies didn't change.""" # create some fake cookies fake_cookiejar = MozillaCookieJar(auth_holder._cookiejar_filepath) fake_cookie = get_cookie() fake_cookiejar.set_cookie(fake_cookie) fake_cookiejar.sa...
5,318,976
def check_file_hash(outer_json_blob: bytes, outer_json: Dict) -> None: """Test integrity of whole preferences file""" # It's HMAC-SHA256 after static-hash-substitution with a magic phrase file_hash = outer_json["security"]["file_hash"] hashed_json = outer_json_blob.replace(file_hash.encode("utf8"), HASH...
5,318,977
def get_entity(name): """Get an entity by the given name. Args: name (str): namespace.entity_name Returns: OntologyEntity: The entity with the given name. """ ns, n = name.split(".") return _namespace_registry._get(ns)._get(n)
5,318,978
def tst(): """members page.""" return render_template('users/testing2.html')
5,318,979
def get_bq_col_type(col_type): """ Return correct SQL column type representation. :param col_type: The type of column as defined in json schema files. :return: A SQL column type compatible with BigQuery """ lower_col_type = col_type.lower() if lower_col_type == 'integer': return 'I...
5,318,980
async def test_get_url_external(hass: HomeAssistant): """Test getting an instance URL when the user has set an external URL.""" assert hass.config.external_url is None with pytest.raises(NoURLAvailableError): _get_external_url(hass, require_current_request=True) # Test with external URL: http:...
5,318,981
def _log_exceptions_in_root_logger() -> None: """ Configure root logger to log uncaught exceptions under log level `ERROR`. :returns: Nothing, only side effects. """ root_logger = logging.getLogger() def handle_exception(exc_type, exc_value, exc_traceback): root_logger.error("Uncaught ex...
5,318,982
def _do_boundary_search(search_term): """ Execute full text search against all searchable boundary layers. """ result = [] query = _get_boundary_search_query(search_term) with connection.cursor() as cursor: wildcard_term = '%{}%'.format(search_term) cursor.execute(query, {'term'...
5,318,983
def test_microvm_virtio_blk_configuration(test_session_root_path, microvm, readonly): """ Test virtio-blk configuration: 1) Generate a temp disk 2) Configure temp disk read_only and Add it to test_vm 3) Launch to test_vm and get block information 4) Assert temp disk readonly as expect """ ...
5,318,984
def prices(identifier, start_date=None, end_date=None, frequency='daily', sort_order='desc'): """ Get historical stock market prices or indices. Args: identifier: Stock market symbol or index start_date: Start date of prices (default no filter) end_date: Last date (defaul...
5,318,985
def verify_captcha(secret, response, remoteip=None): """ From https://developers.google.com/recaptcha/docs/verify: secret: The shared key between your site and ReCAPTCHA. response: The user response token provided by the reCAPTCHA to the user and provided to your site on. rem...
5,318,986
def doc_a_pdf(archivo_entrada, archivo_salida): """ Carga un archivo de Word (.doc o .docx) de una ruta especificada por \ el usuario y lo convierte a PDF. El archivo PDF es guardado en otra \ ruta especificada por el usuario. Se necesita tener Microsoft Word \ instalado para utilizar esta función. ...
5,318,987
def x1y1x2y2_to_xywh(x1y1x2y2): """Convert [x1 y1 x2 y2] box format to [x y w h] format.""" if isinstance(x1y1x2y2, (list, tuple)): # Single box given as a list of coordinates assert len(x1y1x2y2) == 4 ct_x, ct_y = (x1y1x2y2[3] + x1y1x2y2[1]) / 2, (x1y1x2y2[2] + x1y1x2y2[0]) / 2 ...
5,318,988
def col(loc, strg): """ Returns current column within a string, counting newlines as line separators. The first column is number 1. Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See :class:`ParserElement.parseString` for more ...
5,318,989
def main(): """controls sequence of build pipeline""" args = main_parse_args() log_dir = os.path.join(args.working_dir, args.logs_path) if not os.path.exists(log_dir): os.makedirs(log_dir) # if there are scheduled jobs, return job_status = get_status(args.chronos) if len(job_status...
5,318,990
def create_model_fn(model_class, hparams, use_tpu=False): """Wraps model_class as an Estimator or TPUEstimator model_fn. Args: model_class: AstroModel or a subclass. hparams: ConfigDict of configuration parameters for building the model. use_tpu: If True, a TPUEstimator model_fn is returned. Otherwise ...
5,318,991
def boolean(value: Any) -> bool: """Validate and coerce a boolean value.""" if isinstance(value, str): value = value.lower() if value in ("1", "true", "yes", "on", "enable"): return True if value in ("0", "false", "no", "off", "disable"): return False rais...
5,318,992
def test_invalid_imei_char(pairing_list_importer, logger): """Test Depot ID 96616/2. Verify that Pairing List data is checked for invalid IMEI(s) and is not imported into the database. """ expect_failure(pairing_list_importer, exc_message='regex("^[0-9A-Fa-f\\\\*\\\\#]{1,16}$") fails ' ...
5,318,993
def unmap(data, count, inds, fill=0): """ Unmap a subset of item (data) back to the original set of items (of size count) :param data: input data :param count: the total count of data :param inds: the selected indices of input data :param fill: filled value :return: unmaped data """ ...
5,318,994
def test_fit_encoder(): """Test method fit of Categorical_encoder class.""" df = pd.read_csv("data_for_tests/train.csv") encoder = Categorical_encoder(strategy="wrong_strategy") with pytest.raises(ValueError): encoder.fit(df, df["Survived"]) encoder.set_params(strategy="label_encoding") ...
5,318,995
def test_fleur_band_fleurinp_Si_seekpath(with_export_cache, fleur_local_code, create_fleurinp, clear_database, clear_spec, aiida_caplog): """ Full example using the band dos workchain with just a fleurinp data as input. Uses seekpath to determine the path for the ban...
5,318,996
def processbundle(repo, unbundler, transactiongetter=None, op=None, source=b''): """This function process a bundle, apply effect to/from a repo It iterates over each part then searches for and uses the proper handling code to process the part. Parts are processed in order. Unknown Mandatory part will ...
5,318,997
def recursive_feature(G, f, n): """ G: iGraph graph with annotations func: string containing function name n: int, recursion level Computes the given function recursively on each vertex Current precondition: already have run the computation for G, func, n-1. """ retur...
5,318,998
def create_csv_dump(target_date, end_time='15:01:00', verbose=False): """ Creates a CSV file from JSON files for a given date. Raise an error if directory for the gven is not present. Created CSV files will be saved at the same location by the name: 'success.csv' & 'failure.csv' ...
5,318,999