content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def compute_lorentz(Phi, omega, sigma): """In a time-harmonic discretization with quantities .. math:: \\begin{align} A &= \\Re(a \\exp(\\text{i} \\omega t)),\\\\ B &= \\Re(b \\exp(\\text{i} \\omega t)), \\end{align} the time-average of :math:`A\\times B` over one ...
5b82df614d8245565e3427277ace2e0ba3fd27c5
10,900
def play_db(cursor, query_string, lookup_term): """ Given a query string and a term, retrieve the list of plays associated with that term """ play_list = [] try: cursor.execute(query_string, [lookup_term]) play_res = cursor.fetchall() except DatabaseError as err: LOG...
35ee0f96e122cddf65dbce7b127a8123b703b8f8
10,901
def find_nocc(two_arr, n): """ Given two sorted arrays of the SAME lengths and a number, find the nth smallest number a_n and use two indices to indicate the numbers that are no larger than a_n. n can be real. Take the floor. """ l = len(two_arr[0]) if n >= 2 * l: return l, l if n ...
42c8998e24095f03b0d873a0c9ad1f63facab8cb
10,902
import json def get_dict(str_of_dict: str, order_key='', sort_dict=False) -> list: """Function returns the list of dicts: :param str_of_dict: string got form DB (e.g. {"genre_id": 10, "genre_name": "name1"}, {"genre_id": 11, "genre_name": "name12"},...), :param order_key: the key by which dictionaries...
81d20db2dbe929693994b5b94aa971850ef9c838
10,903
import hashlib import struct def get_richpe_hash(pe): """Computes the RichPE hash given a file path or data. If the RichPE hash is unable to be computed, returns None. Otherwise, returns the computed RichPE hash. If both file_path and data are provided, file_path is used by default. Source : https...
30e5437f36f76a6225eaba579d55218440ab46b9
10,904
def get_input(label, default=None): """Prompt the user for input. :param label: The label of the prompt. :param label: str :param default: The default value. :rtype: str | None """ if default: _label = "%s [%s]: " % (label, default) else: _label = "%s: " % label ...
11de813f0fcfd16f1198299030656c07392f95c9
10,905
import logging def get_pretrain_data_text(data, batch_size, num_ctxes, shuffle, num_buckets, vocab, tokenizer, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, whole_word_mask, num_parts=1, part_idx=0, num_workers...
986ba7afc87f8ce5b054816de365e1c2793f6876
10,906
def define_app_flags(scenario_num): """ Define the TensorFlow application-wide flags Returns: FLAGS: TensorFlow flags """ FLAGS = tf.app.flags.FLAGS tf.app.flags.DEFINE_boolean('save_model', False, 'save model to disk') tf.app.flags.DEFINE_string('summaries_dir', './logs', 'tens...
de79e076db37f7981633b3b2b38db6b462155709
10,907
def longitude_validator(value): """Perform longitude validation. """ valid = -180 < value < 180 if not valid: raise ValidationError(_('longitude not in range of -90 < value < 90')) return value
866c45da71d1b4d6b2d5bd60e331caecb365f297
10,908
import os import json def getVariables(): """ Retrieves the variables.json file. """ if os.path.exists('variables.json'): with open('variables.json') as jsonFile: variables = json.loads(jsonFile.read()) return variables else: variables = {} variable...
ba0c37c14e92caa9bb83bb078d864541cbeec4ac
10,909
from typing import List import random def stop_random_tasks( cluster: str, task_count: int = None, task_percent: int = None, service: str = None, reason: str = "Chaos Testing", configuration: Configuration = None, secrets: Secrets = None, ) -> List[AWSResponse]: """ Stop a random n...
8e56f5aee8254deb7d11e6f48477491a8e572a99
10,910
def test_create_batch_multi_record_update_fails(shared_zone_test_context): """ Test recordsets with multiple records cannot be edited in batch (relies on config, skip-prod) """ client = shared_zone_test_context.ok_vinyldns_client ok_zone = shared_zone_test_context.ok_zone # record sets to setup...
b2fe0cea07af57996058cdb0f9a31cbbf11a88ce
10,911
from typing import OrderedDict def _build_colormap(data, hue, palette, order): """Builds a colormap.""" if hue is None: color_map = {} else: if palette is None: palette = sns.color_palette() if order is None: order = data[hue].unique() color_map =...
82294634a1295fc68e5d3afb05fa00d83dfdc6ea
10,912
def f_is_oword(*args): """ f_is_oword(F, arg2) -> bool See 'is_oword()' @param F (C++: flags_t) """ return _ida_bytes.f_is_oword(*args)
a6d75a65b527ebdd029a5d3e65a756bcbb86561a
10,913
def aggregate_CSV_files(data_path): """ Aggregate the data in CSV files, specified in the config file, into a single pandas DataFrame object. """ merge_queue = [] for path in data_path: data_df = pd.read_csv(path, na_values = ['.']); data_df.index = pd.to_datetime(data_df['DATE'], forma...
281ca2a5e84e2dfbb2c2269083d0d2be5654fb75
10,914
def dR2(angle: np_float) -> np.ndarray: """Derivative of a rotation matrix around the second axis with respect to the rotation angle Args: angle: Scalar, list or numpy array of angles in radians. Returns: Numpy array: Rotation matrix or array of rotation matrices. """ zero = _ze...
5080c78c46505ed9e155fb76ae4a9be3b6e5d685
10,915
import os def build_symm_filter_commands(chainfiles, chromref, outpath, cmd, jobcall): """ :return: """ chromfiles = collect_full_paths(chromref, '*.tsv') assert chromfiles, 'No chromosome files found at location: {}'.format(chromref) assm_chrom = dict() for chrf in chromfiles: ass...
b76b978d805802dc46666ad69efe5e7c89bea6b6
10,916
def clear_predecessor(n): """ Sets n's predecessor to None :param n: node on which to call clear_predecessor :return: string of response """ def clear(node): node.predecessor = None n.event_queue.put(clear) resp_header = {"status": STATUS_OK} return utils.create_request(resp...
e5c071572799c8df6b629d0bb1cbde4d106a4e95
10,917
import os def resource_file(): """ Create an empty resource file :return: """ def _resource_file(dirname, filename): filepath = os.path.join(dirname, filename) open(filepath, 'a').close() return filepath return _resource_file
044b8561bed7660e74b02f359bceb55604431cb6
10,918
def get_local_variable_influence(model, form_data): """ """ row = format_data_to_row(form_data) model_obj = read_model(model.path, model.file_type) df = load_dataset_sample(model.dataset, nrows=50) df = df[model.dataset.model_columns] explainer = load_model_explainer_from_obj(model_obj, ...
403c2e89937a7b8bfbeb1ce44d49147fe9c35ddc
10,919
def submit_experiment(body, **kwargs): """Submit an experiment :param body: experiment payload :type body: dict | bytes :rtype: StatusSerializer """ serializer = ExperimentSerializer.from_dict(body) check_experiment_permission(serializer, kwargs["token_info"]) stub = get_experiments_s...
21b91876f1d9ffa4b55c296a2e1dc9a2c66e1026
10,920
def obj_assert_check(cls): """ The body of the assert check for an accessor We allow all versions of add/delete/modify to use the same accessors """ if cls in ["of_flow_modify", "of_flow_modify_strict", "of_flow_delete", "of_flow_delete_strict", "of_flow_add"]: ...
4ebddebdd87c0bdb28e7687ec2b0da623507f89e
10,921
from typing import List import hashlib def ripemd160(data: List[int]) -> List[int]: """ :param data: :return: """ try: bytes_data = bytes(data) except TypeError: raise NativeContractException digest = hashlib.new("ripemd160", bytes_data).digest() padded = 12 * [0] + li...
bfa29479b6d2633c0075462f558f21562fc96a04
10,922
def has_duplicates(s:list) -> dict: """Returns True if any element appears more than once in a sequence.""" d = dict() for char in s: if char in d: return True d[char] = 1 return False
f702e53cded0c18a0e1b7cffb58bccbff3386bce
10,923
def get_from_chain(J, domain, nof_coefficients, ncap=10000, disc_type='sp_quad', interval_type='lin', mapping_type='lan_bath', permute=None, residual=True, low_memory=True, stable=False, get_trafo=False, force_sp=False, mp_dps=30, sort_by=None, **kwargs): """ Returns st...
d5cd09a088d4946015eb9556b0fed3ca5be55187
10,924
from typing import Type def factory(kernel_type, cuda_type=None, gpu_mode=None, *args, **kwargs): """Return an instance of a kernel corresponding to the requested kernel_type""" if cuda_type is None: cuda_type = default.dtype if gpu_mode is None: gpu_mode = default.gpu_mode # turn enu...
2d9bf5fb0fd45e367d31b76656dfc611912f7202
10,925
from typing import Dict from typing import Union def init_scaler( scaler_parameters: Dict, fit_data: np.ndarray, ) -> Union[MinMaxScaler, StandardScaler, RobustScaler]: """Initialize and return scaler. Args: scaler_parameters: Parameters of scaler. fit_data: Data to be fit. ...
18f15e8e6bebb32ad659636f46ee2e5f54ccc69d
10,926
def get_dynamic_resource(previous_length: str): """Get the job with job_name. Returns: None. """ name_to_node_usage = redis_controller.get_resource_usage( previous_length=int(previous_length) ) return name_to_node_usage
05efd928f66b8237e39bd04df2482d8b24259700
10,927
def _margo_bin(exe=""): """Returns the path of the margo executable. """ return gs.home_path("bin", exe or INSTALL_EXE)
a540357e84411ec84820163966440d75ae142d8b
10,928
def csl_density(basis, mini_cell, plane): """ returns the CSL density of a given plane and its d_spacing. """ plane = np.array(plane) c = csl_vec(basis, mini_cell) h = np.dot(c.T, plane) h = smallest_integer(h)[0] h = common_divisor(h)[0] g = np.linalg.inv(np.dot(c.T, c)) h_norm ...
852ba976f1bfc9b1fa30ba660f8b660e023bed94
10,929
def mw_Av(): """Build the A_V attenuation by the MW towards M31.""" curve = SF11ExtinctionCurve() ratio = curve['Landolt V'] # A_V / E(B-V) from T6 of SF2011 return ratio * 0.07
ff53a5c302945ab6020a3734950bc8449c522faa
10,930
import os def load_model(model_uri): """ Load an H2O model from a local file (if ``run_id`` is ``None``) or a run. This function expects there is an H2O instance initialised with ``h2o.init``. :param model_uri: The location, in URI format, of the MLflow model. For example: - ``...
1363bd19fa3744de84a0b0f6b451ad8eba742808
10,931
def load_data(filenames): """Load a single file or sequence of files using skimage.io""" filenames = [filenames, ] if isinstance(filenames, str) else filenames loadfunc = tifffile.imread if all(f.lower().endswith("tif") for f in filenames) else skio.imread if len(fi...
be9c451c5aa3469a2bcaceb2fb6ab8ab09195794
10,932
def GetInverseMatrix(matrix): """ :param matrix: the matrix which will get its inverse matrix :return: the inverse matrix(two dimensions only) """ matrix[0, 0], matrix[1, 1] = -matrix[1, 1], -matrix[0, 0] matrix = matrix / -(matrix[0, 0] * matrix[1, 1] - matrix[0, 1] * matrix[1, 0]) return m...
c4fdba364cc6b73a3b72a40f980a0fa402a1968f
10,933
import re def petsc_memory_stats(log): """Return the memory stats section of PETSc's -log_view output as a dictionary.""" # first search for the 'Memory usage' header, then match anything that follows # after the first line starting with --- up until the first line starting with ===== # re.DOTALL make...
c7756190ae2a4c25f5cf7a16764ace06da95b0f6
10,934
import torch def track2result(bboxes, labels, ids, num_classes): """Convert tracking results to a list of numpy arrays. Args: bboxes (torch.Tensor | np.ndarray): shape (n, 5) labels (torch.Tensor | np.ndarray): shape (n, ) ids (torch.Tensor | np.ndarray): shape (n, ) num_class...
ae2dda3abd32d8b6c3dd0fc0c8c5f65268a8e747
10,935
def build_result_dataframe(gh, pred, df): """ Construct a datarame that contain the prediction. :param gh: the geohas6 code of the prediction :param pred: numpy array of prediction :param df: the dataframe used for prediction :returns: prediction dataframe :rtype: pandas.core.frame.DataFrame ...
0b1523aa42c7a31aa286522ee81ec93690dfbf0c
10,936
from typing import Sequence from pathlib import Path import sys from contextlib import suppress def find_module(module_name: str, search_paths: Sequence[str | Path] | None = None) -> Path: # noqa: WPS231 """Find a module in a given list of paths or in `sys.path`. Parameters: module_name: The module ...
4d066fa6e528b1d3ae36d789b8cc9df7a38bf5f0
10,937
def day_1_puzzle_1_solution() -> int: """Use this function to return the total fuel requirements for all of the modules. This function is used for reading the text file of puzzle data and returning the total amount of fuel that is required for the modules. :return: the total fuel requirement. """ ...
625497ea7e7619b1e84abc9eb8dfdfd1076af392
10,938
def is_description_style(style): """ True if this is a style used for Relationships paragraph text """ return is_style(style, 'Normal') or is_style(style, 'Note')
0e96d9977f7d18e8253a87e3af59f31e8326f4ae
10,939
def inject_content_head_last(html, content): """ 将文本内容插入到head的尾部 :type html: str :type content: str :rtype: str """ head_end_pos = html.find("</head") # 找到 </head> 标签结束的位置 if head_end_pos == -1: # 如果没有 </head> 就不进行插入 return html return html[:head_end_pos] + conten...
61792831f859a966e8cfa01ca56a6b9be10ede4d
10,940
from typing import Union def download(ticker: str, start: Union[pd.Timestamp, str] = None, end: Union[pd.Timestamp, str] = None, frequency: str = "day") -> pd.DataFrame: """ Download market data from yahoo finance using the yfinance library from ticker `ticker` from `sta...
733d5ac8244ca6fdbcb73a11585067c90dd7210b
10,941
import types import os import re def sortUrlList(urlList): """Return ordered url list (localFile, DAP, HTTP, FTP).""" #localList = [url for url in urlList if os.path.exists(url)] #dodsList = [url for url in urlList if sciflo.utils.isDODS(url)] #httpList = [url for url in urlList if not sciflo.utils.is...
839a4e451c2052eaf3b2c5df6499399cbd693f4b
10,942
import sys import os from datetime import datetime def main(args): """ Main method """ # await/async requires python >= 3.5 if sys.version_info.major < 3 and sys.version_info.minor < 5: print("Error, language features require the latest python version.") print("Please install python 3...
3dc81fdb1e69ae1eadf5ca0be3a577d6cc37b866
10,943
def _ps_run_one_reset_kwargs(G, reset_kwargs: tuple, eval: bool): """ Sample one rollout with given init state and domain parameters, passed as a tuple for simplicity at the other end. This function is used when a minimum number of rollouts was given. """ if len(reset_kwargs) != 2: raise pyr...
95e23ad682d6afc3014bfa7932b00a955cc5bd3d
10,944
from exopy_pulses.testing.context import TestContext from typing import OrderedDict def test_compiling_a_sequence_not_compiling2(workspace, root, monkeypatch, exopy_qtbot, dialog_sleep): """Test compiling a sequence that can be evaluated but not compiled. """ ...
eec3ee453346a75398da230e59013bfaa47f8b23
10,945
import warnings def deprecated(message, exception=PendingDeprecationWarning): """Throw a warning when a function/method will be soon deprecated Supports passing a ``message`` and an ``exception`` class (uses ``PendingDeprecationWarning`` by default). This is useful if you want to alternatively pass a...
86ccfeb53048d130a7fe35a0609dc5e95440da23
10,946
import subprocess def check(config, content, filename): """ Run flake8 with the given ``config`` against the passed file. Returns a ``list`` of :py:class:`flake.Violation`. """ with environment(config, content, filename) as env: out = subprocess.check_output(['flake8', ...
2d75348b489cef9fc60e3d76ce94200e7542a0d2
10,947
def x_dot(y): """x_dot(y) Describes the differential equation for position as given in CW 12. """ return y
7fa01584b09c6e83e28ddf63b300323fdcb7fa0b
10,948
def get_comp_depends(comp_info, comps): """ Get comp depends from comp index """ depends = [] for comp in comps: if comp in comp_info: depends += comp_info[comp]["dependencies"] if depends: depends += get_comp_depends(comp_info, depends) return list(set(depends))
79a8b51e329cf9be414391508cc0ecbe76ff0707
10,949
def get_naiveb_model(x_train: pd.DataFrame, y_train: pd.Series) -> GaussianNB: """ Trains and returns a naive Bayes model Data must all be on the same scale in order to use naive Bayes """ gnb = GaussianNB(priors=None) gnb.fit(x_train, y_train) return gnb
f1b93acf80ee88f1eb0be7a61aa0d9ac94248966
10,950
def updateDF(df, fields, id_patient): """ fields is a dictionary of column names and values. The function updates the row of id_patient with the values in fields. """ for key in fields: df.loc[df["id_patient"] == id_patient, key] = fields[key][0] return df
5ced64eca8d8736836f82dacd1750cb8ac612989
10,951
def gcd(num1: int, num2: int) -> int: """Computes the greatest common divisor of integers a and b using Euclid's Algorithm. """ while num2 != 0: num1, num2 = num2, num1 % num2 return num1
c53ff5be770570278f497d7ce2a2146a3ac3d9da
10,952
import tempfile import json import os def application(request): """ To use this application, the user must send a POST request with base64 or form encoded encoded HTML content and the wkhtmltopdf Options in request data, with keys 'base64_html' and 'options'. The application will return a response...
69fac274a111d9e9c9dff446dacc0cf2520468c9
10,953
import json async def check_user_name(request): """Check if a user exists with provided username.""" log_request(request) conn = await create_connection() response = await users_query.users_search_duplicate( conn, request.args.get("username") ) conn.close() return json({"exists": b...
72ff533a02e6377b78bfbfc631e87acc5fe59779
10,954
def azip_longest(*aiterables, fillvalue=None): """async version of izip_longest with parallel iteration""" return _azip(*aiterables, fillvalue=fillvalue, stop_any=False)
22f4ef6b4f1294ccca71a59337913a64e89a9e62
10,955
def drop_table(name, con): """ drop table from database Parameters ---------- name : string, name of SQL table con : sqlalchemy.engine.Engine or sqlite3.Connection Returns ------- True Examples -------- >>> import pandas as pd >>> from sqlalchemy import create_engi...
c86ad4e71c24bdfaba924171a21e74096ab8c11e
10,956
def class_info_interface(**class_name): """ Set Class_Name, Class_Index, and DNN Model \nclass_name (kwargs) : Input Class Name with list type, if want to set class number, add tuple parameters like 'class_info_interface(class_name = [list], class_number = [list])' \nclass_number : Default the n...
a9da1515192cf67bfe326ab90ff7c12a32106304
10,957
def uint8(value): """ Create an SPL ``uint8`` value. Returns: Expression: Expression representing the value. """ return streamsx.spl.op.Expression('UINT8', int(value))
7e8562b4ec82bbb932c92a9af4cfd06224b6596d
10,958
import re def print_table(log_results, platform_width = 0, build_failures_width = 0, test_failures_width = 0, successful_width = 0, space_char = " ", list_separator = DEFAULT_LIST_SEPARATOR): """Print out a table in the requested format (text o...
e12ada2d86f3dcecef6292b5c052094599abda4b
10,959
def is_valid(filepath, digest, hashAlgo='md5'): """Verify the integrity of a file against a hash value.""" assert(isinstance(digest, str)) res = calculate(filepath, hashAlgo) LOG.debug('Calculated digest: '+res) LOG.debug(' Original digest: '+digest) return res is not None and res == digest
bb83d8b8a3a0bed7e061009a04b30c2eb361abd7
10,960
def align_reconstruction_to_pdr(reconstruction, data): """ leveling and scaling the reconstructions to pdr """ if reconstruction.alignment.aligned: return reconstruction if not data.pdr_shots_exist(): return reconstruction pdr_shots_dict = data.load_pdr_shots() X, Xp = [],...
c3f5afd859a1275863cce6e2ccf3cd9523b94186
10,961
def checkLengthSmaller(op, graph, frm, to): """ Confirm resulting video has less frames that source. :param op: :param graph: :param frm: :param to: :return: @type op: Operation @type graph: ImageGraph @type frm: str @type to: str ...
a2101371e4f8af0ebaab1ece5d7cc31f4a277aca
10,962
import logging def enable_log(fmt='[%(asctime)s] [%(process)5s] %(levelname)s %(module)s %(name)s %(message)s', enable_color=True, filename=None): """ Clears all log handlers, and adds color handler and/or file handlers :param fmt: logging format string :param enable_color: True to ena...
3e018012e7cff555d86e93396485c9644dfb32ae
10,963
def build_con_and_ds(dataset: str): """ Builds test connector and test datasource for testing with API key Leave this function in if ever want to run tests without skipping due to there being no Bearer tokens How to use: Replace build_ds function with this one in test_aircall file Be sure t...
7fa19e15e0a38c22f575d6509e3156a874b8ea60
10,964
def _get_search_str_regex_main_body(join_with, last_date): """Returns something like: (t1[0-5]\d\d\d\d|t160[0-2]\d\d|t16030\d|t16031[0-3])""" todo_date = _get_todo_date(last_date + timedelta(1)) # yrs = _make_last_digit_all_values_less_last_digit(todo_date[:3]) # search_substrs = [yrs[-1]] #Only go ...
85a65df09ad5e35f71500ff30345c83f745564ea
10,965
def is_palindrome_recursive(text, left=None, right=None): """time complexity: O(1) because you are checking which conditional will run, which does not involve any loops text = str left = int right = int""" if len(text) == 0: return True given = get_letters(text) if left is None and r...
d7bf4ab6e7f43d6418cde3485f94dc2d83e40180
10,966
import operator import numpy def flip(m, axis=None): """Reverses the order of elements in an array along the given axis. The shape of the array is preserved, but the elements are reordered. Parameters ---------- m : array_like Input array. axis : None or int or tuple of ints, optiona...
495b75a548d94bc9dbc9827678b08282efb104d8
10,967
def radius_of_gyration(pos): """ Radius of gyration of a group of positions. Does not account for periodic boundaries. """ com = np.mean(pos, axis = 0) delta = pos - com rgv = np.sqrt(np.sum(delta**2, axis = 0) / len(pos)) return np.linalg.norm(rgv)
a12450cf63768bf9a238bef11a3360ce49e3092f
10,968
def get_metadata_for_list(commit_range, git_dir=None, count=None, series=None, allow_overwrite=False): """Reads out patch series metadata from the commits This does a 'git log' on the relevant commits and pulls out the tags we are interested in. Args: commit_range (st...
0134a836f28bf97e5196c63f80f5b07d372cc5d4
10,969
def side_seperator(lsep,rsep): """ To have a custom side lined formatter. A side-lined formatter is: `[DATE] SEP "L_SEP" EVENT "R_SEP" LOG` `loggy.side_seperator(lsep="||",rsep="||") # Default vals` """ fmt['ls']=lsep fmt['rs']=rsep return fmt
803519e93cef7342e9f951090823fc536f37839f
10,970
def _semi_implicit_euler(ode_fun, jac_fun, y_olds, t_old, f_old,dt, args, solver_parameters, J00, I): """ Calculate solution at t_old+dt using the semi-implicit Euler method. Based on Section IV.9.25 of Ref II. """ y_older, y_old = y_olds je_tot = 0 if(f_old is None)...
5db2c6b520ce401b986a2bb7468cd5cdac7413a7
10,971
from typing import OrderedDict def make_sequential(layer_configs, input): """Makes sequential layers automatically. Arguments: layer_configs: An OrderedDict that contains the configurations of a sequence of layers. The key is the layer_name while the value is a dict contains hyper-param...
662c8787115c7d6d3e499a89aa7e8c301b9e5e4b
10,972
import random def Pol_Dyn_ExploreWithNUTS(resultsList,totalSimDays=1000,numDaysRemain=1000,\ totalBudget=1000,numBudgetRemain=1000,policyParamList=[0],startDay=0): """ Grab intermediate and end node distribtuions via NUTS. Identify intermediate node sample variances. Pick an in...
a96638a7f2816a42069cfa714822e728ee7e325f
10,973
import numpy def calc_cos_t(hb_ratio, d, theta_s_i, theta_v_i, relative_azimuth): """Calculate t cossine. Args: hb_ratio (int): h/b. d (numpy array): d. theta_s_i (numpy array): theta_s_i. theta_v_i (numpy array): theta_v_i. relative_azimuth (numpy array): relative_azi...
5ac37f2aa8994b75bb0c71d9f54616ff041a5ff6
10,974
from typing import Callable def guild_only() -> Callable: """A decorator that limits the usage of a slash command to guild contexts. The command won't be able to be used in private message channels. Example --------- .. code-block:: python3 from discord import guild_only @bot.s...
d8ca993dd0ea71791458edd3c3bcec0551262552
10,975
import re def truncate(text, words=25): """Remove tags and truncate text to the specified number of words.""" return " ".join(re.sub("(?s)<.*?>", " ", text).split()[:words])
18d994a52dc5549aabb7cc8f33d5755be5392208
10,976
from datetime import datetime def _run_query_create_log(query, client, destination_table=None): """ Runs BigQuery queryjob :param query: Query to run as a string :param client: BigQuery client object :return: QueryJob object """ # Job config job_config = bigquery.QueryJobConfig() ...
265361c150f654bc8826cda096d85b4ae2911317
10,977
def read_disparity_gt(filename: str) -> np.ndarray: """ reads the disparity files used for training/testing. :param filename: name of the file. :return: data points. """ points = [] with open(filename, 'r') as file: for line in file: line = line.split(' ') fra...
bad5ad6698d58e5173709cf866fb027367daa8b1
10,978
def purchase_index(request): """displays users purchase history""" login_id = request.user.id context = {'histories': Purchase_history.objects.all().filter(acc_id=login_id).order_by('-date')} # get users purchase history return render(request, 'profile/histories/purchase_history.html', context)
d353e839ff08adfeebaa28a708d36df4d21a7ea8
10,979
import array def solve_EEC(self): """Compute the parameters dict for the equivalent electrical circuit cf "Advanced Electrical Drives, analysis, modeling, control" Rik de doncker, Duco W.J. Pulle, Andre Veltman, Springer edition <--- ---> -----R-----wsL...
ad862028447acd038e76ba95960b089985bffe9b
10,980
def is_active(seat): """Return True if seat is empty. If occupied return False. """ active = seat_map.get(seat, ".") return True if active == "#" else False
098c4ccf9d4e9bbadb853d77a100eabd4e5142bf
10,981
from typing import List import tqdm def calibrate_intensity_to_powder(peak_intensity: dict, powder_peak_intensity: dict, powder_peak_label: List[str], image_numbers: List[int], powder_start: int = 1): """Calibrate peak intensity values to intensity measurements taken from a 'rand...
8019eec6c63152ee25bacc9dcf8fa723407f8107
10,982
import json def examine(path): """ Look for forbidden tasks in a job-output.json file path """ data = json.load(open(path)) to_fix = False for playbook in data: if playbook['trusted']: continue for play in playbook['plays']: for task in play['tasks']: ...
e441fc58bbfc4547bbdff451d6d06ba952e5a1ba
10,983
import subprocess import sys def determine_disjuct_modules_alternative(src_rep): """ Potentially get rid of determine_added_modules and get_modules_lst() """ findimports_output = subprocess.check_output(['findimports', src_rep]) findimports_output = findimports_output.decode('utf-8').splitlines() custom_modul...
be3e0f1e4edf84bdeb8ea5b2a0117d9853581884
10,984
def config_ask(default_message = True, config_args = config_variables): """Formats user command line input for configuration details""" if default_message: print("Enter configuration parameters for the following variables... ") config_dictionary = dict() for v in config_ar...
277d26ae67baf14ee6b16547bb72c029ab0bc610
10,985
import sys def parseAndRun(args): """interface used by Main program and py.test (arelle_test.py) """ try: hasWebServer = True except ImportError: hasWebServer = False cntlr = CntlrCmdLine() # need controller for plug ins to be loaded usage = "usage: %prog [options]" p...
d7cf011ee59aea93659594411051e71ae4dd76e0
10,986
def build_A(N): """ Build A based on the defined problem. Args: N -- (int) as defined above Returns: NumPy ndarray - A """ A = np.hstack( (np.eye(N), np.negative(np.eye(N))) ) A = np.vstack( (A, np.negative(np.hstack( (np.eye(N), np.eye(N)) ))) ) A = np.vstack( (A, np.h...
eecb541e44cc177e594f38d9a7c1930f2d4f0c40
10,987
def gms_change_est2(T_cont, T_pert, q_cont, precip, level, lat, lev_sfc=925., gamma=1.): """ Gross moist stability change estimate. Near surface MSE difference between ITCZ and local latitude, neglecting geopotential term and applying a thermodynamic scaling for the moisture ter...
991721a2dae52269dec276fa384d568b1d58672f
10,988
def solid_polygon_info_(base_sides, printed=False): """Get information about a solid polygon from its side count.""" # Example: A rectangular solid (Each base has four sides) is made up of # 12 edges, 8 vertices, 6 faces, and 12 triangles. edges = base_sides * 3 vertices = base_sides * 2 faces =...
a16bae9b82fd7a89332d5403359c2aa1eddf6cb4
10,989
def read(id=None): """ This function responds to a request for /api/people with the complete lists of people :return: sorted list of people """ # Create the list of people from our data with client() as mcl: # Database ppldb = mcl.ppldb # collection (kind of...
92490bf44d4929709c95833f32c92236fe265fd0
10,990
def load_prism_theme(): """Loads a PrismJS theme from settings.""" theme = get_theme() if theme: script = ( f"""<link href="{PRISM_PREFIX}{PRISM_VERSION}/themes/prism-{theme}""" """.min.css" rel="stylesheet">""" ) return mark_safe(script) return ""
565e9fdb7b201bf6c34b3b2d198aa18f22070145
10,991
def get_root_name(depth): """ Returns the Rootname. """ return Alphabet.get_null_character() * depth
1514bcd0ef9c6a2a4051772d8eeee34f3f7197a7
10,992
import hashlib def md5(fname): """ Cacualte the MD5 hash of the file given as input. Returns the hash value of the input file. """ hash_md5 = hashlib.md5() with open(fname, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_md5.update(chunk) return hash_md5.hexdigest()
0c238810f1682f86e8a31982135c37017df4d6fd
10,993
def date2num(date_axis, units, calendar): """ A wrapper from ``netCDF4.date2num`` able to handle "years since" and "months since" units. If time units are not "years since" or "months since" calls usual ``netcdftime.date2num``. :param numpy.array date_axis: The date axis following units :param str ...
b435697098c58d1045f7e31eefb23cac201bfe0c
10,994
import gettext def _(txt): """ Custom gettext translation function that uses the CurlyTx domain """ t = gettext.dgettext("CurlyTx", txt) if t == txt: #print "[CurlyTx] fallback to default translation for", txt t = gettext.gettext(txt) return t
839c36184eabde641a40d7b7ad55d4695574dafb
10,995
import html def output_node(ctx, difference, path, indentstr, indentnum): """Returns a tuple (parent, continuation) where - parent is a PartialString representing the body of the node, including its comments, visuals, unified_diff and headers for its children - but not the bodies of the children ...
dbe4c5f806457d4308954fb9e13bf01419b4e1a1
10,996
def split_tree_into_feature_groups(tree: TreeObsForRailEnv.Node, max_tree_depth: int) -> ( np.ndarray, np.ndarray, np.ndarray): """ This function splits the tree into three difference arrays of values """ data, distance, agent_data = _split_node_into_feature_groups(tree) for direction in TreeObsFor...
87352b0d500d178b32d4697ae49736133c7fd6a1
10,997
def _generate_training_batch(ground_truth_data, representation_function, batch_size, num_points, random_state): """Sample a set of training samples based on a batch of ground-truth data. Args: ground_truth_data: GroundTruthData to be sampled from. representation_function: Functi...
944ed5845385089063f0e1558a9a9aedb4aa6d26
10,998
def get_mnist_loaders(data_dir, b_sz, shuffle=True): """Helper function that deserializes MNIST data and returns the relevant data loaders. params: data_dir: string - root directory where the data will be saved b_sz: integer - the batch size shuffle: boolean - whether...
7149dbe78ceb321c0afea52c20ae927ce154a8f6
10,999