content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import inspect def get_gradient_clip_fn(hparams=None): """Creates a gradient clipping function based on the hyperparameters. See the :attr:`gradient_clip` field in :meth:`~texar.core.optimization.default_optimization_hparams` for all hyperparameters and default values. The gradient clipping func...
88dedd060763b529eafe4982a4f3abd9d27b0455
51,400
def find_delimiter_in(value): """Find a good delimiter to split the value by""" for d in [';', ':', ',']: if d in value: return d return ';'
4a60fbe6294fff048645a6fbc397ec96fd748d67
51,401
from nzmath.prime import generator_eratosthenes as generator_eratosthenes def powerDetection(n, largest_exp=False): """ param positive integer n param boolean largest_exp return integer x, k s.t. n == x ** k (2 <= k if exist else x, k == n, 1) if largest_exp is true then return l...
5e5a4e374957660b60a5bb51b7b780801ce8e570
51,402
def get_parser_from_config(): """ Uses the 'parser' field in the config file to find and return the parser :return: """ parser_instance = config.read_config_option("parser") return parsers.parser_factory(parser_instance)
a83a8ba2e2b88c29276400b3fb405227950027ec
51,403
def _SeqPaddingLength(inputs_nmap): """Returns the lengths of paddings at the beginning and end of the sequence. Args: inputs_nmap: A `.NestedMap` of tensors that may have 'padding' Every tensor's 0-th dim has the same size. Returns: padding length at the beginning, padding length at th...
9ceeccca913dd8ed0738db88073a7bc8c791480e
51,404
def get_ROT(ch,pe,te,ze,verbose=True): """ calculate ROT and depol ratio """ args = [ch, pe, ze, te, MISSING, verbose] ROT, depol_ratio, rc = VLIDORT_POLAR_.rot_calc(*args) return ROT,depol_ratio
54b6173db6d676f6eaeb45b3980b3af74a6ffa0d
51,405
def getFailsafeQueue(): """ Method returns failsafe queue """ global failsafeq return failsafeq
43ee8f9090e6cc719946176b2673a93553be8aae
51,406
def wait_for_read(socks, timeout=None): """Waits for reading to be available from a list of sockets or optionally a single socket if passed in. Returns: A list of sockets that can be read from immediately. """ return _wait_for_io_events(socks, EVENT_READ, timeout)
ba254b3fe46c104d90252d212e79587f2a5fd38a
51,407
import sys def alpha_032(enddate, index='all'): """ Inputs: enddate: 必选参数,计算哪一天的因子 index: 默认参数,股票指数,默认为所有股票'all' Outputs: Series:index 为成分股代码,values为对应的因子值 公式: (scale(((sum(close, 7) / 7) - close)) + (20\* scale(correlation(vwap, delay(close, 5), 230)))) """ ...
16a8c2865de4fcc6d0ce69a3d21c6ffc2a134d22
51,408
import logging import time import os def make_custom_logger() -> Logger: """ Set up a new custom logger for using across modules of the bot :return: new logging.Logger() instance """ log_folder = './log' # __name__ needs to add name of corresponding module in a log message new_log = log...
f03e579a0349549bc5b42e56c46a702a4e83e53f
51,409
def group_frame(frame_partitions, num_new_parts, key_columns): """Group frame to prepare for the join """ return [ local_shuffle(part, num_new_parts, key_columns) for part in frame_partitions ]
116b32cd69655c6f88dd6835af3d939a83d24074
51,410
import json def post_message(data: str): """helper for debugging""" payload = json.loads(data, parse_float=Decimal) result = BETS.post_message(payload) return result
4452cc9801facff0d0487bf42919ea87a2952ca3
51,411
def read(**kwds): """ Read all data. """ title = kwds.get("title") text = kwds.get("text") tags = kwds.get("tags") offset = kwds.get("offset") limit = kwds.get("limit") query = Article.query if title: query = query.filter(Article.title.contains(title)) if text: ...
d277e43384d3487941cf5ed7e16ccde5f02a27f9
51,412
import os def reward_word2vec_coherence(conversations): """Allocates reward for coherence between user input and bot response in word2vec embedding space""" if 'word2vec' not in globals(): print('Loading word2vec dict') global word2vec, keys word2vec_path = os.path.join(ROOT_DIR, "...
7756ca937880570a7fb9d4e684b42d58cfcb0536
51,413
import sys import argparse def evaluation_io(parser, ann_suffix, det_suffix, ann_dir=None, det_dir=None): """ Add evaluation input/output and formatting related arguments to an existing parser object. Parameters ---------- parser : argparse parser instance Existing argparse parser obj...
4ab11b82fa1b3f5e79e505742796f3d9dd3b85f3
51,414
from datetime import datetime def project_with_max_gross_value_added(): """Test fixture returns an investment project with the max gross value.""" gva_multiplier = GVAMultiplierFactory( multiplier=Decimal('9.999999'), financial_year=1980, ) with mock.patch( 'datahub.investment...
a0ec8d6a700f54c6e56f33ab3750e51dcd4a2283
51,415
def Adaptor3d_HSurfaceTool_VResolution(*args): """ :param S: :type S: Handle_Adaptor3d_HSurface & :param R3d: :type R3d: float :rtype: float """ return _Adaptor3d.Adaptor3d_HSurfaceTool_VResolution(*args)
3d26f8bca3ff02ac58d607c43f885d75e878e183
51,416
import argparse def parse_args(): """Parse command-line arguments.""" p = argparse.ArgumentParser(description=__doc__) p.add_argument('-v', '--verbose', action='count', help='increase verbosity') p.add_argument('-f', '--featlist', default='feats.txt') p.add_argument('-s', '--sam...
1995f18e1c9195f88912d9f0b5f1b660ff302739
51,417
def enhance_contrast(im, cmap='pink', display_contrast=1): """Enhance contrast of the input image.""" im = ensure_positive(im) color_img = ind2cmap(im, cmap) color_img = color_img * 255 * display_contrast color_img[color_img > 255] = 255 color_img = np.uint8(color_img) return color_img
5a150d658f89bf09a6238cdaa01a6b9d986a3555
51,418
import io import os def step_props(first, last, specs, night): """ Internal helper function used only in the desi_pipe script to build names of scripts and directories. """ specstr = "" if specs is not None: specstr = " --spectrographs {}".format(",".join([ "{}".format(x) for x in spec...
6f91dee6113078f7c851e249ec084f1075c8516e
51,419
def drift_stability_ind( missing_recs_drift, drift_tab, missing_recs_stability, stability_tab ): """ This function helps to produce the drift & stability indicator for further processing. Ideally a data with both drift & stability should produce a list of [1,1] Parameters ---------- missing_recs...
6964f0b258d0c531e242b47ccc864b54c72d4dd0
51,420
import time def sample_function(integer1: int, integer2: int): """ This function takes as input two integers (integer1 and integer2) and returns integer1 raised to the power of integer2 Parameters: ----------- integer1 (int) a number greater than or equal to zero ...
2e3ff92a398adda8cc558c8a20f939614b0e0b94
51,421
def get_dfs(path): """ Grabs the different data splits and converts them into dataframes. Expects format from Code Search Net Challenge. """ dfs = [] for split in ["train", "valid", "test"]: files = sorted((path/split).glob("**/*.gz")) df = jsonl_list_to_dataframe(files, ...
6d293f2a4562c132675bab091d8f5d0b314e939d
51,422
import time import datetime import time import datetime import string import traceback from sys import path import operator def panorama_request(): """ Gets the details of anomalies from the database, using the URL arguments that are passed in by the :obj:`request.args` to build the MySQL select query...
1684e3f8b033ce683fba149e2ef2b0ab878b03bb
51,423
def _get_entropy(data): """ helper function that calculates the entropy of the input array """ H = 0 for value in data: if value > 0: H -= value * np.log2(value) return H
0cf33bc39964571c9fb52ccef694e41bf91b003d
51,424
def make_doc(): """ Only used for sphinx documentation to add the prefix """ doc_app = Flask(__name__) doc_app.register_blueprint(bp, url_prefix='/tmp_dids') return doc_app
045b16f10aae4b55fd9c11f8309b6092f03b1bb0
51,425
def tf_box_4c_to_box_3d(boxes_4c, ground_plane): """Vectorized box_4c to box_3d conversion Args: boxes_4c: Tensor of boxes_4c (N, 10) ground_plane: Tensor of ground plane coefficients (4,) Returns: Tensor of boxes_3d (N, 7) """ format_checker.check_box_4c_format(boxes_4c) ...
f8ac4d71577510e58ed3b00255657fb4fe89be21
51,426
def timed(function): """ Log how long a function took :param function: Function to time :return: Result of the function """ @wraps(function) def wrapper(*args, **kwargs): start = timer() result = function(*args, **kwargs) print("{} took {} ms".format(function.__name__...
f2932a6acd13730eb2d450c24dc1bde8910a0096
51,427
def tfmatrix2tf(sys): """Convert a matrix of transfer functions to a MIMO transfer function. Parameters ---------- sys: list of (list of control.xferfcn.TransferFunction) The transfer function matrix representing a MIMO system. sys[i][j] is the transfer function from the i+1...
6e0ee5224162a0784e3fc30fde6ecb78ca5f4191
51,428
def active_genes_and_tf(active): """ From differentially expressed genes, return the genes and transcription factors. """ active = list(active) t_factors = list({gene.regulatory_product for gene in active if\ isinstance(gene.regulatory_product, TranscriptionFactor)}) return t_fac...
74a6393294f3f69666235ffae1e7d1a97b200566
51,429
def get_cmap(name: str) -> np.ndarray: """Retrieve the given colormap and return RGB values as a uint8 NumPy array of shape (255, 3)""" name = name.lower() if name not in AVAILABLE_CMAPS: raise ValueError(f'Unknown colormap {name}, must be one of {AVAILABLE_CMAPS}') with _get_cmap_data(name) a...
527c51d3c0cae517637509f9907c5d37215df3e8
51,430
def _addvFuncNumba( mNrmNext, mNrmGridNext, vNvrsNext, vNvrsPNext, MPCminNvrsNext, hNrmNext, CRRA, PermShkVals_temp, PermGroFac, DiscFacEff, ShkPrbs_temp, EndOfPrdvP, aNrmNow, BoroCnstNat, mNrmGrid, cFuncNow, mNrmMinNow, MPCmaxEff, MPCminNow, )...
1736d5451cf573067f19f7cab63490cb0cf6731e
51,431
def rename_get_variable(mapping): """ Args: mapping(dict): an old -> new mapping for variable basename. e.g. {'kernel': 'W'} Returns: A context where the variables are renamed. """ def custom_getter(getter, name, *args, **kwargs): splits = name.split('/') basename = s...
17aded74fb06d7aeaba7ecedccb07622775d5d96
51,432
import functools def with_color(color_code: str): """Coloring decorator Arguments: color_code {str} -- e.g.: '\033[91m' """ def wrapper(func): @functools.wraps(func) def inner(args): result = func(f'{color_code}{args}\033[0m') return result retu...
3f5ecd79b3d4579ba4348b2492eaaa3688201907
51,433
def compute_accuracy(idxR,idx,k): """ # =============================== #----- INPUT # idxR : real labels # idx : estimated labels # k : number of class #----- OUTPUT # ACC_glob : global accuracy # tab_acc : accuracy per class # =============================== """ ...
bf70ac41be460cd7623ccf8dcc85073c7bac69a6
51,434
def tri_lexique_lemme(corpus,lex_5g,lex_4g,lex_3g,lex_2g,dict_lexique): """ dans un corpus, retrouve les mwes d'un lexique donné en passant par les lemmes entrée : - corpus .conllu (lu par read_file()) - lexiques de mwe ordonnées par tailles de mwe - dico {'mwe' : 'POS associée'} sortie : - dico {phrase : [lis...
814d07ef0a8517c7161aa0038d7c2b3cca44f298
51,435
import sys def python_executable(): """Return the real path for the Python executable, if it exists. Return RuntimeError otherwise. Returns: (str): The real path of the current Python executable. """ if not sys.executable: raise RuntimeError( "Failed to retrieve the rea...
ee3e9a0f083b49d26f68c6dfa395d510d3c68b57
51,436
def count_ones(value: bytes) -> int: """Count the number of 1's in the binary string.""" return bin(value).count("1")
0752a267b977df5a6ff11160deb6ef2d14712d92
51,437
def test_kernel_shap_with_a1a_sparse_nonzero_background(): """ Check with a sparse non zero background matrix. """ np.set_printoptions(threshold=100000) np.random.seed(0) X, y = shap.datasets.a1a() # pylint: disable=unbalanced-tuple-unpacking x_train, x_test, y_train, _ = sklearn.model_selectio...
6eb54eee11efc99f983c37d55e6439344a6a0f5f
51,438
def is_lyrics_content_ok(title, text): """Compare lyrics text to expected lyrics for given title""" setexpected = set(LYRICS_TEXTS[lyrics.slugify(title)].split()) settext = set(text.split()) setinter = setexpected.intersection(settext) # consider lyrics ok if they share 50% or more with the referen...
330f60eab27ea754d383cd98d9671926e0801bff
51,439
def ratio_enum(anchor, ratios): """Enumerate a set of anchors for each aspect ratio wrt an anchor """ base_w, base_h, x_ctr, y_ctr = genwhctrs(anchor) size = base_w * base_h # 16 * 16 size_ratios = size / ratios # (2*16**2, 1*16**2, 0.5*16**2) a_w = np.round(np.sqrt(size_ratios)) a_h = np.round(a_w * ra...
16871ffa286ef0091ffb9074b143e87474e26c57
51,440
import shlex from typing import Sequence def escape_value(value: OptionValueType) -> OptionValueType: """Escapes an option value based on its type.""" if isinstance(value, str): return shlex.quote(value) elif isinstance(value, Sequence): return [shlex.quote(v) for v in value] else: ...
20636c3239edc5cf8c328a5df68478cf0366e979
51,441
def over(funcs): """Creates a function that invokes all functions in `funcs` with the arguments it receives and returns their results. Args: funcs (list): List of functions to be invoked. Returns: function: Returns the new pass-thru function. Example: >>> func = over([max...
6cd1a966366ee372c18dd35d71adf91028a04b1c
51,442
import logging def get_logger(): """retrieves logger ("singleton"). Returns ------- logging.Logger logger for this module """ global module_name try: get_logger.logger except AttributeError: get_logger.logger = logging.getLogger(module_name) return get_...
ba83ed2db59f879ccaf8b04f8a0a5ee2bb7e4d5e
51,443
def load_labels_map(labels_map_path): """Loads the labels map from the given path. The labels mmap must be in the following plain text format:: 1:label1 2:label2 3:label3 ... The indexes are irrelevant to this function, they can be in any order and can start from zero,...
8ff1e41b87fedffa053981299c48488add754ff9
51,444
def get_user(email): """ Return a user object by email lookup """ model = get_user_model() return model.objects.get(email=email)
3d85bdac487c06c33cf754976be87bb9873b335f
51,445
def generate_pruned_random_no_correlations_dataset(n_token, n_docs, n_subjects, min_samples): """Generate random data without any subject correlations, but with minimum samples per subject.""" dataset = generate_random_dataset(n_token, n_docs, n_subjects) return filter_subjects_with_insufficient_samples(dat...
ae31b487da75f7bc4c079aa3981cd41b10c9e1ac
51,446
async def m_aggregate(table, pipeline, **kwargs): """ aggregate """ db, kwargs = get_motor(**kwargs) plan = await db.command(SON([("aggregate", table), ("pipeline", pipeline)])) return plan
08e1969a22250cba648a2880a207f8699e0a6bb6
51,447
from typing import List def neurons_values(lstm_layer: md.ml.nn.layers.LSTMLayer, data: List[float], ppty_name: str) -> List[np.ndarray]: """ Get the activation values for a LSTM layer Args: lstm_layer: LSTM layer data: data to process ppty_name: the type of values to get Returns: List where each position ...
780fcf16698385e71f3426274f4f34782ec2a005
51,448
import logging as log from scipy.signal import butter, filtfilt def band_stop_filter(signal, Fs, Fc=60): """ This function filters out frequencies close to a desired cutoff Fc (in Hz). The default Fc is 60 Hz as that is most common for unwanted noise :param list signal: input signal :param int Fs...
e64224af3bbb34275daa12f07573033358ed0cc8
51,449
import math def bbox_to_integer_coords(t, l, b, r, image_h, image_w): """ t, l, b, r: float Bbox coordinates in a space where image takes [0; 1] x [0; 1]. image_h, image_w: int return: t, l, b, r int Bbox coordinates in given ima...
90fb198e2d6cd170a2e7a2b648f15554a9997389
51,450
def load_config(args): """Tries to load the configuration file or throws ExitWithError.""" config = ConfigManager(DEFAULT_CONFIG) config_dir = home_dir.get() try: if args.config_file is not None: filename_override = os.path.abspath(args.config_file) else: filename...
4f8070d8d5373571d44d6c72a9c5e04f7b33497e
51,451
import numpy as np def circular_layout(G, scale=1, center=None, dim=2): # dim=2 only """Position nodes on a circle. Parameters ---------- G : NetworkX graph or list of nodes A position will be assigned to every node in G. scale : number (default: 1) Scale factor for positions...
eb679719704fa260381b26b558d505deeb09a8a0
51,452
def sdp_sub(f, g, u, O, K): """Subtract distributed polynomials in `K[X]`. """ h = dict(f) for monom, c in g: if h.has_key(monom): coeff = h[monom] - c if not coeff: del h[monom] else: h[monom] = coeff else: h[...
2c82175cca3f209327ac48a8ef436300231d3337
51,453
def create_meeting(): """ При GET запросе возвращает страницу для создания встречи. При POST запросе, в случае успешной валидации сохраняет новую встречу в БД. """ title = 'Создание встречи' meeting_form = MeetingForm(request.form) with db_session() as session: meet_data = GameMe...
473ac76693589b5f46d846ea05d0e623e991b85b
51,454
def correlation_ratio(col1: ndarray, col2: ndarray) -> float: """Returns the correlation ratio for col1 and col2. Used for categorical - numerical variable pairs. Args: col1 (ndarray): A categorical column with no null values col2 (ndarray): A numerical column with no null values""" uni...
016ff428c1895bf4cb5380baac95fbba9ec76c74
51,455
def read_txt_tensor(filePath): """ read tensor data from text file. Parameters ---------- filePath : str the path of file Returns ------- tensor three-way numpy array """ tensor = pd.read_csv(filePath, header=0, names= ["v1", "v2", "v3", "v4"]) rowIndices ...
15f65958d9937f00c532dbc383bac5b2cb4ef990
51,456
from typing import Tuple from typing import Any def train_sequence_model(data: Tuple[Any, Any], output_dir: str, embedding_dim: int = 200, dropout_rate: float = 0.2, filters: int = 3, kernel_size: int = 3, pool_size: int = 3, num_classes: int = 3, learning_rate: float...
da3769bfa017e68ec9e7bca2c40a4692c1f6a028
51,457
import os import psutil def execute(*args, **kwargs): # type: (*Any, **Any) -> psutil.Popen """A thin wrapper around 'psutil.Popen'""" if is_unix: # Call os.setpgrp to make sure the process starts in a new group orig = kwargs.get('preexec_fn', None) def wrapper(): os.s...
400043163fd5d87fd1e4e837c5fac0faa8472093
51,458
def get_pose3_vector(num_poses: int) -> Pose3Vector: """Generate camera poses for use in triangulation tests""" # Looking along X-axis, 1 meter above ground plane (x-y) upright = Rot3.Ypr(-np.pi / 2, 0.0, -np.pi / 2) pose1 = Pose3(upright, Point3(0, 0, 1)) # create second camera 1 meter to the rig...
196c33faec30cb74b59a2302397ac41866bc0d3a
51,459
import requests from requests.auth import HTTPBasicAuth def execute_request_with_global_keys(operation, url, **kwargs): """execute_request_with_global_keys helper function which takes a global CP4S API Key and Secret rather than one derived from cases. These API keys use different authentication met...
65534d5c9cd858688db9258a0f5054eb54944dca
51,460
def from_datestring(datestring): """Parse an arbitrary datestring and return a datetime object using dateutils' parser. """ if dateutil_available: return parser.parse(datestring) else: raise RuntimeError('from_datestring requires the python-dateutil library')
98efc647c609c6cf34474ecdb18c985551975089
51,461
def clean_word(word): """Clean the word. Parameters ---------- word : str Returns ------- str """ new_word = (word .replace('(', '') .replace(')', '') .replace(':', '') .replace(';', '') .replace('+', '...
5d776bd9ad6bcb7824e56bafb15d6fec0fae6024
51,462
import signal from warnings import warn import threading from warnings import warn from pudb.lowlevel import format_exception import sys from warnings import warn def set_interrupt_handler(interrupt_signal=DEFAULT_SIGNAL): """ Set up an interrupt handler, to activate PuDB when Python receives the signal `...
3307a39893f28a00a5644e1419daaa6b43173601
51,463
from emonitor.extensions import scheduler from emonitor.lib.osm.loaddata import parseOsmData def getAdminData(self, **params): """ Deliver admin content of module maps (ajax) :return: rendered template as string or json dict """ if request.args.get('action') == 'checkpath': if os.path.exi...
cda30d64a5294b30716cfa35598efcf29bbb969d
51,464
def get_attrib_recursive(element, *attribs): """Find the first attribute in attribs in element or its closest ancestor that has any of the attributes in attribs. Usage examples: get_attrib_recursive(el, "fallback-langs") get_attrib_recursive(el, "xml:lang", "lang") Args: elemen...
d04ba71a280bd1697cc61b79af21df46023473d2
51,465
def _antisymmetricity_score(v_1: float, v_2: float, coef_lambda: float): """ degree of the anti-symmetry between two values. z = exp(-\lambda*d(v_1,v_2)) d(v_1,v_2) = |v_1 + v_2| :param v_1: a value :param v_2: another value :param lambda: exponential decay parameter. :return: z """ ...
8e8912cae7b009a27303a33a79c30898da7ac88f
51,466
def find_extra_inferred_properties(spec_dict: dict) -> list: """Finds if there are any inferred properties which are used. Args: spec_dict: Dict obj containing configurations for the import. Returns: List of properties that appear in inferredSpec but are not part of 'pvs' section. """ re...
3be2950a227cfca8d0ab4c4413322f8aa8b22cc0
51,467
import time def signup(driver, Users, ISAAC_WEB, WAIT_DUR, **kwargs): """Test whether users can sign up to Isaac using an email address. - 'driver' should be a Selenium WebDriver. - 'Users' must be a TestUsers object. - 'ISAAC_WEB' is the string URL of the Isaac website to be tested. ...
1f9cfd19c48984c93cf721033e0218fbb1463153
51,468
import torch def collate(data, tokenizer, block_size, device): """ Collate formats the data passed to the data loader. In particular we tokenize the data batch after batch to avoid keeping them all in memory. We output the data as a namedtuple to fit the original BertAbs's API. """ data = [x f...
bb5b04bf69b33f033570910020dc4985f93670e4
51,469
def _read_json(nc): """ This is easily the laziest piece of code in this library. In the future, I want to modify this to be a simple CFG parser to identify valid JSON, but in the meantime, performance wasn't my priority, and this gets the job done. """ json_str = '' last_char = '' whil...
11f5e7259d106044f5fd0d33711c367b92dba96c
51,470
def zeroDistanceByFit(analysis, axis='y', useTrap='pm'): """ Find the trap distance at which the beads touch and use this as an offset to calculate the extension. Args: analysis (:class:`.TweezersAnalysis`): analysis file to check axis (str): axis on which to do the correction, either 'y' (...
89c7906a166dc3d66e58f74da65b3b1df697300f
51,471
def log_file_path(): """ Provides the path where tor's log file resides, if one exists. :returns: **str** with the absolute path of tor log file, or **None** if one doesn't exist """ controller = tor_controller() for log_entry in controller.get_conf('Log', [], True): entry_comp = lo...
b485955858b55c14f88a5349be46204ec85eebaa
51,472
def topics(request): """显示所有的主题""" topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context)
b31f6094d8a138e681414c7518dd746c0bcf924f
51,473
def parse_styles(node, source): """Return the Styles represented by node.""" styles = [] for style_type, value in node.items(): if style_type == 'opacity': amount = value opacity = Opacity(amount) styles.append(opacity) elif style_type == 'fill': ...
fabc31affab80001cd5310a2c33396a74607aeee
51,474
def moveYaxis(board, way): """ Function used to move in list on y axis a.k.a. vertical axis. """ if(way == "up"): new_board = turn(sanitizey(board, "up")) for i in range(len(new_board)): for j in range(len(new_board)): if(new_board[i][j] in powers_of_two and...
6c6fddea84f6b7ecda5b5ec330dd6d2b1b4b5a77
51,475
import numpy def calculate_idf(list_books): """ IDF = ln((total_numbers of docs)/(number of docs in which the word is present)) :param list_books: list of the all the books :return: IDF of all the books """ total_documents = len(list_books) # total number of documents master_map = {} ...
294d4a437b2899c601f6269b4a6837595c73f83c
51,476
def _PreprocessComponentCond( cnxn, cond, project_ids, services, harmonized_config): """Preprocess a component= or component:name cond into component_id=IDs.""" exact = _IsEqualityOp(cond.op) component_ids = [] if project_ids: # We are searching within specific projects, so harmonized_config # holds...
a3f069bb052526981e864b4d37668817fd9c22fd
51,477
import math def attention_layer(input_tensor, attention_mask, num_attention_heads, size_per_head, query_act, key_act, value_act, attention_dropout_prob, initi...
6b895ac068291fded7a89bf5fe6ce934f0640e2d
51,478
import re def _GetAssetName(args): """Prepares asset relative path using organization and asset.""" resource_pattern = re.compile("organizations/[0-9]+/assets/[0-9]+") id_pattern = re.compile("[0-9]+") assert resource_pattern.match(args.asset) or id_pattern.match(args.asset), ( "Asset must match either ...
3963454569a63426d49ff81735cfd9243f1c4976
51,479
import argparse def main(argv=None): """Entry point""" parser = argparse.ArgumentParser( description="Test matplotlib's plot3d with a flowing data feed") parser.add_argument( '-a', '--animate', dest='method', action='store_const', const=METHOD_ANIMATE, help="use matplotlib....
a952078e20d19ae869029e77ca1aeaa1a4069068
51,480
import math def get_antithetic_slices(shape: tp.Sequence[int], antithetic_dimension: int) \ -> tp.Tuple[slice, ...]: """ This function generates a tuple of slices to index the original array of random numbers to take either half or one less than half of the the original ...
d2668b0edbc7c45b1b586065712f5b07d1a69e2f
51,481
import unicodedata def unquote(string, charset="utf-8"): """Unquote and normalize unicode string. Params: string : string to be unquoted charset : string : optional : output encoding Returns: string : an unquoted and normalized string """ string = unquote_orig(string) ...
03f79e0a960d582541bb9ee22d25f3b5c2783c31
51,482
from typing import List from typing import Dict from typing import OrderedDict def calculate_panelist_losing_streaks(panelists: List[Dict], database_connection: mysql.connector.connect): """Retrieve panelist stats and calculate their losing streaks""" losing_streaks = []...
459cd3836116bf71825a1934b2ae0082241513e3
51,483
def find_corresponding_basins(pfaf_id_level6,gdf_level7): """ Using a pfaf_id from level 6, find all hydrobasins in level 7 that make up the hydrobasin level 6 polygon. """ pfaf_id_level7_min = pfaf_id_level6*10 pfaf_id_level7_max = pfaf_id_level7_min + 9 gdf_level7_selection = gd...
d8952abfb681fc2b1c33d53b930fff6c56f6bc0a
51,484
def downsize_storm_images( storm_image_matrix, radar_field_name, num_rows_to_keep=None, num_columns_to_keep=None): """Downsizes storm-centered radar images. :param storm_image_matrix: See doc for `_check_storm_images`. :param radar_field_name: Same. :param num_rows_to_keep: Number of ro...
fc064eb55f793dfa09071b406c601c67ee2a0442
51,485
def apply_tile_blur(tile, circle_blur): """ Blur the classification tile by radial distance from robot. (Less confident in pixels "further" away) Inputs: tile: Classification tile (nparray 3 chan RGB) circle_blur: "kernel" tile of same shape, with circular gradient (1 in center, fades...
ebd628592bd1c86c0c795b87f279c3a667d9e6ab
51,486
from .simul.ngNRC import slope_to_ramp import traceback def gen_fits(args): """ Helper function for generating FITs integrations from a slope image """ # Must call np.random.seed() for multiprocessing, otherwise # random numbers for parallel processes start in the same seed state! np.random....
f48b74d8447f57d7c4e059f7356e80dd439afb6f
51,487
def gaussian_kernel(y,sigma=7): """ gaussian_kernel: Gaussian filter. Arguments: y (numpy array): input 2D map. sigma (float) (default=7): effective length of Gaussian smoothing. -------- Returns: kerneled image. """ return gaussian_filter(y, sigma)
0eb17843b9c4545ae59e48b01528c9c25961904a
51,488
import glob import os def get_vid_info_list(mode, img_path, keypoints_path, imgnums_txtfile, i, k=None): """ General function to create vid_info_list for all meta-learning datasets """ vids = glob.glob(keypoints_path + 'keypoints_*') n_vids = len(vids) vid_info_list = [] if mode == ModelMode.train: ...
d7f93937c8d53f033264dc155604506aacf7e47e
51,489
from typing import Tuple from typing import List def header(buffer: bytes, offset: int = 0) -> Tuple[bytes, str, List[int], int]: """ Unpack a Starbound header structure from the buffer at a given offset. :param buffer: buffer to read :param offset: offset in buffer :return: Starbound header ...
88e2c0392cda55941d100dbdaf26c26774f6b35f
51,490
import warnings def create_setting_analyzer_ranking( optimizer_path, mode="final", metric="valid_accuracies" ): """Reads in all settings in ``optimizer_path`` and sets up a ranking by returning an ordered list of SettingAnalyzers. Args: optimizer_path (str): The path to the optimizer to analyse. ...
c08f3aa310bfda1c77ed514d5affb5a3922231af
51,491
async def async_setup_entry(opp, entry): """Set up a smarttub config entry.""" controller = SmartTubController(opp) opp.data.setdefault(DOMAIN, {}) opp.data[DOMAIN][entry.entry_id] = { SMARTTUB_CONTROLLER: controller, } if not await controller.async_setup_entry(entry): return F...
d15d5a768b165a17382fbaf00ceb66751550f47d
51,492
def merge_dicts(idx, *args): """ Merges lists of dictionaries, by adding each other the values of corresponding dictionaries `args` can contain `None` values (except for the first one); in such case, that argument will be skipped; this is useful if a dataset contains annotations not for all the...
f51eb7a4e71d4cacacf3920189170df5f3a546a6
51,493
def send(signal, sender=dispatcher.Anonymous, *args, **kwargs): """ Sends a signal, causing connected handlers to be invoked. Parameters: :signal: Signal to be sent. This must be an instance of :class:`wa.core.signal.Signal` or its subclasses. :sender: The sender of the si...
4d1792451fae256d0218f9dd0df691294cd0bc01
51,494
import torch from typing import List from typing import Optional from typing import Dict def fp_fn_eval(query_features: torch.Tensor, query_labels: torch.LongTensor, ks: List[int], gallery_features: Optional[torch.Tensor] = None, gallery_labels: Opti...
5d9ab37b7ed3d2573f8242bf44a55ae9b8522208
51,495
import urllib import csv def backupFromGoogleSheet(fileUri): """Reads google spreadsheet file from given path and make sures backup is stored for listed reposities in the given fileUri. """ cloneCount = fetchCount = failCount = 0 sheetResponse = urllib.request.urlopen(fileUri) sheetLines = [l....
54823ae00b9b6c3492668bbb9f8973b67620ecda
51,496
import csv import codecs def get_row_iterator(iterable, options=None): """Accepts an interable, options and returns a csv.DictReader object which can be used to yield CSV rows.""" options = options or {} def get_csv_quoting(options): quoting = str(options.get('quoting', "MINIMAL")).upper() ...
256606bcda86e040602c8bdbe838a3fbf78fe018
51,497
def get_content_function_ratio(content, function): """ Calculate the content-function word ratio. """ ratio = float(len(content)) / float(len(function)) if len(function) != 0 else 0 return round(ratio, 4)
e82109ed1fd2a3f3136945c4598358efdc0985e9
51,498
def AdVm(context, machine_type, zone, image): """Creates a VM definition for the AD VM. This VM only has a single boot disk because it will not be a part of the cluster. Args: context: context of the deployment. machine_type: full path of the machine type. zone: The zone where the VM will reside. ...
6f3f10aba6f4417a4c0a12cb422011c8013d249d
51,499