content
stringlengths
22
815k
id
int64
0
4.91M
def rot_permutated_geoms(geo, saddle=False, frm_bnd_key=[], brk_bnd_key=[], form_coords=[]): """ convert an input geometry to a list of geometries corresponding to the rotational permuations of all the terminal groups """ gra = graph(geo, remove_stereo=True) term_atms = {} all_hyds = [] ...
21,900
def wasserstein_loss(y_true, y_pred): """ for more detail: https://github.com/keras-team/keras-contrib/blob/master/examples/improved_wgan.py""" return K.mean(y_true * y_pred)
21,901
def call_and_transact( contract_function: ContractFunction, transaction_params: Optional[TxParams] = None, ) -> HexBytes: """ Executes contract_function.{call, transaction}(transaction_params) and returns txhash """ # First 'call' might raise an exception contract_function.call(transaction_params) r...
21,902
def bidirectional_rnn_model(input_dim, units, output_dim=29): """ Build a bidirectional recurrent network for speech Params: input_dim (int): Length of the input sequence. units: output dimensions of the GRU output_dim: output dimensions of the dense connected layers Retur...
21,903
def test_setitem(): """Test __setitem__.""" sl = setlist('abc') sl[0] = 'd' assert sl == setlist('dbc') sl[0] = 'd' assert sl == setlist('dbc') sl[1] = 'e' assert sl == setlist('dec') sl[2] = 'f' assert sl == setlist('def') with pytest.raises(IndexError): sl[3] = 'g' sl[0], sl[1] = 'h', 'i' assert sl == ...
21,904
def compress_sparql(text: str, prefix: str, uri: str) -> str: """ Compress given SPARQL query by replacing all instances of the given uri with the given prefix. :param text: SPARQL query to be compressed. :param prefix: prefix to use as replace. :param uri: uri instance to be replaced. :return:...
21,905
def easter(g_year): """Return fixed date of Easter in Gregorian year g_year.""" century = quotient(g_year, 100) + 1 shifted_epact = mod(14 + 11 * mod(g_year, 19) - quotient(3 * century, 4) + quotient(5 + (8 * century), 25), 30) adju...
21,906
def _with_generator_error_translation(code_to_exception_class_func, func): """Same wrapping as above, but for a generator""" @funcy.wraps(func) def decorated(*args, **kwargs): """Execute a function, if an exception is raised, change its type if necessary""" try: for x in func(*a...
21,907
def test_link_ts8(): """Test linking input ts8 files""" link_ts8_files(LINK_OPTIONS_TS8)
21,908
async def test_failed_update_and_reconnection( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker ): """Test failed update and reconnection.""" mock_responses(aioclient_mock) assert await async_setup_component( hass, SENSOR_DOMAIN, {SENSOR_DOMAIN: ONE_SENSOR_CONFIG} ) aioclient_moc...
21,909
def openei_api_request( data, ): """Query the OpenEI.org API. Args: data (dict or OrderedDict): key-value pairs of parameters to post to the API. Returns: dict: the json response """ # define the Overpass API URL, then construct a GET-style URL as a string to # ...
21,910
def boring_stuff(axarr, edir): """ Axes, titles, legends, etc. Yeah yeah ... """ for i in range(2): for j in range(3): if i == 0 and j == 0: axarr[i,j].set_ylabel("Loss Training MBs", fontsize=ysize) if i == 0 and j == 1: axarr[i,j].set_ylabel("Los...
21,911
def cloudtrail_cleanup(): """Function to clean up CloudTrail Logs""" logging.info("Cleaning up CloudTrail Logs.") try: logging.info("Cleaning up CloudTrail Logs created by Assisted Log Enabler for AWS.") trail_list: list = [] removal_list: list = [] logging.info("DescribeTrai...
21,912
def generate_content(vocab, length): """Generate a random passage. Pass in a dictionary of words from a text document and a specified length (number of words) to return a randomized string. """ new_content = [] pair = find_trigram(vocab) while len(new_content) < length: third = find...
21,913
def transform_generic(inp: dict, out, met: ConfigurationMeta) -> list: """ handle_generic is derived from P -> S, where P and S are logic expressions. This function will use a generic method to transform the logic expression P -> S into multiple mathematical constraints. This is done by first conv...
21,914
def test_pass_by_reference() -> None: """Test whether pass-by-reference arguments work correctly.""" inc = TestNamespace() incArgRef = inc.addArgument("R") incArgVal = inc.emit_load(incArgRef) incAdd = AddOperator(incArgVal, IntLiteral(1)) inc.emit_store(incArgRef, incAdd) incCode = inc.crea...
21,915
def generate_mprocess_from_name( c_sys: CompositeSystem, mprocess_name: str, is_physicality_required: bool = True ) -> MProcess: """returns MProcess object specified by name. Parameters ---------- c_sys : CompositeSystem CompositeSystem of MProcess. mprocess_name : str name of t...
21,916
def convert_polydata_to_image_data(poly, ref_im, reverse=True): """ Convert the vtk polydata to imagedata Args: poly: vtkPolyData ref_im: reference vtkImage to match the polydata with Returns: output: resulted vtkImageData """ from vtk.util.numpy_support import vtk_to_n...
21,917
def matplot(x, y, f, vmin=None, vmax=None, ticks=None, output='output.pdf', xlabel='X', \ ylabel='Y', diverge=False, cmap='viridis', **kwargs): """ Parameters ---------- f : 2D array array to be plotted. extent: list [xmin, xmax, ymin, ymax] Returns ------- Save a ...
21,918
def createNewClasses(df, sc, colLabel): """ Divide the data into classes Parameters ---------- df: Dataframe Spark Dataframe sc: SparkContext object SparkContext object colLabel: List Items that considered Label logs_dir: string Directory for...
21,919
def scan_usb(device_name=None): """ Scan for available USB devices :param device_name: The device name (MX6DQP, MX6SDL, ...) or USB device VID:PID value :rtype list """ if device_name is None: objs = [] devs = RawHid.enumerate() for cls in SDP_CLS: for dev in dev...
21,920
def start_bme280_sensor(args): """Main program function, parse arguments, read configuration, setup client, listen for messages""" global status_topic, read_loop i2c_address = bme280.I2C_ADDRESS_GND # 0x76, alt is 0x77 options = Options() if args.daemon: file_handle = open(args.log_f...
21,921
def _boolrelextrema( data, comparator, axis=0, order: tsutils.IntGreaterEqualToOne = 1, mode="clip" ): """Calculate the relative extrema of `data`. Relative extrema are calculated by finding locations where comparator(data[n],data[n+1:n+order+1]) = True. Parameters ---------- data: ndarray...
21,922
def parse_description(offer_markup): """ Searches for description if offer markup :param offer_markup: Body from offer page markup :type offer_markup: str :return: Description of offer :rtype: str """ html_parser = BeautifulSoup(offer_markup, "html.parser") return html_parser.find(id="t...
21,923
def return_args(): """Return a parser object.""" _parser = ArgumentParser(add_help=True, description=( "Translate msgid's from a POT file with Google Translate API")) _parser.add_argument('-f', '--file', action='store', required=True, help="Get the POT file name.") _pars...
21,924
def get_df_tau(plot_dict, gen_err): """ Return a dataframe of the kendall tau's coefficient for different methods """ # tau, p_value = compute_tau(result_dict[err], plot_dict['avg_clusters'], inverse=True) # taus, pvalues, names, inverses = [tau], [p_value], ['cc'], ['True'] taus, pvalues, names...
21,925
def traverse(graph, priorities): """Return a sequence of all the nodes in the graph by greedily choosing high 'priority' nodes before low 'priority' nodes.""" reachable = PriorityContainer() visited = {} # start by greedily choosing the highest-priority node current_node = max(priorities.items...
21,926
def build_dataset(dataset_name, set_name, root_path, transforms=None): """ :param dataset_name: the name of dataset :param root_path: data is usually located under the root path :param set_name: "train", "valid", "test" :param transforms: :return: """ if "cameo_half_year" in dataset_name...
21,927
def process_quote_data(): """ Write fetched quote data as a CSV. """ quote_data = api.get_quote_data(",".join(SYMBOLS)) field_names = list(quote_data[0].keys()) lib.write_csv(CSV_OUT_QUOTE_DATA, quote_data, field_names)
21,928
def remove_characters(text, characters_to_remove=None): """ Remove various auxiliary characters from a string. This function uses a hard-coded string of 'undesirable' characters (if no such string is provided), and removes them from the text provided. Parameters: ...
21,929
def changePrev ( v, pos, findPat, changePat, bodyFlag = 1 ): """ changePrev: use string.rfind() to change text in a Leo outline. v the vnode to start the search. pos the position within the body text of v to start the search. findPat the search string. changePat the replacement string. bodyFlag t...
21,930
def put_mint(update: Update, context: CallbackContext) -> int: """ Returns the token data to user """ session_uuid = context.user_data['session_uuid'] user = get_chat_info(update) creator_username = user['username'] # Start DB Session to get addr session = Session() sesh_exists = session.qu...
21,931
def handle_edge_event_3sides(evt, step, skel, queue, immediate): """Handle a collapse of a triangle with 3 sides collapsing. It does not matter whether the 3-triangle has wavefront edges or not. Important: The triangle vertices should collapse to 1 point. The following steps are performed: - stop ...
21,932
def craft_one_type(sess, model, X, Y, dataset, attack, batch_size): """ TODO :param sess: :param model: :param X: :param Y: :param dataset: :param attack: :param batch_size: :return: """ if attack == 'fgsm': # FGSM attack print('Crafting fgsm adversarial s...
21,933
def trait_colors(rows): """Make tags for HTML colorizing text.""" backgrounds = defaultdict(lambda: next(BACKGROUNDS)) for row in rows: for trait in row['traits']: key = trait['trait'] if key not in ('heading',): _ = backgrounds[key] return backgrounds
21,934
def test(): """Run the unit tests""" import unittest tests = unittest.TestLoader().discover("tests") unittest.TextTestRunner(verbosity=2).run(tests)
21,935
def main(): """ NAME foldtest_magic.py DESCRIPTION does a fold test (Tauxe, 2010) on data INPUT FORMAT pmag_specimens format file, er_samples.txt format file (for bedding) SYNTAX foldtest_magic.py [command line options] OPTIONS -h prints help message and q...
21,936
def webhook(): """ CI with GitHub & PythonAnywhere Author : Aadi Bajpai https://medium.com/@aadibajpai/deploying-to-pythonanywhere-via-github-6f967956e664 """ try: event = request.headers.get('X-GitHub-Event') # Get payload from GitHub webhook request payload = request.ge...
21,937
def regenerate_browse_image(dataset_directory): """ Regenerate the browse image for a given dataset path. (TODO: This doesn't regenerate package checksums yet. It's mostly useful for development.) :param dataset_directory: :return: """ dataset_metadata = serialise.read_dataset_metadata(dat...
21,938
def cli_parser() -> argparse.Namespace: """ Parser for the command line interface. """ fw_parser = argparse.ArgumentParser( fromfile_prefix_chars="@", description="FileWriter Starter" ) fw_parser.add_argument( "-f", "--filename", metavar="filename", type...
21,939
def pension_drawdown(months, rate, monthly_drawdown, pension_pot): """ Returns the balance left in the pension pot after drawing an income for the given nr of months """ return monthly_growth(months, rate, -monthly_drawdown, pension_pot)
21,940
def bytesToUInt(bytestring): """Unpack 4 byte string to unsigned integer, assuming big-endian byte order""" return _doConv(bytestring, ">", "I")
21,941
def safe_mkdirs(path): """ This makes new directories if needed. Args: path (str): The full path of the would be directory. """ if not os.path.exists(path): os.makedirs(path)
21,942
def fractal_se(p_x, p_y, img): """ if possible, place pixel's SE fractal on image """ if ( # S ((p_y + 1) < len(img) and img[p_y + 1][p_x] != "1") and # SW ((p_x - 1) >= 0 and img[p_y + 1][p_x - 1] != "1") and # E ((p_x + 1) < len(img) and img[p_y][p_x + 1] != "1"...
21,943
def use(*authenticator_classes): """ A decorator to attach one or more :class:`Authenticator`'s to the decorated class. Usage: from thorium import auth @auth.use(BasicAuth, CustomAuth) class MyEngine(Endpoint): ... OR @auth.use(BasicAuth) @auth.use...
21,944
def list_standard_models(): """Return a list of all the StandardCellType classes available for this simulator.""" standard_cell_types = [obj for obj in globals().values() if isinstance(obj, type) and issubclass(obj, standardmodels.StandardCellType)] for cell_class in standard_cell_types: try: ...
21,945
def test_distinct_multi_columns(schools): """Test getting distinct values for a multiple columns.""" boro_grade = distinct(schools, columns=['borough', 'grade']) assert len(boro_grade) == 37 assert boro_grade[('K', '09-12')] == 14 assert sum(v for v in boro_grade.values()) == 100
21,946
def AchievableTarget(segments,target,Speed): """ The function checks if the car can make the required curvature to reach the target, taking into account its speed Return [id, radius, direction} id = 1 -> achievable else id =0 direction = 1 -> right ...
21,947
def handle_generic_response(response): """ Handle generic response: output warning and suuggested next steps This is reserved for unhandled status codes. Output a snippet of the response text to aid the user with debugging. Parameters ---------- response: requests.Response The response...
21,948
def test_equals(): """ Verify that a parameter set and a covering array that contains a "don't care" value is correctly converted to a data frame, where the "don't care" value becomes Pandas' pd.NA value. """ p1 = Parameter("Colour", [RED, GREEN]) p2 = Parameter("Pet", [BIRD, CAT, DOG, F...
21,949
def read_silixa_files_routine_v4( filepathlist, timezone_netcdf='UTC', silent=False, load_in_memory='auto'): """ Internal routine that reads Silixa files. Use dtscalibration.read_silixa_files function instead. The silixa files are already timezone aware Parameters ...
21,950
def mutual_information(co_oc, oi, oj, n): """ :param co_oc: Number of co occurrences of the terms oi and oj in the corpus :param oi: Number of occurrences of the term oi in the corpus :param oj: Number of occurrences of the term oi in the corpus :param n: Total number of words in the corpus :ret...
21,951
def random(population: pd.DataFrame, num_parents_per_nationality: Dict[str, int]) -> pd.DataFrame: """Selects parents of next generation randomly Args: population (pd.DataFrame): Current population dataframe. num_parents_per_nationality (Dict[str, int]): ...
21,952
def interpolate_GLMdenoise_to_fsaverage_prior(freesurfer_sub, prf_props, save_stem, GLMdenoise_path=None, plot_class=0, plot_bootstrap=0, target_varea=1, interp_method='linear'): """interpolate a scanning session's GLMdenois...
21,953
def is_dark(color: str) -> bool: """ Whether the given color is dark of bright Taken from https://github.com/ozh/github-colors """ l = 0.2126 * int(color[0:2], 16) + 0.7152 * int(color[2:4], 16) + 0.0722 * int(color[4:6], 16) return False if l / 255 > 0.65 else True
21,954
def test_null_identifiers_go_to_the_right_case(multiple_identifier_target, stu, cases): """ If an identifying column can be null, then there is no way to associate it with a case unless there is another non-null identifying column. """ multiple_identifier_target.load_actual( [ {...
21,955
async def consume(queue: asyncio.Queue, es: AsyncElasticsearch) -> NoReturn: """Consume and run a job from the shared queue.""" while True: # Wait for a job from the producers job = await queue.get() logging.info(f"Starting the '{job.name}' job") # Execute the job functi...
21,956
def get_date_input_examples(FieldClass) -> list: """ Generate examples for a valid input value. :param FieldClass: InputField :return: List of input examples. """ r = [] for f in FieldClass.input_formats: now = datetime.now() r.append(now.strftime(f)) return r
21,957
def fail(value, context_info=None, *, src_exception=None, err_condition=None): """Wrapper to raise (and log) DAVError.""" if isinstance(value, Exception): e = as_DAVError(value) else: e = DAVError( value, context_info, src_exception=src_exception, ...
21,958
def sve_logistic(): """SVE of the logistic kernel for Lambda = 42""" print("Precomputing SVEs for logistic kernel ...") return { 10: sparse_ir.compute_sve(sparse_ir.LogisticKernel(10)), 42: sparse_ir.compute_sve(sparse_ir.LogisticKernel(42)), 10_000: sparse_ir.compute_sve(spa...
21,959
def post_team_iteration(id, team, organization=None, project=None, detect=None): # pylint: disable=redefined-builtin """Add iteration to a team. :param id: Identifier of the iteration. :type: str :param team: Name or ID of the team. :type: str """ organization, project = resolve_instance_an...
21,960
def JoinTypes(types): """Combine a list of types into a union type, if needed. Leaves singular return values alone, or wraps a UnionType around them if there are multiple ones, or if there are no elements in the list (or only NothingType) return NothingType. Arguments: types: A list of types. This list ...
21,961
def main(): """Populate MMap datasets."""
21,962
def scale_bar_and_direction(ax,arrow_location=(0.86,0.08),scalebar_location=(0.88,0.05),scalebar_distance=25,zorder=20): """Draw a scale bar and direction arrow Parameters ---------- ax : axes length : int length of the scalebar in km. ax_crs: projection system of the axis to be...
21,963
def calc_nominal_strike(traces: np.ndarray): """ Gets the start and ending trace of the fault and ensures order for largest lon value first Parameters ---------- traces: np.ndarray Array of traces of points across a fault with the format [[lon, lat, depth],...] """ # Extract just la...
21,964
def data_split(config_path: Text) -> None: """Split dataset into train/test. Args: config_path {Text}: path to config """ config = load_config(config_path) dataset = pd.read_csv(config.featurize.features_path) train_dataset, test_dataset = train_test_split( dataset, test...
21,965
def make_tree_plot(df_summary, param_names=None, info_path=InfoPath(), tree_params: TreePlotParams = TreePlotParams(), summary_params=SummaryParams()): """ Make tree plot of parameters. """ info_path = InfoPath(**info_path.__dict__) tree_plot_data = extract_tre...
21,966
def create_category_freq_plots(freq_dict, iri2label_dict, args={'subonto':'all'}, categories=['gender', 'sexual orientation', 'race', 'disability', 'religion']): """ Create heatmap of annotation categories frequencies of (sub)ontology: subannot - all_ent For each category class, c...
21,967
def merge_options(custom_options, **default_options): """ Utility function to merge some default options with a dictionary of custom_options. Example: custom_options = dict(a=5, b=3) merge_options(custom_options, a=1, c=4) --> results in {a: 5, b: 3, c: 4} """ merged_option...
21,968
def test_exception_negative_count(marker_trackerstore: TrackerStore): """Tests an exception is thrown when an invalid count is given.""" with pytest.raises(RasaException): MarkerTrackerLoader(marker_trackerstore, STRATEGY_SAMPLE_N, -1)
21,969
def build_wall(game: Board, player: Player) -> float: """ Encourage the player to go the middle row and column of the board to increase the chances of a partition in the later game """ position = game.get_player_location(player) blanks = game.get_blank_spaces() blank_vertical = [loc for loc...
21,970
def get_menu_from_hzu_navigation(): """ 获取惠州学院官网的导航栏的 HTML 文本。 :return: 一个 ul 标签文本 """ try: html = urlopen("https://www.hzu.edu.cn/") except HTTPError as e: print(e) print('The page is not exist or have a error in getting page.') return None except URLError ...
21,971
def test_find_by_id(session, client, jwt): """Assert that user find by id is working as expected.""" user = User.find_by_id(1) if not user: user2 = User.create_from_jwt_token(TEST_TOKEN, 'PS12345') user = User.find_by_id(user2.id) assert user assert user.id assert user.username ...
21,972
def calc_user_withdraw_fee(user_id, amount): """手续费策略""" withdraw_logs = dba.query_user_withdraw_logs(user_id, api_x.utils.times.utctoday()) if len(withdraw_logs) > 0: return Decimal('2.00') return Decimal('0.00')
21,973
def test_exception_handling_captures_calctypeerror(err_class, capfd): """Test exception handling captures input. Args: capfd: pytest stdout/stderr capture data """ from app.cli import _exception_handler import app.calculator as calc Error = getattr(calc, err_class) def f(n1, n2):...
21,974
def get_last_row(dbconn, tablename, n=1, uuid=None): """ Returns the last `n` rows in the table """ return fetch(dbconn, tablename, n, uuid, end=True)
21,975
def checkAtomicElementAxes(project): """Check Atomic Element axes: - Are all defined axes used? - Are all used axes defined? - Are all axis values within the defined range? """ glyphSet = project.deepComponentGlyphSet compoGlyphSet = project.atomicElementGlyphSet yield from _checkCompone...
21,976
def get_start(period, reference_date: Optional[FlexDate] = None, strfdate="%Y-%m-%d") -> FlexDate: """ Returns the first day of the given period for the reference_date. Period can be one of the following: {'year', 'quarter', 'month', 'week'} If reference_date is instance of str, returns a string. If...
21,977
def prepare_lc_df(star_index, frame_info, magmatch, magx): """Prepare cleaned light curve data Add mag, mag_err, magx, and magx_err to info Remove nan values or too bright values in magx Args: star_index (int): index of the star frame_info (DataFrame): info data magmatch (array...
21,978
def _filter_nones(centers_list): """ Filters out `None` from input list Parameters ---------- centers_list : list List potentially containing `None` elements Returns ------- new_list : list List without any `None` elements """ return [c for c in centers_list if...
21,979
def test_bbox_deltas_2d(): """ Test that `deltas` property returns the correct value for an example 1D region. """ minp = [5, 2] maxp = [7, 83] expected = [2, 81] numpy.testing.assert_allclose(AxisAlignedBoundingBox(minp, maxp).deltas, expected)
21,980
def pseudo_shuffle_mat(ref_var, mat, replace=False, debug=False): """ Shuffles the data but keeps the time information (i.e. shuffles the velocity while keeping the time information intact) :param np.array ref_var: shape: n_accelerations :param np.array mat: shape: (n_trials, n_accelerations) :...
21,981
def CleanupDjangoSettings(): """Removes incompatible entries from the django settings module.""" # Ensure this module is installed as an application. apps = getattr(settings, "INSTALLED_APPS", ()) found = False for app in apps: if app.endswith("appengine_django"): found = True break if not ...
21,982
def exec_in_subprocess(func, *args, poll_interval=0.01, timeout=None, **kwargs): """ Execute a function in a fork Args: func (:obj:`types.FunctionType`): function * args (:obj:`list`): list of positional arguments for the function poll_interval (:obj:`float`, optional): interval to poll...
21,983
def nroot_real_matplotlib(n, res=101): """ Plot the Riemann surface for the real part of the n'th root function. """ x = np.linspace(-1, 1, res) X, Y = np.meshgrid(x, x, copy=False) Z = X + 1.0j * Y r = np.absolute(Z) theta = np.angle(Z) rroot = r**(1./n) theta /= n real = rroot ...
21,984
def tour_de_jeu(minesweeper): """ Function called at each turn of play. Asks the player the coordinates of a cell and the type of movement that he wants to do. :param minesweeper: minesweeper game :minesweeper type: Minesweeper :return: None :CU: None """ r=input('Your play x,y,C (C=(R)e...
21,985
def hold_numpy_printoptions(**kwargs): """ Temporarily set the numpy print options. See https://docs.scipy.org/doc/numpy/reference/generated/numpy.set_printoptions.html :param kwargs: Print options (see link) """ opts = np.get_printoptions() np.set_printoptions(**kwargs) yield np.set...
21,986
def format_code(c, check=False): """Format code""" BLACK_CMD = ( f"black {apply_paths(CODE, TESTS, ADDITIONAL)} " f"--line-length {LINE_LENGTH}" ) if check: result = c.run(BLACK_CMD + " --check") if result.return_code != 0: exit(1) else: c.run(BLACK_CMD)
21,987
def get_cv_score_table(clf): """ Get a table (DataFrame) of CV parameters and scores for each combination. :param clf: Cross-validation object (GridSearchCV) :return: """ # Create data frame df = pd.DataFrame(list(clf.cv_results_['params'])) # Add test scores df['rank'] = clf.cv_r...
21,988
def test_environment_from_manifest(): """Test scenarios for loading manifest files.""" # load an invalid manifest (bad schema) manifest_path = get_resource(os.path.join("manifests", "test.yaml"), False) env = from_manifest(manifest_path) assert not env.get_valid() # make sure we can't double-l...
21,989
def message(self, update, context): """Receive message, generate response, and send it back to the user.""" max_turns_history = self.chatbot_params.get('max_turns_history', 2) giphy_prob = self.chatbot_params.get('giphy_prob', 0.1) giphy_max_words = self.chatbot_params.get('giphy_max_words', 10) i...
21,990
async def test_setup_depose_user(hass): """Test set up and despose user.""" notify_auth_module = await auth_mfa_module_from_config(hass, {"type": "notify"}) await notify_auth_module.async_setup_user("test-user", {}) assert len(notify_auth_module._user_settings) == 1 await notify_auth_module.async_se...
21,991
def test_extra_pol_setup(): """Test reading in an ms file with extra polarization setups (not used in data).""" uvobj = UVData() testfile = os.path.join( DATA_PATH, "X5707_1spw_1scan_10chan_1time_1bl_noatm.ms.tar.gz" ) import tarfile with tarfile.open(testfile) as tf: new_filen...
21,992
def show_image_matrix(images, titles=None, suptitle=None): """Displays a matrix of images in matplotlib.""" rows = len(images) columns = len(images[0]) fig = plt.figure(figsize=(columns + 1, rows + 1)) # Avoid large blank margins fig.set_dpi(images[0][0].shape[0]) # Preserve original image size ...
21,993
def model_handle_check(model_type): """ Checks for the model_type and model_handle on the api function, model_type is a argument to this decorator, it steals model_handle and checks if it is present in the MODEL_REGISTER the api must have model_handle in it Args: model_type: the "type"...
21,994
def train_model_mixed_data(type_tweet, split_index, custom_tweet_data = pd.Series([]), stop_words = "english"): """ Fits the data on a Bayes model. Modified train_model() with custom splitting of data. :param type_tweet: :param split_index: :param custom_tweet_data: if provided, this is used instea...
21,995
def _fit_curves(ns, ts): """Fit different functional forms of curves to the times. Parameters: ns: the value of n for each invocation ts: the measured run time, as a (len(ns), reps) shape array Returns: scores: normalised scores for each function coeffs: coefficien...
21,996
def isolate_integers(string): """Isolate positive integers from a string, returns as a list of integers.""" return [int(s) for s in string.split() if s.isdigit()]
21,997
def start_thread(func): """Start a thread.""" thread = threading.Thread(target=func) thread.start()
21,998
def extractAFlappyTeddyBird(item): """ # A Flappy Teddy Bird """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or 'preview' in item['title'].lower(): return None if 'The Black Knight who was stronger than even the Hero' in item['title']: return buildReleaseMess...
21,999