content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import gdata.gauth def credentials_to_token(credentials): """ Transforms an Oauth2 credentials object into an OAuth2Token object to be used with the legacy gdata API """ credentials.refresh(httplib2.Http()) token = gdata.gauth.OAuth2Token( client_id=credentials.client_id, clie...
549b1041c275c542d96e1d048832f71969d727d7
3,632,500
def solve2x2(lhs, rhs): """Solve a square 2 x 2 system via LU factorization. This is meant to be a stand-in for LAPACK's ``dgesv``, which just wraps two calls to ``dgetrf`` and ``dgetrs``. We wrap for two reasons: * We seek to avoid exceptions as part of the control flow (which is what :func:`nu...
2f773a0e452ce1401dc5fb5c17256b662614c366
3,632,501
def fetch_global_notifications(count=0) -> dict: """ Always returns notifications in user view. """ cfg = get_config() if count == 0: count = cfg.default_max_notes global_feed = get_global_feed() global_notes = global_feed.get_notifications(count=count, user_view=True) return glo...
661232b2477eabd0c5a3b706b8253e4956e1aabd
3,632,502
def getClusterPositionsRedshift(hd_clu, cluster_params, redshift_limit): """ Function to get the positions and redshifts of the clusters that pass the required criterion @hd_clu :: list of cluster headers (each header ahs info on 1000 clusters alone) @cluster_params :: contains halo_mass_500c and centra...
4b30bb44a82daa3f2f113c14b7f044ac22d20c6c
3,632,503
def lark_to_field_definition_node(tree: "Tree") -> "FieldDefinitionNode": """ Creates and returns a FieldDefinitionNode instance extracted from the parsing of the tree instance. :param tree: the Tree to parse in order to extract the proper node :type tree: Tree :return: a FieldDefinitionNode ins...
f00d0ed11d3ff61d8017cecbb0226b88accb9854
3,632,504
def variant_wraps(vfunc, wrapped_attributes=VARIANT_WRAPPED_ATTRIBUTES): """Update the variant function wrapper a la ``functools.wraps``.""" f = vfunc.__main_form__ class SentinelObject: """A unique sentinel that is not None.""" sentinel = SentinelObject() for attr in wrapped_attributes: ...
4143a0e2cb5676c80314096575c9d33fbdcdb788
3,632,505
from typing import Iterable def gradient_activity(activity, periods=1, append=True, columns=None): """Compute the gradient for all given columns. Read more in the :ref:`User Guide <gradient>`. Parameters ---------- activity : DataFrame The activity to use to compute the gradient. pe...
fd05c9323d406b9f0c5089f7715b8ec55ceeaae2
3,632,506
def password_validators_help_texts(password_validators=None): """ Return a list of all help texts of all configured validators. """ help_texts = [] if password_validators is None: password_validators = get_default_password_validators() for validator in password_validators: help_t...
3df7b1a669ee7ef01b1e28645d3d7fca5816cf8d
3,632,507
import torch def spherical_schwarzchild_metric(x,M=1): """ Computes the schwarzchild metric in cartesian like coordinates""" bs,d = x.shape t,r,theta,phi = x.T rs = 2*M a = (1-rs/r) gdiag = torch.stack([-a,1/a,r**2,r**2*theta.sin()**2],dim=-1) g = torch.diag_embed(gdiag) print(g.shape)...
4e65d520a88f4b9212bab43c7ebc4dfc30245bd3
3,632,508
def _get_pathless_grib_file_names( init_time_unix_sec, model_name, grid_id=None, lead_time_hours=None): """Returns possible pathless file names for the given model/grid. :param init_time_unix_sec: Model-initialization time. :param model_name: See doc for `nwp_model_utils.check_grid_name`. :para...
6435348fa760b5bd36e8c54df192b024210dcf4f
3,632,509
def get_picard_mrkdup(config): """ input: sample config file output from BALSAMIC output: mrkdup or rmdup strings """ picard_str = "mrkdup" if "picard_rmdup" in config["QC"]: if config["QC"]["picard_rmdup"] == True: picard_str = "rmdup" return picard_str
87e24c0bf43f9ac854a1588b80731ed445b6dfa5
3,632,510
import random def ChoiceColor(): """ 模板中随机选择bootstrap内置颜色 """ color = ["default", "primary", "success", "info", "warning", "danger"] return random.choice(color)
15779e8039c6b389301edef3e6d954dbe2283d54
3,632,511
import platform def filter_command_line(line): """Returns and updates the command line starting with the flag""" line_flag = line.strip().split(":")[0].strip() new_line = line.strip()[len(line_flag) + 1:].strip().lstrip(":").strip() if line_flag == EXEC_FLAG: return new_line elif line_flag...
ff5560b1ba23544902e0904bc08030b2d24a40e4
3,632,512
def load_image(path: str): """ Return a loaded image from a given path. :param path: (str) relative path of the iamge. :return: PIL image. """ image = Image.open(path) return image
8c9d96d5cea2fdac67ba937b7d01bc01a860d1d7
3,632,513
from operator import concat def mergeSeries(sdata, resetIdx=False): """ Merge Series Inputs: > sdata: Either a list of dictionary of Series data > resetIdx (False by default): should we reset the indices? Output: > The merged Series """ if isinstance(sdata, list):...
dc0382581d3e14dc46abe9c5b40d685f3d80ec20
3,632,514
def ranking_overview(request): """ Show history of rankings for top N teams in current ranking """ # Check which rounds are complete rnd_complete = get_completed_rounds() # Calculate ranking after each of these rounds increment_rnds = [] ranking_matrix = [] round_names = [] ...
c68505833f72d529d4ea1617d4d8455120c5321d
3,632,515
def release_lock(lock_name, identifier): """ :param lock_name: 锁名称 :param identifier: uid :return: True or False """ lock = "string:lock:" + lock_name pip = redis_client.pipeline(True) while True: try: pip.watch(lock) lock_value = redis_client.get(lock) ...
8df9f174d11a36ffad9ed2310c2293630669dc4c
3,632,516
def add_user(): """ Add a user""" payload = request.json for required_key in users_schema: if required_key not in payload.keys(): return jsonify({"message": f"Missing {required_key} parameter"}), 400 user = db.users.find_one({"email": payload["email"]}) if user is not None: ...
1c674dbb70caa0ae43819391c97694d3dd82a235
3,632,517
import hashlib def __get_str_md5(string): """ 一个字符串的MD5值 返回一个字符串的MD5值 """ m0 = hashlib.md5() m0.update(string.encode('utf-8')) result = m0.hexdigest() return result
1d55cd42dc16a4bf674907c9fb352f3b2a100d6c
3,632,518
from typing import List def create_optimizers() -> List[OptimizationProcedure]: """Creates a list of all optimization procedures""" optimizers: List[OptimizationProcedure] = [] ordering_rules = TaskOrderingRule.__subclasses__() for rule in ordering_rules: optimizers.append(StationOriented...
f5cade59c03b017435c18a97423eb059418a6e20
3,632,519
import urllib def command_get_file_list(ip_addr, directory): """command.cgi?op=100: Get list of files in a directory. Not recursive. :raise FlashAirBadResponse: When API returns unexpected/malformed data. :raise FlashAirDirNotFoundError: When the queried directory does not exist on the card. :raise F...
40f8c9b84113be84358959f246a868424d382947
3,632,520
def axml_content(d): """ OwcContent dict to Atom XML :param d: :return: """ # <owc:content type="image/tiff" href=".." if is_empty(d): return None else: try: content_elem = etree.Element(ns_elem("owc", "content"), nsmap=ns) mimetype = extract_p(...
c35c266d4ae7c5026958cbb271598f76369ecc6f
3,632,521
def average_water_consumed(wn): """ Compute average water consumed at each node, qbar, computed as follows: .. math:: qbar=\dfrac{\sum_{k=1}^{K}\sum_{t=1}^{lcm_n}qbase_n m_n(k,t mod (L(k)))}{lcm_n} where :math:`K` is the number of demand patterns at node :math:`n`, :math:`L(k)` is the number o...
bf88a45035b993d00fb31ff7151e48a0a1d59c83
3,632,522
def _shuffle(arr1, arr2): """ Shuffles arr1 and arr2 in the same order """ random_idxs = np.arange(len(arr1)) np.random.shuffle(random_idxs) return arr1[random_idxs], arr2[random_idxs]
785ecd0b9e92d5695cd2466fec6649d463f55feb
3,632,523
from datetime import datetime import pytz def assign_output(request): """assigns the given files as version outputs for the given entity """ logger.debug('assign_output') logged_in_user = get_logged_in_user(request) full_paths = request.POST.getall('full_paths[]') original_filenames = reques...
7a0a6f0131a4bee9cc3248ee8e695980b5850024
3,632,524
def make_pipeline(tfidf_vectorizer, model): """ Creates sklearn NLP pipeline :param vectorizer: Vectorizer object :param model: Model object :return: Pipeline object """ tfidf_vectorizer = tfidf_vectorizer model = model pipeline = Pipeline([("tfidf", tfidf_vectorizer), ...
423b59d2635bf34169091c7456e71eca2dbdf5d6
3,632,525
def pnf_peeling_mechanism(item_counts, k, epsilon): """Computes epsilon-DP top-k counts by the permute-and-flip peeling mechanism. The peeling mechanism (https://arxiv.org/pdf/1905.04273.pdf) adaptively uses the counts as a utility function for the exponential mechanism. Once an item is selected, the item is ...
2c2fe9e59addc4905211ca70efd1f88bdeb5a976
3,632,526
from datetime import datetime def format_date(timestamp): """Reusable timestamp -> date.""" return datetime.date.fromtimestamp(timestamp).isoformat()
0f735dc18700332238ab4441677c786f9accc069
3,632,527
import sys def getpwuid(uid): """ getpwuid(uid) -> (pw_name,pw_passwd,pw_uid, pw_gid,pw_gecos,pw_dir,pw_shell) Return the password database entry for the given numeric user ID. See pwd.__doc__ for more on password database entries. """ if uid > sys.maxint or uid < 0: ...
e2917351bb23ece2fabb5274391bf2939df590c6
3,632,528
import time def train(model, optimizer, loader, epoch): """ Train the models on the dataset. """ # running statistics batch_time = AverageMeter("time", ":.2f") data_time = AverageMeter("data time", ":.2f") # training statistics top1 = AverageMeter("top1", ":.3f") top5 = AverageMet...
3d65714a50f1842c32c85fe0cd3c02d7069a88f9
3,632,529
import functools def ResidualBlock(name, input_dim, output_dim, filter_size, inputs, resample=None, he_init=True): """ resample: None, 'down', or 'up' """ if resample == 'down': conv_shortcut = functools.partial(lib.ops.conv2d.Conv2D, stride=2) conv_1 = functools.partial( l...
1b78b86ea42dd225f5a2bde6bcb6ed47b055ec00
3,632,530
def run_uGLAD_direct( Xb, trueTheta=None, eval_offset=0.1, EPOCHS=250, lr=0.002, INIT_DIAG=0, L=15, VERBOSE=True ): """Running the uGLAD algorithm in direct mode Args: Xb (np.array 1xMxD): The input sample matrix trueTheta (np.array 1xDxD): The corresp...
5b362abfec18a217c768bbe45bce3059ece8be22
3,632,531
def twitter_api(): """Returns an authenticated tweepy.API instance. Returns None on failure. """ try: auth = tweepy.OAuthHandler(TWITTER_API_KEY, TWITTER_API_KEY_SECRET) auth.set_access_token(TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_TOKEN_SECRET) ap...
5f0e748740025d4065c6317fdf03eead25e7ba95
3,632,532
def as_general_categories(cats, name="cats"): """Return a tuple of Unicode categories in a normalised order. This function expands one-letter designations of a major class to include all subclasses: >>> as_general_categories(['N']) ('Nd', 'Nl', 'No') See section 4.5 of the Unicode standard fo...
391185d75dce63df7deb724f8dea035389122b94
3,632,533
from pathlib import Path import glob def upload_directory( directory: str = './', upsert=False, ignore_duplicate_error=False, recursive=False, pattern='*'): """ Upload files in a directory to the database. :param directory: [Optional] The root directory to upload. ...
d156c44f511182958172ba30bfb5422bb5da8dcd
3,632,534
def tExtract(rft, T_INDEX): """T_INDEX is either of T_WL, T_SPEC, T_COM """ tdat = [dat[T_INDEX] for dat in rft[RFT_T] if (dat[T_WL] >= rft[RFT_R][R_WL] and dat[T_WL] <= rft[RFT_R][R_WH])] return tdat
c1cdf75b377851316a5da050b8f248f14cfd34e5
3,632,535
from typing import Union from pathlib import Path from typing import Optional def open_txt(path: Union[str, Path], cf_table: Optional[dict] = cmor) -> xr.Dataset: """Extract daily HQ meteorological data and convert to xr.DataArray with CF-Convention attributes.""" meta, data = extract_daily(path) return t...
3a77ed5a501c1d455299504e4dd36e55cea580e9
3,632,536
def dc_coordinates(): """Return coordinates for a DC-wide map""" dc_longitude = -77.016243706276569 dc_latitude = 38.894858329321485 dc_zoom_level = 10.3 return dc_longitude, dc_latitude, dc_zoom_level
c07812ad0a486f549c63b81787a9d312d3276c32
3,632,537
import argparse def get_arguments(): """ Obtains command-line arguments. :rtype: argparse.Namespace """ parser = argparse.ArgumentParser() parser.add_argument( '--clusters', type=argparse.FileType('rU'), required=True, metavar='CLUSTERS', help='read c...
32ce1446d8ac04208a4387bcd2ac31a2609580a3
3,632,538
def request_id_to_key(request_id): """Converts a request id into a TaskRequest key. Note that this function does NOT accept a task id. This functions is primarily meant for limiting queries to a task creation range. """ return ndb.Key(TaskRequest, request_id ^ task_pack.TASK_REQUEST_KEY_ID_MASK)
a5c3ef9939390d43264ba397e4c123af44758471
3,632,539
from typing import Optional def get_web_app_premier_add_on_slot(name: Optional[str] = None, premier_add_on_name: Optional[str] = None, resource_group_name: Optional[str] = None, slot: Optional[str] = None, ...
764101a407305b1f6e03fe8b1ccb17cb2ecbd86f
3,632,540
from typing import Callable from typing import Iterable from typing import List def lmap(f: Callable, x: Iterable) -> List: """list(map(f, x))""" return list(map(f, x))
51b09a3491769aafba653d4198fde94ee733d68f
3,632,541
import ImportPathHelper as imports 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.physics as phys import azlmbr.math as mathazon def C4925577_Materials_MaterialAssignedToTerrain()...
45b527c1b413c33be81fecf7babd4d11de513a8f
3,632,542
def fallible_to_exec_result_or_raise( fallible_result: FallibleExecuteProcessResult, description: ProductDescription ) -> ExecuteProcessResult: """Converts a FallibleExecuteProcessResult to a ExecuteProcessResult or raises an error.""" if fallible_result.exit_code == 0: return ExecuteProcessResult( fal...
774cf9e89fd383a37992fff0b2e1b72ff96bddc8
3,632,543
def cumprod_np(a: np.ndarray, mod: int) -> np.ndarray: """Compute cumprod over modular not in place. the parameter a must be one dimentional ndarray. """ n = a.size assert a.ndim == 1 m = int(n**0.5) + 1 a = np.resize(a, (m, m)) for i in range(m - 1): a[:, i + 1] = a[:, i + 1] *...
b5b1635000bf82b563c350341c8c56edbb0eb9fb
3,632,544
def table_of_contents(df_documentation=''): """ Function::: table_of_contents Description: brief description here (1 line) Details: Full description with details here Inputs doc_csv_file: FILE csv file with documentation of functions Outputs tab_contents: STR Table of content...
fa5c26b729278bcc312a07fc6822ecf4837e2828
3,632,545
def mock_get_location_business_from_sam(client, duns_list): """ Mock function for location_business data as we can't connect to the SAM service """ columns = ['awardee_or_recipient_uniqu'] + list(update_historical_duns.props_columns.keys()) results = pd.DataFrame(columns=columns) duns_mappings = { ...
61c9d0c0ee18a3840f7b2c0b70c504c388e83343
3,632,546
def repeat(N, fn): """repeat module N times :param int N: repeat time :param function fn: function to generate module :return: repeated loss :rtype: MultiSequential """ return MultiSequential(*[fn() for _ in range(N)])
da20e6af56fd227d6eb2c6e083ac21d5c65e71e3
3,632,547
import numpy def dense_to_one_hot(labels_dense, num_classes): """Convert class labels from scalars to one-hot vectors.""" num_labels = labels_dense.shape[0] index_offset = numpy.arange(num_labels) * num_classes labels_one_hot = numpy.zeros((num_labels, num_classes)) labels_one_hot.flat[index_offset + labels...
dc4c717a03624708be6b09b040acb5a901d1e8f0
3,632,548
from typing import Set from typing import Mapping def parse_input(data: str) -> (Set[str], Mapping[str, Mapping[str, int]]): """Extract the names and associated happines changes from data.""" names = set() happiness_changes = {} for line in data.splitlines(): match = INPUT.fullmatch(line) ...
147cc6a19160b6e472249e59c5a8a41fb73f6cde
3,632,549
def main(argv): """The program. Returns an error code or None. """ try: # Build an environment from the list of arguments. env, writer = make_env_and_writer(argv) try: cmd = COMMANDS[env.options.command](env, writer) cmd.execute() finally: ...
00063921703fea4ef21e8767ccdb1156f3c45911
3,632,550
import pandas def merger(primary_path:str, secondary_path:str, desired_columns:list, shared_column="time"): """ --> Primary path is the global analysis file produced by analyzing NMR spectra --> Secondary path is the raw-data file recorded by the DAQ. --> Desired columns is a list of columns that you want to MIG...
8db087622b691bb0b36505e038c8aa5ed5902121
3,632,551
import unicodedata import re def slugify_ref(value: Text, allow_unicode: bool = False) -> Text: """ Convert to ASCII if 'allow_unicode' is False. Convert spaces to hyphens. Remove characters that aren't alphanumerics, underscores, or hyphens. Convert to lowercase. Also strip leading and trailing whit...
1ce3893436f1590e55679248290aadc486f0d717
3,632,552
import json def user_search(): """UserSearch""" value = request.args.get('search') cur = MY_SQL.connection.cursor() cur.execute( '''SELECT id, username FROM accounts.users WHERE username LIKE '%%%s%%';''', (value) ) users = json.dumps(cur.fetchall()) return users
774234ee4cb4bae2b77a0c469037c695660d250e
3,632,553
def graphcut(img1, img2, mask): """ Inputs: Mask: The 80px area out of the boundary. 2 dims. Pixels on the edge of Img1 are marked with 1 and same for Img2. Internal pixels are marked with 3. Img1 & Img2: Here Img1 means source img, aka. the input img. Img2 is...
a6d113e714191015f446cf1e687d925258dfb06f
3,632,554
def lutForTBMap(): """ produce a look up table for a red-black-blue colormap""" cmap=mpl.colors.LinearSegmentedColormap.from_list('my_colormap', ['blue','black','red'], 256) #I'm not entirely sure what this lower is for. Its use...
1017d2fc7c7279ac3baa1393286244586d0e30c8
3,632,555
import typing import tqdm def val_one_epoch(model: Module, dataloader: DataLoader, criterion, device: str) -> typing.Tuple[typing.Union[np.ndarray, None], dict]: """ Validate the given model for one epoch. :param model: model to evaluate ...
d51a5fbb064d00de1a48d30927cb1695db0a3168
3,632,556
def multiply_something(num1, num2): """this function will multiply num1 and num2 >>> multiply_something(2, 6) 12 >>> multiply_something(-2, 6) -12 """ return(num1 * num2)
1a726c04df146ab1fa7bfb13ff3b353400f2c4a8
3,632,557
def post_shift_dp(train_set, vali_set, test_set, logreg_model): """Post-shifts log. regression model for demographic parity using vali_set. Returns the train, validation and test sets with the group attribute appended as an additional feature, and the post-shifted linear model for the expanded datasets. Arg...
03cfcf5060e6419398042ff08fbb991c34551726
3,632,558
def determine_acknowledgement(record, report, ignore_string): """Mark report for output unless ignored""" if record[COMMENT_TEXT]: comment = record[COMMENT_TEXT].lower() else: comment = "" if ignore_string in comment: report["should"] = False return True report["shou...
8fd4d0d2623a0183953a21cb2029da0fadc95bff
3,632,559
def estimate_infectious_rate_constant_vec(event_times, follower, t_start, t_end, kernel_integral, count_events...
207833e1b32885fe39a209bfef227665c8c59ad1
3,632,560
import urllib import json def cotacaoBRL(): """ Retorna a última cotação do Bitcoin em BRL - Mercado Bitcoin via API BitValor """ with urllib.request.urlopen("https://api.bitvalor.com/v1/ticker.json") as url: data = json.loads(url.read().decode()) last = data['ticker_24h']['exchanges...
a6c96aa8c8cff46ab4b410a81d1ef19ac912fcbb
3,632,561
from typing import List def adder(journal: Journal) -> List[JournalEntry]: """A task that requires previous phases to have recorded journal entres with tags 'x' and 'y', which it will sum. Returns a new journal entry, titled 'x+y', containing the sum of the existing journal entries 'x' and 'y' """ x...
03303cd74dffa0631dbb120280666701268871e7
3,632,562
def find(word,letter): """ find letter in word , return first occurence """ index=0 while index < len(word): if word[index]==letter: #print word,' ',word[index],' ',letter,' ',index,' waht' return index index = index + 1 return -1
bdeb0f0993fb4f7904b4e9f5244ea9d7817fa15f
3,632,563
def subsample_ind(n, k, seed=32): """ Return a list of indices to choose k out of n without replacement """ rand_state = np.random.get_state() np.random.seed(seed) ind = np.random.choice(n, k, replace=False) np.random.set_state(rand_state) return ind
958ddcf3122bc8c8f9cab0539896bfc624d1901f
3,632,564
def HA2(credentails, request): """Create HA2 md5 hash If the qop directive's value is "auth" or is unspecified, then HA2: HA2 = md5(A2) = MD5(method:digestURI) If the qop directive's value is "auth-int" , then HA2 is HA2 = md5(A2) = MD5(method:digestURI:MD5(entityBody)) """ if crede...
94f9a6b6e6371f1d7c1c6606577cbbced201facf
3,632,565
from typing import Dict from typing import Any import hashlib def name_to_scope( template: str, name: str, *, maxlen: int = None, params: Dict[str, Any] = None, ) -> str: """Return scope by given template possibly shortened on name part. """ scope = template.format(name=name, **params)...
cd6759da406b6072565f693cdffe8eb16107c074
3,632,566
def bootstrap_idxs(n, rng: np.random.Generator = None): """ Generate a set of boostrap indexes of length n, returning the pair (in_bag, out_bag) containing the in-bag and out-of-bag indexes as numpy arrays """ if rng is None or type(rng) is not np.random.Generator: rng = np.random.default_rn...
3d76cfea110c91a228bc8bc3ec5698c9a94676b8
3,632,567
def run(argv=None): """Main entry point; defines and runs the wordcount pipeline.""" parser = argparse.ArgumentParser() parser.add_argument('--input', dest='input', default='$GTFS_BUCKET/at/20190429120000/at.zip', help='Input file to p...
d4bacf3a16dc53e3e8b6213e6dbbb2be9a7df2b0
3,632,568
def check_skyscrapers(input_path: str): """ Main function to check the status of skyscraper game board. Return True if the board status is compliant with the rules, False otherwise. >>> check_skyscrapers("check.txt") True """ lst = read_input(input_path) if check_columns(lst) and\ ...
ff57e649bbd87563fe97e870e304259041f0582f
3,632,569
from typing import Dict from typing import Any import importlib def load_preprocessor(preproc_params: Dict[str, Any], device: str) -> Module: """Load preprocessor from module preprocessors.name""" preproc = None if preproc_params is not None: preproc_module = importlib.import_module( f...
a6ea8dc293c883f5bcd1841bd1d483b97d393dab
3,632,570
def get_image_ground_truth(image_id, dataset): """Load and return ground truth data for an image (image, mask, bounding boxes). Args: image_id: Image id. Returns: image: [height, width, 3] class_ids: [instance_count] Integer class IDs bbo...
3894e5714ceb64c7b414f100e69ac5c3b2b36fb8
3,632,571
import html def update_stream_metadata(stream_names): """ Updates the sidebar with metadata from a board live stream """ if not stream_names[0]: return html.P("Metadata will appear here when you pick a stream"), print(f"Getting metadata for {stream_names[0]}") metadata = cfg.redis_ins...
f0db85b232d00deebc9f970c9ab92a472e717288
3,632,572
def nested_field_map(name: str) -> Mapper: """ Arguments --------- name : str Name of the property. Returns ------- Mapper Field map. See Also -------- field_map """ return field_map( name, python_to_api=lambda x: [[x]], api_to_...
7af0a3e8df4f4bc8228a3473d75bbab527bf0eee
3,632,573
def socket_state(realsock, waitfor="rw", timeout=0.0): """ <Purpose> Checks if the given socket would block on a send() or recv(). In the case of a listening socket, read_will_block equates to accept_will_block. <Arguments> realsock: A real socket.socket() object to check for. ...
fc2fa9162d3228021c6738e0e2453cabae907899
3,632,574
def wrap_with_threadpool(obj, worker_threads=1): """ Wraps a class in an async executor so that it can be safely used in an event loop like asyncio. """ async_executor = ThreadPoolExecutor(worker_threads) return AsyncWrapper(obj, executor=async_executor), async_executor
744a428535aa70d7b130e12bb9c144aac3df4d96
3,632,575
import re def file_read(lines): """ Function for the file reading process Strips file to get ONLY the text; No timestamps or sentence indexes added so returned string is only the caption text. """ # new_text = "" text_list = [] for line in lines: if re.search('^[0-9]', line) is No...
7d37bb79c6b1cdd43d7b813e03bf3d8b18f5a6ed
3,632,576
from sys import exc_info def ipn(request): """PayPal IPN (Instant Payment Notification) Cornfirms that payment has been completed and marks invoice as paid. Adapted from IPN cgi script provided at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/456361""" payment_module = config_get_group('PAYM...
d04e6b8a5bf08a59c081d912e531be2b7e7539ab
3,632,577
def has_file_ext(view, ext): """Returns ``True`` if view has file extension ``ext``. ``ext`` may be specified with or without leading ``.``. """ if not view.file_name() or not ext.strip().replace('.', ''): return False if not ext.startswith('.'): ext = '.' + ext return view.fil...
043edf03874d1ec20e08fcb5795fd205206f7194
3,632,578
def balanced_accuracy_score(y_true: np.array, y_score: np.array) -> float: """ Calculate the balanced accuracy for a ground-truth prediction vector pair. Args: y_true (array-like): An N x 1 array of ground truth values. y_score (array-like): An N x 1 array of predicted values. Returns:...
4c7a17e5a5706b8b8cf65d15db51283d7873aca0
3,632,579
import re def VOLTS(text): """ Parse all voltages in tegrastats output [VDD_name] X/Y X = Current power consumption in milliwatts. Y = Average power consumption in milliwatts. """ return {name: {'cur': int(cur), 'avg': int(avg)} for name, cur, avg in re.findall(VOLT_RE, text)}
f79934a037b2d995974e833c8b7b045e195637d4
3,632,580
from typing import Union async def get_team_id(user_id: int) -> Union[int, None]: """Return the team id of a user based on their user id.""" data = await users.find_one( {"user_id": user_id}, {"team_id": 1, "_id": 0}, ) if data: team_id = data.get("team_id") else: ...
e0905e65edc6ff84d35d25ec43eb98f3898295af
3,632,581
def _clone_static_fields(ex: TensorDict,) -> TensorDict: """Clone static fields to each ray. Args: ex: A single-camera or multi-camera example. Must have the following fields -- frame_name, scene_name. Returns: Modified version of `ex` with `*_name` features cloned once per pixel. """ # Identi...
126d564e4704ee3a7c878630cadcd3adcb58eeaf
3,632,582
def get_atom_types_selected(smi_file, database): """ Determines the atom types present in an input SMILES file. Args: smi_file (str) : Full path/filename to SMILES file. """ # list of atom types to be selected if database == "GDB-13": atom_types = ['H', 'C', 'N', 'O', 'Cl'] p...
26a92a44db7c4f187f21e6dfe8dd64694fabc29a
3,632,583
def run_profile(times, schedule, msid, model_spec, init, pseudo=None): """ Run a Xija model for a given time and state profile. :param times: Array of time values, in seconds from '1997:365:23:58:56.816' (cxotime.CxoTime epoch) :type times: np.ndarray :param schedule: Dictionary of pitch, roll, etc. va...
92ffe057738183d50aac40693d572a232354e621
3,632,584
def extract_optimized_structure(out_file, n_atoms, atom_labels): """ After waiting for the constrained optimization to finish, the resulting structure from the constrained optimization is extracted and saved as .xyz file ready for TS optimization. """ optimized_xyz_file = out_file[:-4]+".xyz" ...
203dfd85987c29ec4f2479ca47be0d497a230480
3,632,585
def get_genes(exp_file, samples, threshold, max_only): """ Reads in and parses the .bed expression file. File format expected to be: Whose format is tab seperated columns with header line: CHR START STOP GENE <sample 1> <sample 2> ... <sample n> Args: exp_file (str): Name...
62b27eef9c863078c98dee0d09bada5e058909e2
3,632,586
def conv_name_to_c(name): """Convert a device-tree name to a C identifier This uses multiple replace() calls instead of re.sub() since it is faster (400ms for 1m calls versus 1000ms for the 're' version). Args: name: Name to convert Return: String containing the C version of this...
150af670d8befea7374bbb5b13da9d6e0734863e
3,632,587
from typing import Tuple from typing import Optional from typing import List import io from re import I import textwrap def generate( symbol_table: intermediate.SymbolTable, namespace: csharp_common.NamespaceIdentifier ) -> Tuple[Optional[str], Optional[List[Error]]]: """ Generate the C# code of the visit...
53e905a0ad37b5f6e47220439747a004db7f8203
3,632,588
def get_account_id(role_arn): """ Returns the account ID for a given role ARN. """ # The format of an IAM role ARN is # # arn:partition:service:region:account:resource # # Where: # # - 'arn' is a literal string # - 'service' is always 'iam' for IAM resources # - 'regi...
623eb66eefd59b9416deb478c527062ae4454df7
3,632,589
def retrieve_context_topology_node_total_potential_capacity_total_potential_capacity(uuid, node_uuid): # noqa: E501 """Retrieve total-potential-capacity Retrieve operation of resource: total-potential-capacity # noqa: E501 :param uuid: ID of uuid :type uuid: str :param node_uuid: ID of node_uuid ...
5a4cdee9e14783598ad622fd7faacc5c11b2ed70
3,632,590
def GHP_Op_max(Q_max_GHP_W, tsup_K, tground_K): """ For the operation of a Geothermal heat pump (GSHP) at maximum capacity supplying DHN. :type tsup_K : float :param tsup_K: supply temperature to the DHN (hot) :type tground_K : float :param tground_K: ground temperature :type nProbes: float...
3025a70d8d32030cb098b2087e0d9e0eef16b315
3,632,591
def attention_lm_decoder(decoder_input, decoder_self_attention_bias, hparams, name="decoder"): """A stack of attention_lm layers. Args: decoder_input: a Tensor decoder_self_attention_bias: bias Tensor for self-attention (see c...
90ff631cdf8898dfde86e965ad70c317936f0b1c
3,632,592
from typing import Any def list_to_dict(data: list, value: Any = {}) -> dict: """Convert list to a dictionary. Parameters ---------- data: list Data type to convert value: typing.Any Default value for the dict keys Returns ------- dictionary : dict Dictionary ...
1e73bb6ca98b5e2d9b1e0f8d4cb19fc044a9ce63
3,632,593
def Routing_Meta(): """Routing_Meta() -> MetaObject""" return _DataModel.Routing_Meta()
f5fc17eb8dc8e428e03ec6fe37cb9dec2c32f355
3,632,594
def get_tag_name(tag): """ Extract the name portion of a tag URI. Parameters ---------- tag : str Returns ------- str """ return tag[tag.rfind("/") + 1:tag.rfind("-")]
e24f0ae84ed096ec71f860291d1e476c75bf8370
3,632,595
import requests def create_user(token, user_name, maps_to_id): """ Creates the user account in Keycloak """ users_url = '{keycloak}/auth/admin/realms/{realm}/users'.format( keycloak=KEYCLOAK['SERVICE_ACCOUNT_KEYCLOAK_API_BASE'], realm=KEYCLOAK['SERVICE_ACCOUNT_REALM']) headers = {...
e7a4b9cce99343156dc3933d7726cbc8ff5a1597
3,632,596
import os def construct_url(test): """Construct URL for the REST API call.""" server_env_var = test["Server"] server_url = os.environ.get(server_env_var) if server_url is None: log.error("The following environment variable is not set {var}".format(var=server_env_var)) return None ...
2623313d9c34170b87bfb756905da2802cc1b805
3,632,597
def view_profile(request, username=None): """view a user's profile """ message = "You must select a user or be logged in to view a profile." if not username: if not request.user: messages.info(request, message) return redirect("collections") user = request.user ...
5ab171f5d1f414100b8c8e36b652511b3df37a9b
3,632,598
import torch def bf_shannon_entropy(w: 'Tensor[N, N]') -> 'Tensor[1]': """ Compute the Shannon entropy of w. Warning: this method is very inefficient. It should only be used on small examples, e.g., for testing purposes. """ Z = torch.zeros(1).double().to(device) H = torch.zeros(1).double(...
b606c97cd43ead270b82d73bf9af2a0aed2b9a08
3,632,599