content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def is_valid_ip(ip_addr): """ :param ip_addr: :return: """ octet_ip = ip_addr.split(".") int_octet_ip = [int(i) for i in octet_ip] if (len(int_octet_ip) == 4) and \ (0 <= int_octet_ip[0] <= 255) and \ (0 <= int_octet_ip[1] <= 255) and \ (0 <= int_octet_ip...
7d776107f54e3c27a2a918570cbb267b0e9f419e
3,646,480
def make_replay_buffer(env: gym.Env, size: int) -> ReplayBuffer: """Make a replay buffer. If not ShinEnv: Returns a ReplayBuffer with ("rew", "done", "obs", "act", "log_prob", "timeout"). If ShinEnv: Returns a ReplayBuffer with ("rew", "done", "obs", "act", "log_prob", "timeout", "state"). ...
27f7c0bae37fc1963f4f7c72b42e8da424ab313e
3,646,481
from typing import Callable import decimal def scale_places(places: int) -> Callable[[decimal.Decimal], decimal.Decimal]: """ Returns a function that shifts the decimal point of decimal values to the right by ``places`` places. """ if not isinstance(places, int): raise ValueError( ...
aaf2d9eb14d7a1b28d169d971011b456e2164000
3,646,482
def create_model(params : model_params): """ Create ReasoNet model Args: params (class:`model_params`): The parameters used to create the model """ logger.log("Create model: dropout_rate: {0}, init:{1}, embedding_init: {2}".format(params.dropout_rate, params.init, params.embedding_init)) # Query and Doc...
b175adef530dbbbdb132fed0a6653945ec02fef9
3,646,483
def _process_voucher_data_for_order(cart): """Fetch, process and return voucher/discount data from cart.""" vouchers = Voucher.objects.active(date=date.today()).select_for_update() voucher = get_voucher_for_cart(cart, vouchers) if cart.voucher_code and not voucher: msg = pgettext( '...
d89816fc24192d7d2d4ce7d8edaf11ae94e3f171
3,646,484
def prep_seven_zip_path(path, talkative=False): """ Print p7zip path on POSIX, or notify if not there. :param path: Path to use. :type path: str :param talkative: Whether to output to screen. False by default. :type talkative: bool """ if path is None: talkaprint("NO 7ZIP\nPLEA...
c9d4cc77111c8fc9768c713556fb16e5b8f69ec2
3,646,486
def overlapping_community(G, community): """Return True if community partitions G into overlapping sets. """ community_size = sum(len(c) for c in community) # community size must be larger to be overlapping if not len(G) < community_size: return False # check that the set of nodes in the...
da9e3465c6351df0efd19863e579c49bbc6b9d67
3,646,488
import json def validate_credential(zone, credential): """ Token is already calculated """ source = DataSource(DataSource.TYPE_DATABASE, CONNECTION_FILE_PATH) canAccess = source.get_or_create_client_access_rights(credential, zone) if canAccess: return json.dumps({'success':True}), 200, {'ContentType':'appli...
083ecc977b53e6f5c5df64b0ed52ad9ebeeee821
3,646,489
def gm(data,g1=0.0,g2=0.0,g3=0.0,inv=False): """ Lorentz-to-Gauss Apodization Functional form: gm(x_i) = exp(e - g*g) Where: e = pi*i*g1 g = 0.6*pi*g2*(g3*(size-1)-i) Parameters: * data Array of spectral data. * g1 Inverse exponential width. * g2 ...
7c6aec6d9a21f9c5b2800aa742e5aaa3ead1ac63
3,646,490
import torch def exp_t(u, t): """Compute exp_t for `u`.""" if t == 1.0: return torch.exp(u) else: return torch.relu(1.0 + (1.0 - t) * u) ** (1.0 / (1.0 - t))
8b1a8773b8a5159d9332332d6f77d65cacc68d7c
3,646,491
def decode_json_dict(data): # type: (Dict) -> Dict """Converts str to python 2 unicodes in JSON data.""" return _strify(data)
d2512ea50bf5cfca059ca706adc403bea5af1753
3,646,492
from typing import Any def linear_search(lst: list, x: Any) -> int: """Return the index of the first element of `lst` equal to `x`, or -1 if no elements of `lst` are equal to `x`. Design idea: Scan the list from start to finish. Complexity: O(n) time, O(1) space. For an improvement on linear se...
47e73d53ff68954aadc6d0e9e293643717a807d8
3,646,493
def get_color_cmap(name, n_colors=6): """ Return discrete colors from a matplotlib palette. :param name: Name of the palette. This should be a named matplotlib colormap. :type: str :param n_colors: Number of discrete colors in the palette. :type: int :return: List-like object of colors as h...
90550127196bb1841f48d37ed1f304462d165037
3,646,494
def logkde2entropy(vects, logkde): """ computes the entropy of the kde incorporates vects so that kde is properly normalized (transforms into a truly discrete distribution) """ vol = vects2vol(vects) truth = logkde > -np.infty return -vects2vol(vects)*np.sum(np.exp(logkde[truth])*logkde[trut...
5ce96636607bc3b2160791cda28ef586cb0f29c2
3,646,495
from typing import Optional from typing import Dict import json def get_deployment_json( runner: Runner, deployment_name: str, context: str, namespace: str, deployment_type: str, run_id: Optional[str] = None, ) -> Dict: """Get the decoded JSON for a deployment. If this is a Deployment...
b9cb4cabea6a506cc33c18803bbe45699cf2b222
3,646,496
import ctypes def is_admin() -> bool: """Check does the script has admin privileges.""" try: return ctypes.windll.shell32.IsUserAnAdmin() except AttributeError: # Windows only return None
000fdc8034bf026045af0a5264936c6847489063
3,646,497
import urllib def get_firewall_status(gwMgmtIp, api_key): """ Reruns the status of the firewall. Calls the op command show chassis status Requires an apikey and the IP address of the interface we send the api request :param gwMgmtIp: :param api_key: :return: """ global gcontext...
16d06a5659e98b3d420ab90b21d720367ecde97a
3,646,498
import logging def create_logger(name, logfile, level): """ Sets up file logger. :param name: Logger name :param logfile: Location of log file :param level: logging level :return: Initiated logger """ logger = logging.getLogger(name) handler = logging.FileHandler(logfile) forma...
83a0614053c558682588c47e641eceee368f88e0
3,646,499
def checksum(number): """Calculate the checksum. A valid number should have a checksum of 1.""" check = 0 for n in number: check = (2 * check + int(10 if n == 'X' else n)) % 11 return check
8ada40ca46bc62bbe8f96d69528f2cd88021ad6a
3,646,502
def instanceof(value, type_): """Check if `value` is an instance of `type_`. :param value: an object :param type_: a type """ return isinstance(value, type_)
3de366c64cd2b4fe065f15de10b1e6ac9132468e
3,646,503
def step(y, t, dt): """ RK2 method integration""" n = y.shape[0] buf_f0 = np.zeros((n, ndim+1)) buf_f1 = np.zeros((n, ndim+1)) buf_y1 = np.zeros((n, ndim+1)) buf_f0 = tendencies(y) buf_y1 = y + dt * buf_f0 buf_f1 = tendencies(buf_y1) Y = y + 0.5 * (buf_f0 + buf_f1) * dt retu...
e3c946b37d96ad0083fc5cc7a8d84b2f03ca897b
3,646,504
import torch import gc def sample_deletes(graph_, rgb_img_features, xyz, delete_scores, num_deletes, threshold, gc_neighbor_dist, padding_config, **kwargs): """Sample Deletes. Args: graph_: a torch_geometric.data.Batch instance with attributes...
3a24d3806e3e7aebf5ae6d2c7141149358d21607
3,646,505
def make_char(hex_val): """ Create a unicode character from a hex value :param hex_val: Hex value of the character. :return: Unicode character corresponding to the value. """ try: return unichr(hex_val) except NameError: return chr(hex_val)
edbbad92c56ec74ff28295c46dca4f2976768d0a
3,646,506
def normalize(features): """ Normalizes data using means and stddevs """ means, stddevs = compute_moments(features) normalized = (np.divide(features, 255) - means) / stddevs return normalized
3b4c07bf80e68ec3d6c807a9293aa5b4f4203401
3,646,507
def get_args_from_str(input: str) -> list: """ Get arguments from an input string. Args: input (`str`): The string to process. Returns: A list of arguments. """ return ARG_PARSE_REGEX.findall(input)
50de69e4ee60da31a219842ce09833a92218ea14
3,646,508
from typing import List def simulate(school: List[int], days: int) -> int: """Simulates a school of fish for ``days`` and returns the number of fish.""" school = flatten_school(school) for day in range(1, days + 1): school = simulate_day(school) return sum(school)
efcfbfdde9c3fc941a40028459ddc35db0653296
3,646,510
import torch def SPTU(input_a, input_b, n_channels: int): """Softplus Tanh Unit (SPTU)""" in_act = input_a+input_b t_act = torch.tanh(in_act[:, :n_channels, :]) s_act = torch.nn.functional.softplus(in_act[:, n_channels:, :]) acts = t_act * s_act return acts
a03cc114cf960af750b13cd61db8f4d2e6c064ad
3,646,511
def is_fouling_team_in_penalty(event): """Returns True if fouling team over the limit, else False""" fouls_to_give_prior_to_foul = event.previous_event.fouls_to_give[event.team_id] return fouls_to_give_prior_to_foul == 0
ac1578af1092586a30b8fc9cdb3e5814da1f1544
3,646,512
import re def is_img_id_valid(img_id): """ Checks if img_id is valid. """ t = re.sub(r'[^a-z0-9_:\-\.]', '', img_id, re.IGNORECASE) t = re.sub(r'\.+', '.', t) if img_id != t or img_id.count(':') != 1: return False profile, base_name = img_id.split(':', 1) if not profile or not ...
749a8830d1a932465ca0c9c8c3a18032e2dc357e
3,646,513
import warnings def lmc(wave, tau_v=1, **kwargs): """ Pei 1992 LMC extinction curve. :param wave: The wavelengths at which optical depth estimates are desired. :param tau_v: (default: 1) The optical depth at 5500\AA, used to normalize the attenuation curve. :returns tau: ...
04c89605e8ad4188c62b631e173a9c8fe714958a
3,646,514
def minMax(xs): """Calcule le minimum et le maximum d'un tableau de valeur xs (non-vide !)""" min, max = xs[0], xs[0] for x in xs[1:]: if x < min: min = x elif x > max: max = x return min,max
8453b71e5b62592f38f4be84f4366fb02bd0171b
3,646,515
def events(request): """Events""" # Get profile profile = request.user.profile # Get a QuerySet of events for this user events = Event.objects.filter(user=request.user) # Create a new paginator paginator = Paginator(events, profile.entries_per_page) # Make sure page request is an int,...
3561856af65d2e54eb4f00a13ca85ece4c939b7a
3,646,516
from typing import Tuple from typing import Callable def latent_posterior_factory(x: np.ndarray, y: np.ndarray) -> Tuple[Callable]: """Factory function that yields further functions to compute the log-posterior of the stochastic volatility model given parameters `x`. The factory also constructs functions ...
0fe2ec7a7fab480fbe19a374e71ac3ab5232d8e0
3,646,517
def update_build_configuration_set(id, **kwargs): """ Update a BuildConfigurationSet """ data = update_build_configuration_set_raw(id, **kwargs) if data: return utils.format_json(data)
ee02faf0d683e271747d6e30a3ef8ffd9c271e6c
3,646,518
from typing import Optional def create_app(settings_override: Optional[dict]=None) -> Flask: """ Create a Flask app :param settings_override: any settings to override :return: flask app """ app = Flask(__name__, instance_relative_config=True) app.config.from_object('config.settings') ...
2a4ee3b8f4f67db1966a678b6059b53aa21ac73f
3,646,519
def compute_prefix_function(pattern): """ Computes the prefix array for KMP. :param pattern: :type pattern: str :return: """ m = len(pattern) prefixes = [0]*(m+1) i = 0 for q in range(2, m + 1): while i > 0 and pattern[i] != pattern[q - 1]: i = prefixes[...
7933cc33eba53247e858ae40b9691d101c7030e6
3,646,520
def binary_indicator(states, actions, rewards, next_states, contexts, termination_epsilon=1e-4, offset=0, epsilon=1e-10, state_indices=None, ...
68531010c695e4bb8d49d05f5b0ba8799e1e3cf5
3,646,521
import math def sigmoid(num): """ Find the sigmoid of a number. :type number: number :param number: The number to find the sigmoid of :return: The result of the sigmoid :rtype: number >>> sigmoid(1) 0.7310585786300049 """ # Return the calculated value return...
73730a39627317011d5625ab85c146b6bd7793d8
3,646,522
def list_lattices(device_name: str = None, num_qubits: int = None, connection: ForestConnection = None): """ Query the Forest 2.0 server for its knowledge of lattices. Optionally filters by underlying device name and lattice qubit count. :return: A dictionary keyed on lattice names a...
a6fb4754f3f76135ed2083441782924f03160994
3,646,523
def inflate_tilegrid( bmp_path=None, target_size=(3, 3), tile_size=None, transparent_index=None, bmp_obj=None, bmp_palette=None, ): """ inflate a TileGrid of ``target_size`` in tiles from a 3x3 spritesheet by duplicating the center rows and columns. :param Optional[str] bmp_path...
b3c67c9aaa38cc77208f6fc7cafe91814a0fdbb4
3,646,524
def get_name_and_version(requirements_line: str) -> tuple[str, ...]: """Get the name a version of a package from a line in the requirement file.""" full_name, version = requirements_line.split(" ", 1)[0].split("==") name_without_extras = full_name.split("[", 1)[0] return name_without_extras, version
424b3c3138ba223610fdfa1cfa6d415b8e31aff3
3,646,525
def _compute_eval_stats(params, batch, model, pad_id): """Computes pre-training task predictions and stats. Args: params: Model state (parameters). batch: Current batch of examples. model: The model itself. Flax separates model state and architecture. ...
cc7e9b48d6255c8f82ae2bff978c54631d246bda
3,646,526
import locale import itertools def validateTextFile(fileWithPath): """ Test if a file is a plain text file and can be read :param fileWithPath(str): File Path :return: """ try: file = open(fileWithPath, "r", encoding=locale.getpreferredencoding(), errors="strict") # Read only a...
22167a4501ca584061f1bddcc7738f00d4390085
3,646,527
from bs4 import BeautifulSoup def get_title(filename="test.html"): """Read the specified file and load it into BeautifulSoup. Return the title tag """ with open(filename, "r") as my_file: file_string = my_file.read() file_soup = BeautifulSoup(file_string, 'html.parser') #find all ...
31c35588bb10132509a0d35b49a9b7eeed902018
3,646,528
import re def is_valid_dump_key(dump_key): """ True if the `dump_key` is in the valid format of "database_name/timestamp.dump" """ regexmatch = re.match( r'^[\w-]+/\d{4}_\d{2}_\d{2}_\d{2}_\d{2}_\d{2}_\d+\.\w+\.dump$', dump_key, ) return regexmatch
66fd7d465f641a96bd8b22e95918a6dcbefef658
3,646,529
import math def GetProfileAtAngle( imdata, xc,yc, angle, radius, width=1 ): """ Returns a 1D profile cut through an image at specified angle, extending to specified radius. Note: this is designed to imitate pvect, so angles are measured CCW from +x axis! This function uses IRAF coordinates (1...
5c20ae064989251a807690e8f90f7156a6dbe642
3,646,530
def extract_axon_and_myelin_masks_from_image_data(image_data): """ Returns the binary axon and myelin masks from the image data. :param image_data: the image data that contains the 8-bit greyscale data, with over 200 (usually 255 if following the ADS convention) being axons, 100 to 200 (usually 127 if f...
087f80d4c55b7bbba7e60720be26ff3e3ca1648a
3,646,532
def expand_advanced(var, vars_, nounset, indirect, environ, var_symbol): """Expand substitution.""" if len(vars_) == 0: raise MissingClosingBrace(var) if vars_[0] == "-": return expand_default( var, vars_[1:], set_=False, nounset=nounset, ...
1be5d66c18775bca8669d97ccf8ccd439f154ff2
3,646,534
def overlap(n2, lamda_g, gama): """ Calculates the 1/Aeff (M) from the gamma given. The gamma is supposed to be measured at lamda_g (in many cases we assume that is the same as where the dispersion is measured at). """ M = gama / (n2*(2*pi/lamda_g)) return M
00e1d59a6a8e5b908acfa3097cfb9818edaf608f
3,646,535
def fill_none(pre_made_replays_list): """Fill none and reformat some fields in a pre-made replays list. :param pre_made_replays_list: pre-made replays list from ballchasing.com. :return: formatted list. """ for replay in pre_made_replays_list: if replay["region"] is None: replay...
ee900227a8afcba71e6a00ef475892da4fdc3e3b
3,646,536
def parse_args_from_str(arg_str, arg_defs): # , context=None): """ Args: args_str (str): argument string, optionally comma-separated arg_defs (tuple): list of argument definitions context (dict, optional): When passed, the arguments are parsed for ``$(var_name)`` macros, ...
1c21cf170c360c7b429b1303bd19e1a23ea5cd3c
3,646,537
import torch def model_evaluation( data_loader, ml_model_name, ml_model, smiles_dictionary, max_length_smiles, device_to_use, ): """ Evaluation per batch of a pytorch machine learning model. Parameters ---------- data_loader : torch.utils.data The training data as ...
8c381eee394e989f8920cc52ad4b94ca4b502741
3,646,538
def reverse_dict2(d): """Reverses direction of dependence dict >>> d = {'a': (1, 2), 'b': (2, 3), 'c':()} >>> reverse_dict(d) # doctest: +SKIP {1: ('a',), 2: ('a', 'b'), 3: ('b',)} :note: dict order are not deterministic. As we iterate on the input dict, it make the output of this functio...
2419538a13699015f8fefa156e89cf9b1960e358
3,646,539
import random def Flip(p, y='Y', n='N'): """Returns y with probability p; otherwise n.""" return y if random.random() <= p else n
072e170e3f37508a04f8bdbed22470b178f05ab9
3,646,540
def sub_to_db(sub, add_area=True, area_srid=3005, wkt=True, wkb=False, as_multi=True, to_disk=False, procs=1, engine=None): """ Convert the object to a SQLite database. Returns the |db| module exposin...
6f3d3763a129a4235c0e5c0e884f7ab62bdfc391
3,646,542
def T_autoignition_methods(CASRN): """Return all methods available to obtain T_autoignition for the desired chemical. Parameters ---------- CASRN : str CASRN, [-] Returns ------- methods : list[str] Methods which can be used to obtain T_autoignition with the given input...
ab194547a1cc7b5eeb2032b1decad366bc4b43c2
3,646,543
def masa(jd, place): """Returns lunar month and if it is adhika or not. 1 = Chaitra, 2 = Vaisakha, ..., 12 = Phalguna""" ti = tithi(jd, place)[0] critical = sunrise(jd, place)[0] # - tz/24 ? last_new_moon = new_moon(critical, ti, -1) next_new_moon = new_moon(critical, ti, +1) this_solar_month = raasi(...
b8b7572f4b5dc597d844683e30c92be618e32c43
3,646,545
from scipy.special import erf def sigma(s): """The probablity a normal variate will be `<s` sigma from the mean. Parameters ---------- s : float The number of sigma from the mean. Returns ------- p : float The probability that a value within +/-s would occur. """ ret...
88727617b1cca678613818be8fdb90e114b25438
3,646,546
def addneq_parse_residualline(line: str) -> dict: """ Parse en linje med dagsløsningsresidualer fra en ADDNEQ-fil. Udtræk stationsnavn, samt retning (N/E/U), spredning og derefter et vilkårligt antal døgnresidualer. En serie linjer kan se således ud: GESR N 0.07 0.02 -0....
6d1556cbd01f3fe4cd66dcad231e41fa6b1b9470
3,646,547
def get_xsd_schema(url): """Request the XSD schema from DOV webservices and return it. Parameters ---------- url : str URL of the XSD schema to download. Returns ------- xml : bytes The raw XML data of this XSD schema as bytes. """ response = HookRunner.execute_inj...
12f5088fea1b9268d75ee90d60b729c8a9577dd0
3,646,549
def get_char_pmi(data): """ 获取 pmi :param data: :return: """ print('get_char_pmi') model = kenlm.LanguageModel('../software/kenlm/test.bin') res = [] for line in data: words = line.strip().split() length = len(words) words.append('\n') i = 0 pm...
2cb28e7671561a52efbbf98431e3c938700f691a
3,646,550
def fahrenheit_to_celsius(fahrenheit): """Convert a Fahrenheit temperature to Celsius.""" return (fahrenheit - 32.0) / 1.8
4aee3dd0b54450fabf7a3a01d340b45a89caeaa3
3,646,551
import random import itertools def sample_blocks(num_layers, num_approx): """Generate approx block permutations by sampling w/o replacement. Leave the first and last blocks as ReLU""" perms = [] for _ in range(1000): perms.append(sorted(random.sample(list(range(0,num_layers)), num_approx))) ...
b4b75e77b3749bc7766c709d86bf1f694898fc0d
3,646,552
def adjacent_values(vals, q1, q3): """Helper function for violinplot visualisation (courtesy of https://matplotlib.org/gallery/statistics/customized_violin.html#sphx-glr-gallery-statistics-customized-violin-py) """ upper_adjacent_value = q3 + (q3 - q1) * 1.5 upper_adjacent_value = np.clip(upper_adja...
a596ed82a1d66213dbdd3f19b29d58b36979c60d
3,646,553
def l2_first_moment(freq, n_trials, weights): """Return the first raw moment of the squared l2-norm of a vector (f-p), where `f` is an MLE estimate of the `p` parameter of the multinomial distribution with `n_trials`.""" return (np.einsum("aiai,ai->", weights, freq) - np.einsum("aiaj,ai,aj->", weights, ...
bf597aaa57759dc6d4f0ee1f5ed4f99f49ea271b
3,646,554
def sigmoid(x: float, a: float = 1, b: float = 1, shift: float = 0) -> float: """ Sigmoid function represented by b * \frac{1}{1 + e^{-a * (x - shift)}}} Args: x (float): Input x a (float, optional): Rate of inflection. Defaults to 1. b (float, optional): Difference of lowest to hig...
761497db712619008c1261d2388cea997ae3fff8
3,646,555
def db_credentials(): """Load creds and returns dict of postgres keyword arguments.""" creds = load_json('creds.json') return { 'host': creds['db_host'], 'user': creds['db_username'], 'password': creds['db_password'], 'database': creds['db_database'] }
4248452ffb5a9c05b14449972c1db7a18d906b73
3,646,556
import logging def generate_corpus_output( cfg, docL, tfidfL ): """ Generate a list of OutputRecords where the number of key words is limited to the cfg.corpusKeywordCount highest scoring terms. (i.e. cfg.usePerDocWordCount == False) """ outL = [] # for the cfg.corpusKeyWordCount highest...
2296d319fd00022df73da9e7d8484adfd5ab16ad
3,646,557
import tqdm def harmonic_fitter(progressions, J_thres=0.01): """ Function that will sequentially fit every progression with a simple harmonic model defined by B and D. The "B" value here actually corresponds to B+C for a near-prolate, or 2B for a prolate top. There...
55a2c4080938c947501ed830f4236ca8f87608e8
3,646,560
def print_KruskalWallisH(div_calc): """ Compute the Kruskal-Wallis H-test for independent samples. A typical rule is that each group must have at least 5 measurements. """ calc = defaultdict(list) try: for k1, v1 in div_calc.iteritems(): for k2, v2 in v1.iteritems(): ...
74579ad2f9ee4336ab33f099982a9419d723774e
3,646,561
import random import string def _random_exptname(): """Generate randome expt name NNNNNNNN_NNNNNN, where N is any number 0..9""" r = ''.join(random.choice(string.digits) for _ in range(8)) r = r + '_' + ''.join(random.choice(string.digits) for _ in range(6)) return r
d9c72ed4bf742adf50e1fdad4f6acb1cc0046167
3,646,562
def remove_store(store_name): """ Deletes the named data store. :param store_name: :return: """ return get_data_engine().remove_store(store_name)
ea8ada276095c2ceb85b339b2a925fa53fd93a1e
3,646,563
import random def limit_checkins_per_user(checkins: list, num_checkins_per_user: int, random_seed=1): """ Limit for each user a maximum number of check-ins by randomly select check-ins. Parameters ---------- checkins: list list of check-ins num_checkins_per_user: int max numbe...
286760c3630162b78c314f9f8be0943350f47859
3,646,565
import warnings import warnings def getCharacterFilmography(characterID, charIF, charDF, movieIF, movieKF, personIF, personKF, limit=None): """Build a filmography list for the specified characterID.""" try: ifptr = open(charIF, 'rb') except IOError, e: warnings....
ddf7f1da3e95441a2da9d3fe2f16065e0a13f634
3,646,566
def sqrt_fixed_full(x, config, is_training=True, causal=True): """Full attention matrix with sqrt decomposition.""" bsize = x.shape[0] query, key, value = attention.get_qkv(x, x, x, hidden_size=config.model_size, num_heads=config.num_heads, ...
3ee88f2adf767c6fb6e0f1c006ff301c45ffc322
3,646,567
def mcf_from_row(row, gene_to_dcid_list): """Generate data mcf from each row of the dataframe""" gene = row['Gene name'] tissue = get_class_name(row['Tissue']) cell = get_class_name(row['Cell type']) expression = EXPRESSION_MAP[row['Level']] reliability = RELIABILITY_MAP[row['Reliability']] ...
ee78c68bb89a100fa4e0b972d0907e14dcb6d289
3,646,568
def loads(json_str, target=None): """ Shortcut for instantiating a new :class:`JSONDecoder` and calling the :func:`from_json_str` function. .. seealso:: For more information you can look at the doc of :func:`JSONDecoder.from_json_str`. """ return _decoder.from_json_str(json_str, target)
76eab90dd544d695f55967969d81ef9cccb1c2fd
3,646,569
def discover(discover_system: bool = True) -> Discovery: """ Discover capabilities offered by this extension. """ logger.info("Discovering capabilities from aws-az-failure-chaostoolkit") discovery = initialize_discovery_result( "aws-az-failure-chaostoolkit", __version__, "aws" ) dis...
ad9b7674f8f8f7cc06ce21dacba2138231b7e69c
3,646,570
def getter_nofancy(a, b, asarray=True, lock=None): """ A simple wrapper around ``getter``. Used to indicate to the optimization passes that the backend doesn't support fancy indexing. """ return getter(a, b, asarray=asarray, lock=lock)
63e355eb3245c8f394c345fb2ebd4e469fcd7500
3,646,571
def xy_to_array_origin(image): """Return view of image transformed from Cartesian to array origin.""" return rgb_transpose(image[:, ::-1])
e2e47f95093e1808cfbe7c2ba28af8c3e5b40307
3,646,572
import csv def read_csv(infile, delimiter=',', encoding='utf-8', named=False): """Reads a csv as a list of lists (unnamed) or a list of named tuples (named) Args: string infile: the file to read in OPTIONAL: string delimiter: the delimiter used (default ',') encoding en...
7318293d884fa80a7d93d8046f66b3801d809f42
3,646,573
def get_directions_id(destination): """Get place ID for directions, which is place ID for associated destination, if an event""" if hasattr(destination, 'destination'): # event with a related destination; use it for directions if destination.destination: return destination.destinatio...
f7cd182cb5ea344c341bf9bfaa7a4389335ae353
3,646,575
def decode_token(params, token_field=None): """ This function is used to decode the jwt token into the data that was used to generate it Args: session_obj: sqlalchemy obj used to interact with the db params: json data received with request token_field: name of the field that tok...
8adac31df7d5659c06f5c4d66fc86ae556531aae
3,646,576
def find_storage_pool_type(apiclient, storagetype='NetworkFileSystem'): """ @name : find_storage_pool_type @Desc : Returns true if the given storage pool type exists @Input : type : type of the storage pool[NFS, RBD, etc.,] @Output : True : if the type of storage is found False : if th...
1d3e64185e0361f02a8cc7e2e4316895e22e517e
3,646,579
from typing import Any from typing import cast def parse_year(candidate: Any) -> int: """Parses the given candidate as a year literal. Raises a ValueError when the candidate is not a valid year.""" if candidate is not None and not isinstance(candidate, int): raise TypeError("Argument year is expec...
337cc3be16e1e1246d1d1f02b55665c655fe131f
3,646,580
def dropout2d(tensor: Tensor, p: float = 0.2) -> Tensor: """ Method performs 2D channel-wise dropout with a autograd tensor. :param tensor: (Tensor) Input tensor :param p: (float) Probability that a activation element is set to zero :return: (Tensor) Output tensor """ # Check argument as...
6719fa5a3e55665770faf1034677642d78561f83
3,646,581
def svn_repos_finish_report(*args): """svn_repos_finish_report(void * report_baton, apr_pool_t pool) -> svn_error_t""" return _repos.svn_repos_finish_report(*args)
19b42660beb7fa5995a8c5e6e0cb5df39116ddb5
3,646,582
import array import itertools def problem451(): """ Consider the number 15. There are eight positive numbers less than 15 which are coprime to 15: 1, 2, 4, 7, 8, 11, 13, 14. The modular inverses of these numbers modulo 15 are: 1, 8, 4, 13, 2, 11, 7, 14 because 1*1 m...
efb000a8f367cf13e7aec2117efed092e3d5a5f3
3,646,583
import torch def collate_molgraphs(data): """Batching a list of datapoints for dataloader. Parameters ---------- data : list of 3-tuples or 4-tuples. Each tuple is for a single datapoint, consisting of a SMILES, a DGLGraph, all-task labels and optionally a binary mask indicati...
3ff726fca71ab64ec1e2e665babd8f46b027e819
3,646,584
def recouvrement_view(request, id): """ Fonction Detail """ user = request.user recouvrement = Recouvrement.objects.filter(user=user).get(id=id) context = { 'recouvrement': recouvrement, } template_name = 'pages/recouvrement/recouvrement_view.html' return render(reque...
f0e26257a39ef385b9dfaa51bff68b0fec51a263
3,646,586
def getFileServicesNames(fileServices=None, verbose=True): """ Returns the names and description of the fileServices available to the user. :param fileServices: a list of FileService objects (dictionaries), as returned by Files.getFileServices(). If not set, then an extra internal call to Jobs.getFileServi...
ef476f2c661dadebee8e8a16863ff2f4c286d99e
3,646,587
def username_in_path(username, path_): """Checks if a username is contained in URL""" if username in path_: return True return False
131a8fa102fd0a0f036da81030b005f92ea9aab0
3,646,588
def str_parse_as_utf8(content) -> str: """Returns the provided content decoded as utf-8.""" return content.decode('utf-8')
75b8d5f1f8867c50b08146cc3edc1d0ab630280a
3,646,589
def TypeProviderClient(version): """Return a Type Provider client specially suited for listing types. Listing types requires many API calls, some of which may fail due to bad user configurations which show up as errors that are retryable. We can alleviate some of the latency and usability issues this causes by...
2e735b37d01b9a9a0b44d5cf04acd89d2a8d9b90
3,646,590
from typing import Optional from datetime import datetime from typing import List from typing import Dict from typing import Any def create_indicator( pattern: str, pattern_type: str, created_by: Optional[Identity] = None, name: Optional[str] = None, description: Optional[str] = None, valid_fr...
421e9d1d060709facb9a8b8d6831b6a45ef479c9
3,646,591
def import_data( path_to_csv: str, response_colname: str, standards_colname: str, header: int = 0, nrows: int = None, skip_rows: int = None, ) -> pd.DataFrame: """Import standard curve data from a csv file. Args: path_to_csv: Refer to pd.read_csv docs. response_colname: ...
fffc650ac7b672e0585b0dc307977c4adf9a0a69
3,646,592
def plus(x: np.ndarray, y: np.ndarray) -> np.ndarray: """ 矩阵相加""" if x.shape == y.shape: return x + y
9d042d90c8d3ca9588c02ddd9ed53ec725785d13
3,646,593
def add_noise(wave, noise, fs, snr, start_time, duration, wave_power): """Add a noise to wave. """ noise_power = np.dot(noise, noise) / noise.shape[0] scale_factor = np.sqrt(10**(-snr/10.0) * wave_power / noise_power) noise = noise * scale_factor offset = int(start_time * fs) add_length = mi...
3f8df3098751b081f93b61da16682bdac2bf6a02
3,646,594
def _sort_factors(factors, **args): """Sort low-level factors in increasing 'complexity' order.""" def order_if_multiple_key(factor): f, n = factor return len(f), n, default_sort_key(f) def order_no_multiple_key(f): return len(f), default_sort_key(f) if args.get('multiple', Tru...
60be823e0f12b0e33d6a9567458cc98d95d1f900
3,646,595
def get_affix(text): """ This method gets the affix information :param str text: Input text. """ return " ".join( [word[-4:] if len(word) >= 4 else word for word in text.split()])
eb0aa68e803ce6c0ae218f4e0e2fd1855936b50f
3,646,596