content
stringlengths
22
815k
id
int64
0
4.91M
def remove_header_comments_from_files(list_of_files: List[Union[str, Path]]) -> None: """ Check the files in the provided list for invalid headers (no type defined) and removes those inplace when found. Args: list_of_files (List[Union[str, Path]]): list of Paths to **TFS** files meant to be che...
5,330,800
def coeff_modulus_192(poly_modulus_degree): """ Returns the default coefficients modulus for a given polynomial modulus degree. :param poly_modulus_degree: Polynomial modulus degree (1024, 2048, 4096, 8192, 16384, or 32768) :return: """ return seal.coeff_modulus_128(poly_modulus_degree)
5,330,801
def __add_statement(is_position: bool) -> Statement: """ Adds a new statement to the database :param is_position: True if the statement should be a position :return: New statement object """ db_statement = Statement(is_position=is_position) DBDiscussionSession.add(db_statement) DBDiscus...
5,330,802
def draw_track(center: Path, left: Path, right: Path, **kwargs): """ Draws a center line and two side paths. This works for e.g. linearized track + extruded sides """ Tracking(center.x, center.y, lw=2, color=blue_grey_light, **kwargs) Tracking(left.x, left.y, lw=1, ls="--", color=blue_gr...
5,330,803
def xgcd(a: int, b: int) -> tuple: """ Extended Euclidean algorithm. Returns (g, x, y) such that a*x + b*y = g = gcd(a, b). """ x0, x1, y0, y1 = 0, 1, 1, 0 while a != 0: (q, a), b = divmod(b, a), a y0, y1 = y1, y0 - q * y1 x0, x1 = x1, x0 - q * x1 return b, x0, y0
5,330,804
def correct_predictions(output_probabilities, targets): """ 计算与模型输出中的某些目标类匹配的预测数量 Args: output_probabilities: 不同输出类的概率张量 targets: 实际目标类的索引 Returns: 返回:“output_probabilities”中正确预测的数量 """ _, out_classes = output_probabilities.max(dim=1) correct = (out_classes == targets)...
5,330,805
def test_compress_non_str(): """Verify only str being accepted by compress.""" raw = "The quick brown fox jumps over the lazy dog." with pytest.raises(TypeError): smaz.compress([raw]) with pytest.raises(TypeError): smaz.compress((raw,)) with pytest.raises(TypeError): smaz.com...
5,330,806
def get_base_url(url: str) -> str: """ Return base URL for given URL. Example: Return http://example.com for input http://example.com/path/path Return scheme://netloc """ url = format_url(url) parsed = parse_url(url) return'{uri.SCHEME}://{uri.NETLOC}/'.format(uri=parsed)
5,330,807
def setup_tutorial(): """ Helper function to check correct configuration of tf and keras for tutorial :return: True if setup checks completed """ # Set TF random seed to improve reproducibility tf.set_random_seed(1234) if not hasattr(backend, "tf"): raise RuntimeError("This tutoria...
5,330,808
def split_value(s, splitters=["/", "&", ","]): """Splits a string. The first match in 'splitters' is used as the separator; subsequent matches are intentionally ignored.""" if not splitters: return [s.strip()] values = s.split("\n") for spl in splitters: spl = re.compile(r"\b\s*%s\s*...
5,330,809
def plotStressxEpoch(data, title="", outdir=""): """ Plots mean stress of hidden layer when training, along time (epochs). :param data: pandas dataframe, ordered by epoch :param title: title for the plot :param outdir: output dir to store the plot """ fig, ax = plt.subplots() x=data["ep...
5,330,810
def smape(y_true: np.ndarray, y_pred: np.ndarray) -> float: """ Calculates symmetric mean absolute percentage error SMAPE Args: y_true (np.ndarray): Actual values Y y_pred (np.ndarray): Predicted values Y Returns: [float]: smape """ error = np.abs(y_true - y_pred) / (np...
5,330,811
def dealwithtype( x, t ): """ return x and t as an array broadcast values if shape of x != shape of y and neither x or t are scalar """ x = np.asarray( x ) t = np.asarray( t ) if not x.shape and not t.shape: pass elif not x.shape: x = x*np.ones_like( t ) elif...
5,330,812
def format_img_size(img, C: FasterRcnnConfiguration): """ formats the image size based on config """ img_min_side = float(C.resize_smallest_side_of_image_to) (height, width, _) = img.shape if width <= height: ratio = img_min_side / width new_height = int(ratio * height) new_widt...
5,330,813
def test_atomic_language_min_length_2_nistxml_sv_iv_atomic_language_min_length_3_5(mode, save_output, output_format): """ Type atomic/language is restricted by facet minLength with value 9. """ assert_bindings( schema="nistData/atomic/language/Schema+Instance/NISTSchema-SV-IV-atomic-language-min...
5,330,814
def build_tile_count_map(tile_counts): """Build a map from a tile key to a count.""" tile_count_map = defaultdict(int) for tile_count in tile_counts: tile = tile_count.tile tile_key = (tile.letter, tile.value, tile.is_blank) tile_count_map[tile_key] = tile_count.count return tile...
5,330,815
def test_resample_errors(fx_asset): """Sampling errors.""" with Image(filename=str(fx_asset.join('mona-lisa.jpg'))) as img: with raises(TypeError): img.resample(x_res='100') with raises(TypeError): img.resample(y_res='100') with raises(ValueError): img...
5,330,816
def format(session): """ Run black and isort on the codebase. It is known that both formatters can have conflicts, so try to run `nox -s lint` before commiting! """ session.install("-r", "tests/requirements.txt") session.run("isort", ".") session.run("black", ".")
5,330,817
def after_feature(context: Context, feature: Feature) -> NoReturn: """Running after each feature file is exercised. The feature passed in is an instance of Feature. Args: context (behave.runner.Context): used by behave framework, store with scenario, feature, user data and so on. ...
5,330,818
def _convert_dataset(dataset_split): """Converts the specified dataset split to TFRecord format. Args: dataset_split: The dataset split (e.g., train, test). Raises: RuntimeError: If loaded image and label have different shape. """ dataset = os.path.basename(dataset_split)[:-4] #? sys.stdout.write(...
5,330,819
def get_uid_to_user(restful_url): """Gets uid -> user mapping from restful url""" query_url = restful_url + "/GetAllUsers" resp = requests.get(query_url) if resp.status_code != 200: logger.warning("Querying %s failed.", query_url) return {} data = json.loads(resp.text) uid_to_us...
5,330,820
def test_filtered_instrument_keywords(): """Test to see that the instrument specific service keywords are different for all instruments""" kw = [] for ins in JWST_INSTRUMENT_NAMES: kw.append(mm.instrument_keywords(ins, caom=False)['keyword'].tolist()) assert kw[0] != kw[1] != kw[2] != kw[3]...
5,330,821
def test_select_deterministc_leaf_by_max_scores(): """Some tests on :func:`select_deterministc_leaf_by_max_scores`""" node_scoring_method = partial(ucb_scores, ucb_constant=10) info = {} # if only one leaf, should find it root = DeterministicNode( {"latent_state": "root", "reward": 0.5, "n"...
5,330,822
def parse_text(text): """ Parse raw text format playlists, each line must contain a single. track with artist and title separated by a single dash. eg Queen - Bohemian Rhapsody :param str text: :return: A list of tracks """ tracks: List[tuple] = [] for line in text.split("\n"): ...
5,330,823
def set_tickers(request, tickers): """ Sets requested tickers in the Bloomberg's request. Parameters ---------- request request to be sent tickers: List[str] required tickers """ securities = request.getElement(SECURITIES) for ticker in tickers: securities.a...
5,330,824
def R_nl(n, l, r, Z=1): """ Returns the Hydrogen radial wavefunction R_{nl}. n, l .... quantum numbers 'n' and 'l' r .... radial coordinate Z .... atomic number (1 for Hydrogen, 2 for Helium, ...) Everything is in Hartree atomic units. Examples:: >>> from sympy.physics.hydrogen...
5,330,825
def generate_new_classes(start_cycle_number=0, class_number=50, input_stack="combined_stack.mrcs", pixel_size=1.2007, mask_radius=150, low_res=300, high_res=40, new_star_file="cycle_0.star", working_directory="~", automask=False, autocenter=True): """ Call out to cisTEM2 ``refine2d`` using :py:func:`subprocess....
5,330,826
def entity_by_name(name): """Adapt Entity.name (not Entity.class_name!) to entity.""" entities = zope.component.getUtility( icemac.addressbook.interfaces.IEntities).getEntities(sorted=False) for candidate in entities: if candidate.name == name: return candidate raise ValueErr...
5,330,827
def _update_longitude_attrs(config, output_filename): """Update attributes of longitude.""" ncodir = config["s2smetric"]["ncodir"] cmd = f"{ncodir}/ncatted" cmd += " -a long_name,longitude,c,c,'longitude'" cmd += " -a standard_name,longitude,c,c,'longitude'" cmd += " -a units,longitude,c,c,'degr...
5,330,828
def export_single_floor(floor): """exports a single floor """ return mt.Floor( *export_vertices(floor.Points), id=str(next_id()), ep_id=floor.Id, type=str(id_map(floor.Type.Id)))
5,330,829
def test_tcp_tls_verify_both(): """ Test TCP TLS client server connection with verify certs for both client and server """ certDirPath = localTestCertDirPath() assert os.path.exists(certDirPath) serverKeyPath = os.path.join(certDirPath, 'server_key.pem') # local server private key serverC...
5,330,830
def test_hapd_dup_network_global_wpa2(dev, apdev): """hostapd and DUP_NETWORK command (WPA2)""" passphrase="12345678" src_ssid = "hapd-ctrl-src" dst_ssid = "hapd-ctrl-dst" src_params = hostapd.wpa2_params(ssid=src_ssid, passphrase=passphrase) src_ifname = apdev[0]['ifname'] src_hapd = hosta...
5,330,831
def tensor_lab2rgb(input): """ n * 3* h *w """ input_trans = input.transpose(1, 2).transpose(2, 3) # n * h * w * 3 L, a, b = input_trans[:, :, :, 0:1], input_trans[:, :, :, 1:2], input_trans[:, :, :, 2:] y = (L + 16.0) / 116.0 x = (a / 500.0) + y z = y - (b / 200.0) neg_mask = z.da...
5,330,832
def get_absolute_path(file_name, package_level=True): """Get file path given file name. :param: [package_level] - Wheather the file is in/out side the `gmail_api_wrapper` package """ if package_level: # Inside `gmail_api_wrapper` dirname = os.path.dirname(__file__) else: ...
5,330,833
def cancel_order(order, restock): """Cancel order and associated fulfillments. Return products to corresponding stocks if restock is set to True. """ if restock: restock_order_lines(order) for fulfillment in order.fulfillments.all(): fulfillment.status = FulfillmentStatus.CANCELED ...
5,330,834
def thanos(planet: dict, finger: int) -> int: """ Thanos can kill half lives of a world with a snap of the finger """ keys = planet.keys() for key in keys: if (++finger & 1) == 1: # kill it planet.pop(key) return finger
5,330,835
def ordered_list_item_to_percentage(ordered_list: List[str], item: str) -> int: """Determine the percentage of an item in an ordered list. When using this utility for fan speeds, do not include "off" Given the list: ["low", "medium", "high", "very_high"], this function will return the following when w...
5,330,836
def simple2tradition(line): """ 将简体转换成繁体 """ line = Converter('zh-hant').convert(line) return line
5,330,837
def normalize_colors(colors): """ If colors are integer 8bit values, scale to 0 to 1 float value used by opengl :param colors: :return: """ if colors.dtype is not np.float32: colors = colors.astype(np.float32) / 255.0 return colors
5,330,838
def load_text_data(path, word_dict): """ Read the given path, which should have one sentence per line :param path: path to file :param word_dict: dictionary mapping words to embedding indices :type word_dict: WordDictionary :return: a tuple with a matrix of sentences and an array ...
5,330,839
def test_identity_projection(projection_type): """Sanity check: identical input & output headers should preserve image.""" header_in = fits.Header.fromstring(IDENTITY_TEST_HDR, sep='\n') data_in = np.random.rand(header_in['NAXIS2'], header_in['NAXIS1']) if projection_type == 'flux-conserving': d...
5,330,840
def dirty(graph): """ Return a set of all dirty nodes in the graph. """ # Reverse the edges to get true dependency return {n: v for n, v in graph.node.items() if v.get('build') or v.get('test')}
5,330,841
def hangman(secret_word): """ secret_word: string, the secret word to guess. Starts up an interactive game of Hangman. * At the start of the game, let the user know how many letters the secret_word contains and how many guesses s/he starts with. * The user should start with 6 guesses * Before ...
5,330,842
def sin_potential(z): """Sin-like potential.""" z = tf.transpose(z) x = z[0] y = z[1] # x, y = z return 0.5 * ((y - w1(z)) / 0.4) ** 2 + 0.1 * tf.math.abs(x)
5,330,843
def erode_label(image_numpy, iterations=2, mask_value=0): """ For each iteration, removes all voxels not completely surrounded by other voxels. This might be a bit of an aggressive erosion. Also I would bet it is incredibly ineffecient. Also custom erosions in multiple dimensions look a lit...
5,330,844
def _resolve_dir_against_charm_path(charm: CharmBase, *path_elements: str) -> str: """Resolve the provided path items against the directory of the main file. Look up the directory of the main .py file being executed. This is normally going to be the charm.py file of the charm including this library. Then, ...
5,330,845
def mpi_submit(nworker, nserver, pass_envs): """ customized submit script, that submit nslave jobs, each must contain args as parameter note this can be a lambda function containing additional parameters in input Parameters nworker number of slave process to start up nserver numb...
5,330,846
def computeBFGridPoint(basis, U, gpi, gps): """ Compute the bilinear form for one grid point with the points stored in gps @param basis: basis of sparse grid function, @param U: list of distributions @param gpi: HashGridPoint @param gps: list of HashGridPoint """ n = len(gps) s =...
5,330,847
def test_lateValidation(): """ Test that you can populate a Query using strings and run the validation afterwards """ y = q.Query('myToc', myStr="foo", myBool=True) assert y.toc is None assert y.tocName == 'myToc' for attr in list(y[0].keys()): assert isinstance(attr, str) y...
5,330,848
def list_files(commit: Optional[str] = None, pathspecs: Collection[PathOrStr] = (), exclude: Collection[Pattern[str]] = (), repo: Optional[Path] = None) -> List[Path]: """Lists files with git ls-files or git diff --name-only. Args: commit: commit to use as a b...
5,330,849
def merge_apply(las_paths_fn, las_fn): """Merge the las files into one, a few at a time. This replaces the logic of HPC.daligner. """ io.rm_force(las_fn) #all_las_paths = rel_to(io.deserialize(las_paths_fn), os.path.dirname(las_paths_fn)) all_las_paths = io.deserialize(las_paths_fn) # Crea...
5,330,850
def compute_smatch_batch(gold_filename, test_filename, starts, method , restart_threshold, concept_edges, precise, missing, detailed): """ Compute SMATCH on two files with pairwise AMRs, one-AMR-per-line. """ ps, rs, fs = [], [],[] try: ...
5,330,851
def sum_by_hexagon(df,resolution,pol,fr,to,vessel_type=[],gt=[]): """ Use h3.geo_to_h3 to index each data point into the spatial index of the specified resolution. Use h3.h3_to_geo_boundary to obtain the geometries of these hexagons Ex counts_by_hexagon(data, 8) """ if vessel_t...
5,330,852
def _ibp_sub(lhs, rhs): """Propagation of IBP bounds through a substraction. Args: lhs: Lefthand side of substraction. rhs: Righthand side of substraction. Returns: out_bounds: IntervalBound. """ return lhs - rhs
5,330,853
def test_bool(): """ >>> assert lua.decode('false') == False >>> assert lua.decode('true') == True >>> assert lua.encode(False) == 'false' >>> assert lua.encode(True) == 'true' """ pass
5,330,854
def toil_make_tool( toolpath_object: CommentedMap, loadingContext: cwltool.context.LoadingContext, ) -> Process: """ Emit custom ToilCommandLineTools. This factory funciton is meant to be passed to cwltool.load_tool(). """ if ( isinstance(toolpath_object, Mapping) and toolpa...
5,330,855
def sentinel_s1(metadata): """ Parse metadata and return basic Item with rasterio.open('/Users/scott/Data/sentinel1-rtc/local_incident_angle.tif') as src: ...: metadata = src.profile ...: metadata.update(src.tags()) """ def get_datetime(metadata): ''' retrieve UTC start...
5,330,856
def get_loc(data, attr={'lr_mult':'0.01'}): """ the localisation network in lenet-stn, it will increase acc about more than 1%, when num-epoch >=15 """ loc = mx.symbol.Convolution(data=data, num_filter=30, kernel=(5, 5), stride=(2,2)) loc = mx.symbol.Activation(data = loc, act_type='relu') l...
5,330,857
def test_data_dimension_after_dead_time_correction(crd_file): """Ensure ToF and data have the same dimensions - BF 2021-07-23.""" _, _, _, fname = crd_file crd = CRDFileProcessor(Path(fname)) crd.spectrum_full() crd.dead_time_correction(3) assert crd.tof.ndim == crd.data.ndim
5,330,858
def meanwave(signals): """ This function computes the meanwave of various signals. Given a set of signals, with the same number of samples, this function returns an array representative of the meanwave of those signals - which is a wave computed with the mean values of each signal's samples. ...
5,330,859
def set_difficulty(): """Ask the difficult level and return the number of turns corresponding""" if input("Choose a difficulty level. Type 'easy' or 'hard': ").lower() == "easy": return EASY_TURNS else: return HARD_TURNS
5,330,860
def delete_event_by_id(id, user_id): """Remove one event based on id.""" sql = "DELETE FROM events WHERE id = :id AND host_id = :user_id RETURNING title;" db.session.execute(sql, {"id": id, "user_id": user_id}) db.session.commit() return ["Event deleted."]
5,330,861
def get_cmap_colors(cmap='jet',p=None,N=10): """ """ cm = plt.get_cmap(cmap) if p is None: return [cm(i) for i in np.linspace(0,1,N)] else: normalize = matplotlib.colors.Normalize(vmin=min(p), vmax=max(p)) colors = [cm(normalize(value)) for value in p] return colors
5,330,862
def reader_factory(load_from, file_format): """Select and return instance of appropriate reader class for given file format. Parameters __________ load_from : str or file instance file path or instance from which to read file_format : str format of file to be read Returns _...
5,330,863
def scrape_with_selenium(chrome, chrome_webdriver, url, xpath_tup_list, timeout): """Scrape using Selenium and Chrome.""" result_dic = {} with SeleniumChromeSession(chrome=chrome, chrome_webdriver=chrome_webdriver) as driver: wait_conditions = [] for xpath_tup in xpath_tup_list: ...
5,330,864
def take_element_screenshot(page_screenshot: Image.Image, bbox: Rectangle) -> Image.Image: """ Returns the cropped subimage with the coordinates given. """ w, h = page_screenshot.size if bbox.area == 0: raise ValueError(f"Rectangle {bbox} is degenerate") if bbox not in Rectangle(Point(...
5,330,865
def officeOfRegistrar_forward(request, id): """form to set receiver and designation of forwarded file """ context = {"track_id": id} return render(request, "officeModule/officeOfRegistrar/forwardingForm.html", context)
5,330,866
def test_batching_hetero_topology(index_dtype): """Test batching two DGLHeteroGraphs where some nodes are isolated in some relations""" g1 = dgl.heterograph({ ('user', 'follows', 'user'): [(0, 1), (1, 2)], ('user', 'follows', 'developer'): [(0, 1), (1, 2)], ('user', 'plays', 'game'): [(0...
5,330,867
def vector_quaternion_arrays_allclose(vq1, vq2, rtol=1e-6, atol=1e-6, verbose=0): """Check if all the entries are close for two vector quaternion numpy arrays. Quaterions are a way of representing rigid body 3D rotations that is more numerically stable and compact in memory than other methods such as a 3x3...
5,330,868
def test_gen_mocs_epoch_stmoc_failure(mocker) -> None: """ Tests the generation of all MOCs and STMOCs for a single epoch. Also tests the update of the full STMOC. Args: mocker: The pytest mock mocker object. Returns: None """ base_stmoc = '/path/to/stmoc.fits' mocker...
5,330,869
def compute_coherence_values(dictionary, corpus, texts, limit, start=2, step=3): """ Compute c_v coherence for various number of topics Parameters: ---------- dictionary : Gensim dictionary corpus : Gensim corpus texts : List of input texts limit : Max num of topics Returns: ----...
5,330,870
def bot_reply(ctx, smtp, fallback_delivto): """reply to stdin mail as a bot. This command processes an incoming e-mail message for the bot and sends a reply if the bot was addressed in a "To" header. If the bot was only addressed in the CC header it will process the mail but not reply. If the ...
5,330,871
def autocorr_quad(w, f, t, method = 'direct'): """ Calculate the vacuum state autocorrelation function for propagation on a quadratic potential energy surface. Parameters ---------- w : array_like The harmonic frequency (in energy units) of each mode. f : array_like ...
5,330,872
def train(**kwargs): """ This will be a two step process, first train disc only, then train gen only :param kwargs: :return: """ batch_size = kwargs['batch_size'] gen = kwargs['gen'] disc = kwargs['discriminator'] device = kwargs['device'] gen.to(device) disc.to(device) ...
5,330,873
def add_project(body): """ POST /api/projects :param body: :return: """ try: return { 'title': 'Succeed to Create Project', 'detail': svcProject.add_project(body) }, 200 except Exception as e: raise DefaultError(title='Failed to Create Project'...
5,330,874
def new_client(user_id: str, session=DBSession) -> Client: """ from user_id get a miniflux client :param user_id: telegram chat_id :param session: database session class :type user_id: Union[int, str] :raise UserNotBindError: user not bind a miniflux account """ session = session() user...
5,330,875
def create_utility_meters( hass: HomeAssistantType, energy_sensor: Union[VirtualEnergySensor, GroupedEnergySensor], sensor_config: dict, ) -> list[UtilityMeterSensor]: """Create the utility meters""" utility_meters = [] if not sensor_config.get(CONF_CREATE_UTILITY_METERS): return [] ...
5,330,876
def plot_all_K(name_or_paths, *args): """Plot the typical K-N plot. Args: name_or_paths: a list of str """ if isinstance(name_or_paths, str): name_or_paths = [name_or_paths] all_name_or_paths = name_or_paths[:] for arg in args: all_name_or_paths += arg all_name_or_pa...
5,330,877
def builtin_divmod(a, b): """Divide two numbers and take the quotient and remainder.""" aa, bb = BType.commonize(a, b) dv, mv = divmod(aa.value, bb.value) d = type(aa)(dv) m = type(aa)(mv) return (d, m)
5,330,878
def format_adjacency(G: nx.Graph, adj: np.ndarray, name: str) -> xr.DataArray: """ Format adjacency matrix nicely. Intended to be used when computing an adjacency-like matrix off a graph object G. For example, in defining a func: ```python def my_adj_matrix_func(G): adj = some_adj_...
5,330,879
def delete_contact(contacts: list[list[str]]) -> None: """Delete a contact from the contact list.""" contact_number: int = int(input(NUMBER_PROMPT)) if not _is_contact_number(contact_number, contacts): display_contact_error(contact_number) else: contact: list[str] = contacts.pop(co...
5,330,880
def batch_local_stats_from_coords(coords, mask): """ Given neighborhood neighbor coordinates, compute bond distances, 2-hop distances, and angles in local neighborhood (this assumes the central atom has coordinates at the origin) """ one_hop_ds, two_dop_d_mat = batch_distance_metrics_from_coords...
5,330,881
def resolve_sender_entities(act, lexical_distance=0): """ Given an Archive's activity matrix, return a dict of lists, each containing message senders ('From' fields) that have been groups to be probably the same entity. """ # senders orders by descending total activity senders = act.sum(0)....
5,330,882
def ddpg( env: gym.Env, agent: ContinuousActorCriticAgent, epochs: int, max_steps: int, buffer_capacity: int, batch_size: int, alpha: float, gamma: float, polyak: float, act_noise: float, verbose: bool, ) -> List[float]: """Trains an agent using Deep Deterministic Policy ...
5,330,883
def import_module_from_path(full_path, global_name): """ Import a module from a file path and return the module object. Allows one to import from anywhere, something ``__import__()`` does not do. The module is added to ``sys.modules`` as ``global_name``. :param full_path: The absolute path...
5,330,884
def civic_eid26_statement(): """Create a test fixture for CIViC EID26 statement.""" return { "id": "civic.eid:26", "description": "In acute myloid leukemia patients, D816 mutation is associated with earlier relapse and poorer prognosis than wildtype KIT.", # noqa: E501 "direction": "sup...
5,330,885
def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # Use a dummy metaclass that replaces itself with the actual metaclass. class metaclass(type): def __new__(cls, name, this_bases, d): return meta(name, bases, d) return type.__new__(metaclass, '_TemporaryCl...
5,330,886
def validate_user(username, minlen): """Checks if the received username matches the required conditions.""" if type(username) != str: raise TypeError("username must be a string") if minlen < 1: raise ValueError("minlen must be at least 1") """ Username should not be shorter than min...
5,330,887
def neg_mae_macro(y_trues, y_preds, labels, topics): """ As for absolute error, lower is better Thus use negative value in order to share the same interface when tuning dev data with other metrics """ return -mae_macro(y_trues, y_preds, labels, topics)
5,330,888
def transcribe_from_google(tmp_dir): """ Transcribes assets in given tmp directory into text assets via Google Cloud Transcribe """ def tmp(path): return os.path.join(tmp_dir, path) script = "#!/bin/bash\n \ export GOOGLE_APPLICATION_CREDENTIALS=~/.gcloud/gcloud-alexa-cli.json \n \ export ACCESS_TOK...
5,330,889
def clean_data(df): """Cleans the a dataset provided as a DataFrame and returns the cleaned DataFrame. Cleaning includes expanding the categories and cleaning them up. Args: df (DataFrame): Data, containing categories as a single column, as well as messages Returns: DataFrame: Cleaned...
5,330,890
def _validate_float(mapping: Mapping[str, Any], ref: str) -> Optional[SchemaError]: """ Validate the definition of a float value. :param mapping: representing the type definition to be validated :param ref: reference to the type definition :return: error, if any """ if '...
5,330,891
def greatest_product(number): """ Finds the greatest product of 5 consecutive digits in the 1000-digit number """ largest = 1 for n in range(1, 997, 1): product = compute_product(number % (10 ** 5)) if product > largest: largest = product number //= 10 print('...
5,330,892
def test_cray_crus_session_create_usage_info(cli_runner, rest_mock): """ Test `cray crus` to make sure the expected commands are available """ runner, cli, _ = cli_runner result = runner.invoke(cli, ['crus', 'session', 'create', '--help']) outputs = [ "cli crus session create [OPTIONS]", ...
5,330,893
def tokenize_document(document: str) -> typing.List[str]: """ Helper method to tokenize the document. :param document: The input document represented as a string. :return: A list of tokens. """ try: return nltk.tokenize.word_tokenize(document) except LookupError: nltk.downloa...
5,330,894
def get_type_name_value(obj): """ Returns object type name from LLDB value. It returns type name with asterisk if object is a pointer. :param lldb.SBValue obj: LLDB value object. :return: Object type name from LLDB value. :rtype: str | None """ return None if obj is None else obj.GetTy...
5,330,895
def fastqprint(fastq): """ Printing a fastq file """ for record in SeqIO.parse(fastq, "fastq"): print("%s %s" % (record.id, record.seq)) return seq1.reverse_complement()
5,330,896
def make_day(day: int, input_dir: Path, session_path: Path): """Make or read the input file for the day. Reading preferred so we don't hammer the fine folk's server at Advent of Code. """ session_id = load_session_id(session_path) txt = do_get(day, session_id) if not input_dir.exists(): ...
5,330,897
def test_radius_auth_unreachable(dev, apdev): """RADIUS Authentication server unreachable""" params = hostapd.wpa2_eap_params(ssid="radius-auth") params['auth_server_port'] = "18139" hostapd.add_ap(apdev[0]['ifname'], params) hapd = hostapd.Hostapd(apdev[0]['ifname']) connect(dev[0], "radius-aut...
5,330,898
def encodePartList( part_instance: ObjectInstance, vh_group_list: List[int]) -> dict: """ Used for copying and pasting TODO: unify encodePart and encodePartList Args: part_instance: The ``Part`` ``ObjectInstance``, to allow for instance specific property copying ...
5,330,899