content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def handle_array_input(args): """ Format any command argument that is supposed to be an array from a string to a list. parameter: (dict) args The command arguments dictionary returns: The arguments dict with field values transformed from strings to lists where necessary """ arr...
f072412936e16425d1217423c01689d8c32e3f2e
71,937
def parse_source(source): """Parse a source in the format <region>:<db-identifier> Args: source (str): The source string Returns: :class:`Source`: A Source namedtuple. """ try: region, _id = source.split(":", 1) except ValueError: raise ValueError( "...
a799392e353dedc6e34d2242143ae3212923cae0
71,938
def mat_load(path, m_dict=None): """ Load mat files. :param path: :return: """ if m_dict is None: data = sio.loadmat(path) else: data = sio.loadmat(path, m_dict) return data
ebab6c377c0d7d2fc544d5f94b4f002021454677
71,939
def internal_redirect(url, default_path): """ Redirect to the specified URL after checking that host is in the allowed hosts list :param url: URL to redirect to :param default_path: Default path to redirect to if url is unsafe """ if not is_safe_url(url, settings.ALLOWED_HOSTS): retu...
5ee3e46e46ed9a28e46ae3e741a9ffa255ec3a7d
71,940
def convert_to_letter(grade): """Convert a decimal number to letter grade""" grade = round(grade, 1) if grade >= 82.5: return 'A' elif grade >= 65: return 'B' elif grade >= 55: return 'C' elif grade >= 50: return 'D' else: return 'F'
13ce25275750e7a27e0699078a15ba551674a941
71,941
import numpy def _reorient_4d(image): """ Reorganize the data for a 4d nifti """ # print 'converting 4d image' # Create empty array where x,y,z correspond to LR (sagittal), PA (coronal), IS (axial) directions and the size # of the array in each direction is the same with the corresponding dire...
9159e75daef5bc65dab9a7d8c6ff0cfa35fae96c
71,942
def mask_sequence(aln, rstart, rend): """Masks quality according to changed softclips in cigarstring Args: aln (pysam.AlignedSegment): aligned read rstart (int): start of non-primer sequence rend (int): end of non-primer sequence Returns: aln (pysam.AlignedSegment): aligned...
ba351335136411e4c0dd1c55a800c9990fe3f217
71,943
import base64 def get_encid(decid): """ Generate an encrypted ID from a decrypted ID :param decid: Decrypted ID, type int :return: Encrypted ID, type str """ try: int(decid) except: raise InvalidIDException('Decrypted ID must be int-castable') # Slashes are not URL-fr...
9fd425bc8f09ade997b12d533386ef2be7c6eaa8
71,944
def time_coord(cube): """ Return the variable attached to time axis. Examples -------- >>> import iris >>> url = ('http://omgsrv1.meas.ncsu.edu:8080/thredds/dodsC/' ... 'fmrc/us_east/US_East_Forecast_Model_Run_Collection_best.ncd') >>> cube = iris.load_cube(url, 'sea_water_potent...
12a706f956846e8471d0d7f044367c77210c4486
71,946
def filter_lowpass(trace: Trace, sampling_frequency: int, cutoff: int) -> Trace: """ Apply a lowpass digital filter (Butterworth) to `trace`, given `sampling_frequency` and `cutoff` frequency. :param trace: :param sampling_frequency: :param cutoff: :return: """ return _filter_any(trace,...
47dc83a5a53f97af562eba45289b9bf52bcfbc9b
71,947
import multiprocessing def _valid_general_args(cfg, logger): """ Validates the "general" parameters of a json configuration file used for inference. :param cfg: EasyDict, json configuration file imported as dictionary :param logger: logger instance :return: EasyDict, dictionary compos...
0f78e2b905a15289730ed4252d3c7e6568d1b5fb
71,948
import re def oneliner(s) -> str: """Collapse any whitespace in stringified `s` into a single space. """ return re.sub(r"[\n ]+", " ", str(s).strip())
ed1d419b4fab8cb2deccdbc2944996ef7be28cc5
71,949
def _get_nominal_integer_dict(nominal_vals): """Convert nominal values in integers, starting at 0. Parameters: nominal_vals (pd.Series): A series. Returns: d (dict): An dictionary with numeric values. """ d = {} for val in nominal_vals: if val not in d: curre...
1005c00ea5d7033368b589d4954934e85b0e1d6e
71,950
import cgi def xml_escape(input): """Replace special characters "&", "<" and ">" to HTML-safe sequences. """ return cgi.escape(input)
87f60cdf680372761da23e64c2880ad649d5b0a6
71,951
from typing import Counter def diff_counts(values : list[int]) -> dict[int, int]: """Count the gaps between ordered elements in a list, by size.""" ordered = [0] + sorted(values) + [max(values) + 3] return Counter(j - i for i, j in zip(ordered, ordered[1:]))
897cb7fdfed85b37bd8bd7031290e34199c57574
71,952
def plot_visibility(snnames, obs_windows, dark_time, priorities=None, labeltype='index', figsize=None): """Function for plotting visibility of targets as previously determined in ztfcosmology_visibility.ipynb """ if priorities is None: priorities = np.zeros(len(snnames), dtype=int) ...
2f396fb45cc3c9526cb74e5824aca5acbce10c07
71,953
import re def find_autoxc_code_skeleton(lines,subr_lines): """ Assuming that the subroutine is of the autoxc code skeleton type find all the if-branches and return a list of all the (start,end) tuples. """ (lineno_start,lineno_end) = subr_lines ifbranches = [] line = lineno_start ifstart = -1 ...
122e5e082929451019d1689eed9f182085593daa
71,954
def get_one_prior_probability(state, segment_df, total_positions): """ Returns the number of genomics positions that are of the state """ state_df = segment_df[segment_df[3] == state] num_pos_this_state = float(sum(state_df['num_occ'])) return num_pos_this_state / float(total_positions)
157666f84d9ba6b7d236bb0f10e331e9315d9efa
71,955
def ticket_details(): """ Upon request, generate a TicketDetails object for the user's session if it does not exist, fetch the details of the requested ticket as well as its associated users by the given ticket URL using the TicketDetails get_ticket() method. Render the pop-up modal HTML with the ti...
2276f2a5b9d57667433c75bec35d1320c6a7cca9
71,956
from typing import Callable def stochastic_policy( fun: Callable[[FloatLike], FloatLike], fun_params0: randvars.RandomVariable, rng: np.random.Generator, ) -> float: """Policy returning a random action. Parameters ---------- fun : One-dimensional objective function. fun_params...
57524f09045a21b47eafe553b869e5ad98838a29
71,957
import torch def conv1x1(in_planes, out_planes, stride=1, num_experts=1, binary=False, activation=torch.sigmoid, use_se=False): """1x1 convolution""" if num_experts > 1: return EBConv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False, num_experts=num...
8461c4e8be1438aeaf383b0804e4aebfa9720298
71,959
def get_welcome_response(): """ If we wanted to initialize the session to have some attributes we could add those here """ session_attributes = {} card_title = "Welcome" speech_output = "Welcome to the UCSC Bus Bot. " \ "Please state the bus stop id or location to get starte...
deed05421cf8d19b88f1c1703f3bab15cf6354a2
71,960
def parse_request_query(request) -> QueryModel: """ Like atoolbox.utils.parse_request_query but simplified and with a more human readable error response. """ data = {} for k in QueryModel.__fields__.keys(): v = request.query.get(k) if v is not None: data[k] = v try: ...
62c59422610d6080d97a465b159e881746abcbec
71,961
def convert_netdict_to_pydict(dict_in): """Convert a net dictionary to a Python dictionary. Parameters ---------- dict_in : dict Net dictionary to convert. Returns ------- dict Dictionary converted to Python. """ pydict = {} for key in dict_in.Keys: pyd...
6aa9bb5ac00ff92d23ff5a449d096caad0d01c9c
71,962
def sigmoid (x, parameters): """Sigmoid function POI = A2 + (A1 - A2) / (1. + exp((x - x0) / dx)) Parameters ---------- x: float or array of floats variable parameters: dict dictionary containing 'sigmoid_A1','sigmoid_A2','sigmoid_x0', and 'sigmoid_dx' R...
bcf77e2e508800f6c4c37ec4c8c79c4bda2a6934
71,963
def heatmap_chart(df, title=""): """Plot custom confusion matrix chart.""" source = df.copy() source = source.reset_index() source = pd.melt(source, id_vars="index", value_vars=df.columns) source.columns = ["m1", "m2", "value"] base = alt.Chart(source).encode( alt.X('m1:O', title="New M...
6e6405afcbffff7159446c96ad1c87757708ac09
71,964
def server(request): """Return the server based upon the server class in the request.""" if 'production' == request.param: return ReviewBoardServer('https', 'reviews.reviewboard.org') if 'demonstration' == request.param: return DemonstrationServer() raise ValueError("invalid internal tes...
d4a485706258a032e6a069ce9cdad4671f13c141
71,965
def poolformer_s24(pretrained=False, **kwargs): """ PoolFormer-S24 model, Params: 21M """ model = _create_poolformer('poolformer_s24', pretrained=pretrained, layers=(4, 4, 12, 4), **kwargs) return model
84f255eff21b158e4826830e74e3cb8dcdfe4ae0
71,966
def laptop_history(request, id): """ View a history of password retrievals and rotations for a given laptop :param id: Primary key of laptop """ laptop = get_object_or_404(Laptop, retired=False, pk=id) password_retrievals = laptop.password_retrievals.all() password_rotations = laptop.passwo...
20908500aa5946e3e4dce7004ef57ae15efae753
71,967
import logging def make_restore_checkpoint_fn(checkpoint_path, prefix='', skip_regex=None): """Returns scaffold function to restore parameters from v1 checkpoint. Args: checkpoint_path: path of the checkpoint folder or file. Example 1: '/path/to/model_dir/' Example 2: '/path/to/model.ckpt-22500' ...
3af8013b460cd9e7f3ef0396c144723600943a73
71,968
from typing import List def binary_search(input_array: List[int], target: int): """ Given a sorted input array of integers, the function looks for a target or returns None Returns: Target index or None """ if not input_array or not target: return None left_pointer = 0 ri...
b9f389d1b31e5b95bb885bd638549f7775db207e
71,969
from datetime import datetime def _sort_by_date(time_coord): """ Private sorting function used by _file _sort_by_earliest_date() and sort_by_earl iest_date(). Args: time_coord: Cube time coordinate for each cube to be sorted by. Returns: time_origin: The time origin t...
89c52c40dd8dfa03cbe431a4db6f107b42b22e81
71,970
def preprocess_img(img): """ Preprocesses screenshot of AH for OCR. Removes details which would be needed for image matching. """ # grayscale newimg = get_grayscale(img) #cv2.imwrite("screenshots/img_9g.png",newimg) # crop newimg = newimg[175:660, 0:1920] # cv2.imwrite("screensh...
ff3348580e84e2d01069c25b46c327dd98177817
71,971
from typing import Callable import functools def aws_provider(api: str = None, name="default", should_load: Callable[[], bool] = None): """ Decorator for marking methods that create a Service instance as a ServicePlugin. Methods marked with this decorator are discoverable as a PluginSpec within the namesp...
8db109647f82fbf2fe44ccd1f4140e704f1247b6
71,972
import galsim def rotate(image, rot_center, interpolate=False, force_interpolate=False): """ Rotate an image about a point. Defaults to using numpy array operations, which means that the rotation center is rounded to the nearest half-pixel grid point. Optionally, use GalSim to rotate about arbitrary pos...
86bc0e6a651ac997cd044daac07597cc5896c066
71,973
def _parse_labels_map(labels_path): """Loads a labels map via the `label_map_util` from the TF-Models library. Args: labels_path: path to a labels map in `.pbtxt` format Returns: (category_index, class_labels), where `category_index` is a dict mapping IDs to names, and `class_l...
d737831d57f27c983ff54bb7154c26136f3f6a24
71,974
def is_superuser(view): """Allow access to the view if the requesting user is a superuser.""" return view.request.user.is_superuser
5a15433200634ca326c36bdc17acbc1ada4e6426
71,975
def _restrict_asap(func=None, backend=None, issuers=None, required=True, subject_should_match_issuer=None): """Decorator to allow endpoint-specific ASAP authorization, assuming ASAP authentication has already occurred. """ def restrict_asap_decorator(func): @wraps(func) ...
6e9496d41a5aab3c0e3aef0662c8eb3e91019a2f
71,977
def tag_row(tag): """Format a tag table row""" return [tag.get('id'), tag.get('name'), tag.get('referenceCount', 0)]
4cd1d0991eae996a52288c6d1d9bb3bd1a368ea6
71,979
import types import numpy import pandas def hpat_pandas_series_sort_values(self, axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last'): """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.Series.sort_values Limit...
31b0f49f2a8e75b0cec27a33b5969893924c96e7
71,980
def get_owner_apikey_id(): """ Get owner api key id from the config file. """ config_key = 'owner_api_key_id' try: owner_apikey_id = CONFIG.get(AUTH_SECTION, config_key) if not validators.uuid(owner_apikey_id): print_config_error_and_exit(AUTH_SECTION, 'Owner API key ID(...
9c7cac14a60b38788ef49d2103e6dd331673ef1b
71,981
import math import time def parse_cookies(target_cookie): """Deserializes single Target cookie into several individual cookies""" if not target_cookie: return {} raw_internal_cookies = get_internal_cookies(target_cookie) now_in_seconds = math.ceil(time.time()) valid_cookies = [deserialize...
33591141624a06bf37f1bc879521b5ac45e8692e
71,982
from typing import Any def get_state_from_observation(observation: Any) -> State: """ Function which given an observation returns a state :param observation: :return: """ return State( robots_data=list(observation[:len(observation) // 2]), time=observation[len(observation) // ...
95e33e884df25a6c4f00ee91dd764d886eafe05e
71,983
from typing import Iterable import ctypes def vaddg(v1: Iterable[float], v2: Iterable[float], ndim: int) -> ndarray: """ Add two n-dimensional vectors https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vaddg_c.html :param v1: First vector to be added. :param v2: Second vector to be added. :...
d87c7171e0296587d02d66e04522ff3f1c5d02e7
71,984
from typing import Any import torch import numbers def python_scalar_to_tensor(data: Any, device: torch.device = torch.device("cpu")) -> Any: """ Converts a Python scalar number to a torch tensor and places it on the given device. """ if isinstance(data, numbers.Number): data = torch.tensor([data], de...
83e4ac093a40225f9c5fe121d9b67424f258e039
71,985
def allpath(path): """ return paths """ paths = path.strip("/").split("/") for i in range(1,len(paths)): paths[i] = paths[i-1] + "/" + paths[i] return paths
8b76f70dbae41a1ae46462d0755dbb5c5c0eb4c1
71,986
def zoom(input, zoom, mode="nearest", blocks=(16, 16, 4), **kwargs): """scale array with nearest neighbors or linear interpolation If a float, `zoom` is the same for each axis. If a sequence, `zoom` should contain one value for each axis. """ if isinstance(zoom, (int, float)): zoom = tuple(...
299689876f03776d121f9d36256ba90adf6f404c
71,989
def calculate_null_kl(experimental_condition_list=None, filename=None): """ Calculates the smoothed null KL distribution. One of the two parameters must be non-null :param experimental_condition_list: [list] The list of treatment condition from which the null kl is to be calculated. :param filename: If ...
55ff2d73827e2a5b0140a0460ea9a4e1a9c97efe
71,990
def read_tsv(file_path): """ General method for converting a tsv into a dictionary of lists, assuming each key has an associated time series :param file_path: :return: """ headers = None header_indexes = None # Each data type will have a list data = defaultdict(list) static_data...
28f2c53c9302269fc3d3e9d34867e6845fa3c13d
71,991
def validate_actions(data): """ Validate an Action configuration dictionary, as imported from actions.yml, for example. The method returns a validated and sanitized configuration dictionary. :arg data: The configuration dictionary :rtype: dict """ # data is the ENTIRE schema... cle...
9e027ccf74d9ec2c610e237fd0b9dca9f7ac9e8b
71,992
def LIGHTNING(conf): """Get Lightning Color code from config""" return conf.get_color("colors", "color_lghtn")
08781e469c7262228904e883594e475be634816b
71,993
def process_ordinal(X): """ordinal numeric value preprocessing.""" # missing value imputation X = median_impute(X, strategy='median') # remove any low info columns (high variance) X = remove_low_info(X) # remove low variance variables X = remove_low_variance(X) # scaling X = scale...
9e144dc6e1e2e145feda80a94ac493acdf44522a
71,996
def devname_from_index(if_index): """Return Windows adapter name for given Windows interface index""" return ifaces.devname_from_index(if_index)
69b5ef2a33451ca755a8388fad5de3fcac0e60d2
71,997
import io import locale def purchase_order_pdf(request, pk): """ Función para imprimir la orden de ventas """ response = HttpResponse(content_type='application/pdf') pdf_name = _("purchase_order.pdf") response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name # Los productos de la...
6d5be05cfbc32aecb904c724fa406371e822e5c2
71,998
def chrxor(st1, st2, strf1, ar1, strf2, ar2, fun1, fun2): """Takes two strings and applies a function to each charater in the string. Function is some function that takes characters and turns them into integers. This could be something to turn them into ascii order, or simply map them to another range of integers....
d463e21e55bf41ce9dee612d77810c2000210477
71,999
from typing import List def set_firewall_rule_ids_to_computer_command(client: Client, computer_id: int, rule_ids: List[int], overrides: bool) -> CommandResults: """ Assign rule IDs to a certain computer. Args: client (Client): The Trend Micro API clie...
58ac799738c8ce510cc30f1f6d5de26ad5e124d2
72,000
from datetime import datetime import torch def train(model, epochs, data, optimizer, criterion, device, logger): """ Train NN """ epochs = epochs steps = 0 running_loss = 0 print_every = 40 for e in range(epochs): start_ts = datetime.now() model.train() for images, labe...
92f5e8b9a7388de26a3369338c5ceed37ffea4ee
72,001
def single_column_kernel(i, scale_sqrt=True): """Returns a kernel function with weights that correspond to a single column of the veps numpy.ndarray. :param int i: column of which weights should be selected :return: kernel function that linearly weights the genotypes with a single column of veps (e.g. corr...
9fb5bbbf8bc5f86709a78924869030ac5398c749
72,002
def is_exists(t): """Whether t is of the form ?x. P x.""" return t.is_comb() and t.fun.is_const() and \ t.fun.name == "exists" and t.arg.is_abs()
7f7c5f32685df636ec2181efd5a1b7dbc8313d4c
72,004
from typing import Dict from typing import Any def get_amendments_for_year(year: int, bill_number: int) -> Dict[str, Any]: """See: http://wslwebservices.leg.wa.gov/legislationservice.asmx?op=GetAmendmentsForYear""" argdict: Dict[str, Any] = dict(year=year, billNumber=bill_number) keydict: Dict[str, Any] =...
8866bd8bf00fee8431bb4eed9beb2716d7dc1d99
72,005
def generate_help(): """Generates help text with alphabetically sorted recipes.""" help_text = '\nAvailable recipes:\n\n' recipes = config.Config.get_registered_recipes() for contents, _, _ in sorted(recipes, key=lambda k: k[0]['name']): help_text += ' {0:<35s}{1:s}\n'.format( contents['name'], cont...
92451c52feb7610b8ceb4bbb562d04cec3415b4c
72,006
def welch_statistic(sample_a, sample_b): """Calculates Welch's t statistic. Takes a 2D data matrix, a column to classify data by, and the labels corresponding to the data of interest. Assumes that the largest (-1) column in the data matrix is the dependent variable. Parameters ---------- d...
a6f937aebaa52709a9763e0dbb3d5b6946e69dfe
72,007
def lookup(type, language, key): """ Get an object of a certain *type*, specified by the code for what *language* it is in and its *key*. The types currently supported are: `assertion` Use the `id` as the key. `concept` Use the concept's raw name as the key. ...
0bb71860882cb7f653a274ea083f56bdaa8b7438
72,008
import requests import json def login(request): """ Do OAUTH dance with GitHub (for sign in) and PyPI (for releasing packages) """ # # Redir https # if request.headers.get('X-Forwarded-Proto') is not None: # if request.headers['X-Forwarded-Proto'] != 'https': # return H...
bf12dc64dcf286fc3ff4bcef252d12c9eab05140
72,009
import numpy def xy_field_grid_points_to_edges(field_matrix=None, x_min_metres=None, y_min_metres=None, x_spacing_metres=None, y_spacing_metres=None): """Re-references x-y field from grid points to edges. M = number of rows (unique grid-poin...
075977ced527458a84823e64d64ebbe05a8f2e14
72,010
def predict(samplerid): """ provides a prediction of the forward model at a set of given query parameters It expects a list of lists with n elements in the main list corresponding to the number of queries and each element has d elements corresponding to the number of parameters in the forward m...
cc65e566e3bb5bca754d1b5b47c7739cd371ec4a
72,011
from typing import Optional def all_history_date( tickers: tuple[str, ...], *, start: Optional[pd.Timestamp] = None, end: Optional[pd.Timestamp] = None, bus: bootstrap.TableBus = bootstrap.BUS, ) -> pd.Index: """Перечень дат для которых есть котировки после проверки на наличие новых данных. ...
21a84b7451a50db691a885d94e6b09efa8a28461
72,012
import zfused_api import maya.cmds as cmds def software_id(): """ return zfused software id """ _softwares = zfused_api.zFused.get("software", filter = {"Name":"Autodesk Maya", "Code":"maya", "Version": int(cmds.about(version = True))}) if _softwares: return _softwares[0]["Id"] return...
7ead0b78c54d122c6212dfb2ff9d519294ad4efe
72,013
def is_in_poly(p, poly): """ :param p: [x, y] :param poly: [[], [], [], [], ...] :return: is_in: boolean. True = p in poly """ px, py = p is_in = False for i, corner in enumerate(poly): next_i = i + 1 if i + 1 < len(poly) else 0 x1, y1 = corner x2, y2 = poly[next_...
00d46af2dc04c6d3c1d86db887d904abe17e3bdb
72,014
from typing import Tuple def InterpolateValue(x: float, xy0: Tuple[float, float], xy1: Tuple[float, float]) -> float: """Get the position of x on the line between xy0 and xy1. :type x: float :type xy0: Tuple[float, float] :type xy1: Tuple[float, float] :return: y :rtype: float """ if ...
9de4372b593fae65f772c19a8ac369315a8489d0
72,015
def max_bounded(max_func, bounds, *args, **options): """Finds the input value that maximizes `max_func`. min_func: computes the function to be maximized bounds: sequence of two values, lower and upper bounds of the range to be searched args: any additional positional arguments are passe...
5056bd9b19acb2ea145cfa2ce6107ca9176eacae
72,016
from typing import Tuple from typing import Any def v3_pos_to_position(v3_rep: Tuple[Any], hex_width: float, hex_depth: float) -> Position: """ Maps from the Unity-given tuple representing the position to a Position. Inputs: v3_rep (Tuple[str]): The Unity representation of the position (x, y, z). ...
6045afbb17e6e93fd06bb46f728194bceff6339f
72,017
from typing import Dict def bwt_transform(s: str) -> Dict: """ :param s: The string that will be used at bwt algorithm :return: the string composed of the last char of each row of the ordered rotations and the index of the original string at ordered rotations list :raises TypeError: If the s param...
a206074307f0857cbe0e6e75d2101fc9b50d21e9
72,018
def facebook_share(context, label=None, css_class=None, icon_class=None, **kwargs): """ Renders a 'Share' button to share content on Facebook. Parameters: - label: the text to show as button label. - css_class: the class to apply to the button. Keyword arguments: ...
23be9f936c0f5a993b228bf1f0847cbb22791d3c
72,019
def get_sliding_band(sym, lam_int, lam_ext): """Returns a list of surface in the airgap including the sliding band surface Parameters ---------- sym: int Symmetry factor (1= full machine, 2= half of the machine...) Rgap_mec_int: float Internal lamination mechanic radius Rgap_me...
65b67d8a22492d94cdd6d49fcc2a120a225be4d1
72,020
def get_subset_with_sum(a, n): """Returns a subset of a with sum equal to n (if exists).""" dp = [[]] * (n + 1) for i in range(len(a)): for j in range(n, a[i] - 1, -1): if j == a[i]: dp[j] = [a[i]] elif dp[j]: continue elif dp[j - a...
c9e2ba7b6ea3b33d839cdad3586ccd8717089ebf
72,021
def blackbody_lambda(in_x, temperature): """Like :func:`blackbody_nu` but for :math:`B_{\\lambda}(T)`. Parameters ---------- in_x : number, array-like, or `~astropy.units.Quantity` Frequency, wavelength, or wave number. If not a Quantity, it is assumed to be in Angstrom. temperatur...
8db191c843836a7bef4e8a82d1218120ba075f9c
72,022
def op_wait(pc,lc,seconds,dummy,dummy2,rtime): """ waits for a number of seconds or on a previously set condition seconds : wait time, or timeout if waiting for condition """ global condition,wtime res = pc if (condition == None): # unconditional wait based on time if wtime == 0: wtime = rtime if...
f72705ea0a6a229c8a247d6323f3712407f6ec62
72,023
def _safe_latex(to_fix): """Escape characters that make LaTeX unhappy. """ chars = ["%", "_", "&", "#"] for char in chars: to_fix = to_fix.replace(char, "\\%s" % char) return to_fix
166de7858b319d9e07f7e0ad67e293ca96da63ab
72,024
import six import json def create_doc_obj(body): """Turn a message str into a |DocumentObj|. Parses a message body, adds an ``_id`` field based on the document's ``@uuid`` field, and creates a |DocumentObj| from the result. Parameters ---------- body : str Returns ------- |Docum...
37ee7ac927909e51fd1fdd3de175364cfaaacd69
72,025
def _abs(u): """np.abs for AD array.""" if isinstance(u, ADI): return u.abs() else: return np.abs(u)
f8820046cde6a999b64e2ac8c7817269ba88f35a
72,026
def boolean(prompt=None, yes='y', no='n', default=None, sensitive=False, partial=True): """Prompt for a yes/no response. Parameters ---------- prompt : str, optional Use an alternative prompt. yes : str, optional Response corresponding to 'yes'. no : str, optional ...
159c8be6004e4e9f2c5a271e36facd3610561b61
72,027
def get_tags_from_names(session,taglist): """Returns all tag objects with Tag.name in taglist. """ return session.query(Tag).filter(Tag.name.in_(taglist)).all()
52a1db2eef1bb7ebf769d606698f107fbdfbf4e4
72,028
def top_token_set_ratio(values): """Return the best token set ratio match from fuzzywuzzy module.""" scores = [] for combo in combinations(values, 2): score = fuzz.token_set_ratio(combo[0], combo[1]) tokens_0 = len(combo[0].split()) tokens_1 = len(combo[1].split()) if tokens_...
084b86af527ca2832530c066883a49d7a69bf7ad
72,029
def get_non_refinement_chain(): """ Create 3-level chain without class_decompose node """ node_scaling = PrimaryNode('scaling') node_rf = SecondaryNode('rf', nodes_from=[node_scaling]) node_logit = SecondaryNode('logit', nodes_from=[node_scaling]) node_xgboost = SecondaryNode('xgboost', nodes_from=[...
0504218d27d7c49146022cca57c5e5c9602c624d
72,030
def get_auc(m, auc_limits): """Gustavo's method for generating uniformly distributed auc values. Args: m: (int) > 2, representing the number of base classifiers auc_limits: (len(2) list, tuple, or ndarray, i.e. Sequence) representing the (minimum AUC, maximum AUC) among the ...
b658fc028f69cc0c4f934e7176a6cfbd7738c661
72,031
def create_model(architecture, num_features): """ create uncompiled model with given architecture NOTE: currently only the DeepSpeech model is supported. Other models can be added here :param architecture: name of the architecture (see descriptions in argparse) :param num_features: number of feature...
f33959efa568f898df3927e314fb3a8eac8a5ccb
72,032
from pathlib import Path def get_image_path(card_number): """ Return the full path of the image file on the server. This may be used by printable templates. """ if card_number: parts = get_image_parts(card_number) # return os.path.join(settings.MEDIA_ROOT, *parts) return Pa...
7bc97c2272447aaea2dd0b36e78aa8a1e4d8241c
72,033
def export_result_image(song: Song, chords_vocabulary: ChordVocabulary, midi: bool = True, tab: bool = True, audio: str = 'CHF_2017', df: bool = True): """ Export visualisation to a png file. :param song: Song for which we want to export the visualisation :param chords_vocabular...
d0e404779eeaae4a963d37f24b6615796bdf1375
72,034
def arg_num_in_range(args, low, up): """ check if low <= len(args) <= up """ return check_in_range(len(args), low, up)
b478d0b3aee1373e6a45b2f6339af005bf8a093c
72,035
import time def retry(exceptions=Exception, tries=4, delay=3, backoff=2, logger=None, silence: bool = False): """ Retry calling the decorated function using an exponential backoff. Args: exceptions: The exception to check. may be a tuple of exceptions to check. tries: Number o...
24b61bd7634a75ad38ec35a878f1faf39bbbbd1a
72,036
import json def dumps(obj, **kwargs): """ calls json.dumps using DateTimeEncoder """ return json.dumps(obj, cls=DateTimeEncoder, **kwargs)
397b2efd2145a894582532fd20f9e0631caa34d5
72,037
def parse_image_meta(meta): """Parses an image info Numpy array to its components. See compose_image_meta() for more details. """ image_id = meta[:, 0] image_shape = meta[:, 1:4] window = meta[:, 4:8] # (y1, x1, y2, x2) window of image in in pixels active_class_ids = meta[:, 8:] return...
9c5099351b6a63be3a2e7b62464b846db8fe3836
72,038
import unicodedata import re def slugify(value): """ URL to filename Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens. """ val = unicodedata.normalize('NFKD', value).encode('utf-8', 'ignore') val = val.decode() val = re.sub(r'[^\w\s...
028d6800c87932c61c18fc2ec09d5d97ad3fd399
72,039
def make_html(email_dict: dict) -> MIMEText: """ Function that makes html text portion of message, including placeholders for inline images @param email_dict: output of make_email_dict, a dict with the email body text as a key, the images to attach as values @returns: HTML encoded email text ""...
4ea2885d0381419ebec5d05c144445ce2de1cb2e
72,040
def kernel(t): """ 畳み込みカーネル """ return np.exp(-t / 20) - np.exp(-t / 10)
b5b4085681b6e84f25072863e04f09e6cdf72ed0
72,041
def scoring_function(context_features, example_features, mode): """A feed-forward network to score query-document pairs.""" with tf.compat.v1.name_scope("input_layer"): context_input = [ tf.compat.v1.layers.flatten(context_features[name]) for name in sorted(context_feature_columns()) ] e...
edae314eb09e896028d9c8334fdaa1fb92733c0f
72,042
def _not_(x: symbol) -> symbol: """ >>> isinstance(not_(symbol(True)), symbol) True >>> not_.instance(True) False """ return not x
6961757837cfbfeb134e7b932dd48d7fcc9d070a
72,043
import torch def compute_local_cost(pi, a, dx, b, dy, eps, rho, rho2, complete_cost=True): """Compute the local cost by averaging the distortion with the current transport plan. Parameters ---------- pi: torch.Tensor of size [Batch, size_X, size_Y] transport plan used to compute local cost ...
3d29e8ae5ef14ab30cd676eebeb6507e9cbfafca
72,044
def discretenorm(K,mu,sig): """ Discrete approximation of normal density with N bins, mean mu and standard deviation sigma. """ pts = np.linspace(mu-3*sig, mu+3*sig, K) space = pts[1]-pts[0] probs = st.norm.cdf(pts+space/2, loc=mu, scale=sig) - st.norm.cdf(pts-space/2, loc=mu, scale=sig) ...
f3bd2178ed8c7e171c54426726e100c8869b07f0
72,045