content
stringlengths
22
815k
id
int64
0
4.91M
def walk_files(b, **kwargs): """ Walk a blueprint's files and execute callbacks. * `before_files():` Executed before files are enumerated. * `file(pathname, f):` Executed when a file is enumerated. * `after_files():` Executed after files are enumerated. """ kwargs.get('be...
5,315,600
def run_from_args(args): """ Runs the script based on a Namespace containing the command line arguments """ arr1, axes1 = args.first_parcellation arr2, axes2 = args.second_parcellation bm, (idx1, idx2) = combine((axes1[-1], axes2[-1])) arr1 = arr1[..., idx1] arr2 = arr2[..., idx2] a...
5,315,601
def check_predicted_masks(): """ Returns the list of images for which we have a mask. The length of this list must be equal to the total number of original images. Because there should be a black and white mask for every image. :return: python list of strings """ path_to_masks = os.path.join...
5,315,602
def _sparse_elm_mul(spmat_csr, col): """ spmat (n, m) col (n,) """ for i in range(spmat_csr.shape[0]): i0, i1 = spmat_csr.indptr[i], spmat_csr.indptr[i+1] if i1 == i0: continue spmat_csr.data[i0:i1] *= col[i] return spmat_csr
5,315,603
def roll_out(): """ Just a function to check if the Spark dataframe has been Monkey Patched :return: """ print("Yes!")
5,315,604
def list_ports(): """ Return a list of current port trees managed by poudriere CLI Example: .. code-block:: bash salt '*' poudriere.list_ports """ _check_config_exists() cmd = "poudriere ports -l" res = __salt__["cmd.run"](cmd).splitlines() return res
5,315,605
def _make_vc_curves(ch_data_cache: analyzer.CalcCache): """ Format the VC curves of the main accelerometer channel into a pandas object. """ df_vc = ch_data_cache._VCCurveData * analyzer.MPS_TO_UMPS # (m/s) -> (μm/s) df_vc["Resultant"] = calc_stats.L2_norm(df_vc.to_numpy(), axis=1) if df_vc.siz...
5,315,606
def RunEstimate(update_func, num_points=31, median_flag=False): """Runs the whole analysis. update_func: which of the update functions to use num_points: number of points in the Suite (in each dimension) """ d = ReadHeights(nrows=None) labels = {1:'male', 2:'female'} suites = {} for ke...
5,315,607
def match_attribute_node(obj: Any, name: Optional[str] = None) -> bool: """ Returns `True` if the first argument is an attribute node matching the name, `False` otherwise. Raises a ValueError if the argument name has to be used, but it's in a wrong format. :param obj: the node to be tested. :param ...
5,315,608
def get_data_accessor_predicate( data_type: DataTypeLike = None, format_id: str = None, storage_id: str = None ) -> ExtensionPredicate: """ Get a predicate that checks if a data accessor extensions's name is compliant with *data_type*, *format_id*, *storage_id*. :param data_type...
5,315,609
def check(value: Any, ty: Type[Any]) -> Result: """ # Examples >>> assert is_error(check(1, str)) >>> assert not is_error(check(1, int)) >>> assert is_error(check(1, list)) >>> assert is_error(check(1.3, int)) >>> assert is_error(check(1.3, Union[str, int])) """ if not isinstance(v...
5,315,610
def construct_feature_columns(): """Construct the TensorFlow Feature Columns. Returns: A set of feature columns """ # There are 784 pixels in each image. return set([tf.feature_column.numeric_column('pixels', shape=784)])
5,315,611
def is_array_str(obj): """ Check if obj is a list of strings or a tuple of strings or a set of strings :param obj: an object :return: flag: True or False """ # TODO: modify the use of is_array_str(obj) in the code to is_array_of(obj, classinfo) flag = False if isinstance(obj, str): ...
5,315,612
def generate_sample_path(n): """ Generates a sample path :param n: path length :returns x, y: state and observations sample path """ x = np.zeros((n + 1, m_W.shape[0])) y = np.zeros((n + 1, m_Nu.shape[0])) # w = np.random.normal(self.m_w, self.std_w, (n + 1, self.m_w.shape[0])) # nu ...
5,315,613
def plotTSNE(resultPaths, experimentNames, metricsToCluster, applySoftmax, tsneLearningRate, tsnePerplexity, labelWithImages, labelsAndImages, export=None, title=None, printExamples=None): ...
5,315,614
def main(): """Entry point for thumber console script""" if len(sys.argv) < 4: help_msg() sys.exit(1) a = Thumber() if sys.argv[1] == "store": data_blob, header = a.create_thumbs_and_index(file_path = sys.argv[2]) output_filename = sys.argv[3] elif sys.argv[1] == "loa...
5,315,615
def get_pod_by_label_selector( kube_client, label_selector, pod_namespace=namespace ) -> str: """Return the name of a pod found by label selector.""" pods = kube_client.list_namespaced_pod( pod_namespace, label_selector=label_selector ).items assert ( len(pods) > 0 ), f"Expected ...
5,315,616
def make_file_path(file, args): """Create any directories and subdirectories needed to store data in the specified file, based on inputs_dir and inputs_subdir arguments. Return a pathname to the file.""" # extract extra path information from args (if available) # and build a path to the specified file. ...
5,315,617
def get_ticket_refs(text, prefixes=None): """Returns a list of ticket IDs referenced in given text. Args: prefixes (list of unicode): Prefixes allowed before the ticket number. For example, prefixes=['app-', ''] would recognize both 'app-1' and '1' as ticket IDs. ...
5,315,618
def print_pvalues_to_screen(res): """ Print p-values for various statistical tests to screen. Parameters ---------- res: dict Contains Shannon information values, p-values, and test names (labels) for various tests. """ print() print(" statistical ...
5,315,619
def xsh_session(): """return current xonshSession instance.""" return builtins.__xonsh__
5,315,620
def is_date_valid(keyid, date, lookup_dict=movie_dict): """ Function to see if a date is valid for a given key. :param keyid: key into the dictionary :param date: a date to check for in the list corresponding to 'keyid' :param lookup_dict: lookup dictionary Note, the date is treated as an exact ...
5,315,621
def test_creating_list_with_cons(): """TEST 6.2: The `cons` functions prepends an element to the front of a list.""" result = evaluate(parse("(cons 0 '(1 2 3))"), Environment()) assert_equals(parse("(0 1 2 3)"), result)
5,315,622
def train_op_initialize_fit_cp(self, feed_dict, val_feed_dict, dprep_dict, daug_dict, show_metric, summ_writer, coord): """ initialize_fit. Initialize data for feeding the training process. It is meant to be used by `Trainer` before starting to fit data. Arguments: ...
5,315,623
def format_filename(name): """Take a string and return a valid filename constructed from the string. Uses a whitelist approach: any characters not present in valid_chars are removed. Also spaces are replaced with underscores. Note: this method may produce invalid filenames such as ``, `.` or `..` When I use this m...
5,315,624
def bin_plot(frame, x = None, target = 'target', iv = True): """plot for bins """ group = frame.groupby(x) table = group[target].agg(['sum', 'count']).reset_index() table['badrate'] = table['sum'] / table['count'] table['prop'] = table['count'] / table['count'].sum() prop_ax = tadpole.barp...
5,315,625
def getCtimeOfFile(fileName): """ input: string output: string description: Get the first line of the file to determine whether there is a date, if any, change to the specified date format(yyyymmddHHMM) and return, if not, return an empty string ...
5,315,626
def Get_ConfusionMatrix(TrueLabels, PredictedLabels, Classes, Normal=False, Title='Confusion matrix', ColorMap='rainbow', FigSize=(30,30), save=False): """ Function designed to plot the confusion matrix of the predicted labels versus the true leabels INPUT: vector containing the actual ...
5,315,627
def _noncentrality_chisquare(chi2_stat, df, alpha=0.05): """noncentrality parameter for chi-square statistic `nc` is zero-truncated umvue Parameters ---------- chi2_stat : float Chisquare-statistic, for example from a hypothesis test df : int or float Degrees of freedom alp...
5,315,628
def delete_helm_release(release): """Delete helm release This method deletes a helm release without --purge which removes all associated resources from kubernetes but not from the store(ETCD) In the scenario of updating application, the method is needed to clean up the releases if there were deplo...
5,315,629
def get_subjects(): """ Get all subjects from the database """ connection = db_engine.connect() subject = get_table("subject") columns = [ subject.c.id, cast(subject.c.date_created, Text), subject.c.date_created.label('date_created'), cast(subject.c.date_modified, Text), subject....
5,315,630
def get_rest_api(*, config: Config) -> FastAPI: """Creates a FastAPI app.""" container = setup_container(config=config) container.wire(modules=["ucs.adapters.inbound.fastapi_"]) api = FastAPI() api.include_router(router) configure_app(api, config=config) return api
5,315,631
def read_expression_profiles(pro_file): """ Return a DataFrame containing data from a FluxSimulator .pro file. Return a DataFrame encapsulating the data from a FluxSimulator transcriptome profile (.pro) file. pro_file: Path to a FluxSimulator transcriptome profile file. """ return pd.read_c...
5,315,632
def format_list(lst): """ Format a list as a string, ignore if it is string :param lst the list to format :return the formatted string """ if not isinstance(lst, basestring): return " ".join(str(i) for i in lst) return lst
5,315,633
def sampler_paraphrase(sentence, sampling_temp=1.0): """Paraphrase by sampling a distribution Args: sentence (str): A sentence input that will be paraphrased by sampling from distribution. sampling_temp (int) : A number between 0 an 1 Returns: str: a candidate paraphra...
5,315,634
def create_graph(tensorboard_scope, mode_scope, input_file, input_len=2, output_len=1, batch_size=1, verbose=True, reuse=None, n_threads=2): """ create or reuse graph :param tensorboard_scope: variable scope name :param mode_scope: 'train', 'valid', 'test' :param input_file: train or valid or test f...
5,315,635
def update_trip_public(request, trip_id): """ Makes given trip public :param request: :param trip_id: :return: 400 if user not present in the trip :return: 404 if trip or user does not exist :return: 200 successful """ try: trip = Trip.objects.get(pk=trip_id) # if si...
5,315,636
def get_peer_count(ihash): """Return count of all participating peers we've seen""" return g.redis.scard("%s:peers:N" % ihash)
5,315,637
def calc_checksum(filename): """ Calculates a checksum of the contents of the given file. :param filename: :return: """ try: f = open(filename, "rb") contents = f.read() m = hashlib.md5() m.update(contents) checksum = m.hexdigest() return checksum ...
5,315,638
def Axes_add_rectangle_maxY(ax,pos,**kwargs): """ Add retangle to axes by specifing xaxis data limits: x1,x2 Parameters: ----------- pos: the positions on xaxis where rectangles should be drawn. could be: - tuple: 2-length tuple specifying beginning and end of x-position. - list: a li...
5,315,639
def alignment_matrix(subject, target, precision=BASE_PREC, verbosity=0, max_steps=BASE_STEPS): """ Numerically find the rotation matrix necessary to rotate the `subject` vector to the `target` direction. Args: subject (np.ndarray): Length-3 vector to rotate. target (np.ndarray): Length-3 ve...
5,315,640
def make_batch(sentences): """ create batch data from sentences (list) """ input_batch = [] target_batch = [] for sen in sentences: word = sen.split() input = [word_dict[n] for n in word[:-1]] target = word_dict[word[-1]] input_batch.append(np.eye(n_class)[input...
5,315,641
def save_file(file_path, content, hdfs_client=None, use_hdfs=False): """Opens a file for write and returns its corresponding file object. """ if use_hdfs: if hdfs_client.status(file_path, strict=False): print('[WARNING] File already exists: %s' % file_path) with hdfs_client.writ...
5,315,642
def query_to_str(statement, bind=None): """ returns a string of a sqlalchemy.orm.Query with parameters bound WARNING: this is dangerous and ONLY for testing, executing the results of this function can result in an SQL Injection attack. """ if isinstance(statement, sqlalchemy.orm.Que...
5,315,643
def __filter_card_id(cards: list[str]): """Filters an list with card ids to remove repeating ones and non-ids""" ids = list() for c in cards: try: int(c) except ValueError: continue else: if c not in ids: ids.append(c) ret...
5,315,644
async def test_switch_api_failure(hass: HomeAssistant, caplog) -> None: """Test general exception turning switch on/off.""" await setup_uptimerobot_integration(hass) entity = hass.states.get(UPTIMEROBOT_SWITCH_TEST_ENTITY) assert entity.state == STATE_ON with patch( "pyuptimerobot.UptimeRo...
5,315,645
def get_elapsed_time(start_time) -> str: """ Gets nicely formatted timespan from start_time to now """ end = time.time() hours, rem = divmod(end-start_time, 3600) minutes, seconds = divmod(rem, 60) return "{:0>2}:{:0>2}:{:05.2f}".format(int(hours), int(minutes), seconds)
5,315,646
def predict_causalforest(cforest, X, num_workers): """Predicts individual treatment effects for a causal forest. Predicts individual treatment effects for new observed features *X* on a fitted causal forest *cforest*. Predictions are made in parallel with *num_workers* processes. Args: cfo...
5,315,647
def sectnum(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): """Automatic section numbering.""" pending = nodes.pending(parts.SectNum) pending.details.update(options) state_machine.document.note_pending(pending) return [pending]
5,315,648
def make_vectorized_optimizer_class(cls): """Constructs a vectorized DP optimizer class from an existing one.""" child_code = cls.compute_gradients.__code__ if child_code is not parent_code: logging.warning( 'WARNING: Calling make_optimizer_class() on class %s that overrides ' 'method compute_...
5,315,649
def filename_matches_pattern(filepath, pattern): """ """ if isinstance(pattern, string_types): pattern = (pattern, ) for p in tuple(pattern): if fnmatch(filepath, p): return True return False
5,315,650
def gmt_time(): """ Return the time in the GMT timezone @rtype: string @return: Time in GMT timezone """ return time.strftime('%Y-%m-%d %H:%M:%S GMT', time.gmtime())
5,315,651
def convertbase(num, base=10): """ Convert a number in base 10 to another base :type num: number :param num: The number to convert. :type base: integer :param base: The base to convert to. >>> convertbase(20, 6) '32' """ sign = 1 if num > 0 else -1 alphanum = ...
5,315,652
def get_riskmodel(taxonomy, oqparam, **extra): """ Return an instance of the correct riskmodel class, depending on the attribute `calculation_mode` of the object `oqparam`. :param taxonomy: a taxonomy string :param oqparam: an object containing the parameters needed by the riskmodel...
5,315,653
def is_subdirectory(path_a, path_b): """Returns True if `path_a` is a subdirectory of `path_b`.""" path_a = os.path.realpath(path_a) path_b = os.path.realpath(path_b) try: relative = os.path.relpath(path_a, path_b) except ValueError: # Different mounts on Windows: # ValueErro...
5,315,654
def add_str(arg1, arg2): """concatenate arg1 & arg2 Using in template: '{{ arg1|add_str:arg2 }}' """ return str(arg1) + str(arg2)
5,315,655
def clean_string_columns(df): """Clean string columns in a dataframe.""" try: df.email = df.email.str.lower() df.website = df.website.str.lower() except AttributeError: pass str_columns = ["name", "trade_name", "city", "county"] for column in str_columns: try: ...
5,315,656
def build_profile(first, last, **user_info): """Build a dictionary containing everything we know about a user.""" profile = {} profile['first_name'] = first profile['last_name'] = last for key, value in user_info.items(): profile[key] = value return profile
5,315,657
def test_0070_check_invalid_installation(config): """Test cse check against config that hasn't been used for installation.""" try: cmd = f"check {env.ACTIVE_CONFIG_FILEPATH} --skip-config-decryption --check-install" # noqa: E501 env.CLI_RUNNER.invoke(cli, cmd.split(), catch_exceptions=False) ...
5,315,658
def main(): """Main function""" import gym import warnings import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from tqdm import tqdm from scipy.optimize import minimize from mdp_extras import ( vi, OptimalPolicy, ...
5,315,659
def test_lfs_storage_clean(runner, project, client_with_remote): """Test ``renku storage clean`` command.""" client = client_with_remote['client'] with (client.path / 'tracked').open('w') as fp: fp.write('tracked file') client.repo.git.add('*') client.repo.index.commit('tracked file') ...
5,315,660
def _QueryForUser(user, role=None, target=None): """Gets all _Permissions for the user's ID and e-mail domain.""" return _Query(user.id, role, target) + _Query(user.email_domain, role, target)
5,315,661
def decode_transfer2(instruction: TransactionInstruction) -> Transfer2Params: """Decode a transfer2 token transaction and retrieve the instruction params.""" parsed_data = __parse_and_validate_instruction(instruction, 4, InstructionType.TRANSFER2) return Transfer2Params( program_id=instruction.progr...
5,315,662
def postprocess(annotator, genomes, working_dir): """ Finds eCIS-screen output files and creates file with annotations for upload into DB """ output_file = os.path.join(annotator.config['cgcms.temp_dir'], 'ecis-screen-plugin-output.txt') accessions = {} for genome in genomes: gb...
5,315,663
def deep_predict(data: pd.DataFrame, model, kernel: str): """ Deepl Predict Method. """ data = feature_time(data) print(data.shape) print(data.tail(5)) # normalization data = data.set_index('time') data_norm = (data - data.mean()) / data.std() print("name: ", model.name) thi...
5,315,664
def main(argv=None): """Program entry point for parsing the command line.""" parser = argparse.ArgumentParser( description=("Parse PED file and transform pedigree information into" "VCF header format") ) parser.add_argument( "--ped-file", type=argparse.FileType("rt"), req...
5,315,665
def create(user_id): """ Create User Function """ req_data = request.get_json() isuser = UserModel.get_one_user(user_id) #Check if user exist if isuser: return custom_response({'error': 'User already exist'}, 400) req_data["user_guid"] = user_id user = UserModel(req_data) message = user.create...
5,315,666
def ordinal(n: int) -> str: """ from: https://codegolf.stackexchange.com/questions/4707/outputting-ordinal-numbers-1st-2nd-3rd#answer-4712 """ result = "%d%s" % (n, "tsnrhtdd"[((n / 10 % 10 != 1) * (n % 10 < 4) * n % 10)::4]) return result.replace('11st', '11th').replace('12nd', '12th').replace('13r...
5,315,667
def part_2(): """Function which calculates the solution to part 2 Arguments --------- Returns ------- """ return None
5,315,668
def new_hdf5(new_filename): """ This function creates a new hdf5 file in the active directory taking as the sole argument a string name for the file. Args: new_filename (str): Filename for the new hdf5 file such that the created empty file will have the name new_file...
5,315,669
def test_Magnetic_FEMM_sym(): """Validation of outer rotor SPMSM Open circuit (Null Stator currents) Machine B from Vu Xuan Hung thesis "Modeling of exterior rotor permanent magnet machines with concentrated windings" Hanoi university of science and technology 2012 Test compute the Flux in F...
5,315,670
def calc_dist_enrichment(ref_pos,spots_pos,img_size,delta_dist = 100, img_density=[],flag_plot=False): """ Calculates the expression level as a function of the distance from a reference point. Args: ref_pos (tuple): position of reference point. spots_pos (np array): RNA positions ...
5,315,671
def get_single_two_body_file(molecule_file_name): """ Loads the molecule from a file. :param molecule_file_name: Filename :return: Molecule """ molecule = MolecularData(filename=molecule_file_name) molecule.load() # _molecule = run_pyscf(molecule) return molecule.one_body_integrals...
5,315,672
def proposition_formatter(propositions): """Returns a list of propositions with selected fields.""" return [ { 'deadline': dateutil_parse(proposition['deadline']).strftime('%Y-%m-%d'), 'status': proposition['status'], 'modified_on': dateutil_parse(prop...
5,315,673
def CondSphereAnalFunB(x, y, z, R, x0, y0, z0, sig1, sig2, E0, flag): """ test Analytic function for Electro-Static problem. The set up here is conductive sphere in whole-space. * (x0,y0,z0) * (x0, y0, z0 ): is the center location of sphere * r: is the radius of the sphere .. math:: \mathbf{E}_0 = ...
5,315,674
def num2hr (num): """Given an integer, return a string with the same amount expressed with a quantifier.""" num = long (num) for quant_abbr, quant_amount in quants_tups_dec: if num >= quant_amount: return "%.2f%s" % (float (num) / quant_amount, quant_abbr...
5,315,675
def super_resolve_service(path): """ Take the input image and super resolve it """ # check if the post request has the file part if 'file' not in request.files: return BadRequest("File not present in request") file = request.files['file'] if file.filename == '': return BadReq...
5,315,676
def init_logger() -> None: """ Initialize the main system logger """ LOG_PATH.mkdir(parents=True, exist_ok=True) start_time = time.strftime("%Y-%m-%d_%H.%M.%S") logging.basicConfig( level=logging.DEBUG if os.environ.get("MTGJSON5_DEBUG", "").lower() in ["true", "1"] els...
5,315,677
def quarks_to_kin(quarks: int) -> str: """Converts an integer quark amount into a string Kin amount. :param quarks: An amount, in quarks. :return: A string Kin amount. """ kin = (decimal.Decimal(quarks) / _KIN_TO_QUARKS) return str(kin)
5,315,678
def get_feature_representations(model, content_path, style_path, num_style_layers): """Helper function to compute our content and style feature representations. This function will simply load and preprocess both the content and style images from their path. Then it will feed them through the network to obt...
5,315,679
def check_string(sql_string, add_semicolon=False): """ Check whether a string is valid PostgreSQL. Returns a boolean indicating validity and a message from ecpg, which will be an empty string if the input was valid, or a description of the problem otherwise. """ prepped_sql = sqlprep.prepare...
5,315,680
def init_db(): """Initializes the database.""" with app.app_context(): db = get_db() with app.open_resource('backend/schema.sql', mode='r') as f: db.cursor().executescript(f.read()) db.commit() set_default_settings()
5,315,681
def interpolate_freq_stft(Y, F_coef, F_coef_new): """Interpolation of STFT along frequency axis Notebook: C2/C2_STFT-FreqGridInterpol.ipynb Args: Y: Magnitude STFT F_coef: Vector of frequency values F_coef_new: Vector of new frequency values Returns: Y_inter...
5,315,682
def save_shapely_shapes_to_file(shapes_list, ref_shp, output_shp,copy_field=None): """ save shapes in shapely format to a file Args: shapes_list: shapes list, can be polygon, line, and so on ref_shp: reference shapefile containing the projection information output_shp: save path ...
5,315,683
def slow_blocking_gen(): """Slow synchronous client generator""" for i in range(INPUT_LEN): print(f'in sync_slow_gen {i}') yield get_document(i) time.sleep(INPUT_GEN_SLEEP_TIME)
5,315,684
def get_guide_counts(mags, t_ccd): """ Get guide star fractional count in various ways. - count_9th : fractional stars greater than "9th" magnitude (need 3.0) - count_10th : fractional stars greater than "10th" magnitude (need 6.0) - count_all : weighted fractional count of all stars Parameter...
5,315,685
async def amireallyalive(salive): """ For .alive command, check if the bot is running. """ if ALIVE_PHOTTO: pm_caption = "**⚡ 𝐁 𝐔 𝐙 𝐙 ⚡ 🅾︎🅽🅻🅸🅽🅴**\n" pm_caption += f"**𝕄𝕪 𝔹𝕠𝕤𝕤** : {DEFAULTUSER}\n" pm_caption += "𝚃𝙴𝙻𝙴𝚃𝙷𝙾𝙽 𝚅𝙴𝚁𝚂𝙸𝙾𝙽 : 1.1...
5,315,686
def test_triples_in_file(path): """ This function loads the test suite and gold standard and prints the mismatches between the system analysis of the test suite, including perspective if it is added, as well as the number of correctly and incorrectly extracted triple elements :param path: filepath o...
5,315,687
def db_write_y(filename): """Write yearly data to sqlite database""" table = 'yearly' rows = 0 chunksize = 150 chunk_num = 0 LOGGER.info('Connect to DB %s - table: %s.', DB_FILE, table) conn = sqlite3.connect(DB) LOGGER.debug('Get a cursor object.') cursor = conn.cursor() for d...
5,315,688
def cal2theta(qmag, energy_kev=17.794): """ Calculate theta at particular energy in keV from |Q| twotheta = cal2theta(Qmag,energy_kev=17.794) """ energy = energy_kev * 1000.0 # energy in eV # Calculate 2theta angles for x-rays twotheta = 2 * np.arcsin(qmag * 1e10 * fg.h * fg.c / (energy *...
5,315,689
def convert(df,to_convert,out_file=None,overwrite=False, uid_to_pretty=False): """ Private function wrapped by uid_to_pretty and pretty_to_uid that converts a file or string between uid and pretty. df: dataframe with pretty name data and uid to_convert: content to edit. if this is a fil...
5,315,690
def melhor_filme(browser, filme, email, telefone): """Preenche o formulário do melhor filme de 2020.""" browser.find_element_by_name('filme').send_keys(filme) browser.find_element_by_name('email').send_keys(email) browser.find_element_by_name('telefone').send_keys(telefone) browser.find_element_by_n...
5,315,691
def _load_lib(): """Load libary by searching possible path.""" curr_path = os.path.dirname(os.path.realpath(os.path.expanduser(__file__))) lib_search = curr_path lib_path = libinfo.find_lib_path(_get_lib_names(), lib_search, optional=True) if lib_path is None: return None, None lib = cty...
5,315,692
def get_train_data( image_list, gt_list, out_dir=None, name='train-unet', shape=(10, 256, 256), n_each=100, channels=('z-1', 'y-1', 'x-1', 'centreness'), scale=(4, 1, 1), log=True, validation_prop=0.2, ): """ Generate training data from whole ground truth volumes. ...
5,315,693
def data_combiner(n_actions: int, subject_ids: list, n_takes: int, modalities: list, skeleton_pose_model: str): """Combines skeleton point information for all actions, all takes, given list of subject ids and given list of modalities. ...
5,315,694
def log_uncaught_exceptions(exc_type, exc_value, exc_traceback): """ Qt slots swallows exceptions but this ensures exceptions are logged """ logging.error('An unhandled exception occurred!', exc_info=(exc_type, exc_value, exc_traceback)) logging.shutdown() sys.exit(1)
5,315,695
def yolo_eval(yolo_outputs, model_image_size, true_image_size=None, max_boxes=9, score_threshold=.6, iou_threshold=.5, on_true=False): """Converts the output of YOLO encoding (a lot of boxes) to your predicted boxes along with their scores, box coordinates and classes. Parameters: ----------- yolo_outputs -- ...
5,315,696
def input_fn_builder(features, seq_length, is_training, drop_remainder): """Creates an `input_fn` closure to be passed to TPUEstimator.""" all_input_ids = [] all_input_mask = [] all_segment_ids = [] all_label_ids = [] for feature in features: all_input_ids.append(feature.input_ids) ...
5,315,697
def expand_files(files): """Expands a wildcard to a list of paths for Windows compatibility""" # Split at whitespace files = files.split() # Handle wildcard expansion if len(files) == 1 and '*' in files[0]: files = glob.glob(files[0]) # Convert to Path objects return files
5,315,698
def get_index(): """ Return the index from a loaded index if loaded or from building and loading from files. """ global _LICENSES_INDEX if not _LICENSES_INDEX: _LICENSES_INDEX = get_license_index() return _LICENSES_INDEX
5,315,699