content
stringlengths
22
815k
id
int64
0
4.91M
def build_dict_det_pair(det_df): """ Build the dictionary that converts from detector pair to index and angle Parameters ---------- det_df : pandas dataFrame dataFrame of detector pair indices and angles Returns ------- dict_pair_to_index : dict keys: detecto...
5,303,600
def random_layout(H, center=None, dim=2, seed=None): """Position nodes uniformly at random in the unit square. Exactly as networkx does. For every node, a position is generated by choosing each of dim coordinates uniformly at random on the interval [0.0, 1.0). NumPy (http://scipy.org) is required for th...
5,303,601
def test_close_handles_odbql_error(monkeypatch): """Test that the close method handles ODBQL_ERROR.""" def mock_odbql_close(connection): """mock odbql_close""" return py3odb.odbql.ODBQL_ERROR monkeypatch.setattr("py3odb.odbql.odbql_close", mock_odbql_close) conn = py3odb.connect("") ...
5,303,602
def _get_serializer(meta: Optional[AttributeMetadata]) -> Callable[[Any], str]: """Get a serializer function from the given attribute metadata.""" serializer = None if meta is None else SERIALIZER_MAP.get(meta.attribute_type) if serializer is None: serializer = SERIALIZER_MAP.get("default", repr) ...
5,303,603
def client(): """ Create the configuration that we will have to use to be able to run our test cases, with this method we won't be able to run our test cases """ app = create_app() return app.test_client()
5,303,604
def WR(df, n): """威廉指标""" hn = df["high"].rolling(n).max() ln = df["low"].rolling(n).min() df["wr"] = (hn - df["close"]) / (hn - ln) * (-100) return df
5,303,605
def volume_correction(distance_values, temperature=298.15): """Calculates the volume correction of the free energy Parameters ------------- distance_values : numpy.array 1-D numpy.array containing the distance of the ligand from the protein (center of mass - center of mass) IN A...
5,303,606
def key_released(key: int) -> bool: """Determines if the given key is released.""" # Handle the queued keys.""" for event in pygame_queued_events: if event.type == pygame.KEYUP: if event.key == key: pygame_queued_events.remove(event) return True # Time...
5,303,607
def extract_mocha_summary(lines): """ Example mocha summary lines (both lines can be missing if no tests passed/failed): ✔ 3 tests completed ✖ 1 test failed """ passes, fails = 0, 0 for line in lines: if line and line[0] == '✔': passes = int(line.split()[1]) elif ...
5,303,608
def test_descritize_non_square(): """Test to make sure requesting a grid with a num_rays that is not a perfect square raises ValueError. """ if not HAVE_PYMOAB: raise SkipTest p = multiprocessing.Pool() results = p.apply_async(discretize_non_square) r = results.get() assert_equa...
5,303,609
def vote(request, ballot_url): """ For ballots with tokens. """ display_ballot = get_object_or_404(BallotPaper, ballot_url=ballot_url) queryset = Category.objects.filter(ballot_paper=display_ballot) caty = get_list_or_404(queryset) user = request.user for cat in caty: try: selected_choice = cat.choice_set...
5,303,610
def index(): """Homepage""" dishes = Dishes.query.all() if not dishes: flash("No dishes are available in Mess!", category='warning') return render_template( 'index.html', year=year, dishes=dishes )
5,303,611
def get_gts(init_weight, aft_weight): """ """ gts = np.where(init_weight != aft_weight) return gts
5,303,612
def get_headword(tag): """ Extract the content of a BeautifulSoup element Tag object. Args: tag (Tag): a BeautifulSoup element tag, obtained by extracting from a soup Returns: short, long ([str]): short and long form of a word in dictionary definition Modules: bs4 (Beautifu...
5,303,613
def _boundary(sample, n_i, n_g, n_t, b): """ Find matrix for R and T for air/glass/slab interface. The resulting matrix is a diagonal matrix that is represented as an array. The reflection matrix is the same entering or exiting the slab. The transmission matrices should differ by a factor of ...
5,303,614
def test_workflow_nothing_there_yet(client): """ test policy put good""" # no type there yet res = client.get(ADM_CTRL_TYPE) assert res.status_code == 404 # no types at all res = client.get("/a1-p/policytypes") assert res.status_code == 200 assert res.json == [] # instance 404 beca...
5,303,615
def gen_all_datasets(dir): """Looks through all .mat files in a directory, or just returns that file if it's only one.""" if dir.endswith(".mat"): (r, f) = os.path.split(dir) (f, e) = os.path.splitext(f) return [(r, f)] file_list = [] for r,d,f in os.walk(dir): for f...
5,303,616
def get_obo() -> Obo: """Get ITIS as OBO.""" return Obo( ontology=PREFIX, name='Integrated Taxonomic Information System', iter_terms=iter_terms, auto_generated_by=f'bio2obo:{PREFIX}', data_version=_get_version(), )
5,303,617
def _calculate_discount_for_last_element( lines_total_prices, total_price, total_discount_amount, currency ): """Calculate the discount for last element. If the given line is last on the list we should calculate the discount by difference between total discount amount and sum of discounts applied to re...
5,303,618
def tfprint(tensor, prefix=None, summarize=256): """tf.Printのショートカットメソッド Return: tf.Print(tensor, [tensor],・・・・) の復帰値をそのまま返す。 """ if stop: # stopならprint無し return tensor if prefix is None: prefix = tensor.name if not re.match(out_name_pattern,...
5,303,619
def replace_text(text): """ Android资源文件英文的双引号或单引号需要加斜杠,否则会报错,中文的双引号和单引号不需要 :param text: :return: """ temp_text = text.replace(r' \ "', r' \"').replace(r' / ', r'/').replace(r'% ', r' %') \ .replace(r' $ ', r'$').replace(r'$ ', r'$').replace(r'¥ ', r'¥ ').replace(r'¥ ', r'¥ ').replace(r...
5,303,620
def all_installed_products_are_not_instantiated(step): """ Assertions to check if all productInstances do not exist in SDC """ for product in world.list_of_installed_products: world.product_name = product['product_name'] world.product_version = product['product_version'] the_product_is_n...
5,303,621
def mask_linear(module, value): """Mask linear.""" if not isinstance(module, torch.nn.Linear) or not value or sum(value) == len(value): return idx_in = [idx for idx, value in enumerate(value) if value == 0] if not idx_in: return module.weight.data[:, idx_in] = 0
5,303,622
def change_pwd(username, password): """ 修改密码 @param self 绑定为当前对象 @param username 要修改密码的账户名 @param password 新密码 """ try: sock = socksPool.get() cmd = [[{'op': '5'}, {'name': username}, {'pwd': password}]] json_data = _assembly_request(cmd) if json_data: ...
5,303,623
def quantity_list_validator( item: List[Union[unyt.unyt_quantity, unyt.unyt_array, str]] ) -> List[unyt.unyt_quantity]: """ Converts a list of either strings (as ``FloatValue UnitX / UnitY``) or unyt quantities and arrays to a list of unyt quantities. Parameters ---------- item: List[Union...
5,303,624
def upwindFirstENO3a(grid, data, dim, generateAll=False): """ upwindFirstENO3a: third order upwind approx of first deriv by divided diffs. [ derivL, derivR ] = upwindFirstENO3a(grid, data, dim, generateAll) Computes a third order directional approximation to the first derivative, using an ...
5,303,625
def start_proxy(port, project): """Start HTTPtools in Proxy Mode.""" argz = ['httptools', '-m', 'capture', '-p', str(port), '-n', project] proxies, _ = upstream_proxy('http') if proxies['http']: argz.extend(['-u', proxies['http']]) fnull = open(os.devnull, 'w') su...
5,303,626
def _import_from_path(name, path): """A helper function that imports a module from the given path.""" spec = importlib.util.spec_from_file_location(name, path) mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) return mod
5,303,627
def makeextensive(curvelist): """ Set the y-values such that ``y[i] *= (x[i+1] - x[i])`` >>> curves = pydvif.read('testData.txt') >>> pydvif.makeextensive(curves) >>> pydvif.create_plot(curves, legend=True) :param curvelist: The curve or list of curves :type curvelist: Curve or list ...
5,303,628
def netstat(): """ Return information on open ports and states .. note:: On BSD minions, the output contains PID info (where available) for each netstat entry, fetched from sockstat/fstat output. .. versionchanged:: 2014.1.4 Added support for OpenBSD, FreeBSD, and NetBSD ....
5,303,629
def add_package_headings(toc: Toc, root_pkg: str, labels: Mapping[str, str]) -> Toc: """Breaks up a flat structure with headings for each 1st-level package.""" new_toc = [] current_section = None for entry in toc.get('toc', []): new_entry = d...
5,303,630
def wrap_deepmind(env, episode_life=True, clip_rewards=True, stack=4): """Configure environment for DeepMind-style Atari. Note: this does not include frame stacking!""" assert 'NoFrameskip' in env.spec.id # required for DeepMind-style skip if episode_life: env = EpisodicLifeEnv(env) # env ...
5,303,631
def setup(): """ This creates the initial directory structure as defined in the RCFILE. This is expected to be called once, when a new site is being commissioned. """ _status("Creating directories.") _init() run("mkdir -p %(site_root)s" % env) run("mkdir -p `dirname %(current_path)s`" ...
5,303,632
def push_formats(spreadsheet, id_to_format, sheet_formats): """Batch add formats to a spreadsheet.""" for sheet_title, cell_to_format in sheet_formats.items(): worksheet = spreadsheet.worksheet(sheet_title) requests = [] for cell, fmt_id in cell_to_format.items(): fmt = id_to...
5,303,633
def build_dataset( x: np.ndarray, y: np.ndarray, num_classes: int, shuffle_buffer_size: int = 0, augment: bool = False, augment_color: bool = False, augment_horizontal_flip: bool = False, augment_offset: int = 0, seed: Optional[int] = None, normalization_factor: float = 255.0, ) ...
5,303,634
def factorial(n): """ Returns the factorial of n. e.g. factorial(7) = 7x6x5x4x3x2x1 = 5040 """ answer = 1 for i in range(n, 1, -1): answer = answer * i return answer
5,303,635
def get_available_holidays_in_countries( countries, year_start, year_end): """Returns a dictionary mapping each country to its holidays between the years specified. :param countries: List[str] countries for which we need holidays :param year_start: int first ...
5,303,636
def plot_fancy_thing(metrics, output_name): """ Draws a bar plot of the metrics passed as parameter; It requires a plotly account to be locally installed on the machine :param metrics: the metrics to plot :param name: the name of the metrics """ values, names = zip(*metrics) names = [x....
5,303,637
def load_json(filename: str) -> dict: """Load JSON from file.""" try: with open(filename, encoding="utf-8") as fdesc: return json.loads(fdesc.read()) # type: ignore except (FileNotFoundError, ValueError, OSError) as error: LOGGER.debug("Loading %s failed: %s", filename, error) ...
5,303,638
def vfun(self, parr="", func="", par1="", con1="", con2="", con3="", **kwargs): """Performs a function on a single array parameter. APDL Command: *VFUN Parameters ---------- parr The name of the resulting numeric array parameter vector. See *SET for name restrictions. ...
5,303,639
def send_email(*args, **kwargs): """ :param host: SMTP host :param port: SMTP port :param username: username to authenticate with :param email_string: body of the email (a text string) :param recipients: comma-separated list of recipients :param subject: subject of the email :param tunn...
5,303,640
def hard_reset(): """ Resets the pyboard in a manner similar to pushing the external RESET button. """
5,303,641
async def async_setup_entry(hass, _config_entry, async_add_entities): """Set up Tesy sensor dynamically.""" async def async_discover_sensor(dev, instance): """Discover and add a discovered sensor.""" async_add_entities([TesyWaterHeater(dev, instance)]) async_dispatcher_connect( ...
5,303,642
def reverse_colors(frame): """ Reverse the order of colors in a frame from RGB to BGR and from BGR to RGB. """ return frame[:, :, ::-1]
5,303,643
def extract_geohash_from_path(paths): """ :param paths: Sentinel2 paths;Shape = (batch_size, no_of_timestamps=3) :return: 1d list of geohashes for which imputation is made """ return [i[i.find('9q'):i.find('9q')+5] for i in paths]
5,303,644
def load_defaults(_args): """ Load a hardcoded set of defaults which are useful in testing """ # Could also put the default on the class, but seems too fancy configs = [ ThreatExchangeConfig( "303636684709969", fetcher_active=True, privacy_group_name="Tes...
5,303,645
def chl_decision(uncorrected_chl_value, regression_table, sample_date): """ Decision tree for correcting Chl values using a linear model regression results :param uncorrected_chl_value: the value to correct :param regression_table: the table to look up the rsquared, a coeff, b coeff for given date :param sample_da...
5,303,646
def PCA_reduction( df: pd.DataFrame, cols: List[str], n_components: int, prefix: str = 'PCA_', random_seed: int = 42, keep: bool = False ) -> pd.DataFrame: """ Substitutes given feature columns with their principal components. Args: df: Dataframe to work on. ...
5,303,647
def getunknownwordmodel(tagged_sents, unknownword, unknownthreshold, openclassthreshold): """Collect statistics for an unknown word model. :param tagged_sents: the sentences from the training set with the gold POS tags from the treebank. :param unknownword: a function that returns a signature for a given word;...
5,303,648
def plot_kde_data(data, epoch, preview_path, **kwards): """ Plot the data Parameters -------------- data: array whose shape is (datasize, 2) plotted data epoch: int Epoch number preview_path: PosixPath file path to save plotted result **kwards: key, value pairings...
5,303,649
def __alive_bar(config, total=None, *, calibrate=None, _cond=threading.Condition): """Actual alive_bar handler, that exposes internal functions for configuration of both normal operation and overhead estimation.""" if total is not None: if not isinstance(total, int): raise TypeError(f"i...
5,303,650
def read_lattice(filename='lattice.in'): """Reads the lattice.in file. Args: filename (str, optional): The filename to be read in. Default is 'lattice.in'. Returns: result (dict): A dictionary with the following fields: "sizes": the range of cell sizes, "lat_vecs": l...
5,303,651
def is_compatible(testVersion: str, baseVersion: str = None) -> bool: """ Determine if testVersion is compatible with baseVersion Args: testVersion: the version identifier to test, as the string 'x.y.z' where x is the major version, y is the minor version, and z is the patch. ...
5,303,652
def counter_unit(): """Unit symbol of a counter, motor or EPICS record""" return unit(counter_name)
5,303,653
def resample_apply(rule: str, func: Optional[Callable[..., Sequence]], series, *args, agg='last', **kwargs): """ Apply `func` (such as an indicator) to `series`, resampled to a time frame specified by `rule`. When...
5,303,654
def print_partial_data(params: dict, count_per_label=5, clinc_labels=None): """ Prints partial data from the original Clinc150 dataset for verification. :param params: Has the root_path as a key. :param count_per_label: number of items you want to see per label. :param clinc_labels: list of labels t...
5,303,655
def algo_parts(name: str) -> tuple[str, Optional[int]]: """Return a tuple of an algorithm's name and optional number suffix. Example:: >>> algo_parts('rot13') ('rot', 13) >>> algo_parts('whirlpool') ('whirlpool', None) """ base_algo = name.rstrip('0123456789') try: ...
5,303,656
def gen_lib_options (compiler, library_dirs, runtime_library_dirs, libraries): """Generate linker options for searching library directories and linking with specific libraries. 'libraries' and 'library_dirs' are, respectively, lists of library names (not filenames!) and search directories. Returns a l...
5,303,657
def get_page_ids_by_slug(slug, parents=None): """ Return all the page id according to a slug """ if not parents: sql = ''' SELECT c.page_id, c.language, MAX(c.creation_date) FROM pages_content c WHERE c.type = 'slug' AND c.body = %s GROUP BY c.page_id, c.language ...
5,303,658
def linear_q_learning(env, max_episodes, eta, gamma, epsilon, seed=None): """ Initialize coefficients, Q values and random state. Iterating through max episodes: start game. Until game over, choose action, play action to get rewards and new features. Use new features to select best new action. ...
5,303,659
def voc_to_coco( xml_dir: Path, image_dir: Optional[Path] = None, category_mapping: Optional[Mapping[str, int]] = None, ): """Convert VOC to MS COCO images and annotations Parameters ---------- xml_dir : pathlib.Path image_dir : pathlib.Path category_mapping : Mapping By def...
5,303,660
def get_non_zero_deplexed_samples(sample_sheet): """ Given a sample sheet return the names of the samples for which one or more reads were found. The sample sheet is assumed to have columns, ``SampleID``, ``TagRead`` and ``NumReads``. Rows whose ``SampleID`` values are ``Unassigned`` or ``Total...
5,303,661
def storbinary(host, port, user, password, stream, filename, ignore_host=False, tls=False, debug_level=0): """Upload streamio object to ftp""" # use correct version of ftp if tls: if ignore_host: session = FTP_TLS_IgnoreHost() else: session = ftplib.FTP...
5,303,662
def stakes(): """List all your stakes.""" click.echo(prettify(napi.get_stakes()))
5,303,663
def eval_vectors(args): """ Method for evaluating a list of vectors""" vectors = json.load(open(args.testvectors)) annotations_to_csv(args.labels, "./eval/annotations.csv") materials = read_gazetter(args.materials) items = read_gazetter(args.items) styles = read_gazetter(args.styles) compani...
5,303,664
def isolate_lru_cache(lru_cache_object): """Clear the cache of an LRU cache object on entering and exiting.""" lru_cache_object.cache_clear() try: yield finally: lru_cache_object.cache_clear()
5,303,665
async def updateImplementationStatus(namespace, name): """Helper function to get EndPointSice and find the Resdy status. Args: * namespace (String): The namespace for the Kubernetes Service that implements the API * name (String): The name of the Kubernetes Service that implements the API ...
5,303,666
def getGateEstimates(): """ Returns a list of gate estimates for the current_user's company """ if request.method == 'GET': gates = dbSession.query(Gate) gates = gates.filter(Gate.company_name == current_user.company_name).all() if len(gates) == 0: return bad_request('No gate...
5,303,667
def validate_pandas( cnx_table, sql, cases, col_count, method="one", data_type="float", epsilon=None, scale=0, timezone=None, ): """Tests that parameters can be customized. Args: cnx_table: Connection object. sql: SQL command for execution. cases: Tes...
5,303,668
def calculate_rsi(analysis_df, column, window): """ Calculates relative stength index. Args: analysis_df: Pandas dataframe with a closing price column column: String representing the name of the closing price column window: Integer representing the number of periods used in the RSI ...
5,303,669
async def test_user_form_cannot_connect(opp): """Test we handle cannot connect error.""" result = await opp.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) with patch( "openpeerpower.components.nzbget.coordinator.NZBGetAPI.version", side_effect=NZBGetAP...
5,303,670
def repl(ctx, english): """the Hapy REPL (interactive programming environment)""" prompt = f"hapy>" lcls = {"sys": sys, "__name__": "__repl__"} runner = InteractiveConsole(locals=lcls) # join all the arguments all_args = " ".join(ctx.args) # only match arguments ending in '.hapy' for now ...
5,303,671
def test_match_l1c_gmi(): """ Tests reading a GMI L1C file and matching it to data in a GMI .sim file. """ l1c_path = DATA_PATH / "gmi" / "l1c" l1c_file = L1CFile.open_granule(27510, l1c_path, sensors.GMI) l1c_data = l1c_file.to_xarray_dataset() tbs = l1c_data.brightness_temperatures.dat...
5,303,672
def has_slide_type(cell, slide_type): """ Select cells that have a given slide type :param cell: Cell object to select :param slide_type: Slide Type(s): '-', 'skip', 'slide', 'subslide', 'fragment', 'notes' :type slide_type: str / set / list :return: a bool object (True if cell should be select...
5,303,673
def yolo_head(feats: tf.Tensor, input_shape: tf.Tensor, calc_loss: bool = False ) -> Tuple[tf.Tensor, tf.Tensor, tf.Tensor, tf.Tensor]: """Convert final layer features to bounding box parameters.""" # Reshape to batch, height, width, num_anchors, box_params. grid_sha...
5,303,674
def test_homepage(client): """Tests the rendering of the custom homepage.""" live_pages = Page.objects.live() home_page = live_pages.get(title="Home") response = client.get(home_page.get_url()) assert response.status_code == 200 assert home_page.get_url() == "/" assert "home/home_page.html" ...
5,303,675
def shelter(): """ RESTful CRUD controller >>> resource="shelter" >>> from applications.sahana.modules.s3_test import WSGI_Test >>> test=WSGI_Test(db) >>> "200 OK" in test.getPage("/sahana/%s/%s" % (module,resource)) True >>> test.assertHeader("Content-Type", "text/html") >>> test.asse...
5,303,676
def clip_matrix(left, right, bottom, top, near, far, perspective=False): """Returns a matrix to obtain normalized device coordinates from a frustum. The frustum bounds are axis-aligned along x (left, right), y (bottom, top) and z (near, far). Normalized device coordinates are in the range [-1, 1] ...
5,303,677
def metadata(request): """ Add some generally useful metadata to the template context """ return {'display_version': getattr(settings, 'DISPLAY_VERSION', False), 'version': getattr(settings, 'VERSION', 'N/A'), 'shop_name': settings.OSCAR_SHOP_NAME, 'shop_tagline': set...
5,303,678
def engine(request): """Create an SQLAlchemy engine with a disposable PostgreSQL database.""" if request.param == 'postgresql': postgresql = request.getfixturevalue('postgresql') return create_engine('postgresql://', poolclass=StaticPool, ...
5,303,679
def rigids_to_tensor_flat12( r: Rigids # shape (...) ) -> paddle.Tensor: # shape (..., 12) """Flat12 encoding: rotation matrix (9 floats) + translation (3 floats).""" return paddle.stack(list(r.rot) + list(r.trans), axis=-1)
5,303,680
def auto_expand(list_or_value): """Given a list return it, given a scalar return a corresponding broadcasted 'infinite list'""" if isinstance(list_or_value, list): return list_or_value else: class Expanded: def __init__(self, value): self.value = value def __getitem__(self, i): ...
5,303,681
def defined(var): """Returns true if the variable has already been defined. Otherwise, returns false.""" str(var) if not isinstance(var, str): raise Exception("defined() must be given a string") if not re.search(r'[A-Za-z][A-Za-z0-9\_]*', var): raise Exception("defined() must be given a...
5,303,682
def shape_from_zip(zip_filename, shape_filename=None): """ Loads a shapefile from a zipfile. If shape_filename is None, we guess which shape file you want. """ dest = unzip(zip_filename) if shape_filename is None: shape_filenames = [ splitext(filename)[0] for fi...
5,303,683
def auto_crop(data_and_label, mode=None, buffer_size=10, debug=False): """ return cropped [img, label] data_and_label : list of 3d-array numpy image. e.g. [data, labels] crop area = (x of estimated brain area + 2 * buffer_size) * (y of estimated brain area + 2 * buffer_size) """ imgs =...
5,303,684
def add_model_name( name_csv, fig_name, household_weight, neighbor_weight, food_weight, transmission_rate, recovery_rate, progression_rate, hosp_rate, crit_rate, death_rate, init_symp_cases, init_asymp_cases, t_steps, q_time="", q_red="", h_time="", ):...
5,303,685
def add_category( name: str, description: str = None, position: int = 0 ) -> flask.Response: """ This is the endpoint for forum category creation. The ``forums_forums_modify`` permission is required to access this endpoint. .. :quickref: ForumCategory; Create a forum category. **Example reques...
5,303,686
def query(x,db,v=True): """ A function that takes in a query and returns/ prints the result""" conn = sqlite3.connect(db) curs = conn.cursor() my_result = list(curs.execute(x).fetchall()) curs.close() conn.commit() if v is True: print(my_result) return my_result
5,303,687
def build_url(selector, child_key, parent_key): """Return url string that's conditional to `selector` ("site" or "area").""" if selector == "site": return "https://%s.craigslist.org/" % child_key return "https://%s.craigslist.org/%s/" % (parent_key, child_key)
5,303,688
def get_data(): """Get data in form suitable for episodic training. Returns: Train and test data as dictionaries mapping label to list of examples. """ with tf.gfile.GFile(DATA_FILE_FORMAT % 'train', 'rb') as f: processed_train_data = pickle.load(f) with tf.gfile.GFile(DATA_FILE_FORMAT % 'test', ...
5,303,689
def write_files(inp_files, run_path, exe_names=()): """ Write all of the VaReCoF inut files and run the code """ # Write all of the VaReCoF input files for (inp_str, inp_name) in inp_files: file_name = os.path.join(run_path, inp_name) print(file_name) # Write the file wi...
5,303,690
def create_cache_directory( directory_subpath: str, cache_directory: str = DEFAULT_CACHE_DIRECTORY, use_cache: bool = True) -> str: """Create the cache directory structure for the given directory.""" # Ensure the cache_directory always exists. os.makedirs(cache_directory, exist_ok=Tr...
5,303,691
def svd(a, full_matrices=True, algo='svd', **kwargs): """ ctypes wrapper for LAPACK SVD (DGESVD) Factorizes the matrix a into two unitary matrices U and Vh and an 1d-array s of singular values (real, non-negative) such that a == U S Vh if S is an suitably shaped matrix of zeros whose main diagonal ...
5,303,692
def reshape(fd: DahliaFuncDef) -> str: """https://tvm.apache.org/docs/api/python/relay/index.html#tvm.relay.reshape""" data, res = fd.args[0], fd.dest newshape = fd.attributes.get_int_tuple("newshape") ddims = get_dims(data.comp) rdims = get_dims(res.comp) assert ( # See the TVM Relay A...
5,303,693
async def time(ctx): """ Return a video """ aliasUsed = ctx.invoked_with if aliasUsed == "night": emoji = "😴" file = discord.File("./staticfiles/night.mp4", filename="night.mp4") await ctx.send(f"Goodnight, sailers {emoji}", file=file) else: await ctx.send("Specify ...
5,303,694
def convert(digits, base1, base2): """Convert given digits in base1 to digits in base2. digits: str -- string representation of number (in base1) base1: int -- base of given number base2: int -- base to convert to return: str -- string representation of number (in base2)""" # Handle up to base 3...
5,303,695
async def test_if_not_fires_on_change_bool(opp, calls): """Test for not firing on boolean change.""" assert await async_setup_component( opp, automation.DOMAIN, { automation.DOMAIN: { "trigger": { "platform": "template", ...
5,303,696
def _nanuq_get(url, username="", password="", logprefix=""): """returns an open request object to a NANUQ download""" # nanuq has a non-standard form auth log.info("%s GET %s (username=%s)", logprefix, url, username or "") if username: r = requests.post(url, data={'j_username': username, ...
5,303,697
def insert_tables(cur, conn): """ Function that reads data from our staging tables and place into our final data model following the star schema on Redshift. Args: cur: psycopg2 cursor object establishing a connection to our database conn - The corresponding psycopg2 connection to the A...
5,303,698
def initMap(llCrds,urCrds,figsize=(16,16)): """ Function for initializing a figure using a cartopy map projection. Parameters ---------- llCrds : tuple Tuple of (lat,lon) at the lower left corner of the desired domain. urCrds : tuple Tuple of (lat,lon) at the up...
5,303,699