content
stringlengths
22
815k
id
int64
0
4.91M
def cleanInputFolder(dataset_folder): """Removes unused input images in the given dataset folder.""" # Step 1. Find all cache folders (could be more than 1) cache_folder = Path(dataset_folder) / "Cache" list_subfolders_with_paths = [f.path for f in os.scandir(cache_folder) if f.is_dir()] if len(lis...
5,301,900
def test_non_json_with_200_status_code(): """Tests non json response with 200 status code""" client = API(base_url=mock_base_url) response = client.send_request("GET", "/test/non/json/with/200") response.should.equal(mock_error_body)
5,301,901
def formatParagraphLine(text, width): """ :return: array of rows """ words = text.split() tail = words result = [] buf = '' while len(tail): curWord, tail = tail[0], tail[1:] if len(buf) + len(curWord) + 1 > width: if buf == '': row = curWord ...
5,301,902
def process_image(base_image, mask_array, output_format="jpeg"): """ Create the final image including the aerial imagery background with the outside of the featured boundaries masked. :param base_image: A file-like object with the image :type base_image: File-like object :param mask_array: nump...
5,301,903
def get_scene(scene_id, client=default): """ Return scene corresponding to given scene ID. """ return raw.fetch_one("scenes", scene_id, client=client)
5,301,904
def build_uwp( package_family_name, target, location=None,logo44x44=None, lnk_name=None, ) -> Lnk: """ :param lnk_name: ex.: crafted_uwp.lnk :param package_family_name: ex.: Microsoft.WindowsCalculator_10.1910.0.0_x64__8wekyb3d8bbwe :param target: ex.: Microsoft.WindowsCalcul...
5,301,905
def display_streams(youtube: YouTube) -> None: """Probe YouTube video and lists its available formats. :param YouTube youtube: A valid YouTube watch URL. """ for stream in youtube.streams: print(stream)
5,301,906
def elevation_nl(xarray=False): """ Fetch surface elevation dataset for the Netherlands. """ fname = REGISTRY.fetch("elevation_nl.nc") ds = xr.open_dataset(fname) if xarray: return ds else: grid = xugrid.Ugrid2d.from_dataset(ds) return xugrid.UgridDataArray(ds["elevat...
5,301,907
def parse_single_event(when, local_tz=None, now=None): """ This function parses a text string describing a single time range on a specified date, returning a tuple of start and end times (datetime.datetime). The year will be set to the current year, unless the optional argument now is provided, in w...
5,301,908
def encode(state: "knx_stack.State", msg: "knx_stack.Msg") -> "knx_stack.Msg": """ >>> import knx_stack >>> address_table = knx_stack.AddressTable(0x1001, [], 255) >>> association_table = knx_stack.AssociationTable(address_table, []) >>> state = knx_stack.State(knx_stack.state.Medium.usb_hid,associa...
5,301,909
def _antialias_filter_image(data, oldstep, newstep, oldfmax=None, window="blackman"): """Apply an anti-aliasing prefilter to an image to prepare it for subsampling. Parameters ---------- data : np.ndimage The 2D image to be filtered. oldstep: float or (float,...
5,301,910
def outitem(title, elems, indent=4): """Output formatted as list item.""" out(title) max_key_len = max(len(key) for key, _ in elems) + 1 for key, val in elems: key_spaced = ('%s:' % key).ljust(max_key_len) out('%s%s %s' % (indent * ' ', key_spaced, val)) out()
5,301,911
def module(stack: List[object], stash: List[object]) -> None: """$method -- $method$.__module__""" stack.append(stack.pop().__module__)
5,301,912
def post(name): """Prints a post.""" global config global dbh if name == "all": return index() elif name == "": return index(config.getint("blog", "default")) elif "\t" in name: (selector, term) = name.split("\t", 1) return search(term) c = dbh.cursor() c.execute("SELECT post_title, post_content FROM...
5,301,913
def read_csv(csv_path: PathLike) -> pandas.DataFrame: """ Read a csv file. Returns a DataFrame. """ csv_info = pandas.read_table( csv_path, sep=",", index_col=False, header=None, ).T csv_info.columns += 1 # Make the channel numbers correspond to the MatLab ch...
5,301,914
def create_post(title): """Create a new post.""" # Create an empty contents file filename = "posts/" + title.lower().replace(" ", "_") + ".html" # after taking a input title , a string is created with title removing spaces and upper caps outfile = open("contents/" + title.lower().replace(" ", "_") +...
5,301,915
def update_index_memory_optimize(document_list): """ update index with optimized memory usage """ all_documnents = [] for i in tqdm(document_list): all_documnents.append(get_arxiv_document_by_id(i)) print(document_list) unique_term = set() prev_term_index = get_term_freq("WORDCOU...
5,301,916
def c2t00a(tta, ttb, uta, utb, xp, yp): """ Form the celestial-to-terrestrial matrix given the date, the UT1 and the polar motion, using IAU 2000A nutation model. :param tta, ttb: TT as a two-part Julian date. :type tta, ttb: float :param uta, utb: UT1 as a two-part Julian date. :type uta, utb...
5,301,917
def center_of_mass(input, labels=None, index=None): """ Calculate the center of mass of the values of an array at labels. Args: input (cupy.ndarray): Data from which to calculate center-of-mass. The masses can either be positive or negative. labels (cupy.ndarray, optional): Labe...
5,301,918
def encodewrap(s): """改行コードを\nに置換する。""" r = [] if not s: return u"" for c in s: if c == '\\': r.append("\\\\") elif c == '\n': r.append("\\n") elif c == '\r': pass else: r.append(c) return "".join(r...
5,301,919
def initialize_new_task_list(user_info, all_tasks): """ initializes new task and user from POST request """ new_user = User(**user_info) new_user.save() user_id = new_user.id for task in all_tasks.values(): task['user_id'] = user_id new_task = Task(**task) new_task.sa...
5,301,920
def test_omit_after_expanded_paths(InsightsFile, parse_file_spec): """ Files are omitted based on the expanded paths of the uploader.json path """ c = InsightsConfig() data_collector = DataCollector(c) collection_rules = {'files': [{"file": "/etc/yum.repos.d/()*.*\\.repo", "pattern": [], "symbo...
5,301,921
def load_labels(label_path, label_interest): """ Loads the label table. Parameters ---------- label_path: string, path to label csv table label_interest: string, name of variable to predict. Has to be in the table loaded by the parameter label_path. Returns ----...
5,301,922
def clonotype_modularity( adata, ax=None, target_col="clonotype_modularity", jitter: float = 0.01, panel_size: Tuple[float, float] = (6, 4), base_size: float = 2, size_power: Optional[float] = 1, show_labels: bool = True, labels_quantile_cutoff: Tuple[float, float] = (0.9, 0.9), ...
5,301,923
def gen_plot_4(fig, x_recon_l,x_recon_r,inputs_l,inputs_r ): """Create a pyplot plot and save to buffer.""" ax1 = get_ax(x_recon_l, fig, subplot='141', az=0) plot_skeleton_and_scatter(x_recon_l, ax1) ax2 = get_ax(inputs_l, fig, subplot='142', az=0) plot_skeleton_and_scatter(inputs_l, ax2) ax3 = ...
5,301,924
def is_lone_coo(where): """Check if ``where`` has been specified as a single coordinate triplet. """ return (len(where) == 3) and (isinstance(where[0], Integral))
5,301,925
def get_tzoffset(): """ 取得時區差異秒數 (在臺灣會取得負值: -28800) """ global _tzoffset, _tzoffset_last_update current_time = time.time() if (current_time - _tzoffset_last_update) > 3600: _tzoffset_last_update = current_time _tzoffset = time.altzone if _tzoffset is None: _tzoffset = time.timezone if _tzoffset is Non...
5,301,926
def build_metrics(config): """pytorch_lightning metrics""" metrics = {} if config.trainer.metrics is not None: for name, cfg in config.trainer.metrics.items(): metrics[name] = build_from_config(cfg, METRICS) return edict(metrics)
5,301,927
def update_covids(h_settings,stats,screen,hero,covids,bullets,sb): """Verifies if at least one covid of the pandemy has reachead the screen edge and updates the positions of all covids on the pandemy""" check_pandemy_edges(h_settings,covids) covids.update() #Verifies if there is a collision...
5,301,928
def kde_scipy(x, x_grid, bandwidth=0.2, **kwargs): #x_grid = np.linspace(-4.5, 3.5, 1000) """Kernel Density Estimation with Scipy""" # Note that scipy weights its bandwidth by the covariance of the # input data. To make the results comparable to the other methods, # we divide the bandwidth by the s...
5,301,929
def gini(x): """Calculate the Gini coefficient for series of observed values (x). where: * x is the array of observed values (and all x are positive, non-zero values) Note: x must be a numpy array or a pandas series See: https://www.statsdirect.com/help/default.htm#nonparametric_methods/gini.htm ...
5,301,930
def pre_train(est, X, y): """Adjust settings based on data before training""" if X.shape[0]*X.shape[1] <= 1000: est.penalty = 0.01 print('TIR penalty adjusted to',est.penalty)
5,301,931
def try_request(url, params=None, data=None, timeout=5, num_retries=1, method='post'): """ @params dict: 请求查询参数 @data dict: 提交表单数据 @timeout int: 超时时间,单位秒 @num_retries int: 超时重试次数 """ headers = {"User-Agent": "Mozilla/5.0 (X11; CentOS; Linux i686; rv:7.0.1406) Gecko/20100101 %s/%s" % (PROCNAM...
5,301,932
def test_segments_any(input, expected): """Test the "any()" function.""" assert input.any(lambda s: s.raw[-1] <= "2") == expected
5,301,933
def qv_to_char(qv): """Convert a qv to a phred-encoded char.""" return chr(qv + CHAR_OFFSET)
5,301,934
async def test_http_error400(aresponses: ResponsesMockServer) -> None: """Test HTTP 404 response handling.""" aresponses.add( "api.tailscale.com", "/api/v2/test", "GET", aresponses.Response(text="OMG PUPPIES!", status=404), ) async with aiohttp.ClientSession() as session...
5,301,935
def get_public_urls(): """Get a list of available external tunnel URLs""" urls = [] try: http = urllib3.PoolManager() req = http.request('GET', 'http://localhost:4040/api/tunnels') data = str(req.data, 'utf-8') obj = json.loads(data) tunnels = obj['tunnels'] ...
5,301,936
def init(filename: str): """ Initialise the database. """ management = Stardog( endpoint=settings.STARDOG_ENDPOINT, database=settings.STARDOG_DATABASE, username=settings.STARDOG_USERNAME, password=settings.STARDOG_PASSWORD, ) management.init(filename=filename)
5,301,937
def test_quadbin_sibling_null(): """Returns NULL if the sibling does not exist""" result = run_query("SELECT QUADBIN_SIBLING(5192650370358181887, 'up')") assert result[0][0] is None
5,301,938
def check_schema(name, file_contents): """Check a Spack YAML schema against some data""" f = StringIO(file_contents) data = syaml.load(f) spack.config.validate(data, name)
5,301,939
def is_fragment(href): """Return True if href is a fragment else False""" is_fragment = False try: if href[0] == '#': is_fragment = True except IndexError: is_fragment = False return is_fragment
5,301,940
def adjacency_matrix(graph): """ :param graph: :return: dictionary Converts directed graph to an adjacency matrix. Note: The distance from a node to itself is 0 and distance from a node to an unconnected node is defined to be infinite. This does not mean that there is no path from a node to...
5,301,941
def query_shard(args): """Helper for request query from shard, same as shard[query]. Parameters --------- args : (list of (int, number), :class:`~gensim.interfaces.SimilarityABC`) Query and Shard instances Returns ------- :class:`numpy.ndarray` or :class:`scipy.sparse.csr_matrix` ...
5,301,942
def s_cat(inputfiles: List[str], outputfile: str, NumPort: int) -> str: """Concatenate 2 port s files into an n port s file Args: inputfiles (List[str]): List of files outputfile (str): Name of output file - optional NumPort (int): Number of ports - optional Raises: ValueEr...
5,301,943
def is_dir(path): """Is the path a directory""" return os.path.isdir(path)
5,301,944
def test_independent_multi_output_shk_sei( register_posterior_test: RegisterPosterior, q_sqrt_factory: QSqrtFactory, full_cov: bool, full_output_cov: bool, whiten: bool, num_latent_gps: int, output_dims: int, ) -> None: """ Independent multi-output posterior with a shared kernel and ...
5,301,945
def gen_rhombus(width): """Create a generator that yields the rows of a rhombus row by row. So if width = 5 it should generate the following rows one by one: gen = gen_rhombus(5) for row in gen: print(row) output: * *** ***** *** * So the m...
5,301,946
def get_item_by_id(item_id): """ Return item by id :param item_id: :return object: """ return session.query(Catalog).filter_by(id=item_id).first()
5,301,947
def data_generator(X: np.ndarray, encoder_preprocessor: Callable, predictor: Callable, conditional_func: Callable, batch_size: int, shuffle: bool = True, **kwargs): """ Constructs a tensorflow data ...
5,301,948
def plot_nc(*ScanNum,**kwgraph): """ ScanNum = Scan number to be plotted: single scan, or range (first,last,countby) to average. kwgraph = EDC / FilePath / Prefix - Transmission mode: angle integrated EDC. - Angular mode: default: band map only EDC = 'y' : angle integ...
5,301,949
def generate_room_times(course_data: CourseData) -> dict: """ Generates data structure for getting the room availability. """ room_time = {} # iterate through all the courses for course in course_data.courses: # checks if room does not already have an entry if course.room not in ...
5,301,950
def make_mlph_data(modified, h): """Creates features and target labels data with MLPH histogram computations. :param modified: Boolean value to indicate if modified MLPH is used :param h: Integer with window size for MLPH histogram computations :return: Training set features and target labels numpy mat...
5,301,951
def _create_ignore_cell_config(config_file_path: Path, config: str) -> None: """Create configuration file for nbqa.""" config_file_path.write_text(config)
5,301,952
def drawSeasonalDecompose(df): """Draw the widgets for seasonal decompose""" #Display de plot of the data if not isinstance(df, str): with plotSDOutput: fig_layout = widgets.Layout(width='auto', height='auto') fig_marg = dict(top=30, bottom=20, left=50, right=20) ...
5,301,953
def do_download_photo(dirname, pset, photo, size_label, suffix, get_filename, skip_download=False, save_json=False): """ Handle the downloading of a single photo @param dirname: str, directory to download to @param pset: FlickrList, photo list to download @param photo: FlickrP...
5,301,954
def add_poster_by_email(conference, message): """ :param Conference conference: :param ConferenceMessage message: """ # Fail if no attachments if not message.attachments: return send_mail( message.sender_email, CONFERENCE_FAILED, fullname=message.sende...
5,301,955
def _remove_scheme(bucket_path): """Remove scheme from the bucket path.""" if '://' not in bucket_path: raise BuildManagerException('Invalid bucket path: ' + bucket_path) return bucket_path.split('://')[1]
5,301,956
def check_if_limits_executed(product, log_dir, quiet): """Function which checks if any of our two limit orders have executed since the last time this script was run. It checks by looking at the order ids in the file current_order_ids.txt, and comparing to the current active orders. If any have exec...
5,301,957
def check_admin(): """ check for an admin. If no admin user, ask for one and add to chatters db. """ dbmgr = DatabaseManager('db/bottoman.db') permissions_list = [i[0] for i in dbmgr.query( "SELECT permissions \ ...
5,301,958
def test_verify_spec_fails(capsys): """ We could check more functionality, but at that point we'd just be testing cerberus. This test is just to verify that a failure will happen and will be presented as we'd expect """ spec_yaml = """ fred: attribute: - flub """ ...
5,301,959
def gen_mask_array(icon_dir, dtype): """Generates a numpy array of an icon mask.""" icon = Image.open(os.path.join(icon_dir, 'icon.png')) mask = Image.new("RGBA", icon.size, (255, 255, 255, 255)) mask.paste(icon, icon) mask_array = np.array(mask, dtype=dtype) return mask_array
5,301,960
def run_sources_on_mesh(mesh, sources_list, processes=1): """ Run multiple sets of sources on the mesh, supports multiprocessing. :param mesh: Mesh to be used in calculations. :param sources_list: a LIST of LISTS of sources, like: [[mag1_1, mag1_2, mag1_3], [mag2_2, mag2_2, mag2_3], ...] ...
5,301,961
def test_shacl_shapes(): """Test SHACL shapes that should fail SHACL validation.""" # We start by constructing a tree that consists of a single node. graph = Graph() node1 = BNode() graph.add((node1, RDF.type, CDAO_NODE)) save_graph_and_validate(graph, False) # If we add a non-CDAO_Node as...
5,301,962
def download(ctx, source, destination, f): """Download a file from EPIC SOURCE to local DESTINATION SOURCE should be prefixed with "epic://"\n Example, download EPIC file from /my_sim_data/my.file to directory ./work/\n "epiccli sync download epic://my_sim_data/my.file ./work/"\n to download whole ...
5,301,963
def test_get_sample_rejected_status(datareader): """ This test checks: - DataReader::get_sample_rejected_status """ status = fastdds.SampleRejectedStatus() assert(fastdds.ReturnCode_t.RETCODE_OK == datareader.get_sample_rejected_status(status)) assert(0 == status.total_count) ...
5,301,964
def parse_xml_io(xml_io): """ Parses xml and get data for mapped_name key """ assert xml_io is not None port_names = [] for xml_cell in xml_io.findall("CELL"): mapped_name = xml_cell.get("mapped_name") # define properties for scalar pins scalar_mapped_pins = vec_to_scalar...
5,301,965
def isposdef(A): """ Check if a matrix positive definite.""" if np.array_equal(A, A.T): try: np.linalg.cholesky(A) return True except np.linalg.LinAlgError: return False else: return False
5,301,966
def read(stream): """Read a Scheme expression from a stream""" def read_ahead(token): if token == '(': expr = [] while True: token = stream.next_token() if token == ')': return expr else: expr...
5,301,967
def reset_initial_conditions(ClockStruct, InitCond, ParamStruct, weather): """ Function to reset initial model conditions for start of growing season (when running model over multiple seasons) *Arguments:*\n `ClockStruct` : `ClockStructClass` : model time paramaters `InitCond` : `InitCondCl...
5,301,968
async def ws_handle_remove_entity_card( hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict ) -> None: """Handle remove entity card command.""" path = "dwains-dashboard/configs/cards/entities" filename = hass.config.path(path+"/"+msg["entityId"]+".yaml") if os.path.e...
5,301,969
def _get_interpreters_relative(): """ Get interpreters relative to our prefix and the parent directory. This allows Pyzo to be shipped inside a pre-installed conda env. """ pythonname = "python" + ".exe" * sys.platform.startswith("win") exes = [] for d in [".", ".."]: for fname in...
5,301,970
def test_copying_file_to_directory(tmpdir): """If copying from directory to file, place file in directory.""" temp_dir = Path(tmpdir) / 'content' temp_dir.mkdir() target = Path(tmpdir) / 'target' target.mkdir() file1 = temp_dir / 'file1' file1.touch() copy_options = { 'content...
5,301,971
def show_component(comp, w1, w3, comp_num): """ Show a plot of the specified component image. :param comp: numpy array, set of n_comp images, each X x Y :param w1: x-axis, X x 1 numpy array :param w3: y-axis, Y x 1 numpy array :param comp_num: component number to plot (1 through n_comp) :ret...
5,301,972
def move_back_in(user, building, level, room_number, mac, processor, traffic_group_id=None): """Move a user back in to a given room. This function sets `user.room` accordingly, adds a new :py:cls:`Host` with an interface with the given MAC, and adds the user to :py:obj:`config.member_g...
5,301,973
def test_build_full_io_compartment(session, biology_qualifiers, namespaces): """Expect that a fully fleshed out compartment can be serialized.""" compartment = Compartment(notes="bla bla bla") go = namespaces["go"] compartment.names = [ CompartmentName(name=n, namespace=go) for n in ["cytosol", ...
5,301,974
def myocardialmass(myocardvol): """ Specific gravity of heart muscle (1.05 g/ml) """ return myocardvol*1.05
5,301,975
def lineEdit(*args, editable:bool=True, transparentBackground:bool=True, borders=False, **kwargs): """ Generate a pre-customized QLineEdit Widget :param parent: Parent Index :param editable: Defines whether the line edit should be editable or not :param transparentBackground: Sets the style sheet to a ...
5,301,976
def sheva_nah_ending_tsere_hiriq_male(neg_idx, guess, guesses): """`sheva` before `tsere`, `hiriq-male` is `sheva-nah` This rule was emperically checked for the Pentateuch. """ pattern = [ {"vowel": T.NAME_SHEVA}, {"vowel": T.NAME_TSERE}, {"vowel": T.NAME_HIRIQ_MALE_YOD}, ...
5,301,977
def train(gan, train_dataset, n_epochs, epochs_so_far=0, checkpoint_path=None): """Train the GAN model Args: gan (GAN): GAN model to train train_dataset (tf.data.Dataset): training dataset n_epochs (int): number of epochs to train epochs_so_far (int, optional): starting epoch (i...
5,301,978
def test_start_task_other_status(mock_agent): """Test a task that's already marked as 'running'. In this case, we expect an error. Not sure we particularly care about the encoded session, so we just use a Mock session. """ mock_agent.register_task('test_task', tfunc) # set session to 'run...
5,301,979
def curvature(dem, res, kind, L=None): """ Calculate curvature for a digital terrain model. Parameters ---------- dem : ndarray Terrain elevation (m). res : float DEM resolution (m). kind : str Curvature calculation method. Allowed values are: - 'liston...
5,301,980
def parse_datasets(xml_str, tds_type): """ """ results = [] root = etree.fromstring(xml_str) ns_map = root.nsmap # check a ns_map for a key of None, i.e.default namespace and set to arbitray prefix so we can use xpath # Search for k of None, delete and set a random prefix to the original ns value for k...
5,301,981
def test_atomic_name_min_length_2_nistxml_sv_iv_atomic_name_min_length_3_2(mode, save_output, output_format): """ Type atomic/Name is restricted by facet minLength with value 28. """ assert_bindings( schema="nistData/atomic/Name/Schema+Instance/NISTSchema-SV-IV-atomic-Name-minLength-3.xsd", ...
5,301,982
async def challenge(websocket, user): """Challenges a user. """ return await websocket.send(f'|/challenge {user}, gen8metronomebattle')
5,301,983
def onset_to_hosp_or_asymp(clip_low=2, clip_high=21.1, mean=6.2, std=4.3): """ Returns the time for someone to either get removed or hospitalized in days within range(clip_low, clip_high), of a truncated_norm(mean, std). """ return sample_truncated_norm(clip_low, clip_high, mean, std)
5,301,984
def validate_endpoint_create_and_update_params( endpoint_type: str, managed: bool, params: dict ) -> None: """ Given an endpoint type of "shared" "server" or "personal" and option values Confirms the option values are valid for the given endpoint """ # options only allowed for GCS endpoints ...
5,301,985
def create_app(debug=False): """Create an application.""" app = Flask(__name__) CORS(app) socketio.cors_allowed_origins = "*" socketio.init_app(app) # these imports required to be after socketio initialization from .main.config import MachineType from .main.model import PicoF...
5,301,986
def assert_allclose( actual: numpy.int64, desired: int, rtol: float, atol: float, equal_nan: bool, err_msg: str, ): """ usage.statsmodels: 1 """ ...
5,301,987
def python(ctx, args, **kwargs): """ Uses python from virtualenv if available, falls back to ENV variable PYTHON """ ctx.run('{python} {args}'.format(python=prefix_venv(os.environ.get('PYTHON')), args=args), shell=os.environ.get('INVOKE_SHELL'), **kwargs)
5,301,988
def _error(message): """error(message: string) Prints a usage message incorporating the message to stderr and exits. """ args = {'message': message} _exit(2, ("Error: %(message)s\n" % args))
5,301,989
def create_character_ngrams(text_list, length): """ Create character ngrams of the specified length from a string of text Args: text_list (list): Pre-tokenized text token to process. length (int): Length of ngrams to create. http://stackoverflow.com/questions/18658106/quick-implement...
5,301,990
def unscramble_wavefunction(wavefunction): """ the state ordering within the wavefunctions (complex numpy array) returned by cirq's simulate() function are not in standard sequential counting order (0, 1, 2), but are scrambled this function takes a wavefunction of arbitrary qubit legnth, an...
5,301,991
def fit_bonus_points( gameweek=NEXT_GAMEWEEK, season=CURRENT_SEASON, min_matches=10, dbsession=session ): """Calculate the average bonus points scored by each player for matches they play between 60 and 90 minutes, and matches they play between 30 and 59 minutes. Mean is calculated as sum of all bonus p...
5,301,992
def get_gt_SHT(gt_path, img_w, img_h, scaling=1., sigma=4): """ Retrieves and generates the GT density for the ShanghaiTech A/B dataset.""" mat = io.loadmat(gt_path) points = mat["image_info"][0, 0][0, 0][0] den = gen_scaled_den_from_points(img_w, img_h, points, scaling, sigma) return den
5,301,993
def gen_output_mappings( outputs : int, inputs : int, active : int, rows : int = MAX_ROW_COUNT, columns : int = MAX_COLUMN_COUNT, base_off : int = 0, min_tgts : int = 1, max_tgts : int = 1, exclude : Optional[NodeID] = None, debug : bool = False, ) -> Tuple[List[Out...
5,301,994
def test_constraint_type(): """Test ConstraintType.""" constraint_type_values = { "int": 12, "bool": True, "float": 10.4, "str": "some_string", "location": Location(1.1, 2.2), } constraint_type_types = { "int": int, "bool": bool, "float": f...
5,301,995
def TestMachineCleanup(user_profile_dir, host_logs=None): """Cleans up test machine so as not to impact other tests. Args: user_profile_dir: the user-profile folder used by Chromoting tests. host_logs: List of me2me host logs; these will be deleted. """ # Stop the host service. RunCommandInSubProces...
5,301,996
def air2vacMortonIAU(wl_air): """Take an input air wavelength in Angstroms and return the vacuum wavelength. Formula taken from https://www.astro.uu.se/valdwiki/Air-to-vacuum%20conversion """ s = 1e4 / wl_air n = 1 + 0.00008336624212083 + (0.02408926869968 / (130.1065924522 - s**2))\ ...
5,301,997
def verify_path(file_name, folder): """Ensures folders for checkpoints and network parameters exists. :param file_name: Name of file. :param folder: Name of folder """ folder_path = os.path.join(os.getcwd(), folder) if not os.path.isdir(folder_path): os.makedirs(folder_path) ...
5,301,998
def get_vocabs(datasets): """Build vocabulary from an iterable of datasets objects Args: datasets: a list of dataset objects Returns: a set of all the words in the dataset """ print("Building vocab...") vocab_words = set() vocab_tags = set() for dataset in datasets: ...
5,301,999