content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def add(a,b): """ This function adds two numbers together """ return a+b
96173657034d469ea43142179cd408e0c1f1e12d
3,651,388
def decode_ADCP(data): """ Decodes ADCP data read in over UDP. Returns two lists: header and current. input: Raw data string from ADCP UDP stream Output: header: [timestamp, nCells, nBeams, pressure] - timestamp in unix format - nBeams x nCells gives dimensions of current data ...
07c5b430ac2321e4e47124e71c83bf8a2440f43f
3,651,389
def RowToModelInput(row, kind): """ This converts a patient row into inputs for the SVR. In this model we use RNAseq values as inputs. """ SampleID = row[TissueSampleRow(kind)] TrueSampleIDs = [r for r in TissueSamples.columns if r.startswith(SampleID)] if not TrueSa...
1167a7c47be7893252820087098db6e416f6c9bc
3,651,390
from datetime import datetime def str_to_timedelta(td_str): """Parses a human-readable time delta string to a timedelta""" if "d" in td_str: day_str, time_str = td_str.split("d", 1) d = int(day_str.strip()) else: time_str = td_str d = 0 time_str = time_str.strip() i...
dc3449c708ef4fbe689a9c130745d7ada6ac8f78
3,651,391
import cgi def filter_safe_enter(s): """正文 换行替换""" return '<p>' + cgi.escape(s).replace("\n", "</p><p>") + '</p>'
6091abec0ff87361f1bbe4d146c64ddef3cc99f0
3,651,392
def _full_rank(X, cmax=1e15): """ This function possibly adds a scalar matrix to X to guarantee that the condition number is smaller than a given threshold. Parameters ---------- X: array of shape(nrows, ncols) cmax=1.e-15, float tolerance for condition number Returns ------- X...
8f24509fb921877c9f1bcff09fc035285beee69e
3,651,393
from typing import Optional def create( session: Session, instance: Instance, name: str, description: Optional[str] = None, external_id: Optional[str] = None, unified_dataset_name: Optional[str] = None, ) -> Project: """Create a Mastering project in Tamr. Args: instance: Tamr ...
aac88500ecd60df9a1496e38e33bc212f3e26701
3,651,394
import random import time def users_with_pending_lab(connection, **kwargs): """Define comma seperated emails in scope if you want to work on a subset of all the results""" check = CheckResult(connection, 'users_with_pending_lab') # add random wait wait = round(random.uniform(0.1, random_wait), 1) ...
6136531c523cf344405cda42bbfcae1e4719280d
3,651,395
import pandas import types def hpat_pandas_series_lt(self, other, level=None, fill_value=None, axis=0): """ Pandas Series method :meth:`pandas.Series.lt` implementation. .. only:: developer Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_op8 Parameters ---------- ...
b22497f64b711f92bbdf472feba657bc9b49115a
3,651,396
def getBanner(host, port): """ Connects to host:port and returns the banner. """ try: s = socket.socket() s.connect((host, port)) banner = s.recv(1024) return str(banner).strip() except Exception, e: error(str(host) + ':' + str(port) + ' ' + str(e))
46d497067790ef19521f84345adb8c8369ca8737
3,651,398
from typing import List def create_cmd_table(table_data: List[List[str]], width: int = 15) -> BorderedTable: """Create a bordered table for cmd2 output. Args: table_data: list of lists with the string data to display width: integer width of the columns. Default is 15 which generally works for...
044630072f9927262673d65e9cfeadbd49d44f31
3,651,399
def get_parser(dataset_name): """Returns a csv line parser function for the given dataset.""" def inat_parser(line, is_train=True): if is_train: user_id, image_id, class_id, _ = line return user_id, image_id, class_id else: image_id, class_id, _ = line return image_id, class_id d...
4901dde39ef6af9cab1adeacb50fff7b90950cd6
3,651,400
import sqlite3 def one_sentence_to_ids(sentence, sentence_length=SENTENCE_LENGTH): """Convert one sentence to a list of word IDs." Crop or pad to 0 the sentences to ensure equal length if necessary. Words without ID are assigned ID 1. >>> one_sentence_to_ids(['my','first','sentence'], 2) ([11095, 121], 2) >>> on...
14bb42a5bbec7e05b28601903c8732c140bf92ed
3,651,402
def full_class_name(class_): """ Returns the absolute name of a class, with all nesting namespaces included """ return '::'.join(get_scope(class_) + [class_.name])
c2e7c0df1394d76a181677fcceec424a9bec1f4b
3,651,403
import math def mul_pdf(mean1, var1, mean2, var2): """ Multiply Gaussian (mean1, var1) with (mean2, var2) and return the results as a tuple (mean, var, scale_factor). Strictly speaking the product of two Gaussian PDFs is a Gaussian function, not Gaussian PDF. It is, however, proportional to a Gau...
8ecb925273cd0e4276b867687e81b0a26419f35f
3,651,404
def mean_squared_error(y_true, y_pred): """ Mean squared error loss. :param y_true: groundtruth. :param y_pred: prediction. :return: loss symbolic value. """ P = norm_saliency(y_pred) # Normalized to sum = 1 Q = norm_saliency(y_true) # Normalized to sum = 1 return K.mean(K.square(P...
9ecc02bfa6fc0417ea286a8f8195fdcc264c6593
3,651,405
def format_epilog(): """Program entry point. :param argv: command-line arguments :type argv: :class:`list` """ author_strings = [] for name, email in zip(metadata.authors, metadata.emails): author_strings.append('Author: {0} <{1}>'.format(name, email)) epilog = ''' {project} {versio...
ab1b378092006b3c4d7208e99c4a6ead41b528e4
3,651,406
from typing import List import difflib def text_differences(original_text: List[str], new_text_version: List[str]) -> TextDifferences: """ Builds text differences from input texts. Parameters ---------- original_text: List[str] original text (as a list of lines) new_text_version: List...
3f17489ac888714a2769e838e35a30384d76e961
3,651,408
import json async def delete_port(request : VueRequest): """ 删除端口的接口 :param: :return: str response: 需要返回的数据 """ try: response = {'code': '', 'message': '', 'data': ''} request = rsa_crypto.decrypt(request.data) request = json.loads(request) target = reque...
71a90d9e14f514bb65e7d47d4a63090be70af033
3,651,410
def get_start_indices_labesl(waveform_length, start_times, end_times): """ Returns: a waveform_length size boolean array where the ith entry says wheter or not a frame starting from the ith sample is covered by an event """ label = np.zeros(waveform_length) for start, end in zip(start_times, end...
39d264f837940e11b4d5e6897a93e30da234730d
3,651,411
def get_function_euler_and_module(): """ Function return tuple with value function euler and module. This tuple is namedtuple and we can use it this way: euler = tuple.euler module = tuple.module Thanks to this, we will not be mistaken. """ first_number_prime, second_number_prime...
0b44391c9b38cc5f04f2e5faa212542716543883
3,651,412
def _read_host_df(host, seq=True): """Reads the metrics data for the host and returns a DataFrame. Args: host (str): Hostname, one of wally113, wally117, wally122, wally123, wally124 seq (bool): If sequential or concurrent metrics should be read Returns: DataFrame: Containing all t...
5e2872816b0e9b77ccccd1ead03e3c9660c604f2
3,651,413
def compacify(train_seq, test_seq, dev_seq, theano=False): """ Create a map for indices that is be compact (do not have unused indices) """ # REDO DICTS new_x_dict = LabelDictionary() new_y_dict = LabelDictionary(['noun']) for corpus_seq in [train_seq, test_seq, dev_seq]: for seq in...
c695022c6216b035618342c0aaecc39d8337a84c
3,651,414
def obfuscate_email(email): """Takes an email address and returns an obfuscated version of it. For example: test@example.com would turn into t**t@e*********m """ if email is None: return None splitmail = email.split("@") # If the prefix is 1 character, then we can't obfuscate it if l...
36c230ed75fc75fc7ecd6dd2ea71a6b3310c4108
3,651,415
def list_small_kernels(): """Return list of small kernels to generate.""" kernels1d = [ NS(length= 1, threads_per_block= 64, threads_per_transform= 1, factors=(1,)), NS(length= 2, threads_per_block= 64, threads_per_transform= 1, factors=(2,)), NS(length= 3, threads_per_block= 64...
332c94c0957ddb438822574e416a37eaef09c5f6
3,651,416
def parse_boolean(arg: str): """Returns boolean representation of argument.""" arg = str(arg).lower() if 'true'.startswith(arg): return True return False
2f0a214212aa43a8b27d9a3be04f14af67c586bc
3,651,417
def ascending_coin(coin): """Returns the next ascending coin in order. >>> ascending_coin(1) 5 >>> ascending_coin(5) 10 >>> ascending_coin(10) 25 >>> ascending_coin(2) # Other values return None """ if coin == 1: return 5 elif coin == 5: return 10 elif coi...
e927d8ac3f38d4b37de71711ac90d6ca2151a366
3,651,418
def to_numpy(qg8_tensor): """ Convert qg8_tensor to dense numpy array """ dtype = dtype_to_name(qg8_tensor.dtype_id) ndarray = np.zeros(qg8_tensor.dims, dtype=dtype) if np.iscomplexobj(ndarray): ndarray[tuple(qg8_tensor.indices)] = np.asfortranarray(qg8_tensor.re)\ ...
808c42fd1a6a4488cef34876674a212231fc2979
3,651,419
def _get_results(report): """Limit the number of documents to REPORT_MAX_DOCUMENTS so as not to crash the server.""" query = _build_query(report) try: session.execute(f"SET statement_timeout TO {int(REPORT_COUNT_TIMEOUT * 1000)}; commit;") if query.count() == 0: return None e...
0575ec42c3b7cd729d4bc454986e02280ae4bb68
3,651,420
import warnings def text_match_one_hot(df, column=None, text_phrases=None, new_col_name=None, return_df=False, case=False, supress_warnings: bool=False): """Given a dataframe, text column to search and a list of text phrases, return a binary column with 1s when text is present and 0 o...
3db69fc6459dde7b14bbd1ae1507adc0b6c9a8b4
3,651,421
import six def pack_feed_dict(name_prefixs, origin_datas, paddings, input_fields): """ Args: name_prefixs: A prefix string of a list of strings. origin_datas: Data list or a list of data lists. paddings: A padding id or a list of padding ids. input_fields: The input fieds dict...
6de17aa1235d929fee20fcddcfcfb04e3907484b
3,651,422
from PyQt4 import QtGui def get_directory(**kwargs): """ Wrapper function for PyQt4.QtGui.QFileDialog.getExistingDirectory(). Returns the absolute directory of the chosen directory. Parameters ---------- None Returns ------- filename : string of absolute directory. """ f...
8b27ec800ccaa237d79e198d23058b70f71df4b8
3,651,423
def single_particle_relative_pzbt_metafit(fitfn, exp_list, **kwargs): """Fit to single-particle energies plus zero body term, relative to the first point """ return single_particle_metafit_int( fitfn, exp_list, dpath_sources=DPATH_FILES_INT, dpath_plots=DPATH_PLOTS, transform=rel...
81dfc60f1f27df710ccdb489ff322d576b8d9922
3,651,424
def hetmat_from_permuted_graph(hetmat, permutation_id, permuted_graph): """ Assumes subdirectory structure and that permutations inherit nodes but not edges. """ permuted_hetmat = initialize_permutation_directory(hetmat, permutation_id) permuted_hetmat = hetmat_from_graph( permuted_graph...
54728e3522f76e24d4a4107752980a57990c551d
3,651,425
import types def can_see_all_content(requesting_user: types.User, course_key: CourseKey) -> bool: """ Global staff, course staff, and instructors can see everything. There's no need to run processors to restrict results for these users. """ return ( GlobalStaff().has_user(requesting_user)...
c4de054b235da20074841e7225123ef73e7d4a16
3,651,426
def part2(steps, workers=2, extra_time=0): """ Time is in seconds """ workers = [Worker() for _ in range(workers)] steps_to_time = { step: alphabet.index(step) + 1 + extra_time for step in alphabet } time = 0 graph = build_graph(steps) chain = find_orphans(graph) while...
792c6ca6e5334491eb38d8549b6c9df41d101924
3,651,427
from typing import Any from typing import List from typing import Iterable def to_local_df(df: Any, schema: Any = None, metadata: Any = None) -> LocalDataFrame: """Convert a data structure to :class:`~fugue.dataframe.dataframe.LocalDataFrame` :param df: :class:`~fugue.dataframe.dataframe.DataFrame`, pandas D...
12aae7869067b14f2f0f8ffcb3e393f41db5114f
3,651,428
def create_local_meta(name): """ Create the metadata dictionary for this level of execution. Parameters ---------- name : str String to describe the current level of execution. Returns ------- dict Dictionary containing the metadata. """ local_meta = { '...
61a2ef73e8a6f74360881b97150a79079f3f8c29
3,651,429
def matches_uri_ref_syntax(s): """ This function returns true if the given string could be a URI reference, as defined in RFC 3986, just based on the string's syntax. A URI reference can be a URI or certain portions of one, including the empty string, and it can have a fragment component. """ ...
73b0dde1f76edcf4fe7f7754cc67d7604f984521
3,651,430
from datetime import datetime def get_end_hour(dt=None): """根据日期、或时间取得该小时59:59的时间;参数可以是date或datetime类型""" end = None if not dt: dt = datetime.date.today() if isinstance(dt, datetime.date): dt_str = dt.strftime("%Y-%m-%d %H") + ":59:59" end = datetime.datetime.strptime(dt_str, "...
73d2760cf085295e13a4699aaf3dd8aa9dd5ae49
3,651,431
def all_ped_combos_strs(num_locs=4, val_set=("0", "1")): """Return a list of all pedestrian observation combinations (in string format) for a vehicle under the 4 location scheme""" res = [] lsts = all_ped_combos_lsts(num_locs, val_set) for lst in lsts: res.append(" ".join(lst)) return res
4a87cf48da5fb9582c7d7284fc78471e84918256
3,651,432
def create_image( image_request: ImageRequest, background_tasks: BackgroundTasks, db: Session = Depends(get_db), ): """ (2) add database record (3) give background_tasks a reference of image record """ image = Images() image.url = image_request.image # image.output = "4" # <<<...
77042168b61262b832bdad438a4d6661cfb263d6
3,651,433
def get_key(rule_tracker, value): """ Given an event index, its corresponding key from the dictionary is returned. Parameters: rule_tracker (dict): Key-value pairs specific to a rule where key is an activity, pair is an event index value (int): Index of event in event log Returns: ...
1921e9a68d0df0867248ca83e2ba641101735fc7
3,651,434
def get_cxml(filename): """ Create and return CXML object from File or LocalCache """ cxml = Cxml(filename) return cxml
c2c440793ea4b509823dd0ad90677eb7db2696ff
3,651,435
def save_layer(index, settings) -> Action: """Action to save layer settings""" return {"kind": SAVE_LAYER, "payload": {"index": index, "settings": settings}}
8fde0e1c752455e386745f428a69ae4a9936c028
3,651,436
def request_user_input(prompt='> '): """Request input from the user and return what has been entered.""" return raw_input(prompt)
1c8507edb17977005e068abee90b84832354adaf
3,651,437
def get_clinic_qs(): """ Returns a list of clinic uuid values for clinics whose patients will receive follow up reminder messages """ q = Q() for clinic in MESSAGE_CLINICS: q = q | Q(name__iexact=clinic) return list(Clinic.objects.filter(q).values_list('uuid', flat=True))
8224db73bd14839b8db6e2ee4a77c1404d846e34
3,651,438
def NPnm(n, m, x): """Eq:II.77 """ return sqrt( (2*n+1)/2 * abs(nmFactorial(n,m)) ) * lpmv(m, n, x)
8444f8d3a56e62bf66c6c0a318641d212202438d
3,651,439
def all_columns_empty(): """All columns are empty ... test will demoonstrate this edge case can be handled""" return [[] for i in range(0, 100)]
77a354978f82fd61d0f4d12db57a7fc455f4af28
3,651,440
def ping(host, destination, repeat_count, vrf_name): """Execute Ping RPC over NETCONF.""" # create NETCONF provider provider = NetconfServiceProvider(address=host, port=830, username='admin', p...
b2486447a5c8e0c48a8420a2f8c7795d0eef68b8
3,651,441
def compute_shape_index(mesh) -> np.ndarray: """ Computes shape index for the patches. Shape index characterizes the shape around a point on the surface, computed using the local curvature around each point. These values are derived using PyMesh's available geometric processing functionality. P...
e7c84aeb39eaf7e752fe8e98d6519b342b22088a
3,651,442
from typing import Tuple def edit_frame(frame: ndarray, y: int) -> Tuple[ndarray, ndarray]: """ Parameters ---------- frame : (is row-major) y Returns ------- (frame, cut) """ np.random.uniform(-1, 1, size=20000000) # 20000000@6cores cut = cv.cvtColor(frame[[y], :], cv.CO...
30f2550839067eb837f38734a761f1f06e50db27
3,651,443
def get_location(uniprot_id: str) -> Location: # pragma: no cover """Queries the UniProt database for a subcellular location with the id `uniprot_id` and returns a `Location` object""" g: LocationRDF = get_location_graph(uniprot_id) return Location.from_location_rdf(g)
cbe77792023954095962eaa8d379518a6ee10027
3,651,444
import copy def _gaussian2d_rot_no_bg(p,x,y): """ Required Arguments: p -- (m) [A,x0,y0,FWHMx,FWHMy,theta] x -- (n x o) ndarray of coordinate positions for dimension 1 y -- (n x o) ndarray of coordinate positions for dimension 2 Outputs: f -- (n x o) ndarray of function values at position...
8f9433993ff4992c1d4d7fd5b36cd1ca57003f31
3,651,445
def queue_get_all(q): """ Used by report builder to extract all items from a :param q: queue to get all items from :return: hash of merged data from the queue by pid """ items = {} maxItemsToRetreive = 10000 for numOfItemsRetrieved in range(0, maxItemsToRetreive): try: ...
221700485ee10893bfd1e4e290523ed35cf21418
3,651,446
def sample_account(self, profile, company, **params): """Create and return a sample customer""" defaults = { "balance": 0, "account_name": "string", "account_color": "string" } defaults.update(params) return Account.objects.create( profile=profile, company=c...
6360d0b6a15592d42ffc7f9315181ae769812d4b
3,651,447
def get_funghi_type_dict(funghi_dict): """ Parameters ---------- funghi_dict: dict {str: list of strs} is the name: html lines dict created by get_funghi_book_entry_dict_from_html() Return ------------ dict {str: FunghiType} each entry contains a mushroom name and the corresponding ...
6fe891fe4f9766b7f8a78e9bd13950d5c6af264e
3,651,449
def default_error_mesg_fmt(exc, no_color=False): """Generate a default error message for custom exceptions. Args: exc (Exception): the raised exception. no_color (bool): disable colors. Returns: str: colorized error message. """ return color_error_mesg('{err_name}: {err_mes...
248d99d5d08f9499a2349e66b03e9ec6ab1557a4
3,651,450
def check_values_on_diagonal(matrix): """ Checks if a matrix made out of dictionary of dictionaries has values on diagonal :param matrix: dictionary of dictionaries :return: boolean """ for line in matrix.keys(): if line not in matrix[line].keys(): return False return Tru...
bc7979adcfb5dc7c19b3cdb3830cf2397c247846
3,651,451
def read_quantity(string): """ convert a string to a quantity or vectorquantity the string must be formatted as '[1, 2, 3] unit' for a vectorquantity, or '1 unit' for a quantity. """ if "]" in string: # It's a list, so convert it to a VectorQuantity. # The unit part comes after...
ab36a26425a4bbc236ac84a807707431d3c9dc14
3,651,453
async def stop_service(name: str) -> None: """ stop service """ task = TASKS.get(name) if task is None: raise Exception(f"No such task {name}") return task.cancel()
245f60e70dcce09147d83697128c525e3630f238
3,651,454
def rand_bbox(img_shape, lam, margin=0., count=None): """ Standard CutMix bounding-box Generates a random square bbox based on lambda value. This impl includes support for enforcing a border margin as percent of bbox dimensions. Args: img_shape (tuple): Image shape as tuple lam (float): ...
47fd5fa1f2530c198aad50e883ec57dbd60cb4db
3,651,455
from pathlib import Path def get_current_dir(): """ Get the directory of the executed Pyhton file (i.e. this file) """ # Resolve to get rid of any symlinks current_path = Path(__file__).resolve() current_dir = current_path.parent return current_dir
c0e6fa1300970226fce42bf57fe2d2ed6b3e3604
3,651,456
import csv def build_gun_dictionary(filename): """Build a dictionary of gun parameters from an external CSV file: - Key: the gun designation (e.g. '13.5 in V' or '12 in XI') - Value: a list of parameters, in the order: * caliber (in inches) * maxrange (maximum range in yard...
b9e38d766430d44b94ae9fa64c080416fdeb8482
3,651,457
def plot_learning_curve(estimator, title, X, y, ylim=None, cv=None, n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)): """ Generate a simple plot of the test and training learning curve. Parameters ---------- estimator : object type that implements the "fit" and "predict" metho...
903f3119338c7886a663aa9a0e173849811365f9
3,651,458
from bs4 import BeautifulSoup import requests def fetch_events_AHEAD(base_url='http://www.ahead-penn.org'): """ Penn Events for Penn AHEAD """ page_soup = BeautifulSoup(requests.get( urljoin(base_url, '/events')).content, 'html.parser') events = [] event_table = page_soup.find('div', ...
24dc865a1db2ff5361e8d502ab47d78de94b875b
3,651,459
import string def column_to_index(ref): """ カラムを示すアルファベットを0ベース序数に変換する。 Params: column(str): A, B, C, ... Z, AA, AB, ... Returns: int: 0ベース座標 """ column = 0 for i, ch in enumerate(reversed(ref)): d = string.ascii_uppercase.index(ch) + 1 column += d * pow(len(...
7a6f89fa238d3d47a1e45b2e83821dbd4e8b23f8
3,651,460
def cols_to_tanh(df, columns): """Transform column data with hyperbolic tangent and return new columns of prefixed data. Args: df: Pandas DataFrame. columns: List of columns to transform. Returns: Original DataFrame with additional prefixed columns. """ for col in columns:...
b24c5467fa3c38415c8a4a0ab399a3ab44f481e9
3,651,461
import numpy as np def stdev_time(arr1d, stdev): """ detects breakpoints through multiple standard deviations and divides breakpoints into timely separated sections (wanted_parts) - if sigma = 1 -> 68.3% - if sigma = 2 -> 95.5% - if sigma = 2.5 -> 99.0% - if si...
b243f1d4ba904cbc2fb0e46b37305c857fce0be1
3,651,463
def main(_, **settings): """ This function returns a Pyramid WSGI application. """ config = Configurator(settings=settings, route_prefix="/api") # Initialise the broadcast view before c2cwsgiutils is initialised. This allows to test the # reconfiguration on the fly of the broadcast framework ...
f47bdb2e551aabfb5d03c4eefd52ec37f875e55d
3,651,464
def GetVarLogMessages(max_length=256 * 1024, path='/var/log/messages', dut=None): """Returns the last n bytes of /var/log/messages. Args: max_length: Maximum characters of messages. path: path to /var/log/messages. dut: a cros.factory.device.device_types.Devi...
f615f60b8daf0ee21b7b932ee23a21573b5d0db5
3,651,466
def find_index(predicate, List): """ (a → Boolean) → [a] → [Number] Return the index of first element that satisfy the predicate """ for i, x in enumerate(List): if predicate(x): return i
0c6010b8b169b7bfa780ca03c0551f189bda892a
3,651,467
from typing import Callable from typing import Any from typing import Dict def logger( wrapped: Callable[..., str], instance: Any, args: Any, kwargs: Dict[str, Any] ) -> str: """Handle logging for :class:`anndata.AnnData` writing functions of :class:`cellrank.estimators.BaseEstimator`.""" log, time = kwar...
6fc9d5867d2f9ebbacb3fef902d4b4d84670e449
3,651,468
def search_front(): """ Search engine v0.1 - arguments: - q: query to search (required) """ q = request.args.get('q', None) if not q: return flask.jsonify({'status': 'error', 'message': 'Missing query'}), 400 res = dict() cursor = db.run(r.table(PRODUCTS_TABLE).pluck('sho...
8230cd0b304fce767dbd19d3073e05fe1e083928
3,651,469
def insert_rare_words(sentence: str) -> str: """ attack sentence by inserting a trigger token in the source sentence. """ words = sentence.split() insert_pos = randint(0, len(words)) insert_token_idx = randint(0, len(WORDS)-1) words.insert(insert_pos, WORDS[insert_token_idx]) return " "....
ca07dec0492bff7c843e073b1093a13a418052d4
3,651,470
def _can_be_quoted(loan_amount, lent_amounts): """ Checks if the borrower can obtain a quote. To this aim, the loan amount should be less than or equal to the total amounts given by lenders. :param loan_amount: the requested loan amount :param lent_amounts: the sum of the amounts given by lenders ...
6fd717f3d0e844752e07e9dd435ff72eaa4b34c9
3,651,471
def load_specs_from_docstring(docstring): """Get dict APISpec from any given docstring.""" # character sequence used by APISpec to separate # yaml specs from the rest of the method docstring yaml_sep = "---" if not docstring: return {} specs = yaml_utils.load_yaml_from_docstring(docst...
88c245f56bba10355e78c20eb421f865b054bdbe
3,651,472
import skimage.transform from skimage.measure import ransac def get_transform(V1, V2, pair_ix, transform=None, use_ransac=True): """ Estimate parameters of an `~skimage.transform` tranformation given a list of coordinate matches. Parameters ---------- V1, V2 : [N,2] arrays Coordi...
d68b0c639df48cad6278b021d7bdb347cfc0d0b0
3,651,474
def no_trajectory_dct(): """ Dictionary expected answer """ return ()
95cc96bbfb23e621511f99f4d19f1af5a31bcc0f
3,651,475
import json def transform_fn(net, data, input_content_type, output_content_type): """ Transform a request using the Gluon model. Called once per request. :param net: The Gluon model. :param data: The request payload. :param input_content_type: The request content type. :param output_content_t...
756eb7093c7c56ded15d24356ead8a08d3eea7e7
3,651,476
def superuser_required(method): """ Decorator to check whether user is super user or not If user is not a super-user, it will raise PermissionDenied or 403 Forbidden. """ @wraps(method) def _wrapped_view(request, *args, **kwargs): if request.user.is_superuser is False: ra...
7bab907af1be1e81448db660f7d05b42741015da
3,651,477
def _section_data_download(course, access): """ Provide data for the corresponding dashboard section """ course_key = course.id show_proctored_report_button = ( settings.FEATURES.get('ENABLE_SPECIAL_EXAMS', False) and course.enable_proctored_exams ) section_key = 'data_download_2' i...
159d3fb4e13979826dbf1e95baf85224b82aeba8
3,651,478
def tcache(parser, token): """ This will cache the contents of a template fragment for a given amount of time with support tags. Usage:: {% tcache [expire_time] [fragment_name] [tags='tag1,tag2'] %} .. some expensive processing .. {% endtcache %} This tag also supports ...
206bcaa5c11a33e2f2bfe19fa75f7abe07fbc9c2
3,651,480
def location_edit(type_, id_, location_name, location_type, date, user, description=None, latitude=None, longitude=None): """ Update a location. :param type_: Type of TLO. :type type_: str :param id_: The ObjectId of the TLO. :type id_: str :param location_name: The name o...
b4bd584423e66242a6919fbcf3defcdd431ae9d3
3,651,482
def G2(species_index, eta, Rs): """G2 function generator. This is a radial function between an atom and atoms with some chemical symbol. It is defined in cite:khorshidi-2016-amp, eq. 6. This version is scaled a little differently than the one Behler uses. Parameters ---------- species_index...
a98b6ee7f6ff602a9ac8003b4c7cf515580aa9a3
3,651,483
def convert_leg_pose_to_motor_angles(robot_class, leg_poses): """Convert swing-extend coordinate space to motor angles for a robot type. Args: robot_class: This returns the class (not the instance) for the robot. Currently it supports minitaur, laikago and mini-cheetah. leg_poses: A list of leg poses...
7d71edd6dede2e523a3b61b48ff291924ce9df23
3,651,484
def get_all_records(session): """ return all records """ result = session.query(Skeleton).all() skeletons = convert_results(result) return skeletons
7a5205a40afdff943e9ad15636e41563059fd8ee
3,651,486
import scipy def pwm_to_boltzmann_weights(prob_weight_matrix, temp): """Convert pwm to boltzmann weights for categorical distribution sampling.""" weights = np.array(prob_weight_matrix) cols_logsumexp = [] for i in range(weights.shape[1]): cols_logsumexp.append(scipy.special.logsumexp(weights...
f7dac6149660b230986682d6e52d5455708c1fcb
3,651,487
def mutation_delete_music_composition(identifier: str): """Returns a mutation for deleting a MusicComposition. Args: identifier: The identifier of the MusicComposition. Returns: The string for the mutation for deleting the music composition object based on the identifier. """ retur...
64f4f2cba056e96d7c63ac2672d5613e3009c380
3,651,488
from astroquery.gaia import Gaia import warnings def coords_from_gaia(gaia_id): """Returns table of Gaia DR2 data given a source_id.""" warnings.filterwarnings('ignore', module='astropy.io.votable.tree') adql = 'SELECT gaia.source_id, ra, dec FROM gaiadr2.gaia_source AS gaia WHERE gaia.source_id={0}'.form...
6177a846528003f56c82451622c671c100f5ea71
3,651,489
from random import shuffle, random import numpy as np def partition(smilist,ratio=0.7): """ A function to create test/ train split list :param smilist: smiles (list) :param ratio: test set split fraction (float) Return type: traininglist, testlist (list) """ shuffle(smilist, random) t...
6dbfa6ecdf543c03ecac210e634aaaeee68a6979
3,651,490
def align(reference, query): """ do a pairwise alignment of the query to the reference, outputting up to 10000 of the highest-scoring alignments. :param reference: a STRING of the reference sequence :param query: a STRING of the query sequence :return: a list of up to 10000 Alignment objects """...
a10d9a5ade48fb11c8a8b497c6ef764115c9843d
3,651,491
import re def output_name(ncfile): """output_name. Args: ncfile: """ ncfile_has_datetime = re.search('[0-9]{4}-[0-9]{2}-[0-9]{2}_[0-9]{2}', ncfile) if ncfile_has_datetime: forecast_time = ncfile_has_datetime.group() else: raise Exception("ncfile doesn't have datetime ...
81d04e9fe572e6ba2eb97506d4690818008a1aaf
3,651,492
def _replacement_func_decorator( fn=None, name=None, help="", args=None): """ Replaces xlo.func in jupyter but removes arguments which do not make sense when called from jupyter """ def decorate(fn): spec = _FuncDescription(fn, name or fn._...
92ab0a28107bfb88e8cf1084e07e252bd5994388
3,651,493
def stress_x_component(coordinates, prisms, pressure, poisson, young): """ x-component of the stress field. Parameters ---------- coordinates : 2d-array 2d numpy array containing ``y``, ``x`` and ``z`` Cartesian cordinates of the computation points. All coordinates should be in mete...
f47b8e6301964454b85e5a124db642708ba7abf6
3,651,494
def process_time_data(flag, last_time, model_params_dict_raw, time_data_raw): """ This is a helper function that takes the raw time data from the model file and replaces it with the correct value in the params file. :param flag: :param last_time: :param model_params_dict_raw: :param time_da...
6684ba352f2a339029581816ac72690c26dd8a73
3,651,495
def create_pos_data(data, parser): """ creating the positive fh numeric dataset. performing another cleaning. :param data: suspected fh examples :param parser: parser used for the word tokenization :return: all positive examples (after the cleaning), will be used for creating the negat...
a55b43f9d953284494629b4f4bc6f6901be0f865
3,651,496
async def absent(hub, ctx, name, resource_uri, connection_auth=None, **kwargs): """ .. versionadded:: 2.0.0 Ensure a diagnostic setting does not exist for the specified resource uri. :param name: The name of the diagnostic setting. :param resource_uri: The identifier of the resource. :param ...
ed97a9d765e8bda566b85b2bc22a585f02378dff
3,651,497
def get_ngrok() -> str or None: """Sends a `GET` request to api/tunnels to get the `ngrok` public url. See Also: Checks for output from get_port function. If nothing, then `ngrok` isn't running. However as a sanity check, the script uses port number stored in env var to make a `GET` request. ...
51cc61f3aea7f0ffc8d21284548df50e3e77d2b6
3,651,498
def contacts_per_person_symptomatic_60x80(): """ Real Name: b'contacts per person symptomatic 60x80' Original Eqn: b'contacts per person normal 60x80*(symptomatic contact fraction 80+symptomatic contact fraction 60\\\\ )/2' Units: b'contact/Day' Limits: (None, None) Type: component b'' ...
bf887237e77ffe0c3cb39a12285904f14ca14dd2
3,651,499