content
stringlengths
22
815k
id
int64
0
4.91M
def delistify(a, b=None): """ If a single element list, extract the element as an object, otherwise leave as it is. Examples -------- >>> delistify('string') 'string' >>> delistify(['string']) 'string' >>> delistify(['string', 'other']) ['string', 'other'] >>> delisti...
69,800
def test_symmetrical(matrix_size): """Test if output symmetry is respected when the inputs are symmetric. """ inputA = np.random.random((matrix_size, matrix_size)) inputB = np.random.random((matrix_size, matrix_size)) outputA, outputB, _ = serp.serpentin_iteration( inputA, inputB, triangular...
69,801
def upload_parts( mcg_obj, awscli_pod, bucketname, object_key, body_path, upload_id, uploaded_parts ): """ Uploads individual parts to a bucket Args: mcg_obj (obj): An MCG object containing the MCG S3 connection credentials awscli_pod (pod): A pod running the AWSCLI tools bucket...
69,802
def get_available_datasets(m1: str, m2: str) -> List[str]: """Calculate what datasets are available between m1 and m2 Args: m1 (str): Name (or path) to pretrained HF model 1 m2 (str): Name (or path) to pretrained HF model 2 Returns: List[str]: List of all dataset names that apply t...
69,803
def load(x, dtype=None, **kwargs): """ Load local or remote files in a wide range of formats Parameters ---------- :param x: a string containing a URL or file path :param dtype: Optional argument for specifying how the data should be loaded; can be one of: - 'pickle': use the dill library...
69,804
def writeOutput(cur, source, custodian): """ The writeOutput function handles writing either the CSV or HTML reports :param cur: The sqlite3 database cursor object :param source: The output filepath :param custodian: Name of the custodian :return: None """ custodian_id = getCusto...
69,805
def histc_cast(input: Tensor, bins: int, min: int, max: int) -> Tensor: """Helper function to make torch.histc work with other than fp32/64. The function torch.histc is only implemented for fp32/64 which makes impossible to be used by fp16 or others. What this function does, is cast input data type to ...
69,806
def getkwpars(camera,parname): """Extract the correct row of the parameter file based on the value of CAMERA. Parameters are returned as a keyword:value dictionary.""" d={} f=pyfits.open(parname) t=f[1].data cols=f[1].columns # Pick out the matching row of the "camera" column. cams ...
69,807
def main(): """ Runs the simulation with parameters set settings.py :rtype : None """ random.seed(RANDOM_SEED) simulation = Controller(import_network=False, export_network=True, build_network=True) pickle.dump(simulation, open(PICKLE_PATH, 'w+b')) time.sleep(2) # wait till pickle dump i...
69,808
def do_host_sensor_list(cc, args): """List sensors.""" ihost = ihost_utils._find_ihost(cc, args.hostnameorid) isensors = cc.isensor.list(ihost.uuid) field_labels = ['uuid', 'name', 'sensortype', 'state', 'status', ] fields = ['uuid', 'sensorname', 'sensortype', 'state', 'status', ] utils.pri...
69,809
def _run_scan(guess_zma, spc_info, mod_thy_info, coord_names, grid_vals, scn_run_fs, scn_save_fs, scn_typ, script_str, overwrite, zrxn=None, errors=(), options_mat=(), retryfail=True, update_guess=True, saddle=False, const...
69,810
def get_routes(): """ Get a list of routes for this agency. NOT USED. RESERVE. :return: """ # First get the list of routes route_list_xml = get_nextbus_request(command='routeList', a=NEXTBUS_AGENCY) route_list_dom = parseString(route_list_xml) routes = [] # Collect here the routes ...
69,811
def get_new_drugs(month=7,year=2017): """Returns a list of all new drug ids or urls.""" drugs = [] query_url=FDA_URL+FDA_QRY_URL+FDA_MONTH+str(month)+FDA_YEAR+str(year) req = requests.get(query_url) print( req.status_code) soup = BeautifulSoup(req.text,"html5lib") count = 0 trs = soup.f...
69,812
def pipe_through(clip, command_and_args): """ *pipe_through* pipes *clip* through *command_and_args*, which can be a string that is passed to the shell. If it is a list, any arguments after the first one are arguments to the shell, not to the command. """ if isinstance(command_and_args, str): ...
69,813
def jwt_token(value: str) -> T.Union[T.Match[str], None]: """ JWT Token Validator Detail: https://en.wikipedia.org/wiki/JSON_Web_Token """ _jwt_pat = r'^[\w\d\-\_\=]+\.[\w\d\-\_\=]+\.?[\w\d\-\_\.\+\/\=]*$' return re.fullmatch(_jwt_pat, value)
69,814
def paginate(parser, token, paginator_class=None): """Paginate objects. Usage: .. code-block:: html+django {% paginate entries %} After this call, the *entries* variable in the template context is replaced by only the entries of the current page. You can also keep your *entries* ori...
69,815
def autocorrelation(x, lag): """Credit goes to https://github.com/blue-yonder/tsfresh""" if type(x) is pd.Series: x = x.values if len(x) < lag: return np.nan # Slice the relevant subseries based on the lag y1 = x[:(len(x) - lag)] y2 = x[lag:] # Subtract the mean of the wh...
69,816
def test_validate_sleep_bool_true(): """ test _validate_sleep function with True """ pytest.raises(SaltInvocationError, mac_power._validate_sleep, True)
69,817
def run_with_lightboxpanel(func, *args, **kwargs): """Create a ``FSLeyesFrame`` with a ``LightBoxPanel`` and run the given function. """ from fsleyes.views.lightboxpanel import LightBoxPanel return run_with_viewpanel(func, LightBoxPanel, *args, **kwargs)
69,818
def auth_callback(): """ Callback route for after authorization. parameters: - name: code in: args type: string required: true description: Authorization code sent by OAuth Server - name: state in: args type: string required: true ...
69,819
def init_translations(language_code: str) -> None: """ Initialize new language to use for translations. LANGUAGE_CODE is the IETF language tag. """ # https://github.com/python-babel/babel/issues/53 files_to_translate = " ".join([ *glob.glob("src/**/*.py", recursive=True), *glob....
69,820
def convert_specification_to_graph(formula): """Converts a specification formula to a specification graph.""" given_clause, when_clause, then_clause = get_fundamental_clauses(formula) when_property = convert_clause_to_graph(when_clause) then_property = convert_clause_to_graph(then_clause) final_pr...
69,821
def get_sens_spec(y_true, y_pred): """ Args: y_true: list of binary ground-truth labels y_pred: list of binary predictions Returns: sensitivity: True Positive Rate = Sensitivity specificity: True Negative Rate = Specificity (TNR = 1-FPR) """ stat_table = sensitivity_s...
69,822
def save_config(path, config, args, model): """ Alternate way to save model parameters. """ with open(path / 'experiment_config.txt', 'w') as f: f.write(f'\nArguments file:\n') f.write(f'Seed: {args.seed}\n') f.write(f'Batch size: {args.bs}\n') f.write(f'N_epochs: {args.n...
69,823
def log_stats(stats): """ Take the statistics from the track and log the output """ if log_error(stats["error"]): return logger.info( " - Timing (Bayesian updates: {0:.2f}ms, Linking:" " {1:.2f}ms)".format(stats["t_update_belief"], stats["t_update_link"]) ) logger.info( ...
69,824
def compute_word_ops_replace_phrase(phrase): """ Returns the required word operations for given substitute phrase. """ num_words_target = len(phrase.words_target) phrase.num_word_ops = Counter({ "num_word_replaces": num_words_target }) phrase.num_word_ops_abs = Counter(phrase.num_w...
69,825
def shape(context): """Returns a new, independent geometry with coordinates *copied* from the context. """ if hasattr(context, "__geo_interface__"): ob = context.__geo_interface__ else: ob = context geom_type = ob.get("type").lower() if 'coordinates' in ob and _is_coordinates...
69,826
def process_csv(csv_path, image='image_id_', stage='image_stage_', fake='image_fake_', answer='image_answer_'): """ Process a csv file to a list of Result objects :param csv_path: :param image: :param stage: :param fake: :param answer: :return: """ results = [] with open(csv_...
69,827
def main(): """Display the number of nodes.""" client = Client() # obtain all devices connected to an RF Domain domains = settings.INDAHAUS_RF_DOMAINS devices = None token = client.get_token() for idx, domain in enumerate(domains): print(domain) zona = Area.objects.get(rf_dom...
69,828
def extract_colorpalette(palette_name: str, n: int=None, mode: str='hex'): """ Convert color palette to color ramp list. palette_name {str} name of color palette n {int} size of color ramp. If None, automatically return the maximum number of colors in the color palette mode {str} type of colors to ...
69,829
def max_wave_speed(u): """Returns the maximum wave speed for the Euler system""" # Primitive variables rho = u[0, 0::3] v = u[0, 1::3] / rho E = u[0, 2::3] p = (constants.gamma - 1) * (E - 0.5 * rho * v * v) # Get the wave speed wave_speed = np.fabs(v) + np.sqrt(constants.gamma * p / r...
69,830
def detect_face(frame): """ detect human faces in image using haar-cascade Args: frame: Returns: coordinates of detected faces """ faces = face_cascade.detectMultiScale(frame, 1.1, 2, 0, (20, 20)) return faces
69,831
def read_aq(filename, UTC=False): """read in a corrected record that has been exported from Aquarius springboard""" #filename = r'NO3+NO2,water,insitu_as_N.mg_l.(purged,_ex_situ_SUNA2)@364200119420001.EntireRecord (1).csv' #skiprows=15 #UTC=False meta_data = read_aq_metadata(filename) skipro...
69,832
def create_plan( self, plan_name: str, plan_trial_days: int, plan_length: int, plan_type: str, main_currency_code: str = 'USD', initial_price_usd: float = None, initial_price_gbp: float = None, initial_price_eur: float = None, recurring_price_usd: float = None, recurring_pric...
69,833
def make(target: str = "all", rules: dict = rules) -> Optional[File]: """ Make a target (file) using a series of rules. """ rule = rules.get(target) if not rule: # No rule. See if target already exists. file = File(target) if not file.exists(): raise ValueError(f"...
69,834
def _make_datasets(tfds_datasetname: str, vocab: seqio.vocabularies.Vocabulary, batch_size: int, sequence_length: int, has_test: bool = True) -> base.Datasets: """Make Datasets object from tokenized tfds dataset.""" if has_test: splits ...
69,835
def fftconvolve2d(inData, inKernel): """ Parameters ---------- inData: array_like Image to be convolved. inKernel: array_like Convolution kernel. Odd size preferred. Returns ------- outData: array_like Convolved image. """ # Input sizes y1, x1 = inD...
69,836
def middle_of_bracket_teams(): """ Finds teams whose only rounds have been one of the following results: 1 - win by forfeit 2 - lenient_late rounds 3 - byes These teams have speaks of zero but _should_ have average speaks, so they should be paired into the middle of their bracket. Randomiz...
69,837
def unsorted_segment_sum(tensor, segment_ids, num_segments): """Custom PyTorch op to replicate TensorFlow's `unsorted_segment_sum`.""" result_shape = (num_segments, tensor.size(1)) result = tensor.new_full(result_shape, 0) # Init empty result tensor. segment_ids = segment_ids.unsqueeze(-1).expand(-1, t...
69,838
def predict_dataframe(df, model_class, hyperspectral_pool, site_label_dict, domain_label_dict, HSI_size=20, k_neighbors=5): """Iterate through a geopandas dataframe and get neighbors for each tree. Args: df: a geopandas dataframe model_class: A deeptreeattention model class to extract layer features ...
69,839
def bam(ctx, bam_path, cram_path, dry_run): """Compress a bam file to cram format with samtools""" LOG.info("Running compress bam") if dry_run: LOG.info("Dry Run! No files will be created or deleted") cram_api = ctx.obj.get("cram_api") try: cram_api.self_check() except (SyntaxErr...
69,840
def extract_trades_of_period(dataframe: pd.DataFrame, trades: pd.DataFrame, date_index=False) -> pd.DataFrame: """ Compare trades and backtested pair DataFrames to get trades performed on backtested period :return: the DataFrame of a trades of period """ if date_index: ...
69,841
def lock(caller_id, pool_id): """ Sets AvailableNetwork's state as @val{locked}. @cmview_admin_cm @param_post{pool_id,int} id of the AvailableNetwork to lock """ try: network = AvailableNetwork.objects.get(id=pool_id) except: raise CMException('available_network_not_found') ...
69,842
def chunks(png): """Yield ``(chunk_type, chunk_raw_data)`` from ``png``. .. note:: ``chunk_raw_data`` includes chunk length, type, and CRC. :arg png: If ``png`` is a :any:`path-like object` or :any:`file-like object` object, read the content into bytes. :type png: path-like, file-like, or bytes :rtype: G...
69,843
def readCodons(seq): """ Provide an iterator that reads through a sequence one codon at a time. """ for i in xrange(0, len(seq), 3): yield seq[i:i+3]
69,844
def get_device_tracking_counters_vlan_message_type(device, vlanid, message_type="received"): """ Get device_tracking vlan count message type Args: device ('obj'): device object vlanid ('str'): vlan message_type ('str', optional): message type. Defaults to "received" ...
69,845
def match(name: str, expression: str) -> bool: """Test whether NAME matches EXPRESSION. Patterns are Unix shell style: * matches everything ? matches any single character [seq] matches any character in seq [!seq] matches any char not in seq F...
69,846
def fixup_attachment_references(tree: Node, attachments: Dict[Path, AttachmentInfo], source_root_dir: Path, target_root_dir: Path): """ The export from Confluence results in attachments identified by page_id (directory) and attachment_id (filename). Additionally, drawio macro...
69,847
def mock_winreg(fake_registry_xml: str) -> None: """Mock winreg with a mock registry database. Args: fake_registry_xml: XML structure that describes the registry. """ global winreg from .tests import winreg_mock winreg = winreg_mock winreg.InitRegistry(fake_registry_xml)
69,848
def before_request(): """ CORS preflight, required for off-server access """ def _build_cors_prelight_response(): response = make_response() response.headers.add("Access-Control-Allow-Origin", "*") response.headers.add("Access-Control-Allow-Headers", "*") response.headers.add("A...
69,849
def main(): """ Entry point for the sample client """ update = SampleUpdate() update.run()
69,850
def waa_leijnse_2008_from_A_obs( A_obs, f_Hz, L_km, T_K=293.0, gamma=2.06e-5, delta=0.24, n_antenna=np.complex(1.73, 0.014), l_antenna=0.001, ): """Calculate wet antenna attenuation according to Leijnse et al. 2008 Calculate the wet antenna attenuation from observed attenuation,...
69,851
def find_brackets(text: str) -> tuple: """ Find position of angled brackets in a string and return as a tuple (start, end) ISSUES: - Will return a value for "<adjective noun>" which isn't what we want (Maybe can resolve this by checking returned str matches certain values - done...
69,852
def test_join_team(mongo_proc, redis_proc, client): # noqa (fixture) """Test the /api/v1/team/join endpoint.""" clear_db() register_test_accounts() client.post( "/api/v1/user/login", json={ "username": STUDENT_DEMOGRAPHICS["username"], "password": STUDENT_DEMOGRA...
69,853
def fake(): """ Fake Dataset by torchvision Returns: ImageDataset """ target_transform = transforms.Compose([ transforms.Lambda(lambda x: torch.LongTensor([x])), transforms.Lambda(lambda x: F.one_hot(x, num_classes=10).float()), ]) training_set = datasets.FakeData(...
69,854
def find_e0(energy, mu=None, group=None, _larch=None): """calculate E0 given mu(energy) This finds the point with maximum derivative with some checks to avoid spurious glitches. Arguments ---------- energy: array of x-ray energies, in eV or group mu: array of mu(E) group: outpu...
69,855
def _comparison_Equal(testclass, dbdata, comparisondata): """ Compare two objects to see if they are equal """ testclass.assertEqual(dbdata, comparisondata['value'])
69,856
def fqstat(root_dir: pathlib.Path, pattern: str, num_nucleotides: int, quiet: bool) -> None: """Recursively find FastQ files and report the percent of records with nucleotides greater than a provided value per file. Stores results in a JSON file. Args: root_dir: Path (pathlib) obje...
69,857
def move_odict_item(odict, key, newpos): """ References: http://stackoverflow.com/questions/22663966/changing-order-of-ordered-dictionary-in-python CommandLine: python -m utool.util_dict --exec-move_odict_item Example: >>> # ENABLE_DOCTEST >>> from utool.util_dict impor...
69,858
def document_search_keys(): """A list of Regulations.gov document search keys.""" return ['documents', 'totalNumRecords']
69,859
def sleep_timer(enable=None, period=1800, **kwargs): """ Setup sleep timer to schedule power off upon inactivity. NOTE: Do not access pillar data in this function as they will not be available when called from engines (separate processes). Optional arguments: - enable (bool): Enable or disable t...
69,860
def environment(): """ Environment Setting """ form = EnvironmentForm() # TODO: find a way to apply dynamic validation if gluu_settings.db.get("DEPLOYMENT_ARCH") == "gke": form.gmail_account.validators.append(InputRequired()) else: form.gmail_account.validators.append(Optiona...
69,861
def eqn23_rule(model,g,tm): """ Ensures that once you begin to use H2, you cannot transition backwards to old technologies. """ if tm > 1: return model.hydrogen_use[g,tm] >= model.hydrogen_use[g,tm-1] else: return Constraint.NoConstraint
69,862
def test_api_files_exist(api_name : str): """Makes sure all the relevant API files are in test-files directory.""" ini_path = INI_DIRECTORY + "\\" + api_name + ".ini" dll_path = DLL_DIRECTORY + "\\" + api_name + ".dll" assert os.path.isfile(ini_path) assert os.path.isfile(dll_path) assert os.pat...
69,863
def _is_union_type(t) -> bool: """Check if the argument is a union type.""" if sys.version_info >= (3, 10): # This checks for the `|` based syntax introduced in Python 3.10. p310_check = t.__class__ is UnionType else: p310_check = False return p310_check or (hasattr(t, "__origin_...
69,864
def post_reasoner_predict(request_body): """Get predicted associations for a given ReasonerAPI query. :param request_body: The ReasonerStdAPI query in JSON :return: Predictions as a ReasonerStdAPI Message """ query_graph = request_body["message"]["query_graph"] model_id = 'openpredict-basel...
69,865
def test_append_input_workplace(): """test_append_input_workplace.""" workplace = BaseWorkplace("workplace") workplace1 = BaseWorkplace("workplace1") workplace2 = BaseWorkplace("workplace2") workplace.append_input_workplace(workplace1) workplace.append_input_workplace(workplace2) assert work...
69,866
def readjMRUItxt(filename): """ Read .txt format file Parameters ---------- filename : string Name of jmrui .txt file Returns ------- array-like Complex data dict Header information """ signalRe = re.compile(r'Signal (\d{1,}) out of (\d{1,}) in file'...
69,867
def call_hooks(event, entry): """ Rerun pre or post hooks """ hook = event + "-command" if entry.config["holland:backup"][hook] is not None: cmd = entry.config["holland:backup"][hook] try: cmd = Template(cmd).safe_substitute( hook=hook, backupset=entry.ba...
69,868
def make_envs(env_id, log_dir, gamma, max_train_ep_length, max_eval_ep_length, seed): """Make training and evaluation environments (vectorized envs).""" # Training env train_env = gym.make(env_id) train_env.seed(seed) # Set random seed train_env = TimeLimitW...
69,869
def list_or_caseless_string(value): """ Converts the value into a list of ``caseless_string``'s. If the value is not iterable a one-element list with stringified value will be returned. """ if isinstance(value, basestring): return [caseless_string(value)] else: try: ...
69,870
async def fetch_all( session: aiohttp.ClientSession, urls: List[str], output=False, task_per_second: int = 1000, forbidden_max: int = 10, output_number: int = 100, ): """ Fetches multiple sites using a list of URLs given as a parameter. Handles error code 403 (forbidden) in...
69,871
def keyinplaintext(ciphertext, keylen, keyindex, seed, seedindex, decfunc=xor, keyfunc=None): """Solves the case when the key used to encrypt is embedded in the plaintext itself. This function assumes a polyalphabetic substition cipher is used. Arguments: ciphertext -- the ciphertext as a byte arr...
69,872
def load_testdata_from_file(filepath: str) -> None: """creates eve objects in the database from testdata dump given as JSON file Args: filepath: Absolute path to the JSON file containing the testdata created by `create_testdata()` """ with open(filepath, "r", encoding="utf-8") as f: tes...
69,873
def _parallel_spi( arrays_dict: dict, input_var_names: dict, output_var_name: str, input_type: InputType, number_of_workers: int, args, ): """ TODO document this function :param dict arrays_dict: :param dict input_var_names: :param str output_var_name...
69,874
def LBGI_HBGI(df): """ Connecter function to calculate rh and rl, used for ADRR function Args: (pd.DataFrame): dataframe of data with DateTime, Time and Glucose columns Returns: LBGI (float): Low blood glucose index HBGI (float): High blood glucose index ...
69,875
def metadata_edit(gvar): """ Edit the specified cloud metadata file. """ mandatory = ['-cn', '-mn'] required = ['-te'] optional = ['-g', '-H', '-h', '-s', '-v', '-x509', '-xA'] if gvar['retrieve_options']: return mandatory + required + optional # Check for missing arguments or...
69,876
def describe(col, data): """ return basic statistical descriptions """ import pandas as pd d = {} # number of observations d['Nobs'] = [data[col].count()] # mean d['Mean'] = [data[col].mean()] # std d['Std.'] = [data[col].std()] # mad d['Mad'] = [data[col].mad()] ...
69,877
def delivery_report(err, msg): """ Called once for each message produced to indicate delivery result. Triggered by poll() or flush(). """ if err is not None: print(f'{time_stamp()}: Message delivery failed: {err}') else: print(f'{time_stamp()}: Message delivered to {msg.topic()} [{ms...
69,878
def nose_command(verbose=True, detailed=True, cover=None): """Returns the NoseTest TestCommand runner. You can use this directly if you want, or pass any of these kwargs to test_command instead, while also passing nose=True. KWArgs: verbose: print verbose test output detailed: print ex...
69,879
def remove(path, retry=5, wait=False): """ Remove a directory or file :param path: path to remove :return: """ def _remove(path): if exists(path): returncode = 1 for i in range(retry): if path.startswith('hdfs:'): output = subp...
69,880
def dealt_damage( attacker: Pokemon, defender: Pokemon, attack_type: str, attack_power: float, attack_modifier: float = 1, defense_modifier: float = 1, global_modifier: float = 1, ) -> float: """ Calculates the damage dealt by a pokemon to another one. Args: attacker (Po...
69,881
def export(state, case_number, path): """Download a case detail summary as a PDF file at the given path with name <case_number>_case_summary.pdf.""" response = state.sdk.cases.export_summary(case_number) file = os.path.join(path, f"{case_number}_case_summary.pdf") with open(file, "wb") as f: f.w...
69,882
def last_breakout_failed(mode, historical_data, num_days_entry=55, num_days_exit=20): """ Returns a Boolean result indicating whether the last breakout cycle before the specified date, if acted upon, would have led to a loss. Ar...
69,883
def timing_report(file_path): """Check whether `file_path` is a valid YAML timing report file @param file_path @return ``True`` if valid, ``False`` otherwise @throw IOError if `file_path` cannot be opened for reading @throw YAMLError if `file_path` cannot be parsed as a YAML file """ with o...
69,884
def _resample(resampling_way, ts_list, resampling_period, adding_method=AddingMethod.LINEAR_INTERPOLATION, timestamp_position=TimestampPosition.BEG, aggregation_method=AggregationMethod.AVG, nb_points_by_chunk=50000, gener...
69,885
def send_roll(team, roll, args): """Post the roll to Slack.""" chat = Chat(team.get_bot_token()) try: # Attempt to post message chat.post_message( args['channel_id'], roll, username='Roll Bot', icon_emoji=':game_die:' ) except Err...
69,886
def add_log_files(*args: TextIO): """ Add multiple opened file objects to the list of files which the logger logs to. When using tcpsockets.server or tcpsockets.client these list of files(logging.log_to) will be closed automatically. Args: args(TextIO):All the file objects where logs are written to. ...
69,887
def _patch_test_result(klass: Type[Any]) -> None: """Patches flexmock into any class that inherits unittest.TestResult. This seems to work well for majority of test runners. In the case of nose it's not even necessary as it doesn't override unittest.TestResults's addSuccess and addFailure methods so si...
69,888
def get_intervals(x): """ From an unsorted and possibly sparse collection of 1D coordinates, compute the number of bins and the distance between bin centres. Default is nearest-metre precision, which should be fine for most seismic surveys. """ # Preliminaries. x = np.asanyarray...
69,889
def checkBaseLineType(self,name,value): """ checks the baseline type""" checkInStringsListInt(self,name,value,[ 'zero', ['setmin','set min'], ['setmax','set max'], ['graphmin','graph min'], ['graphmax','graph max'], ['setaverage','set average','setavg','setaverage...
69,890
def main(argv=None): """ :param argv: Argument list to parse or None (sys.argv will be set). """ (_psr, args) = parse_args.parse((argv if argv else sys.argv)[1:]) args = process_args_or_run_command(args) cnf = os.environ.copy() if args.env else {} if args.extra_opts: args.extra_opt...
69,891
def test_pdb_list_different(): """ Test a list of PDB codes with fpocket and different alpha sphere sizes to see that results are different to reference results obtained with default parameters """ pdb_list=['1UYD','3LKF','1ATP','4URL','5WA6','7TAA'] for pdb_code in pdb_list: fpocket...
69,892
def cmt_final_digest(parent_digest: str, spec_digest: str, refs_digest: str) -> str: """Determine digest of commit based on digests of its parent, specs, and refs. Parameters ---------- parent_digest : str digest of the parent value spec_digest : str digest of the user spec value ...
69,893
def get_mouse_loc(): """ Get the x,y location of the mouse """ pos = pygame.mouse.get_pos() return pos[0], pos[1]
69,894
def download_highres(lowres_dir, high_res='hsc', band='g', output_name='hires', output_dir='./', overwrite=False, verbose=True): """ Download high resolution image which overlaps with the given low resolution image. This could be **TIME CONSUMING**! Typically one frame could be 500M to...
69,895
def b85encode(octet_string): """Encode a octet_string using 85 characters. Compliant with RFC1924 Intended originally for only 128 bit IPv6 addresses Longer or shorter strings will work. """ return base_N_encode(octet_string, _b85chars )
69,896
def computeIoUs(preds, truths): """ Compute intersection over union for the predicted masks vs ground-truth masks. @preds and @truths must have the same length and both are iterables of numpy matrices of same dimensions. """ # List to collect IoU for each pair IoUs = [] # Iterate over the collections and comput...
69,897
def ruler_show(editor): """ Show ruler. """ editor.show_ruler = True
69,898
def gamma_prior(mode,std): """ In general you should prefer the log_normal prior. """ a = std/mode#sqrt(k)/(k-1) shape = (2* a**2 + np.sqrt((4 * a**2 + 1)/a**4) * a**2 + 1)/(2 *a**2) scale = std/np.sqrt(shape) return gp.priors.Gamma(shape,scale)
69,899