content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import List def render(gs: game.VisibleGameState, actions: List[game.Action] = None) -> str: """ Pretty fuckin hacky... """ screen = [[" "] * WIDTH for _ in range(HEIGHT)] # Talon: talon_height_offset = 0 for i, card in enumerate(reversed(game.bitmask_to_cards(gs.talon))): ...
5708fe2cb9d84f35c2ea38e3ec10acb79ed46a83
3,617,100
import logging def evaluate_srnpdj(gt, pred, K=25): """ Parameters: gt: np.array([N, ...]) ground truth array of binary labels (integers) pred: np.array([, ...]) same shape as ground truth Returns: srnpdj_N6: np.array(shape=[N, 6]) for each paire...
77db14c4a6e0bdecd2207e9955abfd8e33bb0724
3,617,101
from datetime import datetime def ajax_delete(): """ 客户删除 :return: """ ajax_success_msg = AJAX_SUCCESS_MSG.copy() ajax_failure_msg = AJAX_FAILURE_MSG.copy() # 检查删除权限 if not permission_customer_section_del.can(): ext_msg = _('Permission Denied') ajax_failure_msg['msg'] ...
e33cbab8db34739e970c2fe5651d49487245fc9b
3,617,102
from typing import List def compute_clustering_metrics(y_true: List, y_pred: List) -> List[float]: """ Computes ARI, NMI, goldInstance, sysInstance, goldClusterNum and sysClusterNum between predicted and gold labels Args: y_true: Iterable, ground truth labels y_pred: Iterable, labels ...
289eb6d278aedd79bad83ed1140fb1656caad072
3,617,103
from bs4 import BeautifulSoup import time def _open_url(url: str): """Opens url, creates BeutifulSoup object and waits. :param url: url to get :type url: str :return: BeautifulSoup object """ opener = build_opener() opener.addheaders = [ ('User-Agent', 'Mozilla/5.0 (Windows NT 10....
255b6aaabcfc3b1be2c284e3244067b2f03265bf
3,617,104
def square(vx=1.0, vy=0, wz=0.8, t=16): """ Generate square trajectory, starting and ending at origin. """ time_points = range(t) speed_points = ( # Get set (0, 0, 0, 0), # Walk forward and then turn left (vx, 0, 0, 0), (vx, 0, 0, 0), (0, 0, 0, wz), ...
7db4f1c13cb3055b45e96b0e85934df0c6aa0389
3,617,105
def crypto_adapter(adapter): """Modify an adapter to disable non-crypto symbols. ``crypto_adapter(adapter)(name, active, section)`` is like ``adapter(name, active, section)``, but unsets all X.509 and TLS symbols. """ def continuation(name, active, section): if not include_in_crypto(name): ...
6f1345d4266fc7a7f2391897170b08d29c57a729
3,617,106
from typing import Optional from typing import List from pathlib import Path def get_ann_dir( encoder_type: Encoder.Types, code_lang: str, query_langs: Optional[List[str]]=None, run_id : Optional[str]=None ) -> Path: """ Returns the path to the .ann index files for a specif...
8fa5b2a23cbc9dd436007299e239f39bb9e27050
3,617,107
from typing import Type from typing import cast def coerce(expr: Node, target_type: Type, source_type: Type, context: TypeInfo, is_wrapper_class: bool = False, is_java: bool = False) -> Node: """Build an expression that coerces expr from source_type to target_type. Return bare expr if the coercion...
9687fccd5fddd216f2a96f21030da8e26f8ec3f3
3,617,108
def check_surrounded(string): """ Check if the string as a whole is surrounded by brackets :param string: The string to check. :return: True if it is surrounded. """ length = len(string) if length <= 1: return False counter = 0 for idx in range(length): char = string[id...
6855cadee02c32010ea98752a35ee6d929d53925
3,617,109
def make_message(name): """Constructs a welcoming message. Input: string, Output:string.""" message = "Good morning, %s! Nice to see you."%name return message
ac5c9f845cd6779fa37758ec6b27b69dd325fb7d
3,617,110
def format_time(sec: float) -> str: """Return formatted time in seconds.""" m, s = divmod(sec, 60) h, m = divmod(m, 60) return "%d h %d m %d s" % (h, m, s)
5c825c7556c0e01d4344af8c35c0f005be69114c
3,617,111
def file_path_pair(config, section): """Return input and output file paths for a config section.""" input_obj = config[section]['input'] if isinstance(input_obj, str): input_path = get_file_path(config, input_obj) else: input_path = [] for path in input_obj: input_pat...
eea94ae41595e18a11d30002a19aa3c5f7bb6f63
3,617,112
def get_name_candidates_from_email(parsed_text): """ Gets possible combination of names from the email address :param parsed_text: (unicode string) parsed text from the resume. :return: a list of possible combination of names. """ banned = ['the', 'and'] string_list = [] list_name_data =...
afa14780861d0e024c6f91c0d593ed0440e0bf1e
3,617,113
def spot_price_difference(): """返回 DOT 火币,币安,okex,抹茶,uniswap,heco交易所现货价格的最大价差 @@@ ### description > finished ### args None ### return status code: **200** ```json [ { "dex": "huobi", "price": 100, ...
2bc563cb9e80cf73a651a80938af34fe3c3f9267
3,617,114
def view_eco(key): """View existing eco.""" eco = ECO.get_by_key(key) users = User.query.all() projects = Project.query.all() variables = { 'eco': eco, 'users': users, 'projects': projects } return render_template('eco/view_eco.html', **variables)
578993b8549bd7f5f4c39e915b13ae4173afc8fb
3,617,115
def fetch_accounts(clientCard): """ Function to return the accounts owned by the account holder that is linked to the bank card they used to login into the website, and associated information. Args: clientCard (int): Bank card used for login Returns: accounts_modified (list): List w...
e38895073aaf4c3edad0551edc94dee259a6a1d7
3,617,116
def get_classifier_training_job_from_model(classifier_training_job_model): """Gets a classifier training job domain object from a classifier training job model. Args: classifier_training_job_model: ClassifierTrainingJobModel. Classifier training job instance in datastore. Returns: ...
4297df181b9fcb747bad2f5d839aad1787c84fac
3,617,117
import requests def makeModel(filenum=FILENUM): """ :param str file_num: :return libsbml.Model: """ url = makeURL(filenum) response = requests.get(url).content document = tesbml.readSBMLFromString(response.decode("utf-8")) return document.getModel()
4a0a1c5021c138bc2f0fbddefcdd31e04b0b92ec
3,617,118
import numpy.random def random_sequences(num_seqs, average_length): """ @arg num_seqs: The number of sequences to return. @arg average_length: The expected length of each sequence. (the lengths are actually distributed according to a Poisson distribution). @return: A list of random sequences. """ ...
c778a947faba9fcd651124fcf895f3e8a3a697a2
3,617,119
def tone3_to_tone(tone3): """将 :py:attr:`~pypinyin.Style.TONE3` 风格的拼音转换为 :py:attr:`~pypinyin.Style.TONE` 风格的拼音 :param tone3: :py:attr:`~pypinyin.Style.TONE3` 风格的拼音 :return: :py:attr:`~pypinyin.Style.TONE` 风格的拼音 Usage:: >>> from pypinyin.contrib.tone_convert import tone3_to_tone >>> to...
8facc123f5a8f381dc4166e326f919591dafd1e1
3,617,120
import io def part1(stdin: io.TextIOWrapper, stderr: io.TextIOWrapper) -> int: """ Consider the validity of the nearby tickets you scanned. What is your ticket scanning error rate? """ fields, tickets = parse(stdin) groups = valid_groups(fields) invalid_values = [ value fo...
db8a7ce80df23ab5503b3ca37b181982d761f583
3,617,121
def image_update(client, image_id, values, purge_props=False): """ Set the given properties on an image and update it. :raises NotFound if image does not exist. """ return client.image_update(values=values, image_id=image_id, purge_props...
ddd89c57cefa2972833ce87e382572406fbb811f
3,617,122
def get_new_map(trace): """ Returns the new MAP model from exoplanet after sampling the posterior. Parameters ---------- trace : arviz.data.inference_data.InferenceData Information on the trace of all fitted parameters used in the model sampling, including the posterior values, log_likeliho...
5fec674e4ba56c0163872357a40ed32d576c20f5
3,617,123
def encodeMorse(sequence: str) -> str: """ Encodes the given string to Morse Code Morse code is case-insensitive and traditonally Capital Letters are used Lower cases are converted to Upper cases Every Character code is seperated by a single space between them A space in the se...
7fb6b631d894fe4d73d277d8a4374be581616b32
3,617,124
def brightness(image): """Change brightness of image randomly (maximum 30%)""" hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV) scale = 1.0 + np.random.uniform(-0.3, 0.3) hsv[:,:,2] = hsv[:,:,2] * scale return cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB)
0f0463039992dc3d0087bbe066776af61eb889d3
3,617,125
def _parse_vertex_tuple(s): """Parse vertex indices in '/' separated form (like 'i/j/k', 'i//k' ...).""" vt = [0, 0, 0] for i, c in enumerate(s.split('/')): if c: vt[i] = int(c) return tuple(vt)
e83182401b6443726660caf3688008f6209aed13
3,617,126
import random def __create_clicks_for_statements(up_votes, statement_uid, users, is_up_vote): """ :param up_votes: Int :param statement_uid: Statement.uid :param users: {Users.nickname: User} :return: [ClickedStatement] :param is_up_vote: Boolean """ tmp_firstname = list(first_names) ...
14a31bb3b594d92bc08322d6783828c92bce27f8
3,617,127
def get_pct_on_clutter_map_rhi(filename, polarization): """ get_pct_on_clutter_map_rhi grabs and returns clutter map point percentage occurrences and clutter map masks from daily HSRHI clutter maps (in either H or H and V polarizations). Parameters ---------- filename: str full path...
5cf4ea50b568744dfb39da615c1cdf1458f8d14b
3,617,128
import torch def tfidf_transform(tfidf_vectorizer, corpus_data, cuda0): """ Apply TFIDF transformation to test data. Args: vectorizer_train (object): trained tfidf vectorizer newsgroups_test (ndarray): corpus of all documents from all categories in test set Returns:...
6f18b7114579412e1442b1c6220f34b7f643a2ab
3,617,129
import os def RunAllDir(dir_string, method, no_glob, param): """ Run 'method' on the pinballs in all directories which start with the string 'dir_string'. Uses os.path.walk() to run the method on all pinballs in each directory (or directories). @param dir_string string used to determine directories ...
69d05be6288706cebc9c6babeb773555557e89c8
3,617,130
def or_(*args): """ Trick operator precedence. or_(foo < bar, bar < baz) """ value = DummyAttr() for elem in args: value |= elem return value
5e709f65fe2e03af2fe8e55e1638e8a012acc1c9
3,617,131
def plot_image(data=None, mode='imshow', backend='matplotlib', **kwargs): """ Overall plotter function, converting kwarg-names to match chosen backend and redirecting plotting task to one of the methods of backend-classes. """ if backend in ('matplotlib', 'plt'): return MatplotlibPlotter.plot(da...
f2a4dd4a81aafb182aefd33ffd98667e154ad2d8
3,617,132
import tqdm def project_to_ids_UNSC(Tokenizer, data, max_seq_length=512): """ Function to map data to indices in the albert vocabulary, as well as adding special bert tokens such as [CLS] and [SEP] Args: Tokenizer (bert.tokenization.albert_tokenization.FullTokenizer): tokenizer class ...
159210068640e62bd3eb66acec3131dcf8d9b75e
3,617,133
import os import urllib def download_pretrained_checkpoint(data_config: DatasetConfiguration, cache_folder: os.PathLike) -> str: """Utility function to download a pre-trained checkpoint from the original repository. Parameters ---------- data_config : DatasetConfiguration The configuration id...
802b2330341e0c7de953d21b6ab70fcc4d0683ce
3,617,134
def voigtMath(x, alpha, gamma): """ Function to return the Voigt line shape centered at cent with Lorentzian component HWHM gamma and Gaussian component HWHM alpha. Creates a Voigt line profile using the scipy.special.wofz, which returns the value of the Faddeeva function. WARNING scipy.sp...
623de058a893b79d857869f8a19bc0e3194b457a
3,617,135
def get_installation_coordinates_google(dir_in, key_google, fn_out=None): """ Gets installation coordinates using googlemaps api :param dir_in: <string> path to directory with downlaoded installation data file :param key_google: <string> google api key :param fn_out: <string> name output file. If None, ...
3f33fe2fb14fb3fba92d540c4b2d405a75e53426
3,617,136
def diag_dump( enode, list='', daemon='', level='', file='', _shell='vtysh', _shell_args={ 'matches': None, 'newline': True, 'timeout': None, 'connection': None } ): """ Display diagnostics dump that supports diag-dump. This function runs the following vtysh ...
07a97e8e1dbb2a29b19b49c8b94c7e1fd2d5529f
3,617,137
def randomizeCarVelocities(nCars, vMax): """This function takes integers nCars, and vMax. It then returns an array of of random integers from 0 to vMax. The array is of length nCars. No integers in the returned array are the same.""" carVelocities = [] for i in range(nCars): randomVelocity =...
edd1d118d3b95560c4bcb85c266b63e0380c9b87
3,617,138
import time import logging def get_absl_log_prefix(record): """Returns the absl log prefix for the log record. Args: record: logging.LogRecord, the record to get prefix for. """ created_tuple = time.localtime(record.created) created_microsecond = int(record.created % 1.0 * 1e6) critical_prefix = '' ...
623c6b8966424b8168686d05f5d65c1268a1d0e1
3,617,139
def delete_zcs_container(session, zcs_container_id, return_type=None, **kwargs): """ Deletes a Zadara Container Services (ZCS) container. The container must first be stopped. This action is irreversible. :type session: zadarapy.session.Session :param session: A valid zada...
0eda96c2a07e5a0280584ba9cd323f6fa58e8190
3,617,140
def numStationsNotIgnored(observations): """ Take a list of ObservedPoints and returns the number of stations that are actually to be used and are not ignored in the solution. Arguments: observations: [list] A list of ObservedPoints objects. Return: [int] Number of stations that ...
279f4075bc1fe155e4fa8b39758997c9748f06b8
3,617,141
import attr from typing import Any def _next_and_end(cls: "StateMirror") -> "StateMirror": """Add "Next" and "End" parameters to the class. Also adds the "then()" and "end()" helper methods. """ def _validate_next(instance, attribute: attr.Attribute, value: Any): if value is not None and inst...
1bc7c87f0c9373c5a25866c05bbafb2e9b4d5518
3,617,142
def jf_mcma_lb(sample: np.ndarray, ref_size=None, c=None, delta=0.05, mode=None, mc_size=10000) -> float: """ A function calculates the lower bound using Monte-Carlo M_alpha method. For more details, please check the paper: "A New Confidence Interval for the Mean of a Bounded Random Variable" ...
02791a7e22802cd50e20aa803b981111193cfd4f
3,617,143
def parse_thumbnail_requirements(thumbnail_sizes): """ Takes a list of dictionaries with "width", "height", and "method" keys and creates a map from image media types to the thumbnail size, thumnailing method, and thumbnail media type to precalculate Args: thumbnail_sizes(list): List of dicts w...
07a1e6b5eac978aa59b7a676d8f5b932367599d5
3,617,144
def get_connected_regions_light(input_flow, strict=False): """ :param input_flow: the binary mask array, with shape [x, y, z], pid_id :param strict: whether diagonal pixel is considered as adjacent. :return: a dict, with key 1, 2, 3, ... (int), value is list of location: {1: [(x1, y1, z1), (x2, y2, z2),...
58f89018e0933ac0aff29df83d1cb31f653ed70c
3,617,145
def policy_decision(): """Determines whether a request is allowed or not Args: The function uses HTTP request directly. These argument must be contained in the request: thing_id (str): identification of the thing thing_type (str): type of the thing action (str): get,delete, or c...
031446c3f212f7ecc5944ca040bc026f204fc9e3
3,617,146
def calc_num_nodes(np, ppn=1, threshold=0, name=None): """Calculate the number of required nodes with optional utilization check. :param np: Number of required processing units (e.g. CPUs, GPUs). :param ppn: Number of processing units available per node. :param threshold: (optio...
950b72248b1e4f26f8d8e2ed4c2f6c26b0faa51b
3,617,147
def get_status(req_sheet, row_num): """ Accessor for JIRA Key Args: req_sheet: A variable holding an Excel Workbook sheet in memory. row_num: A variable holding the row # of the data being accessed. Returns: A string value of the Notes """ return (req_sheet['G' + str(row_...
3e1de0013bc0efc5824f5261ff4c0b278f486ea8
3,617,148
import torch def validate(model, criterion, valset, iteration, batch_size, n_gpus, collate_fn, distributed_run, rank): """Handles all the validation scoring and printing""" model.eval() with torch.no_grad(): val_sampler = DistributedSampler(valset) if distributed_run else None ...
a71192ee93901fb1c2f10c1d7cfcd12dfbd1dfbe
3,617,149
def get_permissions(limit=None, offset=None): """Get permissions""" session = current_app.appbuilder.get_session total_entries = session.query(func.count(Permission.id)).scalar() query = session.query(Permission) actions = query.offset(offset).limit(limit).all() return action_collection_schema.d...
6fbb85696aaaafc2209d3e039f5d55c29ac726e3
3,617,150
from typing import List import torch def build_data_loader( X: List[str], y: List[List[str]], batch_size: int, tokenizer: BPETokenizer, ) -> torch.utils.data.DataLoader: """Build data loader. Args: X: list of textual data. y: list of tags (TODO). batch_...
0952e9a3bcb3a171fcb97afbc8378998aff7b00b
3,617,151
from typing import Union from typing import Optional def extract_wikipedia_id(url: Union[str, ParseResult, None]) -> Optional[str]: """ extract Wikipedia ID from URL """ url = parse_url(url, ("en.wikipedia.org", "en.m.wikipedia.org")) return ( unquote_plus(url.path[6:]) or None if url and ...
9388db4aefc4eb08338e9ed0c6619ba2e2afa365
3,617,152
def summation(num) -> int: """This function makes numbers summation.""" return sum(range(1, num + 1))
78983a3e60be914987fd1dc91d5097e1edb326da
3,617,153
def SaveArrayWithGeo( array, src_filename, dst_filename, format ): """ SaveArrayWithGeo(): Saves an Array (array) with Georeferencing from another file (src_flnm), save it in file (dst_flnm) with format (format) SaveArrayWithGeo( self, array, src_filename, dst_filename, format ) """ #From warmerdam at p... Thu Ma...
39191b446006c652860c054a627078d3038592a5
3,617,154
def get_mapshape_from_searchmap(hashtable): """Suppose keys have the form (x, y). We want max(x), max(y) such that not necessarily the key (max(x), max(y)) exists Args: hashtable(dict): key-value pairs Returns: int, int: max values for the keys """ ks = hashtable.keys() h = max([y...
cf5cb2051fc9254d70c60a71d2c7f9e378b0a39e
3,617,155
def det(a, b): """ Calculate the determinent between two vectors @param[a] One vector represented as [x,y] @param[b] One vector represented as [x,y] """ return a[0] * b[1] - a[1] * b[0]
61dfcbf421241ac9885643554bbf0c235f698098
3,617,156
import glob def find_rar(path): """ This function is designed to find the most appropriate file to use when extracting and/or processing releases. This is designed for use with torrent clients and their various "on complete" functionality. This function will always return the largest file found under...
6d1134a276352390d677f1d7fe63328e21498a2e
3,617,157
def test_fft(): """ Kymatio, (C) 2018-present. The Kymatio developers. https://github.com/kymatio/kymatio/blob/master/kymatio/tests/scattering1d/ test_tensorflow_backend_1d.py """ if not got_tf: return None if run_without_pytest else pytest.skip() def coefficent(n): return np...
99d64eb78fd4642fe7b44e1749eb665db04436dd
3,617,158
import re def GetOSVersion(): """Retrieve the current OS version from machine. Returns: os_version: string, like '10.9.5' or '10.10'. Raises: GmacpyutilException: command failed to execute. GmacpyutilException: os_version does not match expected formatting. """ cmd = ['sw_vers', '-productVersio...
2dad46642c448b32100c692de2d9c16051dbb46d
3,617,159
def env_to_bool(environment_variable: str) -> bool: """ Translate an environment variable to a boolean value, accounting for minor variations (case, None vs. False, etc.) """ env_value = getenv(environment_variable) return bool(env_value) and str(env_value).lower() not in ["false", "none"]
69dc81884e900edd9b7849f927e8ea4387ed98a1
3,617,160
def make_var_with_poisson(infile, units, maskfile=None, gain=None, rdnoise=0., texp=None, origbkgd=0., epsilon=None, hext=0, statcent=None, statsize=None, outfile=None, outtype='var', outsnr=None, returnvar=True, ver...
1e5270fdef24d5a6d903ec64a487a2f80566d4b4
3,617,161
def dtype_limits(image, clip_negative=True): """Return intensity limits, i.e. (min, max) tuple, of the image's dtype. Parameters ---------- image : ndarray Input image. clip_negative : bool If True, clip the negative range (i.e. return 0 for min intensity) even if the image ...
a75969f0f0f7664c05ef187050cb699ab3e81fdb
3,617,162
def get_test_data(fname, as_file_obj=True, mode='rb'): """Access a file from MetPy's collection of test data.""" path = POOCH.fetch(fname) # If we want a file object, open it, trying to guess whether this should be binary mode # or not if as_file_obj: return open(path, mode) return path
cfefdda29925e24da84f96ce2365fd042080d196
3,617,163
def runline(y, n, dn): """Perform local linear regression on a channel of EEG data. A re-implementation of the ``runline`` function from the Chronux package for MATLAB [1]_. Parameters ---------- y : np.ndarray A 1-D array of data from a single EEG channel. n : int Length o...
f1ab5b972004e838ee34f6e2bb1e43335eddd73e
3,617,164
def ConsecutiveArrays(arr, step=1): """ Finds consecutive subarrays satisfying monotonic stepping with step in array. Returns on each array element the island index (starting from 1). :param list colors: colors to be included in the colormap :param string name: name the colormap :returns: f...
e9bb07ac1b3c3d527136b19bf9db8f2e5b33dd6c
3,617,165
def normalize(X : np.ndarray, feature_axis = 1) -> np.ndarray: """ 对数据进行归一化 \n :param feature_axis: 各特征所在的维度 \n feature_axis = 1 表示每列是不同的特征 \n """ if not feature_axis: X = X.T _sum = np.sum(X, axis = 0) for j in range(len(_sum)): if _sum[j] > 1e-100: X[:, j] /= _sum[j] else: X[:, j] = 1 / X.s...
47cd365d4a112d1cc2d014374bb7a1b24c8f425c
3,617,166
import io def table_to_image( data: pd.DataFrame, titile: str = "" ) -> io.BytesIO: """Create image with rate table. """ dia = data.plot() if titile: ax.set_title(titile) buffer = io.BytesIO() img = dia.get_figure() img.savefig(buffer) buffer.seek(0) return buffer
bd308fbd916cf6f3285c52403302c22d986b57c4
3,617,167
def update_item(id: str, item_update: ItemUpdate = Body( ..., example=ItemFactory.updated_mock_item)): """ update an item """ item = item_service.get_item(id) if not item: raise HTTPException(status_code=404, detail="Item not found.") return item_servi...
60edc4b33eb7d1661e0c9e94e5cab0ba0f7dd91a
3,617,168
from bs4 import BeautifulSoup import requests def fetch_events_ldi(base_url='https://ldi.upenn.edu'): """ Fetch events from Leonard & Davis Institute, https://ldi.upenn.edu """ events = [] page_soup = BeautifulSoup(requests.get( urljoin(base_url, '/events')).content, 'html.parser') tr...
599bf4284ddc039c70daa4ae16b71456bb764e66
3,617,169
def splitdata_n_max(data, n_max): """ split N into n_max - sized bins """ data = np.array(data).flatten() N = len(data) data_splited = [] for i in range(np.int64(np.ceil(N/n_max))): start = i*n_max stop = np.min([(i+1)*n_max, N]) data_splited.append(data[start:stop]) ret...
9054ad90d632cc256e18ad90d0e02591cfc59ca3
3,617,170
def comments_search(posts,comments): """ :param posts1:Список со словарями, в которых данные публикаций :param comments:Список со словарями, в которых данные комментариев :return:Измененные список posts, с комментариями к постам с статусом sponsored """ for post in posts: post['comms'] ...
e5d57854693de563b9a5beb7ca5f5e40b8d68d5a
3,617,171
import torch def update_weights(batch, batch_dic): """ Readjust weights so they sum to 1. Args: batch_dic (dict): Dictionary with extra conformer information about the batch batch (dict): Batch dictionary Returns: new_weights (torch.Tensor): renormalized weights ...
90131e119e9d2cb849b79346fd2f5f86411f652b
3,617,172
def scaled_dot_product_attention(q, k, v, mask): """Calculate the attention weights. q, k, v must have matching leading dimensions. k, v must have matching penultimate dimension, i.e.: seq_len_k = seq_len_v. The mask has different shapes depending on its type(padding or look ahead) but it must be br...
2c239f141ac7aad901c2f2e597f228af4f0e4838
3,617,173
def get_client_lease_status_raw(client_row=None): """list the raw status of client leases.""" theRawLeaseStatus = u'UNKNOWN' try: # should probably move to config file filepath = str("/var/lib/misc/dnsmasq.leases") if (utils.xisfile(filepath) is True): theRawLeaseStatus = utils.readFile(filepath) except Ex...
ae139d824103ef2e96b0eb4f19814d8502c30fa1
3,617,174
def __edfdv__(fp, e, kv, dt): """ :param fp: :param e: :param kv: :param dt: :return: """ return np.exp(-1j * kv * dt * e[:, None]) * fp
0ceff5470440e8fdc2d49b4b8d9824a3f5ccd660
3,617,175
def design_pts_from_ranges(ranges: np.ndarray, thetas: np.ndarray): """ Args: ranges (np.ndarray, shape=(C,), dtype=np.float32): range per camera ray thetas (np.ndarray, shape=(C,), dtype=np.float32): in degrees and in increasing order in [-fov/2, fov/2] ...
667c4afa9f8546caaabf8414ddc116f36d020a5d
3,617,176
import inspect def _dict_as_called(function, args, kwargs): """ return a dict of all the args and kwargs as the keywords they would be received in a real function call. It does not call function. """ names, args_name, kwargs_name, defaults = inspect.getargspec(function) # assign basic args ...
e4d3ce1f1190b3a72d79235a6aa42ae0605d6737
3,617,177
import torch def idcst2(x, expk0, expk1): """compute inverse discrete cosine-sine transformation This is equivalent to idxct(idxst(x)^T)^T """ if x.is_cuda: output = dct_cuda.idcst2(x.view([-1, x.size(-1)]), expk0, expk1) else: output = dct_cpp.idcst2(x.view([-1, x.size(-1)]), expk...
c5eacfc656a879d902e062d3fc0ff218616c0155
3,617,178
from typing import Any def is_match(pattern: Any, expr: Expr) -> bool: """Returns whether or not an expression matches a pattern.""" if isinstance(pattern, Star): raise ValueError('`Star` pattern must be inside of a sequence.') for _ in matcher(pattern)(expr, {}, id_success): return True return False
6bf59437256fdf260c38a06dad8ad0cc71ffb13c
3,617,179
def add(a, b): """The add function. Args: a (Union[:class:`~taichi.lang.expr.Expr`, :class:`~taichi.lang.matrix.Matrix`]): A number or a matrix. b (Union[:class:`~taichi.lang.expr.Expr`, :class:`~taichi.lang.matrix.Matrix`]): A number or a matrix. Returns: sum of `a` and `b`. "...
514592483910ee75730b2636e78c6b50a7b18125
3,617,180
import os def export_file(isamAppliance, name, filepath, check_mode=False, force=False): """ Exporting a User Mapping CDAS file """ ret_obj = search(isamAppliance, name=name) id = ret_obj['data'] if id == {}: logger.info("User Mapping CDAS file '{0}' does not exists. Skipping expor...
07e682e8e68f9fb52e86417b182466efd750b010
3,617,181
def create_authy_user(email, country_code, phone): """ Creates a user with the Authy API :param email: email to be associated with the user. Used by the API for account recovery :param country_code: country code for the phone number :param phone: national format phone number :returns: ...
fb551badbe633bf839eee687c052806e093abcd6
3,617,182
import urllib def check_remote_vcs(): """ Check if the vcs-url is reachable. Returns ------- check_result: bool Result for the remote vcs to check. """ try: status = urllib.request.urlopen(VCS_SETTINGS['url']).getcode() check_result = True if status == 200 else Fal...
7c37a99d8630be680ba3ec28caefc2a3865afae9
3,617,183
import json def jsonify(*args, **kwargs): """Improved json response factory""" indent = None status = kwargs.pop('_status', 200) mime = kwargs.pop('_mime', 'application/json') # Check for an argument passed, otherwise dict() the kwargs data = args[0] if args else dict(kwargs) # Format...
49a5eb2d2df4ea8af62df8ae6e721b9c870d4c1b
3,617,184
def pull_data_for_tickers( tickers, tiingo_api_key, start_date=None, end_date=None, save_to='', check_existing=True, ): """ Persist all the available data for each of the ticker in ticker_list """ n_tickers = len(tickers) bar = progressbar.ProgressBar( maxval=n_ticke...
024e55db0be03375ecf8cc4fb9dcde9c5089c9ac
3,617,185
def edmonds_karp(graph, source, destination): """Find maximum flow between two vertices in a weighted graph. Args: graph: Undirected or directed graph where every edge has property 'capacity' that indicates how many units may flow through it. source: Source vertex. destinati...
80e1397004a676c6ef1673b66d90d6000724df7a
3,617,186
import ast def _get_all_names(tree): """ Return list of all words. :param tree: _ast.Module object :return: list with words """ return (node.id for node in ast.walk(tree) if isinstance(node, ast.Name))
2b7f39af8bbe0c253d0206bcc86a8a0d05c7686e
3,617,187
import urllib import os import mimetypes import logging def download_image_link(link, dir_path, prefix = ''): """Use urllib to download asset Args: link (str): dir_path (str): prefix (str): Returns: bool """ print(f'download_image_link: from "{link}"') ...
301b21361515a8b70de57bdac30e74cb3acd9a4c
3,617,188
def rot_mat2rot_angle(rot_mat): """ Return the angle corresponding to the given 2D rotation matrix.""" return np.arctan2(rot_mat[1, 0], rot_mat[0, 0])
770eb09b0124d5ca20cc08721e5cbd96a1df7785
3,617,189
def normalize(array): """ Normalize a 1d numpy array between [0,1] Parameters ---------- array: ndarray the array to normalize Returns ------- ndarray the normalized array """ ptp = np.ptp(array) if ptp != 0: return (array - np.min(array)) / np.ptp(...
96ebf4326938026191e857f1da8495dcae84c465
3,617,190
def heatmap(matrix, highlight_index=None, labels_left=None, labels_right=None, path=None): """ :param matrix: (n x n) :param highlight_index: (n x 2) :return: """ fig, ax = plt.subplots() ax = sns.heatmap(matrix, ax=ax, linewidths=.5, cbar=False, yticklabels=["%.1f" % l ...
ef1dbfff0791bed94b27f6f84542cb9c943a7628
3,617,191
import sys import json import traceback def read_file_info(file, hdrnum, print_trace=None, content_mode="translated", content_type="simple", outstream=sys.stdout, errstream=sys.stderr): """Read information from file Parameters ---------- file : `str` The file from which the...
fd674959c412bdca5d101cd902095cfface5f977
3,617,192
def get_dataset(config, key, *, num_tasks): """"Get dataset.""" if config.env.name == 'gym' or config.env.name == 'random': return MDPDataset(config, key, num_tasks=num_tasks) elif config.env.name == 'pw': return DistributedSampleDataset(config, key, num_tasks=num_tasks) else: raise ...
c5597c81e6e4021601dbb87fac1adae21c92892f
3,617,193
def km2_by_state(list_of_park_dicts): """ This function takes a list of national park data (e.g. the returned value from <read_csv_file>), and returns a new dictionary that contains the summed area (in kilometers squared) of national parks in each state. The output dictionary should have the format:...
d513f4b46944964cd52ad3c751a4022606182704
3,617,194
def getRuleCount( lstRules, policy_name ): """ This function return the rule count for a given policy indicated by policy_name Parameters: - IN : 1. List containing all the rules 2. Name of the policy - Out: # of rules in the policy. """ count = 0 for x in lstRules: if x.split(',')[0] == poli...
b4956b0a5af91f1834ee4d463414df2cc02c8796
3,617,195
def send_format(catfact): """ Format's the catfact into a the message to send content string """ return """ Thank you for subscribing to CatFacts™ Did you know: ``` {}``` Type "UNSUBSCRIBE" to unsubscribe from future catfacts. """.format(catfact)
208605f35db4505bb0037cae23088c89e6b1475f
3,617,196
import sys def setup_ssh(tn_conn): """Function to enable SSH on the device :param tn_conn: the Telnet connection :type tn_conn: class:Telnet :return: 0 if the function succeeded, 1 if it failed, or 2 if there was an error. :rtype: int :raises ex: raises a runtime error """ rval = lu...
d32d8a2273e28afef0a8bbb665c54b32d58e84b4
3,617,197
def build_d_layer(flow, name, num_outputs=3): """ arXiv:1703.10593v1 d64 """ with tf.variable_scope(name): weights_initializer = tf.truncated_normal_initializer(stddev=0.02) flow = tf.contrib.layers.convolution2d( inputs=flow, num_outputs=num_outputs, ...
472a904141af6dde2ec762ccc0580e351a5920ca
3,617,198
import logging def drop_infreq_labels(seqs, labels): """Filter out infrequent labels.""" label_vocab, label_counts = np.unique(labels, return_counts=True) is_dropped = {} for i in xrange(len(label_vocab)): logging.info('Found label %s, with count %d.', label_vocab[i], label_counts[i]) ...
4f4567c03f84c92aab7d173c8d446eb857e361da
3,617,199