content
stringlengths
22
815k
id
int64
0
4.91M
def enquiry_client_add(request): """ Add new enquiry and see the list of clients """ success_message, error_message = None, None form = ClientForm clients = Client.objects.all() enquiry_form = EnquiryClientForm enquiry_clients = EnquiryClient.objects.all() if request.method=="POS...
5,298,500
def transpose(table): """ Returns a copy of table with rows and columns swapped Example: 1 2 1 3 5 3 4 => 2 4 6 5 6 Parameter table: the table to transpose Precondition: table is a rectangular 2d List of numbers """ # LIST COMPREHENSIO...
5,298,501
def memsizeformat(size): """Returns memory size in human readable (rounded) form. """ if size > 1048576: # 1024**2 return "{0} GB".format(size / 1048576) elif size > 1024: return "{0} MB".format(size / 1024) else: return "{0} KB".format(size)
5,298,502
def q5(): """Identifying outliers.""" # Definindo os quartis: Q1 = countries['Net_migration'].quantile(q= 0.25) Q3 = countries['Net_migration'].quantile(q= 0.75) # Intervalo interquartil: IQR = Q3 - Q1 # Limite inferior: lim_max = (countries['Net_migration'] < (Q1 - 1.5 * IQR)).sum() ...
5,298,503
def matrix_div(model_out, *derivative_variable): """Computes the divergence for matrix/tensor-valued functions. Parameters ---------- model_out : torch.tensor The (batch) of matirces that should be differentiated. derivative_variable : torch.tensor The spatial variable in which resp...
5,298,504
def main(): """A command line program that gives an overview of a set of generated traces.""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("-a", "--after", help="database row counts AFTER testing (*.csv)") parser.add_argument("-b", "--before", help="database row counts BEFOR...
5,298,505
def stats(ctx, blood: bool, only_blood: bool, min_samples: int): """ Show some stats about the samples in the database """ ctx.obj["db"].print_stats(blood, only_blood, min_samples)
5,298,506
def flip_dataframe(df, new_colname='index'): """Flips table such that first row becomes columns Args: df (DataFrame): Data frame to be flipped. new_colname (str): Name of new column. Defaults to 'index'. Returns: DataFrame: flipped data frame. """ colnames = [new_...
5,298,507
def test_launch_actor_init_error(supervisor): """ Create a supervisor and launch a FakeActorInitError Test if: - the size of the supervised actor list didn't increase - an powerapi.actor.ActorInitError is raise """ list_length = len(supervisor.supervised_actors) actor = FakeActorIni...
5,298,508
def wind_direction(values: dict, data: StepData): """Wandelt einen String von Windrichtungen um. Funktion nur mit den wind_cdir_full-Werten aus der Weatherbit-API ausführbar. :param values: Werte aus der JSON-Datei :param data: Daten aus der API """ value = data.get_data(values["key"], values)...
5,298,509
def ca65_bytearray(s): """Convert a byteslike into ca65 constant byte statements""" s = [' .byt ' + ','.join("%3d" % ch for ch in s[i:i + 16]) for i in range(0, len(s), 16)] return '\n'.join(s)
5,298,510
def config(args): """Find the limit transformations to apply globally.""" reference = json.load(open(os.path.join(SELFDIR, 'reference.json'), 'r')) # Language specified on the command-line if args.lang: if args.lang not in reference: print("Error: language '%s' has no reference limit...
5,298,511
def dequeue(q: queue.Queue, download: Callable[[File], None]) -> None: """Call download on each item in queue until q.get() returns None.""" logger = logging.getLogger('backup.dequeue') while True: file = q.get() if file is None: logger.info(f'Poison pill found with {q.qsize()}...
5,298,512
def test_deprecated_base_class(caplog): """Test deprecated base class.""" class CustomAlarm(alarm_control_panel.AlarmControlPanel): def supported_features(self): pass CustomAlarm() assert "AlarmControlPanel is deprecated, modify CustomAlarm" in caplog.text
5,298,513
def read_basis_shell_num(trexio_file) -> int: """Read the basis_shell_num variable from the TREXIO file. Parameter is a ~TREXIO File~ object that has been created by a call to ~open~ function. Returns: ~num_r~: int Integer value of basis_shell_num variable read from ~trexio_file~. Rai...
5,298,514
def get_codec( cls: AnyType, /, *, using: Optional[Codec[Any]] = None, fallback: bool = False, ) -> Result[Codec[Any], TestplatesError]: """ Retrieves codec from structure type. If there are multiple codecs attached to given structure type, `using` parameter value is used to de...
5,298,515
def theme(ctx, cli_obj, default, list_, config, preview, edit, clone, delete): """Manage osxphotos color themes.""" subcommands = [default, list_, config, preview, edit, clone, delete] subcommand_names = ( "--default, --list, --config, --preview, --edit, --clone, --delete" ) if not any(subc...
5,298,516
def convert_to_pdf(input_path): """ Use external tools to convert the powerpoint file to a pdf. Returns: path of converted file """ path, extension = os.path.splitext(input_path) if extension not in ['.ppt', '.pptx']: raise ValueError("{0} not a valid powerpoint extension".format(extension)) re...
5,298,517
def convert_db_fetch_to_df(fetched, column_names=None): """ This method converts the cursor.fetchall() output of SELECT query into a Pandas dataframe. :param fetched: the output of SELECT query :type fetched: list of row tuples :param column_names: column names to use for the dataframe :type col...
5,298,518
def get_synsets(s): """Suggested helper method for `synset_featurizer`. This should be completed so that it returns a list of stringified Synsets associated with elements of `s`. """ # Use `parse_lem` from the previous question to get a list of # (word, POS) pairs. Remember to convert the PO...
5,298,519
def tpe_submit_commands( cmds: List[Any], thread_count: int, timeout: int, fn: Callable = subprocess_commands_pipe, di=DI, ) -> list: """Run commands on multiple threads. Stdout and stderr are logged on function success. Exception logged on function failure. Accepts: cmds (L...
5,298,520
def register(): """Register new user.""" form = RegisterForm(request.form, csrf_enabled=False) if form.validate_on_submit(): User.create(username=form.username.data, email=form.email.data, password=form.password.data, active=True) flash('Thank you for registering. You can now log in.', 'succ...
5,298,521
def ind2latlon(index, filePath): """ Use gdal/osr to get latlon point location from georeferenced array indices """ # Load georeferencing ds = gdal.Open(filePath) proj = ds.GetProjection() gt = ds.GetGeoTransform() srs = osr.SpatialReference() srs.ImportFromWkt(proj) x0 = gt[0] ...
5,298,522
def is_response_paginated(response_data): """Checks if the response data dict has expected paginated results keys Returns True if it finds all the paginated keys, False otherwise """ try: keys = list(response_data.keys()) except AttributeError: # If we can't get keys, wer'e certainl...
5,298,523
def get_context(*args, **kwargs) -> dict: """ context 导航栏信息 """ from ..article.models import Tag, Category from ..travel.models import Province model_list: dict[object:tuple, ...] = { Tag: ('id', 'name'), Category: ('id', 'name'), } # # 初始化 context context: dict[str:'Query...
5,298,524
def store_tweets(statuses): """ Stores the tweet in the mongoDB :param tweet: dict or list of dicts to store """ if isinstance(statuses, dict): statuses = [statuses] try: result = db.tweets.insert_many(statuses, ordered=False) return result except BulkWriteError as ...
5,298,525
def test_func(G, p0, q0, bif_type): """ Parameters ---------- """ q0 = np.zeros(q0.shape) q0[0] = 1 p0 = np.zeros(p0.shape) p0[0] = 1 return bordered_system(G, p0, q0, bif_type)
5,298,526
def build_actions_embed(actions: List[LoggingActions]) -> discord.Embed: """ A method that generates an embed detailing with LoggingActions are currently enabled. Parameters: actions (List[LoggingActions]): A list of currently enabled logging actions. Returns: embed (discord.Embed): Th...
5,298,527
def add_derived_cols_to_modeldata(dfmodel, derived_cols, dimensions=None, t_model_init_seconds=None, wid_init=None, modelpath=None): """add columns to modeldata using e.g. derived_cols = ('velocity', 'Ye')""" if dimensions is None: dimensions = get_dfmodel_dimensions(df...
5,298,528
def main(argv): """Entrypoint of the command line script.""" arg_parser = argparse.ArgumentParser(description=__doc__) arg_parser.add_argument("skills_txt", help="Path to Skills.txt") arg_parser.add_argument( "--ulvl-per-blvl", type=int, help="If provided, specifies ulvl requirem...
5,298,529
def get_tag_for_physical_resolution(res): """Input a physical resolution string or value, output a formatted string tag to be used in filenames. """ check_flag, res_value = is_physical_resolution(res, return_value=True) if check_flag: sigfigs = 0 fmt_str = '{:.%df}'%(sigfigs) res...
5,298,530
def test_torch_module_hook(workers): """Tests sending and getting back torch nn module like nn.Linear""" model = nn.Linear(2, 1) model_ptr = model.send(workers["bob"]) model_back = model_ptr.get() bias = model_back.bias model_back.fix_precision() model_back.float_precision() assert (bia...
5,298,531
def search_dnb(query_params): """ Queries the dnb-service with the given query_params. E.g.: {"duns_number": "29393217", "page_size": 1} {"search_term": "brompton", "page_size": 10} """ if not settings.DNB_SERVICE_BASE_URL: raise ImproperlyConfigured('The setting DNB_SERVICE_BAS...
5,298,532
def connect_to_zone(zone, access_key_id, secret_access_key, lowercase=True): """ Connect to one of zones in shanhe by access key. """ if lowercase: zone = zone.strip().lower() return APIConnection(access_key_id, secret_access_key, zone)
5,298,533
def compare_versions(value, required, verbose): """Compares the numerical value of two dot-separated version strings :type value: str :type required: str """ # allow for unexpected input for value. # required is within our control. val = [int(x) for x in re.split(r"\D+", value) if x] r...
5,298,534
def single_resonance_statistics(r): """ Compute global, sequence-specific ncIDP-based chemical shifts using resonance list """ seq = sequence.molecule_sequence(r.condition.molecule).one_letter_codes path = get_sparky_home()+'/Python' prediction = compute_RC(path+'/ncIDP-cs.tab', path+'/ncIDP-dev.tab', seq...
5,298,535
def get_response(message, code): """ Create a response. Args: message (str): The message to include in the response code (str): The return code to include in the response Return: a dict, if present key = 'Accept' """ response = HttpResponse(status=code) # pylint: d...
5,298,536
def rk4(data, critic, step, num_step = 1): """Assumes data is a batch of images, critic is a Kantorovich potential, and step is desired step size. Applies fourth order Runge-Kutta to the data num_step times with stepsize step/num_step. Unused in TTC""" h = step/num_step for j in range(num_step): ...
5,298,537
def test_filter_coordinates(): """Test different coordinate filtering functions for patch extraction""" bbox_list = np.array( [ [0, 0, 4, 4], [0, 4, 4, 8], [4, 0, 8, 4], [4, 4, 8, 8], [8, 0, 12, 4], [8, 4, 12, 8], ] ) ...
5,298,538
def delete_measurements(cur, project_key, measurement_ids): """ Delete a list of measurements from the database. """ print(measurement_ids) snapshots = cur.execute( "SELECT file_name FROM snapshots " + "WHERE measurements_id IN ({})".format(", ".join("?" for _ in measurement_ids)), m...
5,298,539
def configure_subinterfaces_for_vlan_range( device, interface, vlan_id_start, vlan_id_step, vlan_id_count, network_start, network_step,host_address_step, netmask, ospf_network_type=None): """ Configures multiple subinterfaces looping through vlan range Args: device ('obj'): Device t...
5,298,540
def post_new_patient(): """This is the function that receive the post request fom patient client The in_data is sent by the patient side client. It is a dictionary with the following keys: "patient_name" (str): the uploaded patient's name "MRI" (str): the medical record number uploaded, this value ...
5,298,541
def test(args): """Execute all tests (unittests, feature tests).""" call_task("unittest") call_task("behave_test")
5,298,542
def weighted_scalarizer(xs: np.ndarray, ws: np.ndarray) -> np.ndarray: """A simple linear weight based scalarizer. Args: xs (np.ndarray): Values to be scalarized. ws (np.ndarray): Weights to multiply each value in the summation of xs. Returns: np.ndarray: An array of scalar...
5,298,543
def blueschist_felsic(): """ Elastic constants of Felsic Blueschist (GPa) from Cao et al. (2013), in Voigt notation - Abbreviation: ``'BS_f'`` Returns: (tuple): tuple containing: * C (np.ndarray): Elastic stiffness matrix (shape ``(6, 6)``) * rho (float): Density (2...
5,298,544
def ensure_wide_weights_is_1D_or_2D_ndarray(wide_weights): """ Ensures that `wide_weights` is a 1D or 2D ndarray. Raises a helpful ValueError if otherwise. """ if not isinstance(wide_weights, np.ndarray): msg = "wide_weights MUST be a ndarray." raise ValueError(msg) ndim = wide_w...
5,298,545
def LMPR_complexity(dist, rvs=None, rv_mode=None): """ Compute the LMPR complexity. Parameters ---------- dist : Distribution Distribution to compute the LMPR complexity of. rvs : list, None The indexes of the random variable used to calculate the LMPR complexity. If Non...
5,298,546
async def read_users( skip: int = 0, limit: int = 100, db: Session = Depends(get_db), token: str = Depends(oauth2_scheme) ) -> List[User]: """ Read all users with all the information: - **skip**: Number of records to be skipped - **limit**: Limit num...
5,298,547
def load_private_key( data: bytes, passphrase: typing.Optional[bytes] = None, ) -> RSAPrivateKey: """Loads the private key and returns a Key interface. If the private key was not encrypted duting the serialization, ``passphrase`` must be ``None``, otherwise it must be a ``bytes`` object. Args:...
5,298,548
def nb_argsort(x, axis): """ Implementation of numpy.argsort in numba. """ assert (axis==0) | (axis==1), "axis must be set to either 0 or 1." ordered = np.zeros_like(x) if axis == 0: for i in range(x.shape[1]): ordered[:, i] = np.argsort(x[:, i]) return ordered elif axis ...
5,298,549
def edge_color(lattice: Lattice, n_colors:int = 3, all_solutions = False, n_solutions = None, fixed = []): """Return a coloring of the edges using n_colors different labels. Args: adjacency (np.ndarray): A list of pairs of vertex indices representing edges. n_colors (int): The maximum number of...
5,298,550
def read_labels(geojson_dict, crs_transformer, extent): """Construct ClassificationLabels from GeoJSON containing grid of cells. If the GeoJSON already contains a grid of cells, then it can be constructed in a straightforward manner without having to infer the class of cells. Args: geojson_dic...
5,298,551
def server_hardware_from_local_link_information_list( oneview_client, local_link_information_list): """Get the Server Hardware from Local Link Information. :param oneview_client: a instance of the OneView Client; :param local_link_information_list: an list of local link information; :return: se...
5,298,552
def maya_window(): """Return the MayaWindow if in Maya else None.""" for each in QtWidgets.QApplication.topLevelWidgets(): if each.objectName() == "MayaWindow": return each return None
5,298,553
def get_ode_solver(args): """get the ODE solver based on the given argument""" if args.ode_solver == 'heun': return heun_solver if args.ode_solver == 'euler': return euler_solver if args.ode_solver == 'rk4': return rk4_solver if args.ode_solver == 'midpoint': return m...
5,298,554
def user_agent_info(sdk_version, custom_user_agent=None): # type: (str, Optional[str]) -> str """Return the user agent info along with the SDK and Python Version information. :param sdk_version: Version of the SDK being used. :type sdk_version: str :param custom_user_agent: Custom User Agent st...
5,298,555
def signal_crossing(signal: List[float], value: int) -> int: """ Args: signal: The signal is described as a list of real numbers. value: The crossing value. Returns: A non-negative integer number that is the number of value crossing events. Examples: >>> signal_crossin...
5,298,556
def create_metadata_dict(): """A Python dictionary will be created to hold the relevant metadata. :return: dictionary with keys for the relevant metadata :rtype: dict """ metadata = {'Directory': None, 'Filename': None, 'Extension': None, 'ImageType'...
5,298,557
def test_draw_map(states): """ Tests that draw_map returns HTML """ states.show()
5,298,558
def email_change_emails(driver, inbox, Users, ISAAC_WEB, GUERRILLAMAIL, WAIT_DUR, **kwargs): """Test if the email change confirmation emails are recieved. - 'driver' should be a Selenium WebDriver. - 'inbox' should be a GuerrillaInbox object. - 'Users' must be a TestUsers object. - ...
5,298,559
def compute_power(rawvolts, rawamps): """ Compute the power. Looks trivial, but I'm gonna implement smoothing later. """ power = rawvolts * 1.58 power_low = rawvolts * 1.51 power_high = rawvolts * 1.648 return power, power_low, power_high
5,298,560
def custom_ceph_config(suite_config, custom_config, custom_config_file): """ Combines and returns custom configuration overrides for ceph. Hierarchy is as follows: custom_config > custom_config_file > suite_config Args: suite_config: ceph_conf_overrides that currently exist in the test ...
5,298,561
def plot_scenario(path, file_type=None, graphml_file=None): """ Plot the graph of an energy system. If no filename is given the plot will be shown on the screen but not writen to an image file Parameters ---------- path : str A valid deflex scenario file. file_type : str or None ...
5,298,562
def arguments(): """ Builds a generic argparse :return: parser """ workdir = '/opt/nuvlabox/installation' parser = argparse.ArgumentParser(description='NuvlaBox Agent') parser.add_argument('--nuvlabox-installation-trigger-json', dest='nb_trigger_content', default=None, metavar='JSON', ...
5,298,563
async def selector(ctx, header, select_from, timeout=120, max_len=20): """ Interactive routine to prompt the `ctx.author` to select an item from a list. Returns the list index that was selected. Parameters ---------- header: str String to put at the top of each page of selection options...
5,298,564
def prettify_labels(labels, format=None): """ Prettify label for typesetting in various formats :param labels: a list of length-2 tuples, in the format(position, label) :param format: a string with the format for the prettifier (e.g. 'agr', 'matplotlib', ...) :return: the same list as labe...
5,298,565
def get_activity_score(target_gene, haplotype_call): """Convert haplotype call to activity score. Parameters ---------- target_gene : str Name of the target gene (e.g. cyp2d6). haplotype_call : str Haplotype call. Returns ------- float Activity_score. """ ...
5,298,566
def drawTree( tree, label_func=str, show_confidence=False, # For power users orientation='horizontal', inverted=False, branch_labels=None, label_colors=None, *args, **kwargs ): """Plot the given tree using matplotlib. This function is adapted from :func:`~Bio.Phylo._util...
5,298,567
def replace_naics_w_naics_from_another_year(df_load, sectorsourcename): """ Replace any non sectors with sectors. :param df_load: df with sector columns or sector-like activities :param sectorsourcename: str, sector source name (ex. NAICS_2012_Code) :return: df, with non-sectors replaced with sector...
5,298,568
def test_negative_start_time(tmpdir_factory): """Test using the 'save whatever you have' mode of the baseband dump Using -1 as the trigger start point initiates the dump using the oldest frame available in the buffers. """ rest_commands = [ command_rest_frames(1), wait(0.5), ...
5,298,569
def push_docs(): """ Build docs and zip for upload to RTD """ build_docs(clean='yes') v = _version('short') local("cd docs/_build/html && zip -r ../%s.zip ." % v)
5,298,570
def datagroup1D(kwsd=None, _larch=None): """utility to perform wrapped operations on a list of 1D data groups""" return DataGroup1D(kwsd=kwsd, _larch=_larch)
5,298,571
def main(): """ """ # Check command-line arguments parser = argparse.ArgumentParser(description="Converts plain text documents to SerifXML input") parser.add_argument("input", help="an input text file or a directory containing them") parser.add_argument("output", help="an output directory that ...
5,298,572
def install(*packages): """Install python packages""" for name in packages: try: installFromPip(name) sucess(name) except: fail() print(white + "Retrying...") try: installFromPipwin(name) sucess(name) ...
5,298,573
def success_revocation(cert_path): """Display a box confirming a certificate has been revoked. :param list cert_path: path to certificate which was revoked. """ z_util(interfaces.IDisplay).notification( "Congratulations! You have successfully revoked the certificate " "that was located...
5,298,574
def create_app(config_filename=None, config=None): """Application factory function that returns the flask app with the configs loaded correctly. Use YGGDRASIL_CFG to point to a right configuration file. The CFG file *needs* to set the SQLALCHEMY_URI value, and the SECRET_KEY. For secret key, use ...
5,298,575
def wait_for_status(client, stream_name, status, wait_timeout=300, check_mode=False): """Wait for the status to change for a Kinesis Stream. Args: client (botocore.client.EC2): Boto3 client stream_name (str): The name of the kinesis stream. status (str): The status to...
5,298,576
def read_aa_losses(filename): """ Read AA losses from data file. (assume fixed structure...) """ aa_losses = {} with open(filename, 'r') as f: reader = csv.reader(f, delimiter=',') next(reader) # skip headers for line in reader: if len(line) == 0: ...
5,298,577
def filter_document(ctx, user_id, project_id, id_str): """Gets and returns the first document by project id and id str Admin level access will ignore user_id parameter. :param ctx: context :param user_id: user id (not username) :param project_id: project id :param id_str: :return: """ ...
5,298,578
def del_duplicate_mw(lib_name, lib_ver): """some libraries has 2 mw """ library = get_library(lib_name, lib_ver) mw = PropertyField.objects.get(name='MW') for c in library.compound_set.all(): if c.property_set.filter(field=mw).count() == 2: c.property_set.filter(field=mw)[1].delete...
5,298,579
def message_in_state(message, state_slug): """ Checks if a message is tagged with a race that is in a given state. """ races = get_races_from_message(message) for race in races: if race.split("-")[0].lower() == slug_to_postal(state_slug).lower(): return True return False
5,298,580
def get_matching_taxon(brow): """ Searches taxon objects for taxa matching an occurrence :param row: :return: returns a single element record set """ # get data from all taxon fields and collect them in a list # e.g. ["Animalia", "Chordata", "Mammalia", "Primates", "", "Hominidae", "", "", "...
5,298,581
def calc_injection(request): """Calculates injection dosages based on weight. GET parameters: weight: weight in lbs Contxt: calculated dose rounded to 3 decimal places """ meds = Injection.objects.all() rx = dict() # default displayed dosage of 0.0 mLs for med in med...
5,298,582
def convert(iterable, remove_tags=None, prepend_tags=None, append_tags=None): """ >>> convert('red green blue banana APPLE nogreen purple red'.split()) ['banana', 'APPLE', <purple>, <red>] """ items = [] my_removes = remove_tags[:] if remove_tags else [] my_prepends = prepend_tags[:] if prepend_tags else [] my_ap...
5,298,583
def add(M1, M2): """ Returns a matrix Q, where Q[i][j] = M1[i][j] + M2[i][j]. M2 is replaced by Q. """ m = len(M1) n = len(M1[0]) for p in range(m): for q in range(n): M2[p][q] = M2[p][q] + M1[p][q] return M2
5,298,584
def compute_groupwise(y_hat, y, ct, num_groups): """ :param y_hat: (N, ). Prediction from M, binary :param y: (N, ) true label :param ct: (N, ) group membership fo each instance :param num_groups: int :return: """ tpr = np.zeros((num_groups,)) fpr = np.zeros((num_groups,)) tnr =...
5,298,585
def attention(inputs, input_shape, attention_size, context=None, context_shape=None): """General attention mechanism model. It return the weighted average of inputs and the weights. Args: inputs: A 3D shaped Tensor [batch_size x time x input_...
5,298,586
def cal_zscores(gdf, fieldNames): """ claculate z-scores for variables in sample point dataframe columns Arguments: gdf {GeoDataFrame} -- some new fields will add to zscore fieldNames {list} -- field names, the columns needed to calculate zscores Returns: GeoDataFrame -- the da...
5,298,587
def analyze_tower(img, mask, data): """ Detects tower using horizontal coins """ out_img, infos = analyze_horizontal_coin(img, mask, data) if infos: tower_info = init_detected_object('tower', data) tower_info.centroid = [np.mean([i.centroid[0] for i in infos]), ...
5,298,588
def whowinner(board): """ Returns the winner of the game, if there is one. """ for i in range(bs-nt+1): for j in range(bs-nt+1): subboard = [[board[i+row][j+col] for col in range(nt)] for row in range(nt)] if X_winner(subboard): return X elif O...
5,298,589
def azure_pipelines_broken(): """Azure pipelines has multiple major versions of python that are broken. The fixes for this will take a month since the regression was first noted since they have to rebuild thier images and roll them out which apparently takes a while (which makes me wonder what they...
5,298,590
async def get_leak_cable_id( cable_id: str, from_date: Optional[str] = None, to_date: Optional[str] = None, token: str = Security(access_token_header), ): """ Download probalilities of leak on a single oilcables Args: cable_id: cable id from_date: from date (...
5,298,591
def loopFeatures(source): """Geokit internal *Loops over an input layer's features * Will reset the reading counter before looping is initiated Parameters: ----------- source : Anything acceptable by loadVector() The vector datasource to read from """ if(isinstance(source, str...
5,298,592
def _async_register_events_and_services(hass: HomeAssistant): """Register events and services for HomeKit.""" hass.http.register_view(HomeKitPairingQRView) def handle_homekit_reset_accessory(service): """Handle start HomeKit service call.""" for entry_id in hass.data[DOMAIN]: i...
5,298,593
async def test_pin_form_incorrect_pin(hass, pin_form): """Test we handle invalid pin.""" with patch( MOCK_API_TEST_PIN, side_effect=InvalidPIN("invalidPin"), ) as mock_test_pin, patch( MOCK_API_UPDATE_SAVED_PIN, return_value=True, ) as mock_update_saved_pin: result = await hass.c...
5,298,594
def manual_action(request, **kwargs): """ Create an instance of Event. Make a request to raspberry pi to lock/unlock. Chanage lock status to pending. Redirect to dashboard """ lock = Lock.objects.get(pk=kwargs['pk']) data = { 'lock_id': kwargs['pk'], 'action': kwargs['action...
5,298,595
def displace_PSF_moffat(x, y, FWHM, beta): """ :param x: x-coordinate of light ray :param y: y-coordinate of light ray :param FWHM: full width at half maximum :param beta: Moffat beta parameter :return: displaced ray by PSF """ X = draw_moffat_r(FWHM, beta) dx, dy = draw_xy(X) r...
5,298,596
def generate_config(context): """ Entry point for the deployment resources. """ properties = context.properties name = properties.get('name', context.env['name']) project_id = properties.get('project', context.env['project']) zone = properties.get('zone') # Network formatting if 'network' ...
5,298,597
def set_parameters(goal,bifurcation,parentDir): """Set all needed node and network parameters Parameters ---------- goal : string, can be 'sync' or 'switch' the control task bifurcation : string, can be 'low' or 'high' bifurcation lne close to which parameter...
5,298,598
def get_config_by_url(cfg, url): """ :param cfg: dictionary :param url: path to value separated by dot, e.g, key1.key2.key3 :return: value from dictionary """ keys = url.split('.') for key in keys: cfg = cfg[key] return cfg
5,298,599