content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def conv3x3(in_planes, out_planes, stride=1, groups=1): """3x3 convolution with padding""" return nn.Conv2d( in_planes, out_planes, kernel_size=3, stride=stride, padding=1, groups=groups, bias=False, )
10c9700ed4c0c675831f226d1342a52936298bc3
59,200
def generate_columns_dictionary(key_list: list) -> dict: """Uses the passed ordered list (key_list) of values to generate a dictionary of corresponding column letters. {list0: "A", list1: "B", list2: "C"} Args: key_list (list): Ordered list of values to be used as the keys in the genera...
93fbdeaae594ced2edee0ab56ede415f1794945c
59,201
def vuln_info(vuln_name=None, vuln_id=None): """Returns information about a vulnerability""" #data = [] #query = (db.t_service_vulns.f_services_id == db.t_services.id) & (db.t_services.f_hosts_id == db.t_hosts.id) if vuln_name is not None: vuln_rec = db(db.t_vulndata.f_vulnid == vuln_name).sele...
2ae1304811fca6a36d112e549edd001aea8a2f86
59,202
def add_client(values): """Registers a new client. To register a new client the request must be autheticated by providing the username and password of the existing user. The function will return a dictionary with the client_id and client_secret which will than be used to request authorization for a ...
154ab54b4935e6ebd61dfaef1f5b18022961ea23
59,203
def weighted_values(values, weights): """Takes a dictionary of model => value""" models = values.keys() values_list = [values[model] for model in models if model in weights] weights_list = [weights[model] for model in models if model in weights] return (values_list, weights_list)
8e3c11a5811ead50aa144f103e0cb456476b500d
59,204
def get_ipv6_by_search(search=dict()): """Get List of Ipv6 by Search.""" networks = Ipv6.objects.all() net_map = build_query_to_datatable_v3(networks, search) return net_map
164b85c33af7411a5d9b49a75de6b6afdd3f00e8
59,205
def _should_create_database(connection): """Return whether we should recreate the given DB. This is true if the DB doesn't exist or the REUSE_DB env var isn't truthy. """ # TODO: Notice when the Model classes change and return True. Worst case, # we can generate sqlall and hash it, though it's a b...
ac4e1ad0bd781cd3070dd7cf02a0cf9a3ccd7253
59,206
def APSyn(x_row, y_row): """ APSyn(x, y) = (\sum_{f\epsilon N(f_{x})\bigcap N(f_{y})))} \frac{1}{(rank(f_{x})+rank(f_{y})/2)}) :param x_row: :param y_row: :return: """ # Sort y's contexts y_contexts_cols = sort_by_value_get_col(y_row) # tuples of (row, col, value) y_context_rank = {...
5f2166433bacd4fc22e709401c9078ce2d1a2563
59,207
def check_sender(tx: dict, sender: str) -> bool: """ :param tx: transaction dictionary :param sender: string containing sender's address :return: boolean """ if tx["events"][0]["sub"][0]["sender"][0]["account"]["id"] == sender: return True return False
785c8453b876a2ca2b14f374836987c77a01f882
59,208
import logging def spec_dep(wd=None, spec='O3', s_area=None, months=None, years=None, res='4x5', vol=None, trop_limit=True, Iodine=False, output_freq='Monthly', debug=False): """ Get array of dry deposition values for a given species Parameters ---------- trop_limit (boo...
14aa142adf75db3426a6ffadc2af97c5fc3e132d
59,209
import wingdbstub import time def Run(args): """Execute the STATS NTILE ANALYSIS command""" args = args[list(args.keys())[0]] oobj = Syntax([ Template("PREDPROB", subc="", ktype="existingvarlist", var="predprob", islist=False), Template("DEPVAR", subc="", ktype="existingvarlist", var=...
5842a01ff9590e9f6069c946654457dcb7d96c52
59,210
def is_prime_det(n): """ Returns <True> if <n> is a prime number, returns <False> otherwise. It uses an (optimized) deterministic method to guarantee that the result will be 100% correct. """ # 2 and 3 are prime numbers if (n <= 3): return (n > 1) # Corner cases to speed up the ...
65ee46364510f45485c7d95ee0973d42ebc81d34
59,211
def MedianCombine(ImgList, zero_bo=False, zero='Bias.fits', dark_bo=False, darks=[], flat_bo=False, flat='Flat.fits'): """ Median combine a list of images """ n = len(ImgList) if n==0: raise ValueError("empty list provided!") h = pyfits.open(ImgList[0])[0] d = h.data d = OverscanTrim(d,h.header['BIASSEC']) ...
e15dbe25ee5f5b57e6ce36e8d1e0f542d02248a7
59,212
import argparse import textwrap def _NormalizeDescription(description): """Normalizes description text. argparse.SUPPRESS normalizes to None. Args: description: str, The text to be normalized. Returns: str, The normalized text. """ if callable(description): description = description() if ...
bd2b2cc2ece49b9bac1d121fe594e00b87a4abc3
59,213
from typing import Optional def get_work_group(name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetWorkGroupResult: """ Resource schema for AWS::Athena::WorkGroup :param str name: The workGroup name. """ __args__ = dict() __args__['name'...
75d4d3b683857bdfccb947c1c5d168a0f487b61e
59,214
import torch def kcsd_ustat(X, Z, cond_score_fn, k, l, return_variance=False): """Computes KSCD U-stat estimate""" n = X.shape[0] assert n == Z.shape[0] S = cond_score_fn(X, Z) cond_ksd_gram = ksd_ustat_gram(Z, S, l) K = k.eval(X, X) H = K * cond_ksd_gram stat = (torch.sum(H) - torch....
9ef852ba61c9f325be766136b9a506406fb91573
59,215
def var_window_discrete(Dt, width): """ Variance along window """ N = len(Dt) s = np.empty(N) for i in range(0, N): s[i] = np.var(window_discrete(Dt, i, width)) return s
f88f38e2ea7bd2b38bf1f4a9e60af92b7469d5a8
59,216
def getPixelArray(image, rect=None): """Get pixel array of given rect.""" if not rect: width, height = image.get_size() dimension = min([width, height]) rect = pygame.Rect(0, 0, dimension, dimension) part = image.subsurface(rect) assert(part.get_size()[0] == part.get_size()[1...
c95d1284e9392981fffb9358ccf1125232381713
59,217
import numpy def readScp(filename, limit=numpy.inf): """ Reads the features in a Kaldi script file. Returns a list of feature matrices and a list of the utterance IDs. """ features = [] uttids = [] with open(filename, "r") as f: for line in f: uttid, pointer = line.stri...
e18fea9167b58078c1005ebeb70964255e92aff3
59,218
def padding_to_length(padding): """Calculate the length of mask based on padding. Args: padding: a Tensor with shape [..., length]. Returns: a Tensor with shape [...]. """ non_padding = 1.0 - padding return tf.to_int32(tf.reduce_sum(non_padding, axis=-1))
fad1c2119f0814f7bd310a7245f73184ae01c827
59,219
import subprocess import sys import os def process_handler(cmd, callback, stderr=subprocess.PIPE): """Open a command in a shell subprocess and execute a callback. This function provides common scaffolding for creating subprocess.Popen() calls. It creates a Popen object and then calls the callback with i...
ef1ca51cac706e0103ecbf26a4488a01a9a903f3
59,220
def make_lego_image(image, brick): """Make legofied version of original static image.""" image_width, image_height = image.size brick_width, brick_height = brick.size width = image_width * brick_width height = image_height * brick_height rgb = image.convert('RGB') lego = Image.new('RGB', (...
55b260f6a081eba999f805cbb817c274135bb66c
59,221
import time from typing import Union import logging def wait_on_bq_job_id(bq_client: bigquery.Client, job_id: str, table: bigquery.TableReference, polling_timeout: int, polling_interval: int = 1) -> bool: """" Wait for a B...
f43b501f6449033af4a94a6b36335f8342bf2351
59,222
def has_from_email_address(message: MessageBase): """ Check if the message has a valid From Email Address :param message: message to validate :type message: MessageBase :return the result :rtype bool """ if not message.from_email_address: return False return not StringExtensi...
f3c1975d55a489bf409abb5e52fd6967a80abdfb
59,223
def n_m_state(qubit, n_lex, m_lex): """ Helper function to generate an arbitry n-qubit pure state |n><m|. :param qubits: number of qubits :type qubits: int :param n_lex: index n :type n_lex: int :param m_lex: index m :type m_lex: int :return: pure state |n><m| :rtype: np.nda...
c89adafa6b0d7463d6fc30f55bd340c4dd4d5286
59,224
import argparse import logging def parse_args(args): """Parse command line parameters Args: args ([str]): command line parameters as list of strings Returns: :obj:`argparse.Namespace`: command line parameters namespace """ parser = argparse.ArgumentParser( description="Genera...
cd942eef26ed63f9ea6eb4abf632e88942492271
59,225
def compare(pipeline1, pipeline2): """ Compare if two dataset pipelines are the same. Args: pipeline1 (Dataset): a dataset pipeline. pipeline2 (Dataset): a dataset pipeline. """ return pipeline1.to_json() == pipeline2.to_json()
a97035af5102f4fe652a388d6572fc1110f57c14
59,226
def build_server_broadcast_message(server_state): """Builds `BroadcastMessage` for broadcasting. This method can be used to post-process `ServerState` before broadcasting. For example, perform model compression on `ServerState` to obtain a compressed state that is sent in a `BroadcastMessage`. Args: ser...
8bebdba27e5565a4135185c8615a2074ea26d31f
59,227
def move_gauge_left_tens(ten1,ten2,truncate_mbd=1e100,return_ent=True,return_wgt=True,split_s=False): """ Move the gauge via svd from ten2 to ten1 Args: ten1 : np or ctf array The neighboring left site ten2 : np or ctf array The site currently holding the gauge ...
5f64f84a465008e79da24a7c9fe4728a97c9a0e9
59,228
def count_indents(text): """Takes a string and counts leading white spaces, return int count""" return len(text) - len(text.lstrip(" ")) pass
1c0466c932f0a4204dc704d9718781821246ee89
59,229
def psum(x, axis_name): """Compute an all-reduce sum on ``x`` over the pmapped axis ``axis_name``. Args: x: array with a mapped axis named ``axis_name``. axis_name: hashable Python object used to name a pmapped axis (see the ``pmap`` docstring for more details). Returns: An array with the same...
32a18bb0b30b1a7ce272d4dc35972f2d58d84e5f
59,230
def get_colors_pack(img: np.ndarray) -> list: """ Get unique colors from image Args: img: RGB image Returns: List of unique colors """ colors_pack = [] for i in range(img.shape[0]): for j in range(img.shape[1]): cl = img[i, j] if not check_arr(...
e4aa114192211b9d112c2ad9e6064b67a24fcf82
59,231
from typing import Any def _get_sensor_data( sensors: dict[str, Any], forecast_day: int | None, kind: str ) -> Any: """Get sensor data.""" if forecast_day is not None: return sensors[ATTR_FORECAST][forecast_day][kind] if kind == "Precipitation": return sensors["PrecipitationSummary"][...
8c3d5d108a0a41150bb3dc5d09c7e0b49bbd12af
59,232
def get_payment_request_with_service_fees(business_identifier: str = 'CP0001234', corp_type: str = 'BEN', filing_type: str = 'BCINC'): """Return a payment request object.""" return { 'businessInfo': { 'businessIdentifier': business_identifier, ...
54fcc9b624c0b3603d8f7d2a49c8ad1299615a20
59,233
def zippify(iterable, len=2, cat=False): """ Zips an iterable with arbitrary length pieces e.g. to create a moving window with len n Example: zippify('abcd',2, cat=False) --> [('a', 'b'), ('b', 'c'), ('c', 'd')] If cat = True, joins the moving windows together ...
def01ff9f940009f80c312fe9ee07b282733d99b
59,234
def find_match(data, title): """Parse the list of search results to find the best match. This uses LDA to compare titles against each other. :param data: the iterable of response data to search through :param title: the title to compare the result set against :returns: an `Answer` `namedtuple` hold...
f245939934980a62c5c9cf2d9b80344218abe546
59,235
async def pass_user(order: Order, current_user: User = Depends(identify_user)): """ Receive an Order object, and return the same object. The user in session/connection must send a valid JWT. Args: current_user (User, optional): the user in the session. Defaults to Depends(identify_user...
8c79fabd14456cda0078c846205e771693c853d1
59,236
import os def find_paths(directory,stipe): """"" Arguments: directory {str} -- taranmak istenen ust dizin stipe {str} -- taranan uzanti Returns: path_list {list} -- path list for stipe """ if stipe.islower(): stipe_u = stipe.upper() else: ...
e30b7ee0427db2b4fa45d3944524e056043888f3
59,237
def create_pose_euler(x_p, y_p, z_p, roll_rad, pitch_rad, yaw_rad): """Creates a pose using euler angles Creates a pose for use with MoveIt! using XYZ coordinates and RPY orientation in radians :param x_p: The X-coordinate for the pose :param y_p: The Y-coordinate for the pose :param z_p: The ...
84fe1fb2bce9e34338ef3c7fddc2e526485d8bff
59,238
def getdate(): """ --------------------------------------------------------------------------- Returns the current statement's start date and time as a TIMESTAMP value. Returns ------- str_sql SQL expression. """ return str_sql("GETDATE()", "date")
29a22e31aa5fffe5657d6bc6871cee22f210e7d9
59,239
import requests import html def verbose_counter(website, number_of_words, duplicates_allowed=True, stopwords_allowed=False): """ returns a list of a website's most frequently used words. keyword args: website -- the website url number_of_words -- the number of ...
5c1f6e87889ee35f090d98775954bbfaba2711eb
59,240
def _create_portfolio_grid( numPortGrid, meanVec, sigMat, startPort, numPort, shrinkage=0, minMu=None, maxMu=None, ): """Creates possible portfolios that can be invested in as part of a strategy Parameters ---------- numPortGrid: int Number of total portfolios t...
bed7a28c7c1cd303691ae980b54887f7db2beb6b
59,241
def sesame_convert(filename, drop_rs=True): """ generic converter, sesame to mprep dataframe, assuming II,IG,IR were rbind() into one df then CSV'ed.""" df = pd.read_csv(filename).rename(columns={'Unnamed: 0':'IlmnID'}).set_index('IlmnID') # separate into meth and unmeth dataframes meth_columns = [c for...
8494432601182dc50c081fc7b2fdf534682a33b5
59,242
def db_connect(): """ Connect to the sqlite database. """ # Connect to the engine. engine = create_engine('sqlite:///contact_book.db', echo=False) # Create a schema Base.metadata.create_all(engine) # Create a session Session = sessionmaker(bind=engine) Session.configure(bind=en...
195bf263abde40701972d087e01f19da91fa26e5
59,243
def compute_average_precision(recall, precision): """ Compute the average precision, given the recall and precision curves. Code originally from https://github.com/rbgirshick/py-faster-rcnn. # Arguments recall: The recall curve (list). precision: The precision curve (list). # Returns...
0bbdac3f3469ec60cf52e51d72febe4364c1abc7
59,244
def sanitize_int(value): """ Sanitize an input value to an integer. :param value: Input value to be sanitized to an integer :return: Integer, or None of the value cannot be sanitized :rtype: int or None """ if isinstance(value, str): try: return int(value) except...
5c0481c0c7414f5fdba946f66346b3233ffe6644
59,245
def is_param(obj, _larch=None, **kws): """return whether an object is a Parameter""" return isParameter(obj)
524a11d3fa2d4ceedec046878abf86bae9d90e3a
59,246
import sys import os def getResourcePath(relative_path): """Get absolute path to resource""" # if cx_freeze attribute found, use frozen resources if getattr(sys, 'frozen', False): base_path = os.path.dirname(sys.executable) else: # use path to development resources base_path = os.path...
fe7c087a81eef0e002f893a3f9a4e2a3a8b40ff9
59,247
from typing import Any import enum def union_formatted(value: Any) -> str: """ Return a string with a cross-referencing link for the Optional module. Note that all usages of union on CaseDescription are from the Optional module. """ optional_with_reference = _get_optional_reference() ref_value...
c8c4bc225c92ff1e90b688cd45e2faacd0be32cb
59,248
def svn_fs_make_file(*args): """svn_fs_make_file(svn_fs_root_t root, char path, apr_pool_t pool) -> svn_error_t""" return _fs.svn_fs_make_file(*args)
c662585f5fec9b1b73f4f5d4f95e7c61c49cef96
59,249
def zlibVersion(): """Return the runtime version of zlib library""" return rffi.charp2str(_zlibVersion())
8333f673b9530287ae7533e4eed53ad322b1913d
59,250
import os import shutil def rename_note(oldname, newname): """Renames a note on disk inside the currently USE'd notebook :param oldname: The old filename for note :type oldname: str :param newname: The new filename for note :type newname: str :return: True on sucessful renaming of note ...
55826947f5ca47673ac370bf085dd9a23f280503
59,251
def tap_down(tap, min_tap): """ Go to the next upper tap position """ if tap - 1 >= min_tap: return tap - 1 else: return tap
3e205dc2e7e9562a84b2be50e54c781c29a80336
59,252
def sequences_to_residues(reslist, chains): """ Identify for each element of the chains which are the residues that may be associated to them. Args: reslist(list): the list of all the residues of the system chains (list): a list containing the sequences of the system Returns: ...
612087acfef7d9bc674b2ea9077f76aa29dd63ca
59,253
import logging def _check_elasticsearch(operation, record, *args, **kwargs): """Return permission that check if the record exists in ES index. :params record: A record object. :returns: A object instance with a ``can()`` method. """ def can(self): """Try to search for given record.""" ...
5e6e3efa3750e1b9bf5cff92b98d4befe0ca9efa
59,254
from datetime import datetime def get_ztp_timestamp_obj(ztp_timestamp): """ Author: Chaitanya Vella (chaitanya-vella.kumar@broadcom.com) API to get ztp timestamp :param ztp_timestamp: :return: """ try: return datetime.datetime.strptime(ztp_timestamp, '%Y-%m-%d %H:%M:%S') except...
c090418a103c61515fb60efb5a3270a8a0c8577e
59,255
def quaternion_to_roation(Q): """Convert quaternion vector to 3x3 rotation matrix.""" rotation_mat = np.zeros(shape=(3,3), dtype=float) rotation_mat[0][0] = Q.qw**2 + Q.qx**2 - Q.qy**2 - Q.qz**2 rotation_mat[0][1] = 2 * (Q.qx*Q.qy - Q.qw*Q.qz) rotation_mat[0][2] = 2 * (Q.qx*Q.qz + Q.qw*Q.qy) rot...
071f688ec00f2eb2f55d1e8ff9689974302c0dae
59,256
from typing import Callable from typing import Union from typing import Type def resolve_fw_decl(function: Callable, annotation: Union[None, str, Type]) -> Type: """ Resolve a parameter annotation. :param function: the function that owns the annotation :param annotation: an annotation string :ret...
cf6282e3cb0ff1ed896757a4afec228e2da75e8d
59,257
import threading def run_cmds_parallel(commands): """ Run several commands in parallel, waiting for them all to finish. :param commands: an array of tuples, where each tuple consists of (command_name, exit_on_fail) """ threads = [] results = [None] * len(commands) def run_cmd_in_threa...
9fb7e2c8ecb9b19777fdc37a0ab75b65551e0728
59,258
def collate_metadata(): """Create a collation based metadata object""" train_test_val_instances, classdata, pretransform = _simple() basic_collate_fn = _collate() metadata = {} metadata["pretransform"] = pretransform metadata["classdata"] = classdata metadata["train_test_val_instances"] = tr...
0915f7d40f1d0bce6bb06b36763171bf9a8c3fdf
59,259
def lambda_handler(event, context): """Calls custom transform developed by user Arguments: event {dict} -- Dictionary with details on previous processing step context {dict} -- Dictionary with details on Lambda context Returns: {dict} -- Dictionary with Processed Bucket and...
5ed4f4663fb670dac5be6e37bca034c616b197d7
59,260
def is_valid_ean(ean): """Validate check digit against rest of EAN""" clean = clean_ean(ean) return clean[-1] == ean_check_digit(clean[:-1])
ac6b96c79c8687095073be5de46a8284d417767e
59,261
def nonlinearity(x, activation='relu', name=None): """Nonlinearity layers.""" if activation in ['relu', 'sigmoid']: return tf.keras.layers.Activation(activation, name=name)(x) elif activation == 'leaky_relu': return tf.keras.layers.LeakyReLU(alpha=0.1, name=name)(x) else: return x
cfc5f49b0bbaf6a603559001b0fdc5881ffa27e6
59,262
from datetime import datetime def now(): """Return the current UTC time in ISO format""" return datetime.datetime.now(tz=datetime.timezone.utc).isoformat()
30603fd2c623069ba3c83142b02b131f358a11a7
59,263
def substitute(expr, var_map): """Substitute symbols or (sub-)expressions with the given replacements and re-evalute the result Args: expr: The expression in which to perform the substitution var_map (dict): The substitution dictionary. """ try: if isinstance(expr, SympyBasi...
8bfb60b1a7da856098095ee220e573997b844e99
59,264
def MeanIoUConfig(argument_parser): """ Set CLI arguments :param argument_parser: argument parser :type argument_parser: ```ArgumentParser``` :returns: argument_parser :rtype: ```ArgumentParser``` """ argument_parser.description = """Computes the mean Intersection-Over-Union metric. M...
119b3c005a47e92dad2d298befa330ddab33128e
59,265
import numpy def ltecm(epj): """ Wrapper for ERFA function ``eraLtecm``. Parameters ---------- epj : double array Returns ------- rm : double array Notes ----- The ERFA documentation is below. - - - - - - - - - e r a L t e c m - - - - - - - - - ICRS eq...
6d963f9ac30343165c1a85c56faa6b4f3418a1f4
59,266
def _get_value_by_path(obj, path): """ Get object value by path (e.g. `"a.b"` for object `{a: {b: 2}}`) """ keys = path.split(".") try: for k in keys[:-1]: obj = obj[k] return obj[keys[-1]] except Exception as ex: raise UnprocessableEntity(f"`{path}` could not...
9517f6e923153faca4c0162510ec2ef1d9727cb6
59,267
def _concatenate_regex_dict(map_rgx): """ This builds a regular expression for finding ODBC connection strings. The input is a dict of ODBC character key. mapped to the regular expression for finding it. This might be very slow. """ # Not letter, then the keyword, then "=", then the value regex,...
aff982c329d65b6c3f5a2f5316d0c5bd896db749
59,268
def _ParseKeywordArgs(args, fn_args, fn_keywords): """Parses the supplied arguments for keyword arguments. Given a list of arguments, finds occurences of --name value, and uses 'name' as the keyword and 'value' as the value. Constructs and returns a dictionary of these keyword arguments, and returns a list of ...
9be2cc7b5a338e92228c4b8b338018aff050af22
59,269
import logging import subprocess def run(command): """Execute a command in the shell, return the exit code""" logging.debug(command) res = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) return res.returncode
9a869fd50aa0539f4036581baf1c074b2d5defe3
59,270
def index(): """ --- get: summary: Search entities description: > Returns a list of entities matching the given search criteria. A filter can be applied to show only results from a particular collection: `?filter:collection_id={collection_id}`. If you know you o...
b3b8719f59e036291c910007fcb9e7622a0efdb3
59,271
def tan(t: Tensor): """ Applies tan function to all the elements of the input tensor. ## Parameters: t: `Tensor` - input tensor ## Example usage ```python from beacon.tensor import Tensor from beacon.tensor import functions as fn t = Tensor([1, 2, 3]) x = fn.tan(t) ``` ...
38f20fddac1d27315053fa8816d521c2193b9c73
59,272
import ctypes def create_ffm(): """ Create a field-aware factorization machine. """ model_type = 'ffm' handle = XLearnHandle() _check_call(_LIB.XLearnCreate(c_str(model_type), ctypes.byref(handle))) return XLearn(handle)
24d131afd5d6354dab9d43c458bf66bc1c2876cd
59,273
def Linear_Fit(array_A, array_B): """ Returns slope and y-intercept of the line of best fit """ array_A = np.array(array_A) array_B = np.array(array_B) #Pair arrays then sort them for easier fit zipped_list = zip(array_A[~np.isnan(array_A)], array_B[~np.isnan(array_B)]) sorted_list ...
594a7d7c905e20a27bf7bd76989c68092207abec
59,274
def show_l(l): """Render webpage for l Wikidata item. Parameters ---------- l : str Wikidata lexeme item identifier """ entity = current_app.base.entities.get(l) return render_template("l.html", l=l, entity=entity)
8dad7f93389268e9fb25eeae58e65c09455fdcf6
59,275
def diff(x, dim: int = -1): """Inverse of x.cumsum(dim=dim). Compute differences between subsequent elements of the tensor. Args: x: Input tensor of arbitrary shape. dim: Dimension over which to compute the difference, {-2, -1}. Returns: diff: Tensor of the the same shape as x. ...
2232e0febf48073a1d6f960d0be68f0aebfad4a1
59,276
def infer_mask(seq, eos_ix, time_major=False, dtype=tf.float32): """ compute mask given output indices and eos code :param seq: tf matrix [time,batch] if time_major else [batch,time] :param eos_ix: integer index of end-of-sentence token :returns: mask, float32 matrix with '0's and '1's of same shape...
92af1eaaed58ff7f9fb90b7749e468d9140a44d8
59,277
def embedding_to_padding(emb): """Input embeddings -> is_padding. We have hacked symbol_modality to return all-zero embeddings for padding. Args: emb: a Tensor with shape [..., depth]. Returns: a boolean Tensor with shape [...]. """ emb_sum = tf.reduce_sum(tf.abs(emb), axis=-1) ...
270ce63069ce41a09805fe2bc2ec0f1f56d6ac1d
59,278
def clonality_matrix(insertions, value='clonality', fill_value=None, aggfunc='max'): """Summarizes insertion clonality values in genes-by-samples matrix. Parameters ---------- insertions : pd.DataFrame Insertion dataframe. value...
8f2920b589ce8dbb9737a8eeda1af7ee783b1554
59,279
import warnings def _check_rainfall_rate_values(rain_source, times_in_1st_col=True): """ Check the rainfall rate values in rain source array Args: times_in_1st_col: True|False indicate whether the first column is times Return: float: maximum rainfall rate in mm/h float: average r...
47cb91268222e3ac09798aef5ab81fcc33609c68
59,280
def index(environ, start_response): """ Generic index. """ start_response("200 OK", [("Content-Type", "text/html")]) return [_response_skeleton % dict( page_title = "Cryto-Tahoe-Gateway: Index", page_header = "This gateway does not provide an index page.", page_text = "Pl...
d0c948eba662be3d407742ee8c1ce598e0b8910b
59,281
from datetime import datetime def retrieve_breadcrumbs(path, model_instance, root_name=''): """ Build a semi-hardcoded breadcrumbs based of the model's url handled by Zinnia. """ breadcrumbs = [] zinnia_root_path = reverse('zinnia:entry_archive_index') if root_name: breadcrumbs.ap...
f8b81d2aa14a9c8277222285cc0bf322f1da7f49
59,282
import array def linear_matrix_from_meta(store: Store) -> NP.Matrix: """ Read linear transformation matrix used as input_transform in function.sample from the resulting __meta__.json Args: store: The data.Store Returns: The transformation matrix found, or the identity. """ function_with_...
f780b2cfc72e236e06887699f2884fc3024a303e
59,283
def normal_h3(size: int = 10000) -> HistogramND: """A simple 3D histogram with normal distribution. Parameters ---------- size : Number of points """ data1 = np.random.normal(0, 1, (size,)) data2 = np.random.normal(0, 1, (size,)) data3 = np.random.normal(0, 1, (size,)) return h3( ...
2239a56c2516d037b3c18c8f8d4c074652e5e807
59,284
def run_part2(_): """Implmentation for Part 2.""" # Reverse-engineered the input, it simply does: return sum(val for val in range(1, 10551340 + 1) if 10551340 % val == 0)
75cd89377d4500c8455b96ef1dcf010215e9d058
59,285
def _smallest_size_at_least(height, width, smallest_side): """Computes new shape with the smallest side equal to `smallest_side`. Computes new shape with the smallest side equal to `smallest_side` while preserving the original aspect ratio. Args: height: an int32 scalar tensor indicating the current...
893d2cf0f7323381efae44570d579ffb705bd3c9
59,286
def ConvertComponents(explicit_component_ids, derived_component_ids, config): """Make a ComponentRef for each component_id.""" result = [ConvertComponentRef(cid, config) for cid in explicit_component_ids] result += [ ConvertComponentRef(cid, config, is_derived=True) for cid in derived_component_ids] ...
27cbc72b9d8b89e80cc911f25a42b20ce1226672
59,287
def get_space_info(place_id, return_fields=None, ignore_exceptions=False): """This function obtains the space information for a given Place ID. (aka Browse ID) .. versionchanged:: 3.1.0 Changed the default ``return_fields`` value to ``None`` and adjusted the function accordingly. :param place_id: T...
b45b6bdfa08ba6c97a2526cfcf1b22c630f42837
59,288
import logging def test(model, dataset, device, test_data, criterion): """ Tests a given model. """ model.eval() loss_test = 0.0 batch_number = 0 all_labels = list() all_outputs = list() for idx, data in enumerate(test_data): batch_number = idx + 1 logging.info(f'Te...
16445630abd2760e9d999d62a9e97c746ae7f15d
59,289
def perceptual_distance(y_true, y_pred): """Calculate perceptual distance, DO NOT ALTER""" y_true *= 255 y_pred *= 255 rmean = (y_true[:, :, :, 0] + y_pred[:, :, :, 0]) / 2 r = y_true[:, :, :, 0] - y_pred[:, :, :, 0] g = y_true[:, :, :, 1] - y_pred[:, :, :, 1] b = y_true[:, :, :, 2] - y_pred...
1cca52d0678cf9155c77242249decec6c2dbe30f
59,290
def update_item(name, id_, field=None, value=None, postdata=None): """ Update an item. Either a field and a value, or a chunk of POST data, may be used, but not both. CLI Example: .. code-block:: bash salt myminion rallydev.update_<item name> <item id> field=<field> value=<value> ...
42ea0480983a8e59bceb20dfdfe6c2cd89e803f3
59,291
def _get_dir_names(param): """Gets the names of the directories for testing the given parameter :param param: The parameter triple to be tested. :returns: A list of directories names to be used to test the given parameter. """ return [ '-'.join([param[0], str(i)]) for i in ...
8ef2ad44127402987a26ec0bc6bfffc372f3c64d
59,292
import argparse def parse_args(): """ parse arguments """ parser = argparse.ArgumentParser( description="PaddlePaddle Youtube Recall Model Example") parser.add_argument( '--train_set_path', type=str, required=True, help="path of the train set") parser.ad...
784dd2876d7fa675d999d432072d6cde8fda644b
59,293
from typing import Optional def entity_creation( Link: Optional[str] = Header(None), msg: dict = Body( ... ) ): """Register the hash of the new entity created on Context Broker. """ if Link is None: pass receipt = {} return receipt
0b1df0c4d05a019f91471cb65580a38a590b5aca
59,294
from typing import Union def _safe_sandwich_dot( X: Union[MatrixBase, StandardizedMatrix], d: np.ndarray, rows: np.ndarray = None, cols: np.ndarray = None, intercept=False, ) -> np.ndarray: """ Compute sandwich product ``X.T @ diag(d) @ X``. With ``intercept=True``, ``X`` is treated a...
92963e99696a5d7719ad59c7cf33d5328c6efc3e
59,295
def bool_converter(value: str) -> bool: """ :param value: a string to convert to bool. :return: False if lower case value in "0", "n", "no" and "false", otherwise, returns the value returned by the bool builtin function. """ if value.lower() in ['n', '0', 'no', 'false']: return False ...
10251dfbb0200297d191dce1eb20237aed9e5ac9
59,296
def heat_stor(cp, spm, tdif): """ Calculate the heat storage Args: cp: specific heat of layer (J/kg K) spm: layer specific mass (kg/m^2) tdif: temperature change (K) """ return cp * spm * tdif
397736e091a2cea09328cbf7f6e81c99db6fe384
59,297
def make_per_population_n_cases(): """ This function computes per-population and per-sex case count for each phenotype. """ path_loc = f'{bucket}/combined_results/per_pop_per_sex_case_counts.ht' ht_saige = hl.read_matrix_table(get_variant_results_path('full')).cols() ht_saige = ht_saige.explode(...
d9ebb818c954bdc233a4561537c58845dbe950e8
59,298
import sys def password(password_command): """Create a password prompt function.""" gui = lambda: has_Gtk() and get_password_gui tty = lambda: sys.stdin.isatty() and get_password_tty if password_command == 'builtin:gui': return gui() or tty() elif password_command == 'builtin:tty': ...
d1ec470751f50ef3acb6728bf735f2c12d1fb756
59,299