content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def reduce_aet_if_dry(aet, wat_lev, fc): """ Reduce actual evapotranspiration if the soil is dry. If the water level in a cell is less than 0.7*fc, the rate of evapo-transpiration is reduced by a factor. This factor is 1 when wat_lev = 0.7*fc and decreases linearly to reach 0 when wat_lev...
170462a23c3903a390b89963aa6ce21839e5d44b
3,638,112
def merge_sort(array): """ Sort array via merge sort algorithm Args: array: list of elements to be sorted Returns: Sorted list of elements Examples: >>> merge_sort([1, -10, 21, 3, 5]) [-10, 1, 3, 5, 21] """ if len(array) == 1: return array[:] mi...
9730f88be4a54334bac801dc4713bf20b683f824
3,638,113
def create_monitored_session(target: tf.train.Server, task_index: int, checkpoint_dir: str, save_checkpoint_secs: int, config: tf.ConfigProto=None) -> tf.Session: """ Create a monitored session for the worker :param target: the target string for the tf.Session :param task_in...
f963e61cf57aa602a9a9397104a935b5a17a6dc1
3,638,114
def sun_rise_set_times(datetime_index, coords): """ Return sunrise and set times for the given datetime_index and coords, as a Series indexed by date (days, resampled from the datetime_index). """ obs = ephem.Observer() obs.lat = str(coords[0]) obs.lon = str(coords[1]) # Ensure datetime...
9c2dfb3c7c86c98144b23788b0b399899724c8ff
3,638,115
def get_n1_event_format(): """ Define the format for the events in a neurone recording. Arguments: None. Returns: - A Struct (from the construct library) describing the event format. """ # Define the data format of the events # noinspection PyUnresolvedReferences r...
8663c4b8ba8d83e10ed6dc03a35589c74cd23420
3,638,116
def idzp_rid(eps, m, n, matveca): """ Compute ID of a complex matrix to a specified relative precision using random matrix-vector multiplication. :param eps: Relative precision. :type eps: float :param m: Matrix row dimension. :type m: int :param n: Matrix column...
7655afb9b5c29f395ca6c5c83baaa8592f68d124
3,638,117
def update_position(request, space_url): """ This view saves the new note position in the debate board. Instead of reloading all the note form with all the data, we use the partial form "UpdateNotePosition" which only handles the column and row of the note. """ place = get_object_or_404(Space, ...
29cc55ad30c8cdf6a326381a9b267aaf515059b6
3,638,118
def tan(x): """Return the tangent of *x* radians.""" return 0.0
51a8f497b2cc81cfd0066a7f8f5b1afef362941e
3,638,119
def entropy(p): """ Calculates the Shannon entropy for a marginal distribution. Args: p (np.ndarray): the marginal distribution. Returns: (float): the entropy of p """ # Since zeros do not contribute to the Shannon entropy by definition, we # ignore them t...
d9deb56211069e70ee688ec7cf9cea4cb6507d2a
3,638,120
def format_to_str(*a, **kwargs): """ Formats gotten objects to str. """ result = "" if kwargs == {}: kwargs = {'keepNewlines': True} for x in range(0, len(a)): tempItem = a[x] if type(tempItem) is str: result += tempItem elif type(tempItem) in [list, dict, tup...
066262f6059a7f146026b1bc638b9119e2c34718
3,638,121
def zero_corrected_countless(data): """ Vectorized implementation of downsampling a 2D image by 2 on each side using the COUNTLESS algorithm. data is a 2D numpy array with even dimensions. """ # allows us to prevent losing 1/2 a bit of information # at the top end by using a bigger type. Wi...
7b0dc08f0233f929b572d555ad611c8bf795bbfd
3,638,123
from typing import Union def mnn_synthetic_data( n_samples: int = 1000, n_features: int = 100, n_batches: int = 2, n_latent: int = 2, n_classes: int = 3, proportions: np.ndarray = None, sparsity: float = 1.0, scale: Union[int, float] = 5, batch_scale: float = 0.1, bio_batch_ang...
e3e696cfb1e207db2159cdc512bc5b4d8f24e47b
3,638,124
def create_labeled_pair(img, gt_center, prop_center, gt_radius, scale): """ Given a crater proposal and ground truth label, this function creates a labeled pair. Returns X, Y, where X is an image, and Y is a set of ground truths. img: an array gt_center: the known ground-truth center point (x, y...
b65bc6234183794c432377f8475833dc1f8b72c7
3,638,125
def loader_to_dask(loader_array): """ Map a call to `dask.array.from_array` onto all the elements in ``loader_array``. This is done so that an explicit ``meta=`` argument can be provided to prevent loading data from disk. """ if len(loader_array.shape) != 1: raise ValueError("Can only ...
75039dac3f5ed21e6c1a0b8b5445af30757267cf
3,638,126
import re def list_to_sentences(string): """ Splits text at newlines and puts it back together after stripping new- lines and enumeration symbols, joined by a period. """ if string is None: return None lines = string.splitlines() curr = '' processed = [] for line in lines: stripped = line.strip() # e...
3f155bf501d78cb9263a9cbb0b6d7e4102daeb53
3,638,127
def decode_locations_one_layer(anchors_one_layer, offset_bboxes): """decode the offset bboxes into center bboxes Args: anchors_one_layer: ndarray represents all anchors coordinate in one layer, encode by [y,x,h,w] offset_bboxes: A tensor with any shape ,the shape of l...
96df6f6b9756cda991e47aea226ea64d5de8648c
3,638,128
def FormatReserved(enum_or_msg_proto): """Format reserved values/names in a [Enum]DescriptorProto. Args: enum_or_msg_proto: [Enum]DescriptorProto message. Returns: Formatted enum_or_msg_proto as a string. """ reserved_fields = FormatBlock('reserved %s;\n' % ','.join( map(str, sum([list(range(r...
56b3ad5c2d31a901847c50ad05bd324ca366f101
3,638,129
def download_pepper(load=True): # pragma: no cover """Download scan of a pepper (capsicum). Originally obtained from Laser Design. Parameters ---------- load : bool, optional Load the dataset after downloading it when ``True``. Set this to ``False`` and only the filename will be ...
3d35c19a5eb36d8a393076b212c5a9789ff61625
3,638,130
def getAllSerial(): """get all device serials found by command adb devices""" _, msgs = shell_command("adb devices") devices = [line for line in msgs if "\tdevice\n" in line] serials = sorted([dev.split()[0] for dev in devices], key=len) return serials
a6a6fd93c4bd27babbca2a15999e19985677e0a1
3,638,131
import io def plot_points(points): """Generate a plot with a varying number of randomly generated points Args: points (int): a number of points to plot Returns: An svg plot with <points> data points """ # data for plotting data = np.random data = np.random.rand(points, 2) fig =...
1b3bba3e48ef252e80ad7895ce596e9deb9a0c86
3,638,133
def bisect_status(): """Reproduce the status line git-bisect prints after each step.""" return "Bisecting: {} revisions left to test after this (roughly {} steps).".format( ceil((bisect_revisions() - 1) / 2), bisect_steps_remaining() - 1, )
7ddca3f9de9de3775a52aac1b03a3383ebc487df
3,638,134
def echo_view(): """Call echo() with the Flask request.""" return echo(flask.request)
f51f9f6b2f1f58abcc6f1a0ed9a28056c092f289
3,638,135
def read_bytes_offset_file(f,n_bytes,v=0): """ Used to skip some offset when reading a binary file. Parameters ---------- f : file handler (sys.stdin). n_words : int number of words of type TYPE_WORD. v : int [0 by default] verbose mode if 1. """ wo...
3f68b4ff22dba97e89cc7b036f63655f3d6b756d
3,638,136
from datetime import datetime def person_relationship_dates(node): """Find the nearest start/end dates related to a node's person.""" person = node.people.single() rel = node.people.relationship(person) if rel.start_date is not None: return {'start_date': rel.start_date, 'end_date': rel.end_da...
cd16b3f69979f0d516cb28313ac0dabda9416f30
3,638,137
def oops(): """Lazy way to return an oops reponse.""" return make_response('oops', 400)
e52fb6621ff9fdba48d2d5b81a8cbbb5241eeac8
3,638,138
def get_lowest_energy_conformer( name, mol, gfn_exec=None, settings=None, ): """ Get lowest energy conformer of molecule. Method: 1) ETKDG conformer search on molecule 2) xTB `normal` optimisation of each conformer 3) xTB `opt_level` optimisation of lowest energy con...
e09cb7ed755e2a94075c2206ebd5d7600d633657
3,638,139
def dictize_params(params): """ Parse parameters into a normal dictionary """ param_dict = dict() for key, value in params.iteritems(): param_dict[key] = value return param_dict
4847815622b0855b1056361bff7f7ee02fe6d97a
3,638,140
def dot(x, y, sparse=False): """Wrapper for tf.matmul (sparse vs dense).""" if sparse: res = tf.sparse_tensor_dense_matmul(x, y) else: res = tf.matmul(x, y) return res
fd904bbbaf09ea3207ed8dfa47a17f30ed640ff7
3,638,141
def get_python3_status(classifiers): """ Search through list of classifiers for a Python 3 classifier. """ status = False for classifier in classifiers: if classifier.find('Programming Language :: Python :: 3') == 0: status = True return status
b4bf347dc0bbf3e9a198baa8237f7820cbb86e0b
3,638,142
def drawBeta(s, w, size=1): """Draw beta from its distribution (Eq.9 Rasmussen 2000) using ARS Make it robust with an expanding range in case of failure""" #nd = w.shape[0] 用于多维数据 lb = 0.0 flag = True cnt = 0 while flag: xi = lb + np.logspace(-3 - cnt, 1 + cnt, 200) # update range i...
f0a7826a8411dfc224b2b161d1372984630647e8
3,638,143
def get_unique_map_to_pullback(p, p_a, p_b, z_a, z_b): """Find a unique map to pullback.""" z_p = dict() for value in p: z_keys_from_a = set() if value in p_a.keys(): a_value = p_a[value] z_keys_from_a = set(keys_by_value(z_a, a_value)) z_keys_from_b = set() ...
6dfcef9e2fa531ae84641be3dd1b4b8836baa958
3,638,144
import torch from typing import Optional def f1_score( pred: torch.Tensor, target: torch.Tensor, num_classes: Optional[int] = None, class_reduction: str = 'micro', ) -> torch.Tensor: """ Computes the F1-score (a.k.a F-measure), which is the harmonic mean of the precision and re...
3a5e8bb2915da7aedb16266575bb099f64554c8f
3,638,145
def PyramidPoolingModule(inputs, feature_map_shape): """ Build the Pyramid Pooling Module. """ interp_block1 = InterpBlock(inputs, 1, feature_map_shape) interp_block2 = InterpBlock(inputs, 2, feature_map_shape) interp_block3 = InterpBlock(inputs, 3, feature_map_shape) interp_block6 = Interp...
4182291ff038ef89620412f2087c9a8bc23e0cd9
3,638,146
def order(ord): """ `order` is decorator to order the pipeline classes. This decorator specifies a property named "order" to the member function so that we can use the property to order the member functions. This `order` function can be combined with the decorator `with_transforms` which orders the member ...
7cba4dda9a844733e45698257f206aeb22e2e6b2
3,638,147
import math def collisionIndicator(egoPose, egoPoly, objPose, objPoly): """ Indicator function for collision between ego vehicle and moving object Param: egoPose: ego vehicle objPose: pose of object Return: col_indicator: (float) collision indicator between two object """ ...
074852f5a12cd18c1b201ba4d72e2f710c21417c
3,638,148
def lookup_listener(param): """ Flags a method as a @lookup_listener. This method will be updated on the changes to the lookup. The lookup changes when values are registered in the lookup or during service activation. @param param: function being attached to @return: """ def decor(func): ...
5d053e20ca8c2316aa46f27809b8e0ae59077d32
3,638,149
async def read_multi_analog_inputs(app, addr): """ Execute a single request using `ReadPropertyMultipleRequest`. This will read the first 40 analog input values from the remote device. :param app: An app instance :param addr: The network address of the remote device :return: """ read_acc...
9b2d6f820bcb6fc0ee9ef4ad65c7c7654e4a47b1
3,638,150
def lookupBlock(blockName): """ Look up block name string in name list data value (e.g. color) override may be appended to the end e.g. stained_hardened_clay_10 Note: block name lookup is case insensitive """ blockName = blockName.upper() try: try: name, data ...
f1cd8a43751df8bf710a1d0379887725c5a5e400
3,638,151
def factorize(values, sort=False, na_sentinel=-1, size_hint=None): """Encode the input values as integer labels Parameters ---------- values: Series, Index, or CuPy array The data to be factorized. na_sentinel : number, default -1 Value to indicate missing category. Returns ...
be4001dc9873ace10dce9100f7375718db783b24
3,638,152
def make_proc(code, variables, path, *, use_async=False): # pylint: disable=redefined-builtin """Compile this code block to a procedure. Args: code: the code block to execute. Text, will be indented. vars: variable names to pass into the code path: the location where the code is stored...
7f4e6f279ede515f71dbee6c3a5a796ee76815d2
3,638,153
def ratings_std(df): """calculate standard deviation of ratings from the given dataframe parameters ---------- df (pandas dataframe): a dataframe cotanis all ratings Returns ------- standard deviation(float): standard deviation of ratings, keep 4 decimal """ std_value = df['ratings...
b1bf00d25c0cee91632eef8248d5e53236dd4526
3,638,154
def save(objct, fileoutput, binary=True): """ Save 3D object to file. (same as `write()`). Possile extensions are: - vtk, vti, ply, obj, stl, byu, vtp, xyz, tif, vti, mhd, png, bmp. """ return write(objct, fileoutput, binary)
c310e5be80bcfb56f2c6bd9f9734f171a0fbd2c6
3,638,155
def read_pfm(fname): """ Load a pfm file as a numpy array Args: fname: path to the file to be loaded Returns: content of the file as a numpy array """ file = open(fname, 'rb') color = None width = None height = None scale = None endian = None header = fi...
3c1f90965479cd1fdaaecbd2c740d807d952f687
3,638,156
import math def broaden_spectrum(spect, sigma): """ Broadens a peak defined in spect by the sigma factor and returns the x and y data to plot. Args: ---- spect (np.ndarray) -- input array containing the peak info for the individual peak to be broadened. sigma (floa...
9c177dfaf282ad16b9742f96bb70e971a2fce6c6
3,638,157
import requests def mv_audio(serial_id, audio_setting): """ This function will change the audio recording settings to {audio_setting} in the meraki dashboard for the mv camera with the {serial_id} :param: serial_id: the serial id for the meraki mv camera :param: audio_setting: 'true' to turn on au...
cb6f2415d8950513760afdcfbe11993999071b73
3,638,158
from typing import List def lsp_text_edits(changed_file: ChangedFile) -> List[TextEdit]: """Take a jedi `ChangedFile` and convert to list of text edits. Handles inserts, replaces, and deletions within a text file """ old_code = ( changed_file._module_node.get_code() # pylint: disable=protect...
9069db3931606874e0cf8a796ffe6acb88f4ad8a
3,638,159
import hashlib def _hash(file_name, hash_function=hashlib.sha256): """compute hash of file `file_name`""" with open(file_name, 'rb') as file_: return hash_function(file_.read()).hexdigest()
463d692116fbb85db9f1a537cbcaa5d2d019ba05
3,638,160
def prepare_cmf(observer='1931_2deg'): """Safely returns the color matching function dictionary for the specified observer. Parameters ---------- observer : `str`, {'1931_2deg', '1964_10deg'} the observer to return Returns ------- `dict` cmf dict Raises ------ ...
82422c521fc9b55acbad6ab0fbb31a67ec5f71b9
3,638,161
def list_project_milestones(request): """ list project specific milestones """ project_id = request.GET.get('project_id') project = Project.objects.get(id=project_id) template = loader.get_template('project_management/list_project_milestones.html') open_status = Status.objects.get(nam...
b7a8cc729f17f9e8640ae83d5f70ede6ce9c1ece
3,638,163
from opax import apply_updates, transform_gradients from re import T from typing import Tuple from typing import Any from typing import Union def build_update_fn(loss_fn, *, scan_mode: bool = False): """Build a simple update function. *Note*: The output of ``loss_fn`` must be ``(loss, (aux, model))``. A...
28d6ac1b38ae4cf4e9c7e1e50ffe89d87437e01c
3,638,164
def _get_perf_hint(hint, index: int, _default=None): """ Extracts a "performance hint" value -- specified as either a scalar or 2-tuple -- for either the left or right Dataset in a merge. Parameters ---------- hint : scalar or 2-tuple of scalars, optional index : int Indicates wheth...
d67a70d526934dedaa9f571970e27695404350f2
3,638,165
def synchronized_limit(lock): """ Synchronization decorator; provide thread-safe locking on a function http://code.activestate.com/recipes/465057/ """ def wrap(f): def synchronize(*args, **kw): if lock[1] < 10: lock[1] += 1 lock[0].acquire() ...
a28adfca434b7feaa5aa33c2ba4d1ed2e48cf916
3,638,166
from scipy.ndimage import affine_transform def fast_warp(img, tf, output_shape=(50, 50), mode='constant', order=1): """ This wrapper function is faster than skimage.transform.warp """ m = tf._matrix res = np.zeros(shape=(output_shape[0], output_shape[1], 3), dtype=floatX) trans, offset = m[:2,...
989b6edc370b7ab92685741f70d8346717d60505
3,638,167
def _get_detections(generator, model, score_threshold=0.05, max_detections=400, save_path=None): """ Get the detections from the model using the generator. The result is a list of lists such that the size is: all_detections[num_images][num_classes] = detections[num_detections, 4 + num_classes] # A...
1800bba86a21c07356fd0075d8d911b9ec55540b
3,638,168
def BF (mu, s2, noise_var=None, pps=None): """ Buzzi-Ferraris et al.'s design criterion. - Buzzi-Ferraris and Forzatti (1983) Sequential experimental design for model discrimination in the case of multiple responses. Chem. Eng. Sci. 39(1):81-85 - Buzzi-Ferraris et al. (1984) Sequential experimental design...
f51e7c2a6827e1a1283afc8d0b8af5e3fe66a034
3,638,169
def deploy(usr, pwd, path=getcwd(), venv=None): """release on `pypi.org`""" log(INFO, ICONS["deploy"] + 'deploy release on `pypi.org`') # check dist module('twine', 'check --strict dist/*', path=path, venv=venv) # push to pypi.org return module("twine", "upload -u %s -p %s dist/*" % (usr, pwd), ...
cfb13ac61addfc783a0f6e5963fb44838142f77d
3,638,170
def most_interval_scheduling(interval_list): """ 最多区间调度:优先选择'end'值小的区间 Args: interval_list(list): 区间列表 Returns: scheduling_list(list): 去重实体列表 """ scheduling_list = list() sorted_interval_list = sorted(interval_list, key=lambda x: x['end']) ...
82b1d051221043025497c95d9657245b5b507bde
3,638,171
def kernel_program(inputfile, dimData, Materials, dict_nset_data, \ dict_elset_matID={}, dict_elset_dload={}): """The kernel_program should be called by the job script (e.g., Job-1.py) where the user defines: - inputfile: the name of the input file - dimData: the dimensional data (s...
ac65f5c1355ed4097018ded03a9484cf77e7bf17
3,638,172
from typing import Collection def rmse_metric(predicted: Collection, actual: Collection) -> float: """ Root-mean-square error metric. Args: predicted (list): prediction values. actual (list): reference values. Returns: root-mean-square-error metric. """ ...
87b14ae0c99db10ffaa8a352d7deb6007ba1f00e
3,638,174
import json def set_user_data(session_id, user_data): """ this function temporarily stores data transmitted by user, when POSTed by the user device; the data is then picked up by the page ajax polling mechanism """ return session_id if red.set(K_USER_DATA.format(session_id), json.dumps(...
c3230dd751d2b34f8abb142be5dc170c639258b5
3,638,175
def find_keys(info: dict) -> dict: """Determines all the keys and their parent keys. """ avail_keys = {} def if_dict(dct: dict, prev_key: str): for key in dct.keys(): if key not in avail_keys: avail_keys[key] = prev_key if type(dct[key]) == d...
8d0bed361767d62bbc3544efdfe47e8e1065f462
3,638,176
def valid(exc, cur1, cur2=None, exclude=None, exclude_cur=None): """ Find if the given exc satisfies currency 1 (currency 2) (and is not exclude) (and currency is not exclude) """ if exclude is not None and exc == exclude: return False curs = [exc.to_currency, exc.from_currency] if e...
84a37e669fee120aed8fbc57ab13d5f70f583cf4
3,638,177
import math def arc( x: float, y: float, radius: float, start: float, stop: float, quantization: float = 0.1, ) -> np.ndarray: """Build a circular arc path. Zero angles refer to east of unit circle and positive values extend counter-clockwise. Args: x: center X coordinate y: center Y ...
99ce50042e4199c38fdb0a6e79134fab0cd30196
3,638,178
def build_feature_columns(schema): """Build feature columns as input to the model.""" # non-numeric columns exclude = ['customer_id', 'brand', 'promo_sensitive', 'weight', 'label'] # numeric feature columns numeric_column_names = [col for col in schema.names if col not in exclude] numeric_colu...
048ebe72e291db6a92ee9d2d903baf6e10df9bf2
3,638,179
def get_mol_func(smiles_type): """ Returns a function pointer that converts a given SMILES type to a mol object. :param smiles_type: The SMILES type to convert VALUES=(deepsmiles.*, smiles, scaffold). :return : A function pointer. """ if smiles_type.startswith("deepsmiles"): _, deepsmil...
7af4260cb79c21e763ee2ad4a64c38b5e3fd84fe
3,638,180
def index(): """Return to the homepage.""" return render_template("index.html")
6b3a8595173d8919478ae4a0f4dc7f8a3958af56
3,638,181
def species_thermo_value(spc_dct): """ species enthalpy at 298 """ return spc_dct['H298']
7684b0ace0fa9717cb1cc3ea83bb6be8099c4bf6
3,638,182
async def async_setup(hass: HomeAssistant, config: dict): """Set up the Flood integration.""" hass.data.setdefault(DOMAIN, {}) return True
5d404d856346e26f8c7f32102c6286f05ac91f8c
3,638,184
def typehint(x, typedict): """Replace the dtypes in `x` keyed by `typedict` with the dtypes in `typedict`. """ dtype = x.dtype lhs = dict(zip(dtype.fields.keys(), map(first, dtype.fields.values()))) dtype_list = list(merge(lhs, typedict).items()) return x.astype(np.dtype(sort_dtype_items(dty...
a5e8ab9e94f3d622467a3e486bc21ffed1336878
3,638,185
import random def balance(samples, labels, balance_factor, adjust_func): """create a balanced dataset by subsampling classes or generating new samples""" grouped = group_by_label(samples, labels) if balance_factor <= 1.0: largest_group_size = max([len(x[1]) for x in grouped]) target_...
128aaec1b3c60348190394c5ceab6b561eba6f51
3,638,186
import random def generate_sha1(string, salt=None): """ Generates a sha1 hash for supplied string. Doesn't need to be very secure because it's not used for password checking. We got Django for that. :param string: The string that needs to be encrypted. :param salt: Optionally def...
9ff8cbfd987972fea6712f90752c9d94aeb78b44
3,638,187
def sentences_from_doc(ttree_doc, language, selector): """Given a Treex document, return a list of sentences in the given language and selector.""" return [bundle.get_zone(language, selector).sentence for bundle in ttree_doc.bundles]
d9c09249171d5d778981fb98a8a7f53765518479
3,638,188
import math def demo_func(par): """Test function to optimize.""" x = par['x'] y = par['y'] z = par['z'] p = par['p'] s = par['str'] funcs = { 'sin': math.sin, 'cos': math.cos, } return (x + (-y) * z) / ((funcs[s](p) ** 2) + 1)
5899be5709c4a6ecf09cf9852c1b7569d85616b3
3,638,189
def file_to_list(filename): """ Read in a one-column txt file to a list :param filename: :return: A list where each line is an element """ with open(filename, 'r') as fin: alist = [line.strip() for line in fin] return alist
33bee263b98c4ff85d10191fa2f5a0f095c6ae4b
3,638,190
def regular_ticket_price(distance_in_km: int) -> float: """ calculate the regular ticket price based on the given distance :int distance_in_km: """ # source --> Tarife 601 Chapter 10.1.3 on https://www.allianceswisspass.ch/de/Themen/TarifeVorschriften price_ticket_per_km = {range(1, 5): 44.51, ...
220b4eb9362b9a48b5c3d2e2ad17e23755098785
3,638,191
def find_cal_indices(datetimes): """ Cal events are any time a standard is injected and being quantified by the system. Here, they're separated as though any calibration data that's more than 60s away from the previous cal data is a new event. :param epoch_time: array of epoch times for all of the supp...
2e823e5ffc5fb509639a2d5746bd26af77a650ae
3,638,192
def rename(isamAppliance, id, new_name, check_mode=False, force=False): """ Rename a Password Strength """ if force is True or _check(isamAppliance, id) is True: if check_mode is True: return isamAppliance.create_return_object(changed=True) else: return isamApplia...
b140e618370cff1086b27fef13e0ff91b22cf075
3,638,193
import asyncio import traceback def reinvoke_on_edit(ctx, *additional_messages: discord.Message, timeout: float = 600) -> None: # noinspection PyUnresolvedReferences """ Watches a given context for a given period of time. If the message that invoked the context is edited within the time period, then t...
523048caadac3efc0f8065623a6448077dcb05fd
3,638,194
def gen_model_forms(form, model): """Creates a dict of forms. model_forms[0] is a blank form used for adding new model objects. model_forms[m.pk] is an editing form pre-populated the fields of m""" model_forms = {0: form()} for m in model.objects.all(): model_forms[m.pk] = form(instanc...
28bf3f007a7f8f971c18980c84a7841fd116898f
3,638,195
def _state_size_with_prefix(state_size, prefix=None): """Helper function that enables int or TensorShape shape specification. This function takes a size specification, which can be an integer or a TensorShape, and converts it into a list of integers. One may specify any additional dimensions that precede the f...
7f8aaab1dd42b6470dce08f9a13a59d8cdc66f4f
3,638,196
def as_pandas(cursor, coerce_float=False): """Return a pandas `DataFrame` out of an impyla cursor. This will pull the entire result set into memory. For richer pandas-like functionality on distributed data sets, see the Ibis project. Parameters ---------- cursor : `HiveServer2Cursor` ...
e1a9f5ba9b589a9c94f6df1a379833d8d7176d2b
3,638,197
def check_ip(ip, network_range): """ Test if the IP is in range Range is expected to be in CIDR notation format. If no MASK is given /32 is used. It return True if the IP is in the range. """ netItem = str(network_range).split('/') rangeIP = netItem[0] if len(netItem) == 2: ran...
be2bf16e4b000ff4b106761ea99bf69596d3ece2
3,638,198
async def index(_request: HttpRequest) -> HttpResponse: """A request handler which provides an index of the compression methods""" html = """ <!DOCTYPE html> <html> <body> <ul> <li><a href='/gzip'>gzip</a></li> <li><a href='/deflate'>deflate</a></li> <li><a href='/compress'>compress</a><...
df5af2085494f4dfe1ce22a8c6feaed71ebad5e7
3,638,199
def ifft_function(G,Fs,axis=0): """ This function gives the IDFT Arguments --------------------------- G : double DFT (complex Fourier coefficients) Fs : double sample rate, maximum frequency of G times 2 (=F_nyquist*2) axis : double the axis on which the IDFT...
901218d6c795d0ee3163496b6889899b9be16342
3,638,200
def user_tweets_stats_grouped_new(_, group_type): """ Args: _: Http Request (ignored in this function) group_type: Keyword defining group label (day,month,year) Returns: Activities grouped by (day or month or year) wrapped on response's object """ error_messages = [] success_messages = [] status = HTTP_2...
e1fc3dfd96fde3f2e01822b79bd97e508982e3d4
3,638,201
def login_required(func, *args, **kwargs): """ This is a decorator that can be applied to a Controller method that needs a logged in user. The inner method receives the Controller instance and checks if the user is logged in using the `request.is_authenticated` Boolean on the Controller instance :p...
3611bb87544ece2516d4a738e3ab68b58ee154f4
3,638,203
def preProcessImage(rgbImage): """ Preprocess the input RGB image @rgbImage: Input RGB Image """ # Color space conversion img_gray = cv2.cvtColor(rgbImage, cv2.COLOR_BGR2GRAY) img_hsv = cv2. cvtColor(rgbImage, cv2.COLOR_BGR2HLS) ysize, xsize = getShape(img_gray) #Detecting yellow and w...
ea70956bca99e28a6928867a40a3b579e2c8931b
3,638,204
from typing import List from typing import Dict from typing import Any import time import json def consume_messages(consumer: Consumer, num_expected: int, serialize: bool = True) -> List[Dict[str, Any]]: """helper function for polling 'everything' off a topic""" start = time.time() consumed_messages = [] ...
5bf5db5180222d235e08a65a4e67e6daccf9c4d7
3,638,205
def get_compressed_size(data, compression, block_size=DEFAULT_BLOCK_SIZE): """ Returns the number of bytes required when the given data is compressed. Parameters ---------- data : buffer compression : str The type of compression to use. block_size : int, optional Input...
f7c72cf7097ee9f15b9aa0b1b6d46fe060cc0c15
3,638,206
def flat_command(bias=False, flat_map=False, return_shortname=False, dm_num=1): """ Creates a DmCommand object for a flat command. :param bias: Boolean flag for whether to apply a bias. :param flat_map: Boolean flag for whether to apply a flat_map. ...
7b375c4b73686f286f07b8a327f2237e3ecb9ad0
3,638,207
def plot_graph_routes( G, routes, bbox=None, fig_height=6, fig_width=None, margin=0.02, bgcolor="w", axis_off=True, show=True, save=False, close=True, file_format="png", filename="temp", dpi=300, annotate=False, node_color="#999999", node_size=15, ...
333479cd0924df968f66ba328735a309a10e41a9
3,638,208
import re def _parse_book_info(html): """解析豆瓣图书信息(作者,出版社,出版年,定价) :param html(string): 图书信息部分的原始html """ end_flag = 'END_FLAG' html = html.replace('<br>', end_flag) html = html.replace('<br/>', end_flag) doc = lxml.html.fromstring(html) text = doc.text_content() pattern = r'{}[::]...
d327d9561a1306f1242f1f78c01517bd2358aa0b
3,638,209
def offers(request, region_slug, language_code=None): """ Function to iterate through all offers related to a region and adds them to a JSON. Returns: [String]: [description] """ region = Region.objects.get(slug=region_slug) result = [] for offer in region.offers.all(): resu...
d0256abb9a1fda0fd0296dab811f3bef2091c6d3
3,638,210
def get_ellipse(mu: np.ndarray, cov: np.ndarray, draw_legend: bool = True): """ Draw an ellipse centered at given location and according to specified covariance matrix Parameters ---------- mu : ndarray of shape (2,) Center of ellipse cov: ndarray of shape (2,2) Covariance of G...
639e2161819e76c485efaf22598cfcc601a10122
3,638,211
from typing import Sequence from typing import List import hashlib from typing import Dict def load_hashes( filename: str, hash_algorithm_names: Sequence[str] ) -> HashResult: """ Load the size and hash hex digests for the given file. """ # See https://github.com/python/typeshed/issues/2928 ...
6846e39838f2017a46472826ba07bc9974e80c5a
3,638,212
def ucs(st: Pixel, end: Pixel, data: np.ndarray): """ Iterative method to find a Dijkstra path, if one exists from current to end vertex :param startKey: start pixel point key :param endKey: end pixel point key :return: path """ q = PriorityQueue() startPri...
743dbe230073bde4ba7b95e4520f097d8f7a4443
3,638,213
def tvdb_refresh_token(token: str) -> str: """ Refreshes JWT token. Online docs: api.thetvdb.com/swagger#!/Authentication/get_refresh_token. """ url = "https://api.thetvdb.com/refresh_token" headers = {"Authorization": f"Bearer {token}"} status, content = request_json(url, headers=headers, ...
a1974f43ed0e314100c686545bb610be9cc910ed
3,638,214
def get_data(): """ _ _ _ """ df_hospital = download_hospital_admissions() #sliding_r_df = walkingR(df_hospital, "Hospital_admission") df_lcps = download_lcps() df_mob_r = download_mob_r() df_gemeente_per_dag = download_gemeente_per_dag() df_reprogetal = download_reproductiegetal() df_...
2a9b909dc53b710ce9f1729e336464857a27bb30
3,638,215
def load_bin_file(bin_file, dtype="float32"): """Load data from bin file""" data = np.fromfile(bin_file, dtype=dtype) return data
facdabb726efd66ce6e7e462aed9458d8f3dc947
3,638,216
def nearest_value(array, value): """ Searches array for the closest value to a given target. Arguments: array {NumPy Array} -- A NumPy array of numbers. value {float/int} -- The target value. Returns: float/int -- The closest value to the target value found in the array. ""...
e9bf37b02bd55a0bdd9bf6f001aca6bc69895d8c
3,638,217