content
stringlengths
22
815k
id
int64
0
4.91M
def test_verify_wrong_password(): """ with the credentials file try to verify wrong password combination. """ with app.app_context(): assert auth.verify_pw("winnie", "pooh") == False
73,900
def emit_metrics(metric: dict): """ Generate dicts to pass to metric emitter plugin """ if sr_plugins.exists("metrics"): metric_emitter = sr_plugins.load("metrics") metric_emitter.main(metric)
73,901
def parse_report_filter_values(request, reports): """Given a dictionary of GET query parameters, return a dictionary mapping report names to a dictionary of filter values. Report filter parameters contain a | in the name. For example, request.GET might be { "crash_report|operating_...
73,902
def generate_jwt(payload): """Encode given payload to jwt, return encoded jwt, private key, public key Args: payload (dict): the payload to be encoded in the jwt Returns: Encoded jwt(json), private key (str) used to encode the payload, public key(str) used to encode the payload """ ...
73,903
def advantage_returns(rewards, values, gamma, lam): """Compute the advantage and returns from rewards and values.""" # GAE-Lambda advantage calculation. deltas = rewards[:-1] + gamma * values[1:] - values[:-1] advantages = discount(deltas, gamma * lam) # Compute rewards-to-go (targets for the value ...
73,904
def parse_cases(raw_data_file, source_id, source_url): """ Parses G.h-format case data from raw API data. Caveats: - Assuming the date confirmed is the date of diagnosis (Fecha diagnostico) rather than Fecha de notificación (generally several days earlier). When date of diagnosis, using date report...
73,905
def test_gamma_delta_manually_step_by_step(): """ Test that the user can go through the automatic steps, manually, one-by-one for well formatted gamma delta data. """ df = pd.read_csv("sant.csv") tr = TCRrep( cell_df = df, organism = "human", chains = ['gamma', "delta"], i...
73,906
def iter_extend(iterable, length, obj=None): """Ensure that iterable is the specified length by extending with obj""" return itertools.islice(itertools.chain(iterable, itertools.repeat(obj)), length)
73,907
def _ldap_search(cnx, filter_str, attributes, non_unique='raise'): """Helper function to perform the actual LDAP search @param cnx: The LDAP connection object @param filter_str: The LDAP filter string @param attributes: The LDAP attributes to fetch. This *must* include self.ldap_username @param non...
73,908
def read_yaml(filename:str) -> dict: """ Return dic from yaml. Args: filename: Output file name. Returns: dict: Dictionary object. """ with open(filename, 'r') as f: dic = yaml.load(f, Loader=Loader) return dic
73,909
def download(id): """Serve the pickle file""" passwd = hashlib.sha256(ID.encode()).hexdigest() if id == passwd: return send_file("model.pickle", as_attachment=True)
73,910
def pip_install(pkg_str=" pandas "): """ try: import pandas as pd except ImportError: finally: import pandas as pd """ import subprocess, sys clist = [sys.executable, "-m", "pip", "install", ] + pkg_str.split(" ") log("Installing", pkg_str) subproc...
73,911
def get_common_prefix(string_1, string_2): """Find the largest common prefix of two strings. Args: string_1: A string. string_2: Another string. Returns: The longest common prefix of string_1 and string_2. """ # If either string_1 or string_2 is the empty string, the common ...
73,912
def main(): """ Purpose: Start codex_st Args: N/A Returns: N/A """ st.title("Codex") st.header("Codex allows you to gain insights from your data") get_codex_keyspaces()
73,913
def get_user_limit(session: Session, group: Group, modifier: int) -> bool: """ Comparing number of free seats and number of users in group and subgroups with parent groups. :return: False if space is exhausted. """ max_seats = get_num_seats(session, group) num_users = get_num_users(session,...
73,914
def test_get_annotations_no_data( pandas_series, coordination_args, monkeypatch ): """Test coordination of annotation retrieval when no data retrieved for a given protein.""" def mock_get_anno(*args, **kwargs): protein_data = [] return protein_data monkeypatch.setattr(get_genbank_annot...
73,915
def AddDeviceTest() -> bool: """Test of adding Devices to a DeviceGraph.""" t = test('AddDeviceTest') graph = DeviceGraph() ltd = LibraryTestDevice('ltd') sub1 = LibraryTestDevice('sub1') sub2 = LibraryTestDevice('sub2') sub11 = LibraryTestDevice('sub11') sub1.add_submodule(sub11, 'slot...
73,916
def create_half_val_test_imagesets(canteen, val_content, test_content, imageset): """create_train_and_val_imagesets create train.txt and val.txt for canteen :param canteen: :param train_content: :param val_content: """ print("------processing {}-----------".format(canteen)) root_path = ...
73,917
def get_name(scoring): """Get name of score. """ if not isinstance(scoring, str): scoring = get_scorer(scoring)._score_func.__name__.replace('_score', '') return scoring.replace('neg_', '').replace('maximum_', 'max_')
73,918
def login_with_token(refresh_token): """ Authenticate using an existing token. """ # Get an access token and a new refresh token. auth = _update_auth(refresh_token) url = get_registry_url() contents = _load_auth() contents[url] = auth _save_auth(contents) clear_session() #...
73,919
def community_portal_policies_page_data(): """ This function pulls and returns all data required for the community portal stories page and returns a json of this information """ return json_loader('./database/raw_data/portal/policiesPageData.json')
73,920
def test_missing_config(): """Test error string is formatted correctly""" error = MissingEnvVar("client_id") assert str(error) == "Missing client_id environment variable"
73,921
def retrieve_redcap_events(url, token, max_time=30): """Read the list of events from the REDCap instance using the API""" data = redcap_api_call(url, token, content='event', fields={}, max_time=max_time) # print("events: {}".format(data)) return data
73,922
def global_to_local_space( points: torch.Tensor, cam_pose: torch.Tensor, device: Optional[torch.device] = None, _validate_args: bool = True ) -> torch.Tensor: """Transform points from global space to local space Args: points (torch.tensor): points in shape (b, ..., 3), torch.float32 cam_pose (torch...
73,923
def quantization_model_or_class_factory(args, *, model=None, cls=None): """Return either converted model for quantization or a quantized version of the class passed""" if model is not None and cls is not None: raise AttributeError( "Pass either model or class to be converted for quantization...
73,924
def fps_label(fps, image_np): """ Function to draw a label indicating the FPS value in the top corner of an image. """ cv2.putText(image_np, fps, (20, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (77, 255, 9), 2)
73,925
def get_user(user_id): """Get user by ID""" app.logger.info( 'Starting show user id: {} of request: {}'.format(user_id, g.request_id) ) response = user_schema.dump(UserService().find_or_404(user_id)) app.logger.info( 'Response of show user id: {} with response: {} of request: {}'.f...
73,926
def test_invalid_timestamp(): """Test that a valid datetime returns the timestamp.""" with pytest.raises(validation.vol.Invalid): validation.timestamp("test")
73,927
def h2o_H2OFrame_dim(): """ Python API test: h2o.frame.H2OFrame.drop(index, axis=1) copied from pyunit_drop.py """ pros = h2o.import_file(pyunit_utils.locate("smalldata/prostate/prostate.csv")) nc = pros.ncol nr = pros.nrow h2oframe1 = pros.drop([pros.names[0]]) assert h2oframe1.di...
73,928
def check_type_force_float(x, name): """ If an int is passed, convert it to a float. If some other type is passed, raise an exception. """ if type(x) is int: return float(x) elif type(x) is not float and type(x) is not numpy.float64: raise TypeError("%r should be a float" % (name...
73,929
def platform2str(platform: str) -> str: """ get full platform name """ if platform == "amd": return "AMD Tahiti 7970" elif platform == "nvidia": return "NVIDIA GTX 970" else: raise LookupError
73,930
def pdf_single_grid(request: HttpRequest, calendar_id: int): """A PDF grid from start date to end date with a given style and size""" cal = get_object_or_404(models.Calendar, pk=calendar_id) try: style_index = int(request.GET.get('style_index', 0)) size_index = int(request.GET.get('layout_...
73,931
def obtain_api_credentials(s3_client): """ Creates HTTP headers credentialed for access to the Global.health Source API. """ try: fd, local_creds_file_name = tempfile.mkstemp() with os.fdopen(fd) as _: logger.info( "Retrieving service account credentials from ...
73,932
def enable_tpoint_group(client, name): """Enable trace on a specific tpoint group. Args: name: trace group name we want to enable in tpoint_group_mask. (for example "bdev"). """ params = {'name': name} return client.call('enable_tpoint_group', params)
73,933
def tags_for_talks(conference=None, status=None): """ Return the used tags by talks, filtered by conferences and state of the talk """ talks = models.Talk.objects.all().values('id') if conference: talks = talks.filter(conference=conference) if status: talks = talks.filter(sta...
73,934
async def setup_gateway(hass, data): """Load the deCONZ switch platform.""" from pydeconz import DeconzSession loop = Mock() session = Mock() config_entry = config_entries.ConfigEntry( 1, deconz.DOMAIN, 'Mock Title', ENTRY_CONFIG, 'test', config_entries.CONN_CLASS_LOCAL_PUSH) ga...
73,935
def dump(*, obj: Any, file: Union[BinaryIO, TextIO]) -> None: """Dump a Python object to a file handle.""" cloudpickle.dump( obj, file=file, protocol=_PICKLE_PROTOCOL_VERSION, )
73,936
def ldl_fft(G): """Compute the LDL decomposition of G. Args: G: a Gram matrix Format: FFT Corresponds to algorithm 8 (LDL) of Falcon's documentation. """ deg = len(G[0][0]) dim = len(G) L = [[[0 for k in range(deg)] for j in range(dim)] for i in range(dim)] D = [[[0 for k ...
73,937
def get_time_step_data(data_in, time_step): """ Sparses data file for time steps specified by user. Parameters ---------- data_in : Density Data to be condensed into time steps time_step : float Time steps requested. Returns ------- data_out : Density Data in sp...
73,938
def handle_command(command, event): """ Executes bot command if the command is known """ # Finds and executes the given command, filling in response for cmd, callback in command_mapping.items(): if command.lower().startswith(cmd): # command cleanup command = command.r...
73,939
def run_default_griduniverse(): """ Run a random agent on the default griduniverse. This piece of code shows the main interface to the environment. This runs in ascii format """ print('\n' + '*' * 20 + 'Starting to run random agent on default GridUniverse' + '*' * 20 + '\n') env = GridUniverseE...
73,940
def glorot_weight_zero_bias(model): """ Initalize parameters of all modules by initializing weights with glorot uniform/xavier initialization, and setting biases to zero. Weights from batch norm layers are set to 1. Taken from: https://github.com/robintibor/braindecode/blob/master/braindecode/t...
73,941
def select_from_context(context: TreeContext, criterion: CriteriaType, reverse: bool=False): """Yields all nodes from context which fulfill the criterion.""" return select_from_context_if(context, create_match_function(criterion), reverse)
73,942
def combat_batch_correction(data, batch_col, index_cols): """ This function corrects processed data for batch effects. For more information visit: https://pypi.org/project/pycombat/ :param data: pandas dataframe with samples as rows and protein identifiers as columns. :param batch_col: column with the b...
73,943
def test_series_in_command(capfd): """ A separate command is generated for each series """ run_command("- echo test{{A,B}}") out, err = capfd.readouterr() assert "testA" in out assert "testB" in out
73,944
def test_perimeter_corners(): """Test the perimeter corners.""" y = [0, 1, 3, 0, 1, 3, 0, 1, 3] x = [3, 3, 3, 4, 4, 4, 6, 6, 6] graph = DualStructuredQuadGraph((y, x), shape=(3, 3)) assert_array_equal(graph.perimeter_corners, [1, 3, 2, 0])
73,945
def wusatowski_friction_coefficient(roll_pass): """Gets the Wusatowski spreading model friction coefficient f."""
73,946
def lsr_pwave_size(df, istate, stat='amp2', plotMode='0', mouse_avg='mouse', nbins=12): """ Compare mean amplitudes/half-widths of spontaneous and laser-triggered P-waves @Params df - dataframe containing the amplitude and half-width of each spontaneous and laser-triggered P-wave (output of ge...
73,947
def keyfunc(line): """Return the key from a TAB-delimited key-value pair.""" return line.partition("\t")[0]
73,948
def calculate_average_face_encoding( face_encodings: List[List[np.ndarray]], ) -> Optional[np.ndarray]: """ Calculates the average face encodings with numpy.mean() method. :param face_encodings: List of image face encodings """ if not face_encodings: return None average_face_encodin...
73,949
def make_error_extraction_tests(get_messages): """ Create a test case class for testing extraction of fields from exceptions. @param get_messages: Callable that takes an exception instance, returns all message dictionaries generated by logging it. @return: ``TestCase`` subclass. """ c...
73,950
def lambda_handler(event, context): """ Lambda Handler (webhook via api gateway) """ update = telebot.types.Update.de_json(event["body"]) bot.process_new_updates([update]) return { "body": "ok", "statusCode": 200, "headers": {"Content-Type": "application/json"}, }
73,951
def html_wrap(html_string): """Add an html-head-body wrapper around an html string.""" html_prefix="""<html> <head> <title>HTML CSS TESTS</title> <link rel="stylesheet" type="text/css" href="tests/manual html-css tests/html-css.css"> </head> <body>""" html_pos...
73,952
def onpolicy_trainer(policy, train_collector, test_collector, max_epoch, step_per_epoch, collect_per_step, repeat_per_collect, episode_per_test, batch_s...
73,953
def test_write_geotiff_time_index_deprecated(): """The `time_index` parameter to `write_geotiff()` was a poorly thought out addition and is now deprecated.""" with pytest.raises(ValueError): write_geotiff("", None, time_index=1)
73,954
def reindex_las_index_inplace(las): """Reindex a LAS file so that any irregularities in the index interval are smoothed out. Args: las (lasio.LASFile): input las. Returns nothing. Changes are made in place. """ steps = las.index[1:] - las.index[:-1] unique_steps, s...
73,955
def split(ary, n): """Given an array, and an integer, split the array into n parts""" result = [] for i in range(0, len(ary), n): result.append(ary[i: i + n]) return result
73,956
def fK(dO): """run automatic layout on entire node graph of the group""" dO.begin() fL() dO.end()
73,957
def test_mongo_access(host): """Check if MongoDB is available on port 27017.""" addr = host.addr('localhost') assert addr.port(27017).is_reachable
73,958
def default_to_test(app: Application): """Transfer Data From Default To Test""" import textwrap temp_dir = tempfile.mkdtemp() try: # Convertion Contexts cvt_ctxs = [ AttrDict( { "file_name": "db.sql", "src_db": "bb2_de...
73,959
def get_blog_name(url: str) -> str: """get the name of the blog""" path = urlparse(url).path if path.endswith("/"): return path.split("/")[-2] + ".md" else: return path.split("/")[-1] + ".md"
73,960
def fget_preds(subdict, limit_date=False, lcompdate=None, ucompdate=None): """ stack predictions over ensemble runs get predictions and targets from runs shape: (90, 20729, 3) (n_ensemble_runs, n_windows, H) limit_date to crop for comparison with cls, esa etc. """ # shorter lookbacks have m...
73,961
def compute_g(maze: Maze, start_pos: tuple): """ Compute g(n) from starting position for the given maze to all positions :param maze: Maze :param start_pos: This is the starting position of the robot from where it will start applying A* search :return: None are we are updating in the same maze objec...
73,962
def gen_popden_feat(input_raw="./data/raw/popden/", output_folder="./data/features/popden", handicaps=None, remove_over=False): """This function process the raw CSV file with all the world's population density and creates the output CSV file with the class...
73,963
def entity_is_available(hass: HomeAssistant, entity: str): """evaluate whether an entity is ready for targeting""" state = hass.states.get(entity) if state is None: return False elif state.state == STATE_UNAVAILABLE: return False elif state.state != STATE_UNKNOWN: return True...
73,964
def preview_model(request, content_app, content_class, content_id, preview_mode='default', load_dynamic_element=False): """ preview_model """ model_class = apps.get_model(content_app, content_class) form_class = modelform_factory( model_class, fields=[field.name for field in model_...
73,965
def is_valid_word_array(words_to_check): """ --------------------------------------------------------------------- DESCRIPTION Checks if the words in the word (string) array are part of the dictionary. --------------------------------------------------------------------- PARAMETERS words...
73,966
def setup() -> Generator[Any, None, None]: """Setup debugging configuration. This method also clears the `Database` after each test run. It is automatically enabled for all tests in this file. Yields: Access to the local fixture variables. """ config.load(get_resource("debug.py")) ...
73,967
def _polydetrend_get_trend(da, *, dim, degree, preserve_mean, kind): """Polydetrend, atomic func on 1 group.""" if len(dim) > 1: da = da.mean(dim[1:]) dim = dim[0] pfc = da.polyfit(dim=dim, deg=degree) trend = xr.polyval(coord=da[dim], coeffs=pfc.polyfit_coefficients) if preserve_mean: ...
73,968
def image_function(f='sin(x)*cos(y)', xmin=-1, xmax=1, ymin=-1, ymax=1, xsteps=100, ysteps=100, p="x,y", g=None, **kwargs): """ Plots a 2-d function over the specified range f takes two inputs and returns one value. Can also be a string function such as sin...
73,969
def retrieve_images(source, path): """Generate the filenames of one or multiple disk images as they are retrieved from _source_. Source may be one of several types of source, so we dispatch to an appropriate function to deal with it: - a git url to a repo containing disk images - a normal http...
73,970
def actigraph_acc(dirpath): """ Function to take all Actigraph accelerometry data from a directory and format those data with Linux time-series index columns and x, y, z value columns Parameters ---------- dirpath : string path to E4 outputs Returns ------- acc_data : p...
73,971
def fx_index(fastx, output, sort_by): """ Create read index from information in read headers (Guppy) """ sim = SketchySimulator(fastx=fastx) sim.get_run_index(fout=output, sort_by=sort_by)
73,972
def manager(manager_maker): """ return an uninitialized AccountManager instance. """ return manager_maker(addid=False)
73,973
def tcp_to_udp_data(d): """ Trim TCP packet to send it over UDP. :param d: (bytes) TCP DNS response :return: (bytes) UDP ready DNS response """ d = d[2:] return d
73,974
def coda_duration( tr: obspy.Trace, noise: float, ptype: str, cfg: types.ModuleType = config ) -> Tuple[float, float]: """Measure duration and associate quality control Args: tr: time series noise: noise level ptype: plot type cfg: configuration file ...
73,975
def seq_alignment_mask(base_dir, dada2_filtered_rep_seqs, cpu_count=None): """ :param base_dir: Main working directory filepath :param dada2_filtered_rep_seqs: DADA2 filtered representative sequence object :param cpu_count: Number of CPUs to use for analysis :return: QIIME2 sequence mask, sequence a...
73,976
async def list(command, fps): """Lists available pollers.""" poller_status = [] for name in fps.pollers.names: poller_status.append(name + ("*" if fps.pollers[name].running else "")) command.finish(text=",".join(poller_status))
73,977
def list_smc_files(path): """Lists all SMC files in a directory""" files = util.list_files(path, ".smc.gz") files.sort(key=get_smc_sample_iter) return files
73,978
def encMethodSave5(file, picture): """Save an picture to a file.""" file.writeBytes(bit32.rshift(picture[0], 8), bit32.band(picture[1], 0xff)) for i in range(2, len(picture), 4): file.writeBytes(color.to8Bit(picture[i]), color.to8Bit(picture[i+1]), math.floor(picture[i + 2] ...
73,979
def get_settings(lang, mode): """Get the makefile settings.""" schema_json = make_schema(lang, mode) error = None try: settings = json.loads(request.values.get('settings', '{}')) except: log.exception("Error in json parsing the settings variable") error = escape(make_trace()...
73,980
def plot_grid_detection(images, yolo_outputs, model_size, conf_thresh, fig_location=None): """ Draws images and highlights grid boxes where the model is quite certain that it overlaps an object (the grid box is reponsible for that object prediction). Parameters ---------- images : TYPE ...
73,981
def set_trace(): """ invoke PDB set_trace debugging, dropping any IO capturing. """
73,982
def vectorFactorization(vec: np.ndarray) -> typing.Tuple[np.ndarray, np.ndarray]: """I have probably reinvented a wheel. I have searched the Internet and haven't found this kind of factorization. Factors a vector vec into the product of an "upper-triangular-like" (mostly upper triangular, but with holes and elements ...
73,983
def random_funfact(): """Returns random funfact or None.""" if FunFact.objects.published().count(): return FunFact.objects.random() return None
73,984
def combine_results(results_list): """ Given different metrics based on the result lists provided. Inputs: results_list: dictionary containing the lists of all the results Returns: results_overall: dictionary containing the lists of all the results now with additional perfo...
73,985
def chmod_s(updatedone_documents): """Function for updating filesystem metadata for the slave namenodes after chgrp command Parameters ---------- updatedone_documents --> list(list), the list of the conditions for updating MongoDB documents, the values which have to be updated and the collection in...
73,986
def files_permission_factory(obj, action=None): """Permission for files are always based on the type of record. Record bucket: Read access only with open access. Deposit bucket: Read/update with restricted access. """ # Extract bucket id bucket_id = None if isinstance(obj, Bucket): ...
73,987
def _generate_perfect_bst(height: int) -> Optional[Node]: """Generate a perfect BST (binary search tree) and return its root. :param height: Height of the BST. :type height: int :return: Root node of the BST. :rtype: binarytree.Node | None """ max_node_count = 2 ** (height + 1) - 1 node...
73,988
def test_simulated_module_annotation_predict(simulated_ann_predict_vcf, simulated_ann_predict_csv): """Test the predictions annotation of the simulated VCF file using the imported module.""" annotate(SIMULATED_VCF, TEST_VCF, predict=True, csv=True) with open(...
73,989
def conference_title(): """Get conference title from environ variable""" return os.environ.get('CONFERENCE_TITLE', None)
73,990
def create_plotting_parameters_for_normal_distribution(mean, variance, num_std_dev_to_plot=3): """Create parameters to easily plot a normal distribution Arguments: mean {float} -- Mean of the normal distribution variance {float} -- Variance of the normal distribution """ sigma = sqrt(v...
73,991
def create_skelgraph(R: nx.Graph, H: nx.DiGraph) -> nx.Graph: """Create a "skelgraph" from a bdc world `H` and its reeb graph, `R`. A skelgraph is a graph of the straight skeletons of each cell of a world `H`, joined by the midpoints of each cell wall on `H`. Traversing the skelgraph of `H` means visit...
73,992
def apply_bounds(grid, lVec): """ Assumes periodicity and restricts grid positions to a box in x- and y-direction. """ dx = lVec[1,0]-lVec[0,0] grid[0][grid[0] >= lVec[1,0]] -= dx grid[0][grid[0] < lVec[0,0]] += dx dy = lVec[2,1]-lVec[0,1] grid[1][grid[1] >= lVec[2,1]] -= dy gri...
73,993
def is_ericsson_2g_supported(): """ Check if Ericsson 2G is supported :return: string parse_and_import_ericsson_2g | ericsson_2g_not_supported """ if bts_utils.is_vendor_and_tech_supported(1,1) is True : return 'ericsson_2g_supported' else: return 'ericsson_2g_not_supported'
73,994
def check_env_vars(env_vars): """Checks if the env variables are set as required to run the test. Returns: True if all the env variables are set as required, otherwise False. """ if not env_vars: return True for key in env_vars: if env.get_env(key) != env_vars.get(key): return False retu...
73,995
def http_check_root(session: requests.Session): """HTTP GET / returns 200 or 404""" res = session.get(URL_PREFIX + "/") assert res.status_code in (200, 404), (res, res.text)
73,996
def custom_sobel(shape, axis): """ shape must be odd: eg. (5,5) axis is the direction, with 0 to positive x and 1 to positive y """ k = np.zeros(shape) p = [(j,i) for j in range(shape[0]) for i in range(shape[1]) if not (i == (shape[1] -1)/2. and j == (shape[0] -1)/2.)] ...
73,997
def _check(edges): """Check consistency""" res = True for src, dsts in edges.items(): for dst in dsts: if dst not in edges: print('Warning: edges[%d] contains %d, which is not in edges[]' % (src, dst)) res = False return res
73,998
def test_travis(options_baked): """The generated .travis.yml file should pass a sanity check.""" travis_text = Path(".travis.yml").read_text() assert 'pip install -r requirements/travis.txt' in travis_text
73,999