content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
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
import sys def load_driver(browser_name): """ load_driver loads the input browser. NOTE - if browser not supported then will exit. Parameters ---------- browser_name : str name of the browser. Returns ------- driver : selenium.driver A Browser window object. ...
78a450b772957b324bbfb99b392f1e65c403a0db
68,811
import os import json def aggregate_baseline(N, params, base_dir='dim'): """ Collects all dci scores and aggregates into single array. Args: N, int: Number of random seeds params, list: params tested base_dir, string: Base directory naming scheme Returns: ...
31a075d49536ee0ca40f11bd71ac464cf8c3b9fe
68,812
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 os def GetDeviceID(): """Returns the device ID. The device ID is created and stored by init/goofy.d/device/device_id.sh calling bin/device_id on system startup. """ if os.path.exists(DEVICE_ID_PATH): return file_utils.ReadFile(DEVICE_ID_PATH).strip() # The device_id file doesn't exist, we prob...
383dd81bcaae77140c2b6cdd0f8f9f135f7f9801
68,817
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
import os def resize_transform(buildState): """ APPLIES: IMAGE Supports local resize through a perspective transform or a global resize. Global resize with a location change and none interpolation implies a resize of the canvas without resize of data (inverse of a crop). 'inputmaskname' is a f...
7344d080fde23786d35aa3c86ae9b46495ce7bdc
68,834
import os def GetModifiedFiles(): """Returns a set that maps from changelist name to (status,filename) tuples. Files not in a changelist have an empty changelist name. Filenames are in relation to the top level directory of the current repositary. Note that only the current directory and subdirectories are...
445982fe2f6c51b1ea79f20ec34cbd6b38ec649d
68,835
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
from typing import Optional import os import sys def get_config_path(location: Optional[Text]) -> Optional[Text]: """Check location of the configuration file is valid and returns the path to the config. Args: location: Location of the configuration file; either the path to the config or its containin...
0532f99603abb19b2652b72e8796db1e8f00ab57
68,838
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 sys import imp def mainfrozen(): """return True if we are a frozen executable. The code supports py2exe (most common, Windows only) and tools/freeze (portable, not much used). """ return (safehasattr(sys, "frozen") or # new py2exe safehasattr(sys, "importers") or # old py2exe ...
d9be608a04aa701af2f2737cd5465a722125dd86
68,857
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
import tempfile import os def save_request(request): """ From: https://gist.github.com/TheWaWaR/bd26ef76dabca2d410dd """ req_data = {} req_data['endpoint'] = request.endpoint req_data['method'] = request.method req_data['cookies'] = request.cookies req_data['data'] = request.data ...
fa9d1e7bbbfade09957120dbf9aa6d26f2743ec5
68,871
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
import os def list_rois(atlas='desikan-killiany', template=None): """Lists the regions of interest available for plotting. Parameters ---------- atlas: str The segementation atlas to use; 'desikan-killiany' (default), 'DKT' or 'destrieux'. template: str The common referenc...
912a4baab1229e00613ea8da8ee6a284e7facd70
68,873
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
def find_feature_expectations(feature_matrix, o_feature_matrix, trajectories, global_trajectories, options_states): """ Find the feature expectations for the given trajectories. This is the average path feature vector. feature_matrix: Matrix with the nth row representing the nth state. NumPy ar...
0ace4de1933485b78823f43d2ce70b33d97d8b73
68,887
def select_t(func): """ Transformation for Sequence.select :param func: select function :return: transformation """ return Transformation( "select({0})".format(name(func)), partial(map, func), {ExecutionStrategies.PARALLEL}, )
0c8fdb9c5af061a023ee7a09b5d53bb1b73643c6
68,888
def group(x, n_filters, n_blocks, alpha): """ Construct a Depthwise Separable Convolution Group x : input to the group n_filters : number of filters n_blocks : number of blocks in the group alpha : width multiplier """ # In first block, the depthwise convoluti...
bd0233d7a672fdf5e1d1d0f84ccee9488d1f5432
68,889
import logging import time def evaluate(loader_dev, metric, segment): """Evaluate the model on validation dataset.""" logging.info('Now we are doing evaluation on %s with %s.', segment, ctxs) metric.reset() step_loss = 0 tic = time.time() out_list = [] label_list = [] for batch_id, seq...
e6ef4ed5553f877ad01ceb3a0e19bfc258ae6a86
68,890
def query_prob(result, Y, y, e): """ Query P(Y | e), or the probability of the variable `Y`, given the evidence set `e`, extended with the value of `Y`. All immediate parents of Y have to be in `e`. """ # if Y is continuous (with discrete parents) if Y in ['Nscore','Escore','...
3b7aec7ef40eca8544286de8b59e509c900b1979
68,891
async def get_user(request: web.Request) -> web.Response: """Handlers for GET /users/{username} List groups of {username} """ hostname = request.app["settings"]["hostname"] username = request.match_info["username"] claims = utils.enforce_authorization(request.headers, request.app["settings"]) ...
f1c509700b07e0631f0d46c17e72265d707337c4
68,892
from datetime import datetime import click import sys def _main(args): """Primary entry point function Args: args (list of str): command line arguments to pass to the command interpreter Returns: int: return code to pass back to the shell """ start = dateti...
bab51b9ef0c14ca3afe5eab002c4de53fa39fb7a
68,893
def scoreboard(board, depthleft, evaluate): """ This method uses a Negated Minimax method. Instead of two subroutines for maximising and minimising players, it passes on the negated score due to following mathematical relation: max(a, b) == -min(-a, -b) """ # Note, if it...
079873b5500085c376015c60b40ff760af680ffa
68,894
def HaarGOB(treeG): """ HaarGOB generates Haar Global Orthonormal Basis for a chain or tree treeG INPUTS: treeG - chain or tree for a graph OUTPUTS: treeG1 - the updated chain treeG which is added for each level a Haar orthonormal basis and for the bottom level the basis is the ...
9934013622249dc14fe7d0a3082de8a0305d01be
68,895
def get_all_but_hidden_sites() -> list: """Returns all but hidden site identifiers.""" sites = get_from_data_portal_api("api/sites") sites = [site["id"] for site in sites if "hidden" not in site["type"]] return sites
50ee53142d58d8b27a7d0e14eda3df642e5b0443
68,896
import logging def lambda_handler(event, context): """ The function intended to be kicked off when loaded up by AWS Lambda. Takes the expected event and context arguments. :param event: :ptype event: dict, list, str, int, float, or NoneType :param context: :ptype context: LambdaContext :re...
c933e758e91cbfde06f982284819c903b12eca7d
68,897
def phasecycle(all_data, dim, receiver_phase): """Phase cycle Args: all_data (dnpdata_collection, dnpdata): data to process dim (str): dimension to perform phase cycle receiver_phase (numpy.array, list): Receiver Phase 0 (x), 1 (y), 2 (-x), 3 (-y) Returns: dnpdata: data obj...
d2035edcc56c09d70b1b221d4e552c3efb799561
68,898
def minutes_to_seconds(minutes): """A function that converts minutes to seconds :param minutes: The number of minutes do be converted :return: The number of seconds in a give number of minutes """ return 60 * minutes
b9dee8e669f7659fe669e5b97ef79e8e035b63bf
68,899