content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def simple_computation(maximum_terms:int=None, configuration_of=None): """ Simple 4-operand computations 移除了分数项,因为除法运算会表示为分数 禁用了括号(random_term的expression参数),因为会导致溢出 :return: Problem object """ if not configuration_of: configuration_of = 'simple_computation' func_config = combine_configur...
0dae4396f74b9a254d0c882c022018c7a69d69cd
3,647,884
def add_torrents_from_folder(path, transmission_url, torrentleech_username, torrentleech_password, torrentleech_rss_key): """Console script for media_server_utils.""" core.add_torrents_from_folder(path, transmission_url, torrentleech_username, torrentleech_password, torrentleech_rss_key) return 0
ac058ff014c76a3af4054076961b52011bc7329c
3,647,885
def cut_graph(G, w): """ Cut a graph down to a given depth Inputs: - G Input graph - w Depth to cut to Output: - cut_G Cut graph """ # Copy the initial graph and get the number of nodes cut_G = G.copy() N = len(G.nodes) # Check all ...
314f804d2d42146e1dcfb1f4a5373f92a4fe2f17
3,647,886
def archive_filter_search(articles_qs): """ gets the qs and filters and sends back to the hook for rendering. """ return articles_qs.exclude(updates__article__stage=STAGE_PUBLISHED)
2f5783de98110b9b74cabcf571a5919b409d1479
3,647,887
from typing import List def init_plotscript(config, markets: List, startup_candles: int = 0): """ Initialize objects needed for plotting :return: Dict with candle (OHLCV) data, trades and pairs """ if "pairs" in config: pairs = expand_pairlist(config['pairs'], markets) else: p...
220118a5d438227932ba9473471d59ff03b44412
3,647,888
from typing import List from typing import Callable def get_one(data: List[LogEntry], filterfun: Callable) -> LogEntry: """Get a single entry and assert that after filtering only a single entry remains.""" filtered = list(filter(filterfun, data)) if len(filtered) != 1: raise ValueError(f"Entri...
ece1b0b9c654f85eda89e2fc8736c84b4a2ca9ca
3,647,889
from typing import Optional def create(env_name: str, episode_length: int = 1000, action_repeat: int = 1, auto_reset: bool = True, batch_size: Optional[int] = None, **kwargs) -> Env: """Creates an Env with a specified brax system.""" env = _envs[env_name](**k...
1d7e8bf147843799f01e7a894b86fce74ca86da7
3,647,891
def from_software_version(software_version): """ Returns the product version dependant limits_constants. This is based on the running software version on the product and can change based on up when you ask a cluster if upgrading. Args: software_version: (str) software version ex "3.1.2.0" o...
fc978610a6aa55a956bb849cae107bc134934f55
3,647,892
def _from_parse_feature(parse_feature): """Convert a single feature spec to a ColumnSchema.""" # FixedLenFeature if isinstance(parse_feature, tf.FixedLenFeature): representation = FixedColumnRepresentation(parse_feature.default_value) return ColumnSchema(parse_feature.dtype, parse_feature.shape, ...
9c7034c3b7663a0c49dc69dbf8507f90f4cacf83
3,647,893
import json def conditional_patch_resource( service_account_json, base_url, project_id, cloud_region, dataset_id, fhir_store_id ): """ If a resource is found based on the search criteria specified in the query parameters, updates part of that resource by applying the operations specified in a JSON...
e04eada0184d38c8d0b1ec4620fd5ef1f0bc90d5
3,647,894
def cal_big_F(p, f): """ calculate finite strain big F for linearized form not fully tested :param p: pressure :param f: small f :return: big F """ return p / (3. * f * np.power((1. + 2. * f), 2.5))
2d98b9e525837cd8d6dd17266f92f959743ad8f2
3,647,895
from typing import List def multiply_aug(data_aug: List[str], factor: int) -> List[str]: """ The original idea here was to use to to speed up some vasp calculations for supercells by initializing the entire CHGCAR file. The current code does not deal with transformation of the Augemetation charges aft...
2baef4c98dbb83f1a08f11e58f3c4cf82ad8ea64
3,647,896
def _parse_instance_chain(chain_str): """ 返回对象链解析出来的实例对象。""" chain = chain_str.split('.') instance_name = chain.pop(0) attr = session['instances'][instance_name] for attr_name in chain: attr = getattr(attr, attr_name) return attr
531b78ee80f3b6437b885ef89b7f285e6cf6a8a5
3,647,897
import math def epochs_lists( draw, start_time=math.inf, max_epochs=5, min_deme_size=FLOAT_EPS, max_deme_size=FLOAT_MAX, ): """ A hypothesis strategy for creating lists of Epochs for a deme. :param float start_time: The start time of the deme. :param int max_epochs: The maximum nu...
9eebece7ac1dc2f9ad6d13f7368de62a6db9433c
3,647,898
import torch def mlp_layers(nch_input, nch_layers, b_shared=True, bn_momentum=0.1, dropout=0.0): """ [B, Cin, N] -> [B, Cout, N] or [B, Cin] -> [B, Cout] """ layers = [] last = nch_input for i, outp in enumerate(nch_layers): if b_shared: weights = torch.nn.Conv1d(last, ...
8085b99b828fcbadee191d90737d582f7dd9ce73
3,647,899
def path_content_to_string(path): """Convert contents of a directory recursively into a string for easier comparison.""" lines = [] prefix_len = len(path + sep) for root, dirs, files in walk(path): for dir_ in dirs: full_path = join(root, dir_) relative_path = full_path[p...
10d350eb866642f52e350b76f01de2b7e0ff6a5d
3,647,901
def get_evts(rslt, a_params): """Return start and end times of candidate replay events.""" # get PC firing rates ## PC spks spks_pc = rslt.spks[:, :rslt.p['N_PC']] ## smoothed instantaneous firing rate avg'd over PCs fr_pc = smooth(spks_pc.sum(axis=1) / (rslt.dt * rslt.p['N_PC']), a_params[...
c8c6867588d72f97dd687dbe17b7494bc534fa1e
3,647,902
from typing import List from typing import Dict def get_threatfeed_command(client: Client, threatfeed_id: int = None): """ Retrieves the current list of threatFeed objects already configured in the system :param threatfeed_id: The id of the ThreatFeed object. :param client: Vectra Client """ ...
7f0b37a724720aea73170d3575ed5b08dec7ea85
3,647,903
def email_subscribe_pending_confirm(hexdomain): """Send a confirmation email for a user.""" domain = tools.parse_domain(hexdomain) if domain is None: flask.abort(400, 'Malformed domain or domain not represented in hexadecimal format.') hide_noisy = bool(flask.request.form.get('hide_noisy')) ...
9932554a3349e3cf1ecd958d15dd762f787f61c7
3,647,904
def getTrackIds(sp, username, playlist, offset=0): """ Returns the ids of the tracks contained in a playlist :param sp: A spotipy.Spotify object to be used for the request. :param username: The username of the user who's playlists you want the retrieve. :param playlist: Na...
5b4e621022f49137b7fd4547bf5ab4efe92b4515
3,647,905
def children_of_head(element: Element): """ get children element of body element :param element: :return: """ if element is None: return [] body_xpath = '//head' body_element = element.xpath(body_xpath) if body_element: body_element.__class__ = Element return ...
90b47d1c0c3f04231ea5dade3f7e9288339eef71
3,647,906
def network(name, nodes): """nodes: [ NodeMeta, ... ]""" return NetworkMeta(name=name, nodes=nodes)
5c0394ae2a31b83ac6889a4b973f51c1cdb1a0d9
3,647,907
def condensed_to_cosine(condensed_format): """Get mhd direction cosine for this condensed format axis""" axis = Axis.from_condensed_format(condensed_format) return permutation_to_cosine(axis.dim_order, axis.dim_flip)
25b3f0d63a84fa687bf4b238b53288fb8f64918b
3,647,908
def get_plants_for_species(item): """Get list of plants for a species.""" if item is None or not item or item['name'] is None: return @cached('species_list_{}.json'.format(item['name']), directory='../../data/wikipedia') def get(): def table(dom): # We need to sw...
ed9522fd97ac101a6040f0485d06b1b88a834060
3,647,909
def check_password_hash(password, password_hash, salt, N=1 << 14, r=8, p=1, buflen=64): """ Given a password, hash, salt this function verifies the password is equal to hash/salt. Args: - ``password``: The password to perform check on. Returns: - ``bool`` """ candidate_hash = gen...
1e3a75235b11c45746cabf03dcf05b88e610c02f
3,647,910
def _dB_calc(J_field, x, y, z): """ Calcualtes the magnetic field at a point due to a current. Args: J_field (VectorField): Vector field describing the current that the magnetic field is generated from. x: The x coordinate of the point in the magnetic field. y: The y coordinate of the point in the magnet...
0a66c59b4ece95c4f683a842b63e80d2a13a697a
3,647,911
import math def create_mpl_subplot(images, color=True): """create mpl subplot with all images in list. even when the color is set to false it still seems to :param images: the list of images to plot :type images: cv2 image :param color: whether to plot in color or grayscale, defaults to True ...
259c352438c19c4639d78ef67aeb9af0271d6ade
3,647,912
def filter_subclasses(superclass, iter): """Returns an iterable of class obects which are subclasses of `superclass` filtered from a source iteration. :param superclass: The superclass to filter against :return: An iterable of classes which are subclasses of `superclass` """ return filter(lambda kl...
2a891835379dfa3661d781d0c1860b650df013f0
3,647,913
def get_database_table_column_name(_conn: psycopg2.extensions.connection, _table: str) -> list: """ Taken from: https://kb.objectrocket.com/postgresql/get-the-column-names-from-a-postgresql-table-with-the-psycopg2-python-adapter-756 # noqa defines a function that gets...
9486e75792e2b7a63db589727a621fd648213487
3,647,914
import asyncio def retry(*exceptions, retries=3, cooldown=5, verbose=True): """ Decorate an async function to execute it a few times before giving up. Hopes that problem is resolved by another side shortly. Args: exceptions (Tuple[Exception]) : The exceptions expected during function execution...
fea7b786815e2aabedf37e8011485eda3c989fe7
3,647,915
def process_student(filename_or_URL): """calls mark_student on one student HTML file Creates a BeautifulSoup object and calls mark_student. If the filename_or_URL starts with "https://", attempt to get Firefox cookies before reading from the URL. Parameters: ---------- filename_or_URL: ei...
185d396f4005954fcc26b0c8ab3c9711b511c611
3,647,916
def find_CH2OH_in_chain(atoms, cycles): """ this function finds terminal CH2OH that C is not in a cycle H ' O(6) ' H ' / R---C(5)---H """ end_carbon_indices = [] end_carbon_indices_atom_list...
55dbb4767c905fd90f5085b4fcea08e80bf43902
3,647,917
def keep_point(p, frame): """ p: TrackedPoint instance frame: image (numpy array) """ if not p.in_bounds(): return False if p.coasted_too_long(): return False if p.coasted_too_far(): return False return True
7f51b9f15ac8befe07b463875b9245194aebbef0
3,647,919
from typing import Dict from typing import List def sqrt(node: NodeWrapper, params: Dict[str, np.ndarray], xmap: Dict[str, XLayer]) -> List[XLayer]: """ONNX Sqrt to XLayer Sqrt conversion function""" logger.info("ONNX Sqrt -> XLayer Sqrt") assert len(node.get_outputs()) == 1 name = ...
711dfe71eaf337c75acd07bf3f09ca8a7c090fa4
3,647,920
def get_testcase_desc(suite, testcase_name): """ Return the description of the testcase with the given name of the given testsuite. Remove trailing line returns if applicable, they look nasty in the reports (text and otherwise) """ desc = getattr(suite, testcase_name).__doc__ return str...
1a97e02047d42f76328cc55debe8006bcfb80a43
3,647,921
def slave_freq_one_pc(args): """Wrapper to be able to use Pool""" return args, freq_one_pc(*args)
0627685181cbec45564066ea9e29601fc3717257
3,647,922
def base10_to_base26_alph(base10_no): """Convert base-10 integer to base-26 alphabetic system. This function provides a utility to write pdb/psf files such that it can add many more than 9999 atoms and 999 residues. Parameters ---------- base10_no: int The integer to convert to base-26...
67aed6602c6813702416310518c892f02fdb58ef
3,647,923
import pickle def train(model, X, y, name: str): """ train a model on the given training set and optionally save it to disk :param model: the model to train :param X: the sample images, list of numpy arrays (greyscale images) :param y: the target labels, list of strings (kanji) :param name: na...
9b5e4e03b25d7692a233370dd2db1fd2435365e0
3,647,924
def run_phage_boost(genecalls, model_file, verbose): """ Run phage boost :param model_file: The model file that is probably something like model_delta_std_hacked.pickled.silent.gz :param genecalls: The pandas data frame of gene calls :param verbose: more output :return: """ # rolling par...
28592977483d092cf67e7eb7bbd98b911044084b
3,647,926
from datetime import datetime def get_wishlist_confirmation_time(): """Return whether user can confirm his wishlist or not No request params. """ try: confirmation_time = g.user.get_wishlist_confirmation_time() can_confirm = datetime.now() - confirmation_time > timedelta( days = 1 ) i...
89c2fbe9a3801805194dbf41274ba348a87954b1
3,647,927
def get_bprop_npu_clear_float_status(self): """Grad definition for `NPUClearFloatStatus` operation.""" def bprop(x, out, dout): return (zeros_like(x),) return bprop
8e0733a9d6294e507bb99f3536cf1898137a0f3b
3,647,928
import pathlib def path_to_filename(path, with_suffix=True): """Get filename from path. Parameters ========== path : str Path to retrieve file name from e.g. '/path/to/image.png'. with_suffix : bool Whether to include the suffix of file path in file name. Returns ====...
45ecfb6e263e65de7165a69eda99bc8de2a157f4
3,647,929
def encode3(Married): """ This function encodes a loan status to either 1 or 0. """ if Married == 'Yes': return 1 else: return 0
3be5ca3b773e5ded6fe8ec834bc0d99af68bf9e6
3,647,930
def rle_encoding(img, mask_val=1): """ Turns our masks into RLE encoding to easily store them and feed them into models later on https://en.wikipedia.org/wiki/Run-length_encoding Args: img (np.array): Segmentation array mask_val (int): Which value to use to create the RLE Returns: RLE ...
8639094ea57138212a73b179eed593e248363314
3,647,932
import asyncio def alt(*ops, priority=False, default=_Undefined): """ alt(*ops, priority=False, default=Undefined) Returns an awaitable representing the first and only channel operation to finish. Accepts a variable number of operations that either get from or put to a channel and commits only o...
e26660938b760e9f3e2b43375c26ee1a2e946056
3,647,933
def make_class_dictable( cls, exclude=constants.default_exclude, exclude_underscore=constants.default_exclude_underscore, fromdict_allow_pk=constants.default_fromdict_allow_pk, include=None, asdict_include=None, fromdict_include=None, ): """Make a class dictable Useful for when the ...
87a0ed0b0baa1449396921c3651c9d2ef4549f35
3,647,934
def async_request_config( hass, name, callback=None, description=None, description_image=None, submit_caption=None, fields=None, link_name=None, link_url=None, entity_picture=None, ): """Create a new request for configuration. Will return an ID to be used for sequent cal...
f3c8ee70b3b51debeb404660a35491b07c78170e
3,647,935
def get_blueprint_docs(blueprints, blueprint): """Returns doc string for blueprint.""" doc_string = blueprints[blueprint].__doc__ return doc_string
8a334a9ddd1ff5fe844821152f4312b2db0e9da5
3,647,936
from typing import Counter def getColorPalatte(image, num, show_chart=False): """ Returns the most prevelent colors of an image arguments: image - image to sample colors from num - number of colors to sample show_chart - show a visual representation of the colors selected """ modified...
9eaa125cefb1b23161479eaf2e2765ebb58bcd9e
3,647,937
import numpy def run_classifier(data,labels, shuffle=False,nfolds=8,scale=True, clf=None,verbose=False): """ run classifier for a single dataset """ features=data if scale: features=sklearn.preprocessing.scale(features) if shuffle: numpy.random.shuffle(labels)...
3a479971040131cb05f7441112ad0e951b8374f2
3,647,938
def merge_sort(linked_list): """ Sorts a linked list in ascending order - Recursively divide the linked list into sublist containing a single node - Repeatedly merge the sublist to produce sorted sublist until one remains Returns a sorted linked list Takes O(kn log n) time """ if linked_...
07dfee0cb5bdcddb688431f00aeb0520f1d2ed1c
3,647,939
def is_binary(file_path): """ Returns True if the file is binary """ with open(file_path, 'rb') as fp: data = fp.read(1024) if not data: return False if b'\0' in data: return True return False
2df56f93d4e31220a580bf1e659c3c51b96260d2
3,647,940
def convert_host_names_to_ids(session, instanceList): """Look up ID of each instance on Amazon. Returns a list of IDs.""" idList = [] for i in instanceList: instId = aws.instanceid_lookup(session, i) if instId is not None: idList.append(instId) return idList
128d3d4a5e5e0729b477687f665abac43d29aef9
3,647,941
def handle_over_max_file_size(error): """ Args: error: Returns: """ print("werkzeug.exceptions.RequestEntityTooLarge" + error) return 'result : file size is overed.'
2bbdc1e38dea46ac08c314b3962ed63063578021
3,647,942
from typing import Mapping import logging import urllib def _load_from_url(url: str, chinese_only=False) -> Mapping[str, DictionaryEntry]: """Reads the dictionary from a local file """ logging.info('Opening the dictionary remotely') with urllib.request.urlopen(url) as dict_file: data = ...
b496db0b767c17476ecbdc7cab89b962f19a4510
3,647,943
def get_images(): """ Canned response for glance images list call """ return images
3f26e3e0527c0885cfff3470e5d40baf19b3ca82
3,647,944
def firstUniqChar(self, s): """ :type s: str :rtype: int """ letters = 'abcdefghijklmnopqrstuvwxyz' index = [s.index(l) for l in letters if s.count(l) == 1] return min(index) if len(index) > 0 else -1
8b42b281c9e80cf89fb9952a0fe7c60c5270c210
3,647,945
def get_form_class_for_class(klass): """ A helper function for creating a model form class for a model on the fly. This is used with models (usually part of an inheritance hierarchy) which define a function **get_editable_fields** which returns an iterable of the field names which should be placed in th...
12fcdcf9a3155e718bab28b30b466824ad425508
3,647,946
def dict_remove_key(d, key, default=None): """ removes a key from dict __WITH__ side effects Returns the found value if it was there (default=None). It also modifies the original dict. """ return d.pop(key, default)
47bd0edf2bbeb9bad5c696d289c69d2d9eba6a1b
3,647,947
from typing import Optional def momentum(snap: Snap, mask: Optional[ndarray] = None) -> ndarray: """Calculate the total momentum vector on a snapshot. Parameters ---------- snap The Snap object. mask Mask the particle arrays. Default is None. Returns ------- ndarray ...
022f58ed494fb381e650ec0f61ed8d75704b846c
3,647,948
import types def limit_epochs(tensor, num_epochs=None, name=None): """Returns tensor num_epochs times and then raises an OutOfRange error. Args: tensor: Any Tensor. num_epochs: An integer (optional). If specified, limits the number of steps the output tensor may be evaluated. name: A name for ...
82fa475bf4fe0f63a66c5718dc2a0336b887b3d6
3,647,949
def hex_machine(emit): """ State machine for hex escaped characters in strings Args: emit (callable): callback for parsed value (number) Returns: callable: hex-parsing state machine """ left = 4 num = 0 def _hex(byte_data): nonlocal num, left if 0x30 <...
39232fdaf3c0ae19154e28307fb7f1254133dc94
3,647,950
import re def isbns(self, key, value): """Translates isbns fields.""" _isbns = self.get("identifiers", []) for v in force_list(value): subfield_u = clean_val("u", v, str) isbn = { "value": clean_val("a", v, str) or clean_val("z", v, str), "scheme": "ISBN", }...
6db2f27733155e33e64b2d2ffba621deda86808d
3,647,951
import requests def create_user(name, age, occupation): """ Function to post a new user. Parameters ---------- name : str Name of the user. age : int Age of the user. occupation : str Occupation of the user. Returns ------- message : str request_s...
7e7a9a1071fd28a10beeaaf3922eaf36533334f8
3,647,952
import torch def gauss_dataset(dim, size=1e6): """ Creates a dataloader of randomly sampled gaussian noise The returned dataloader produces batsize batches of dim-sized vectors """ def samplef(bsize): return torch.randn(bsize, dim) ret = SampleDataset(samplef, size=size) return re...
224640cff465b7e73d091a799498f3282d309b4e
3,647,953
def nightwatch_environment(request): # convenience spelling """Run tests against this environment (staging, production, etc.)""" return request.config.getoption('--nightwatch-environment')
dc284660e062abf1b74a327e4b045cf79a64ee3a
3,647,954
def get_hrs(pid_arg): """ Pulls all recorded heart rate data for a patient from the database Args: pid_arg: patient_id to pull heart rate data for Returns: list: containing all recorded heart rates """ u5 = User.objects.raw({"_id": pid_arg}).first() return u5.heart_rate
48794e2b94359a81d05d435feb0cf39e52142ca1
3,647,955
def resolve(match, *objects): """Given an array of objects and a regex match, this function returns the first matched group if it exists in one of the objects, otherwise returns the orginial fully matches string by the regex. Example: if regex = \\\.([a-z]) and string = test\.abc, then the match = {group0: \...
52f59fb5248ba635866fcd59a549067c3984e460
3,647,956
from editor_python_test_tools.utils import Report from editor_python_test_tools.utils import TestHelper as helper import azlmbr.legacy.general as general import azlmbr.bus import azlmbr def Collider_CollisionGroupsWorkflow(): # type: () -> None """ Summary: Runs an automated test to ensure PhysX colli...
6463d4543a771a50709712012650c804b365fe81
3,647,957
import time from datetime import datetime def _timestamp(zone="Europe/Istanbul") -> int: """Return timestamp of now.""" return int(time.mktime(datetime.now(timezone(zone)).timetuple()))
871c1dcba8b6f581097c2e24d34903c00034fa03
3,647,958
def sumReplacements(tex, functionName): """ Search tex file for the keyString "\\apisummary{" and its matching parenthesis. All text between will be processed such that there are no consecutive spaces, no tabs, and unnecessary "\\n". The text will then have all the macros replaced and put back into...
8b2ed7bec78c6f2fa03c1308cc4a8fcdfbfa6f8d
3,647,959
from typing import Union from typing import List from typing import Optional def path(path: Union[str, List[str]], *, disable_stage_removal: Optional[bool] = False): """Validate the path in the event against the given path(s). The following APIErrorResponse subclasses are used: PathNotFoundError: Whe...
eff9b153e90e3d657733c5c83b13c77aef21395f
3,647,961
import math import torch def inference_fn(trained_model, remove, fixed_params, overwrite_fixed_params=False, days_of_purchases=710, days_of_clicks=710, lifespan_of_items=710, **params): """ F...
3fa306d97d4db7cf5b321b6284c5ab75ff108845
3,647,963
import random import scipy def initialize_mean_variance(args): """Initialize the current mean and variance values semi-intelligently. Inspired by the kmeans++ algorithm: iteratively choose new centers from the data by weighted sampling, favoring points that are distant from those already chosen """ ...
98808bc7ab069c1ea7ca8e05b6dd27275d6c0f09
3,647,964
def verify_file_checksum(path, expected_checksum): """Verifies the sha256 checksum of a file.""" actual_checksum = calculate_file_checksum(path) return actual_checksum == expected_checksum
519d58892a122d5bc7850cb21ca047c152ef4183
3,647,965
import decimal def float_to_str(f, p=20): """ 将给定的float转换为字符串,而无需借助科学计数法。 @param f 浮点数参数 @param p 精读 """ if type(f) == str: f = float(f) ctx = decimal.Context(p) d1 = ctx.create_decimal(repr(f)) return format(d1, 'f')
551ab2f58b48e4005d8b5a85a7eb096e4e749d23
3,647,966
from typing import List def get_classes(parsed) -> List[ClassDef]: """Returns classes identified in parsed Python code.""" return [ element for element in parsed.body if isinstance(element, ClassDef) ]
e339899eb1dd039c9a708bf39f2fafa527d15882
3,647,967
import tqdm def create_index( corpus_f: str, model_name_or_path: str, output_f: str, mode: str = "sent2vec", batch_size: int = 64, use_cuda: bool = False, ): """Given a corpus file `corpus_f` and a sent2vec model `sent2vec_f`, convert the sentences in the corpus (line-by-line) to ve...
b757d55ecf3001cad2ad285f476a391cb013d8f4
3,647,969
import importlib def import_module(name, path): """ correct way of importing a module dynamically in python 3. :param name: name given to module instance. :param path: path to module. :return: module: returned module instance. """ spec = importlib.util.spec_from_file_location(name, path) ...
d78dc5bc9d3a121c53bdd3bc44ad57378976eb28
3,647,971
def response_ssml_text_and_prompt(output, endsession, reprompt_text): """ create a Ssml response with prompt """ return { 'outputSpeech': { 'type': 'SSML', 'ssml': "<speak>" + output + "</speak>" }, 'reprompt': { 'outputSpeech': { 'ty...
7cfa6b245bb80a29b10f3b972d1e9eb68377e836
3,647,972
import re def getAreaQuantityQuantUnit(words): """ from training data: count perc cum_sum cum_perc kind_c hectare 7 58.333333 7 58.333333 acre 2 16.666667 9 75.000000 meter 1 8.333333 ...
10397a73042469a949fa6dbf70e8bba406cf510c
3,647,973
from typing import Optional from typing import List import pwd import grp def add_user( username: str, password: Optional[str] = None, shell: str = "/bin/bash", system_user: bool = False, primary_group: str = None, secondary_groups: List[str] = None, uid: int = None, home_dir: str = No...
17e9cc717f5ff63e65df202e05de88e703a9cf03
3,647,974
def tokenize_and_align(tokenizer, words, cased=False): """Splits up words into subword-level tokens.""" words = ["[CLS]"] + list(words) + ["[SEP]"] basic_tokenizer = tokenizer.basic_tokenizer tokenized_words = [] for word in words: word = tokenization.convert_to_unicode(word) word = basic_tokenizer._c...
d6bd3fa2523b0f2422d6d0c2c87ac2637462542a
3,647,975
def _vagrant_format_results(line): """Extract fields from vm status line. :param line: Status line for a running vm :type line: str :return: (<vm directory path>, <vm status>) :rtype: tuple of strings """ line_split = line.split() return (line_split[-1], line_split[-2],)
78788572e6b695696621775c28ae8b3a1e577ee3
3,647,976
def rect_to_xys(rect, image_shape): """Convert rect to xys, i.e., eight points The `image_shape` is used to to make sure all points return are valid, i.e., within image area """ h, w = image_shape[0:2] def get_valid_x(x): if x < 0: return 0 if x >= w: return w...
a706007dc1651f1b8ce3c35b355b5b02915158e9
3,647,977
from typing import Optional def determine_aws_service_name( request: Request, services: ServiceCatalog = get_service_catalog() ) -> Optional[str]: """ Tries to determine the name of the AWS service an incoming request is targeting. :param request: to determine the target service name of :param ser...
c29cc59324c3bf946cdfcd936b3f523feb657fda
3,647,978
from typing import Any async def async_get_config_entry_diagnostics( hass: HomeAssistant, entry: ConfigEntry ) -> dict[str, Any]: """Return diagnostics for a config entry.""" coordinator: DataUpdateCoordinator[Domain] = hass.data[DOMAIN][entry.entry_id] return { "creation_date": coordinator.da...
3aa4e17c646367721ffc266c31f66cd9f81c26fe
3,647,980
from typing import Dict def binary_to_single(param_dict: Dict[str, float], star_index: int) -> Dict[str, float]: """ Function for converting a dictionary with atmospheric parameters of a binary system to a dictionary of parameters for one of the two stars. Parameters ---------- param_dict...
21099162ffe83715892abf82660e35ee98e02930
3,647,981
def welcome(): """List all available api routes.""" return ( """Available Routes: /api/v1.0/precipitation Convert the query results to a dictionary using date as the key and prcp as the value. Return the JSON representation of your dictionary. /api/v1.0/...
83fcd43ff8dddd0596232dfb4420525bc592b583
3,647,982
import re def armenian_input_latin(field, text): """ Prepare a string from one of the query fields for subsequent processing: replace latin characters with Armenian equivalents. """ if field not in ('wf', 'lex', 'lex2', 'trans_ru', 'trans_ru2'): return text textTrans = '' for c in ...
94764ec931a4469ea0dca39a70880b41345ab7cf
3,647,983
from typing import Union from typing import Tuple from typing import Callable from typing import Optional import types def df_style_cell(*styles: Union[ Tuple[Callable[['cell'], bool], 'style'], Tuple['cell', 'style'], Callable[['cell'], Optional['style']], ]) -> Callable[['cell'], 'style']: """ S...
e45d1b17ecd3bfe6bf05ba70e7ef0c8dc4b99a81
3,647,984
def bbox_transform(boxes, deltas, weights=(1.0, 1.0, 1.0, 1.0)): """Forward transform that maps proposal boxes to predicted ground-truth boxes using bounding-box regression deltas. See bbox_transform_inv for a description of the weights argument. """ if boxes.shape[0] == 0: return np.zeros((...
90e4cb394a12cbb73ce0dea85557b8195f04a961
3,647,985
def get_item_tds(item_id): """ Method conntect to ILS to retrieve item information and generates an html table cells with the information. :param item_id: Item id :rtype: HTML string """ item_bot = ItemBot(opac_url=ils_settings.OPAC_URL,item_id=item_id) output_html = "<td>{0}</td><t...
866e364257aae174a7ddecdaa94f5af1e9cbfcca
3,647,986
def build_data_request(mac, request_type='current', interval=1, units='english'): """ Creates RainWise API request for Recent Data based on station mac, format (optional), and units (optional) """ # Check if interval requested is valid interval if interval not in [1, 5, 10, 15, 30, 60]: rais...
733c20f5c67fe2c630427bfb70ab563df111558c
3,647,988
def load_acs_access_to_car() -> pd.DataFrame: """Function to merge the two files for the QOL outputs and do some standard renaming. Because these are QOL indicators they remain in the same csv output with columns indicating year""" df_0812 = pd.read_excel( "./resources/ACS_PUMS/EDDT_ACS2008-2012.xls...
fa6d606ebeef142417f1ac47c18947d0de08065b
3,647,989
def elastic_transform(image, alpha, sigma, random_state=None): """Elastic deformation of images as described in [Simard2003]_. .. [Simard2003] Simard, Steinkraus and Platt, "Best Practices for Convolutional Neural Networks applied to Visual Document Analysis", in Proc. of the International Confe...
e01660ecf753d7c33aa66786cf9f9db3b94cef49
3,647,991
import time def convert_epoch_to_mysql_timestamp(epoch_timestamp): """ Converts a given epoch timestamp in seconds to the MySQL datetime format. :param epoch_timestamp: The timestamp as seconds since epoch time :return: The MySQL timestamp string in the format 'Y-m-d HH:MM:SS' :rtype: str """...
15647a816e638e7668e2e830ebc4f1c6fdb2f030
3,647,992
import six def _ensure_eventlet(func): """Decorator that verifies we have the needed eventlet components.""" @six.wraps(func) def wrapper(*args, **kwargs): if not _utils.EVENTLET_AVAILABLE or greenthreading is None: raise RuntimeError('Eventlet is needed to wait on green futures') ...
4193b8d68ae45c13a3a88b1e4c7caba5572f16cf
3,647,993
def check_public_key(pk): """ Checks if a given string is a public (or at least if it is formatted as if it is). :param pk: ECDSA public key to be checked. :type pk: hex str :return: True if the key matches the format, raise exception otherwise. :rtype: bool """ prefix = pk[0:2] l = le...
120b3e88a96db45e5e4df0996414448da8b84462
3,647,995
def empty_tree(input_list): """Recursively iterate through values in nested lists.""" for item in input_list: if not isinstance(item, list) or not empty_tree(item): return False return True
1dceb351aac4db23b57394a531db38a3edf61a8c
3,647,996