content
stringlengths
22
815k
id
int64
0
4.91M
def children_intent_handler(handler_input): """Handler for Hello World Intent.""" # type: (HandlerInput) -> Response speech_text = 'Aus meiner Ehe mit Eleonore gingen sechs Kinder hervor, wovon der 1459 geborene Maximilian und die 1465 geborene Kunigunde überlebten.' try: if ENABLE_TWEETS...
76,900
def least_squares_GD(y, tx, initial_w, max_iters, gamma, debug = False): """ implement least squares via gradient descent """ losses, ws = gradient_descent(y, tx, initial_w, max_iters, gamma, loss_f = model_linear.compute_loss, grad_f = model_linear.compute_gradient, debug = debug) return get_last_ans(ws, l...
76,901
def getJobDir(jobName=None): """ Full path of the harnessed job scripts. """ if jobName is None: jobName = getJobName() return os.path.join(os.environ['LCATR_INSTALL_AREA'], jobName, os.environ['LCATR_VERSION'])
76,902
def generate_notebook( notebook: dict, credentials: Credentials, package_versions: dict, path: Path ) -> None: """ Modifies a notebook so that the Relevanceclient has the proper credentials. Updates notebook to latest RelevanceAI SDK version. """ notebook["metadata"]["name"] = str(path.stem) ...
76,903
def create_app() -> Application: """ Creates a new instance of the application. """ app = Application.create( name='Auth API', secret=INTERNAL_TOKEN_SECRET, health_check_path='/health', ) # -- OpenID Connect Login ------------------------------------------------ # ...
76,904
def setup_platform(hass, config, add_devices, discovery_info=None): """Setup Axis camera.""" device_info = { CONF_NAME: discovery_info['name'], CONF_USERNAME: discovery_info['username'], CONF_PASSWORD: discovery_info['password'], CONF_MJPEG_URL: _get_image_url(discovery_info['hos...
76,905
def isSane(filename): """Check whether a file name is sane, in the sense that it does not contain any "funny" characters""" if filename == '': return False funnyCharRe = re.compile('[\t/ ;,$#]') m = funnyCharRe.search(filename) if m is not None: return False if filename[0] == '-'...
76,906
def get_list_of_keys( d, *keys ): """ crea un nuevo dicionario con el subconjunto de llaves Parameters ========== d: dict keys: tuple Examples ======== >>>origin = { 'a': 'a', 'b': 'b': 'c': 'c' } >>>get_list_of_keys( origin, 'b', 'c' ) { 'b': 'b': 'c': 'c' } """ re...
76,907
def _nearest_cluster_distance(distances_row, labels, i): """Calculate the mean nearest-cluster distance for sample i. Parameters ---------- distances_row : array, shape = [n_samples] Pairwise distance matrix between sample i and each sample. labels : array, shape = [n_samples] labe...
76,908
def check_requirements(session): """Checks for out of date requirements and optionally updates them.""" session.install('gcp-devrel-py-tools') if 'update' in session.posargs: command = 'update-requirements' else: command = 'check-requirements' reqfiles = list(_list_files('.', 'requ...
76,909
def submit_request(testurl,payload,method,headers): """ Function to submit Akamai API """ logger.debug("Requesting Method: %s URL %s with payload: %s with Headers %s", \ method, testurl, payload, headers) my_headers = headers logger.debug(my_headers) req_session = requests.Session() req_sess...
76,910
def test_random_crop_09(): """ Test RandomCrop op: invalid type of input image (not PIL), expected to raise TypeError """ logger.info("test_random_crop_09") # Generate dataset data = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False) transforms = [ py_vi...
76,911
def initialize_params(m): """ initialize neural network parameters """ if isinstance(m, nn.ConvTranspose2d) or isinstance(m, nn.Conv2d): m.weight.data.normal_(mean=0, std=args.init_std) m.bias.data.zero_()
76,912
def condense_residual_matrix(matrix, sequential_diffs, data_density): """ Condense the residuals from a residual matrix to three columns that represent how far out the prediction was, the number of data points, and the observed residual. Args: matrix: (np.ndarray) sequential_diffs: ...
76,913
def lfn_list(wb, lfn: str = ''): """Completer function : for a given lfn return all options for latest leaf""" if not wb: return [] if not lfn: lfn = '.' # AlienSessionInfo['currentdir'] list_lfns = [] lfn_path = Path(lfn) base_dir = '/' if lfn_path.parent.as_posix() == '/' else f'{lfn_path.par...
76,914
async def test_onoff_switch(hass): """Test OnOff trait support for switch domain.""" assert helpers.get_google_type(switch.DOMAIN, None) is not None assert trait.OnOffTrait.supported(switch.DOMAIN, 0, None) trt_on = trait.OnOffTrait(hass, State("switch.bla", STATE_ON), BASIC_CONFIG) assert trt_on....
76,915
def unmap(roi_db): """ For each entry in a database, unmap the labels and bounding box targets back to the full canvas size. """ for db in roi_db: db['labels'] = _unmap(db['labels'], db['total_anchors'], db['idx_inside'], fill=-1) db['bbox_targets'] = _unmap(db['bbox_targets'], db['...
76,916
def test_kde(): """ kde(y, eta, s_v = None, c_v = None, hat_s_v = None) """ res = plom.kde(np.array([[1, 2, 3]]), np.array([[1,1],[0,1],[2,4]])) ref = 0.01940049487135241 # Check np.testing.assert_allclose(res, ref, atol=1e-5)
76,917
def csv_read_row(filename, n): """ Read and return nth row of a csv file, counting from 1. """ with open(filename, 'r') as f: reader = csv.reader(f) return next(itertools.islice(reader, n-1, n))
76,918
def roles_show(name, sphinx, extensions, language): """Show information about a single role.""" namespace = compile_namespace( extensions=extensions, use_sphinx=sphinx, language_code=language ) try: data = namespace.get_role_data(name) except KeyError as error: raise click.Cl...
76,919
def test_calculate_distance(): """Test the calculate_distance function""" r1 = np.array([0, 0, -1]) r2 = np.array([0, 1, 0]) expected_distance = np.sqrt(2.) calculated_distance = first_module_name.calculate_distance(r1, r2) assert expected_distance == calculated_distance
76,920
def tweet_civil_twilight_end(): """ Sends a tweet about civil twilight ending """ try: now = datetime.now() time_ran = now.strftime("%-I:%M %p") tweet_text = f"Civil Twilight has now ended at {time_ran} in Grand Forks, ND" tweet(tweet_text, enable_tweet=True) except Excepti...
76,921
def load_proto(fpath, proto_type): """Load the protobuf Args: fpath: The filepath for the protobuf Returns: protobuf: A protobuf of the model """ with open(fpath, "rb") as f: return proto_type().FromString(f.read())
76,922
def remove_selector(name): """ Unregisters selector with the given name. Args: name (str): The name of the selector. """ selectors.pop(name, None)
76,923
def parse_fetch_response(text, normalise_times=True, uid_is_key=True): """Pull apart IMAP FETCH responses as returned by imaplib. Returns a dictionary, keyed by message ID. Each value a dictionary keyed by FETCH field type (eg."RFC822"). """ if text == [None]: return {} response = gen_p...
76,924
def compute_result(result_parameter, inputs, env, fix_point): """ Funciton to generate the expected result of the testcase. Arguments --------- result_parameter: Either OutputArgument or ReturnValue (see pulp_dsp_test.py) inputs: Dict mapping name to the Argument, with arg.value, arg.ctype (and...
76,925
def read_mp_feat(pred_path): """ if no prediction was done take mp_feat_norm """ header = [] temp = {} test = makehash() for line in open(pred_path, "r"): line = line.rstrip("\n") if line.startswith(str("ID") + "\t"): header = re.split(r"\t+", line) else: ...
76,926
def netconf_capabilities(task: Task, **kwargs: Any) -> Result: """nornir get netconf capabilities :params task: type object :returns: nornir result object """ conn = task.host.get_connection( connection="netconf", configuration=task.nornir.config ) results = [capability for capabili...
76,927
def objective_fun(beta, lam, K, y): """Dual objective of binary kernel SVMs with intercept.""" # The dual objective is: # fun(beta) = 0.5 beta^T K beta - beta^T y # subject to # sum(beta) = 0 # 0 <= beta_i <= C if y_i = 1 # -C <= beta_i <= 0 if y_i = -1 # where C = 1.0 / lam return 0.5 * jnp.dot(beta,...
76,928
def filter_control_example(xml_path=None): """ This has two stages: 1. reads an xml 2. casts to experiement 3. does filter tests. The filter tests all belong in MTH5 Helpers. Loads an xml file and casts it to experiment. Iterates over the filter objects to confirm that these all registe...
76,929
def is_unquoted_text(token): """ :param token: Token :return: boolean """ return isinstance(token, UnquotedText)
76,930
def wind(leds, event, cfg): """Briefly changes LEDs to yellow, indicating it's too windy.""" airports = AIRPORTS.values() indicator_duration = cfg.getfloat('settings', 'wind_duration', fallback=1.0) while True: # Which locations are currently breezy windy_airports = [airport for airport ...
76,931
def invalidate_previous_tokens(sender, instance, created, **kwargs): """ Invalidates all previously issued tokens of that type when a new one is created, used, or anything like that. """ if instance.user.pk in api_settings.PASSWORDLESS_DEMO_USERS.keys(): return if isinstance(instance, Call...
76,932
def gallery(request): """renders the gallery for all images """ if request.user.is_authenticated(): return render(request, 'gallery.html') return HttpResponseRedirect("/")
76,933
def publish_mbinfo_pinfo(): """ Zip mbinfo-figure plugin for distribution :return: """ local('cd wordpress/wp-content/plugins; zip -q -X -x .git -r mbinfo-pinfo.zip mbinfo-pinfo') local('mv wordpress/wp-content/plugins/mbinfo-pinfo.zip ./')
76,934
def scapy_send_package(number, worker, pkts): """ 为多线程创建的发包函数 """ idx = 1 while True: for j in range(len(pkts)): send(pkts[j]) idx += 1
76,935
def rel_rmse(obs, mod): """returns RMSE of model results given observations""" arg = ((mod - obs) / obs) ** 2 return sqrt(nanmean(arg))
76,936
def spell_check(request): """ Returns a HttpResponse that implements the TinyMCE spellchecker protocol. """ try: if not enchant: raise RuntimeError("install pyenchant for spellchecker functionality") raw = force_text(request.body) input = json.loads(raw) id =...
76,937
def initialize_firebase(): """Initialize Firebase, unless already initialized. Returns: (Firestore client): A Firestore database instance. """ try: initialize_app() except ValueError: pass return firestore.client()
76,938
def evaluate_(batch_iter, model): """ To evaluate the model in EDU segmentation. 因内存原因,我们依旧选择批量运算的方式 不同的解码评测,不同的是,这个模式下只要一句一句进行,因为边界是未知 的,所以模型要做完边界预测才知道下一步做什么。 """ c_b, g_b, h_b = 0., 0., 0. for n_batch, (inputs, target) in enumerate(batch_iter, start=1): word_ids...
76,939
def message_handler(channel: object, msg: bytes, connection: object, tag: object, *args, **kwargs): """Function used to handle incoming AMQP packets Args: channel (object): [description] msg (bytes): [descriptio...
76,940
def saved_model(od_detection_learner, tiny_od_data_path) -> Tuple[str, Path]: """ A saved model so that loading functions can reuse. """ model_name = "test_fixture_model" od_detection_learner.save(model_name) assert (Path(tiny_od_data_path) / "models" / model_name).exists() return model_name, Path(t...
76,941
def build_instance(ξ, n, m, r, D): """The graph generation algorithm.""" assert n <= m <= n * (n - 1), f"invalid number of arcs {m=}" network = Network(nodes=range(n)) # Create optimal shortest path tree m_neg = nb_neg_arcs(n, m, r) m_neg_tree = nb_neg_tree_arcs(ξ, n, m, m_neg) tree_arcs = s...
76,942
def do_ConfigAddress(client, args): """Config EIP """ val = client.ConfigAddress(args.id, args.name) utils.print_dict(val, 'Address')
76,943
def test_form_mask_triple_write_to_disk() -> None: """ """ rgb_img = np.zeros((3,3,3), dtype=np.uint8) rgb_img[0,0,:] = [255,255,255] rgb_img[1,1,:] = [255,255,255] rgb_img[2,2,:] = [255,255,255] label_img = np.array( [ [0,1,0], [1,1,1], [0,1,0] ] ).astype(np.uint8) save_fpath = '../temp_files/te...
76,944
def _check_if_python_module_exists(path: str) -> bool: """Check if an Earth Engine python module has been created from a JavaScript module in ee_extra. Args: path: str Returns: Whether the python module has been created. """ return pathlib.Path(_convert_path_to_ee_extra_python_modu...
76,945
def test__split(): """ test find.split test find.split_words test find.split_lines """ pattern = '___c_' assert autoparse.find.split(pattern, STRING, case=True) == ( ' ___A_a_ * & b ', ' C 1d 2 __e_ D__') assert autoparse.find.split_words(STRING) == ( '___A_a_', '*',...
76,946
def test_lsu_uppercase() -> None: """ LSU """ run('LSU', LSU, LSU + '.upper.out')
76,947
def conv2d_bn(x, filters, num_row, num_col, padding='same', strides=(1, 1), name=None): """Utility function to apply conv + BN. Arguments: x: input tensor. filters: filters in `Conv2D`. num_row: height o...
76,948
def rho_basis(qubits): """ Generates a complete orthonormal basis composed of pure states for the n-qubit density matrix. :param qubits: number of qubits :type qubits: int :return: pure state spectral decomposition :rtype: np.ndarray, float """ return np.array([i*np.conjugate(j)....
76,949
def formatted_value(value, array=True): """Format a given input value to be compliant for USD Args: array (bool): If provided, will treat iterables as an array rather than a tuple """ if isinstance(value, str): value = '"{}"'.format(value.replace('"', '\\"')) elif isinstance(value,...
76,950
def estimate_highest_divisor(method, divisor, populations, seats): """ Calculates the estimated highest possible divisor. :param method: The method used. :type method: str :param divisor: A working divisor in calculating fair shares. :type divisor: float :param populations: The population...
76,951
def growth_rate(x, steps=1): """ calculates first differences""" return x[steps:]-x[:-steps]
76,952
def vit_base_patch16_224_in21k(num_classes: int = 21843, has_logits: bool = True): """ ViT-Base model (ViT-B/16) from original paper (https://arxiv.org/abs/2010.11929). ImageNet-21k weights @ 224x224, source https://github.com/google-research/vision_transformer. weights ported from official Google JAX i...
76,953
def setup_app(command, conf, vars): """Place any commands to setup helloworld here""" # Don't reload the app if it was loaded under the testing environment load_environment(conf.global_conf, conf.local_conf)
76,954
def rigidbodies(traj,pdb_output=None,pdb_keep_all=False,pdb_filter=False,cluster_output=False,cutoff=None,ndomains=2,similarity_type='distance_fluctuation',similarity_binarize=None): """rigidbodies Description ----------- Rigid body decomposition through Ward clustering of a pariwise atom similarity ma...
76,955
def swinnet50ts_256(pretrained=False, **kwargs): """ """ kwargs.setdefault('img_size', 256) return _create_byoanet('swinnet50ts_256', 'swinnet50ts', pretrained=pretrained, **kwargs)
76,956
def restore_new_building_menu(): """Submenu for backup execution on a new building """ machine = docker_client_prompt(" to execute restores with.") current_building = compose_building_prompt(" to move", skip_if=not machine) new_machine = docker_client_prompt(" to move building to", ...
76,957
def produce_segmentation(mtx, gamma, good_bins='default', method='modularity', max_intertad_size=3, max_tad_size=10000): """ Produces single segmentation (TADs or CDs calling) of mtx with one gamma with the algorithm provided. :param mtx: input numpy matrix :param gamma: parameter for segmentation calli...
76,958
def role_required(*roles): """Ensure that logged in user has one of the required roles. Return 403 if the user doesn't have a required role. Should be applied before the `@login_required` decorator: @login_required @role_required('admin', 'admin-ccs-category') def view(): ...
76,959
def search_for_vowels(word): """Display any vowels found in an supplied word.""" vowels = set('aeiou') found = vowels.intersection(set(word)) for vowel in found: print(vowel)
76,960
def assistant(command): """if statements for executing commands""" if 'open reddit' in command: reg_ex = re.search('open reddit (.*)', command) url = 'https://www.reddit.com/' if reg_ex: subreddit = reg_ex.group(1) url = url + 'r/' + subreddit we...
76,961
def ResNet50(inputs): """ Implementation of the popular ResNet50 the following architecture: CONV2D -> BATCHNORM -> RELU -> MAXPOOL -> CONVBLOCK -> IDBLOCK*2 -> CONVBLOCK -> IDBLOCK*3 -> CONVBLOCK -> IDBLOCK*5 -> CONVBLOCK -> IDBLOCK*2 -> AVGPOOL -> TOPLAYER Arguments: input_shape -- shape of th...
76,962
def readCSV(path, datatype=float, realVal=True): """ Function to read from a CSV file in the given path. Rows of the CSV file are read in as list into an arrays. Parameters ---------- path : str path to the CSV file Returns ------- list list containing the data read fro...
76,963
def test_ensure_string_raise_type_error(provided: Any) -> None: """Test ensure_string.""" with pytest.raises(TypeError) as excinfo: ensure_string(provided) assert "Expected str or bytes but received " in str(excinfo.value)
76,964
def test_datasets_list_non_empty(output_format, runner, project): """Test listing with datasets.""" format_option = '--format={0}'.format(output_format) result = runner.invoke(cli, ['dataset', 'create', 'my-dataset']) assert 0 == result.exit_code assert 'OK' in result.output result = runner.inv...
76,965
def get_prediction(image_location, model_path): """Generate a prediction of the biofuel source in an image Args: image_location: The absolute file path of the image model_path: The absolute file path of the model weights file Returns: The class label of the biofuel detected """...
76,966
def build_lm_1(state_dict_path): """ :meta private: """ model = SkipLSTM(21, 100, 1024, 3) state_dict = torch.load(state_dict_path) model.load_state_dict(state_dict) model.eval() return model
76,967
def mountstats_command(): """Mountstats command """ mountpoints = [] nfs_only = False rpc_only = False for arg in sys.argv: if arg in ['-h', '--help', 'help', 'usage']: print_mountstats_help(prog) return if arg in ['-v', '--version', 'version']: ...
76,968
def _filename(path: Union[str, Path]) -> str: """Get filename and extension from the full path.""" if isinstance(path, str): return Path(path).name return path.name
76,969
def stitch(probs, positions, decode_consensus_func): """Stitch predictions on chunks into a contiguous sequence. Args: probs: 3D array of predicted probabilities. no. of chunks X no. of positions in chunk X no. of bases. positions: Corresponding list of position array for each chunk in probs. ...
76,970
def sync( *, client: AuthenticatedClient, form_data: FormBody, multipart_data: MultiPartBody, json_body: Json, ) -> Optional[Union[str, int]]: """ POST endpoint """ return sync_detailed( client=client, form_data=form_data, multipart_data=multipart_data, json_...
76,971
def CompileJava(target, src, opts): """Compiles a .java file into a .class file.""" cmd = "ecj " optlevel = GetOptimizeOption(opts) if optlevel >= 4: cmd += "-debug:none " cmd += "-cp " + GetOutputDir() + "/classes " cmd += "-d " + GetOutputDir() + "/classes " cmd += BracketNameWit...
76,972
def O2_sat(P_air, temp): """This equation returns saturaed oxygen concentration in mg/L. It is valid for 278 K < T < 318 K Parameters ---------- Pressure_air : float air pressure with appropriate units. Temperature : water temperature with appropriate units Returns ----...
76,973
def test_tile_multiple_tensor_grad_cpu(): """ /// Feature: Tile op dynamic shape /// Description: Tile backward with dynamic shape /// Expectation: Euqal to expected value """ if sys.platform != 'linux': return multiples = Tensor(np.array([2, 1]), mstype.int64) x0 = Tensor(np.arr...
76,974
def new_version_available(): """ Checks this version and checks the download site for a new version. """ return current_version() < available_version()
76,975
def getAppModuleFromProcessID(processID: int) -> AppModule: """Finds the appModule that is for the given process ID. The module is also cached for later retreavals. @param processID: The ID of the process for which you wish to find the appModule. @returns: the appModule """ with _getAppModuleLock: mod=runn...
76,976
def new_algo_logger(): """ Create and return a logger for the simulation algorithms. :return: Logger object from the logging library """ algo_logger = logging.getLogger("algo_logger") algo_logger.propagate = False formatter = logging.Formatter(ALGO_LOGGER_FORMAT) stream_handler = loggi...
76,977
def device(request): """Run a test case for all available devices.""" return request.param
76,978
def _xls_eval_ir_test_impl(ctx): """The implementation of the 'xls_eval_ir_test' rule. Executes the IR Interpreter on an IR file. Args: ctx: The current rule's context object. Returns: DefaultInfo provider """ src = ctx.file.src runfiles, cmd = get_eval_ir_test_cmd(ctx, src) ...
76,979
def main(args=None): """Checks 'print' usage""" hook = CheckPrintHook() sys.exit(hook.handle(args))
76,980
def map_dimensions_to_integers(dimensions): """ FragmentSelector requires percentages expressed as integers. https://www.w3.org/TR/media-frags/#naming-space """ int_dimensions = {} for k, v in dimensions.items(): int_dimensions[k] = round(v) return int_dimensions
76,981
def get_source_title(meta_data): """ get source title for cards on web app :return: string """ if 'source_title' in meta_data: return meta_data['source_title'] crawler_used = meta_data["crawler_used"] display_source = CRAWLER_TO_SOURCE_TITLE_LOOKUP[crawler_used] return display_...
76,982
def test_volume(driver): """Ensures a volume can be created and deleted.""" driver, wait, url = driver volume_name = "ci-test-" + "".join(choices(ascii_lowercase, k=10)) # Click "New Volume" button script = fix_queryselector(["main-page", "iframe-container", "iframe"]) script += ".contentWind...
76,983
def write_LUT_SonySPI3D( LUT: Union[LUT3D, LUTSequence], path: str, decimals: Integer = 7 ) -> Boolean: """ Writes given *LUT* to given *Sony* *.spi3d* *LUT* file. Parameters ---------- LUT :class:`LUT3D` or :class:`LUTSequence` class instance to write at given path. path ...
76,984
def facebook_post_json(endpoint, json): """Makes a POST request to the specified endpoint with a JSON body""" params = {"access_token": os.environ.get("FACEBOOK_PAGE_ACCESS_TOKEN")} return facebook_base_post_json(endpoint, json, params)
76,985
def padstr(x, align=8): """Pad string x with null bytes so it's a multiple of align bytes long. Return bytes object""" nbytes = len(x) rem = nbytes % align npadbytes = align - rem if rem else 0 # nbytes to pad with for 8 byte alignment x = x.encode('ascii') # ensure it's pure ASCII, where each c...
76,986
def rmsprop(step_size, gamma=0.9, eps=1e-8): """Construct optimizer triple for RMSProp. Args: step_size: positive scalar, or a callable representing a step size schedule that maps the iteration index to positive scalar. Returns: An (init_fun, update_fun, get_params) triple. """ step_size = mak...
76,987
def get_mail(monitoring: Monitoring): """ メールを取得する Params ------ monitoring: Monitoring 監視設定オブジェクト """ config = Config() run_time = RunTime(monitoring.search_word) # メールボックスへの接続 credentials = (config.client_id, config.client_secret) token_backend = Fil...
76,988
def grpdelay(b, a=1, nfft=512, whole='none', analog=False, Fs=2.*pi): #================================================================== """ Calculate group delay of a discrete time filter, specified by numerator coefficients `b` and denominator coefficients `a` of the system function `H` ( `z`). ...
76,989
def request_recognizer(user_id, message): """ Выделяет команду из сообщения и передает на выполнение ответственному модулю :param user_id: str or int :param message: str :return: tuple(str, tuple(str, bool)) """ answer = "Не понял вас. Напиши 'помощь', чтобы узнать мои команды", ('text',) ...
76,990
def unbox(boxed_pixels): """ assumes the pixels came from box and unboxes them! """ flat_pixels = [] for boxed_row in boxed_pixels: flat_row = [] for pixel in boxed_row: flat_row.extend(pixel) flat_pixels.append(flat_row) return flat_pixels
76,991
def log_multinomial(x, p, eps=0.0): """ Compute log pdf of multinomial distribution .. math:: \log p(x; p) = \sum_x p(x) \log q(x) where p is the true class probability and q is the predicted class probability. Parameters ---------- x : Theano tensor Values at which to ev...
76,992
def parse_human_input(file_size): """Parse an input in human-readable format and return a number of bytes.""" multipliers = { "K": 10 ** 3, "M": 10 ** 6, "G": 10 ** 9, "T": 10 ** 12, "Ki": 2 ** 10, "Mi": 2 ** 20, "Gi": 2 ** 30, "Ti": 2 ** 40, }...
76,993
def check_internet_connection(ad, ping_addr): """Validate internet connection by pinging the address provided. Args: ad: android_device object. ping_addr: address on internet for pinging. Returns: True, if address ping successful """ droid, ed = ad.droid, ad.ed ping = d...
76,994
def accurate_delay(delay): """ Function to provide accurate time delay in millisecond :param delay: Delay in milliseconds :return: Nothing """ target_time = time.perf_counter() + delay/1000 while time.perf_counter() < target_time: pass
76,995
def create_frozen_request(sheet_id, rows=None, cols=None): """ Create v4 API request to freeze rows and/or columns for a given worksheet. """ grid_properties = {} if rows is not None and rows >= 0: grid_properties["frozen_row_count"] = rows if cols is not None and cols >= 0: ...
76,996
def create_path(): """function to create traffic monitor directory""" data_store_path = '~/Documents/TrafficMonitor' path = Path(data_store_path).expanduser() path.mkdir(parents=True, exist_ok=True) return str(path)
76,997
def search(request): """ Search page view """ try: query = request.GET.get('query') if len(query) < 3: messages.warning(request, "Search query must be at least 4 characters.") query = "NONE" except: query = "NONE" cards = Card.obje...
76,998
def gauss_function(x, a, x0, sigma): """ Gaussian _________ Arguments: x (float or float array) - argument a (float) - amplitude x0 (float) - mathematical expectation sigma (float) - standard deviation __________________________________ Returns: Gauss function by formula ...
76,999