content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _detects_peaks(ecg_integrated, sample_rate): """ Detects peaks from local maximum ---------- Parameters ---------- ecg_integrated : ndarray Array that contains the samples of the integrated signal. sample_rate : int Sampling rate at which the acquisition took place. ...
ab9dd461f65095f048942ab8b8c069c456ea4933
59,306
def FixedRate_ReadFileAdapter_Carousel(readmode = "bytes", **rateargs): """A file reading carousel, that reads at a fixed rate. Takes filenames on its inbox """ return Graphline(RC = RateControl(**rateargs), CAR = ReusableFileReader(readmode), link...
b25735924841c61507e205e7249501dd849dfe70
59,307
def get(id, user=None): """# Retrieve a specific DictKey Receive a single DictKey object by its id ## Parameters (required): - id [string]: DictKey object unique id and PIX key itself. ex: "tony@starkbank.com", "722.461.430-04", "20.018.183/0001-80", "+5511988887777", "b6295ee1-f054-47d1-9e90-ee57b74f60...
f7cfc8bb94a1bdec437ce4387285de0f08c16c21
59,308
import re def pascal2title(string: str) -> str: """Splits on whitespace between capital and lowercase letters.""" # https://stackoverflow.com/a/29922050 return " ".join(re.findall(r"[A-Z](?:[a-z]+|[A-Z]*(?=[A-Z]|$))", string))
c91019552d1d0a3e58b65b3d2d84ec78a48fec52
59,309
def _topological_sort(data, head, top_node, raise_exception=False, result=None, visited=None): """ Internal function """ if not result: result = [] if not visited: visited = [] deps = data.get(head, list()) if head in visited: if head == top_node and raise_exception: ...
e20d4a62278b978489d708a77324a443b6199c5c
59,310
from typing import List from typing import Tuple async def _compile_filters_devs(for_sets: List[ForSetDevelopers], request: AthenianWebRequest, account: int, meta_ids: Tuple[int, ...], ) -> ...
2ce1491dd606c3c718977d41ca25ec97f8fc5f3e
59,311
import copy def flatten_samplesets(samplesets): """ Takes a list of SampleSets (with one or multiple samples in each SampleSet) and returns a list of SampleSets (with one sample in each SampleSet) Parameters ---------- samplesets: list of SampleSets Input list of SampleSets (with one o...
d89c5b58db69caa7570088fbfae4d7e414c5b9af
59,312
import torch def center_conv_point(bboxes, kernel_size=3, c_min=0, c_max=1, v3_form=False): """In a parallel manner also keeps the gradient during BP""" #bboxes.clamp_(min=c_min, max=c_max) if v3_form: base = torch.cat([bboxes[:, :2][:, (1, 0)]] * (kernel_size ** 2), dim=1) else: base ...
a5b14c544525672f8f47fbdbb31a1ccb96ff8e8b
59,313
def lambda_curry2(func): """ Returns a Curried version of a two-argument function FUNC. >>> from operator import add >>> curried_add = lambda_curry2(add) >>> add_three = curried_add(3) >>> add_three(5) 8 """ "*** YOUR CODE HERE ***" return lambda x: lambda y: func(x,y)
bb524c02756c57dcb82ce9dbf722113b7314871d
59,314
def get_trailer_offset(line_list): """Determine the line number where coordinates end.""" i = 0 for i, line in enumerate(line_list): if match_trailer.match(line): break return i
b87c73baecafd829ebde353c6dd3bae35f8a13bb
59,316
def cosine_similarity_sklearn(x, y): """ :param x: :param y: :return: """ result = cosine_similarity(np.array(x).reshape(1, -1), np.array(y).reshape(1, -1)) return result[0][0]*100
d5c2d2b0998787a58cc202bb8dde96fda38aeb27
59,317
def calcPubChemFingerPart2(mol):# 116-263 """ *Internal Use Only* Calculate PubChem Fingerprints (116-263) """ bits=[0]*148 bits=func_1(mol,bits)[1] bits=func_2(mol,bits)[1] bits=func_3(mol,bits)[1] bits=func_4(mol,bits)[1] bits=func_5(mol,bits)[1] bits=func_6(mol,bits)[1] ...
cf0d47671544bd9ff1db8339e28a1214e15b5493
59,318
def auto_type_convert(value): """Try to convert 'value' to a int, float, or bool. Otherwise leave as a string. This is done recursively with complex values.""" if value is None: return None if isinstance(value, list): return [auto_type_convert(item) for item in value] elif isinstan...
1fe873dca7017d25128c30cc5144c3cf890319a1
59,319
def norm_get_dly(): """Get all daily climate normals data""" prcp = norm_get_dly_prcp() snow = norm_get_dly_snow() tavg = norm_get_dly_tavg() tmax = norm_get_dly_tmax() tmin = norm_get_dly_tmin() by = ["id", "month", "day"] df = pd.merge(prcp, snow, how="outer", on=by) df = pd.merge(...
1894ca46bbc1853fc2d0952a85e36a62c64a3a85
59,321
def allowed_with_lowinverse(solution: Solution, other: Solution) -> bool: """Returns True if other can be combined with solution; Otherwise, False. Args: solution (Solution): a Solution with rule=Rule.Lowinverse. other (Solution): a Solution. Requires: 1. solution must have rule=Ru...
af6a8ee81079a4e57ecb7e57d9ff992b20aaadb0
59,322
import requests def _create_upload_url(auth_control, name, size, ht_space='user', ht_space_id=None, ht_id_path=ID_ROOT_PATH, metadata=None): """ Create an upload URL to use to upload a file. Parameters ---------- auth_control HTAuthorizationCo...
7f5d67f663dbca71f995fd3a0b7ac6c006000e97
59,324
def string(commands, data, node): """ Компиляция выражения "строка" """ commands.add(Push, 0) for character in node.characters: commands.add(Push, ord(character)) commands.add(Push, len(node.characters)) StringCompiler.store(commands, data) return commands.set_and_return_type(Types.STR...
eb9ca1a6774553918e285ffc39bea6fc8515c922
59,325
import json def master_serializer(resource): """Function to return a resource json""" data = resource.serialize() user_json = json.dumps( data, default=datetimeconverter, sort_keys=True ) return user_json
1d1ea730a0bb54963960016d945d09d871122dbd
59,326
import itertools def normalise_text(text): """ Removes leading and trailing whitespace from each line of text. Removes leading and trailing blank lines from text. """ stripped = text.strip() stripped_lines = [line.strip() for line in text.split("\n")] # remove leading and trailing empty li...
52ab40cfa4c39ed194fa71aa28d70f5fa737d70c
59,327
def global_precision(actual, predicted, k = 5): """ Computes global precision for recommendation systems using actual items and predicated items at k If the argument `k` isn't passed in, the default k 5 is used. Parameters ---------- actual : list A list of lists of...
b3f0f78e04aa5595cea9ee2789278c0372c86e28
59,328
def export_module_part(request, pk): """ Creates an excel sheet that contains all tests that are in a course. Used mainly to download sign off excel sheets. :param request: Django request :param pk: Module part ID :return: A file response containing an .xlsx file. """ module_part = get_object_...
70b443314c7c041231ab0f3dddb145990ccaa8d3
59,329
import re import string def stdtextpreprocessing(text): """ Desc: Text preprocessing of social media text using typical text cleaning methods such as lowercasing, removal of mentions, etc. Input: text (string) - text to be cleaned Output: text (string) - cleaned text """ # Instantiate wordnet le...
b7319ddca4c629aa77e34cd4220cc00b8c9bf0d0
59,330
def dedispersion_plan(nchan, dmmin, dmmax, start_freq, bandwidth, sample_time): """ Examples -------- >>> tDM = dedispersion_plan(10, 0, 10, 1400, 128, 0.0005) >>> np.isclose(tDM[0], 0) True >>> np.isclose(tDM[-1], 10., atol=1) True """ # dfreq = bandwidth / nchan stop_freq =...
2cb09d31cd581e10593710c48096aac0e9bc1e65
59,331
def RMSpropConfig(argument_parser): """ Set CLI arguments :param argument_parser: argument parser :type argument_parser: ```ArgumentParser``` :returns: argument_parser :rtype: ```ArgumentParser``` """ argument_parser.description = """Implements RMSprop algorithm. Proposed by G. Hinton...
733faf8005c5260ee2443fe6d42bfb85c3ba5979
59,332
def create_from_input(fluid: Fluid, filename=""): """Adds Density and Velocity to a Fluid from an input file. Args: fluid (Fluid): The Fluid object to be modified. filename (str, optional): The name of the file to be read without the extension. Defaults to "". Returns: [str, str, l...
3c4a3f99cb26b12d40185b3ac268e033bd66a0d7
59,333
def remove_stale_events(data): """ Parse an event dictionary and remove transitions to the same state: .. code:: event_dict = { (entity_id, cohort interval) : [(time, state), ..., (time, state)] (entity_id, cohort interval) : (time, state), ..., (time, state)] } :para...
be80965efc7077e06d6e9b2ab5fb8ddc65df79a9
59,334
def get_L_dashdash_ba2_d(L_dashdash_ba2_d_t): """# 1日当たりの浴槽追焚時における太陽熱補正給湯負荷 (MJ/d) Args: L_dashdash_ba2_d_t(ndarray): 1時間当たりの浴槽追焚時における太陽熱補正給湯負荷 (MJ/h) Returns: ndarray: 1日当たりの浴槽追焚時における太陽熱補正給湯負荷 (MJ/d) """ return np.sum(L_dashdash_ba2_d_t.reshape((365, 24)), axis=1)
0ba4ef903ef69cb755eeee657e1eb9d6c72f6ead
59,335
def im2col_indices(x, field_height, field_width, padding=0, stride_y=1, stride_x=1): """ An implementation of im2col based on some fancy indexing """ # Zero-pad the input p = padding x_padded = np.pad(x, ((0, 0), (0, 0), (p, p), (p, p)), mode='constant') k, i, j = get_im2col_indices(x.shape, field_height, fi...
717fae3eec42b5514f912be8abb71cc8b0f2c821
59,336
import sqlite3 def sqlite3get_table_names(sql_conn: sqlite3.Connection): """For a given sqlite3 database connection object, returns the table names within that database. Examples: >>> db_conn = sqlite3.connect('places.sqlite')\n >>> sqlite3get_table_names(db_conn)\n ['moz_origins', 'm...
0cb1ba2ba475268d39fef8bdbe044436f51c4f07
59,339
def add_eDOO_to_summary(df, delay_don=3, delay_dpl=2, blur=1): """Add eDOO column - estimated DOO - to summary dataframe. Also add sDON and sDPL columns, which are estimated shifted DON/DPL values (with blurring). Parameters: - delay_don: assumed delay (days) from date of notification -> day of o...
7331f559d9933c617b044c1bba695c3435ba4215
59,340
from operator import and_ def vulns_by_product(vendor_id=None, product_id=None): """View vulns associated to product.""" if product_id is None or product_id is None: return abort(404) nvd_ids = ( db.session.query(Cpe.nvd_json_id) .filter(and_(Cpe.vendor == vendor_id, Cpe.product ==...
51041bdcb193b956deac619176e70b6e08a76912
59,341
def calc_hcore_matrix(Tuv_, Vuv_): """ calc_hcore_matrix - Computes the 1 electron core matrix Arguments: Tuv_: The Kinetic Energy 1e integral matrix Vuv_: The Nuclear Repulsion 1e integrals matrix Returns: h_core: The one electron hamiltonian matrix """ h_core = Tuv_ +...
5c2dbd61b938a235f6c11b7647e157777fa18428
59,342
def _fit_lines(spectrum, model, fitter=fitting.LevMarLSQFitter(), exclude_regions=None, weights=None, window=None): """ Fit the input model (initial conditions) to the spectrum. Output will be the same model with the parameters set based on the fitting. spectrum, model -> model Par...
84bddc75c562bf9df44269c9b687a0212b512f8e
59,343
def rivm(path="rivm/report.csv", **kwargs): """ DataFrame: Daily new cases from RIVM (Netherlands) PDF report. """ kwargs.setdefault('parse_dates', ['date']) kwargs.setdefault('index_col', 'date') return ( read_csv(DATADIR / path, **kwargs) .rename_axis(None).sort_index(axis=1) ...
d7117d9d33009c0f2915149c1f9db68913ceb1cb
59,344
def vector(x, y, z): """ Make a 3-vector from components x, y, z : vector components """ return tf.stack([x, y, z], axis=0)
4e7ddb6a9f0de0ddfc8f72e4a874465d0075e080
59,345
def _to_sequence_example(image, decoder, vocab, config): """Builds a SequenceExample proto for an image-caption pair. Args: image: An ImageMetadata object. decoder: An ImageDecoder object. vocab: A Vocabulary object. Returns: A SequenceExample proto. """ with tf.gf...
cdd8a0d6a1ec3a16e46a0dd2ab9828754f190f26
59,346
def _improve_answer_span(doc_tokens, input_start, input_end, tokenizer, orig_answer_text): """Returns tokenized answer spans that better match the annotated answer.""" # tok_answer_text = " ".join(tokenizer.tokenize(orig_answer_text)) tok_answer_text = " ".join([sw for w in whitespace_tokenize(orig_answer_t...
10ed5493260ba9f2fba51d3f0b3509ee35e4f684
59,347
def _step_const_v_1d(dt, x0, v, x_lim): """ Evaluate daisy pattern step at `x0` with step `dt`. Parameters ---------- dt : The step size. x0 : The initial position, signed. v : The velocity, signed x_lim : The limit of x such that -x_lim < x < x_lim. ...
36dfd7cff56d3e69d58a121b6977080ebd3c8b00
59,348
def get_confusion_matrix_intersection_mats(groundtruth, predicted): """ Returns a dictionary of 4 boolean numpy arrays containing True at TP, FP, FN, TN. """ confusion_matrix_arrs = {} groundtruth_inverse = np.logical_not(groundtruth) predicted_inverse = np.logical_not(predicted) confusion...
ad7a3351f18a412894ce6261f7cba57acc90bb18
59,349
def run_command(runtime, timeout=0.01): """ Run a command, read stdout and stderr, prefix with timestamp. The returned runtime contains a merged stdout+stderr log with timestamps http://stackoverflow.com/questions/4984549/merge-and-sync-stdout-and-stderr/5188359#5188359 """ PIPE = subprocess.PI...
d66f8769e407417c24ffca74baf22368f760a233
59,350
from pathlib import Path def parse_uri_path(uri: str) -> str: """Parse a URI starting with 'file:///' to a posix path.""" return Path(url2pathname(urlparse(unquote(uri)).path)).as_posix()
d5a35fad0388d2b534f871d985a590159b3f1927
59,351
def make_key_frames(): """ make key frames for the regions """ key_frames = {} key_frames[0] = [100, 200, 300] key_frames[1] = [50, 150] return key_frames
3b551b7bb7fb22fab8e35abc54b2c524bdfa36fd
59,352
from typing import Dict def get_registered_commands() -> Dict[ str, Command ]: """ Gets the registered commands. """ global _lock, _plugin_importer with _lock: if _plugin_importer is None: _plugin_importer = PluginImporter( plugins ) _plugin_importer.import_module...
39eafb0c13f1c1face66e7bbcc72943a8ec89291
59,353
def _get_cov_blocks_ordering(probes): """ Utility function to get the ordering of the covariance matrix blocks """ cl_index = _get_cl_ordering(probes) def find_index(a, b): if (a, b) in cl_index: return cl_index.index((a, b)) else: return cl_index.index((b, a...
660d255c6426172486914a0efe2d53f502b0e43c
59,354
def use_uber_files(ctx, section_name, option_name, value): """ Configure the usage of UberFiles """ if not _is_user_input_allowed(ctx, option_name, value): Logs.info('\nUser Input disabled.\nUsing default value "%s" for option: "%s"' % (value, option_name)) return value info_str = ['UberFil...
5dc44c03268dbacca11132f01623653088922269
59,355
from typing import List def _generate_list_of_keywords_to_prepend( keywords_visible_to_user: List[str], keywords_not_visible_to_user: List[str], title: str, language: str) -> List[str]: """Determines which performant keywords need to be prepended and sorts them. Args: keywords_visible_to_user: ke...
ba9e1811d75a75bbee465f663706b3226f1f67f5
59,357
import re def cal_re(raw_trajs: list, final_trajs: list, min_latitude: float, min_longitude: float, len_latitude: float, len_longitude: float, epsilon: float) -> float: """ calculate RE Args: raw_trajs : original trajectory final_trajs : generated trajectory min_la...
07b34a7a932dcb47c0c05214cc3b31db1eac4160
59,359
def initialize_empty_command(help=None, formatter_class=None): # pylint: disable=redefined-builtin """ Initialize empty command with script for tests """ script = Script() command = EmptyCommand(script) # pylint: disable=redefined-builtin script.add_subcommand(command, help=help, formatter...
f7d37c9cdc67138c8497abc48ffecb1337bd9dd8
59,360
from typing import List from typing import Any def sort(xs: List[Any]) -> List[Any]: """ Sort the list `xs` with the python `sort` function and return the sorted function. The given list is not modified. Parameters ---------- xs A list. Returns ------- xs_sorted ...
706190a533c19b6a7ea4baf540823ca73406560b
59,361
def _parse_chained_types(ctxt, node): # type: (errors.ParserContext, yaml.nodes.MappingNode) -> List[syntax.ChainedType] """Parse a chained types section in a struct in the IDL file.""" chained_items = [] field_name_set = set() # type: Set[str] for [first_node, second_node] in node.value: ...
605fa7c45fcce3dbc3e7bb1aa37d3648553ea636
59,362
def sameQ(v1, v2) -> bool: """Mathics SameQ""" return get_type(v1) == get_type(v2) and v1 == v2
f7e00876cafeca6955a03f2e8836d7e76e87b60a
59,363
def read_from_file(file: str) -> list[list[str]]: """Read row data from the selected file.""" with open(file, 'r', encoding='utf-8') as read_file: csv = reader(read_file) return [row for row in csv]
f55da44817eea8c7fa01883947dead57c7a8b52e
59,364
def response_200(result=None): """GET에 대한 반환""" return { 'msg': 'success', 'result': result }, 200
2c2acbfed5ee678536671a367c67cc7d0b1fb6ba
59,365
def get_all_players(): """Returns a Dict with all players""" return {x.player_name: x for x in soco.discover()}
329ec97a1a91f62e5c2aec080c010736cff97336
59,366
def zernike(img, radius, degree=8, cm=None): """Zernike moments. This geometric moment derivate is based on alternative orthogonal polynomials, which makes it more optimal wrt. information redundancy. These are invariant to rotation. """ img = np.asarray(img, dtype=np.float32) assert img.nd...
dc206872a04900e553e83b52634fb71e13de6d46
59,367
def _list_agave(uri, agave): """ List contents of agave URI. Args: uri: parsed URI to list. agave: dict that contains: agave_wrapper: Agave wrapper object. Returns: On success: a list of filenames (basenames only). On failure: False. """ file_list =...
4c721f710b26687926a613a2346b19fc8fe18cf6
59,368
def overview_of_specific_year(request, year): """ Get the overview of a year """ data_of_year = DATA.get(str(year)) context_data = {} if not data_of_year: return Response({'error': f'Data not found for the year {year}'}, status=status.HTTP_400_BAD_REQUEST) else: context_data[...
fa1b67b75947e34fd85b00b46febc500d39a7554
59,369
import ast def unparse(tree: ast.AST): """`ast.unparse`, but cached.""" return ast_unparse(tree)
0690df059cb6c5f16c401e6474ba8bda6f9c8a6a
59,371
def limit(): """The number of corpus files to process, e.g ``--limit 100`.""" return '--limit 50'
45638e81c16cc9a89a7137566581b43d7e952f46
59,372
import regex def len_img_block(string): """ Length of image html blocks from a string. """ all_oc = regex.findall(r'<img\s[^<>]*+>', string) tot_len = 0 for oc in all_oc: tot_len += len(oc) return tot_len
73caeed3112164a4259a38b92b2041a8a0c6dfe4
59,373
def detect_noise(sp, spt, sp_win, type="positive", max_spikes=None, resample=1): """Find noisy spikes""" spike_waves = extract.extract_spikes(sp, spt, sp_win) if type == "positive": threshold = calc_noise_threshold(spike_waves, 1) spt_noise = extract.detect_spikes(sp, threshold...
f3159ef0ae7abd1612e04acaf9f9542bdce0baf5
59,374
import itertools def check_package_attributes(container, additional_requirements=[]): """ container may be a ConfigurationDescription or MetadataDescription additional_requirements are context-specific attributes to be required Returns an AttrErrorString of problems found. Caller can treat this like a...
064cc6e1aec3fcdf00c5e84fd187239d1c93d27b
59,375
def formatArrayTrinary(*arr, **kwargs): """Converts all elems to -1 (if elem < 0), 0 (if elem == 0), or 1 (if elem > 1) then formats the results as densely as possible. """ defaults = dict([ ('delimiter', ','), ('fmt', '%1d'), ('newline', '\n'), ('squeeze', False), ...
b0e75db41ecd8c44da5c6c6eeb1f788335bc282b
59,376
def protected_dict_attribute( types=(), subtypes=False, checked=None, module=None, factory=None, serialized=None, serializer=None, deserializer=None, represented=True, key_types=(), key_subtypes=False, key_factory=None, child=True, history=None, data=None, ...
b0e70405d039e479b06b7d7f58edb7a271b82a06
59,377
def getAllV2ELBs(): """ This function grabs each v2 elb from each region and returns a list of them. """ regions = boto3.client('ec2').describe_regions()['Regions'] logger.info(f"searching {len(regions)} region(s) for modern load balancers.") # get list of all load balancers in each region ...
9dcfe50a64d6e71af8b7e5800801604c03fbd06a
59,378
def class_is_meter_band(cls): """ Return True if cls_name is an instruction object """ return _unified_by_name(cls).is_instanceof("of_meter_band")
c417d3e09e1868ed68c838e6325341265cb93726
59,380
import re def GetRepositoryFromEbuildInfo(info): """Parse output of the result of `ebuild <ebuild_path> info` This command should return output that looks a lot like: CROS_WORKON_SRCDIR=("/mnt/host/source/src/platform2") CROS_WORKON_PROJECT=("chromiumos/platform2") """ srcdir_match = re.search(r'^CROS_...
dbc609f7d2c56f0d5e231cb0a1e2eb2ab7659f44
59,381
def train_input_fn(features, labels, batch_size): """An input function for training""" # Convert the inputs to a Dataset. dataset = tf.data.Dataset.from_tensor_slices((dict(features), labels)) # Shuffle, repeat, and batch the examples. dataset = dataset.shuffle(1000).repeat().batch(batch_size) ...
ac40034800e4b87670cb8e1d1ea508edcd178162
59,382
def add_pacient(ime, priimek, cepivo=None): """Funkcija v bazo vstavlja novega pacienta za sprejem v bolnišnico.""" return None
18d302d4a926d7af194850f68425137f5ef48968
59,383
def cloud_shadow_confidence(arr): """ 00 = "Not Determined" = Algorithm did not determine the status of this condition 01 = "No" = Algorithm has low to no confidence that this condition exists (0-33 percent confidence) 10 = "Maybe" = Algorithm has medium confidence that this condition exists (34-66 perc...
7b5afe6a5787b6ef03b3acbf7ef2abaa81497282
59,385
from datetime import datetime def load_sequence_and_metadata(kind="csv"): """ Returns the sequences as a list of SeqRecords, and metadata as a pandas DataFrame. """ starttime = datetime.now() sequences = [ s for s in SeqIO.parse("data/20170531-H3N2-global.fasta", "fasta") ] if ...
3c68327040debf0ca897185cdd5a63bf64c62ac9
59,386
def itmMatchingThree_collate(inputs): """Text-Image-Audio Matching dataset collate function""" (input_ids, img_feats, img_pos_feats, attn_masks, audio_feats ) = map(list, unzip(inputs)) # text batches txt_lens = [i.shape[0] for i in input_ids] input_ids = pad_sequence(input_ids, batch_first=Tru...
3226805e1c25ec5db0ca19e9f7f233a9be4f65ea
59,387
def R_ratio_local(omega_par, disp_vector, passive_el, ind_passive, coord, connect, E, v, rho, const_func, aux_R=True): """ Calculates the local strain-to-kinetic energy ratio function. Args: omega_par (:obj:`float`): 2 * pi * frequency. disp_vector (:obj:`numpy.array`): Displacement. pa...
64eabbf73175f2fb65cd966ad7b98827b856bf2b
59,388
def align(sentence, span): """align. Searches for span in sentence, to create character offsets Uses heuristics if the span happens more than once in a sentence. Prefers the earliest span that also ends on a word boundary, which is defined as a non-alpha numeric character (e.g. a space character) r...
eeb9e9b3aabca4c3b39efc4bd24c42547cb2e754
59,389
def profile(request, username): """ This function sets a profile. :param request: A request :param username: A user name :return: A render """ user = User.objects.get(username=username) treasures = Treasure.objects.filter(user=user) return render(request, 'profile.html', {'username':...
311c827703197f82a9523b9ffe5dfbca64e8d485
59,391
def derivatives_close(x, y): """ Returns True iff the AffineScalarFunc objects x and y have derivatives that are close to each other (they must depend on the same variables). """ # x and y must depend on the same variables: if set(x.derivatives) != set(y.derivatives): return False ...
5555348253ce7e64a348c41ce9b65517b985bf5b
59,392
from re import M def get_norm(norm): """ Args: norm (str): currently support "BN", "SyncBN", "FrozenBN" and "GN" Returns: M.Module or None: the normalization layer """ if norm is None: return None norm = { "BN": M.BatchNorm2d, "SyncBN": M.SyncBatchNorm,...
80bdc5b1327f6718ddb371f2bda4c2ffc179077f
59,393
def extraerWrfoutSerie(wrf_file: str, variable: str, x: int, y: int): """ extrae de los arechivos wrfout listados en file_paths para la posicion (x, y) toda la serie de la variable seleccionada""" dfData = pd.DataFrame() t2 = wrf.getvar(wrf_file, variable, timeidx=wrf.ALL_TIMES) t2_loc = t2[:,...
445034862c38dbbb23803354e35114208af8ad8b
59,394
def grad_logloss_theta_lr_weighted(label,ypred,x,weight_ar=None,C=0.03,has_l2=True,scale_factor=1.0,weights=None): """Return d l_i / d_theta = d l_i / d_ypred * d y_pred / d theta Args: label: a scalar (one sample) or an array of shape [None,] ypred: a scalar (one sample) or an array of shape [N...
9d718a9b46648f257a30192cee0eb5905d87802a
59,395
import pickle def read_solver(filename): """ This function reads a .pk1 file. Parameters: filename (str): A file name or path to file excluding file extension. Returns: Content of the loaded .pk1 file. """ try: file = open(filename+'.pk1', 'rb') except IOError: ...
da7bcfb75af1edde3d43091fdbc5c1829c13e5e0
59,396
def chi_square(logu, name=None): """The chi-Square Csiszar-function in log-space. A Csiszar-function is a member of, ```none F = { f:R_+ to R : f convex }. ``` The Chi-square Csiszar-function is: ```none f(u) = u**2 - 1 ``` Warning: this function makes non-log-space calculations and may therefo...
9c221e7e9d0c08a671b00c6809014a42d04031bd
59,397
def get_ir_grgrid_map(rotations, D_diag, PS=None): """Return grid point index mapping table to irreducible grid points (Generalized-regular-grid version) Parameters ---------- rotations : array_like SNF transformed reciprocal rotation matrices. See some more detail in the docstring...
8d945ffaaefeb633446dc5ca23da41bc468e01c7
59,398
def schurs_complement(H, g, m, r, precond=False): """ Shurs-complement """ assert H.shape[0] == (m + r) # H = [Hmm, Hmr # Hrm, Hrr]; Hmm = H[0:m, 0:m] Hmr = H[0:m, m:] Hrm = Hmr.T Hrr = H[m:, m:] # g = [gmm, grr] gmm = g[1:] grr = g[m:] # Precondition Hmm if precond: Hmm = 0.5 * (H...
08d14e0ab5a275230ca926ce20a5ba7bb7cc8c71
59,400
def markdown(text): """ Return match object if text is Markdown-formatted, otherwise None. @param text: The message to check for Markdown formatting. @type text: L{str} """ return mdre_code.match(text) or mdre_reply.match(text) or \ mdre_mono.search(text) or mdre_link.search(text) or \ ...
a658a2932e952deebe140b9369e50a77fe056813
59,401
def neighborSelect(a, x, y): """ finds (local) minima in a 2d grid :param a: 1d array of displacements from the source positions :type a: numpy array with length numPix**2 in float :returns: array of indices of local minima, values of those minima :raises: AttributeError, KeyError """ ...
283066456ab5e9d93402ba24e1623e9d99ef17d2
59,402
from typing import Optional from typing import Set def extract_active_themes(raw_themes: str, graph: dict) -> Optional[Set[str]]: """Safely parse and extract theme uuids.""" if raw_themes != constants.ALL_THEMES: active_themes = set() candidates = [ x.strip() for x in c...
5144361ebee59038c97afe5d44b76f7e73ed7a93
59,404
def hash_password(plain_text_password, salt=None): """Convert a plain text password to salted/hashed form.""" plain_text_password = plain_text_password.encode('utf-8') if salt is None: salt = bcrypt.gensalt() hashed_password = bcrypt.hashpw(plain_text_password, salt) return hashed_password
1fdb95265f535eac868c8486052b0803e9c71146
59,405
def pairwise_cos_similarity_np(features): """Compute the pairwise cosine similarity. Args: features: The input embeddings. :return: The pairwise cosine similarity matrix. """ feature_norm = np.sqrt(np.sum(features ** 2, axis=1, keepdims=True)) features = features / feature_norm retu...
f894666722ea05bd22007f641d1d1f4916d879fb
59,407
def disqus_show_comments(context, shortname=''): """ Return the HTML code to display DISQUS comments. """ shortname = getattr(settings, 'DISQUS_WEBSITE_SHORTNAME', shortname) return { 'shortname': shortname, 'config': get_config(context), }
6ba672b887c5dfb395558943d2110a8ee195b1ac
59,408
def sentence_length_feature(sentences): """ List of values from 0 to 1 rating the length of the sentence in comparation with the longest one """ sentence_length_feature_values = [] max_length_sentence = len(sentences[0].original.split(' ')) # Find the longest sentence for sentence in sentences[1:...
89e705a6b12b30f29352d70977bd80db45a14b6a
59,409
def radar_coords_to_cart_track_relative(rng, rot, roll, drift, tilt, pitch): """ Calculate track-relative Cartesian coordinates from radar coordinates. Parameters ---------- rng : array Distances to the center of the radar gates (bins) in kilometers. rot : array Rotation angle o...
d44912656223c54e6f2e1c94e598b479ee6acfe8
59,411
def _get_agreement_violations(agreement_id, term=None): """ :rtype : list[wsag_model.Violation] """ violations_client = _get_violations_client() violations, response = violations_client.getbyagreement(agreement_id, term) return violations
f0b9e24731acda7233d6dd1dd80f5890641af897
59,412
def processHis(pdb,his_tautomers,default_his=2, valid_his={"CD1":0,"ND1":1,"NE2":2}): """ Take the calc_param.his_tautomers and generate proper input for the generation of an input file. Either: 1) An input file is specified; read the file but return an error if it is mang...
55f2d030168b97b749e613ef11de1912dfaa3d8a
59,414
def serialize(selector: Selector) -> str: """ # Equality: >>> serialize({"a": "b", "c__neq": "d"}) 'a=b,c!=d' # Inclusion: >>> serialize({"a__in": {"x", "y"}, "b__notin": ("z",)}) 'a in (x,y),b notin (z)' # Existence: >>> serialize({"a": Is.PRESENT, "b": Is.ABSENT}) 'a,!b' ...
4fb83bf019ab3dff7761d86d1878542f9f463782
59,415
def __retrieve_linear_data(location=None): """ Testdata from intervention cases. Univariable (here: at one location)""" subsample = list(map(int, np.loadtxt('{}/intervention/subsample.csv'.format(testdata_path), delimiter=","))) predictor = pd.read_csv('{}/intervention/reference.csv'.format(testdata_pa...
93727086814c0882bccec5e54a50fc72ea018eeb
59,416
import inspect def get_argument_help_string(param: inspect.Parameter) -> str: """Get a default help string for a parameter :param param: Parameter object :type param: inspect.Parameter :return: String describing the parameter based on the annotation and default value :rtype: str """ help_...
7381591ce45591bf1aef62280fc4b98e57969576
59,417
def _inTkStep(window): """Return true if the TkStep patches have been applied to Tk.""" global _in_tkstep try: return _in_tkstep except NameError: try: f = Frame(window, text='is TkStep installed?') except TclError: _in_tkstep = 0 else: ...
62c6fd896677ac447f4e31d006fb9ffdcf536744
59,418
def _dask_array_fft_has_norm_kwarg(): """returns True if dask.array's fft supports the norm keyword argument """ return False
93e111839aa5a175ebcdb995193c7774c45e25ec
59,420
import six def generic_signature(name_tensor_map): """Creates a generic signature of name to Tensor name. Args: name_tensor_map: Map from logical name to Tensor. Returns: A Signature message. """ signature = manifest_pb2.Signature() for name, tensor in six.iteritems(name_tensor_map): signatu...
bf652746645348efa0ebabec2bb59c3190edef9a
59,421
def preprocess(input_sentence, en_vocab, en_word2index, output_sentence = None, de_vocab= None): """ :param input_sentence: test sample of input language :param en_vocab: English language vocabulary :param en_word2index: word-to-index dictionary :param output_sentence: target language sentence for c...
f1798a38bebb80b4ecad3a237648b3f1f6f2e33b
59,422