content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def cwd_hg_version(short=False): """Get the Mercurial changeset hash of the repository that contains the current working directory. If ``short`` is True, the short (12-character) form of the changeset hash will be returned. If the current working copy of the repository is modified, a plus sign is append...
4a1f369cd635230c44d4725b13b9704700d5bf3b
3,623,955
from typing import List from typing import Dict def parse_idf(content: str) -> dict: """Parse an IDF file into a dictionary.""" sections = content.rstrip().split(';') sub_sections: List[List[str]] = [] obj_dict: Dict[str, List[List[str]]] = {} for sec in sections: sec_lines = sec.splitline...
9232964d590745482bb0552520b7ad42ebce8d94
3,623,956
from pathlib import Path import joblib def _make_item_rec_sys_data(review_data): """ Generates item_rec_sys_data by obfuscating customer ids. Parameters ---------- review_data: combined_data. Yields ------ item_rec_sys_data.csv Returns ------- item_rec_sys_da...
868cae8a54513be3a129fdf7f38320652f265733
3,623,957
def system_order(tf: scipysig.dlti) -> tuple: """Returns the order of the numerator and denominator of a transfer function Parameters ---------- tf : scipy.signal.dlti discrete time rational transfer function Returns ---------- (num, den): tuple Tuple containing the o...
d432e61758ceed35f3f5f1eeadf41c2080d137c6
3,623,958
def drvit_small_patch16_384(pretrained=False, **kwargs): """ ViT-Small (ViT-S/16) NOTE I've replaced my previous 'small' model definition and weights with the small variant from the DeiT paper """ model_kwargs = dict(patch_size=16, embed_dim=384, depth=12, num_heads=6, **kwargs) model = _create_visi...
e9c59e19c98f17318fb058a8c2262fb8d40f0e79
3,623,959
def pdist_block(pdist_vec, i, j): """Slice the pdist ndarray as if it were a squareform matrix. Args: pdist_vec: ndarray output from pdist() i: ndarray row index of matrix j: ndarray col index Returns: (i.size, j.size) ndarray from distance matrix """ col_ind, row_ind = np.meshgrid(...
4ad2ba8694aa1fb6396d1c396c33264642451d25
3,623,960
def ufile_put_url(bucket, key): """ 采用普通上传方法上传UCloud UFile文件的url :param bucket: string类型, 待创建的空间名称 :param key: string类型, 在空间中的文件名 :return: string类型, 普通上传UFile的url """ return 'http://{0}{1}/{2}'.format(bucket, config.get_default('upload_suffix'), key)
a5bc7ab0bed9dc6368b7ca985c9f5bcb004378e4
3,623,961
from typing import Optional def build_assemblenet_model( input_specs: tf.keras.layers.InputSpec, model_config: cfg.AssembleNetModel, num_classes: int, l2_regularizer: Optional[tf.keras.regularizers.Regularizer] = None): """Builds assemblenet model.""" input_specs_dict = {'image': input_specs} ba...
017347267a768b58609c9bb24faefe0bcb0b5cd5
3,623,962
import httpx async def post_donation(donation_id: str) -> tuple: """Post donations to their respective third party APIs If the donation has already been posted, it will not be posted again. """ donation = await get_donation(donation_id) if not donation: return (jsonify({"message": "Donati...
84fd0e7a975cf913b79b2fa91a1569b25f4bdb8d
3,623,963
import transformers from typing import List import torch import tqdm def predict_in_batches( model: transformers.models, tokenizer, dataset: List[str], batch_size: int = 4 ) -> List[int]: """Predicts the labels for the entries in dataset using the model passed :param model: the model to use for prediction...
e21a668c2181acd076b565bbde379b028cbeead6
3,623,964
def remove_punctuation(sentence: str, punctuation: str = None): """ Default Punctuation -> [',', '!', '#', '$', '%', "'", '*', '+', '-', '.', '/', '?', '@', '\\', '^', '_', '~'] """ punctuation = punctuation or ''.join(PUNCTUATION) for x in punctuation: sentence = sentence.replace(x, '') ...
2b421a69efdb2bb58f1c778725953ceb2357394d
3,623,965
def get_digest_for(changelogs, before_date=None, after_date=None, limit_versions=5): """Before date and after date are inclusive.""" # search packages which have changes after given date # we exclude unreleased changes from digest # because they ...
73dd266b3a02d9a4a1f499937f630605e2918582
3,623,966
import pkg_resources def get_version(): """Returns version""" return pkg_resources.get_distribution("rosetta-cipher").version
4a9e67434e8a1884e44dafaa30ffaf8c5ec5025d
3,623,968
def good_fft_number(goal): """pick a number >= goal that has only factors of 2,3,5. FFT will be much faster if I use such a number""" assert goal < 1e5 choices = [2**a * 3**b * 5**c for a in range(17) for b in range(11) for c in range(8)] return min(x for x in choic...
e469a37f28869dca520aea3520fa0d763e9bb8ae
3,623,969
def adjust_image_resolution(data): """Given image data, shrink it to no greater than 1024 for its larger dimension.""" output_large = cStringIO.StringIO() output_default = cStringIO.StringIO() output_tiny = cStringIO.StringIO() try: im0 = Image.open(cStringIO.StringIO(data)) ...
06a6048efbc11fdc7c151feacbb4eddfa46ad90a
3,623,970
def connect_to_ecs(env): """ Return boto connection to the ecs in the specified environment's region. """ rh = env.resource_handler.cast() wrapper = rh.get_api_wrapper() client = wrapper.get_boto3_client( 'ecs', rh.serviceaccount, rh.servicepasswd, env.aws_region ...
e4c0b7ad80c18fd6d2a90df6670ca9bfa6f1cbe3
3,623,971
import random def dsa_sign(message, private, constants=None): """DSA signs the bytestring `message` with the given private key and returns the signature (r, s) using the hash SHA1""" p, q, g = get_dsa_constants(constants) while True: k = random.randint(1, q - 1) r = pow(g, k, p) % q ...
780fd6370f0a73ca6ee3d761ffb21b5f6d6efaf1
3,623,972
def _pytesmo_to_qa4sm_results(results: dict) -> dict: """ Converts the new pytesmo results dictionary format to the old format that is still used by QA4SM. Parameters ---------- results : dict Each key in the dictionary is a tuple of ``((ds1, col1), (d2, col2))``, and the values...
f4f36562a65dd140a16b3969fe26a3450e7f9037
3,623,973
def infotodict(seqinfo): """Heuristic evaluator for determining which runs belong where allowed template fields - follow python string module: item: index within category subject: participant id seqitem: run number during scanning subindex: sub index within group """ info = {'test':[]...
ea5c334452cbc3e5fd700c38f258578b26f9cf56
3,623,975
def grab_svg(scene): """ Return a SVG rendering of the scene contents. Parameters ---------- scene : :class:`CanvasScene` """ svg_buffer = QBuffer() gen = QSvgGenerator() gen.setOutputDevice(svg_buffer) items_rect = scene.itemsBoundingRect().adjusted(-10, -10, 10, 10) if ...
a4292ff99062be7a110f31aafc4ee50f88618b58
3,623,977
def get_bel_node_uniprot(): """Get UniProt related eBEL nodes.""" b = Bel() conf = { 'rid': "@rid.asString()", 'name': "name", 'namespace': "namespace", 'bel': "bel", 'uniprot_accession': "uniprot" } sql = "SELECT " sql += ', '.join([f"{v} as {k}" for k, v...
ff38ba4f8daaa12549c482a2b7b7bd7444e21750
3,623,978
import torch def decode_ori_batch(ori, b): """Decode a batch of orientation (ori) using the pre-computed orientation decode variable (b) based on the histogram (see pre_compute_ori_decode) """ ori = ori.cpu() batch_size = ori.size(0) ori_avg = torch.zeros((batch_size, 4), dtype=torch.float32...
a6acac339d3cf0613b733d0258ba21d1c8c57d9f
3,623,979
from datetime import datetime def receive_email(msg_str): """ Given a string representation of an email message, parses it into a :class:`~kiki.message.KikiMessage`. Returns a (message, created) tuple, where ``created`` is False if the message was already in the database. """ received = datetime.now() python_m...
58a7bbc758be4eb48d71794452dab18a2ae307b4
3,623,980
def rotated_array_search(input_list, number): """ Find the index by searching in a rotated sorted array """ high = len(input_list) - 1 low = 0 while low <= high: mid = (low + high) // 2 if input_list[mid] == number: return mid elif input_list[mid] < number <= ...
c3deb50e608c58e5e11665d949a602cc661305ae
3,623,981
def parse_sentence_spacy(sentence_text, sentence_entities): """ :param sentence_text: :param sentence_entities: :return: """ # Use spacy to parse a sentence for e in sentence_entities: idx = sentence_entities[e][0] sentence_text = sentence_text[:idx[0] - 1] + sentence_text[...
b6da3a1f5dc02196286c666fa268ad7cfadb4c40
3,623,982
def check_for_deprecated_generators(main, file): """ Check if the conan file if using some deprecated generator :param main: Output stream :param file: Conanfile path """ conan_instance, _, _ = conan_api.Conan.factory() dict_generators = conan_instance.inspect(path=file, attributes=["generators...
a281e6b7e3ff48a49830a19c2bbb2fe9907d1e8d
3,623,983
def get_chat_members_count(chat_id, **kwargs): """ Use this method to get the number of members in a chat. :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) :param kwargs: Args that get passed down to :class:`TelegramBotRPCRequest` ...
1cec0d216fd3c1f28c1592cf2be170c26f32780a
3,623,984
def sample_tag(user, name='Sample tag'): """Create and reutn a sample tag""" return Tag.objects.create(user=user, name=name)
985d40292258efa4fb997a1f68a1ca523c43df02
3,623,985
def _unpack_keypoints(keypoints): """Unpack the keypoints into an array of coordinates. Args: keypoints: a list of `cv2.KeyPoint`s Returns: an n x 2 array of [row, col] coordinates """ return np.array([[kp.pt[1], kp.pt[0]] for kp in keypoints])
a594c580729750f493703310e067abe3196650a4
3,623,986
def get_videos(): """Return a json array of all videos available on the site, built by fetching each page sequentially until there are no more pages.""" videos = [] page = 0 end_of_pages = False while not end_of_pages: page += 1 url = "http://pyvideo.org/api/v2/video?page=%s" % s...
8e3e5e2cea320fcdaf9ce819d06d59db97881ec5
3,623,987
import click def input_mon(ctx): """ Monitors all pins for changes. Expects ANSI terminal color. """ click.echo("Ctrl-\\ to quit") d = CM119_IO(ctx.obj["vid"], ctx.obj["pid"]) d.set_dir({pin: "I" for pin in range(1, 9)}) # All GPIOs as inputs def pin_formatter(pin_name, state): """Helpe...
905ad5433fcb5c774f43b0ac143326367ab46bbd
3,623,988
from typing import Optional def has_at_least_one_share_class(filing_json, filing_type) -> Optional[str]: # pylint: disable=too-many-branches """Ensure that share structure contain at least 1 class by the end of the alteration or IA Correction filing.""" if filing_type in filing_json['filing'] and 'shareStruc...
ce0e324edd1fb4e427aafdedcdecafc736fdb8d0
3,623,990
def color_thresholding(img, thresh_h=None, thresh_s=None, thresh_l=None): """ Crete image mask using color thresholding. :param img: source bgr image :param thresh_h: tuple(min,max), hue threshold in HSL color space :param thresh_s: tuple(min,max), saturation threshold in HSL color space :retur...
387de7a3935431659de8b45e56efed0e4d38dc0f
3,623,992
import builtins def no_matplotlib(monkeypatch): """ Mock an import error for matplotlib""" import_orig = builtins.__import__ def mocked_import(name, globals, locals, fromlist, level): """ """ if name == 'matplotlib.pyplot': raise ImportError("This is a mocked import error") ...
681ba8c0e70387e46ad7ed42ffb11ce8aa7f23bc
3,623,993
def _get_center_context( context_window_type, walks, n_walks, walk_len, window_length, padding_id ): """Get center and context pairs from a sequence window_type = {-1,0,1} specifies the type of context window. window_type = 0 specifies a context window of length window_length that extends both left ...
d09b224341e3ceec2eb69ad3e7d0a03a1ea2035b
3,623,994
def get_files(pga_id): """ Get all uploaded YAML files as a dictionary. :return: dict of uploaded YAML files as JSON """ files_dict = utils.get_uploaded_files_dict(pga_id) return jsonify(files_dict)
b2ab923de32a9ac9eee42dbebb218f075f4ea266
3,623,995
def convert_mask_to_pick(mask, sample_rate, threshold): """Convert a first breaks `mask` into an array of arrival times. The mask has shape (n_traces, trace_length), each its value represents a probability of corresponding index along the trace to follow the first break. A naive approach is to define the f...
615c168bb119a8db1acb5581fa391ef6384c3f44
3,623,996
import tqdm def create_tqdm_reader(reader, max_reads=None): """Wrap an iterable in a tqdm progress bar. Args: reader: The iterable to wrap. max_reads: Max number of items, if known in advance. Returns: The wrapped iterable. """ return tqdm.tqdm(reader, total=max_r...
29bd93b85ace167f5586ac275510e82f7bbe8223
3,623,997
def calc_U_slip_quasisteady(eps, E, x, mu): """ Slip velocity (quasi-steady limit) """ u_slip_quasisteady = -eps*E**2*x/(2*mu) return u_slip_quasisteady
0b5eebc9333b36cbd4b8179731e5998f7cb2739a
3,623,998
def momentum(df, column='close', n=20, add_col=False, return_struct='numpy'): """ Momentum Parameters ---------- df : Pandas DataFrame A Dataframe containing the columns open/high/low/close/volume with the index being a date. open/high/low/close should all be floats. volume ...
72d4c5746e40d2ea70a9527d443249fe850401f7
3,623,999
def mock_cloud_fixture(opp): """Fixture for cloud component.""" opp.loop.run_until_complete(mock_cloud(opp)) return mock_cloud_prefs(opp)
d9fc59fabe3cc49848062fbe4c5c4343b1c3cfed
3,624,001
from typing import OrderedDict def get_distinct_project_attributes(attribute, path=PROJECT_HOME): """Get distinct values of the named attribute. .. versionadded:: 0.16.0-d :param attribute: The name of the attribute. :type attribute: str :param path: The path to where projects are stored. :...
066157c2d5a6e49ddb2e7a7d4ee79f1bee4a6ae1
3,624,002
def scale_y_reverse(name=None, breaks=None, labels=None, limits=None, expand=None, na_value=None): """ Continuous position scales (y) where trans='reverse' Parameters ---------- name : string The name of the scale - used as the axis label or the legend title. If None, the default, the name ...
718b662f1c80193962896765391b89fe12fbc0df
3,624,003
import math def get_sequence_of_considered_visits(max_num_considered_actions, num_simulations): """Returns a sequence of visit counts considered by Sequential Halving. Sequential Halving is a "pure exploration" algorithm for bandits, introduced in "Almost Optimal Explorati...
f0081ae5bfe25d6a3eaad9f032cfb88a403fbb45
3,624,004
import random def select_object(): """Select a random image from the PDS Planetary Rings Node.""" # First randomly select a field fields = set(META['FIELD']) field = random.sample(fields, 1)[0] # Having selected a field, select a random number from that mission max_field = META['MAX_NUM'][META['FIELD'] == field...
05d8c26ad4671bf80cfeee9afa18be558a7a2075
3,624,006
import base64 def load_all_vocabs_details_from_github(): """Uses the GitHub API via the Python client to get all the vocab details from the files in the vocabularies/ folder :return: a dict of vocabularies' details """ print('Loading all vocabs from GitHub') print("Vocabs to be uploaded:") ...
ad662b0ff3517e4415a0f1b0e0d4558c1d4b55ef
3,624,007
def two_node_diff(a): """Calculate and return diffs over two nodes instead of one.""" N = len(a) return a[2:] - a[:(N-2)]
a38abe787ef87c37104373b402fc020f85f8e3aa
3,624,008
def get_hue_sample_num(gamut_boundary_lut_name=mcfl.BT709_BOUNDARY): """ shape[0]: luminance sample shape[1]: hue sample """ return np.load(gamut_boundary_lut_name).shape[1]
8d7b6c4a8895a9574ab07e2eae9df9b0f33336a1
3,624,009
def _get_timeout(payload_len): """Conservatively assume min 5 seconds or 3 seconds per 1MB.""" return max(3 * payload_len / 1024 / 1024, 5)
70ef10f9c4630afafa0019057bdaa005eb39e7ad
3,624,011
def add_vec_mod2(v, w): """ Mod 2 addition separately on each components of v and w :params list/str v, w: bit-strings (or list representations) to be added mod 2 :return str: component-wise mod 2 sum of the input strings/lists """ if len(v) != len(w): raise AssertionError("Input length...
01d01b522f1f046430c7df1f7cc5486280f5588a
3,624,014
def sokal_sneath3( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: """Sokal-Sneath similarity (v3) Sneath, P. H., & Sokal, R. R. (1973). Numerical taxonomy. The principles and practice of numerical classification. Args: x (BinaryFeatureVecto...
054ccadfa0f0b63a508c51ceae33027d6e3ef030
3,624,015
def deactivate(name, path, user): """ Deactivate a wordpress plugin name Wordpress plugin name path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.deactivate HyperDB /var/www/html a...
fadb823fdf9aa9b34fc6a29b877d553f62f2f7a5
3,624,016
def _average_gradients(tower_grads, catname=None): """Calculate the average gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. Args: tower_grads: List of lists of (gradient, variable) tuples. The outer list is over...
1bd6af89d32003299b00ebd3cf5e57d7d6faeb14
3,624,017
def _validate_int( setting, value, option_parser, config_parser=None, config_section=None ) -> int: """Validate an integer setting.""" return int(value)
9036b1b043bd2463cad4f26780d47e80aa404f73
3,624,018
def get_best_name(phenomena): """ Create a best_name field which takes the best name as defined by the preference order :param phenomena: phenomena attributes in form [{"name":"standard_name","value":"time"},{"name":"---","value":"---"},{}...] :return: best_name(string) """ preference_order = ["...
cd5f1153a22e161e96f48fdcc02f4c4dbbfdbc34
3,624,019
def GetFqdn(): """Get the desired FQDN via flags.""" return FLAGS.glazier_spec_fqdn
9cea852620d1c13944294f5ab8e49223b643c525
3,624,020
def get_global_evidence(a): """ PyMultiNest's Analyzer has a get_stats() method, but it's a bit too sluggish if all we want is to get the global evidence out. This is a hack around the issue. """ stats_file = open(a.stats_file) lines = stats_file.readlines() stats = {} a._read_error_...
8677908c4537927f168cd16ab1ddbfaf959f4546
3,624,021
def load_data(database_filepath): """Loads data from database and returns label and features dataframe""" engine = db.create_engine('sqlite:///{}'.format(database_filepath)) conn = engine.connect() df = pd.read_sql_table('messages', con=conn) X = df['message'] Y = df.iloc[:, 4:] return X, Y...
74e2dc17d3971ece3faaaadb25ce6b77d912e1fd
3,624,022
def merge_scalar_results(results, scalar_fields): """ Collect all scalar results in a (hierarchical) dataframe. """ return pd.DataFrame( [[getattr(res, k) for k in scalar_fields] for res in results], columns=scalar_fields, ).set_index("case")
168581d50b00acf21ab45724faf5f678331198e7
3,624,023
from re import M def omega_KMid(r): """ Keplerian angular velocity """ return (const.G*M/((r*u.AU)**3))**0.5
5e3c00b367cdca232e37e6b06df98737bb89f054
3,624,024
def buildRecorderDicts(energyInterval, powerInterval, voltageInterval, energyPowerMeter, triplexGroup, recordMode, query_buffer_limit): """Helper function to construct dictionaries to be used by individuals to add recorders to their own models. Note that th...
def51273b940ef97d61228cfd54277a9ac053aea
3,624,025
def rooms_n2(): """ Two rooms side by side """ rm1 = Room('rm1', 1e3, [[0,0], [5,0], [5,5], [0,5]]) rm2 = Room('rm2', 2e3, [[5,0], [10,0], [10,5], [5,5]]) rooms = [rm1, rm2] return rooms
ced764acc60480a2c1d5d3488e9e0428d0f425ef
3,624,026
def get_env(env_var_name): """ If present, returns environment variable value, if not - raises 'ImproperlyConfigured' """ env = environ.Env() environ.Env.read_env() return env(env_var_name)
77ef5e6a8762abfe6e7268f7d88c7b4e7cf9211f
3,624,027
def sub(arg1, arg2): """ Function that subtracts two arguments. """ return arg1 - arg2
fb3694bc0827f62befe67cb58c1edb9de1adb808
3,624,028
def query_for_data(driver): """Grab all relevant data on a jobs page. Return: ------ job_titles: list job_locations: list posting_companies: list dates: list hrefs: list """ job_titles = driver.find_elements_by_xpath( "//span[@itemprop='tit...
d3a44ec2e66f9c8ba09dac45dc253c2dd67303c4
3,624,029
def users_json(): """ Return the all the users data in json format """ users = session.query(User).all() return jsonify(users=[user.serialize for user in users])
dd3fec73abbbe563eaa2335c5c2a942f98d0fb34
3,624,030
def get_image_info(filepath): """ Gets an image's information. """ image = Image.open(filepath) info = { 'width': image.size[0], 'height': image.size[1], } metadata = get_image_exif(image) # camera camera = None if EXIF_MODEL in metadata: camera = metada...
e0c4ac5340874acf273873d52163d8642746fa18
3,624,031
import typing def split_line(line: str) -> typing.Tuple[str, str]: """ Separates the raw line string into two strings: (1) the command and (2) the argument(s) string :param line: :return: """ index = line.find(' ') if index == -1: return line.lower(), '' return line[:ind...
964877ebe0e63161f449a1d60542fbcab451de28
3,624,033
def naep_aggregate(input_df): """ :param input_df: :return: """ # Treat years as strings input_df['YEAR'] = input_df['YEAR'].astype('str') # input_df.drop_duplicates(inplace=True) # PRIMARY_KEY, STATE, and YEAR will be the same staging_df = pd.DataFrame() staging_df['PRIMARY_KE...
9666ad6b886797ffe168e26d91aa9d591d1bc7f3
3,624,034
from typing import List def matrix_transpose(mat: List[List]) -> List[List]: """ >>> matrix_transpose([[1, 2], [3, 4], [5, 6]]) [[1, 3, 5], [2, 4, 6]] """ if len(mat) == 0: raise ValueError("Matrix is empty") return [[mat[j][i] for j in range(len(mat))] for i in range(len(mat[0]))]
34cf049779408f0b74a1e29cbd1f0a18a6d5dd23
3,624,035
from typing import Optional def generate_nhs_number_from_first_9_digits(first9digits: str) -> Optional[int]: """ Returns a valid NHS number, as an ``int``, given the first 9 digits. The particular purpose is to make NHS numbers that *look* fake (rather than truly random NHS numbers which might acciden...
e939f1f2e0641355ef0d921202647aee4d1706bb
3,624,036
import requests def passthrough_rest_object(source_url): """ Passes through a non-CORS locked down JSON object from the origin request. """ if request.method == 'GET': reqUrl = request.args.get('url','') req = requests.get(reqUrl) if req.status_code == 200: return req.c...
9c99e34a4635f1aec1cb4dd1e373c3dd69ec7c04
3,624,037
def randint(low, high, shape, device=None): """Returns a tensor filled with random integers generated uniformly between low (inclusive) and high (exclusive). Parameters ---------- low Lowest integer to be drawn from the distribution. high One above the highest integer to be drawn fr...
84532888904c75a6866f3a2547342207559b55e7
3,624,038
def construct_formula(label, rel_cols, label_side="l"): """ Constructs a generic formula string from column names and a label name. label ~ Col1+Col2+...+ColN :param label: Label or class which should be regressed for. (case/control, treatment/untreated etc.) :param rel_cols: Relevant columns for t...
622489b6ecc2345362b55b7af64f120af34870ca
3,624,039
def shell_context(): # pragma: no cover """ Make shell context. :return: A dictionary of objects for use in shell context. :rtype: dict """ return {'DB': DB, 'IMBUser': IMBUser, 'Visit': Visit}
3e3100fa9b6f9fb1ad551fd72cf82dfaa35bacd9
3,624,040
import requests def start_new_session(self): """Starts a new session to be used to send requests and returns it.""" session = requests.Session() session.auth = (self._api_key, '') # pylint: disable=protected-access session.headers['User-Agent'] = config.constants.USER_AGENT session.proxies = PROX...
721bdf2f25fb6ace67107d1f3551cc6f4ed81535
3,624,041
import types from typing import Optional def EvaluateMetricsAndPlots( # pylint: disable=invalid-name extracts: beam.pvalue.PCollection, eval_shared_model: types.EvalSharedModel, desired_batch_size: Optional[int] = None, metrics_key: Text = constants.METRICS_KEY, plots_key: Text = constants.PLOTS_...
75b262c62d6a88dc7c8651c15a725eb282163ae1
3,624,042
from typing import List from typing import Set from typing import Union from typing import Dict def _find_first_common_next_vertex_in_edges__impl( g: Graph, es: List[Set[Union[Edge, None]]], map_of_visited: [List[Dict[int, int]]], allow_open_branches: bool, allow_loops: bool, vs_to_not_visit: List[int...
4431e1563cd7a957eeecdae65f941439e11d95ce
3,624,043
from sentry_sdk import capture_exception def catch_errors(exception=None, catch_generic=True, **kwargs): """ A decorator to preprocess an API class method, and catch a specific error. """ if exception is None: exception = RestApiException def decorator(func): @wraps(func) ...
cabfdbabc8ed3a9c9551dd511310f7080ab04e00
3,624,044
def set_alpha(n_points): """Set an alpha value for plotting that is scaled by the number of points. Parameters ---------- n_points : int Number of points that will be in the plot. Returns ------- alpha : float Value for alpha to use for plotting. """ for key, val i...
b1b992fc15491ae752d3de5358e08ec61d751216
3,624,045
def split_nvr_epoch(nvre: str): """Split nvre to N-V-R and E. This function is backported from `kobo.rpmlib.split_nvr_epoch`. @param nvre: E:N-V-R or N-V-R:E string @type nvre: str @return: (N-V-R, E) @rtype: (str, str) """ if ":" in nvre: if nvre.count(":") != 1: ...
6b65a5dd4655b8d0d961952be41ab6a939cc24c8
3,624,048
def findMergeNode(head1, head2): """ Go forward the lists every time till the end, and then jumps to the beginning of the opposite list, and so on. Advance each of the pointers by 1 every time, until they meet. The number of nodes traveled from head1 -> tail1 -> head2 -> intersection point and ...
01c24a3eda17a8063c94c92cff6d558025c03726
3,624,049
def encode_pool_list(pool, normalize_by=None): """ Return a matrix X of `len(shape) * reduce(mul, shape)` columns and `pool.n` rows, encoding the payoffs of all the games in 'pool', and a vector Y, with `pool.n` rows, of integer "labels" representing which action was played for each example. The la...
4844cf6fc4d1dda21324d933f03508c6ed77373e
3,624,050
def set_weights(): """Set weights for each digit in NHS number""" weights = [10, 9, 8, 7, 6, 5, 4, 3, 2] return np.array(weights)
020e94c4a84e7f2eb691ab54aa41cd4057bbf52f
3,624,051
def expand_and_broadcast(s1: Shape, s2: Shape): """Expand two shapes to make them of equal rank and then broadcast. Args: s1 (:class:`lab.shape.Shape`): First shape. s2 (:class:`lab.shape.Shape`): Second shape. Returns: :class:`lab.shape.Shape`: Expanded and broadcasted shape. ...
a1a780f803760571fb2dca6c400fa284cd9ed329
3,624,052
from pathlib import Path async def augment_chat( request_data: TextData, user: str = Path(default="default", description="user for which the chats needs to be log"), current_user: User = Depends(Authentication.get_current_user_and_bot) ): """ Fetches a bot response for a given text/que...
6a5a52627934215716e74b7338036e766e492468
3,624,055
def py_mb_convert(file_location, file_extension): """ Convert files from one format to another with PyMOAB. Input: ______ file_location: str User supplied file location. file_extension: str User supplied file format to convert to, including '.' Returns: ____...
f171a976f2aab10f10f89883d60302d9e85debb5
3,624,056
def _compress_image(buffer, compression="JPEG"): """ Compress array to specified format. >>> _compress_image(np.array([[0]]), 'JPEG') '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofH\ h0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/wAALCAABAAEBAREA/8QAHwAAAQUBAQEB\ AQEAAAAAAAAAA...
21b5aad16eca48e25dc47194de084ae29ec49546
3,624,057
async def edit_bot(request: Request, user_id: int, bot_id: int, bot: BotMeta): """ Edits a bot, the owner here must be the owner editing the bot. Due to backward compatibility, this will return a 202 and not a 200 on success """ bot_dict = bot.dict() bot_dict["bot_id"] = bot_id bot_dict["use...
b15f7e65d3a1ed3c9b620d3e86c3980245a8c2eb
3,624,058
def sigfig(x, n): """ Produces x values to "n" significant figures From : https://stackoverflow.com/a/55599055 :param x: numpy array, the values to round :param n: int, the number of significant figures required :return: """ if isinstance(x, np.ndarray): xin = np.array(x) ...
1cbdd6c1681dfff296459355a384c3635e2cdeaa
3,624,059
def calc_SingleValueDiff(comp, opt, mtype='mean', ef=True): """ Computes a single value difference of the actual PALC results. Called by :any:`optimize_PALC` and :any:`diff_on_ls`. Parameters ---------- comp : list or 1D-array Computed PALC results in optimization region. opt : list...
62a01eb611c033420f844659516ae230709ab64f
3,624,060
def resnet_v1(input_shape, depth, num_classes=10, activation='relu'): """ResNet Version 1 Model builder [a] Stacks of 2 x (3 x 3) Conv2D-BN-ReLU Last ReLU is after the shortcut connection. At the beginning of each stage, the feature map size is halved (downsampled) by a convolutional layer with str...
ee9b0587fec33e105415f6f6abefa800d8b8d4bd
3,624,061
def get_gains_check(speakers, position, sx, sy, sz): """call get_gains, and check that the return is normalised and positive""" g = get_gains(speakers, position, sx, sy, sz) assert np.all(g >= 0) npt.assert_allclose(np.linalg.norm(g), 1) return g
1d40f9ec23949c02b609e05adc8aa543d9457e4a
3,624,062
import cv2 def test_opencv(): """ This function is workaround to test if correct OpenCV Library version has already been installed on the machine or not. Returns True if previously not installed. """ try: # import OpenCV Binaries # check whether OpenCV Binaries are 3.x+ if parse_version(cv2.__version__) ...
5744b6093492bd4c8d5eb51f747c79a276d42c31
3,624,063
import logging def test_asana_error_handler(caplog): """ Tests the `@asana_error_handler` decorator. """ caplog.set_level(logging.ERROR) def gen_text(text1, text2, text3): return f'{text1} | {text2} | {text3}' dec_gen_text = aclient.asana_error_handler(gen_text) assert dec_gen_te...
ea62be525b4ab41e2bc19c89ae8c52e559b206c6
3,624,064
def expandvars_dict(settings: dict) -> dict: """Expand all environment variables in a settings dictionary. ref: http://stackoverflow.com/a/16446566 :returns: Dictionary with settings """ return {key: _expandvars(value) for key, value in settings.items()}
cf5793be1318759cba9e2a1d0f8c0a0c7dfc1390
3,624,065
import functools from typing import Dict from typing import Any import json from typing import Union def token_required(func): """ [x] - deprecated """ @functools.wraps(func) async def wrapper(self, text_data: str, *args, **kwargs): scope = getattr(self, "scope") user = AnonymousU...
cf24d7ed65272205606f06b0953febe3066c931b
3,624,066
import time def execute( method, max_retries, retry_interval, use_retry=True, *args, **kwargs ): """Execute HTTP request with retry support. Args: method (string): HTTP verb. use_retry (bool): If True, will use retry configuration (default: True). m...
5009296882fd8ff2fdecf7cfde7a42ecedb22099
3,624,067
def stacked_sectors(df): """ Takes dataframe and sorts table fields by sector Parameters ---------- **df** : 'pd.df' Dataframe to be sorted by sector. Returns ------- **output** : 'pd.df' Dataframe of the table that was imported and split by sector """ ...
7a8a228a523f5f315b14464730ca510e37df8bd1
3,624,068
def stringify(num): """long int -> 20-character string""" str = hex(num)[2:] if str[-1] == 'L': str = str[:-1] if len(str) % 2 != 0: str = '0' + str str = str.decode('hex') return (20 - len(str)) *'\x00' + str
36cf6888136e42724f2744dfb59de16e4fe494e6
3,624,069