content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def reverse_transcribe(seq: str) -> str: """ transcribes DNA to RNA then reverses the sequence """ t = transcribe(seq) return(t[::-1])
49180931a7209eef1195b8a529437ce393dc3cb1
68,774
def normalize_user_link(url: str, user_id: int) -> str: """Strip off end e.g. 123/user_name""" return f"{url.split(str(user_id))[0]}{user_id}"
d891425c3765286b2d16dc1541100d1aed69f31b
68,775
def format_info_for_high_bias_fold(sess, layer_pairs, consecutive_layer_list, scaling_factor_list): """ Helper function that formats data from cross layer scaling and bn fold for usage by high bias fold. :param sess: tf.compat.v1.Session type :param layer_pairs: info obtained after batchnorm fold. ...
c64cf834c13e89ea2529cede17d39a0e5338026b
68,776
def train_test_split(X, y, test_size=0.25, shuffle=True, random_state=None): """ split features X and target y into train and test sets inputs ------ X: a pandas dataframe with at least 3 rows y: a pandas dataframe with at least 3 rows and only one column test_size: a float number between 0...
1dcf9dac7e3a9d9f62f97ef7cf8bac834576ded5
68,778
def vector_POD(inner_prod, t_train, r): """ Performs the vector POD, and scales the resulting modes to lie on the unit ball. Also returns the names of the temporal modes which will be modeled. Parameters ---------- inner_prod: 2D numpy array of floats (M = number of time samples, M = nu...
5f999ad84d052754a23a38fdcb57929c1a31c5ff
68,779
import functools def etag_headers(method): """ A decorator that adds `ETag` and `Last-Modified` headers to `.get` method responses if not already present. Intended to be use with Timestamped models (or any object with a modified_time field). """ @functools.wraps(method) def add_etag_headers_t...
10f50aff637804870b5268cd2ce92c4c042faa6d
68,780
import re def intcomma(value): """ Converts an integer to a string containing commas every three digits. For example, 3000 becomes '3,000' and 45000 becomes '45,000'. """ orig = force_unicode(value) new = re.sub("^(-?\d+)(\d{3})", '\g<1>,\g<2>', orig) if orig == new: return new ...
89df38e262d8b7d4d729820a8d558443b297b244
68,781
def remez_fir(data, freqmin, freqmax, df): """ The minimax optimal bandpass using Remez algorithm. (experimental) .. warning:: This is experimental code. Use with caution! :type data: numpy.ndarray :param data: Data to filter. :param freqmin: Low corner frequency. :param freqmax: High corn...
3149d7e7f5cb15c60987716f326b00337ad277c2
68,782
def get_image(driver, image_name): """ Return a ``NodeImage`` corresponding to a given name of size. :param driver: The libcloud driver to query for images. """ try: return [s for s in driver.list_images() if s.name == image_name][0] except IndexError: raise ValueError("Unknown ...
be5a246a67fafe18de368a9bdbdf3291542b0cc4
68,783
def fchr(char): """ Print a fancy character :param char: the shorthand character key :type char: str :return: a fancy character :rtype: str """ return { 'PP': chr(10003), 'FF': chr(10005), 'SK': chr(10073), '>>': chr(12299) }.get(char, '...
d953a66546bc99cc44958d84b426d011089c8f97
68,784
import cv2 import requests import urllib3 def download_url_img(url): """ 下载url图像 """ urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) try: response = requests.get(url, verify=False) except Exception as e: print(str(e)) return False, [] if respon...
86c23555a55b759db2d5fac32665d0c92bcb5047
68,786
def hTest_qubitEfficient_alternative3k_circ(n, k, prep_state): """ Implements a qubit efficient Hadamard test for Tr(rho_A^n) using 3 registers and 1 ancilla This implementation alternates which registers it resets. In our noisy simulations, it actually performs worse than the other 3k circuit. `k` is such that ...
afa2a2fc2f0e6d5c280ba468be2fadc34d000ad6
68,787
def extrinsic_euler_yzx_from_active_matrix(R, strict_check=True): """Compute extrinsic yzx Cardan angles from active rotation matrix. Parameters ---------- R : array-like, shape (3, 3) Rotation matrix strict_check : bool, optional (default: True) Raise a ValueError if the rotation ...
4468adcd59116f87b42f65764f209d6947cd29fb
68,788
def load_data(csv): """ The method reads train and test data from their dataset files. Then, it splits train data into features and labels. Parameters ---------- train_file: directory of the file in which train data set is located test_file: directory of the file in which test data set is l...
18d69855bd118c2f30f42ca64e964b21250011d7
68,789
import tqdm def make_feat_mappings(data, feat_extractor, inv_vocab): """Generate the mapping dictionary for features. Args: data: list(tuple) feat_extractor: feature extractor inv_vocab: inverse vocabulary. int->str """ feat_mapping = dict() for item in tqdm(data): ...
d523c7a360f4ae5b90676f1d9bd39690fc55a4aa
68,790
def is_variable(x, exclusive=False): """Determines whether the input is a variable or not. Parameters ---------- x An ivy array. exclusive Whether to check if the data type is exclusively a variable, rather than an array. For frameworks like JAX that do not have exclusive va...
39fa0ae87d3dce411ddf278edcc32d890e6d076b
68,792
import click def get_all_triggers(config, category_id=None, active_only=False): """ Get all pages of triggers from Zendesk. :param config: context config :param category_id: only get triggers from this category :param active: flag to only include active triggers :return: """ url = f"ht...
ae576a979bc445bd9c03695be47e4e531aef755c
68,793
def create_app(config_filename): """Configure the app w.r.t. Flask security, databases, loggers.""" config = read_config(config_filename) app = create_app_without_blueprints(config) register_config(app, config) register_extensions(app, config) register_blueprints(app, config) register_routes...
ea3c1fc1c5d0c1ed9f71423b1fbf4c2f591ad120
68,794
def given_power(n, ef_power): """ Calculate and return the value of given power using given values of the params How to Use: Give arguments for efficiency and ef_power parameters *USE KEYWORD ARGUMENTS FOR EASY USE, OTHERWISE IT'LL BE HARD TO UNDERSTAND AND USE.' Parameters: ef...
9b60bd43b5c53611152ab7edc17d3150670cf08e
68,795
def editItem(item_id): """Modifies the item with the given id. Args: item_id: the id of the item which shall be modified """ categories = session.query(Category).all() item = session.query(Item).get(item_id) if request.method == 'GET': return render_template('edit_item.html', ...
c8f15ce6b366543ac3870e596f4586ba7b11abaa
68,797
def command_eval(expr: str): """Evaluates a given expression.""" # Command callbacks can return values which will be passed to the caller of `dispatch()` return eval(expr)
0664e4c3f6f0aad320642b000e4bbf242a5b219a
68,798
import torch def augment_data(train_X, train_Y): """Subsample the HD signal into 10 low resolution signals""" big_data_set = torch.Tensor(0,28,50) big_target = torch.Tensor(0) for i in range(10): shifted_data = train_X[:,:,i::10] big_data_set = torch.cat((big_data_set,shifted_data),0) ...
93f3135811449bf5167f0b150f115db31d8b0a67
68,799
def getScaledLocation(vf, normalizedLocation): """Answers the instance of self, corresponding to the normalized location. (-1, 0, 1) values for axes as e.g. [wght] and [wdth]. The optical size [opsz] is supposed to contain the font size, so it is not scaled. If [opsz] is not defined, then set it to def...
bbb9d031ce918122afaab0abfd43888f89cda777
68,800
from datetime import datetime def nice_ts(tsarg): """ prettify timestamp string with microseconds precision NOTE: timezones may not always work correctly """ ts, msec = map(int, tsarg.split(".")) d = datetime.datetime.fromtimestamp(ts) d = d.replace(microsecond=msec) return d.strftime(...
7925d46b3e46fb6df281e5bd1fe46af098437fb8
68,801
def into_interval(startnode, endnode, tolerance): """ Creates an interval that contains the two nodes with a certain tolerance """ min_x = min(startnode.x, endnode.x) - tolerance min_y = min(startnode.y, endnode.y) - tolerance max_x = max(startnode.x, endnode.x) + tolerance max_y = max(startnode.y, ...
5a118ccd91f5fc91d27b30ad5e673c388d02c2a5
68,802
def get_scale(tone): """ Find the scale associated to a tone, to make sure we write harmonically coherent tones (eg. in A scale, we prefer to write C# over Db) Args: tone: the tone to get the scale from (eg. 'A' to get an A scale) Returns: The scale associated to the tone """ ...
7196f81f96c114d08d9b352160d0556d3cbcb63b
68,803
def accounting(Eddy, old_ind, centlon, centlat, eddy_radius_s, eddy_radius_e, amplitude, uavg, teke, rtime, new_eddy, first_record, contour_e=None, contour_s=None, uavg_profile=None, shape_error=None, cent_temp=None, cent_salt=None): """ Accounting for...
6f6cd845d30086d8cdbb12cc193d8e3d6974e069
68,804
def analyze_course_quality_by_cID(dict_cursor, cID, campus): """ First query the given course's eval data from database, then convert it into a DataFrame. """ course_quality_by_cID = Database.get_avg_course_eval_by_cID(dict_cursor, cID, campus) course_quality_by_cID_df = pd.DataFrame(list(cours...
aa6b4aa4458b210b538fb789bd4e2296b6fc5e61
68,805
from typing import Tuple from typing import List def getRingAttachedBondsDatabase(database: ndarray, MoleculeCol: int = 0, BondIdxCol: int = 3, aromaticOnly: bool = False) -> Tuple[List[int], ndarray, List[int], ndarray]: """ Retrieve a dataset contained bonds whose atoms are ...
238c0bc6db4ae7344b50fcc2df209b6c72fd7e98
68,806
def to_usd(my_price): """ Converts a numeric value to usd-formatted string, for printing and display purposes. Param: my_price (int or float) like 4000.444444 Example: to_usd(4000.444444) Returns: $4,000.44 """ return f"${my_price:,.2f}"
081ac7a3ff65f9769b33941130e6770d7c4dc68f
68,807
from typing import Union from typing import Tuple from typing import List def ensure_value( config: 'PipetteFusedSpec', name: Union[str, Tuple[str, ...]], mutable_config_list: List[str]): """ Pull value of config data from file. Shape can either be a dictionary with a value key -- ...
437af0dbc72034f55383affadfaeda106562ca25
68,808
import re import html def wordsw(bot: Bot, update: Update, user, args): """ Example usage: User A Hi User B [In reply to User A] /s/Hi/Bye OctoBot Hello, User A Did you mean: Bye """ try: msg = update.message txt = msg.text if msg.reply_to_...
12db6d7f885ee07935b0cb03cce0f6c5ad2f152d
68,809
import logging def pull_missing_emails( new_hams: pd.DataFrame, chromedriver_fname: str ) -> pd.DataFrame: """ Attempt to pull missing email addresses from QRZ. Parameters ---------- new_hams : pd.DataFrame A dataframe containing new ham callsigns and email addresses. chromedriver...
b31821be35fe407ac12584f697ce98fe3e7a024b
68,810
def schema_key(s_id: str) -> SchemaKey: """ Return schema key (namedtuple) convenience for schema identifier components. :param s_id: schema identifier :return: schema key (namedtuple) object """ s_key = s_id.split(":") s_key.pop(1) # take out indy-sdk schema marker: 2 marks indy-sdk sche...
316f484016d23a26ac26cf9d5700f6b5eb619833
68,813
import warnings def logreg_cv(X, y, num_folds, reg_param_vec, method, max_iter, tol, weightvec=None, random_state=42, reg_prec=4, ps_mode='fast'): """Routine to find the best fitting penalized Logistic Regression. User must provide, the X, y, number of folds, range of `lambda` parameter and...
37ba49029c23ab20d1ad531216a5699e1241a7a4
68,814
import builtins def where(*keys, **conditions): """Filter entries with the given keys meeting the given conditions. .. marble:: :alt: where ---a1--b2--c3--| [ where(b=2) ] -------b2------| .. marble:: :alt: where2 ---a1--b2--a3--| [ where(a) ...
748556699817f227375dbe777711e1b44c4cbda0
68,815
def delete_blank_lines(raw_file, start): """ Opens the file, checks that file has more lines than start, go through the file deleting the blank lines and return it. """ with open(raw_file, 'r', encoding='utf-8') as file: file_length = len(file.readlines()) clean_file = '' c =...
cd957f69a91403df6a15953648cae2933bd294f1
68,816
import requests def get_episode_data(cfg, episode_id): """ Requests episode information from Opencast. :param episode_id: Unique identifier for episode :param cfg: Opencast configuration :return: Tuple of episode title, parent seriesId and parent series title """ url = cfg['uri'] + "/api/...
41aa3053312827d7081776fcb3c414e358f0cc61
68,818
def get_inter_times(arrival_times): """Convert arrival times to interevent times.""" return arrival_times - np.concatenate([[0], arrival_times[:-1]])
bbe2306ad99612aa43db5ca79c253cca6e953d7b
68,819
def isempty(prt_r): """Test whether the parent of a missingness indicator is empty""" return len(prt_r) == 0
167e6cb0a63116c6157291a6ba225b14fbfebe11
68,820
def get_oembed_data(url, max_width=None, max_height=None, **params): """ Fetch the OEmbed object, return the response as dictionary. """ if max_width: params["maxwidth"] = max_width if max_height: params["maxheight"] = max_height registry = get_oembed_providers() return regi...
cf34e0c5f41ab619a2fb50c0f8630c90f4d63b50
68,821
def bold(msg: str): """Format to bold markdown text""" return f'**{msg}**'
0aec90a0e59003faf5497a7236d182e39721c131
68,822
def redraw_on_change(meth): """ Decorator. Sends redraw message if lantern state changes. :param meth: lantern method """ @wraps(meth) def _inner(obj, *args, **kwargs): old_state = obj.state meth(obj, *args, **kwargs) if old_state != obj.state: obj._send...
fc5e46424ce5164f4ad08ffbec76d53c5f343fe3
68,823
def nonce_recovery_from_repeated_nonce(): """Finds two messages signed with the same nonce k, recovers that nonce k and, from k, gets the private key x.""" # Parse the file with the signatures signatures = parse_signature_file() # Find two pairs of signatures that used the same k # This is easy to...
73a0e6b35a6c1e422f9ebffbdc6d9995dd73363c
68,824
def time_sequence_decorator(func): """ This decorator is to convert input time into datetime.datetime type :param func: :return: """ def wrapper(*args): time_sequence = args[0] if not time_sequence: return sanitized_time_sequence = convert_to_datetime(time_...
5fa38c49329fa1e2bfc325e280ab5df0fa11c852
68,825
import csv def read_csv(filename): """Read csv file and separate time and voltage into respective lists :param filename: :return: """ csvfile = open(filename, "r") time = [] voltage = [] temp = csv.reader(csvfile, delimiter=",") for row in temp: time.append(row[0]) ...
0e846d2074092cc78cf334840e4346018e609e23
68,826
import pandas import scipy def compare_averages(filename): """ Performs a t-test on two sets of baseball data (left-handed and right-handed hitters). You will be given a csv file that has three columns. A player's name, handedness (L for lefthanded or R for righthanded) and their career batting ...
62c1e44b86fc89722537e08454f36e0f4dddacd4
68,827
import math def vortex_feldtkeller(beta, center, right_handed=True, polarity=+1): """ Returns a function f: (x,y,z) -> m representing a vortex magnetisation pattern where the vortex lies in the x/y-plane (i.e. the magnetisation is constant along the z-direction), the vortex core is centered around...
4714dcdfb2b96413562a6f531be944963a3a3b2f
68,828
def _jupyter_nbextension_paths(): """Used by 'jupyter nbextension' command to install frontend extension""" return [dict( section='notebook', # the path is relative to the `my_fancy_module` directory src='static', # directory in the `nbextension/` namespace dest='sparkmon...
0b6d7606b95023c44368ed9f3f2a4387862b07e2
68,829
def logsigmoid(x): """ calc logsigmoid """ return -tf.nn.softplus(-x)
c2ebf9ef3d49c1f5ea78cb85c9bf404392d687ae
68,830
def der_overlap_element(a,bfi, bfj): """ finds the derivative of the overlap integral with respect to the atomic coordinate of atom "a". Note there are four possible cases for evaluating this integral: 1. Neither of the basis functions depend on the position of atom a ie. they are centere...
89da8b49afe5ef1d3f69e1facc2baf44dd3633c7
68,831
def GetFilter(thisalgorithm, dimension, pixelType): """ Get the filter object - the main algorithm """ if thisalgorithm.GetOutputType(): if thisalgorithm.GetUseRescaler(): filter = eval ( thisalgorithm.GetName() + READER_PIXELTYPE + dimension + READER_PIXELTYPE + dimension + "_New()" ) else: filter = e...
47c34520fc4390925bcd1754c7960e4b447b6932
68,832
def dipole_moment(output_string): """ Reads the dipole moment """ pattern = app.LINESPACES.join([ 'Total Dipole Moment', ':', app.capturing(app.FLOAT), app.capturing(app.FLOAT), app.capturing(app.FLOAT)]) captures = apf.last_capture(pattern, output_string) ...
4576de110fa41b2ce5de2aef0aa3568f108e3475
68,833
def monoalphabetic( message: str, shift: int, alphabet: str = kbd(), space: str = None ) -> str: """ A simple implementation of the monoalphabetic cipher. By convention, use a: Positive integer shift if you want to encode Negative integer if you want to decode """ words = message...
1d4405815b6e31b9fd690dd141538b48886be614
68,836
def get_service(hass, config, discovery_info=None): """Get the Matrix notification service.""" return MatrixNotificationService( config[CONF_DEFAULT_ROOM], config[CONF_DEFAULT_MARKDOWN], config[CONF_DEFAULT_NOTICE], )
14fef6c5de93706eb7a091453b04ef4a822a7d72
68,837
def too_stable(seq, dev_thresh=5, perc_thresh=0.63, window=200): """If a sufficient proportion of <seq> is "stable" return True""" if window > len(seq): window=len(seq) mu_ = seq[:window-1] mu = np.concatenate([mu_, moving_average(seq, window)]) dev_arr = abs(mu-seq) dev_seq = dev_arr[n...
7adb93931392b4831d42e55871cb2ccf592493a2
68,839
def _annotation_url(): """Return a mock annotation_url() function. It just returns a hard-coded URL, enough to make the code that calls this function not crash. """ return mock.Mock(return_value='https://hypothes.is/a/id')
8efcf1ba3a48c6eabdc6cd8bef5db815c0efce04
68,840
def to_this_endpoint(func): """ Decorator; refines a handler so it's only called on requests targeting this endpoint. """ return _wrap_with_field_matcher(func, 'recipient', USBRequestRecipient.ENDPOINT, match_index=True)
5cedb91db18c979b04329d055631a1b133d3fbb4
68,841
def lattice_grain_transition_list(g=0.0, f=0.0, motion=1.0): """ Creates and returns a list of Transition() objects to represent state transitions for simple granular mechanics model. Parameters ---------- g : float (optional) Gravitational parameter. 1/g is the time taken for an initia...
923f523ab8c3efadf69e650368c6eed5287f39dd
68,842
import aiohttp import asyncio async def download_all_sites_truly_async(sites: list[str]) -> list[ClientResponse]: """ Truly async program that calls creates a bunch of coroutines that download data from urls and the uses gather to have the event loop run it asynchronously (and thus efficiently). Note ther...
79c3559278b69a32eb76e6797a6282b94a4e68ee
68,843
def setup_decision_engine(input): """ Decision Engine Setup Function Configures the decision engine. In training mode, the decision is always the one with the maximum probability. In Trump mode, different options can be used on how the decision engine functions. :param input: :return: """ if __m...
4c0eee3277c76667a6e324b169ed7f32644bcc2f
68,844
def findLocalMins(engMatrixRow): """ Take in a row of an energy matrix Shift row to left, center, and right Assign hight weights the leftmost and rightmost elements Calculate localMins of the left, center, and right rows Return local mins e.g. gradientRow = [1, 10, 0, 4, 3, 11, 0] l...
33a0f1a2710b5fce56ea0332a28d5639eb2d63d0
68,845
def prefix(request): """ This view's only purpose is to serve the template. """ return render(request, 'prefix.html')
5a66432272d590b568aed7823a5da7af9bfda845
68,846
def healthcheck_page(): """Respond to the heartbeat request from the Application Load Balancer""" return flask.render_template('healthcheck.html')
bc896aa95a14f87b646948d78b424782cc20fc52
68,847
import torch def loss_function(recon_x, x_repre, mu, log_sigma_sq): """Return Loss Arguments: x {tensor} -- indices of vocabulary p_x_i {tensor} -- probability after softmax layer mu {[type]} -- [description] log_sigma_sq {[type]} -- [description] Returns: [ty...
a8688100ab0e860d3c30aaddc4550ac4888ff199
68,848
import ctypes def prepare_string_result(): """Returns pair of byte pointer and size value for use as return parameters in a LIBRARY call """ return ( ctypes.POINTER(ctypes.c_uint8)(), ctypes.c_size_t(0), ctypes.c_size_t(0), )
1a3e910496766ffb3a64850b9a096d09857b8088
68,849
from typing import Union def action_index(action: Union[Action, np.ndarray]) -> Union[int, np.ndarray]: """Returns the actions index among all possible unit actions.""" return action >> ACTION_INDEX_START
65366bed0807c8cc5bb7692a2679f9ebf01ecf68
68,850
def cve_is_about_application(cpe_type): """ Determines whether CVE is about application. :param cpe_type: One of {'a', 'o', 'h'} = application, operating system, hardware :return: true if description is about application. """ return 'a' in cpe_type
28fba33b158623a14c367b9d7f4a46297d3aa824
68,851
from typing import Union from typing import Optional import re def convert_to_int(value: Union[str, float]) -> Optional[int]: """ Converts string and float input to int. Strips all non-numeric characters from strings. Parameters: value: (string/float) Input value Returns: ...
15036374ca499edfa58e2865d4f5fb70c3aecb40
68,852
def decode_event(abi: ABI, event_log: LogReceipt) -> EventData: """Helper function to unpack event data using a provided ABI Args: abi: The ABI of the contract, not the ABI of the event event_log: The raw event data Returns: The decoded event """ event_id = event_log["topic...
56bc77f591217f7d50d94f5a833d0bcbddd4dd42
68,853
from datetime import datetime def time_to_next(g: int, custom_time: list = None): """ When is the next class(timing)? :param g: Group id in database :param custom_time: Used for tests. Will overwrite current time, H:M :return: Formatted string with minutes till next class """...
9df3d0c9efde72474dfcbd5ae6aa05473899c781
68,854
def median(array): """Return the median of the array """ sa = sorted(array) salen=len(sa) return (salen%2==0)*((sa[salen/2-1]+sa[salen/2])/2)+(salen%2!=0)*sa[salen/2]
c95421eaac1527c5f1e2d8679743bcbebd03e5db
68,855
def prettify_xml_element(element): """Return a pretty-printed XML string for the Element. """ rough_string = ET.tostring(element) reparsed = minidom.parseString(rough_string) prettyxml = reparsed.documentElement.toprettyxml(indent=" ") return prettyxml.encode("utf-8")
e9e38e239005a9cbe11c7507fdbd3c0eda12f2e4
68,856
import re from typing import Any def expand_template(match: re.Match, template: Any) -> Any: """ Return the string obtained by doing backslash substitution on the template. :param match: The match object. :param template: The template. :return: The template replaced with backslash substitution sy...
82effee652443574f09d4ef136568a1a3e8f01b0
68,858
def construct_signals(cbg_df, signal_names): """Construct Census-block level signals. In its current form, we prepare the following signals in addition to those already available in raw form from Safegraph: - completely_home_prop, defined as: completely_home_device_count / device_count - ful...
d007f96ce2174811a623928f8e70cf561881545b
68,859
def calc_parallel_kinematics_bucket(epsilon): """calculates angles of parallel kinematic problem: Args: epsilon (float): angle of upper link Returns: [beta, delta]: angle (joint state) of links """ alpha = pi / 2 - xi + epsilon # inner angle s_tmp = sqrt( pow(l_bucke...
e62d986bf39696470c70278f24f4d2b9991bec64
68,860
def format_describe_str(desc, max_len=20): """Returns a formated list for the matplotlib table cellText argument. Each element of the list is like this : ['key ','value '] Number of space at the end of the value depends on len_max argument. Parameters ---------- desc: dict ...
9d172ea7afc7fbcb10b4fdc3e120cd955b9eb196
68,861
def parse_yaml(yaml_file): """ This is simple approach to parsing a yaml config that is only intended for this SDK as this only supports a very minimal subset of yaml options. """ with open(yaml_file) as f: data = {None: {}} current_key = None for line in f.readlines():...
6994f3180f7405bd83af791aa57a419bc07d9d27
68,862
from typing import Optional def get_role(role_id: Optional[int] = None, db: Session = Depends(get_db), _=Depends(RequirePermission([RequiredPolicy(action='*', resource='*')]))): """Get a list of roles or a specific role.""" if role_id: roles = UserCRUD.get_role(role_id=role_i...
de68df91452f667d04f17e5209f80946a82a393c
68,863
def validator(property_name=None, proprietary=False, unstable=False, wants_base_url=False): """Decorator adding a function to the ``VALIDATORS``. The name of the property covered by the decorated function is set to ``property_name`` if given, or is inferred from the function name (replaci...
d73085c19b5737ce06ef7864de4291ae91f51746
68,864
def fake_post_unauthorized(url, data=None, **kwargs): """ Fake treq_kerberos.post """ response = FakeSSLLoginResponse(url, code=401) return defer.succeed(response)
52737241669051c997892bdf92e2f4698fa67308
68,865
def csorname(changeset, csname): """ Return a uuid if id parses as such, otherwise a name. Put the name back together if it got cut into parts @param changeset: changeset identifier or name @param csname: changeset name @return: updated args """ # Put the name back together if it got split comi...
dd26b4b0eb61016d1cc93622bf7745f2f38c2fe5
68,866
import json def make_org_report_json(df_raw): """Create Report For Organization output as JSON""" report = make_org_report(df_raw) json_report = json.dumps(report) return json_report
c5e6472dd4b44c930b12c22bd2818dc42fc494d1
68,867
import requests def ms_monthly(): # monetary Supply """ Man: manufacturing Non-Man: Non-manufacturing Data Source: http://data.eastmoney.com/cjsj/hbgyl.html """ tmp_url = url["eastmoney"] ua = UserAgent(verify_ssl=False) request_header = {"User-Agent": ua.random} tmp_url = url["ea...
e6c870563e8c808865b0f26ad09a535bf00b75cd
68,868
def conv_elu_pool_layer(num_filters, conv_temporal_size, conv_freq_size, pool_size, activation_fn=ELU()): """Conv2D, ELU activation, then max-pool.""" def conv_elu_pool_fn(x): return elu_pool_layer(pool_size, activation_fn=activation_fn)( Conv2D(num_filters, ...
56ba78a9206c0b782dbf58f47527bb7693d1e956
68,869
def generate_timeseries_products(dataset, prdcfg): """ Generates time series products. Accepted product types: 'COMPARE_CUMULATIVE_POINT': Plots in the same graph 2 time series of data accumulation (tipically rainfall rate). One time series is a point measurement of radar data wh...
adea0c8111247c548345d9ebc19f4450fb18b888
68,870
def mentors_of_status(bot, status, character=None, region=None): """Return mentors of given status and character/region for embed.""" mentors = [] if character: db.execute("""SELECT discord_id, name, region, switch, xbox FROM mentors WHERE status = %(status)s AND characters LIKE %...
b431efc18fc87c56e2a1688d00030639439bd564
68,872
from typing import Optional def get_namespace_in_lui(prefix: str) -> Optional[bool]: """Check if the namespace should appear in the LUI.""" entry = get_resource(prefix) if entry is None: return None return entry.get_namespace_in_lui()
6c4a5773761c648fcb64e66dd9053e7aabac95a3
68,874
def classify(exploration_id, state_id, handler_name, answer, params): """Return the first rule that is satisfied by a reader's answer.""" exploration = get_exploration_by_id(exploration_id) state = get_state_by_id(exploration_id, state_id) # Get the widget to determine the input type. generic_hand...
72e4059c57bef156ce9efebd58609be3e10f10ba
68,875
def EvalCStringToken(tok): # type: (Token) -> Optional[str] """ This function is shared between echo -e and $''. $'' could use it at compile time, much like brace expansion in braces.py. """ id_ = tok.id value = tok.val if id_ in (Id.Char_Literals, Id.Unknown_Backslash): # shopt -u parse_backslash...
88b1fa20d0958ab2a35bf61bf4c4ac75c522b72a
68,876
def source_is_connected(source, user): """ Return True if the given source is connected (has the required data for retrieving the user's data, like a huID or an access token). """ try: return getattr(user, source).is_connected except: # pylint: disable=bare-except return False
448122f82723d91132045aef89fc5c2126a44e16
68,877
def begin_auth(request: Request, context: ConnectionContext) -> Responce: # pylint: disable=W0613 """ Request authentication token to sign """ repository = request.headers['repository'] if repository not in config['repositories']: return fail(no_such_repo_msg) # == repository_path = con...
7467c5e45b6c43fee152af2e559c8cbe16b8d629
68,878
import re def tokenize(text, lemmatizer=WordNetLemmatizer()): """Tokenize text (a disaster message). Args: text: disaster message. lemmatizer: nltk.stem.Lemmatizer. Returns: list. It contains tokens. """ url_regex = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]...
c22187e8e51f5ccc16a45a0e152f6d32b5154810
68,879
import struct def encode_command(magic, packet_type, *args): """XXX :param magic: :param packet_type: :param args: :return: """ assert magic in [REQ, RES], 'magic number must be REQ or RES value' _args = [] for arg in args: if type(arg) in _converters: barg = _...
59003a2e02552631c006db77faf4f369bb568079
68,880
def get_sample_reverse_map(config): """ Extract a mapping from riboseq and rnaseq samples to conditions. """ reverse_map = _return_key_dict() riboseq_reverse_map = get_riboseq_replicates_reverse_map(config) rnaseq_reverse_map = get_rnaseq_replicates_reverse_map(config) reverse_map.update(riboseq_r...
539de66d72f60136c2d0438dac476471eb8890c5
68,881
from typing import Union from typing import List from typing import Dict from typing import Optional def tf_metric_computations( metrics: Union[List[_TFMetricOrLoss], Dict[str, List[_TFMetricOrLoss]]], eval_config: Optional[config_pb2.EvalConfig] = None, model_name: str = '', sub_key: Optional[metric_...
a89eb9bdc7dc31cbdc0e49cf3d52e4cc9579097c
68,882
def implicitMT ( enable = True ) : """Context manager to enable/disable implicit MT in ROOT >>> with implicitMT( True ) : ... - see ROOT::EnableImplicitMT - see ROOT::DisableImplicitMT - see ROOT::IsImplicitMTEnabled """ return ImplicitMT ( enable )
a1bbad53bc6d4807a9f6974353378c684da3c479
68,883
def generate_model(output_len, chars=None): """Generate the model""" print('Build model...') chars = chars or CHARS model = Sequential() # "Encode" the input sequence using an RNN, producing an output of HIDDEN_SIZE # note: in a situation where your input sequences have a variable length, # ...
d5ff6565154c166ab51542f68399e3e6de3f2308
68,884
def provider_bundle_id(one_provider: Provider): """Get provider bundle_id attr""" return {'bundle_id': one_provider.bundle_id}
6e9a3b2c6bddc69e8abfd380b9363bf35a397792
68,885
from typing import Optional def validate(prefix: str, identifier: str) -> Optional[bool]: """Validate the identifier against the prefix's pattern, if it exists.""" pattern = get_pattern_re(prefix) if pattern is None: return None return bool(pattern.match(normalize_identifier(prefix, identifier...
a2b2da27c539b2f63e69358bf0fe833ac6042ff5
68,886