content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def make_non_pad_mask(lengths, xs=None, length_dim=-1): """Make mask tensor containing indices of non-padded part. Args: lengths (LongTensor or List): Batch of lengths (B,). xs (Tensor, optional): The reference tensor. If set, masks will be the same shape as this tensor. length_dim (int...
45c60ed4119958448960db38702e7a31724bce77
3,634,300
import logging def get_time_cols(X: pd.DataFrame, labels: bool = False) -> pd.Series: """Get time columns.""" X = pd.DataFrame(X) logger = logging.getLogger(__name__) is_time = X.dtypes.apply(lambda x: issubclass(x.type, np.datetime64)) n_features = np.sum(is_time) logger.info("The number of ...
c8d350a9ecd5c89fe9d44d31feef5851bd36639e
3,634,301
import json from sys import version import time def load(filename): """Loads result data from the given json file. Args: filename: The name of the input file. """ with open(filename, 'r') as fp: data = json.load(fp) log.debug(f'Read json from {filename}', data) if data['versi...
ad2c04b01e652f26f7ac0be2c7bff5d18024ecdb
3,634,302
def default_browser(): """ Return the name of the default Browser for this system. """ return 'firefox'
a5df3959983bcc11fb59b0aea44a0e6ed42cc579
3,634,303
def dmp_ground(c, u): """ Return a multivariate constant. Examples ======== >>> from sympy.polys.densebasic import dmp_ground >>> dmp_ground(3, 5) [[[[[[3]]]]]] >>> dmp_ground(1, -1) 1 """ if not c: return dmp_zero(u) for i in range(u + 1): c = [c] ...
de3a5743aa4ded69ee0df6aa6d4664919264ccbd
3,634,304
import torch def bkb(gp_model, inducing_points, q_bar=1): """Update the GP model using BKB algorithm. Parameters ---------- gp_model: ExactGP model to update inducing_points: torch.Tensor Tensor of dimension [N x d_x] q_bar: float float with algorithm parameter. ""...
7ac7e4f273dcd3014868bab802da162ca4e01dec
3,634,305
import shlex import tempfile import io import os import sys import subprocess import time def run_duplicate_streams(cmd, timeout=_default_timeout()): """ <Purpose> Provide a function that executes a command in a subprocess and, upon termination, returns its exit code and the contents of what was printed t...
f00454770145543e342d027f33ab36f07ce6f358
3,634,306
def splinter_remote_url(request): """Remote webdriver url. :return: URL of remote webdriver. """ return request.config.option.splinter_remote_url
17bf9bf3ebd7296a2305fe9edeb7168fbca7db10
3,634,307
import shlex import traceback def run(*args, **kwargs): """Run the external command. See ``subprocess.check_output``.""" # normalize args if len(args) == 1: if isinstance(args[0], str): args = shlex.split(args[0], posix=IS_POSIX) else: args = args[0] if args[0]...
d546ec949ec97b418f43319a6da90ef019bba52c
3,634,308
def tfresize_image(image, size=(cfg.IMG_W, cfg.IMG_H)): """ Resize image. """ return tf.image.resize(image, size)
e18fbe2b2ad467e459a0615e088e52279d54d8fc
3,634,309
def history(): """Show history of transactions""" # Get information about stocks that the transactions transactions = db.execute( "SELECT symbol, shares, price_per_share, price, time FROM transactions WHERE user_id = ?", session["user_id"], ) return render_template("history.html", ...
53aee51f5a77e6f00b55915b0d1c8d2f611bf9d5
3,634,310
def serve_static_file(request, filename, root=MEDIA_ROOT, force_content_type=None): """ Basic handler for serving up static media files. Accepts an optional ``root`` (filepath string, defaults to ``MEDIA_ROOT``) parameter. Accepts an optional ``force_content_type`` (string, guesses if ``None``) par...
b7fcb058e381ba8045ea4a14122510ddb2af3ca7
3,634,311
import numpy def crystal_fh2(input_dictionary,phot_in,theta=None,forceratio=0): """ :param input_dictionary: as resulting from bragg_calc() :param phot_in: photon energy in eV :param theta: incident angle (half of scattering angle) in rad :return: a dictionary with structure factor """ #...
438f1491b4458358f58b9212a094dcc2f499369e
3,634,312
import re def split_list_item_by_taking_words_in_parentheses(item): """This function goes through items in a list and creates a new item with only the words inside the parentheses.""" species_pop_name = item.split('(')[0].split(',') if len(species_pop_name) > 1: species_pop_name = species_pop_name...
2d8543611007e799d089c77b79ae7263cba36a30
3,634,313
import re def _set_arxiv_info(paper): """ Retrieve paper information from the html. :param paper: SubmittedPaper object to scrape html information. :type paper: SubmittedPaper :return: SubmittedPaper object with html information retrieved. :rtype: SubmittedPaper """ # Remove all the m...
b37103d1ae3aa0175c49884ed2133b28ab69c327
3,634,314
def fetch_accountTransactions(accountNum): """ Function to return all the transaction related to an account number provided as a parameter. This function assumes that the user has been previously authenticated and that the request is for an account they own. Args: accountNum (int): User's a...
dfce7891a38817775fb6aee198e39bf9f985cf47
3,634,315
import os def resolve_all(dirs, *paths): """ Returns a list of paths created by joining `paths` onto each dir in `dirs` using `os.path.join` and discarding all join results that do not exist. :param dirs: A list of dir strings to resolve against :param paths: Path components to join onto each dir...
7a40dba8b81e3c1a240fd8d8a6f30124e2325bc0
3,634,316
def main(items=None, printmd=None, printcal=None, found=False, filename_template='${collection}/${date}/${id}', save=None, download=None, requester_pays=False, headers=None, **kwargs): """ Main function for performing a search """ if items is None: ## if there are no items then pe...
62b562a9c450f966a6ed6fc3f9a8e37865d900f3
3,634,317
def get_utility_flow(heat_utilities, agent): """Return the total utility duty of heat utilities for given agent in GJ/hr""" if isinstance(agent, str): agent = HeatUtility.get_agent(agent) return sum([i.flow * i.agent.MW for i in heat_utilities if i.agent is agent]) / 1e3
c4fa194d321c4db2bd9b423bc9a1c76a7274f212
3,634,318
from unittest.mock import patch async def test_flux_with_custom_start_stop_times(hass, legacy_patchable_time): """Test the flux with custom start and stop times.""" platform = getattr(hass.components, "test.light") platform.init() assert await async_setup_component( hass, light.DOMAIN, {light....
0e6b4cb257d93524fa596150cc197d94eb83e908
3,634,319
def pad(value, digits, to_right=False): """Only use for positive binary numbers given as strings. Pads to the left by default, or to the right using to_right flag. Inputs: value -- string of bits digits -- number of bits in representation to_right -- Boolean, direction of padding ...
98476653ccafeba0a9d81b9193de0687dbf9d85c
3,634,320
def abort(state: State) -> Process: """End of aborted workflow.""" return Abort(state)
a67e51351a948db0670f7695123cb9dfea28d7e2
3,634,321
def my_todos(): """This takes the user to the homepage.""" return render_template('index.html')
1427c1d71b46c487e74a4cd475823de41628b32d
3,634,322
import tempfile import os def setup_directories( create_report_directory=True, create_publish_directory=False, temporary_work_directory=None, ): """ Setup a temporary directory, a report directory under it (created if necessary), and the publish directory (not created by default if necessary)....
c54db5354523653d87fc8baee0739b401fa5351b
3,634,323
def build_network(cfg): """ Build the network based on the cfg Args: cfg (dict): a dict of configuration Returns: network (nn.Module) """ network = None pretrained = cfg['model']['pretrained'] kwargs = { 'num_classes': cfg['model']['num_classes'], } if cfg['m...
0fe83885846a5b12b580487ff59eb9c07d35035e
3,634,324
def check_band_below_faint_limits(bands, mags): """ Check if a star's magnitude for a certain band is below the the faint limit for that band. Parameters ---------- bands : str or list Band(s) to check (e.g. ['SDSSgMag', 'SDSSiMag']. mags : float or list Magnitude(s) of the ...
9e26fcef5bf79b4480e93a5fe9acd7416337cf09
3,634,325
def findNmin_ballot_comparison_rates(alpha, gamma, r1, s1, r2, s2, reported_margin, N, null_lambda=1): """ Compute the smallest sample size for which a ballot comparison audit, using Kaplan-Markov, with the given statistics could stop Parameters ---------- ...
a3d1f33cdcbbfb10bd0a4f2fff343b752056a37b
3,634,326
from typing import List import json def patch_item(news_id, patches): """Apply the patches to the given news ID. If the categories change, they will be updated in the related NewsCategoriesMapping. Returns the modified JSON presentation.""" news = News.query.filter_by(NewsID=news_id).first() result = ...
6292641585b8d8e11d3440ee517e93bbe5b239f9
3,634,327
def get_sample_prediction(session, regression): """Generate and return a sample prediction formatted specifically for table creation. Args: session: A SQLalchemy session object regression: A regression object from four_factor_regression.py Returns: A DataOperator object initialized...
f2e32aa2b3e892158a47479f21b11893ab553821
3,634,328
def log_variables(y_dataset, variables_to_log): """ take the log of given variables :param variables_to_log: [list of str] variables to take the log of :param y_dataset: [xr dataset] the y data :return: [xr dataset] the data logged """ for v in variables_to_log: y_dataset[v].load() ...
442455781ea52734f12336d7ceca4016987cee9e
3,634,329
def find_place_num(n, m): """ """ if n==1 or m==1: return 1 else: return find_place_num(n-1, m) + find_place_num(n, m-1)
632e06db2eb2e2eebdb1c5b34bea36124843a960
3,634,330
def AddWorkerpoolUpdateArgs(parser, release_track): """Set up all the argparse flags for updating a workerpool. Args: parser: An argparse.ArgumentParser-like object. release_track: A base.ReleaseTrack-like object. Returns: The parser argument with workerpool flags added in. """ return AddWorkerp...
51028000d8059e660d6a97a0d8ac3e82f4bca9fb
3,634,331
def check_vibes(x0, y0, z0, x1, y1, z1, deadzone=750): """ Return boolean if the accelerometer senses vibration. This module has a range of 1500 while resting. The default dead zone is 750 because 1500 is quite rare. Values for this can be measured with min-max.py before coded here. """ tot...
a1bae213f6fa1166cb2f69b52cb22700b0b83811
3,634,332
def voiced_seg(sig,fs,f0,stepTime): """ Voiced segments sig: Speech signal fs: Sampling frequency f0: Pitch contour stepTime: Step size (in seconds) used to computed the f0 contour. """ yp = f0.copy() yp[yp!=0] = 1 #In case the starting point is F0 and not 0 if yp[0] == 1: ...
354383c23e1019a9d68de41bb2a62c575001e0ee
3,634,333
def scale_min_max(x, min_in, max_in, min_out, max_out): """Scales linearly""" return np.clip((((max_out - min_out) * (x - min_in)) / (max_in - min_in)) + min_out, min_out, max_out)
7e77d541e5ae329393adb1a0461a8c2081fb48e1
3,634,334
def ast_to_z3(inspected_function: dict): """ Get the inspected object from the ast visit and call each mapper from extracted object to its generated Z3 conditions then, concatenate their results in a single string. :param inspected_function generated from the AST Visit :return: """ local_variables = [x['declar...
ba94a2265673c98e5cbd5691c88c9fdadf0aa2f4
3,634,335
def freight_june_2014(): """Find the number of freight of the month""" for i in fetch_data_2013(): if i[1] == "Freight" and i[4] == "June": num_0 = i[6] return int(num_0)
571d8e819d6abdf8786c114284de8b5542552be9
3,634,336
def add_license_creation_fields(license_mapping): """ Return an updated ``license_mapping`` of license data adding license status fields needed for license creation. """ license_mapping.update( is_active=False, reviewed=False, license_status="NotReviewed", ) return li...
3856c434a672150c09af4b5e4c7fd9fa55014d5c
3,634,337
def filegroup(space, fname): """ filegroup - Gets file group """ return _filegroup(space, fname)
a5b361d048c37e176e78ac2d6ffbebb3604a79cd
3,634,338
def convert_examples_to_features(examples, tokenizer, label_list=None, max_seq_length=128): """Loads a data file into a list of `InputBatch`s.""" features = [] for (ex_index, example) in enumerate(examples): tokens_a = tokenizer.tokenize(example) tokens_b = None if None: ...
f16969b6409e945be03ac3d99092bc0d46919c18
3,634,339
import numpy as np def make_reference_bands_inline(wannier_bands, vasp_bands, efermi=None): """ Compare bandstructure results from wannier and vasp. Takes two input array.bands nodes, stores them if they're not already stored. Takes the relevant bands from the vasp bandstructure and stores and output...
5369bbd8accf640a79b7ccfaa1971441b93a148d
3,634,340
from matplotlib import colors def streamline(ctx, a): """ Represents Streamline.vi. """ plotid = a.plotid() x = a.dbl_1d('x') # X loc of arrows y = a.dbl_1d('y') # Y loc of arrows u = a.dbl_2d('u') # Arrow X component v = a.dbl_2d('...
d6547d2a150557d715d421f606ed5c86b35bce37
3,634,341
from typing import Optional import contextlib def check_reorgs_task(self) -> Optional[int]: """ :return: Number of oldest block with reorg detected. `None` if not reorg found """ with contextlib.suppress(LockError): with only_one_running_task(self): logger.info("Start checking of r...
58a4d97b9176ae304ad86038b578d5864821191f
3,634,342
import sys def InputChecking(str_inputFileName_genotype, str_inputFileName_phenotype): """ To check the numbers of sample are consistent in genotype and phenotype data. Args: str_inputFileName_genotype (str): File name of input genotype data str_inputFileName_phenotype (str): File name o...
c1cf089a2018d2ab99f35e374f55626458698764
3,634,343
def is_all_gathered(): """ Determines if all languages have had their download goals accomplished """ for lang in gathered: if len(gathered[lang]) < NUM_TO_GATHER: return False return True
ad35ce939f2ca847310c6de27541fa48e64142ef
3,634,344
def greedy_eval_Q(Q: QTable, this_environment, nevaluations: int = 1): """ Evaluate Q function greediely with epsilon=0 :returns average cumulative reward, the expected reward after resetting the environment, episode length """ cumuls = [] for _ in range(nevaluations): evaluation_state ...
296cf19b0090d488ef6ca717585114da7d8fc143
3,634,345
def lowercase(obj): """ Make dictionary lowercase """ if isinstance(obj, dict): return {k.lower(): lowercase(v) for k, v in obj.items()} elif isinstance(obj, (list, set, tuple)): t = type(obj) return t(lowercase(o) for o in obj) elif isinstance(obj, str): return obj.lower...
08b0addd87ef7ba5c016ebee50790e8d5e31042b
3,634,346
def link_translate(course, html): """ return html string with ~/ and ~~/ links translated into the appropriate course and site urls """ # for site course, url ends with / ; for others, it doesn't. if course.url[-1] == '/': course_url_with_slash = course.url else: course_url_with_...
f6dbb87a324407ef4046c394ba06d5163982139b
3,634,347
def _workaround_for_datetime(obj): """Workaround for numpy#4983: buffer protocol doesn't support datetime64 or timedelta64. """ if _is_datetime_dtype(obj): obj = obj.view(np.int64) return obj
8091d264a175e9ecf8ba6bb9621bb10f5940919d
3,634,348
import argparse import os def getOptions(): """Function to pull arguments""" parser = argparse.ArgumentParser(description="Removes samples from the design file" \ "belonging to the user-specified group(s).") # Standar Input standar = parser.add_argument_group(title=...
e86fda9acc65f90f968a3be2b2238370910b866b
3,634,349
def sql_dynamic_row_count_redshift(schemas: list) -> str: """Generates an SQL statement that counts the number of rows in every table in a specific schema(s) in a Redshift database""" sql_schemas = ', '.join(f"'{schema}'" for schema in schemas) return f""" WITH table_list AS ( SELECT schema...
a98fdc11a82144cf7cce152ed7cc6c2e071cd596
3,634,350
from datetime import datetime def eow(date: datetime.date, offset: int = 0, weekday: str = "SUN") -> datetime.date: """ Returns the end of the week, i.e. the first date on or after the given date whose weekday is equal to the the :code:`weekday` argument, and offset by a given number of weeks. ...
3020faaf9edce3912d3627878136d52151699e9b
3,634,351
def dequote(s): """ from: http://stackoverflow.com/questions/3085382/python-how-can-i-strip-first-and-last-double-quotes If a string has single or double quotes around it, remove them. Make sure the pair of quotes match. If a matching pair of quotes is not found, return the string unchanged. """...
41c5e5fed901d70472dd6eef1ada7d53d395002c
3,634,352
def has_issue_tracker(function): """ Decorator that checks if the current pagure project has the issue tracker active If not active returns a 404 page """ @wraps(function) def check_issue_tracker(*args, **kwargs): repo = flask.g.repo if not flask.g.issues_enabled or not repo...
f2efa5755ffd013175456ca7fa6cea8ea386569e
3,634,353
from typing import List def find_deprecated_usages( schema: GraphQLSchema, ast: DocumentNode ) -> List[GraphQLError]: """Get a list of GraphQLError instances describing each deprecated use.""" type_info = TypeInfo(schema) visitor = FindDeprecatedUsages(type_info) visit(ast, TypeInfoVisitor(type_i...
6dd7673d76885de4d66f7e479382108be7ed88de
3,634,354
import torch def construct_embedding_mask(V): """ Construct a mask for a batch of embeddings given node sizes. Parameters ---------- V: (batch_size) actual number of nodes per set (tensor) Returns ------- mask: (batch_size) x (n_nodes) binary mask (tensor) """ batch_size = le...
e149691bfac855911cd3074009eb6b97b2d723a0
3,634,355
def url_form(url): """Takes the SLWA photo url and returns the photo url. Note this function is heavily influenced by the format of the catalogue and could be easily broken if the Library switches to a different url structure. """ if url[-4:] != '.png' and url[-4:] != '.jpg': url = url + '...
7469850ffb6877ca116a28251d204024e15bc407
3,634,356
from datetime import datetime def timedelta_from_now(delta): """ Add a timedelta to now, plus a fudge factor of a few seconds. Most useful for chaining with Django's builtin filter "timeuntil", for producing a humanized timedelta. """ return datetime.datetime.utcnow() + delta + datetime.timede...
769739e3ca5304dfe0cd9a82c3c39be338cd5d03
3,634,357
import os def myglob(paths,include=('/**/*.ipynb',),exclude=None,exclude_default=\ ('/**/*_tested.ipynb','**/testnotebooks.ipynb',\ '**/*Template.ipynb')): """Find files that match some patterns, but exclude other patterns. For paths given by `paths`, find all file path names t...
deb9a769a6614f7c07d72cca2f4ad12d01db7aa0
3,634,358
import os def _filepaths(directory, full_paths=True): """Get the filenames in the directory. Args: directory: Directory with the files full_paths: Give full paths if True Returns: result: List of filenames """ # Initialize key variables if bool(full_paths) is True: ...
1a40cb2f3f940a911690f862fd8711d84d90fc94
3,634,359
def multivariate_gaussian(pos, mu, sigma): """ Calculate the multivariate Gaussian distribution on array pos. Source: https://scipython.com/blog/visualizing-the-bivariate-gaussian-distribution/ :param pos: numpy array, constructed by packing the meshed arrays of variables x1, x2, .. xk i...
b8a2e2851f27737332ffcba8deab6c02a455979d
3,634,360
import subprocess def du(path): """disk usage in human readable format (e.g. '2,1GB')""" return subprocess.check_output(['du', '-sh', path]).split()[0].decode('utf-8')
90a17e31a3b3c760baf27e5b6c5551321df7989d
3,634,361
def Rpivot(p, q, Mb): """ Given an augmented matrix Mb, Mb = M|b, this gives the output of the pivot entry [i, j] in or below row p, and in or to the right of column q. """ # n is the number of columns of M, which is one less than that of Mb. m = len(Mb) n = len(Mb[0]) - 1 # Initialize ...
155be98d8560bf42cea928e8b1da6e14e3e7762d
3,634,362
def create3d_vector(name=None, source='default'): """%s :param name: The name of the created object :type name: `str`_ :param source: The object to inherit from. Can be a 3d_vector, or a string name of a 3d_vector. :type source: `str`_ or :class:`vcs.dv3d.Gf3Dvector` :returns: A 3d_ve...
bfbc821de05c6817d7980d6b0fdb27341aa12911
3,634,363
def _GenerateJSONForTestResults(options, log_processor): """Generates or updates a JSON file from the gtest results XML and upload the file to the archive server. The archived JSON file will be placed at: www-dir/DEST_DIR/buildname/testname/results.json on the archive server. NOTE: This will be deprecated....
c3883a92fd11686862d6dd576205e894872b85d1
3,634,364
def unrank(n, rk): """Return the permutation of rank rk in Sn.""" P = [0] * n # Store (j+1)! for calculation. fac = 1 for j in xrange(n-1): fac *= (j+1) d = (rk % (fac * (j+2))) / fac rk -= d * fac P[n-j-2] = d for i in xrange(n-j-1,n): if P[i] ...
e9da99b2341fc03ab67346f463b60d084b8802df
3,634,365
def _compute_influence_kernel(iter, dqd, iter_scale, radius,learning_rate): """Compute the neighborhood kernel for some iteration. Parameters ---------- iter : int The iteration for which to compute the kernel. dqd : array (nrows x ncolumns) This is one...
fc353b48b11dd85ccbdd280e43cd17da8f7a6f3d
3,634,366
from typing import Union from typing import Dict def get_as_dict(x: Union[Dict, Sentence]) -> Dict: """Return an object as a dictionary of its attributes.""" if isinstance(x, dict): return x else: try: return x._asdict() except AttributeError: return x.__dic...
9d85131564324c021a3ff7f2a068e5a0e80dc59e
3,634,367
def get_user_sector_name(db_id): """ Get the user defined sector for the given database id string. Raise an exception if not found. """ found, sector = user_sector_finder("id", int(db_id)) if found: return make_sector_description(sector[0], True) else: raise NotFoundExcepti...
2ee958e8d151f0ffc3e44d5ded405c660baed014
3,634,368
from pathlib import Path def delete_author_by_id( author_id: int = Path(..., title="The Id of the author to be deleted", ge=0), sql: Session = Depends(db_session), current_user: UsersBase = Depends(get_current_active_user) ): """delete a specific author""" ...
78e0c57dbcc7c76d60cfbbc28a7abfeca728d712
3,634,369
import random def assign_judges_to_track(track, judges): """ Assign judges to projects in a single, specified track with all the projects they will be looking at :param str track: name of the track we want judges for :param list judges: a list of the judges allocated for this track :return: a dictionary with th...
981e52d3d8079835f39fe8f8510174bb351d3682
3,634,370
def get_current_user(current_user): """ User route to get current user Parameters ---------- Registered/Admin access Returns ------- User Data """ sql_query = "SELECT * FROM diyup.users WHERE email_address=%s" cur = mysql.connection.cursor() cur.execute(sql_query, (cur...
98c42555a5153ed06516e528b210a6163e2559e0
3,634,371
import json def incident_exists(name, message, status): """ Check if an incident with these attributes already exists """ incidents = cachet.Incidents(endpoint=ENDPOINT) all_incidents = json.loads(incidents.get()) for incident in all_incidents['data']: if name == incident['name'] and \...
d087b9917a233625a731d6a41389ae9532a6f68d
3,634,372
def compute_down(expr): """ Compute the expression on the entire inputs inputs match up to leaves of the expression """ return expr
71677a16093d82a28c1d153c9385b33c01b4dd24
3,634,373
def NEV_to_HLA(survey, NEV, cov=True): """ Transform from NEV to HLA coordinate system. Params: survey: (n,3) array of floats The [md, inc, azi] survey listing array. NEV: (d,3) or (3,3,d) array of floats The NEV coordinates or covariance matrices. cov: boolean ...
984e6f400d1415b0fde087ad913c4cff05ef6b0c
3,634,374
def create_read_model_cmd() -> list: """Create TaiSEIA device model request protocol data.""" return SAInfoRequestPacket.create( sa_info_type=SARegisterServiceIDEnum.READ_MODEL ).to_pdu()
11efc850a056facd25279336eda7ce8868a248f4
3,634,375
def generate_mandatory_attributes(diagnostic_cubes, model_id_attr=None): """ Function to generate mandatory attributes for new diagnostics that are generated using several different model diagnostics as input to the calculation. If all input diagnostics have the same attribute use this, otherwise s...
c8abbf1a9fd42dfafbd7e1bd957dee8f6bef1a00
3,634,376
def _convert_to_slices(indices, max_nslice_frac=0.1): """ Convert list of indices to a list of slices. Parameters ---------- indices : list A 1D list of integers for array indexing. max_nslice_frac : float A float from 0 -- 1. If the number of slices needed to represent ...
acf0bb5800b7fe5c96836a973b090f748a02875a
3,634,377
def log2(x, dtype=None): """ Base-2 logarithm of `x`. Note: Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are not supported. Args: x (Tensor): Input tensor. dtype (:class:`mindspore.dtype`, optional): Default: :class:`None`. Over...
8c99294cc5efb6c31447428cd930bb01641298a8
3,634,378
async def init_app(): """ Инициализируем приложение :return: """ app = web.Application() try: app.db = await asyncpg.pool.create_pool(get_config()) except asyncpg.exceptions.InvalidCatalogNameError: raise Exception('DSN сконфигурирован неверно ' 'и...
73caac054abe8b356e8e167d3cc815c6254e8dd3
3,634,379
def pad_array( x: np.ndarray, to_multiple: int = None, to_size: int = None, axis: int = 0 ): """Pads an array either to a multiple of `to_multiple` or to the exact length `to_size` along `axis`. Parameters ---------- x: np.ndarray The array to pad. to_multiple: int, optional ...
9a8116fac37b794fe7f2e6e216c722e1f8261068
3,634,380
def fill_defaults(value, default): """ #TODO: no longer needed, remove. """ if value is None: value = default elif isinstance(value, int): value = tuple([value] * 3) elif isinstance(value, tuple): value = tuple(item if item else default[i] for i, item in enumerate(value)) ret...
5767775b7d945aae63ecfd30fbefbae82438c3e9
3,634,381
from typing import Sequence def ihfft2(x, s=None, axes=(-2, -1), norm="backward", name=None): """ Compute the two dimensional inverse FFT of a real spectrum. This is really `ihfftn` with different defaults. For more details see `ihfftn`. Args: x(Tensor): Input tensor s(Sequence[i...
2814a48a449affdc8c057dda6d75cd17e09acdc0
3,634,382
def pp_ajaximg(context, nodelist, *args, **kwargs): """ Modifies the request session data to prep it for AJAX requests to the Ajax image uploader. """ context.push() namespace = get_namespace(context) request = kwargs.get('request', None) obj = kwargs.get('object', None) if obj is not N...
ffc9f3fd2d945614582885bb19ba60575bd4a03d
3,634,383
def bgr2rgb(x, dim=-3): """Reverses the channel dimension. See :func:`channel_flip`""" return channel_flip(x, dim)
dc943e7e814f7d2b0cd4f83ec4cb9bf10aad6924
3,634,384
def get_all_predictions(): """ Function for getting the predictions of models on the mnist test dataset. :return: a dictionary with predictions of all models. """ all_results = {} model_paths = ["ffnn_models", "dropout_models"] sizes = [1000, 2500, 7000, 19000, 50000] pred, correct = Non...
246606cac76b58e98e5a7130a4a0631ddcb69508
3,634,385
def moving_avg(timeseries, days=7, dropna=False, win_type=None, params=None): """Takes a centred moving average of a time series over a window with user-defined width and shape. Note: when taking a N-day centred moving average, the first and last N//2 days won't return a value and are effectively lost, BUT they are...
d7d6cd61d61d341beb3c37f7abe307c65ebe72a2
3,634,386
def get_defined_lvls(inp_str): """ gets a list which specifies what levels have been defined """ levels_def_pattern = ('level' + one_or_more(SPACE) + capturing(one_or_more(NONSPACE))) defined_levels = all_captures(levels_def_pattern, inp_str) return defined_levels
624766b6e3b5f17a721e9deacf316bc6793a64f7
3,634,387
from typing import Tuple def requests_per_process(process_count: int, conf) -> Tuple[int, int]: """Divides how many requests each forked process will make.""" return ( int(conf.concurrency / process_count), int(conf.requests / process_count), )
00af7a63471201c3fffcfb610f74a745ca326b68
3,634,388
def load_into_bamfile(meshdata, subfiles, model): """Uses pycollada and panda3d to load meshdata and subfiles and write out to a bam file on disk""" if os.path.isfile(model.bam_file): print 'returning cached bam file' return model.bam_file mesh = load_mesh(meshdata, subfiles) model...
0ba3e498f400bdf8ebfbcbf6075a749634c13ff3
3,634,389
def gettree(number, count=3): """ Сформировать дерево каталогов """ result = [] newline = str(number) while len(newline) % count: newline = '0' + newline for i in range(0, len(newline)//count): result.append(newline[i*count:i*count+count]) return result
55fcec36ef3a50a949ed4f2d12103374fcfd13b0
3,634,390
def to_unserialized_json(obj): """ Convert a wire encodeable object into structured Python objects that are JSON serializable. :param obj: An object that can be passed to ``wire_encode``. :return: Python object that can be JSON serialized. """ return _cached_dfs_serialize(obj)
9d173afca84f5af3617420be1ba04e5ecb3e4242
3,634,391
import os import yaml def install_simulation( version, sim_dir, rel_name, run_dir, vel_mod_dir, srf_file, stoch_file, stat_file_path, vs30_file_path, vs30ref_file_path, check_vm, fault_yaml_path, root_yaml_path, v1d_full_path, cybershake_root, v1d_dir=pl...
3dd01b1e44d734cfda7063b83eaf0f99bec2b2c8
3,634,392
def get_negatives(all_contexts, vocab, counter, K): """返回负采样中的噪声词.""" # 索引为1、2、...(索引0是词表中排除的未知标记) sampling_weights = [ counter[vocab.to_tokens(i)]**0.75 for i in range(1, len(vocab)) ] all_negatives, generator = [], RandomGenerator(sampling_weights) for contexts in all_contexts: ...
471dcd8afac5cc02507a32bd150229e6b34bcf8a
3,634,393
def _get_msvc_vars(repository_ctx, paths): """Get the variables we need to populate the MSVC toolchains.""" msvc_vars = dict() vc_path = find_vc_path(repository_ctx) missing_tools = None if not vc_path: repository_ctx.template( "vc_installation_error.bat", paths["@baz...
417a11a3fe766f4f1136c934f0f0574feb7261c2
3,634,394
def edmonds(V, E, root): """Recursive application of Edmonds' algorithm according to Wikipedia's description [0]. [0] https://en.wikipedia.org/wiki/Edmonds'_algorithm#Description :param V: set of vertices :type V: [int, ...] :param E: a set of edges :type E: [(int...
3a4ec311e3e167dc3634a3d87dca0628d7c78938
3,634,395
import pymultinest def run_multinest(loglikelihood, prior, dumper, nDims, nlive, root, ndump, eff, seed=-1): """Run MultiNest. See https://arxiv.org/abs/0809.3437 for more detail Parameters ---------- loglikelihood: :obj:`callable` probability function taking a single p...
f388c52ebe8d3a27914d7b7966167e608db274dd
3,634,396
def tema(close, timeperiod=30): """Triple Exponential Moving Average 三重指数移动平均线 The triple exponential moving average was designed to smooth price fluctuations, thereby making it easier to identify trends without the lag associated with traditional moving averages (MA). It does this by taking multip...
74f8b5b465caa3de4417db2afa36375125761153
3,634,397
import re def load_single_model(save_path_stem, load_results_df=True): """load in the model, loss df, and model df found at the save_path_stem we also send the model to the appropriate device """ try: if load_results_df: results_df = pd.read_csv(save_path_stem + '_results_df.csv')...
c42b55e98cf663ea5db778b289a66229f9fc244b
3,634,398
def gray2jet(img): """[0,1] grayscale to [0.255] RGB""" jet = plt.get_cmap("jet") return np.uint8(255.0 * jet(img)[:, :, 0:3])
7ea522cc5361e24d67bcde6760a178ff83a6deb4
3,634,399