content
stringlengths
22
815k
id
int64
0
4.91M
def sort_files(pool_size, filenames): """ Sort files by batches using a multiprocessing Pool """ with Pool(pool_size) as pool: counters = pool.map(sorter, filenames) with open('sorted_nums.txt','w') as fp: for i in range(1, MAXINT+1): count = sum([x.get...
33,100
def test_find_contiguous_blocks(): """ This tests the find contiguous block function """ first_seq = [1, 2, 3, 4, 6, 6, 6, 7, 8, 10, 20, 10, 100] assert list(find_contiguous_blocks(first_seq)) == [(1, 4), (6, 8)] second_seq = [1, 2, 3, 4, 5, 6, 7] assert list(find_contiguous_blocks(second_seq)) ==...
33,101
def test_len_size(): """Check length of Time objects and that scalar ones do not have one.""" t = Time(np.arange(50000, 50010), format='mjd', scale='utc') assert len(t) == 10 and t.size == 10 t1 = Time(np.arange(50000, 50010).reshape(2, 5), format='mjd', scale='utc') assert len(t1) == 2 and t1.size ...
33,102
def main(args): """Main function for lattice arc tagging.""" global LOGGER LOGGER = utils.get_logger(args.verbose, log_file_name=os.path.join(args.file_list_dir, 'targets-info')) dst_dir = os.path.join(args.dst_dir, 'target_overlap_{}'.format(args.threshold)) utils.mkdir(dst_dir) np_conf_dir ...
33,103
def relabel_sig(sig:BaseSignature, arg_map:TDict[str, str]=None, new_vararg:str=None, kwarg_map:TDict[str, str]=None, new_varkwarg:str=None, output_map:TDict[str, str]=None) -> BaseSigMap: """ Given maps along which to rename signature elements, generate a new ...
33,104
def inferred_batch_shape_tensor(batch_object, bijector_x_event_ndims=None, **parameter_kwargs): """Infers an object's batch shape from its parameters. Each parameter contributes a batch shape of `base_shape(parameter)[:-event_ndims(parameter)]`, wh...
33,105
def fsevent_log(self, event_id_status_message): """Amend filesystem event history with a logging message """ event_id = event_id_status_message[0] status = event_id_status_message[1] message = event_id_status_message[2] dbc = db_collection() history_entry = { 'state': fsevents.UPDATE...
33,106
def fetch_synthetic_2d(lags=0): """ Build synthetic 2d data. Parameters ---------- lags : int, optional If greater than 0 it's added time dependence. The default is 0. Returns ------- data : numpy.ndarray, shape=(3000, 2) Synthetic data. """ seed = 98 ...
33,107
def prepare_data() -> tuple: """Do the whole data preparation - incl. data conversion and test/train split. Returns: tuple: (X_train, y_train, X_test, y_test) """ (data, labels) = get_data() from sklearn.preprocessing import MultiLabelBinarizer mlb = MultiLabelBinarizer() mlb.fit(la...
33,108
def current_url_name(request): """ Adds the name for the matched url pattern for the current request to the request context. """ try: match = resolve(request.path) url_name = match.url_name except Http404: url_name = None return { 'current_url_name':...
33,109
def get_crypto_key(): """Shows your crypto key""" key = load_key() if key: click.secho("your actual crypto key:", fg = "blue") return click.echo(load_key())
33,110
def get_entropies(data: pd.DataFrame): """ Compute entropies for words in wide-format df """ counts = pd.DataFrame(apply_count_values( data.to_numpy(copy=True)), columns=data.columns) probs = (counts / counts.sum(axis=0)).replace(0, np.nan) nplogp = -probs * np.log2(probs) return npl...
33,111
def create_dataset(dataset_path, do_train, image_size=224, interpolation='BILINEAR', crop_min=0.05, repeat_num=1, batch_size=32, num_workers=12, autoaugment=False, ...
33,112
def _numeric_adjust_widgets(caption: str, min: float, max: float) -> HBox: """Return a HBox with a label, a text box and a linked slider.""" label = Label(value=caption) text = BoundedFloatText(min=min, max=max, layout=wealth.plot.text_layout) slider = FloatSlider(readout=False, min=min, max=max) wi...
33,113
def test_show_help(capsys): """ Shows help. Arguments: capsys: Pytest fixture to capture output. """ with pytest.raises(SystemExit): cli.review(["-h"]) captured = capsys.readouterr() assert "review" in captured.out
33,114
def project_assignments(): """ Generator that will provide all of the assignments that a user has :return: """ current_page = 1 while True: assignment_data = harvest.current_assignments(current_page) for project_assignment in assignment_data['project_assignments']: ...
33,115
def visualize_stft(eeg_data,fs,title,ax,showPlot=False): """ eeg_data: (time_steps,channels) averages over all frequency spectrums """ if not ax: fig = plt.figure() ax = fig.gca() showPlot=True else: fig = ax.get_figure() eeg_fft = fftpack.fft(eeg_data,axis=0)...
33,116
def evaluate(benchmark, solution): """Evaluate the solution against the benchmark.""" # Get test data root = os.path.dirname(__file__) path = os.path.join(root, "../../task/regression/data/{}_test.csv".format(benchmark)) df_test = pd.read_csv(path, header=None) X = df_test.values[:, :-1].T # X ...
33,117
def where_handle(tokens): """Process where statements.""" internal_assert(len(tokens) == 2, "invalid where statement tokens", tokens) final_stmt, init_stmts = tokens return "".join(init_stmts) + final_stmt + "\n"
33,118
def plot_figure(ms_label, ms_counts, left, right, params_dict, save_directory): """ 'ms_label' mass shift in string format. 'ms_counts' entries in a mass shift. 'left """ #figure parameters b = 0.2 # shift in bar plots width = 0.4 # for bar plots labels = params_dict['labels'] ...
33,119
def nltk_ngram_pos_tagger(input_dict): """ A tagger that chooses a token's tag based on its word string and on the preceding n word's tags. In particular, a tuple (tags[i-n:i-1], words[i]) is looked up in a table, and the corresponding tag is returned. N-gram taggers are typically trained on a...
33,120
def pkg(root, version, output, identifier=CONFIG['pkgid'], install_location='/', sign=CONFIG['sign_cert_cn'], ownership='recommended' ): """ Create a package. Most of the input parameters should be recognizable for most admins. `output` is the pat...
33,121
def remove_app(INSTALLED_APPS, app): """ remove app from installed_apps """ if app in INSTALLED_APPS: apps = list(INSTALLED_APPS) apps.remove(app) return tuple(apps) return INSTALLED_APPS
33,122
def get_feature(cluster, sample, i): """Turn a cluster into a biopython SeqFeature.""" qualifiers = OrderedDict(ID="%s_%d" % (sample, i)) for attr in cluster.exportable: qualifiers[attr] = getattr(cluster, attr.lower()) feature = SeqFeature(FeatureLocation(cluster.start, cluster.end), type=clust...
33,123
def loss(Y, spectra, beta, Yval, val_spec): """ Description ----------- Calculate the loss for a specfic set of beta values Parameters ---------- Y: labels (0 or 1) spectra: flux values beta: beta values Yval: validation set labels (0 or 1) val_spec: validation flux values Returns ------- ...
33,124
def video_detail_except(): """取得channelPlayListItem/videoDetail兩表video_id的差集 Returns: [list]: [目前尚未儲存詳細資料的影片ID] """ playlist_id = get_db_ChannelPlayListItem_video_id() video_detail_id = get_db_VideoDetail_video_id() if video_detail_id and playlist_id: filter_video = list(set(pla...
33,125
def nodes(xmrs): """Return the list of Nodes for *xmrs*.""" nodes = [] _props = xmrs.properties varsplit = sort_vid_split for p in xmrs.eps(): sortinfo = None iv = p.intrinsic_variable if iv is not None: sort, _ = varsplit(iv) sortinfo = _props(iv) ...
33,126
def get_figure(a=None, e=None, scale=10): """ Creates the desired figure setup: 1) Maximize Figure 2) Create 3D Plotting Environment 3) Rotate Z axis label so it is upright 4) Let labels 5) Increase label font size 6) Rotate camera to ideal (predetermined) angle """ from mpl_tool...
33,127
def plot_metric(history, metric="loss", ylim=None, start_epoch=0): """Plot the given metric from a Keras history Parameters ---------- history : tf.keras.callbacks.History History object obtained from training metric : str, optional Metric monitored in training, by default 'loss' ...
33,128
def get_data_loader(transformed_data, is_training_data=True): """ Creates and returns a data loader from transformed_data """ return torch.utils.data.DataLoader(transformed_data, batch_size=50, shuffle=True) if is_training_data else torch.utils.data.DataLoader(transformed_data, batch_size=50)
33,129
def resolve_authconfig(authconfig, registry=None): """ Returns the authentication data from the given auth configuration for a specific registry. As with the Docker client, legacy entries in the config with full URLs are stripped down to hostnames before checking for a match. Returns None if no matc...
33,130
def structured_rand_arr(size, sample_func=np.random.random, ltfac=None, utfac=None, fill_diag=None): """Make a structured random 2-d array of shape (size,size). If no optional arguments are given, a symmetric array is returned. Parameters ---------- size : int Determi...
33,131
def dell_apply_bios_settings(url=None): """ Apply BIOS settings found at the given URL :param url: Full URL to the BIOS file """ # TODO: Implement this assert url raise NotImplementedError
33,132
def test_show_retrieve_all(): """Testing for :py:meth:`wwdtm.show.Show.retrieve_all` """ show = Show(connect_dict=get_connect_dict()) shows = show.retrieve_all() assert shows, "No shows could be retrieved" assert "id" in shows[0], "No Show ID returned for the first list item"
33,133
def append_empty_args(func): """To use to transform an ingress function that only returns kwargs to one that returns the normal form of ingress functions: ((), kwargs)""" @wraps(func) def _func(*args, **kwargs): return (), func(*args, **kwargs) return _func
33,134
def cron_start(instant: bool = True): """Start the crontab. """ if queue.crontab: print('Crontab already exists.') return now = datetime.now() cmd = ( "bash -c 'source $HOME/.bashrc; {cmd} cron:run {opt}' >> {log} 2>&1" .format( cmd=sys.argv[0], ...
33,135
def gateway(job, app, tool, user, user_email): """ Function to specify the destination for a job. At present this is exactly the same as using dynamic_dtd with tool_destinations.yml but can be extended to more complex mapping such as limiting resources based on user group or selecting destinations ...
33,136
def process_command_line(): """ Return a 1-tuple: (args list). `argv` is a list of arguments, or `None` for ``sys.argv[1:]``. """ parser = argparse.ArgumentParser(description='usage') # add description # positional arguments parser.add_argument('d1s', metavar='domain1-source', type=str, help='dom...
33,137
def mqtt_gateway(broker, port, **kwargs): """Start an mqtt gateway.""" with run_mqtt_client(broker, port) as mqttc: gateway = MQTTGateway( mqttc.publish, mqttc.subscribe, event_callback=handle_msg, **kwargs ) run_gateway(gateway)
33,138
def pprint(matrix: list) -> str: """ Preety print matrix string Parameters ---------- matrix : list Square matrix. Returns ------- str Preety string form of matrix. """ matrix_string = str(matrix) matrix_string = matrix_string.replace('],', '],\n') retu...
33,139
def sigmoid(x : np.ndarray, a : float, b : float, c : float) -> np.ndarray : """ A parameterized sigmoid curve Args: x (np.ndarray or float): x values to evaluate the sigmoid a (float): vertical stretch parameter b (float): horizontal shift parameter c (float): horizontal st...
33,140
def merge_testcase_data(leaf, statsname, x_axis): """ statsname might be a function. It will be given the folder path of the test case and should return one line. """ res = get_leaf_tests_stats(leaf, statsname) return merge_testcase_data_set_x(res, x_axis)
33,141
def get_account_ids(status=None, table_name=None): """return an array of account_ids from the Accounts table. Optionally, filter by status""" dynamodb = boto3.resource('dynamodb') if table_name: account_table = dynamodb.Table(table_name) else: account_table = dynamodb.Table(os.environ['A...
33,142
def dashed_word(answer): """ :param answer: str, from random_word :return: str, the number of '-' as per the length of answer """ ans = "" for i in answer: ans += '-' return ans
33,143
def main(urls, daemon): """Check url and print their HTTP statuses (w/ colors) :param urls: URL (or a tuple with multiple URLs) to check :type urls: str or tuple(str) :param daemon: If set to True, after checking all URLs, sleep for 5 seconds and check them again :type daemon: bo...
33,144
def merge_overpass_jsons(jsons): """Merge a list of overpass JSONs into a single JSON. Parameters ---------- jsons : :obj:`list` List of dictionaries representing Overpass JSONs. Returns ------- :obj:`dict` Dictionary containing all elements from input JSONS. """ el...
33,145
def identity_functions(function, args): """This function routes calls to sub-functions, thereby allowing a single identity function to stay hot for longer Args: function (str): for selection of function to call args: arguments to be passed to the selected function Retu...
33,146
def load_template(tmpl): """ Loads the default template file. """ with open(tmpl, "r") as stream: return Template(stream.read())
33,147
def calculate_id_name(message): """ Calculates hash value based on message. Useful for unique id - six hex characters. 6 digits - 16777216 permutations. TODO: check for hash collisions. """ hash_object = hashlib.md5(b'%s'% message) return hash_object.hexdigest()[0:5]
33,148
def get_total_cases(): """全国の現在の感染者数""" return col_ref.document(n).get().to_dict()["total"]["total_cases"]
33,149
def _find_db_team(team_id: OrgaTeamID) -> Optional[DbOrgaTeam]: """Return the team with that id, or `None` if not found.""" return db.session.query(DbOrgaTeam).get(team_id)
33,150
def make_number( num: Optional[str], repr: str = None, speak: str = None, literal: bool = False, special: dict = None, ) -> Optional[Number]: """Returns a Number or Fraction dataclass for a number string If literal, spoken string will not convert to hundreds/thousands NOTE: Numerators ...
33,151
def _readmapfile(fp, mapfile): """Load template elements from the given map file""" base = os.path.dirname(mapfile) conf = config.config() def include(rel, remap, sections): subresource = None if base: abs = os.path.normpath(os.path.join(base, rel)) if os.path.is...
33,152
async def scott_search(ctx, *args): """Grabs an SSC article at random if no arguments, else results of a Google search""" logging.info("scott command invocation: %s", args) await ctx.send(search_helper(args, "2befc5589b259ca98"))
33,153
def gif_jtfs_3d(Scx, jtfs=None, preset='spinned', savedir='', base_name='jtfs3d', images_ext='.png', cmap='turbo', cmap_norm=.5, axes_labels=('xi2', 'xi1_fr', 'xi1'), overwrite=False, save_images=False, width=800, height=800, surface_count=30, opacity=.2, ...
33,154
def PlotHillslopeDataWithBasins(DataDirectory,FilenamePrefix,PlotDirectory): """ Function to make plots of hillslope data vs basin id. Martin probably has nice versions of this but I need something quick for my poster Author: FJC """ # load the channel data ChannelData = Read...
33,155
def get_arguments(): """ Parse command line arguments :return Namespace: parsed arguments """ parser = ArgumentParser(description='') subparsers = parser.add_subparsers(help='sub-command help', dest='subparser_name') parser.add_argument( '-v', '--verbose', type=int, ...
33,156
def _serialize_account(project): """Generate several useful fields related to a project's account""" account = project.account return {'goal': account.goal, 'community_contribution': account.community_contribution, 'total_donated': account.total_donated(), 'total_raised':...
33,157
def _NodeThread(node_ip): """Check if this IP is a node""" log = GetLogger() SetThreadLogPrefix(node_ip) known_auth = [ ("admin", "admin"), ("admin", "solidfire") ] SFCONFIG_PORT = 442 sock = socket.socket() sock.settimeout(0.5) try: sock.connect((node_ip, ...
33,158
def configure_new_8_2_0_cluster(console_url, cluster_name, int_netmask, int_ip_low, int_ip_high, ext_netmask, ext_ip_low, ext_ip_high, gateway, dns_servers, encoding, sc_zonename, smartconnect_ip, compliance_license, logger): """Walk through the config Wiz...
33,159
def neighbor_smoothing_binary(data_3d, neighbors): """ takes a 3d binary (0/1) input, returns a "neighbor" smoothed 3d matrix Input: ------ data_3d: a 3d np.array (with 0s and 1s) -> 1s are "on", 0s are "off" neighbors: the value that indicates the number of neighbors around voxel to check Returns: -------...
33,160
def view( name = None, description = None, parameters = (), devel = False ): """ Decorator function to be used to "annotate" the provided function as an view that is able to return a set of configurations for the proper display of associated information. Proper usage of t...
33,161
def vprint(string): """Prints message if verbose is enabled""" if VERBOSE: print(string)
33,162
def pprint(j, no_pretty): """ Prints as formatted JSON """ if not no_pretty: echo(json.dumps(j, cls=PotionJSONEncoder, sort_keys=True, indent=4, separators=(',', ': '))) else: echo(j)
33,163
def _decode_response(resp_bytes: bytes) -> str: """Even though we request identity, rvm.io sends us gzip.""" try: # Try UTF-8 first, in case they ever fix their bug return resp_bytes.decode('UTF-8') except UnicodeDecodeError: with io.BytesIO(resp_bytes) as bytesio: with g...
33,164
def registrymixin_models(): """Fixtures for RegistryMixin tests.""" # We have two sample models and two registered items to test that # the registry is unique to each model and is not a global registry # in the base RegistryMixin class. # Sample model 1 class RegistryTest1(BaseMixin, db.Model):...
33,165
def delete_imgs(lower_quality_set: List[Path]): """ Function for deleting the lower quality images that were found after the search """ for file in lower_quality_set: print("\nDeletion in progress...") deleted = 0 try: file.unlink() print("Deleted file:", ...
33,166
def tabulate(*args, **kwargs): """Tabulate the output for pretty-printing. Usage: cat a.csv | ph tabulate --headers --noindex --format=grid Takes arguments * --headers * --noindex * --format=[grid, latex, pretty, ...]. For a full list of format styles confer the README. This fu...
33,167
def is_test_input_output_file(file_name: str) -> bool: """ Return whether a file is used as input or output in a unit test. """ ret = is_under_test_dir(file_name) ret &= file_name.endswith(".txt") return ret
33,168
def generate_csv_from_queryset(queryset, csv_name = "query_csv"): """ Genera un file csv a partire da un oggetto di tipo QuerySet :param queryset: oggetto di tipo QuerySet :param csv_name: campo opzionale per indicare il nome di output del csv :return: oggetto response """ try: resp...
33,169
def get(isamAppliance, id, check_mode=False, force=False, ignore_error=False): """ Retrieving the current runtime template files directory contents """ return isamAppliance.invoke_get("Retrieving the current runtime template files directory contents", "/mga/template_f...
33,170
def update(contxt, vsmapp_id, attach_status=None, is_terminate=False): """update storage pool usage""" if contxt is None: contxt = context.get_admin_context() if not vsmapp_id: raise exception.StoragePoolUsageInvalid() is_terminate = utils.bool_from_str(is_terminate) kargs = { ...
33,171
def adsgan(orig_data, params): """Generate synthetic data for ADSGAN framework. Args: orig_data: original data params: Network parameters mb_size: mini-batch size z_dim: random state dimension h_dim: hidden state dimension lamda: identifiability parameter iterations: trainin...
33,172
def unemployed(year,manu, key,state='*'): #ex manu= 54 is professional, scientific, and technical service industries, year= 2017 """Yearly data on self-employed manufacturing sectors for all counties. Returns all receipts in thousands of dollars for all counties for the specified state for certain industries. ...
33,173
def stack_bricks(top_brick, bottom_brick): """Stacks two Duplo bricks, returns the attachment frame of the top brick.""" arena = composer.Arena() # Bottom brick is fixed in place, top brick has a freejoint. arena.attach(bottom_brick) attachment_frame = arena.add_free_entity(top_brick) # Attachment frame is ...
33,174
def trigger(name): """ @trigger decorator allow to register a function as a trigger with a given name Parameters ---------- name : str Name of the trigger """ _app = get_app_instance() return _app.trigger(name)
33,175
def test_group_deduplication(): """Make sure groups are being deduplicated based on group name.""" e = Elements(owner=OWNER) e.create_group('Threat', 'Test threat') e.process() original_threat_count = len(e.get_items_by_type('threat')) # try to create an threat with the same name and make sure ...
33,176
def test_list_my_groups_as_support_user_with_ignore_access_true(list_my_groups_context): """ Test that we can get all the groups as a support user """ results = list_my_groups_context.support_user_client.list_my_groups(ignore_access=True, status=200) assert_that(len(results["groups"]), greater_than...
33,177
def test_inputs(): """Test input validation""" # Valid data model_eval = ModelEvaluation( y_true=np.random.randint(2, size=100), y_pred=np.random.randint(2, size=100), model_name='foo', ) model_eval = ModelEvaluation( y_true=list(range(100)), y_pred=list(rang...
33,178
def get_components_to_remove(component_dict: Dict[str, ComponentImport]) -> List[str]: """Gets a list of components to remove from the dictionary using console input. Args: component_dict (Dict[str, ComponentImport]): The custom component dictionary. Returns: List[str]: The keys to remove ...
33,179
def list_data_objects(): """ This endpoint translates DOS List requests into requests against indexd and converts the responses into GA4GH messages. :return: """ req_body = app.current_request.json_body if req_body: page_token = req_body.get('page_token', None) page_size = r...
33,180
def get_include_file_start_line(block: Block) -> Union[int, None]: """ >>> block = lib_test.get_test_block_ok() >>> # test start-line set to 10 >>> get_include_file_start_line(block) 10 >>> assert block.include_file_start_line == 10 >>> # test start-line not set >>> block = lib_test.get...
33,181
def get_wcets(utils, periods): """ Returns WCET """ return [ui * ti for ui, ti in zip(utils, periods)] # return [math.ceil(ui * ti) for ui, ti in zip(utils, periods)]
33,182
def aws_get_dynamodb_table_names(profile_name: str) -> list: """ get all DynamoDB tables :param profile_name: AWS IAM profile name :return: a list of DynamoDB table names """ dynamodb_client = aws_get_client("dynamodb", profile_name) table_names = [] more_to_evaluate = True last_ev...
33,183
def stack_images_vertical( image_0: NDArray[(Any, ...), Any], image_1: NDArray[(Any, ...), Any] ) -> NDArray[(Any, ...), Any]: """ Stack two images vertically. Args: image_0: The image to place on the top. image_1: The image to place on the bottom. Returns: An image with th...
33,184
def documents(*sources): """fooo""" # ipdb.set_trace() docs = [] q = DocumentModel.objects.timeout(500).allow_filtering().all().limit(1000) querysets = (q.filter(source=source) for source in sources) if sources else [q] for query in querysets: page = try_forever(list, query) wh...
33,185
def simulate_ids(num): """ 模拟生成一定数量的身份证号 """ ids = [] if num > 0: for i in range(1, num+1): id_raw = digit_1to6() + digit_7to10() + digit_11to14() + digit_15to17() id = id_raw + digit_18(id_raw) ids.append(id) else: return False return ids
33,186
def geomean(x): """computes geometric mean """ return exp(sum(log(i) for i in x) / len(x))
33,187
def _get_mean_traces_for_iteration_line_plot( scenario_df: pd.DataFrame, ) -> Tuple[go.Scatter, go.Scatter, go.Scatter]: """Returns the traces for the mean of the success rate. Parameters ---------- scenario_df : pd.DataFrame DataFrame containing the columns "n_iterations", "mean_success_ra...
33,188
def create_graph_of_words(words, database, filename, window_size = 4): """ Function that creates a Graph of Words that contains all nodes from each document for easy comparison, inside the neo4j database, using the appropriate cypher queries. """ # Files that have word length < window size, a...
33,189
def get_dir(path): """ Функция возвращает директорию файла, если он является файлом, иначе возвращает объект Path из указанного пути """ if not isinstance(path, Path): path = Path(path) return path.parent if path.is_file() else path
33,190
def test_downloads_correct_zipfile( bite_number: int, bites_repo_dir: Path, testing_config, ) -> None: """Download a ZIP archive file for a specific bite with correct credentials. Credentials are obtained either from the environment or the the .env located in the directory pytest was launched i...
33,191
def get_file_sha(fname): """ Calculates the SHA1 of a given file. `fname`: the file path return: the calculated SHA1 as hex """ result = '' if isfile(fname): sha1 = hashlib.sha1() with open(fname, 'rb') as f: while True: data = f.read(BUF_SIZE) ...
33,192
def graphtool_to_gjgf(graph): """Convert a graph-tool graph object to gJGF. Parameters ---------- graph : graph object from graph-tool Returns ------- gjgf : dict Dictionary adhering to :doc:`gravis JSON Graph Format (gJGF) <../../format_specification>` Caution ---...
33,193
def forbidden_error(error): """ 418 I'm a teapot """ return engine.get_template('errors/417.html').render({}), 418
33,194
def set(msg_or_dict, key, value): """Set a key's value on a protobuf Message or dictionary. Args: msg_or_dict (Union[~google.protobuf.message.Message, Mapping]): the object. key (str): The key to set. value (Any): The value to set. Raises: TypeError: If ``msg_or...
33,195
def green(s: str) -> str: """green(s) color s with green. This function exists to encapsulate the coloring methods only in utils.py. """ return colorama.Fore.GREEN + s + colorama.Fore.RESET
33,196
def show_failed_samples(grading_data_dir_name, subset_name, num_of_samples = 100, run_num = 'run_1'): """Predicted Samples Viewer""" # Count all iamges path = os.path.join('..', 'data', grading_data_dir_name) ims = np.array(plotting_tools.get_im_files(path, subset_name)) print('All images: ', l...
33,197
def plot_confusion_matrix(label_list, pred_list, classes,dir_out, normalize=True, title='Confusion matrix', cmap=plt.cm.Blues): """ This function prints and saves the plot of the confusion matrix. Normalization can be applied by s...
33,198
def get_files(self): """func to loop through all the files and buildings and add them to the table widget for selection""" # # function to reset the table IMPORTANT # resultsDict = {} if os.path.isfile(self.inpPath): # case for single file resultsDict[os.path.basename(self.inpPat...
33,199