content
stringlengths
22
815k
id
int64
0
4.91M
def _makeSSDF(row, minEvents): """ Function to change form of TRDF for subpace creation """ index = range(len(row.Clust)) columns = [x for x in row.index if x != 'Clust'] DF = pd.DataFrame(index=index, columns=columns) DF['Name'] = ['SS%d' % x for x in range(len(DF))] # name subspaces #...
1,800
def save_checkpoint(logdir, epoch, global_step, model, optimizer): """Saves the training state into the given log dir path.""" checkpoint_file_name = os.path.join(logdir, 'step-%03dK.pth' % (global_step // 1000)) print("saving the checkpoint file '%s'..." % checkpoint_file_name) checkpoint = { '...
1,801
def concatenate_constraints(original_set, additional_set): """ Method for concatenating sets of linear constraints. original_set and additional_set are both tuples of for (C, b, n_eq). Output is a concatenated tuple of same form. All equality constraints are always kept on top. """ C...
1,802
def _isDefaultHandler(): """ Determine whether the I{SIGCHLD} handler is the default or not. """ return signal.getsignal(signal.SIGCHLD) == signal.SIG_DFL
1,803
def downsampling(conversion_rate,data,fs): """ ダウンサンプリングを行う. 入力として,変換レートとデータとサンプリング周波数. アップサンプリング後のデータとサンプリング周波数を返す. """ # 間引くサンプル数を決める decimationSampleNum = conversion_rate-1 # FIRフィルタの用意をする nyqF = (fs/conversion_rate)/2.0 # 変換後のナイキスト周波数 cF = (fs/conversion_rate/2.0...
1,804
def get_client_cache_key( request_or_attempt: Union[HttpRequest, AccessBase], credentials: dict = None ) -> str: """ Build cache key name from request or AccessAttempt object. :param request_or_attempt: HttpRequest or AccessAttempt object :param credentials: credentials containing user information ...
1,805
def test_empty_schema() -> None: """Test that SchemaModel supports empty schemas.""" empty_schema = pa.DataFrameSchema() class EmptySchema(pa.SchemaModel): pass assert empty_schema == EmptySchema.to_schema() class Schema(pa.SchemaModel): a: Series[int] class EmptySubSchema(S...
1,806
def loadMaterials(matFile): """ Loads materials into Tom's code from external file of all applicable materials. These are returned as a dictionary. """ mats = {} name, no, ne, lto, lte, mtype = np.loadtxt(matFile, dtype=np.str, unpack=True) no = np.array(list(map(np.float, no))) ...
1,807
def prepend_with_baseurl(files, base_url): """prepend url to beginning of each file Parameters ------ files (list): list of files base_url (str): base url Returns ------ list: a list of files with base url pre-pended """ return [base_url + file for file in files]
1,808
def streamplot( x, y, u, v, p=None, density=1, color="#1f77b4", line_width=None, alpha=1, arrow_size=7, min_length=0.1, start_points=None, max_length=4.0, integration_direction="both", arrow_level="underlay", **kwargs, ): """Draws streamlines of a vect...
1,809
def wait_for_workspace_to_start(self, *, workspace_pk): """Checks if the workspace is up for up to 10 minutes.""" workspace = Workspace.objects.get(pk=workspace_pk) if workspace.status != WorkspaceStatus.PENDING: # Nothing to do return with requests.Session() as s: _authorise(c...
1,810
def _loc(df, start, stop, include_right_boundary=True): """ >>> df = pd.DataFrame({'x': [10, 20, 30, 40, 50]}, index=[1, 2, 2, 3, 4]) >>> _loc(df, 2, None) x 2 20 2 30 3 40 4 50 >>> _loc(df, 1, 3) x 1 10 2 20 2 30 3 40 >>> _loc(df, 1, 3, inclu...
1,811
def test_legacy_yaml(tmpdir, install_mockery, mock_packages): """Tests a simple legacy YAML with a dependency and ensures spec survives concretization.""" yaml = """ spec: - a: version: '2.0' arch: platform: linux platform_os: rhel7 target: x86_64 compiler: name: gcc ...
1,812
def compare_system_and_attributes_faulty_systems(self): """compare systems and associated attributes""" # compare - systems / attributes self.assertTrue(System.objects.filter(system_name='system_csv_31_001').exists()) self.assertTrue(System.objects.filter(system_name='system_csv_31_003').exists()) ...
1,813
def editPostgresConf(): """ edit /var/lib/pgsql/data/postgresql.conf and change max_connections to 150 """ try: tempFile = tempfile.mktemp(dir="/tmp") logging.debug("copying %s over %s", basedefs.FILE_PSQL_CONF, tempFile) shutil.copy2(basedefs.FILE_PSQL_CONF, tempFile) ...
1,814
def get_regions(contig,enzymes): """return loci with start and end locations""" out_sites = [] enz_1 = [enz for enz in Restriction.AllEnzymes if "%s"%enz == enzymes[0]][0] enz_2 = [enz for enz in Restriction.AllEnzymes if "%s"%enz == enzymes[1]][0] enz_1_sites = enz_1.search(contig.seq) enz_2_si...
1,815
def getHighContrast(j17, j18, d17, d18): """ contrast enhancement through stacking """ summer = j17 + j18 summer = summer / np.amax(summer) winter = d17 + d18 winter = winter / np.amax(winter) diff = winter * summer return diff
1,816
def get_bounding_box(dataframe, dataIdentifier): """Returns the rectangle in a format (min_lat, max_lat, min_lon, max_lon) which bounds all the points of the ´dataframe´. Parameters ---------- dataframe : pandas.DataFrame the dataframe with the data dataIdentifier : DataIdentifier ...
1,817
def get_file_download_response(dbfile): """ Create the HttpResponse for serving a file. The file is not read our output - instead, by setting `X-Accel-Redirect`- header, the web server (nginx) directly serves the file. """ mimetype = dbfile.mimeType response = HttpResponse(content_type=mim...
1,818
def keyWait(): """Waits until the user presses a key. Then returns a L{KeyDown} event. Key events will repeat if held down. A click to close the window will be converted into an Alt+F4 KeyDown event. @rtype: L{KeyDown} """ while 1: for event in get(): if ev...
1,819
def create_project( org_id: str, api_key: str, url: str, label_type: LabelType, taxonomy: str = "DEFAULT::Berkeley Deep Drive (BDD)", reviews: int = 1, ) -> Generator[Tuple[str, RBProject], None, None]: """Create project.""" profile = datetime.strftime(datetime.now(), "%Y%m%d%H%M%S%f") +...
1,820
def create_comentarios_instancia(id_instancia): """ @retorna un ok en caso de que se halla ejecutado la operacion @except status 500 en caso de presentar algun error """ from datetime import datetime if request.method == 'POST': try: values = json.loads( request.data.decode('8859') ) mensaje = val...
1,821
def callEvalGen(args: argparse.Namespace): """ Method for evaluation of the keywords generation task on the Inspec dataset. :param args: User arguments. :type args: argparse.Namespace """ return evalOn(args, "uncontr")
1,822
async def osfrog(msg, mobj): """ Patch 7.02: help string was removed from Captain's Mode """ osfrogs = [ "Added Monkey King to the game", "Reduced Lone Druid's respawn talent -50s to -40s", ] return await client.send_message(mobj.channel, choice(osfrogs))
1,823
def _add_normalizing_vector_point(mesh, minpt, maxpt): """ This function allows you to visualize all meshes in their size relative to each other It is a quick simple hack: by adding 2 vector points at the same x coordinates at the extreme left and extreme right of the largest .stl mesh, all the meshes a...
1,824
def run(): """ function to start flask apps""" host = os.getenv("HOST") or '127.0.0.1' app.run(host=host)
1,825
def radii_ratio(collection): """ The Flaherty & Crumplin (1992) index, OS_3 in Altman (1998). The ratio of the radius of the equi-areal circle to the radius of the MBC """ ga = _cast(collection) r_eac = numpy.sqrt(pygeos.area(ga) / numpy.pi) r_mbc = pygeos.minimum_bounding_radius(ga) re...
1,826
def create_jwt(project_id, private_key_file, algorithm): """Create a JWT (https://jwt.io) to establish an MQTT connection.""" token = { 'iat': datetime.datetime.utcnow(), 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60), 'aud': project_id } with open(private_key...
1,827
def update_analytics(node, file, version_idx, action='download'): """ :param Node node: Root node to update :param str file_id: The _id field of a filenode :param int version_idx: Zero-based version index :param str action: is this logged as download or a view """ # Pass in contributors and ...
1,828
def games(engine1, engine2, number_of_games): """Let engine1 and engine2 play several games against each other. Each begin every second game.""" engine1_wins = 0 engine2_wins = 0 draws = 0 for n in range(number_of_games): if n % 2: result = game(engine1, engine2, True) ...
1,829
def tissue2line(data, line=None): """tissue2line Project tissue probability maps to the line by calculating the probability of each tissue type in each voxel of the 16x720 beam and then average these to get a 1x720 line. Discrete tissues are assigned by means of the highest probability of a particular tissue t...
1,830
def get_version(pyngrok_config=None): """ Get a tuple with the ``ngrok`` and ``pyngrok`` versions. :param pyngrok_config: A ``pyngrok`` configuration to use when interacting with the ``ngrok`` binary, overriding :func:`~pyngrok.conf.get_default()`. :type pyngrok_config: PyngrokConfig, optional ...
1,831
def stat_cleaner(stat: str) -> int: """Cleans and converts single stat. Used for the tweets, followers, following, and likes count sections. Args: stat: Stat to be cleaned. Returns: A stat with commas removed and converted to int. """ return int(stat.replace(",", ""))
1,832
def load_image_ids(img_root, split_dir): """images in the same directory are in the same split""" pathXid = [] img_root = os.path.join(img_root, split_dir) for name in os.listdir(img_root): idx = name.split(".")[0] pathXid.append( ( os.path.join(img_ro...
1,833
def do(ARGV): """Allow to check whether the exception handlers are all in place. """ if len(ARGV) != 3: return False elif ARGV[1] != "<<TEST:Exceptions/function>>" \ and ARGV[1] != "<<TEST:Exceptions/on-import>>": return False if len(ARGV) < 3: return False exception = A...
1,834
def get_available_language_packs(): """Get list of registered language packs. :return list: """ ensure_autodiscover() return [val for (key, val) in registry.registry.items()]
1,835
def _plot_topo_onpick(event, show_func=None, colorbar=False): """Onpick callback that shows a single channel in a new figure""" # make sure that the swipe gesture in OS-X doesn't open many figures orig_ax = event.inaxes if event.inaxes is None: return import matplotlib.pyplot as plt tr...
1,836
def topo_star(jd_tt, delta_t, star, position, accuracy=0): """ Computes the topocentric place of a star at 'date', given its catalog mean place, proper motion, parallax, and radial velocity. Parameters ---------- jd_tt : float TT Julian date for topocentric place. delta_t : float ...
1,837
def py_multiplicative_inverse(a, n): """Multiplicative inverse of a modulo n (in Python). Implements extended Euclidean algorithm. Args: a: int-like np.ndarray. n: int. Returns: Multiplicative inverse as an int32 np.ndarray with same shape as a. """ batched_a = n...
1,838
def _get_simconffile(args): """ Get experiment config file name from command line """ logger = logging.getLogger('fms') try: simconffile = args[1] except IndexError: logger.critical("Missing simulation config file name.") sys.exit(2) return simconffile
1,839
def resample_nearest_neighbour(input_tif, extents, new_res, output_file): """ Nearest neighbor resampling and cropping of an image. :param str input_tif: input geotiff file path :param list extents: new extents for cropping :param float new_res: new resolution for resampling :param str output_f...
1,840
def test_al_validation_third_digit_corresponds_to_type_of_company(): """Test if invalid when the third digit is different to 0_3_5_7_8""" invalid_number = '172030964' assert al.start(invalid_number) == False
1,841
def AptInstall(vm): """Installs the Mellanox OpenFabrics driver on the VM.""" _Install(vm)
1,842
def harvester_api_info(request, name): """ This function returns the pretty rendered api help text of an harvester. """ harvester = get_object_or_404(Harvester, name=name) api = InitHarvester(harvester).get_harvester_api() response = api.api_infotext() content = response.data[harvester.n...
1,843
def init_db(): """Open SQLite database, create facebook table, return connection.""" db = sqlite3.connect('facebook.sql') cur = db.cursor() cur.execute(SQL_CREATE) db.commit() cur.execute(SQL_CHECK) parse = list(cur.fetchall())[0][0] == 0 return db, cur, parse
1,844
def prime_gen(): """Returns prime based on 172 bit range. Results is 44 char""" x = subprocess.run( ['openssl', 'prime', '-generate', '-bits', '172', '-hex'], stdout=subprocess.PIPE) return x.stdout[:-1]
1,845
def aggregate_gradients_using_copy_with_variable_colocation( tower_grads, use_mean, check_inf_nan): """Aggregate gradients, colocating computation with the gradient's variable. Args: tower_grads: List of lists of (gradient, variable) tuples. The outer list is over towers. The inner list is over indiv...
1,846
def module_for_category( category ): """Return the OpenGL.GL.x module for the given category name""" if category.startswith( 'VERSION_' ): name = 'OpenGL.GL' else: owner,name = category.split( '_',1) if owner.startswith( '3' ): owner = owner[1:] name = 'OpenGL.GL....
1,847
def check_file_location(file_path, function, file_ext='', exists=False): """Function to check whether a file exists and has the correct file extension""" folder, file, ext = '', '', '' if file_path == '': exit_prompt('Error: Could not parse path to {} file'.format(function)) try: f...
1,848
def timestamp() -> str: """generate formatted timestamp for the invocation moment""" return dt.now().strftime("%d-%m-%Y %H:%M:%S")
1,849
def test_serder(): """ Test the support functionality for Serder key event serialization deserialization """ with pytest.raises(ValueError): serder = Serder() e1 = dict(vs=Vstrings.json, pre="ABCDEFG", sn="0001", ilk="rot") serder = Serder(ked=e1) assert serder.ked == e1 assert ...
1,850
def sde(trains, events=None, start=0 * pq.ms, stop=None, kernel_size=100 * pq.ms, optimize_steps=0, minimum_kernel=10 * pq.ms, maximum_kernel=500 * pq.ms, kernel=None, time_unit=pq.ms, progress=None): """ Create a spike density estimation plot. The spike density estimations give an esti...
1,851
def content(obj): """Strip HTML tags for list display.""" return strip_tags(obj.content.replace('</', ' </'))
1,852
def main(): """ main() """ action = get_cmd_param(1) if action == 'soup': keyword = get_cmd_param( 2, 'https://tw.news.appledaily.com/local/realtime/20181025/1453825') soup(keyword) elif action == 'search': keyword = get_cmd_param(2, '酒駕') channel = ge...
1,853
def flux(Q, N, ne, Ap, Am): """ calculates the flux between two boundary sides of connected elements for element i """ # for every element we have 2 faces to other elements (left and right) out = np.zeros((ne, N + 1, 2)) # Calculate Fluxes inside domain for i in range(1, ne - 1): ...
1,854
def cp_dir(src_dir, dest_dir): """Function: cp_dir Description: Copies a directory from source to destination. Arguments: (input) src_dir -> Source directory. (input) dest_dir -> Destination directory. (output) status -> True|False - True if copy was successful. (output)...
1,855
def listnet_loss(y_i, z_i): """ y_i: (n_i, 1) z_i: (n_i, 1) """ P_y_i = F.softmax(y_i, dim=0) P_z_i = F.softmax(z_i, dim=0) return - torch.sum(y_i * torch.log(P_z_i))
1,856
def get_volume_parameters(volumes): """Create pipeline parameters for volumes to be mounted on pipeline steps. Args: volumes: a volume spec Returns (dict): volume pipeline parameters """ volume_parameters = dict() for v in volumes: if v['type'] == 'pv': # FIXME: How...
1,857
def _process_active_tools(toolbar, tool_map, active_drag, active_inspect, active_scroll, active_tap): """ Adds tools to the plot object Args: toolbar (Toolbar): instance of a Toolbar object tools_map (dict[str]|Tool): tool_map from _process_tools_arg active_drag (str or Tool): the tool ...
1,858
def normalize(data, **kw): """Calculates the normalization of the given array. The normalizated array is returned as a different array. Args: data The data to be normalized Kwargs: upper_bound The upper bound of the normalization. It has the value of 1 by default. lower...
1,859
def relative_sse(cp_tensor, X, sum_squared_X=None): """Compute the relative sum of squared error for a given cp_tensor. Parameters ---------- cp_tensor : CPTensor or tuple TensorLy-style CPTensor object or tuple with weights as first argument and a tuple of components as second argument...
1,860
def setup_ceilometer_compute(): """Provisions ceilometer compute services in all nodes defined in compute role.""" if env.roledefs['compute']: execute("setup_ceilometer_compute_node", env.host_string)
1,861
def set_elixier_item_status(item, status): """ .. aendert den Status des Elixier-Beitrags """ #id = item.id_local item.status = status item.save()
1,862
def test_enamble_stat_datatype(data): """ make sure, that the wron data type will rais an exception """ with pytest.raises(ValueError): _ = ensemble_stat(data.values)
1,863
def cc_across_time(tfx, tfy, cc_func, cc_args=()): """Cross correlations across time. Args: tfx : time-frequency domain signal 1 tfy : time-frequency domain signal 2 cc_func : cross correlation function. cc_args : list of extra arguments of cc_func. Returns: ...
1,864
def transcribe(args, client, site_id): """Transcribe one or more WAV files using hermes/asr""" from .asr import AsrStartListening, AsrStopListening, AsrTextCaptured from .audioserver import AudioFrame client.subscribe(AsrTextCaptured.topic()) frame_topic = AudioFrame.topic(site_id=site_id) if ...
1,865
def predict_encoding(file_path, n_lines=20): """Predict a file's encoding using chardet""" import chardet # Open the file as binary data with open(file_path, "rb") as f: # Join binary lines for specified number of lines rawdata = b"".join([f.readline() for _ in range(n_lines)]) ret...
1,866
def redirect_handler(url, client_id, client_secret, redirect_uri, scope): """ Convenience redirect handler. Provide the redirect url (containing auth code) along with client credentials. Returns a spotify access token. """ auth = ExtendedOAuth( client_id, client_secret, redirect_uri,...
1,867
def convert_coordinate(coordinate): """ :param coordinate: str - a string map coordinate :return: tuple - the string coordinate seperated into its individual components. """ coord = (coordinate[0], coordinate[1]) return coord
1,868
def tree_falls(geo_index, shps, CHMs,savedir="."): """Find predictions that don't match accross years, where there is significant height drop among years geo_index: NEON geoindex to process shps: List of shapefiles to search CHMs: List of canopy height models to search """ #Find matching shapefi...
1,869
def split_multi_fasta_into_fasta(fasta_file, output_directory): """ Splits a single multi-FASTA-format file into individual FASTA-format files, each containing only one FASTA record. PARAMETERS fasta_file (str): the file location of the FASTA file output_directory (str): the output director...
1,870
def get_noun_phrases(doc: Doc) -> List[Span]: """Compile a list of noun phrases in sense2vec's format (without determiners). Separated out to make it easier to customize, e.g. for languages that don't implement a noun_chunks iterator out-of-the-box, or use different label schemes. doc (Doc): The Do...
1,871
def load_file_from_url(url): """Load the data from url.""" url_path = get_absolute_url_path(url, PATH) response = urlopen(url_path) contents = json.loads(response.read()) return parse_file_contents(contents, url_path.endswith(".mrsys"))
1,872
def speedPunisherMin(v, vmin): """ :param v: :param vmin: :return: """ x = fmin(v - vmin, 0) return x ** 2
1,873
def initialize_ecr_client(): """ Initializes the ECR CLient. If running in Lambda mode, only the AWS REGION environment variable is needed. If not running in Lambda mode, the AWS credentials are also needed. """ if(os.environ.get('MODE') == 'lambda'): ecrClient = boto3.client('ecr', region_n...
1,874
def hexagonal_packing_cross_section(nseeds, Areq, insu, out_insu): """ Make a hexagonal packing and scale the result to be Areq cross section Parameter insu must be a percentage of the strand radius. out_insu is the insulation thickness around the wire as meters Returns: (wire diameter...
1,875
def bk(): """ Returns an RGB object representing a black pixel. This function is created to make smile() more legible. """ return introcs.RGB(0,0,0)
1,876
def autoEpochToTime(epoch): """ Converts a long offset from Epoch value to a DBDateTime. This method uses expected date ranges to infer whether the passed value is in milliseconds, microseconds, or nanoseconds. Thresholds used are TimeConstants.MICROTIME_THRESHOLD divided by 1000 for milliseconds, as-...
1,877
def _write(fname, reqs): """Dump requirements back to a file in sorted format.""" reqs = sorted(reqs, key=sort_key) with open(fname, "w") as f: for r in reqs: f.write(f"{r}\n")
1,878
def compile_recursive_descent(file_lines, *args, **kwargs): """Given a file and its lines, recursively compile until no ksx statements remain""" visited_files = kwargs.get('visited_files', set()) # calculate a hash of the file_lines and check if we have already compiled # this one file_hash = hash_...
1,879
def cl_user(client): # pylint: disable=redefined-outer-name """yield client authenticated to role user""" yield client_in_roles(client, ['user'])
1,880
def majority_voting(masks, voting='hard', weights=None, threshold=0.5): """Soft Voting/Majority Rule mask merging; Signature based upon the Scikit-learn VotingClassifier (https://github.com/scikit-learn/scikit-learn/blob/2beed55847ee70d363bdbfe14ee4401438fba057/sklearn/ensemble/_voting.py#L141) Parameters ...
1,881
def send_msg(content): """ 发送消息 :param content: 消息内容 :return: """ (url, data, field) = __read_data() if not url or not data: print "url={0}, data={1}".format(url, data) return headers = {'Content-Type': 'application/json'} json_content = json.loads(data) json_cont...
1,882
def animate(zdata, xdata, ydata, conversionFactorArray, timedata, BoxSize, timeSteps=100, filename="particle"): """ Animates the particle's motion given the z, x and y signal (in Volts) and the conversion factor (to convert ...
1,883
def name_of_decompressed(filename): """ Given a filename check if it is in compressed type (any of ['.Z', '.gz', '.tar.gz', '.zip']; if indeed it is compressed return the name of the uncompressed file, else return the input filename. """ dct = { '.Z': re.compile('.Z$'), '.tar.gz...
1,884
def sample_distribution(distribution): """Sample one element from a distribution assumed to be an array of normalized probabilities. """ r = random.uniform(0, 1) s = 0 for i in range(len(distribution)): s += distribution[i] if s >= r: return i return len(distribution) - 1
1,885
def benchmark(func): """Decorator to mark a benchmark.""" BENCHMARKS[func.__name__] = func return func
1,886
def write_gvecs(fp, gvecs, kpath='/electrons/kpoint_0'): """ fill the electrons/kpoint_0/gvectors group in wf h5 file Args: fp (h5py.File): hdf5 file object gvecs (np.array): PW basis as integer vectors kpath (str, optional): kpoint group to contain gvecs, default is '/electrons/kpoint_0' Examp...
1,887
def do_positive_DFT(data_in, tmax): """ Do Discrete Fourier transformation and take POSITIVE frequency component part. Args: data_in (array): input data. tmax (float): sample frequency. Returns: data_s (array): output array with POSITIVE frequency component part. data_w (...
1,888
def test_load_extension_valid(import_path: str) -> None: """It loads the extension.""" extension = load_extension(import_path) assert issubclass(extension, jinja2.ext.Extension)
1,889
def scroll_down(driver): """Scrolling the page for pages with infinite scrolling""" loading_thread = threading.Thread(target=loading) loading_thread.start() # Get scroll height. last_height = driver.execute_script("return document.body.scrollHeight") while True: # Scroll down to the bott...
1,890
def service(base_app, location): """Service fixture.""" return base_app.extensions["invenio-records-lom"].records_service
1,891
def test_is_divisible_by_6(s, result): """Test function returns expected result.""" from divisible_by_6 import is_divisible_by_6 assert is_divisible_by_6(s) == result
1,892
def check_file_content(path, expected_content): """Check file has expected content. :param str path: Path to file. :param str expected_content: Expected file content. """ with open(path) as input: return expected_content == input.read()
1,893
def get_arguments(deluge=False): """Retrieves CLI arguments from the 'addmedia' script and uses get_parser() to validate them. Returns the full file path to the config file in use and a dict of validated arguments from the MHParser object. """ # Check for deluge if deluge: return g...
1,894
def verify_apikey(payload, raiseonfail=False, override_authdb_path=None, override_permissions_json=None, config=None): """Checks if an API key is valid. This version does not require a session. Parameters ---------- payload :...
1,895
def merge_image_data(dir_dict, output_image_file, logg): """ Merge image data in dir_dict. Parameters ---------- base_dir : str base directory of dir_dict dir_dict : dictionary containing pairs of directories and associated files output_image_file : str output image file string Returns...
1,896
def save_model(file_name_base, model): """Save and convert Keras model""" keras_file = f'{file_name_base}.h5' fdeep_file = f'{file_name_base}.json' print(f'Saving {keras_file}') model.save(keras_file, include_optimizer=False) print(f'Converting {keras_file} to {fdeep_file}.') convert_model.c...
1,897
def case_mc2us(x): """ mixed case to underscore notation """ return case_cw2us(x)
1,898
def _parse_arguments(): """ Constructs and parses the command line arguments for eg. Returns an args object as returned by parser.parse_args(). """ parser = argparse.ArgumentParser( description='eg provides examples of common command usage.' ) parser.add_argument( '-v', ...
1,899