content
stringlengths
22
815k
id
int64
0
4.91M
def load_data_file(filename): """loads a single file into a DataFrame""" regexp = '^.*/results/([^/]+)/([^/]+)/([^/]+).csv$' optimizer, blackbox, seed = re.match(regexp, filename).groups() f = ROOT + '/results/{}/{}/{}.csv'.format(optimizer, blackbox, seed) result = np.genfromtxt(f, delimiter=',') ...
22,700
def get_hub_manager(): """Generate Hub plugin structure""" global _HUB_MANAGER if not _HUB_MANAGER: _HUB_MANAGER = _HubManager(_plugins) return _HUB_MANAGER
22,701
def extract_stimtype( data: pd.DataFrame, stimtype: str, columns: list ) -> pd.DataFrame: """ Get trials with matching label under stimType """ if stimtype not in accept_stimtype: raise ValueError(f"invalid {stimtype}, only accept {accept_stimtype}") get = columns.copy() get += ["par...
22,702
def compute_rank_clf_loss(hparams, scores, labels, group_size, weight): """ Compute ranking/classification loss Note that the tfr loss is slightly different than our implementation: the tfr loss is sum over all loss and devided by number of queries; our implementation is sum over all loss and devided by...
22,703
def get_org_image_url(url, insert_own_log=False): """ liefert gegebenenfalls die URL zum Logo der betreffenden Institution """ #n_pos = url[7:].find('/') # [7:] um http:// zu ueberspringen #org_url = url[:n_pos+7+1] # einschliesslich '/' item_containers = get_image_items(ELIXIER_LOGOS_PATH) image_url = imag...
22,704
async def download_page(url, file_dir, file_name, is_binary=False): """ Fetch URL and save response to file Args: url (str): Page URL file_dir (pathlib.Path): File directory file_name (str): File name is_binary (bool): True if should download binary content (e.g. images) ...
22,705
def normal_coffee(): """ when the user decides to pick a normal or large cup of coffee :return: template that explains how to make normal coffee """ return statement(render_template('explanation_large_cup', product='kaffee'))
22,706
def _transitive_closure_dense_numpy(A, kind='metric', verbose=False): """ Calculates Transitive Closure using numpy dense matrix traversing. """ C = A.copy() n, m = A.shape # Check if diagonal is all zero if sum(np.diagonal(A)) > 0: raise ValueError("Diagonal has to be zero for matr...
22,707
def _walk_to_root(path): """ Yield directories starting from the given directory up to the root """ if not os.path.exists(path): # pragma: no cover raise IOError('Starting path not found') if os.path.isfile(path): # pragma: no cover path = os.path.dirname(path) last_dir = Non...
22,708
def convert_date(raw_dates: pd.Series) -> pd.Series: """Automatically converts series containing raw dates to specific format. Parameters ---------- raw_dates: Series to be converted. Returns ------- Optimized pandas series. """ raw_dates = pd.to_datetime(raw_dates,...
22,709
def _feed_subs_to_queue(monitored_sub, queue): """Stream all submissions and put them into the queue. Submissions are stored in a tuple with a 0. Error logging should be established as needed.""" subreddit = reddit.subreddit(monitored_sub) while True: try: for sub in subreddit.s...
22,710
async def get_scorekeeper_by_id(scorekeeper_id: conint(ge=0, lt=2**31)): """Retrieve a Scorekeeper object, based on Scorekeeper ID, containing: Scorekeeper ID, name, slug string, and gender.""" try: scorekeeper = Scorekeeper(database_connection=_database_connection) scorekeeper_info = scorek...
22,711
def check_spelling(data, header_to_print=None): """Checks spelling via Yandex.Speller API""" try: p = Popen(['./yasp'], stdin=PIPE, stdout=PIPE, encoding='UTF-8') p.stdin.write(data) output = p.communicate()[0] if output: if header_to_print: print(he...
22,712
def modulePath(): """ This will get us the program's directory, even if we are frozen using py2exe """ try: _ = sys.executable if weAreFrozen() else __file__ except NameError: _ = inspect.getsourcefile(modulePath) return os.path.dirname(os.path.dirname(os.path.dirname(os.pa...
22,713
def get_time(sec_scale): """time since epoch in milisecond """ if sec_scale == 'sec': scale = 0 elif sec_scale == 'msec': scale = 3 else: raise secs = (datetime.utcnow() - datetime.utcfromtimestamp(0)).total_seconds() return int(secs * pow(10, scale))
22,714
def get_json(url): """ Function that retrieves a json from a given url. :return: the json that was received """ with urllib.request.urlopen(url) as response: data = response.readall().decode('utf-8') data = json.loads(data) return data
22,715
def _defaultChangeProvider(variables,wf): """ by default we just forword the message to the change provider """ return variables
22,716
def evaluate_surface_derivatives(surface, params, order=1): """ """ if surface.rational: control_points = np.array(surface.weighted_control_points) else: control_points = np.array(surface.control_points) degree_u, degree_v = surface.degree knot_vector_u, knot_vector_v = surface....
22,717
def GPPrediction(y_train, X_train, T_train, eqid_train, sid_train = None, lid_train = None, X_new = None, T_new = None, eqid_new = None, sid_new = None, lid_new = None, dc_0 = 0., Tid_list = None, Hyp_list = None, phi_0 = None, tau_0 = None,...
22,718
def zdotu(x, y): """ This function computes the complex scalar product \M{x^T y} for the vectors x and y, returning the result. """ return _gslwrap.gsl_blas_zdotu(x, y, 1j)
22,719
def music21_to_chord_duration(p, key): """ Takes in a Music21 score, and outputs three lists List for chords (by primeFormString string name) List for chord function (by romanNumeralFromChord .romanNumeral) List for durations """ p_chords = p.chordify() p_chords_o = p_chords.flat.getElem...
22,720
def city_country(city, country, population=''): """Generate a neatly formatted city/country name.""" full_name = city + ', ' + country if population: return full_name.title() + ' - population ' + str(population) else: return full_name.title()
22,721
def generate_headermap(line,startswith="Chr", sep="\t"): """ >>> line = "Chr\\tStart\\tEnd\\tRef\\tAlt\\tFunc.refGene\\tGene.refGene\\tGeneDetail.refGene\\tExonicFunc.refGene\\tAAChange.refGene\\tsnp138\\tsnp138NonFlagged\\tesp6500siv2_ea\\tcosmic70\\tclinvar_20150629\\tOtherinfo" >>> generate_heade...
22,722
def max(q): """Return the maximum of an array or maximum along an axis. Parameters ---------- q : array_like Input data Returns ------- array_like Maximum of an array or maximum along an axis """ if isphysicalquantity(q): return q.__class__(np.max(q.value), ...
22,723
def make_failure_log(conclusion_pred, premise_preds, conclusion, premises, coq_output_lines=None): """ Produces a dictionary with the following structure: {"unproved sub-goal" : "sub-goal_predicate", "matching premises" : ["premise1", "premise2", ...], "raw sub-goal" : "conclu...
22,724
def request(url=None, json=None, parser=lambda x: x, encoding=None, **kwargs): """ :param url: :param json: :param parser: None 的时候返回r,否则返回 parser(r.json()) :param kwargs: :return: """ method = 'post' if json is not None else 'get' # 特殊情况除外 logger.info(f"Request Method: {method}") ...
22,725
def dump_all(dashboard_dir): """dump dashboard to specific dir with fhs""" if not os.path.exists(dashboard_dir): print("dump: create dashboard dir %s" % dashboard_dir) os.mkdir(dashboard_dir) dbmeta = list_dashboards() folders = set([i.get('folderUid') for i in dbmeta if 'folderUid' in i...
22,726
def log_density_igaussian(z, z_var): """Calculate log density of zero-mean isotropic gaussian distribution given z and z_var.""" assert z.ndimension() == 2 assert z_var > 0 z_dim = z.size(1) return -(z_dim/2)*math.log(2*math.pi*z_var) + z.pow(2).sum(1).div(-2*z_var)
22,727
def denom(r,E,J,model): """solve the denominator""" ur = model.potcurve(r)#model.potcurve[ (abs(r-model.rcurve)).argmin()] return 2.0*(E-ur)*r*r - J*J;
22,728
def approximate_gaussians(confidence_array, mean_array, variance_array): """ Approximate gaussians with given parameters with one gaussian. Approximation is performed via minimization of Kullback-Leibler divergence KL(sum_{j} w_j N_{mu_j, sigma_j} || N_{mu, sigma}). Parameters ---------- confi...
22,729
def return_loss(apply_fn: Callable[[jnp.ndarray, jnp.ndarray], jnp.ndarray], steps: types.Transition): """Loss wrapper for ReturnMapper. Args: apply_fn: applies a transition model (o_t, a_t) -> (o_t+1, r), expects the leading axis to index the batch and the second axis to index the ...
22,730
def part_two(data): """Part two""" array = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p'] commands = data.split(',') for _ in range(1000000000 % 30): dance(array, commands) return ''.join(map(str, array))
22,731
def ts_declare(): """Makes an f5-telemetry-streaming declaration from the supplied metadata""" if is_rest_worker('/mgmt/shared/telemetry/declare') and os.path.isfile( TS_DECLARATION_FILE): tsdf = open(TS_DECLARATION_FILE, 'r') declaration = tsdf.read() tsdf.close() js...
22,732
def readCSVPremadeGroups(filename, studentProperties=None): """studentProperties is a list of student properties in the order they appear in the CSV. For example, if a CSV row (each group is a row) is as follows: "Rowan Wilson, rowan@harvard.edu, 1579348, Bob Tilano, bob@harvard.edu, 57387294" Then the format is:...
22,733
def random_contrast(video, lower, upper, seed=None): """Adjust the contrast of an image or images by a random factor. Equivalent to `adjust_contrast()` but uses a `contrast_factor` randomly picked in the interval `[lower, upper)`. For producing deterministic results given a `seed` value, use `tf.i...
22,734
def load(df: DataFrame, config: Dict, logger) -> bool: """Write data in final destination :param df: DataFrame to save. :type df: DataFrame :param config: job configuration :type config: Dict :param logger: Py4j Logger :type logger: Py4j.Logger :return: True :rtype: bool """ ...
22,735
def phase_correct_zero(spec, phi): """ Correct the phases of a spectrum by phi radians Parameters ---------- spec : float array of complex dtype The spectrum to be corrected. phi : float Returns ------- spec : float array The phase corrected spectrum ...
22,736
def upsample(s, n, phase=0): """Increase sampling rate by integer factor n with included offset phase. """ return np.roll(np.kron(s, np.r_[1, np.zeros(n-1)]), phase)
22,737
def close_connection(exception): """ Close DB connection """ db = getattr(g, "_database", None) if db is not None: db.close()
22,738
def _build_plugin_out(name, outdir, options, builder): """Build the --{lang}_out argument for a given plugin.""" arg = outdir if options: arg = ",".join(options) + ":" + arg builder["args"] += ["--%s_out=%s" % (name, arg)]
22,739
def parse_idx_inp(idx_str): """ parse idx string """ idx_str = idx_str.strip() if idx_str.isdigit(): idxs = [int(idx_str)] if '-' in idx_str: [idx_begin, idx_end] = idx_str.split('-') idxs = list(range(int(idx_begin), int(idx_end)+1)) return idxs
22,740
def toggl_request_get(url: str, params: dict = False) -> requests.Response: """Send a GET request to specified url using toggl headers and configured auth""" headers = {"Content-Type": "application/json"} auth = (CONFIG["toggl"]["api_token"], "api_token") response = requests.get(url, headers=headers, au...
22,741
def sample_point_cloud(source, target, sample_indices=[2]): """ Resamples a source point cloud at the coordinates of a target points Uses the nearest point in the target point cloud to the source point Parameters ---------- source: array Input point cloud target: array...
22,742
def make_satellite_gsp_pv_map(batch: Batch, example_index: int, satellite_channel_index: int): """Make a animation of the satellite, gsp and the pv data""" trace_times = [] times = batch.satellite.time[example_index] pv = batch.pv for time in times: trace_times.append( make_sate...
22,743
def raw_to_engineering_product(product, idbm): """Apply parameter raw to engineering conversion for the entire product. Parameters ---------- product : `BaseProduct` The TM product as level 0 Returns ------- `int` How many columns where calibrated. """ col_n = 0 ...
22,744
def paginate(objects, page_num, per_page, max_paging_links): """ Return a paginated page for the given objects, giving it a custom ``visible_page_range`` attribute calculated from ``max_paging_links``. """ paginator = Paginator(objects, per_page) try: page_num = int(page_num) except ...
22,745
def _get_crop_frame(image, max_wiggle, tx, ty): """ Based on on the max_wiggle, determines a cropping frame. """ pic_width, pic_height = image.size wiggle_room_x = max_wiggle * .5 * pic_width wiggle_room_y = max_wiggle * .5 * pic_height cropped_width = pic_width - wiggle_room_x cropped_h...
22,746
def __vigenere(s, key='virink', de=0): """维吉利亚密码""" s = str(s).replace(" ", "").upper() key = str(key).replace(" ", "").upper() res = '' i = 0 while i < len(s): j = i % len(key) k = U.index(key[j]) m = U.index(s[i]) if de: if m < k: m +...
22,747
def mask_unit_group(unit_group: tf.Tensor, unit_group_length: tf.Tensor, mask_value=0) -> tf.Tensor: """ Masks unit groups according to their length. Args: unit_group: A tensor of rank 3 with a sequence of unit feature vectors. unit_group_length: The length of the unit group (assumes all unit f...
22,748
def fill_session_team(team_id, session_id, dbsession=DBSESSION): """ Use the FPL API to get list of players in an FPL squad with id=team_id, then fill the session team with these players. """ # first reset the team reset_session_team(session_id, dbsession) # now query the API players = f...
22,749
def create_map(users_info): """ This function builds an HTML map with locations of user's friends on Twitter. """ my_map = folium.Map( location=[49.818396058511645, 24.02258071000576], zoom_start=10) folium.TileLayer('cartodbdark_matter').add_to(my_map) folium.TileLayer('stamentoner'...
22,750
def write_dist_mat_file(mat, pdb, ag, out_folder, tag = ''): """ Writes out a file containing the distance matrix """ # output_folder = 'core_contact_maps/dist_mat_txt_folder/' numpy.set_printoptions(threshold=numpy.inf) dist_mat_file = pdb.split('.')[0] dist_mat_file = out_folder + dist_mat_file + '_full_mat...
22,751
def l2sq(x): """Sum the matrix elements squared """ return (x**2).sum()
22,752
def normalize(arr, axis=None): """ Normalize a vector between 0 and 1. Parameters ---------- arr : numpy.ndarray Input array axis : integer Axis along which normalization is computed Returns ------- arr : numpy.ndarray Normalized version of the input array ...
22,753
def successive_substitution(m, T, P, max_iter, M, Pc, Tc, omega, delta, Aij, Bij, delta_groups, calc_delta, K, steps=0): """ Find K-factors by successive substitution Iterate to find a converged set of K-factors defining the gas/liquid partitioning of a mixture using su...
22,754
def Match(context, pattern, arg=None): """Do a regular expression match against the argument""" if not arg: arg = context.node arg = Conversions.StringValue(arg) bool = re.match(pattern, arg) and boolean.true or boolean.false return bool
22,755
def rr_rectangle(rbins, a, b): """ RR_rect(r; a, b) """ return Frr_rectangle(rbins[1:], a, b) - Frr_rectangle(rbins[:-1], a, b)
22,756
def update_type(title, title_new=None, description=None, col_titles_new={}): """Method creates data type Args: title (str): current type title title_new (str): new type title description (str): type description col_titles_new (dict): new column values (key - col id, value - col valu...
22,757
def api(repos_path): """Glottolog instance from shared directory for read-only tests.""" return pyglottolog.Glottolog(str(repos_path))
22,758
def get_all_paginated_data(url, token): """ Get all data for the requesting user. Parameters ---------- url : str URL to the current data to get token: str User's OSF token Returns ------- Data dictionary of the data points gathered up until now. """ header...
22,759
def alaw_decode(x_a, quantization_channels, input_int=True, A=87.6): """alaw_decode(x_a, quantization_channels, input_int=True) input ----- x_a: np.array, mu-law waveform quantization_channels: int, Number of channels input_int: Bool True: convert x_mu (int) from int to float, bef...
22,760
def incoming(ui, repo, source="default", **opts): """show new changesets found in source Show new changesets found in the specified path/URL or the default pull location. These are the changesets that would have been pulled if a pull at the time you issued this command. For remote repository, usin...
22,761
def test_failure(database): """ Test failure for PrimaryPlaceOfPerformanceCode for aggregate records (i.e., when RecordType = 1) must be in countywide format (XX**###). """ det_award_1 = DetachedAwardFinancialAssistanceFactory(place_of_performance_code="00**333", record_type="1") det_award_2 = Deta...
22,762
def test_jujuconfig_missing_file(tmp_path): """No config.yaml file at all.""" result = JujuConfig().run(tmp_path) assert result == JujuConfig.Result.ok
22,763
def _ec_2d(X): """Function for computing the empirical Euler characteristic of a given thresholded data array. Input arguments: ================ Y : ndarray of floats The thresholded image. Ones correspond to activated regions. Output arguments: ================= ec : float ...
22,764
def swap_year_for_time(df, inplace): """Internal implementation to swap 'year' domain to 'time' (as datetime)""" if not df.time_col == "year": raise ValueError("Time domain must be 'year' to use this method") ret = df.copy() if not inplace else df index = ret._data.index order = [v if v !...
22,765
def get_orders( db: Session, skip: int = 0, limit: int = 50, moderator: str = None, owner: str = None, desc: bool = True, ) -> Optional[List[entities.Order]]: """ Get the registed orders using filters. Args: - db: the database session. - skip: the number of filtered ...
22,766
def create_data_loader(img_dir, info_csv_path, batch_size): """Returns a data loader for the model.""" img_transform = transforms.Compose([transforms.Resize((120, 120), interpolation=Image.BICUBIC), transforms.ToTensor()]) img_dataset = FashionDataset(img_dir, img_tra...
22,767
def comp_number_phase_eq(self): """Compute the equivalent number of phase Parameters ---------- self : LamSquirrelCage A LamSquirrelCage object Returns ------- qb: float Zs/p """ return self.slot.Zs / float(self.winding.p)
22,768
def exprOps(expr): """This operation estimation is not handling some simple optimizations that should be done (i.e. y-x is treated as -1*x+y) and it is overestimating multiplications in situations such as divisions. This is as a result of the simple method of implementing this function given the rudim...
22,769
def ellipsis_reformat(source: str) -> str: """ Move ellipses (``...``) for type stubs onto the end of the stub definition. Before: .. code-block:: python def foo(value: str) -> int: ... After: .. code-block:: python def foo(value: str) -> int: ... :param source: The source to reformat. :re...
22,770
def build_wtk_filepath(region, year, resolution=None): """ A utility for building WIND Toolkit filepaths. Args: region (str): region in which the lat/lon point is located (see `get_regions`) year (int): year to be accessed (see `get_regions`) resolution (:obj:`str`, option...
22,771
def init_doc(args: dict) -> dict: """ Initialize documentation variable :param args: A dictionary containing relevant documentation fields :return: """ doc = {} try: doc[ENDPOINT_PORT_KEY] = args[ENDPOINT_PORT_KEY] except KeyError: logging.warning("No port for documentation s...
22,772
def decode_entities(string): """ Decodes HTML entities in the given string ("&lt;" => "<"). """ # http://snippets.dzone.com/posts/show/4569 def replace_entity(match): hash, hex, name = match.group(1), match.group(2), match.group(3) if hash == "#" or name.isdigit(): if hex == ...
22,773
def test_get_or_create_auth_tokens(mocker, settings, user): """ get_or_create_auth_tokens will contact our plugin's API to get a refresh token for a user, or to create one """ settings.OPEN_DISCUSSIONS_REDDIT_URL = "http://fake" refresh_token_url = urljoin( settings.OPEN_DISCUSSIONS_REDDIT_U...
22,774
def convert2board(chrom, rows, cols): """ Converts the chromosome represented in a list into a 2D numpy array. :param rows: number of rows associated with the board. :param cols: number of columns associated with the board. :param chrom: chromosome to be converted. :return: 2D numpy array. "...
22,775
def dots(it, label="", hide=None, every=1): """Progress iterator. Prints a dot for each item being iterated""" count = 0 if not hide: STREAM.write(label) for i, item in enumerate(it): if not hide: if i % every == 0: # True every "every" updates STREAM.write(D...
22,776
def _assert_common_properties(dev, notice_level, msg_file, num_cpu_threads=None): """Assert the properties common to all devices are correct.""" assert dev.notice_level == notice_level assert dev.msg_file == msg_file ...
22,777
def filter_halo_pnum(data, Ncut=1000): """ Returns indicies of halos with more than Ncut particles""" npart = np.array(data['np'][0]) ind =np.where(npart > Ncut)[0] print("# of halos:",len(ind)) return ind
22,778
def _preprocess_sgm(line, is_sgm): """Preprocessing to strip tags in SGM files.""" if not is_sgm: return line # In SGM files, remove <srcset ...>, <p>, <doc ...> lines. if line.startswith("<srcset") or line.startswith("</srcset"): return "" if line.startswith("<refset") or line.start...
22,779
def discover(using, index="*"): """ :param using: Elasticsearch client :param index: Comma-separated list or wildcard expression of index names used to limit the request. """ indices = Indices() for index_name, index_detail in using.indices.get(index=index).items(): indices[index_name] =...
22,780
def quote_sql_value(cursor: Cursor, value: SQLType) -> str: """ Use the SQL `quote()` function to return the quoted version of `value`. :returns: the quoted value """ if isinstance(value, (int, float, datetime)): return str(value) if value is None: return "NULL" if isinstanc...
22,781
def create_admin_nova_client(context): """ Creates client that uses trove admin credentials :return: a client for nova for the trove admin """ client = create_nova_client(context, password=CONF.nova_proxy_admin_pass) return client
22,782
def page_cache(timeout=1800): """ page cache param: timeout:the deadline of cache default is 1800 """ def _func(func): def wrap(request, *a, **kw): key = request.get_full_path() #pass chinese try: key = mkey.encode("utf-8") except Exception, e: key = str(key) data = None try: d...
22,783
def get_available_games(): """Get a list of games that are available to join.""" games = Game.objects.filter(started=False) #pylint: disable=no-member if len(games) == 0: options = [('', '- None -')] else: options = [('', '- Select -')] for game in games: options.append((game...
22,784
def test_unstructure_attrs_lists(benchmark, converter_cls, unstructure_strat): """ Benchmark a large (30 attributes) attrs class containing lists of primitives. """ class E(IntEnum): ONE = 1 TWO = 2 @attr.define class C: a: List[int] b: List[float] c...
22,785
def _add_rays_single_cam( camera_data: TensorDict, *, scene_from_frame: tf_geometry.Isometry, ) -> TensorDict: """Returns the camera, eventually with the rays added.""" if _has_precomputed_rays(camera_data): return camera_data else: # Logic below for generating camera rays only applies to pers...
22,786
def add_vendor_suboption(sender_type, code, data): """ After adding Vendor Specific Option we can decide to add suboptions to it. Please make sure which are supported and if it's necessary add suboption by yourself. """ dhcpmsg.add_vendor_suboption(int(code), data)
22,787
def test_print_albumdata_80(capsys, monkeypatch, albumdata): """Try to print albumdata to width 80 correctly.""" expected = """\ ================================================================================ Test Artist Test album test =====================...
22,788
def read_file(filename=""): """reads filename with utf-8""" with open(filename, encoding='utf-8') as f: print(f.read(), end="")
22,789
def process_ps_stdout(stdout): """ Process the stdout of the ps command """ return [i.split()[0] for i in filter(lambda x: x, stdout.decode("utf-8").split("\n")[1:])]
22,790
def _cleanup_archive_dir(tm_env): """Delete old files from archive directory if space exceeds the threshold. """ archives = glob.glob(os.path.join(tm_env.archives_dir, '*')) infos = [] dir_size = 0 for archive in archives: stat = os.stat(archive) dir_size += stat.st_size ...
22,791
def chpasswd(path, oldpassword, newpassword): """Change password of a private key. """ if len(newpassword) != 0 and not len(newpassword) > 4: return False cmd = shlex.split('ssh-keygen -p') child = pexpect.spawn(cmd[0], cmd[1:]) i = child.expect(['Enter file in which the key is', pexpect.EOF]) ...
22,792
def get_display_limits(VarInst, data=None): """Get limits to resize the display of Variables. Function takes as argument a `VariableInstance` from a `Section` or `Planform` and an optional :obj:`data` argument, which specifies how to determine the limits to return. Parameters ---------- Va...
22,793
def plot_layer_consistency_example(eigval_col, eigvec_col, layernames, layeridx=[0,1,-1], titstr="GAN", figdir="", savelabel="", use_cuda=False): """ Note for scatter plot the aspect ratio is set fixed to one. :param eigval_col: :param eigvec_col: :param nsamp: :param titstr: :param figdir: ...
22,794
def min_vertex_cover(left_v, right_v): """ Use the Hopcroft-Karp algorithm to find a maximum matching or maximum independent set of a bipartite graph. Next, find a minimum vertex cover by finding the complement of a maximum independent set. The function takes as input two dictionaries, one for t...
22,795
def neighbor_dist(x1, y1, x2, y2): """Return distance of nearest neighbor to x1, y1 in x2, y2""" m1, m2, d12 = match_xy(x2, y2, x1, y1, neighbors=1) return d12
22,796
def add_artist_subscription(auth, userid, artist_mbid): """ Add an artist to the list of subscribed artists. :param tuple auth: authentication data (username, password) :param str userid: user ID (must match auth data) :param str artist_mbid: musicbrainz ID of the artist to add :return: True on...
22,797
def get_built_vocab(dataset: str) -> Vocab: """load vocab file for `dataset` to get Vocab based on selected client and data in current directory Args: dataset (str): string of dataset name to get vocab Returns: if there is no built vocab file for `dataset`, return None, else return Vocab ...
22,798
def binidx(num: int, width: Optional[int] = None) -> Iterable[int]: """ Returns the indices of bits with the value `1`. Parameters ---------- num : int The number representing the binary state. width : int, optional Minimum number of digits used. The default is the global value `BIT...
22,799