content
stringlengths
22
815k
id
int64
0
4.91M
def set_version(v): """Change the version number to V.""" old = get_version() sys.stderr.write('%s -> %s\n' % (old, v)) with open(INIT, 'r+') as f: text = f.read() text = pattern.sub("__version__ = %r" % v, text) f.seek(0) f.truncate() f.write(text)
5,303,300
def create_download_dir_structure_and_files(experiment, temp_media_root): """ Create a complete directory tree with possible experiment data directories/files that reproduces the directory/file structure created when Portal receives the experiment data through Rest API and triggers making download.z...
5,303,301
def randomPartition(elems: list, bin_sizes: list) -> list: """ Randomly partition list elements into bins of given sizes """ def shuffleList(elems): random.shuffle(elems) return elems elems = shuffleList(elems) partition = [] start, end = 0, 0 for bin_size in bin_siz...
5,303,302
def find_closest_string(string: str, options: Dict[str, Set[str]]) -> Optional[Tuple[List[str], float]]: """ :param string: string to search for :param options: {option: trigram tokens} dictionary containing string options with corresponding trigram tokens :return: (best options, score) when minimum sc...
5,303,303
def pre_process(line): """ Return line after comments and space. """ if '#' in line: line = line[:line.index('#')] stripped_data = line.strip() return stripped_data
5,303,304
def sum_var_positional_args(a, b, *args): """perform math operation, variable number of positional args""" inspect_simple(inspect.currentframe()) thesum = a + b for n in args: thesum += n return thesum
5,303,305
def get_states_counties_tracts(tract_fips): """ turn a list of tract fips codes into a nested dict keyed by state, then keyed by county, finally with tract as the value """ if not isinstance(tract_fips, pd.Series): raise TypeError("tract_fips must be a pandas series") df = pd.DataFrame...
5,303,306
def gen_spline(point_params: list, verbose=False) -> Spline: """ Function to generate a spline defined by given point parameters. @param point_params: list of point parameters (dictionaries with values for time, position[, velocity, acceleration]) @param verbose: Enable verbose output if True @retur...
5,303,307
def test_capacitor(): """ unity test for capacitor object """ cap = lmp.Capacitor(FREQ, 1e-6, 1e-3, 1) assert cap.par["cap"] == 8.8541878128e-15 cap.set_x_with_y("eps_r", "cap", 1e-15) assert cap.par["eps_r"] == 0.11294090917221976 assert cap.par["cap"] == 1e-15
5,303,308
def download_raw_video(eid, cameras=None): """ Downloads the raw video from FlatIron or cache dir. This allows you to download just one of the three videos :param cameras: the specific camera to load (i.e. 'left', 'right', or 'body') If None all three videos are downloaded. :return: the ...
5,303,309
def get_canonical_values_not_in_goals( slot_cmap: dict[str, dict], domain: str ) -> dict[str, set[str]]: """Some canonical values do not appear in the goals so they are in a special field in the canonical map. This is specific to MultiWOZ 2.1. Parameters ---------- slot_cmap Canonical ...
5,303,310
def df_filters_funcgen_hsapiens_peak() -> pd.DataFrame: """Dataframe with available filters for the hsapiens_peak dataset.""" df = pd.read_pickle(os.path.join(DATADIR, "filters_hsapiens_peak.pkl")) return df
5,303,311
def file_tag_from_task_file(file: str, cut_num_injs: bool = False) -> str: """Returns the file tag from a task output filename. Args: file: Filename of task file with or without path. cut_num_injs: Whether to not include the number of injections per redshift bin. """ file_tag = file.rep...
5,303,312
def decodeBase58(s): """Decode a base58-encoding string, returning bytes""" if not s: return b'' # Convert the string to an integer n = 0 for c in s: n *= 58 if c not in B58_DIGITS: raise InvalidAddress('Character %r is not a valid base58 character' % c) ...
5,303,313
def insert_ones(y, segment_end_ms): """ Update the label vector y. The labels of the 50 output steps strictly after the end of the segment should be set to 1. By strictly we mean that the label of segment_end_y should be 0 while, the 50 followinf labels should be ones. Arguments: y --...
5,303,314
def update_lunch(): """ Update the menu, caching it """ print('Updating menus...') for menu in menu_classes: # the function caches the menu menu().get_week()
5,303,315
def find_friends(user_id, USERS): """ return list of friends for a given user id """ for city, users in USERS.items(): for user in users: if user["user_id"] == user_id: friends = user["friends"].split() return friends
5,303,316
def _dqc_0051_check_instance(instance, parent, child): """Checks if both parent and child are present in the instance with the same aspect values.""" child_facts = instance.facts.filter(child, allow_nil=False) for child_fact in child_facts: constraintSet = xbrl.ConstraintSet(child_fact) cons...
5,303,317
def PolyDiff(u, x, deg = 3, diff = 1, width = 5): """ u = values of some function x = x-coordinates where values are known deg = degree of polynomial to use diff = maximum order derivative we want width = width of window to fit to polynomial This throws out the data close to the edges ...
5,303,318
def create_app(script_info=None, db_uri=DEFAULT_DB_URI, image_dir=DEFAULT_IMAGE_DIR): """create app.""" app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = db_uri # NOQA app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SECRET_KEY'] = os.getenv('TIIS_SECRET_KEY') or os.urand...
5,303,319
def quiet_mode() -> None: """Remove the logging from Werkzeug.""" logging.getLogger("werkzeug").disabled = True os.environ["WERKZEUG_RUN_MAIN"] = "true"
5,303,320
def pw_global_align(seq1, seq2, sub_matrix, gap_penalty): """ Find pairwise global alignment of two sequences through Hirschberg's algorithm. Args: seq1: sequence of arbitrary objects. seq2: sequence of arbitrary objects. sub_matrix: SubstitutionMatrix with symbols matching sequences. gap_penalty: float|tu...
5,303,321
def vectorise_record(record: Dict[str, Any]) -> Dict[str, Any]: """ Vectorise a patient record. Each field is processed to vector format based on a vector configuration specific to the field name and data type. :param record: Dictionary of record fields :return: Vectorised record dict """ v...
5,303,322
def read_tree(nwk, outgroup=None, bold=None, types=None, label_leaves=True): """Read in a Newick format tree.""" tree = Tree(nwk) if label_leaves: add_section_annotations(tree) add_leaf_labels(tree, bold=bold, types=types) if outgroup: set_outgroup(tree, outgroup) return tree
5,303,323
def generate_richcompare_wrapper(cl: ClassIR, emitter: Emitter) -> Optional[str]: """Generates a wrapper for richcompare dunder methods.""" matches = [name for name in RICHCOMPARE_OPS if cl.has_method(name)] if not matches: return None name = '{}_RichCompare_{}'.format(DUNDER_PREFIX, cl.name_pr...
5,303,324
def plot_xcorr_amplitudes(dict_in,region,fignamebase=None,format='png',distance=None, projection="M5i", xshift="6i",frame="af"): """ This function plots the peak amplitude maps for both negative and positive lags, for each xcorr component pair. The map views plot amplitudes corrected for ...
5,303,325
def AVEDEV(series, n=2): """ 平均绝对偏差 :param series: :param n: :return: """ return series.rolling(n).apply(lambda x: (np.abs(x - x.mean())).mean(), raw=True)
5,303,326
def GaussScreen(w, x_shift, y_shift, T, Fin): """ Fout = GaussScreen(w, x_shift, y_shift, T, Fin) :ref:`Inserts a screen with a Gaussian shape in the field. <GaussScreen>` :math:`F_{out}(x,y)= \\sqrt{1-(1-T)e^{ -\\frac{ x^{2}+y^{2} }{w^{2}} }} F_{in}(x,y)` Args:: w: 1/e inten...
5,303,327
def GetMemberCount(GroupID: int) -> Union[int, str]: """ Returns a count of how many users are in a group """ response = requests.get(Utils.GroupAPIV1 + str(GroupID)) try: return response.json()['memberCount'] except: return response.json()['errors'][0]['message']
5,303,328
def mount(mountpoint: str, index: Index, refresh_rate: Type[RefreshRate]): """Mount filesystem. Mount filesystem at given path. Args: mountpoint: where to mount filesystem index: index to read data from refresh_rate: Which refresh rate filesystem should use for fetching...
5,303,329
def cmc_score_count( distances: torch.Tensor, conformity_matrix: torch.Tensor, topk: int = 1 ) -> float: """ Function to count CMC from distance matrix and conformity matrix. Args: distances: distance matrix shape of (n_embeddings_x, n_embeddings_y) conformity_matrix: binary matrix with...
5,303,330
def mergeTempFiles (items, dir): """Read in the post-processed file for each item""" nErrors = 0 for i in items: try: filename = makeFilename(dir, i["itemID"], "html") with codecs.open(filename, "rU", "utf-8") as f: content = "".join(f) if cont...
5,303,331
def signin_user_db(user_db, remember=False): """Signs in given user""" flask_user_db = FlaskUser(user_db) auth_params = flask.session.get('auth-params', { 'remember': remember, }) flask.session.pop('auth-params', None) return login.login_user(flask_user_db, remember=auth_params['remember...
5,303,332
def id_det_noid(env, src) : """Returns detector full name for any src, e.g., XppGon.0:Cspad2x2.0""" return detector_full_name(env, src)
5,303,333
def archive_iteration_output_data(sender, instance, **kwargs): """ Create archive from output data. """ if instance._state.adding: return create_archive(iteration=instance)
5,303,334
def calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6): """Numpy implementation of the Frechet Distance. The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1) and X_2 ~ N(mu_2, C_2) is d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)). Stable version...
5,303,335
def create_house_holds_objects(): """[summary] Creates house holds objects from the database Returns: [list]: [Two lists. One list of consumers and one list_of_prosumers] """ list_of_consumer = [] list_of_prosumer = [] try: connection = database_cred() sql_sele...
5,303,336
def test_atomic_hex_binary_length_3_nistxml_sv_iv_atomic_hex_binary_length_4_2(mode, save_output, output_format): """ Type atomic/hexBinary is restricted by facet length with value 68. """ assert_bindings( schema="nistData/atomic/hexBinary/Schema+Instance/NISTSchema-SV-IV-atomic-hexBinary-length...
5,303,337
def set_targets_json_location(location=None): """Sets the location of the JSON file that contains the targets""" # First instruct Target about the new location Target.set_targets_json_location(location) # Then re-initialize TARGETS, TARGET_MAP and TARGET_NAMES. The # re-initialization does not creat...
5,303,338
def regrid_get_coord_order(f, axis_keys, coord_keys): """Get the ordering of the axes for each N-d auxiliary coordinate. :Parameters: f: `Field` The source or destination field. axis_keys: sequence A sequence of axis keys. coord_keys: sequence A s...
5,303,339
def test_create_new_grant_without_keywords(cbcsdk_mock): """Tests that Grant.create fails if you don't supply the keyword arguments.""" api = cbcsdk_mock.api with pytest.raises(ApiError): Grant.create(api, org_key='ABC12345') with pytest.raises(ApiError): Grant.create(api, userid='DEF678...
5,303,340
def build_detection_targets(rpn_rois, gt_class_ids, gt_boxes, config): """Generate targets for training Stage 2 classifier. This is not used in normal training. It's useful for debugging or to train the Mask RCNN heads without using the RPN head. Inputs: rpn_rois: [N, (y1, x1, y2, x2)] proposal box...
5,303,341
def getprotobyname(name): # real signature unknown; restored from __doc__ """ getprotobyname(name) -> integer Return the protocol number for the named protocol. (Rarely used.) """ return 0
5,303,342
def load_ccgs(path, old=False): """Read CCG parses from the output of Jigg""" child_key = 'child' if old else 'children' symbol_key = 'category' if old else 'symbol' form_key = 'surf' if old else 'form' def read_ccg(sentence): assert sentence.tag == "sentence" ccg = sentence.xpath(...
5,303,343
def upgrade(): """Make TaskInstance.pool field not nullable.""" with create_session() as session: session.query(TaskInstance).filter(TaskInstance.pool.is_(None)).update( {TaskInstance.pool: 'default_pool'}, synchronize_session=False ) # Avoid select updated rows session.comm...
5,303,344
def process_log_data(spark, input_data, output_data): """ Gets the log data from the s3 bucket and creates the users, time and songplays tables :param spark: the spark session :param input_data: the basic path for the input data :param output_data: the basic path wh...
5,303,345
def simple_thread(func, daemon=True): """ Start function in another thread, discarding return value. """ thread = threading.Thread(target=func) thread.daemon = daemon thread.start() return thread
5,303,346
def interface_compatibility(interfaces): """Verify that all the given interfaces are compatible with each other""" attributes = {} for interface in interfaces: for attr, method in inspect.getmembers(interface): if isinstance(method, FunctionWrapper): # TODO: Improve this ...
5,303,347
async def test_show_config_form(hass): """Test show configuration form.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["step_id"] == "user"
5,303,348
def clone(obj, excluded_fields=[], excluded_childrens=[], custom_values={}, recursive_custom_values={}): """ clone object using django_auto_serializer """ try: si = SerializableInstance(obj, excluded_fields=excluded_fields...
5,303,349
def vmin_w(w, mw): """Minimum wimp velocity to emit a Bremsstrahlung photon w :param w: Bremsstrahlung photon energy :param mw: WIMP mass From Kouvaris/Pradler [arxiv:1607.01789v2], equation in text below eq. 10 """ return (2 * w / wr.mu_nucleus(mw))**0.5
5,303,350
def subblockify(data: bytes, terminate: bool = True) -> bytes: """ Properly segments data into 255-byte-max sub-blocks. `terminate` indicates whether to end with a 0x00 terminator. """ # TODO: make less inefficient. ba, idx = bytearray(), 0 # insert 0xff byte before every 255-byte run fo...
5,303,351
def get_hash(x): """hash x and digest""" return hash_func(x).hexdigest()
5,303,352
def parameters_hook(net, modules=None, match_names=None, param_names=None, tag='', save_path='.', replace=True, histogram=True, bins=100): """Registers a forward hook to a network's modules for vizualization of its parameters. When net.forward() is called, the hook saves an image grid or a ...
5,303,353
def create_engine(db: str, **kwargs) -> sa.engine.Engine: """Returns sqlalchemy engine for designated database. Args: db (str): Database name. Possible values : 'ocan', 'fmc', 'monitorenv_remote', 'monistorfish_local', 'cacem_local' Returns: sa.engine.Engine: sqlalchemy engine ...
5,303,354
def scrape_gitlab_handler(users: list, commits=False): """ Handler for scraping GitLab users. :param users: list of users :param commits: boolean value for adding or not commits to output :return: None """ from gitWebScrapper.gitlab.scrapper import gitlab_scrapper return [gitlab_scrappe...
5,303,355
def create_batch_settings( launcher, nodes=None, time="", queue=None, account=None, batch_args=None, **kwargs ): """Create a ``BatchSettings`` instance See Experiment.create_batch_settings for details :param launcher: launcher for this experiment, if set to 'auto', an attempt will...
5,303,356
def list_recorded_hits(client: boto3.session.Session): """ Return all HITs stored in job.yaml """ config = get_config() with open(config['job_filename'], "r") as fid: hits = yaml.safe_load(fid) return hits
5,303,357
def build_classifier(input_size, hidden_size, output_size, p_drop=0.5): """ DESCRIPTION: The function builds a new model classifier with input- hidden- and output size defined by the input arguments. It will also include dropout using the dropout rate from the input argument. The output will be defi...
5,303,358
def sample_info(session): """Query the LIMS database for sample information and return json representation""" kwargs = retrieve_args() samples = _create_samples_info(session, kwargs.get('match', {})) return [s.to_json() for s in samples]
5,303,359
def route_scorer(routes: List[StrDict]) -> Tuple[List[StrDict], List[float]]: """ Scores and sort a list of routes. Returns a tuple of the sorted routes and their costs. :param routes: the routes to score :return: the sorted routes and their costs """ scores = np.asarray([route_score(route)...
5,303,360
def create_compile_cmd(harness, target, args, specification, c_version="gnu11"): """Create the compile command. :param str harness: path to harness file :param str target: path to program under test :param args: arguments as parsed by argparse :param list specification: list of properties to check ...
5,303,361
def _render_markdown(file_path, **kwargs): """ Given a `file_path` render the Markdown and return the result of `render_template`. """ global NAV_MENU, PROJECT_LOGO, PDF_GENERATION_ENABLED default_template = 'document' with open(file_path, 'r', encoding='utf-8') as f: md = markdown.Markdown(...
5,303,362
def get_model(implant, input_shape, num_dense=0, force_zero=False, sigmoid=False, clip=False): """ Makes a keras model for the model """ inputs = layers.Input(shape=input_shape, dtype='float32') x = tf.image.flip_up_down(inputs) # fully convolutional num_filters = [100, 1000, 100] kernel_si...
5,303,363
def plotly_pie(svl_plot, data): """ Creates a plotly pie chart from the SVL plot and data specs. Parameters ---------- svl_plot : dict The SVL plot specifier. data : dict The SVL data specifier. Returns ------- dict The d...
5,303,364
def main(gui: bool = True) -> None: """프로그램 메인 """ static.chart.start() if gui: # GUI gui_main() else: # Account initialization static.signal_manager = SignalManager(config=static.config, db_ip=static.config.mongo_ip, ...
5,303,365
def plot_gamma_components(*args, colorbar=True, dpi=FIG_DPI, **kwargs): """See _plot_gamma_components for function signature""" fig, ax_im, ax_cbar = make_image_figure(colorbar, dpi) _plot_gamma_components(fig, ax_im, ax_cbar, *args, **kwargs) return figure2array(fig)
5,303,366
def zintv(value=None): """Set zintv""" state.time_selection.set_zintv(_maybe_convert(value, int)) state.time_selection.print_show()
5,303,367
def reverse_zone(z,domain_out): """ Generate reverse lookup entries (IP -> FQDN) for a zone file Retains the SOA file """ z2=dns.zone.Zone(dns.name.from_text(domain_out)) z2.replace_rdataset("@",z.find_rdataset(z.origin,'SOA')) z2.replace_rdataset(domain_out,z.find_rdataset(z.origin,'NS')) for k,o in...
5,303,368
def pRDP_asymp_subsampled_gaussian(params, alpha): """ :param params: :param alpha: The order of the Renyi Divergence :return: Evaluation of the pRDP's epsilon See Example 19 of Wang, Balle, Kasiviswanathan (2018) """ sigma = params['sigma'] prob = params['prob'] assert((prob<1) and...
5,303,369
def main(): """Experimental tool to see if we can automatically share calendars. """ service = build_creds() # Call the Calendar API email_to_share_to = 'spescitelli@wisc.edu' iterate_calendars(service, email_to_share_to)
5,303,370
def test_initialise(repository_uninitialised): """Test the ``initialise`` method and the ``is_initialised`` property.""" repository = repository_uninitialised assert not repository.is_initialised repository.backend.initialise() assert repository.is_initialised
5,303,371
async def ping(*args, logger=None, **kwargs): """Respond to the 'ping' event by doing nothing.""" if logger: logger.info("'ping' event received")
5,303,372
def ismissing(x): """ Return True if x is a missing datum. """ return x == MISSING
5,303,373
def get_heuristics_cheating(): """ Grab the heuristic cheating results. """ acc, f1, prec, rec = run_hr_cheating() hr = ["Heuristics", "{:.2f}".format(acc), "{:.2f}".format(prec), "{:.2f}".format(rec), "{:.2f}".format(f1)] return hr
5,303,374
def extract_name(declaration): """ Extract name from the declarator of the declaration. :param declaration: Declaration string or ast. :return: Declarator string or None if there is no declarator. """ if isinstance(declaration, str): try: ast = parse_declaration(declaration)...
5,303,375
def find_geometry_groups(nexus_file): """ Find all kinds of group containing geometry information. Geometry groups themselves are often links (to reuse repeated geometry) so look for parents of geometry groups instead and return parent and child dictionary pairs. :param nexus_file: NeXus file input...
5,303,376
def ifftn(x, shape=None, axes=None, overwrite_x=False, planner_effort=None, threads=None, auto_align_input=True, auto_contiguous=True): """ Perform an nD inverse FFT. The first three arguments are as per :func:`scipy.fftpack.ifftn`; the rest of the arguments are documented in the ...
5,303,377
async def test_imported_flow_encrypted_invalid_pin_code_error(hass): """Test imported flow with encryption and invalid PIN code error during pairing step.""" mock_remote = get_mock_remote(encrypted=True, authorize_error=SOAPError) with patch( "homeassistant.components.panasonic_viera.config_flow.R...
5,303,378
def hass_admin_user(hass, local_auth): """Return a Home Assistant admin user.""" admin_group = hass.loop.run_until_complete(hass.auth.async_get_group( GROUP_ID_ADMIN)) return MockUser(groups=[admin_group]).add_to_hass(hass)
5,303,379
def run(): """ Watches kubernetes events and saves relevant data. """ load_kube_config() api = client.CustomObjectsApi() w = watch.Watch() # When retrieving a collection of resources the response from the server # will contain a resourceVersion value that can be used to initiate a watch...
5,303,380
def get_lonlatalt(pos, utc_time): """Calculate sublon, sublat and altitude of satellite, considering the earth an ellipsoid. http://celestrak.com/columns/v02n03/ """ (pos_x, pos_y, pos_z) = pos / XKMPER lon = ((np.arctan2(pos_y * XKMPER, pos_x * XKMPER) - astronomy.gmst(utc_time)) % (2 * np.pi)) ...
5,303,381
def _compute_tau(eigenvalues, sig2b): """Compute the tau that gives Hanwen Huang's soft thresholded eigenvalues, which maximizes the relative size of the largest eigenvalue""" # NOTE: tau is found by searching between 0 and Ming Yuan's tilde_tau. tilde_tau = _compute_tilde_tau(eigenvalues, sig2b) t...
5,303,382
def sshkeys_post(body: SshkeysPost = None) -> SshkeyPair: # noqa: E501 """Create a public/private SSH Key Pair Create a public/private SSH Key Pair # noqa: E501 :param body: Create a public/private SSH Key Pair :type body: dict | bytes :rtype: SshkeyPair """ try: # get api_user ...
5,303,383
def request(endpoint, auth_token, data=None, files=None, raise_for_status=True, req_type='post'): """ Method to send the request to Snapchat's API. Automatically adds two common fields: `req_token` and `timestamp`. :param endpoint: the api endpoint. :param data: dict containing data ...
5,303,384
def save_config(environ, start_response, lines, rhost): """Config files will be stored in <CFG_DIR> as 'FQDN.cfg'. We don't care about over-writing files, or do we? Since this will be multi-threaded, we should utilize .lock, shouldn't we? """ cfg_file = '%s/%s.cfg' % (config.CFG_DIR, rhost) ...
5,303,385
def run(blueoil_config_file, experiment_id): """Train from blueoil config. Args: blueoil_config_file: experiment_id: """ if horovod_util.is_enabled(): horovod_util.setup() if horovod_util.is_rank0(): # Copy bueoil config yaml. output_dir = os.environ.get...
5,303,386
def send_this(message, ip=IP, port=PORT): """ Takes a message and sends it to the caiman WS server via formatted JSON. Args: message (str, dict): python string or dictionary to send, formatted to a JSON ip (str, optional): IP location of host. Defaults to IP. port (int, optional): W...
5,303,387
def signed_normalint(value, area=4): """ Returns signed value """ # TODO: accept cache arg and depend on int_unpack_fmt return pack('!i', value)
5,303,388
def add_gms_group( self, group_name: str, parent_pk: str = "", background_image_file: str = "", ) -> bool: """Update appliance group in Orchestrator .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - group - POST ...
5,303,389
def die_with_usage(): """ HELP MENU """ print 'list_all_tracks_from_db.py' print ' by T. Bertin-Mahieux (2010) Columbia University' print 'Code to create a list of all tracks in the dataset as' print 'a text file. Assumes track_metadata.db already exists.' print "Format is (IDs are EchoNest's)...
5,303,390
def style_string(string, ansi_style, colormode, nested=False): """ Style the given string according to the given ANSI style string. :param str string: the string to style :param tuple ansi_style: the styling string returned by ``translate_style`` :param int colormode: the color mode to use. See...
5,303,391
def valid_email(emailaddress, domains=GENERIC_DOMAINS): """Checks for a syntactically valid email address.""" # Email address must be at least 6 characters in total. # Assuming noone may have addresses of the type a@com if len(emailaddress) < 6: return False # Address too short. # Split u...
5,303,392
def register_at(app: Flask): """This can be used to register FlaskViews.""" from flexmeasures.api.dev.sensors import SensorAPI dev_api_prefix = "/api/dev" SensorAPI.register(app, route_prefix=dev_api_prefix)
5,303,393
def download_from_time_period(period:str): """ :param period: 'one-year', 'one-week', 'one-month', 'today' """ data = requests.get(f'https://openlittermap.com/global-data?date={period}') if data.ok: geojson = json.loads(data.text)['geojson'] else: raise ValueError('Got inval...
5,303,394
def checkobj(obj,wf=True): """ local conversion. everything sent to the server needs to be a string if wf is True, we also check for well-formed-ness... '{' and '}' are special delimiters in XQuery and need to be escaped by doubling """ if not wf: if isinstance(obj,basestring): ...
5,303,395
def test_all(): """Test all methods.""" env = TfEnv(DummyBoxEnv()) policy = DeterministicMLPPolicy(env_spec=env.spec, hidden_sizes=(32, 32)) max_path_length = 10 max_samples = 50 max_trajs = 50 sampler = PEARLSampler(env, policy, max_path_length) paths, _ = sampler.obtain_samples(max_s...
5,303,396
def _which_h5_group(h5_path): """ Used internally in get_ functions to indentify type of H5_path parameter. H5_path can be passed as string (to h5 location), or as an existing variable in the workspace. This tries If this is a Dataset, it will try and return the parent as that is by default where all rele...
5,303,397
def transformation() -> Response: """ Transformation view. Performs no validation, just passes given JSON to :func:`backend.logic_layer.transformation` for transformation. :return: instance of :class:`~flask.Response` representing JSON response (structure of JSON depends on output type) """ ...
5,303,398
def get_dataset(opts): """ Dataset And Augmentation """ resize_scales = [300 / 720, 375 / 720, 450 / 720, 525 / 720, 1000 / 1280] # TRAIN basic_transform = transform.Compose([ transform.ToTensor(), transform.Normalize(mean=[0.485, 0.456, 0.406], std=[0.22...
5,303,399