content
stringlengths
22
815k
id
int64
0
4.91M
def lstm_cond_layer(tparams, state_below, options, prefix='lstm', mask=None, init_memory=None, init_state=None, trng=None, use_noise=None, **kwargs): """ Computation graph for the conditional LSTM. """ nsteps = state_below.shape[0] n_sample...
5,311,300
def get_frame_tree() -> Generator[dict, dict, FrameTree]: """Returns present frame tree structure. Returns ------- frameTree: FrameTree Present frame tree structure. """ response = yield {"method": "Page.getFrameTree", "params": {}} return FrameTree.from_json(response["frameTree...
5,311,301
def lddmm_transform_points( points, deform_to="template", # lddmm_register output (lddmm_dict). affine_phi=None, phi_inv_affine_inv=None, template_resolution=1, target_resolution=1, **unused_kwargs, ): """ Apply the transform, or position_field, to an array of points to transform...
5,311,302
def check_sanitization(mol): """ Given a rdkit.Chem.rdchem.Mol this script will sanitize the molecule. It will be done using a series of try/except statements so that if it fails it will return a None rather than causing the outer script to fail. Nitrogen Fixing step occurs here to correct for a co...
5,311,303
def build_parser(): """Parser to grab and store command line arguments""" MINIMUM = 200000 SAVEPATH = "data/raw/" parser = argparse.ArgumentParser() parser.add_argument( "subreddit", help="Specify the subreddit to scrape from") parser.add_argument("-m", "--minimum", ...
5,311,304
def extract_msg(log: str, replica_name: str) -> Union[str, None]: """ Extracts a message from a single log Parameters ---------- log full log string replica_name identity name of replica Returns ------- msg message sent from primary to replica """ pa...
5,311,305
def tf_dmdm_fid(rho, sigma): """Trace fidelity between two density matrices.""" # TODO needs fixing rhosqrt = tf.linalg.sqrtm(rho) return tf.linalg.trace( tf.linalg.sqrtm(tf.matmul(tf.matmul(rhosqrt, sigma), rhosqrt)) )
5,311,306
def LF_report_is_short_demo(x): """ Checks if report is short. """ return NORMAL if len(x.text) < 280 else ABSTAIN
5,311,307
def test_segmented_crossover(): """ test that k-ary crossover works as expected for fixed and variable length segments """ a = Individual([[0, 0], [1, 1]]) b = Individual([[1, 1], [0, 0]]) result = n_ary_crossover(iter([a,b])) c = next(result) d = next(result) possible_outcomes...
5,311,308
def configure(dbconf=None, unpack_password=None): """ Configure the databases :Parameters: `dbconf` : ``str`` Config file name. If omitted or ``None``, the environment variable ``WTF_EXT_DB_CONF`` is queried. If that's unset, too, it defaults to ``%r``. `unpack_password...
5,311,309
def binarize_swf( scores: SlidingWindowFeature, onset: float = 0.5, offset: float = 0.5, initial_state: Optional[bool] = None, ): """(Batch) hysteresis thresholding Parameters ---------- scores : SlidingWindowFeature (num_chunks, num_frames, num_classes)- or (num_frames, num_cla...
5,311,310
def writeConfig(force=False, storeRemote=True): """category: General Utility Functions Commit the config to disk/cloud/etc""" bsConfig = bs.getConfig() global gConfigFileIsHealthy if not gConfigFileIsHealthy and not force: print ("Current config file is broken; " "skipping wr...
5,311,311
def invlogit(x, eps=sys.float_info.epsilon): """The inverse of the logit function, 1 / (1 + exp(-x)).""" return (1.0 - 2.0 * eps) / (1.0 + tt.exp(-x)) + eps
5,311,312
def test_main(): """Placeholder for tests.""" assert watchmaker.__version__ == watchmaker.__version__
5,311,313
def test_derivative_multiple_input_single_output_graph_mode(): """ Features: Function derivative Description: Test derivative with multiple inputs in graph mode. Expectation: No exception. """ primals = (Tensor([1., 1.]), Tensor([1., 1.])) order = 3 net = MultipleInputSingleOutputNet() ...
5,311,314
def temporary_project(name='dx client tests temporary project', cleanup=True, reclaim_permissions=False, select=False, region=None, **kwargs): """Creates a temporary project scoped to the context manager, and yields a DXProject handler for the project. :param cleanup: if False...
5,311,315
def train_pytorch_ch7(optimizer_fn, optimizer_hyperparams, features, labels, batch_size=10, num_epochs=2): """ The training function of chapter7, but this is the pytorch library version Parameters ---------- optimizer_fn : [function] the optimizer function that wants t...
5,311,316
def ProcessOptionInfileParameters(ParamsOptionName, ParamsOptionValue, InfileName = None, OutfileName = None): """Process parameters for reading input files and return a map containing processed parameter names and values. Arguments: ParamsOptionName (str): Command line input parameters option ...
5,311,317
def user_annotation_for_application() -> UserInputClass: """ Make info from user annotation 1. Original File 2. VM Runtime configuration 3. Target Goal 3. Function service with parameters """ # Fist make dataclass and save default values user_input_class = UserInputClass() # In...
5,311,318
def brier_score(y_true, y_pred): """Brier score Computes the Brier score between the true labels and the estimated probabilities. This corresponds to the Mean Squared Error between the estimations and the true labels. Parameters ---------- y_true : label indicator matrix (n_samples, n_clas...
5,311,319
def log_done(): """Styling for a block done log statement""" print(" - Done!\n")
5,311,320
def computeD1D2(current: float, volatility: float, ttm: float, strike: float, rf: float) -> Tuple[float, float]: """Helper function to compute the risk-adjusted priors of exercising the option contract, and keeping the underlying asset. This is used in the computation of both the Call and Pu...
5,311,321
def read_trace_data(filename, cpu_mask): """ Read and parse trace data """ global current_max_cpu global sample_num, last_sec_cpu, last_usec_cpu, start_time try: data = open(filename, 'r').read() except: print('Error opening ', filename) sys.exit(2) for line in data.sp...
5,311,322
def control_event(data_byte1, data_byte2=0, channel=1): """Return a MIDI control event with the given data bytes.""" data_byte1 = muser.utils.key_check(data_byte1, CONTROL_BYTES, 'upper') return (STATUS_BYTES['CONTROL'] + channel - 1, data_byte1, data_byte2)
5,311,323
def create_noise_mask(mean, variance, threshold=25): """Creates a binary data mask based on quartile thresholds from two mean and variance arrays. Parameters ---------- mean : numpy array Array containing pixel mean values. variance : numpy array Array containing pixel variance...
5,311,324
def test_getLinksFromRawData(): """unit test for getLinksFromRawData""" #prepare # https://www.w3schools.com/html/html_intro.asp # https://www.w3schools.com/html/html_links.asp multiline_markup = """ <!DOCTYPE html> <html> <body> <h2>The target Attribute</h2> <a href="https://www.facebo...
5,311,325
def test_index_purBeurre_view(): """Creates a test client. Make a request on the URL retrieved using the reverse () function. Check that the HTTP status code is 200 or the expected code. Check that the template used is the expected one""" client = Client() path = reverse("index") response = client.g...
5,311,326
def test_metadata_keys_iter(): """Test iterators over list of metadata keys in a database. """ dbpath = 'db_test_metadata_iter' db = xapian.WritableDatabase(dbpath, xapian.DB_CREATE_OR_OVERWRITE) db.set_metadata('author', 'richard') db.set_metadata('item1', 'hello') db.set_metadata('item1'...
5,311,327
def initialCondition1D(u, a): """ use this function only if initial condition != 0 is needed ????? """ nx = u.size ul = np.zeros(nx) ul[1:nx-1] = u[1:nx-1]+0.5*a[1:nx-1]**2*(u[2:]-2*u[1:nx-1]+u[0:nx-2]) return ul
5,311,328
def test_initialize_parser_with_parameter(parameter, sys_mock): """Test initialize_parser with option help.""" with patch.object(sys, 'argv', sys_mock['mock']): args = initialize_parser(parameter) assert args == sys_mock[parameter]
5,311,329
def learnability_objective_function(throughput, delay): """Objective function used in https://cs.stanford.edu/~keithw/www/Learnability-SIGCOMM2014.pdf throughput: Mbps delay: ms """ score = np.log(throughput) - np.log(delay) # print(throughput, delay, score) score = score.replace([np.inf, -n...
5,311,330
def test_sum_of_yields(n): """ >>> g = test_sum_of_yields(3) >>> next(g) (0, 0) >>> g.send(1) (0, 1) >>> g.send(1) (1, 2) """ x = 0 x += yield (0, x) x += yield (0, x) yield (1, x)
5,311,331
def partition_graph(graph, partitions): """ Create a new graph based on `graph`, where nodes are aggregated based on `partitions`, similar to :func:`~networkx.algorithms.minors.quotient_graph`, except that it only accepts pre-made partitions, and edges are not given a 'weight' attribute. Much fast t...
5,311,332
def test_2D_independent(): """Test a Fermi function which returns a vector over energy and is sampled over different temperatures.""" config_file = 'study_independent/profit_independent.yaml' config = BaseConfig.from_file(config_file) model_file = config['fit'].get('save') try: run(f"profit...
5,311,333
def __misc_badbarcode(): """DEPRECATED: setting badbarcode boolean. Use /misc/itemattr instead. Gets or Sets the barcode-okayness of a SKU. This will return the barcode state of a SKU in a GET message, and will set the barcode state of a SKU in a POST message. :param int sku: The SKU to view/modi...
5,311,334
def action_save_comment(): """Action save comment.""" review_request_id = get_tabvar('review_request_id') start = get_tabvar('start') num_lines = get_tabvar('num_lines') filediff_id = get_tabvar('filediff_id') comment_string = '\n'.join( line for line in vim.current.buffer[:] ...
5,311,335
def lzip(*args): """ this function emulates the python2 behavior of zip (saving parentheses in py3) """ return list(zip(*args))
5,311,336
def sanitize_url(url: str) -> str: """ This function strips to the protocol, e.g., http, from urls. This ensures that URLs can be compared, even with different protocols, for example, if both http and https are used. """ prefixes = ["https", "http", "ftp"] for prefix in prefixes: if url...
5,311,337
def heatmap_on_image(image, heatmap, save_path, alpha=0.3): """ image: 3*H*W heatmap: 1*H*W """ H, W = image.shape[-2:] heatmap = (heatmap-heatmap.min())/(heatmap.max()-heatmap.min()+1e-5) heatmap = F.interpolate(heatmap[None], size=(H, W), mode='bicubic')[0] # 1*H*W image = image.per...
5,311,338
def trimming_parameters( library_type: LibraryType, trimming_min_length: int ) -> Dict[str, Union[str, int]]: """ Derive trimming parameters based on the library type, and minimum allowed trim length. :param library_type: The LibraryType (eg. srna) :param trimming_min_length: The minimu...
5,311,339
def hyperswipe(): """ This is for doing hyperswiping for the model parameters """ reg_scale_list = [1e-4] #reg_scale_list = [0, 1e-5, 5e-5, 1e-4, 5e-4, 1e-3] layer_size_list = [1500] for reg_scale in reg_scale_list: for i in range(3): for layer_num in range(12, 1...
5,311,340
def test_client(): """Pass.""" client = DummyConnect() expected = "ok" args = {} result = run_command(client=client, args=args, command="test-module") assert expected == result
5,311,341
def make_nn(output_size, hidden_sizes): """ Creates a fully connected neural network. Params: output_size: output dimensionality hidden_sizes: list of hidden layer sizes. List length is the number of hidden layers. """ NNLayers = [tf.keras.layers.Dense(h, activation=tf.nn.relu,...
5,311,342
def heatmap_feed(engine, cap_num): """ Opens a camera reader, gets a processed frame, encodes it to JPEG, and returns it as a snippet of a multipart response body. Author of this function: Elias Gabriel """ # In a loop, get the current frame of the camera as a byte sequence and yield it to t...
5,311,343
def image_to_world(bbox, size): """Function generator to create functions for converting from image coordinates to world coordinates""" px_per_unit = (float(size[0])/bbox.width, float(size[1]/bbox.height)) return lambda x,y: (x/px_per_unit[0] + bbox.xmin, (size[1]-y)/px_per_unit[1] + bbox.ymin)
5,311,344
def error_func(A, b, x, x_star, fold=50): """Calculate errors ||Ax_1-b||-||Ax_star-b||, where x1 \in x. Param: A: n*d np.ndarray, coefficient in ||Ax-b|| b: n*1 np.ndarray, coefficient in ||Ax-b|| x: tuple, (x_linBoost, x_inverse, x_cholesky) x_star: d*1 np.ndarray, x* by lstsq()...
5,311,345
def git_reset_all(): """Function that unstages all files in repo for commit. Returns ------- out : str Output string from stdout if success, stderr if failure err : int Error code if failure, 0 otherwise. """ command = 'git reset HEAD' name = 'git_reset_all' return ...
5,311,346
def tag(c): """ Create a release tag. May set a config option for a prefix, e.g. 'v1.0.0' vs just '1.0.0'. This is unset/blank by default. """ pass
5,311,347
def find_kern_timing(df_trace): """ find the h2d start and end for the current stream """ kern_begin = 0 kern_end = 0 for index, row in df_trace.iterrows(): if row['api_type'] == 'kern': kern_begin = row.start kern_end = row.end break; return kern...
5,311,348
def Get(SyslogSource, WorkspaceID): """ Get the syslog conf for specified workspace from the machine """ if conf_path == oms_syslog_ng_conf_path: NewSource = ReadSyslogNGConf(SyslogSource, WorkspaceID) else: NewSource = ReadSyslogConf(SyslogSource, WorkspaceID) for d in NewSourc...
5,311,349
def partie_reelle(c : Complexe) -> float: """Renvoie la partie réelle du nombre complexe c. """ re, _ = c return re
5,311,350
def get_client_folder_id(drive_service): """ Returns the client folder to take the backups TODO fetch client name """ client_name = frappe.db.get_value("ConsoleERP Settings", filters="*", fieldname="client_name") if not client_name: print("Client Name not set") return None print("Client Name: %s" % client...
5,311,351
def get_event_data(url: str) -> dict: """connpassイベントページより追加情報を取得する。 Parameters ---------- url : str connpassイベントのurl。 Returns ------- event_dict : dict[str, Any] イベント情報dict。 """ try: html = urlopen(url) except Exception: # アクセス失敗した場合には...
5,311,352
def write_recordio_shards_from_iterator( records_iter, features_list, output_dir, records_per_shard ): """Writes RecordIO files from Python iterator of numpy arrays.""" # Take the first record batch to check whether it contains multiple items first_record_batch = next(records_iter) is_first_record_b...
5,311,353
def overlap_branches(targetbranch: dict, sourcebranch: dict) -> dict: """ Overlaps to dictionaries with each other. This method does apply changes to the given dictionary instances. Examples: >>> overlap_branches( ... {"a": 1, "b": {"de": "ep"}}, ... {"b": {"de": {"eper"...
5,311,354
def get_dependencies(node, skip_sources=False): """Return a list of dependencies for node.""" if skip_sources: return [ get_path(src_file(child)) for child in filter_ninja_nodes(node.children()) if child not in node.sources ] return [get_path(src_file(chil...
5,311,355
def depolarizing_channel_3q(q, p, system, ancillae): """Returns a QuantumCircuit implementing depolarizing channel on q[system] Args: q (QuantumRegister): the register to use for the circuit p (float): the probability for the channel between 0 and 1 system (int): index of the system qub...
5,311,356
def gen_file_test(basename, testclass, writer="either 'html' or 'txt'"): """creates one test method and adds it to testclass""" referenceoutputdir = os.path.join(mydir, "rtf-as-%s" % writer) referencefilename = os.path.join(referenceoutputdir, "%s.%s" % (basename, write...
5,311,357
def assert_valid_status_timestamp(when: str) -> None: """Check the timestamp of a status change row. The timestamp part of the row is normally "(now)" but can be "(1 second ago)" or more on slow systems and "(in the future)" if MySQL rounds the timestamp up. Allow for all of these. """ if when in ...
5,311,358
def resample_30s(annot): """resample_30s: to resample annot dataframe when durations are multiple of 30s Parameters: ----------- annot : pandas dataframe the dataframe of annotations Returns: -------- annot : pandas dataframe the resampled dataframe of annotations "...
5,311,359
def jamoToHang(jamo: str): """자소 단위(초, 중, 종성)를 한글로 결합하는 모듈입니다. @status `Accepted` \\ @params `"ㅇㅏㄴㄴㅕㅇㅎㅏ_ㅅㅔ_ㅇㅛ_"` \\ @returns `"안녕하세요"` """ result, index = "", 0 while index < len(jamo): try: initial = chosung.index(jamo[index]) * 21 * 28 midial = jungsung.i...
5,311,360
def calc_Vs30(profile, option_for_profile_shallower_than_30m=1, verbose=False): """ Calculate Vs30 from the given Vs profile, where Vs30 is the reciprocal of the weighted average travel time from Z meters deep to the ground surface. Parameters ---------- profile : numpy.ndarray Vs profi...
5,311,361
def prepare_model( model: torch.nn.Module, move_to_device: bool = True, wrap_ddp: bool = True, ddp_kwargs: Optional[Dict[str, Any]] = None, ) -> torch.nn.Module: """Prepares the model for distributed execution. This allows you to use the same exact code regardless of number of workers or th...
5,311,362
def make_legend_labels(dskeys=[], tbkeys=[], sckeys=[], bmkeys=[], plkeys=[], dskey=None, tbkey=None, sckey=None, bmkey=None, plkey=None): """ @param dskeys : all datafile or examiner keys @param tbkeys : all table keys @param sckeys : all subchannel keys @param bmkeys : all beam keys @pa...
5,311,363
def bl_subtract(w_in, a_baseline, w_out): """ Subtract the constant baseline from the entire waveform. Parameters ---------- w_in : array-like The input waveform a_in : float The baseline value to subtract w_out: array-like The output waveform with the basel...
5,311,364
def import_summary_tsv_data(file): """ Import the data from a summary_qc.tsv file """ _qc = dict() with open(file, 'r') as ifh: reader = csv.DictReader(ifh, delimiter='\t') for item in reader: if item['sample'] not in _qc: _qc.update(create_entry(line=item...
5,311,365
def get_parameter_change(old_params, new_params, ord='inf'): """Measure the change in parameters. Parameters ---------- old_params : list The old parameters as a list of ndarrays, typically from session.run(var_list) new_params : list The old parameters as a list of ndarrays...
5,311,366
def get_image_dir(): """Return the `image_dir` set in the current context.""" return get_data_context().image_dir
5,311,367
def preloadRefEd(*args, **kwargs): """ This creates an editor for managing which references will be read in (loaded) and which deferred (unloaded) upon opening a file. Flags: - control : ctl (bool) [query] Query only. Returns the top level control for this ...
5,311,368
def test_beyond_grid(): """Raise an error if points are outside the bounds of the grid.""" rmg = RasterModelGrid((4, 5), spacing=(2., 2.)) assert_equal(rfuncs.find_nearest_node(rmg, (-.999, .2)), 0) assert_raises(ValueError, rfuncs.find_nearest_node, rmg, (-1.001, .2)) assert_equ...
5,311,369
def test_exception_raised_less_calls_expected2(mocker): """Test an exception is raised in the case less calls to a function are expected than happen.""" with pytest.raises( AssertionError, match="incorrect number of calls to dummy_function_b, expected 0 but got 1", ): x = DummyClas...
5,311,370
def get_interface_config_vlan(): """ Return the interface configuration parameters for all IP static addressing. """ parameters = collections.OrderedDict() parameters['VLAN'] = 'yes' return parameters
5,311,371
def get_browser(sport, debug=False): """ Use selenium and chromedriver to do our website getting. Might as well go all the way. :param debug: whether to set the browser to debug mode :param headless: go headless :return: """ chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--use...
5,311,372
def parsear_ruta(linea): """ Lee una linea del archivo de rutas, separa los campos, y devuelve un objeto Ruta armado apropiadamente. Si hay un error al aplicar split, y hay menos campos de los esperados, devuelve None. Si algun valor no tiene el formato apropiado (documentado en la clase) devuelve None. Si la ciud...
5,311,373
def test_handle_find_files2json(): """Tests running the plotclip algorithm""" # pylint: disable=import-outside-toplevel import workflow_docker as wd # Load the result with open(WORKFLOW_FINDFILES_RESULT, 'r', encoding='utf8') as in_file: compare_json = json.load(in_file) # Setup fields...
5,311,374
def split_channel_groups(data,meta): """ With respect to the sensor site, a different number of channels is given. In both sites the first 160 channels contain the meg data. params: ------- data: array w/ shape (160+type2channels+type3channels,time_samples) meta: returns: ...
5,311,375
def test_boolean018_1874_boolean018_1874_v(mode, save_output, output_format): """ TEST :Facet Schemas for string : Test simpleType list with boolean """ assert_bindings( schema="msData/datatypes/boolean018.xsd", instance="msData/datatypes/boolean018.xml", class_name="Root", ...
5,311,376
def _read_header_byte_data(header_structure): """ Reads the byte data from the data file for a PDS4 Header. Determines, from the structure's meta data, the relevant start and stop bytes in the data file prior to reading. Parameters ---------- header_structure : HeaderStructure The PDS4...
5,311,377
def check_random_state(seed): """Turn seed into a np.random.RandomState instance Parameters ---------- seed : None | int | instance of RandomState If seed is None, return the RandomState singleton used by np.random. If seed is an int, return a new RandomState instance seeded with seed. ...
5,311,378
def repolist(orgname, refresh=True): """Return list of repos for a GitHub organization. If refresh=False, we use the cached data in /data/repos{orgname}.json and don't retrieve the repo data from GitHub API. Returns tuples of (reponame, size). Note that this is the size returned by the GitHub API,...
5,311,379
def create_labels(labels=None): """ creates labels based on - agencies (defined by contacts) - statuses (defined in configs) """ if not labels: labels = [] labels += ['agency'] # see https://github.com/mattkiefer/gm/issues/1 labels += ['agency/' + agency for agenc...
5,311,380
def normalize_string(value): """ Normalize a string value. """ if isinstance(value, bytes): value = value.decode() if isinstance(value, str): return value.strip() raise ValueError("Cannot convert {} to string".format(value))
5,311,381
def convert_to_dict(itask, key, value, mr): """ Add each date/number of access to a Python dict for simpler operation. """ timestamp_counts[key] = value
5,311,382
def malloc_chunk(addr, fake=False, verbose=False, simple=False): """Print a malloc_chunk struct's contents.""" # points to the real start of the chunk cursor = int(addr) allocator = pwndbg.heap.current ptr_size = allocator.size_sz size_field = pwndbg.memory.u(cursor + allocator.chunk_key_offse...
5,311,383
def _is_test_env(env_config: tox.config.TestenvConfig) -> bool: """Check if it is a test environment. Tox creates environments for provisioning (`.tox`) and for isolated build (`.packaging`) in addition to the usual test environments. And in hooks such as `tox_testenv_create` it is not clear if the env...
5,311,384
def latest_version(): """Return the latest version of Windows git available for download.""" soup = get_soup('https://git-scm.com/download/win') if soup: tag = soup.find('a', string='Click here to download manually') if tag: return downloadable_version(tag.attrs['href']) retu...
5,311,385
def plot_results(actual_time_series, predicted_values, len_train_data, y_name='Parameter'): """ Function for drawing plot with predictions :param actual_time_series: the entire array with one-dimensional data :param predicted_values: array with predicted values :param len_train_data: number of elem...
5,311,386
def get_interval_date_list_by_freq_code(start_date, end_date, freq_code): """ :param freq_code: D, W, M """ end_date_list = get_end_date_list_by_freq_code(start_date, end_date, freq_code) start_date = start_date interval_date_list = [] for end_date in end_date_list: interval_date_l...
5,311,387
def get_versions(): """ Try to find out the versions of gcc and ld. If not possible it returns None for it. """ from distutils.version import StrictVersion from distutils.spawn import find_executable import re gcc_exe = find_executable('gcc') if gcc_exe: out = os.popen(gcc_e...
5,311,388
def _rotate_move(move, axis, n=1): """Rotate a move clockwise about an axis The axis of rotation should correspond to a primitive rotation operation of a cube Face. """ if n == 0: return move table = { Face.U: { 'U': 'U', 'D': 'D', 'U\'': ...
5,311,389
def mapAddress(name): """Given a register name, return the address of that register. Passes integers through unaffected. """ if type(name) == type(''): return globals()['RCPOD_REG_' + name.upper()] return name
5,311,390
def list_index(ls, indices): """numpy-style creation of new list based on a list of elements and another list of indices Parameters ---------- ls: list List of elements indices: list List of indices Returns ------- list """ return [ls[i] for i in indices]
5,311,391
def create_seed_population(cities, howmany): """Create a seed file with tours generated by the nearest-neighbour algorithm. """ attr = OrderedIndividual.get_attributes() attr['osi.num_genes'] = len(cities) - 1 tours = generate_nntours(cities, howmany) pop = [] for i in range(len(tours))...
5,311,392
def dynamic_load_modules(target_dir, context, excludes=('__init__.py',), verbose=True): """Load all the python files(.py) in the current directory. Notes: It is suggested to import modules explicitly. However, sometimes, we may temporarily add s...
5,311,393
def unlink_or_rename_to_trash(path): """If files are in use, especially on windows, we can't remove them. The fallback path is to rename them (but keep their folder the same), which maintains the file handle validity. See comments at: https://serverfault.com/a/503769 """ try: make_writa...
5,311,394
def copyright_present(f): """ Check if file already has copyright header. Args: f - Path to file """ with io.open(f, "r", encoding="utf-8") as fh: return re.search('Copyright', fh.read())
5,311,395
def calc_LFC(in_file_2, bin_list): """ Mods the count to L2FC in each bin """ #for itereating through the bin list bin_no=0 header_line = True with open(in_file_2, 'r') as f: for bin_count in f: if header_line: header_line = False els...
5,311,396
def download_imagery_with_metadata( inputs_file: str, pre_process_settings: dict): """ Download imagery using CoastSat with the inputs in a given inputs file. Bypasses coastsat's retrieve_imagery. Arguments: ----------- inputs_file:str A json file containing all the inputs ...
5,311,397
def parse_value(named_reg_value): """ Convert the value returned from EnumValue to a (name, value) tuple using the value classes. """ name, value, value_type = named_reg_value value_class = REG_VALUE_TYPE_MAP[value_type] return name, value_class(value)
5,311,398
def construct_model_vector(df, n): """ Convert a dataframe to an array of numpy vectors which are of the form [(1-hot encoding of position), (game stats for n games leading up to this one for a given player)]. If there are p positions and s stats this vector will be of dimension p + s * n. ...
5,311,399