content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def frange(range_def, sep=','): """ Return the full, unabbreviated list of ints suggested by range_def. This function takes a string of abbreviated ranges, possibly delimited by a comma (or some other character) and extrapolates its full, unabbreviated list of ints. Parameters ---------- ...
574930029d0ce1fedeea92b1c74c8f87799548a5
276,235
def digits_to_skip(distinct_letter_pairs: int) -> int: """The number of letters which can be skipped (i.e. not being incremented one by one) depending on the number of distinct letter pairs present.""" if distinct_letter_pairs == 0: # If no letter pair exists already, we know at least one must be ...
fa007f80d3396a78de242e989e32d573f5ce9424
413,204
from typing import Union def try_num(s: str) -> Union[str, float, int]: """Attempt to convert a string to an integer. If that fails, try a float. If that fails, leave it as a string and return it.""" try: return int(s) except ValueError: try: return float(s) except...
5b0cb3533c7dabafec4abbbf0c7479981433fb51
323,063
import requests def fetch_image(session: requests.Session, folder, image): """Fetch an image from TibiaWiki and saves it the disk. Parameters ---------- session: :class:`request.Session` The request session to use to fetch the image. folder: :class:`str` The folder where the image...
582e1a58e62d517656d61a55be7f0c7e575e9be7
441,323
import torch def computeKLD(mean_a_flat, logvar_a_flat, device, mean_b_flat=0.0, logvar_b_flat=1.0): """Compute the kullback-leibler divergence between two Gaussians. Args: mean_a_flat: mean of the Gaussian a. logvar_a_flat: Log variance of the Gaussian a. ...
3c58f945fd003093b55b32a11a8ceb4f4577e368
153,410
def num_articles(data): """ Find the number of unique articles in data. """ art = set() for row in data: art.add(row[1]) return len(art)
7900ffe4f1e1a156ed15b3368cea1faa3b9d3671
461,773
import functools def cached_property(fn, *args, **kwargs): """ Decorator to make a function a "cached property". This means that it is a property whose return value is cached after the first time it is called. Args: fn: The function to be made a cached property *args: Any args fo...
142f240297c9bc2a74b19411dac9c8dc4efa166d
491,611
from typing import Tuple from typing import List def remove_gaps(seq: str) -> Tuple[str, List[int]]: """Remove gaps in the given sequence.""" seqout, idx = "", [] for i, char in enumerate(seq): if char != "-": seqout += char idx.append(i) return seqout, idx
201c4d572fa456a46286bc0c6192bc57a3bcec9e
353,423
def grid_size(config): """ Get size of grid. """ return int(round((config.radius * 2 + 1) / config.resolution))
2e9e72a384b5ae9670fb5752ce80b8d318cce60d
364,346
def is_subpath(spath, lpath): """ check the short path is a subpath of long path :param spath str: short path :param lpath str: long path """ if lpath.startswith(spath): slen, llen = len(spath), len(lpath) return True if slen == llen else lpath[slen] == '/' return False
1ee1d6845d24191282d3546e04b1fa6ce08bcb2f
473,583
def to_mtcsv(data, path=None, decimals=5): """ Save a downloaded ticks dataframe as a csv with a optimized format to be imported by MetaTrader. :param data: pandas dataframe with Ask and Bid columns :param path: file path to save :param decimals: number of decimals to save :return: str if pa...
48f733878bbd3da6f05dfdd38082fc2c425b690a
520,862
def sec_to_time(sec): """ Returns the formatted time H:MM:SS """ mins, sec = divmod(sec, 60) hrs, mins = divmod(mins, 60) return f"{hrs:d}:{mins:02d}:{sec:02d}"
cffe3060a1a98f3dbba53da4666175994c606a31
50,002
def ez_user(client, django_user_model): """A Django test client that has been logged in as a regular user named "ezuser", with password "password". """ username, password = "ezuser", "password" django_user_model.objects.create_user(username=username, password=password) client.login(username=user...
20e54603e8154cbf9f6c7e0cbd06a78627beecd0
21,077
from datetime import datetime def within_time_range(start_time, end_time, now_time=None): # pylint: disable=unused-variable """Check whether time is in a specific time range.""" now_time = now_time or datetime.utcnow().time() if start_time < end_time: return start_time <= now_time <= end_time ...
0657d43048ef4c9e1a7b98a3a3e3822bc4994be8
594,601
def wrangle_counties(df): """ Wrangle the data to group by county. Parameters: ----------- df -- (pandas DataFrame) Cleaned data in a dataframe. Returns the data grouped by county in a pandas df. """ # Group and aggregate the data by Counties counties_grouped = df.groupby(['county'...
8d9aac0cd233db1fa03bc0ccbbb9cbf5cf953671
175,815
def parse_fasta( f ): """Parses a fasta file f can either be a file name or a file handle. Returns a dictionary mapping keys to sequences Not optimised for large files """ if str == type( f ): f = open( f, 'r' ) results = { } key = None for line in f: line = line...
da06dcc8a5ad75d774228e222ef0c0e085a05d27
571,910
def calculate_density_after_time(densities, time_0, time_explosion): """ scale the density from an initial time of the model to the time of the explosion by ^-3 Parameters: ----------- densities: ~astropy.units.Quantity densities time_0: ~astropy.units.Quantity time of the mod...
024f11517a4fcce14a69eed3705a485f1d8940e3
361,534
def moeda(preco=0, moeda='R$'): """ -> Formata um preco com o padrao real brasileiro :param preco: o valor a ser formatado :param moeda: a sigla da moeda :return: retorna uma string formatada de acordo com o padrao monetario do Brasil """ return f'{moeda}{preco:.2f}'.replace('.', ',')
6ce45b3c045854fe2967532f78021b7dec37a969
170,232
from datetime import datetime def parse_windows_timestamp(qword): """see http://integriography.wordpress.com/2010/01/16/using-phython-to-parse-and-present-windows-64-bit-timestamps""" return datetime.utcfromtimestamp(float(qword) * 1e-7 - 11644473600)
de21a39f3000049f09b7560e4cddedea8e8a332f
123,724
def search_content(content_df, content: str): """Search with content. Args: content_df (DataFrame): Table including content element. content (str): Content name as a query. Returns: (DataFrame): Contents DataFrame including a query content. """ mask = content_df["content"]...
1e104dfc72af098f903dfc5369368fcd76d10299
438,526
import re def remove_all_parenthesis_words(text): """Return text but without any words or phrases in parenthesis: 'Good morning (afternoon)' -> 'Good morning' (so don't forget leading spaces)""" pattern = r"\s*\([\w\.]+\)" sub_ = re.sub(pattern, "", text) return sub_
b5b045344cfe113dbd0a254871ca5a3876de11f3
537,544
import re def available_space(ctx, device): """ Determine the available space on device such as bootflash or stby-bootflash: :param ctx: :param device: bootflash / stby-bootflash: / harddisk: / stby-harddisk: :return: the available space """ available = -1 output = ctx.send('dir ' + ...
2d831e644ed5d843b80397472e2cab65fccced1b
680,657
def read_tles(tle_path): """ Convert TLE text files in a given directory to a list of TLEs. Parameters ---------- tle_dir : str Path to the directory containing TLE .txt files. Returns ------- sats : List of lists. Each internal list has the 3 lines of a TLE as its elem...
aa8aae9ec1eb286abf5fd5b4eb1474e807d3f34d
641,557
def parse_input(input): """Seperates the interface input from the user into the name and number ex. Gi1/0/1 becomes ('Gi', '1/0/1') or GigabitEthernet1/0/1 becomes ('GigabitEthernet', '1/0/1')""" interface_name = '' interface_number = '' x = 0 for letter in input: if letter.isdigit(): ...
7c3cc5d759ce1235c9a1d5258c3981d91fddc5dd
70,264
def average_top_runs(speed_df,rank_column,weapon_column='Weapon',time_column='Time (s)',top_pos=1): """ Returns a DataFrame with the average top speedrun times for each weapon class, as ordered by the 'rank_column' column. This will take the 'top_pos' times into the average. For top_pos=1, that's on...
ff7bd304cf2987f34beba6989d684c9e058f949c
327,968
def find_delims(s, delim='"',match=None): """find matching delimeters (quotes, braces, etc) in a string. returns True, index1, index2 if a match is found False, index1, len(s) if a match is not found the delimiter can be set with the keyword arg delim, and the matching delimiter with keyword...
c99012aed8e7ec1a42a93d7c59e2c9b3bce1f9b4
509,423
def error404(e): """ 404 error handler. """ return ''.join([ '<html><body>', '<h1>D20 - Page Not Found</h1>', '<p>The only endpoint available on this entropy micro-service is <a href="/api/entropy">/api/entropy</a>.</p>', '<p>For more information including the complete source code, visit <a href="https://gi...
35ab121b88e84295aaf97e2d60209c17acffd84d
21,607
def keep(pred): """Keep only items that do not return None when pred is called. This is for functions that only return values in certain cases, or which return None for their false value.""" def generator(coll): for item in coll: res = pred(item) if res is not None: ...
a642fb9efc7719c3453c74ab47e1921f2efaf1e3
227,574
import json def to_bundle(sparkSession, dataset, resourceTypeUrl): """ Converts a dataset of FHIR resources to a bundle containing those resources. Use with caution against large datasets. :param sparkSession: the SparkSession instance :param dataset: a DataFrame of encoded FHIR Resources :pa...
0a0a6b38be939b7e3ebea4fcd60ab8c1ddfc748c
515,511
import re import string def format_counter_name(s): """ Makes counter/config names human readable: FOOBAR_BAZ -> "Foobar Baz" foo_barBaz -> "Foo Bar Baz" """ def splitCamels(s): """ Convert "fooBar" to "foo bar" """ return re.sub(r'[a-z][A-Z]', lambda x: x.group(0)[0] + " " + x.g...
15196d7ec3a435b0ab8f4d6c65002b991e964318
192,313
def generate_coordinates() -> list: """Generates the list of coordinates to populate.""" coordinates = [] for x in range(0, 160): for y in range(0, 90): coordinates.append((x, y)) return coordinates
68c17f6d5390e966b713af8ba58807ee27519748
547,021
def is_pos_pow_two(x: int) -> bool: """ Simple check that an integer is a positive power of two. :param x: number to check :return: whether x is a positive power of two """ if x <= 0: return False while (x & 1) == 0: x = x >> 1 return x == 1
6bce29e9f06d7b1393f9042894644e0ede68b0e9
238,201
def udir(obj): """ udir : user-dir Filters all magic methods and private attributes from a dir() call """ return [attribute for attribute in dir(obj) if "__" not in attribute]
2f627d603b8db46af16f89d36b1aae310ec324f3
364,711
import torch def reparametrize( x_min, x_max, y_min, y_max, reparametrization_h, reparametrization_w, inplace=False, inverse=False): """ If `inverse is False`, scale module's parameters so that their range becomes approximately [-1; 1]. Otherwise, do the inverse operation. This ha...
a2a00117fcfa29b5f95f9237a7b6012706f8a44c
400,399
def norm(arr): """ Demean and normalize a given input to unit std. """ if arr.ndim == 1: arr -= arr.mean() arr /= arr.std() else: arr -= arr.mean(axis=-1, keepdims=True) arr = (arr.T / arr.std(axis=-1)).T return arr
7d36ebd6aa9162e99db078b436a48604368c1f10
468,849
def webhook_request( response_id, session, intent_id, text, title, subtitle, image_url, buttons, payload, quick_replies ): """Return a sample WebhookRequest dictionary.""" project_id = 'PROJECT_ID' return { 'responseId': response_id, 'queryResult': { ...
e65c637b45e65ce2b971fa2c1d0074b335f90a83
582,013
import math def get_phase_law(N, d, wavelength, phi): """Computes a phase law given N (number of elements), d (spacing between elements in m), wavelength (in m) and phi (beam steering angle). """ phase_law = []; for n in range(N): phase_law.append(-2 * math.pi * n * d / wavelength * ma...
7a6be2d6b3ff4b583e47f114e8cf15a566dc5864
590,744
def match_i(instance1,instance2): """Return True if given instances match, i.e., contain the same vertex and edge object instances.""" return (instance1.vs == instance2.vs) and (instance1.es == instance2.es)
62000889756b79d07932e93b7877792c23f4b89c
278,570
import random def randomize_list_of_words(input_words): """ Returns the same list of words in a random order. Input: -input_words list of strings Output: -output_words list of strings """ output_words = [] random_order = random.sample(range(len(input_words)), len(input_word...
cbe19aa8cddddedcb439245cfc9ad67e20d7e382
627,536
import re import functools def rgetattr(obj, attr, *args): """ Recursively get an attribute. This is useful for nested subobjects or chained properties. Examples: class A(object): def __init__(self, a=0): self.a = a class B(object): def __init__(se...
0126f91efb4e34ef27d474119374b148feeb1ec6
538,743
def make_json_ok_response(data): """Returns OK response with json body""" return data
69a855234725b2773682628728ada1a2a1817482
505,304
def get_bit(byte, bit_num): """ Return bit number bit_num from right in byte. @param int byte: a given byte @param int bit_num: a specific bit number within the byte @rtype: int >>> get_bit(0b00000101, 2) 1 >>> get_bit(0b00000101, 1) 0 """ return (byte & (1 << bit_num)) >> bit_...
4f25c4ccdc4c3890fb4b80d42d90bfb94d6799c3
8,985
from functools import reduce def concat(l): """ >>> concat([[0, 1], [2], [3, 4, 5]]) [0, 1, 2, 3, 4, 5] """ return reduce(list.__add__, l, [])
a746ad6283466bbd747db4ff2a5ce4e4bedbb0c2
430,465
def format_params(params): """ Casts the hyperparameters to the required type and range. """ p = dict(params) p['min_child_weight'] = p["min_child_weight"] p['colsample_bytree'] = max(min(p["colsample_bytree"], 1), 0) p['max_depth'] = int(p["max_depth"]) # p['subsample'] = max(m...
66c6440a6b88ce567ff49bc625e39c3a8ffd67b3
282,777
import json def read_json(path): """Reads JSON from file. Args: path: the path to the JSON file Returns: a dict or list containing the loaded JSON Raises: ValueError: if the JSON file was invalid """ try: with open(path, "rt") as f: return json.lo...
dd29df960e2e3699119c3a0cafc256c29624e9cb
571,862
import shlex def _parse_tags(tags: str): """Takes a string of whitespace seperated tags and assigns them to a dict. Expects each tag to be of the format 'tag_name:tag_value' Args: tags (str): The tags to parse Returns: dict: The parsed tags """ return dict(item.split(":")...
ce907265c5a1706af6a79860abe4453878b3456e
81,503
def test_astore_model(session, cas_session, change_dir): """Ensure the register_sas_classification_model.py example executes successfully.""" # Mock up Session() to return the Betamax-recorded session def Session(*args, **kwargs): return session change_dir('examples') with open('register_s...
9663ac8c9c1e599c12d9c70a3db4c7fbb39d3413
252,537
def compare_insensitive(a, b): """Compares insensitive if a contains b""" if a is None or b is None: return return b.lower() in a.lower()
b60104f687df26dfb3a85923d6ba09aa41c3aa2e
131,739
def tier_count(count): """ If a tier quota is 9999, treat it as unlimited. """ if count == 9999: return "Unlimited" else: return count
dc702e930377d1533fbacf434a2acd0ddfefc457
665,552
def element(a): """ Return the element """ return a.GetSymbol()
d2e335aff22978da0ae4627c8cae25f6b80cd602
665,238
def fix_data(text): """Add BOS and EOS markers to sentence.""" if "<s>" in text and "</s>" in text: # This hopes that the text has been correct pre-processed return text sentences = text.split("\n") # Removing any blank sentences data sentences = ["<s> " + s + " </s>" for s in senten...
b502784e9e8fa8875030730595dcaaae66e2f31b
28,083
def get_options(options): """ Get options for dcc.Dropdown from a list of options """ opts = [] for opt in options: opts.append({'label': opt.title(), 'value': opt}) return opts
61df747bf10a08aff481c509fbc736ef406d006f
50,832
import random def randChooseWeighted(lst): """Given a list of (weight,item) tuples, pick an item with probability proportional to its weight. """ totalweight = sum(w for w,i in lst) position = random.uniform(0, totalweight) soFar = 0 # We could use bisect here, but this is not going t...
7abb650d9df32f2e12412a31173336507a0b3738
586,861
def always_true(*args): """ A predicate function that is always truthy. """ return True
b08c44467cd14b572b5a7e404da441e9b74b0e26
100,644
def slice_by_lev_and_time( ds, varname, itime, ilev, flip ): """ Slice a DataArray by desired time and level. Args: ds: xarray Dataset Dataset containing GEOS-Chem data. varname: str Variable name for data variable to be sliced...
610c115076e044911a5b6d5f2653cfcae4fce113
440,277
import hashlib def calculate_file_hash(f_name): """calculate hash of a given file""" BLOCK_SIZE = 65536 # The size of each read from the file file_hash = hashlib.sha512() # create the hash object, algo used sha512 with open(f_name, 'rb') as handle: # open the file to read it's bytes fb = h...
fc37486d40e5930dcaaf0b616dfcad81053f0132
503,114
from typing import OrderedDict def build_paragraph_marker_layer(root): """ Build the paragraph marker layer from the provided root of the XML tree. :param root: The root element of the XML tree. :type root: :class:`etree.Element` :return: An OrderedDict containing the locations of markers, suita...
d4b4ae6d0a1be0f4fcb3b550b0a11b2366220912
82,233
def fromOpt(object, default): """ Given an object, return it if not None. Otherwise return default """ return object if object is not None else default
7aa3190f65d01c8812eb22ca1d9058c81be4d7f1
395,655
def trans_f_to_c(f): """Transform f to c temperature.""" return round((f - 32) * (5.0 / 9), 1)
559ad47b721cb211928a6a4403511311feffddf1
392,353
def torchcrop(x, start_idx, crop_sz): """ Arguments --------- x : Tensor to be cropped Either of dim 2 or of 3 start_idx: tuple/list Start indices to crop from in each axis crop_sz: tuple/list Crop size Returns ------- cropped tensor """ dim = len(x.s...
f7a3ef0eb2e81bb77d194b0e04d8c504979475d7
670,369
def missing_branch(children): """Checks if the missing values are assigned to a special branch """ return any([child.predicate.missing for child in children])
75dd5f4cd503ae614023bc73c0119bebc9bb561e
691,577
def add_target_columns(df, targets): """ Adds new columns (empty) to the dataframe form each target variable. """ for env in targets.values(): for v in env.get("aliases"): if v not in df.columns: df[v] = None return df
951eb8168415ed5f8b90b1e130b4df69919ec377
393,949
import torch def cov(x, ddof=1, dim_n=1, inplace=False): """Return the covariance matrix of the data. Parameters ---------- x : torch.Tensor A tensor of shape ``(m, n)``, where ``n`` is the number of samples used to estimate the covariance, and ``m`` is the dimension of the mu...
a5a40fed541a37223da22ce69cabe9ff95a84773
381,480
def countCheckedItems(widget_list, what_to_count): """ Calculation of the amount of records marked in the list. :param widget_list: the current list for which the number of marked records is counted. :param what_to_count: A parameter that tells the function what to count, for example: number of checked...
8621448c9150a2b2ab2a131f7a708810ee3c03e8
571,157
def normalize_text(text, lower=True): """ Normalizes a string. The string is lowercased and all non-alphanumeric characters are removed. >>> normalize_text("already normalized") 'already normalized' >>> normalize_text("This is a fancy title / with subtitle ") 'this is a fancy title with sub...
42b0da0abef13972e31f88cdfecfb343dcefaa2f
262,150
def _check_hospital_unhappy(resident, hospital): """Determine whether a hospital is unhappy because they are under-subscribed, or they prefer the resident to at least one of their current matches.""" return len(hospital.matching) < hospital.capacity or any( [hospital.prefers(resident, match) fo...
2144e6f553f2b43b01a4f6f61f94e2c4c91cccfb
617,004
def _el_orb_tuple(string): """Parse the element and orbital argument strings. The presence of an element without any orbitals means that we want to plot all of its orbitals. Args: string (`str`): The selected elements and orbitals in in the form: `"Sn.s.p,O"`. Returns: ...
b56932ce95afb54e3f5d9f01530d50851edab311
585,406
def calculate_r2_wf(y_true, y_pred, y_moving_mean): """ Calculate out-of-sample R^2 for the walk-forward procedure """ mse_urestricted = ((y_true - y_pred)**2).sum() mse_restricted = ((y_true - y_moving_mean)**2).sum() return 1 - mse_urestricted/mse_restricted
f31c729c1f6008484acde73cf4fd208c04d01f41
536,191
def validateWavelengths(wavelengths: list, bbl: list): """ Validate wavelengths and bbl. Parameters ---------- wavelengths : list of int List of measured wavelength bands bbl : list of str/int/bool List of bbl values that say which wavelengths are measured in good qualit...
795b33b59c026c2dbdea85b602254fbf82adb091
52,911
def add_modal(form, error, name, url): """Render the given template to provide a modal dialog that provides a popup form. Args: form (Forms) : Django form to render error (String) : String to add to the form's class attribute name (String) : Name of the buttons / modal url (...
f8000e6cb99637ee2d32caf8294a9fcd40e0edfa
337,730
def check_requirement(line): """ Check this line for a requirement, which is indicated by a line betinning with "?? ". If one is found, return that line with a newline at the end, as requirements are always a complete line and formatted as a bulleted list. Replace the "??" with a "-" as well so tha...
63511288a11a1278d2438f103ae4abae49c4b318
276,035
def __filter_vertices(k, coreness, *args, **kwargs): """ .. function filter_vertices(k, coreness) Filters coreness mapping for vertex ids in k-core >= k. :param k: minimum k-core :param list coreness: vertex -> k-core mapping :return: vertices in k-core """ return list(filter(lambda i:...
c12b8c60a0c010bda8accabb30775d15d4272b2c
157,194
def calc_formation_energy(prod, react): """ Calculate formation energy of 'A' in a.u. from 2 lists of energies. Formation energy = sum(product energy) - sum(reactant energy) Keyword arguments: prod (list) - list of product energies react (list) - list of reactant energies Returns:...
ec2a8f3d4e7fd72ebfce84e2bb58b3f1fd68472c
524,222
def flipx(tile): """ Return a copy of the tile, flipped horizontally """ return list(reversed(tile))
1203919042cdedd49edd35942d19964d4f1acfdf
59,111
def _parse_match_info(match, soccer=False): """ Parse string containing info of a specific match :param match: Match data :type match: string :param soccer: Set to true if match contains soccer data, defaults to False :type soccer: bool, optional :return: Dictionary containing match informa...
db0f6bbd6f19902202d7d1b0012812cbd22aeaab
278,998
def _ids_to_words(ids, dictionary): """Convert an iterable of ids to their corresponding words using a dictionary. Abstract away the differences between the HashDictionary and the standard one. Parameters ---------- ids: dict Dictionary of ids and their words. dictionary: :class:`~gensi...
2d6328a823e10e686c764aa186bdc10455a9ab85
454,308
from pathlib import Path def lglob(self: Path, pattern="*"): """Like Path.glob, but returns a list rather than a generator""" return list(self.glob(pattern))
eba1b9d6300a1e1aca5c47bedd6ac456430e4d89
9,576
def normalizeTransformationMatrix(value): """ Normalizes transformation matrix. * **value** must be an ``tuple`` or ``list``. * **value** must have exactly six items. Each of these items must be an instance of :ref:`type-int-float`. * Returned value is a ``tuple`` of six ``float``. """ ...
3c13d334f82e91dbc0a5a9a01081c1c8a8438f05
332,508
def named_field(key, regex, vim=False): """ Creates a named regex group that can be referend via a backref. If key is None the backref is referenced by number. References: https://docs.python.org/2/library/re.html#regular-expression-syntax """ if key is None: # return regex ...
b813179e87f8bf6cabc02d7746222787154aed3a
684,365
def readText(inputfile): """Reads a sequence file in text format and returns the file with special character removed.""" with open(inputfile, "r") as seqfile: # read data seq = seqfile.read() # remove special characters \n and \t seq = seq.replace("\n", "") seq = seq.repl...
489b6a92d70eb68414b4221e51b54f3e3dd07ac3
333,237
def cumany(x, axis=0): """Cumulative any (modeled after np.cumprod)""" return x.astype(bool).cumsum(axis=axis) > 0
62832b89be4e0c746bea2ccceea09118341d9808
377,172
import re def copy_from(con, copy_from_sql): """ To be used with a 'COPY FROM' statement. Calls pymapd `execute`, but parses the response to check if it failed or not. If it fails to do too many rejected records, raise an exception. If it succeeds, return a dict with loaded, rejected, and time in ...
18dd479b400ae390e24b9e622a10c7184f86a53c
149,587
def notas(*valores,situacao=False): """ -> Funcao para analise das notas e situcao do estudante : para valores: as notas dos estudantes (aceita varias notas) | PS: o asterixo no principio da variavel indica a condicao de recebimento de varios valores (*n) : para situacao: valor opcional (condicao T...
2ae9d59c494415b3d862c86d6ca3500b23ca0631
539,019
def rep_model(glm_dict, repo_mode): """Reporting results from GLM models in glm_dict. Parameters ---------- glm_dict: :obj: dict of :obj: GLM models. Like: {tar_var:{'forluma': formula, 'res':res}} rep_mode: :obj: string Reporting mode. Returns ------- Nothing. ...
8e15509e397a48e4463d7b3e47167c86ce28e83e
536,482
from datetime import datetime def _parse_created(raw_created): """Parse a string like 2017-02-14T19:23:58Z""" return datetime.strptime(raw_created, "%Y-%m-%dT%H:%M:%SZ")
711883abcc860f5217556d63099c0c15e9b6c819
247,464
import json def _transform_request(request: bytes) -> dict: """ Transform bytes posted to the api into a python dictionary containing the resource routes by tag and weight :param bytes request: containing the payload to supply to the predict method :return: dict containing the r...
f7a9222391ebbbf28c69722196391daef246d54c
144,385
from typing import List def build_ip_set(ip_addresses: List[str]) -> str: """ Build ip set input for list-cmdb-devices command. The input wil be a combination of ip-addresses list and ranges. For example, if ip_address = ['1.1.1.1','3.3.3.3','2.2.2.0-2.2.2.254'], the output will be: '1.1.1.1,3.3.3...
863cb6664b71a424577cd5c28cb76a5d95d1e30f
191,693
import torch def sparse_categorical_kl(log_q, p_support, log_p): """ Computes the restricted Kl divergence:: sum_i restrict(q)(i) (log q(i) - log p(i)) where ``p`` is a uniform prior, ``q`` is the posterior, and ``restrict(q))`` is the posterior restricted to the support of ``p`` and ren...
2eef54e367be5b2bd360f6b4ef90645fa93a50c2
399,493
def analogy2query(analogy): """ Decompose analogy string of n words into n-1 query words and 1 target word (last one) zips with +- >>> analogy2query("Athens Greece Baghdad Iraq") ('+Athens -Greece +Baghdad', 'Iraq') """ words = analogy.split() terms, target = words[:-1], words[-1] pm_ter...
2040d46f361b56388597c839e8dd78eb1f022d94
433,649
def div(format, data): # HTML formatting utility function """Wraps 'data' inside a div of class 'format' for HTML printing.""" d = '<div class="{}">{}</div>' # Basic div template return d.format(format, data)
0596217cabfeb13b0b77a91697ebcfc42888e6b0
82,919
from re import search def img_from_html(html_str: str) -> str: """Scrubs the string of a html page for the b64 string of in image This function uses regex to scan the html template described in the render image function. It scans this template for the base 64 string encoded png image and extracts it ...
5436f6b1b27b90191f6f0461178c343e5b9932c4
328,011
def tokenize (text): """ Tokenizes a text sample. Args: text (str): The text sample Returns: list of str: A list of tokens """ replacements = ["\r", "\n", "\t"] output = text for replacement in replacements: output = output.replace(replacement, " ") # Convert whitespace to spaces only. return list(filter(...
73e89528f41b34740e7e9583f5f387e248588963
418,366
def combine_values(uri_list, check_full_titles_for_volume_info, check_copyright_ocr_for_edition_info, check_fm_and_marc_titles_for_differences): """ Creates list of check values corresponding to title URIs. The following Stack Overflow page was helpful in producing this function: "Merge Two Lists to Ma...
be9edbee9bcd47e6feccfe5f7d03040813f52567
538,025
def bits_to_array(num, output_size): """ Converts a number from an integer to an array of bits """ ##list(map(int,bin(mushroom)[2:].zfill(output_size))) bit_array = [] for i in range(output_size - 1, -1, -1): bit_array.append((num & (1 << i)) >> i) return bit_array
7df0bd8bf3e95770e4eee332df4514581704eef6
650,029
def linear_search(array, element): """ Linear Search Complexity: O(N) """ indices = [] for i in range(len(array)): if element == array[i]: indices.append(i) return indices
6de026b74354d4e9d848514aa730a37738c727b0
416,691
def get_channel_name(sample_rate, is_acceleration=True, is_vertical=False, is_north=True): """Create a SEED compliant channel name. SEED spec: http://www.fdsn.org/seed_manual/SEEDManual_V2.4_Appendix-A.pdf Args: sample_rate (int): Sample rate of sensor in Hz. is_accele...
bf1a845bfa011aa2dbe8b0ba1cb93bfc07b00e69
289,687
def combineUsers(users): """Combine user info into a string with known format.""" res = [] for user in users: userstr = user['name'] if user.get('email'): userstr += ' <%s>' % user['email'] if user.get('affiliation'): userstr += ' (%s)' % user['affiliation'] ...
777672896e730bcacffbf1e2bf958aabb1d33aa8
383,619
import hmac import hashlib def sha256_hmac(key, bytes): """Computes a hexadecimal HMAC using the SHA256 digest algorithm.""" return hmac.new(key, bytes, digestmod=hashlib.sha256).hexdigest()
eabd8c888ec3adaa9ff60d4aeacbd4cb0a9758d3
416,339
import requests def shortenURL(url, key=None): """Take a URL and return the shortened one.""" return requests.post( "https://short.spgill.me/api", data={"url": url, "key": key} ).text
b7650f04394f81a48fe413bf0e90e01bb2c4295c
418,586
import torch def create_random_dictionary(normalize=False): """ Creates a random (normal) dictionary. :param normalize: Bool. Normalize L0 norm of dictionary if True. :return: Tensor. Created dictionary """ dictionary = torch.rand((64, 512)) if normalize: dictionary = dictionary.__...
e26dfc122ac8b061a4466f48d267ce67c658e6af
342,676