content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def generate_warning_message(content: str): """ Receives the WARNING message content and colorizes it """ return ( colorama.Style.RESET_ALL + colorama.Fore.YELLOW + f"WARNING: {content}" + colorama.Style.RESET_ALL )
bdb22e6c434db2252fe50a552d889fc5f506931f
26,218
def extract_Heff_params(params, delta): """ Processes the VUMPS params into those specific to the effective Hamiltonian eigensolver. """ keys = ["Heff_tol", "Heff_ncv", "Heff_neigs"] Heff_params = {k: params[k] for k in keys} if params["adaptive_Heff_tol"]: Heff_params["Heff_tol"] ...
0153b3f7bdca639c7aab659b60ef0a3c28339935
26,219
def illumination_correction(beam_size: sc.Variable, sample_size: sc.Variable, theta: sc.Variable) -> sc.Variable: """ Compute the factor by which the intensity should be multiplied to account for the scattering geometry, where the beam is Gaussian in shape. :param beam_size:...
59ec50e8e8268677b536638e7d6897be38d4ab43
26,220
def get_subscription_query_list_xml(xml_file_path): """ Extract the embedded windows event XML QueryList elements out of a an XML subscription setting file """ with open(xml_file_path, 'rb') as f_xml: x_subscription = lxml.etree.parse(f_xml) # XPath selection requires namespace to used! x_subscript...
9c76a525a691ea91804304efc5e2e0aeab7d87ac
26,221
from typing import Optional from typing import Mapping def get_stream(name: Optional[str] = None, tags: Optional[Mapping[str, str]] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetStreamResult: """ Use this data source to get information about a Kinesis Stream...
ec12fe08019e6d41ec8694d620efdab1e8d7683f
26,223
def get_vlan_config_commands(vlan, vid): """Build command list required for VLAN configuration """ reverse_value_map = { "admin_state": { "down": "shutdown", "up": "no shutdown" } } if vlan.get('admin_state'): # do we need to apply the value map? ...
23be6435f008eb9e043e2dcb5bfdc1e1d72f6778
26,224
def kdf(): """ Returns a dataframe with a few values for generic testing """ return ks.DataFrame( { "x": [36.12, 47.32, 56.78, None], "y": [28.21, 87.12, 90.01, None], "names": ["geography", "place", "location", "geospatial"], } )
ce0500c5e028c6480a2e500d2f0a70063e6ab13d
26,225
from pathlib import Path def build_name(prefix: str, source_ind: int, name: Path) -> str: """Build a package name from the index and path.""" if name.name.casefold() == '__init__.py': name = name.parent name = name.with_suffix('') dotted = str(name).replace('\\', '.').replace('/', '.') ret...
d777b1b875ff6ab6f3228538a9e4c1cfa3c398a0
26,226
def step(x, mu, sigma, bkg, a): """ A step function template Can be used as a component of other fit functions """ step_f = bkg + a * erfc((x-mu)/(np.sqrt(2)*sigma)) return step_f
af83a9773ee0907a2dadd065870025fcc2d41441
26,227
import json def json_line_to_track(line): """Converts a json line to an appropriate Track object """ track_dct = json.loads(line) # Clean up word count dictionary wc_dct = {} for word_id, word_count in track_dct['wordcount'].iteritems(): wc_dct[int(word_id)] = int(word_count) track...
e3b63aec0b1dce0fdf9d5c47f235496ae61fc18e
26,228
def check_for_multiple(files): """ Return list of files that looks like a multi-part post """ for regex in _RE_MULTIPLE: matched_files = check_for_sequence(regex, files) if matched_files: return matched_files return ""
8e9985ef1ef5c85734c576704b7d9e3d690306a0
26,230
def get_density2D(f,data,steps=100): """ Calcule la densité en chaque case d'une grille steps x steps dont les bornes sont calculées à partir du min/max de data. Renvoie la grille estimée et la discrétisation sur chaque axe. """ xmin, xmax = data[:,0].min(), data[:,0].max() ymin, ymax = data[:,1].min(), data[:,1].m...
441a2a440d7d1a095d5719e07da2289059057279
26,231
def draw_cards_command(instance, player, arguments): """ Draw cards from the deck and put them into the calling player's hand. Args: instance: The GameInstance database model for this operation. player: The email address of the player requesting the action. arguments: A list of arguments to this comman...
ad9ef6240b5d9ec8ab2f1331b737a89539ade673
26,232
def recipe_content(*, projects_base, project, recipe): """ Returns the content of a recipe in a project, based on the projects base path, and the project and recipe name. Kwargs: projects_base (str): base path for all projects, e.g. ...
0b6ccc19202927b49383ae5f991f5e66ece89b6a
26,233
from typing import Union def precision_score( y_true: str, y_score: str, input_relation: Union[str, vDataFrame], cursor=None, pos_label: (int, float, str) = 1, ): """ --------------------------------------------------------------------------- Computes the Precision Score. Parameters ---------...
6b849504719d6f85402656d70dba6609e4822f49
26,234
import click def new_deployment(name): """ Creates a new deployment in the /deployments directory. Usage: `drone-deploy new NAME` Where NAME == a friendly name for your deployment. Example: `drone-deploy new drone.yourdomain.com` """ # create the deployment/$name directo...
ab1ae5a8e8d397c493fbd330eacf3986b2f7c448
26,235
def GenerateConfig(context): """Returns a list of configs and waiters for this deployment. The configs and waiters define a series of phases that the deployment will go through. This is a way to "pause" the deployment while some process on the VMs happens, checks for success, then goes to the next phase. Th...
19a8601b876cd3c6793ba6263adc5e30f39bb25f
26,236
import re def _format_param_value(value_repr): """ Format a parameter value for displaying it as test output. The values are string obtained via Python repr. """ regexs = ["^'(.+)'$", "^u'(.+)'$", "^<class '(.+)'>$"] for regex in regexs: m = re.match(regex...
87d881a3159c18f56dd2bb1c5556f3e70d27c1bc
26,237
def data_process(X, labels, window_size, missing): """ Takes in 2 numpy arrays: - X is of shape (N, chm_len) - labels is of shape (N, chm_len) And returns 2 processed numpy arrays: - X is of shape (N, chm_len) - labels is of shape (N, chm_len//window_size) """ # Re...
bc4e1b89e68cbf069a986a40e668311d04e2d158
26,239
def check_response_status(curr_response, full_time): """Check response status and return code of it. This function also handles printing console log info Args: curr_response (str): Response from VK API URL full_time (str): Full format fime for console log Returns: int: Sta...
e1a53cc8ae594dd333e6317840127b0bb6e3c005
26,240
def height_to_amplitude(height, sigma): """ Convert height of a 1D Gaussian to the amplitude """ return height * sigma * np.sqrt(2 * np.pi)
18712e2a308e87e8c2ceb745d7f8c4ebccc7e28d
26,241
def get_param_value(val, unit, file, line, units=True): """ Grab the parameter value from a line in the log file. Returns an int, float (with units), bool, None (if no value was provided) or a string (if processing failed). """ # Remove spaces val = val.lstrip().rstrip() # Is there a v...
05dba3f7b3f138b4481c03cd711bee39c83bb0c0
26,242
def exact_auc(errors, thresholds): """ Calculate the exact area under curve, borrow from https://github.com/magicleap/SuperGluePretrainedNetwork """ sort_idx = np.argsort(errors) errors = np.array(errors.copy())[sort_idx] recall = (np.arange(len(errors)) + 1) / len(errors) errors = np.r_[0.,...
792652ab45096c76d448980ab527bc4d5c2a5440
26,243
def avalanche_basic_stats(spike_matrix): """ Example ------- total_avalanches, avalanche_sizes, avalanche_durations = avalanche_stats(spike_matrix) """ total_spikes = spike_matrix.sum(axis=0) total_spikes = np.hstack(([0], total_spikes)) # Assure it starts with no spike avalanche = pd.S...
c053ad281b6dddd5f144c9717e7ffd352e4a6f94
26,244
from utils import indices_to_subscripts def parse_jax_dot_general(parameters, innodes): """ Parse the JAX dot_general function. Parameters ---------- parameters: A dict containing the parameters of the dot_general function. parameters['dimension_numbers'] is a tuple of tuples of the form ...
d73b3f737411990b3c37d06d4ef3d7b89b74b795
26,245
from typing import Dict from typing import Any def get_stratum_alert_data(threshold: float, notification_channel: int) -> Dict[str, Any]: """ Gets alert config for when stratum goes below given threshold :param threshold: Below this value, grafana should send an alert :type description: float ...
bae4aafe18286eeb5b0f59ad87804a19936ec182
26,246
def opponent1(im, display=False): """ Generate Opponent color space. O3 is just the intensity """ im = img.norm(im) B, G, R = np.dsplit(im, 3) O1 = (R - G) / np.sqrt(2) O2 = (R + G - 2 * B) / np.sqrt(6) O3 = (R + G + B) / np.sqrt(3) out = cv2.merge((np.uint8(img.normUnity(O1) * 255), ...
18ff83f9cc192892c12c020a1d781cabff497544
26,247
import random def shuffle_multiset_data(rv, rv_err): """ """ #shuffle RV's and their errors comb_rv_err = zip(rv, rv_err) random.shuffle(comb_rv_err) comb_rv_err_ = [random.choice(comb_rv_err) for _ in range(len(comb_rv_err))] rv_sh, rv_err_sh = zip(*comb_rv_err_) return np.array(...
3075cb3cd414122b93f4ceed8d82fdd6955a7051
26,248
import time import re def parse_pubdate(text): """Parse a date string into a Unix timestamp >>> parse_pubdate('Fri, 21 Nov 1997 09:55:06 -0600') 880127706 >>> parse_pubdate('2003-12-13T00:00:00+02:00') 1071266400 >>> parse_pubdate('2003-12-13T18:30:02Z') 1071340202 >>> parse_pubdat...
74bc178cc4ea8fc9c7d1178b5b58cb663f1673b6
26,249
from typing import List def find_ngram(x: np.ndarray, occurence: int= 2) -> List[int]: # add token """ Build pairwise of size occurence of conssecutive value. :param x: :type x: ndarray :param occurence: number of succesive occurence :type occurence: int :return: :rtype: Example: ...
0e2d5287cd145c558360a7e4a647dd49b5308b78
26,250
def ewma(current, previous, weight): """Exponentially weighted moving average: z = w*z + (1-w)*z_1""" return weight * current + ((1.0 - weight) * previous)
5a678b51618ebd445db0864d9fa72f63904e0e94
26,252
def srs_double(f): """ Creates a function prototype for the OSR routines that take the OSRSpatialReference object and """ return double_output(f, [c_void_p, POINTER(c_int)], errcheck=True)
6b17a0fa068779c32fc7f8dc8ec45da34dc01b62
26,253
def atmost_one(*args): """Asserts one of the arguments is not None Returns: result(bool): True if exactly one of the arguments is not None """ return sum([1 for a in args if a is not None]) <= 1
448469e2e0d7cb7c00981f899ef09138e8fa17fc
26,254
def _get_default_group(): """ Getting the default process group created by :func:`init_process_group`. """ if not is_initialized(): raise RuntimeError( "Default process group has not been initialized, " "please make sure to call init_process_group." ) return ...
0f9c396eb33abf9441f6cd6ba4c3911efe888efb
26,255
def string_parameter(name, in_, description=None): """ Define a string parameter. Location must still be specified. """ return parameter(name, in_, str, description=description)
a149a7ad491d3a077909b10ce72187cd7b8aafcb
26,256
def greater_version(versionA, versionB): """ Summary: Compares to version strings with multiple digits and returns greater Returns: greater, TYPE: str """ try: list_a = versionA.split('.') list_b = versionB.split('.') except AttributeError: return versio...
6c4a947dbc22cd26e96f9d3c8d43e7e3f57239be
26,257
from bs4 import BeautifulSoup def get_post_mapping(content): """This function extracts blog post title and url from response object Args: content (request.content): String content returned from requests.get Returns: list: a list of dictionaries with keys title and url """ post_d...
0b3b31e9d8c5cf0a3950dc33cb2b8958a12f47d4
26,258
def len_iter(iterator): """Count items in an iterator""" return sum(1 for i in iterator)
1d828b150945cc4016cdcb067f65753a70d16656
26,261
import copy def clones(module, N): """Produce N identical layers.""" return nn.ModuleList([copy.deepcopy(module) for _ in range(N)])
3dfc9d0d8befa26dbecaa8deda53c7fc1d00d3a1
26,262
import re def form_transfer(form): """ :param form: formula in string type. e.g. 'y~x1+x2|id+firm|id',dependent_variable~continuous_variable|fixed_effect|clusters :return: Lists of out_col, consist_col, category_col, cluster_col, fake_x, iv_col respectively. """ form = form.replace(' ', '') ...
77d817a32d5df270a351f7c6a49062aa6ba72941
26,263
def get_user(request): """ Returns the user model instance associated with the given request session. If no user is retrieved an instance of `MojAnonymousUser` is returned. """ user = None try: user_id = request.session[SESSION_KEY] token = request.session[AUTH_TOKEN_SESSION_KEY]...
94360776b1048c53c0f31b78207a7077fcd76058
26,265
import pprint def main(database): """ :type database: db.BlogDB """ sqls = [] sql_create_articles = 'CREATE TABLE {} '.format(database.table_name['articles']) + \ '(id INTEGER PRIMARY KEY AUTOINCREMENT, slug CHAR(100) NOT NULL UNIQUE, cat_id INT,' + \ ...
d0aa5ea2ad4d3eb7909785f427604e3e0bc7681a
26,266
def fav_rate(y_pred_group): """ Gets rate of favorable outcome. :param y_pred_group: Model-predicted labels of test set for privileged/unprivileged group :type y_pred_group: `np.array` :return: rate of favorable outcome :rtype: `float` """ if y_pred_group == []: return 0 els...
cc416dd0bcb37c413728a769652b4074bdd178ee
26,267
def parse_date(datestring): """ Parse a date/time string into a tuple of integers. :param datestring: The date/time string to parse. :returns: A tuple with the numbers ``(year, month, day, hour, minute, second)`` (all numbers are integers). :raises: :exc:`InvalidDate` when the date ca...
c28ac922ba11e032a5400f4d8fb866a87dad2ae6
26,268
def read_datafiles(filepath): """ Example function for reading in data form a file. This needs to be adjusted for the specific format that will work for the project. Parameters ---------- filepath : [type] [description] Returns ------- [type] [descriptio...
789feb11cfa62d2fc2f5ac244ae2be3f618aaf2f
26,269
def get_outputs(var_target_total, var_target_primary, reg, layer): """Construct standard `vlne` output layers.""" outputs = [] if var_target_total is not None: target_total = Dense( 1, name = 'target_total', kernel_regularizer = reg )(layer) outputs.append(target_total...
16c6307cb4d9d2e5d908fec0293cf317f8ff3d24
26,270
import functools import operator def flatten_list(l): """ Function which flattens a list of lists to a list. """ return functools.reduce(operator.iconcat, l, [])
37e8918ce2f71754e385f017cdfdf38ed5a30ff4
26,272
def getPutDeltas(delta, optType): """ delta: array or list of deltas optType: array or list of optType "C", "P" :return: """ # otm_x = put deltas otm_x = [] for i in range(len(delta)): if optType[i] == "C": otm_x.append(1-delta[i]) else: otm_x.appe...
a9950bd383f91c49e6c6ff745ab9b83a677ea9e8
26,274
def test_folders_has_path_long(list_folder_path, max_path=260): """tests a serie of folders if any of them has files whose pathfile has a larger length than stipulated in max_path Args: list_folder_path (list): list of folder_path to be tested max_path (int, optional): max file_path len per...
e00ef7a2707099b0a2606e7f7a032e1347836979
26,275
def get_positive_empirical_prob(labels: tf.Tensor) -> float: """Given a set of binary labels, determine the empirical probability of a positive label (i.e., the proportion of ones). Args: labels: tf.Tensor, batch of labels Returns: empirical probability of a positive label """ n_pos_labels = tf.math...
db2cc7b5a17c74c27b2cdb4d31e5eeef57fa9411
26,276
def networks_get_by_id(context, network_id): """Get a given network by its id.""" return IMPL.networks_get_by_id(context, network_id)
d7c8ac06dcf828090ec99e884751bd0e3ecde384
26,277
def get_particles(range_diff, image, clustering_settings): """Get the detections using Gary's original method Returns a list of particles and their properties Parameters ---------- range_diff: output from background subtraction image: original image frame for intensity calculat...
ee98806ed38e341da80a9bf3c84d57310a84f2ca
26,278
def validate_file(file): """Validate that the file exists and is a proper puzzle file. Preemptively perform all the checks that are done in the input loop of sudoku_solver.py. :param file: name of file to validate :return True if the file passes all checks, False if it fails """ try: o...
31b9a5fa7dc999d0336b69642c549517399686c1
26,279
def poly(coeffs, n): """Compute value of polynomial given coefficients""" total = 0 for i, c in enumerate(coeffs): total += c * n ** i return total
332584e7bc634f4bcfbd9b6b4f4d04f81df7cbe2
26,280
from typing import Iterable from typing import Dict from typing import Hashable from typing import Tuple def group_by_vals( features: Iterable[feature] ) -> Dict[Hashable, Tuple[feature, ...]]: """ Construct a dict grouping features by their values. Returns a dict where each value is mapped to a ...
436b3e038a11131ea6c0b967c57dd5db59a4b67c
26,281
def coords2cells(coords, meds, threshold=15): """ Single plane method with KDTree. Avoid optotune <-> holography mismatch weirdness. Threshold is in pixels. """ holo_zs = np.unique(coords[:,2]) opto_zs = np.unique(meds[:,2]) matches = [] distances = [] ismatched = [] for hz, oz...
7286be31c9e201df4aea9881bc8226816d0fbf32
26,282
def how_many(num): """Count the number of digits of `num`.""" if num < 10: return 1 else: return 1 + how_many(num // 10)
6b6f8c2a95dac9f2a097300924e29bbca0bdd55c
26,283
def line_length_check(line): """Return TRUE if the line length is too long""" if len(line) > 79: return True return False
2cde1a2b8f20ebf57c6b54bf108e97715789a51d
26,284
def load_image_into_numpy_array(path): """Load an image from file into a numpy array. Puts image into numpy array to feed into tensorflow graph. Note that by convention we put it into a numpy array with shape (height, width, channels), where channels=3 for RGB. Args: path: a file path. Returns: u...
e0ac545486a7ae18cf7c40c03352a04d606c093f
26,285
def possibly_intersecting(dataframebounds, geometry, buffer=0): """ Finding intersecting profiles for each branch is a slow process in case of large datasets To speed this up, we first determine which profile intersect a square box around the branch With the selection, the interseting profiles can be de...
a3e5d031555f92de1fe9ee2d1fb75163d0e29eb9
26,286
def compute_complexity(L, k=5, from_evalues=False, from_gram=False): """ Computes a variety of internal representation complexity metrics at once. Parameters ---------- L : numpy.ndarray, shape (n_samples, ...) internal representation matrix or precomputed eigenvalues k : int, default=5 ...
57283101a1dc266f2059b760715f6b2a782a5e4c
26,287
def settings(request, username, args={}, tab="change_password"): """ Show a page which allows the user to change his settings """ if not request.user.is_authenticated(): return render(request, "users/settings/settings_error.html", {"reason": "not_logged_in"}) profile_user = User.objects...
1325f952bc89644e6a9df0c64c43af85e52858a0
26,289
import hashlib def check_contents(md5, filepath, ignore): """ md5 - the md5 sum calculated last time the data was validated as correct filepath - the location/file where the new data is, this is to be validated ignore - a list of regular expressions that should be thrown out, line by line in the compa...
fb6ae4a3b6600f7df64cf2ccfe24d035c4a98042
26,290
def create_id(prefix=None): """ Create an ID using the module-level ID Generator""" if not prefix: return _get_generator().create_id() else: return _get_generator().create_id(prefix)
cfebf908175fc0a0dc64664f5ceb94eb8395671f
26,291
from re import A def evaluate_policy(theta, F): """ Given theta (scalar, dtype=float) and policy F (array_like), returns the value associated with that policy under the worst case path for {w_t}, as well as the entropy level. """ rlq = qe.robustlq.RBLQ(Q, R, A, B, C, beta, theta) K_F, P_F,...
40db3c4215aea266ed2b85256c901f135fdc5b50
26,292
def arspec(x, order, nfft=None, fs=1): """Compute the spectral density using an AR model. An AR model of the signal is estimated through the Yule-Walker equations; the estimated AR coefficient are then used to compute the spectrum, which can be computed explicitely for AR models. Parameters --...
b0e003bf387870320ea61419a169a80b1a41165d
26,293
import warnings def T_asymmetry(x, beta): """Performs a transformation over the input to break the symmetry of the symmetric functions. Args: x (np.array): An array holding the input to be transformed. beta (float): Exponential value used to produce the asymmetry. Returns: The tr...
8ad3fa58fc2d1b641e4fc122517dc4202a76f840
26,294
def fit_improved_B2AC_numpy(points): """Ellipse fitting in Python with improved B2AC algorithm as described in this `paper <http://autotrace.sourceforge.net/WSCG98.pdf>`_. This version of the fitting simply applies NumPy:s methods for calculating the conic section, modelled after the Matlab code in the...
85544ec311edce8eebdd6c143a68e5fc40b0a882
26,295
import copy def generate_complex_topologies_and_positions(ligand_filename, protein_pdb_filename): """ Generate the topologies and positions for complex phase simulations, given an input ligand file (in supported openeye format) and protein pdb file. Note that the input ligand file should have coordinates ...
6c47957c1d70936486d4bf5167f3724935a5f4df
26,296
def aten_append(mapper, graph, node): """ 构造对list进行append的PaddleLayer。 TorchScript示例: %90 : int[] = aten::append(%_output_size.1, %v.1) 参数含义: %90 (list): 输出,append后的list。 %_output_size.1 (list): 需要进行append的list。 %v.1 (-): append的元素。 """ scope_name = mapper.normal...
f95977daf6da0fc2aafceda404d4dd6faf4d5f0c
26,297
def res_from_obseravtion_data(observation_data): """create a generic residual dataframe filled with np.NaN for missing information Parameters ---------- observation_data : pandas.DataFrame pyemu.Pst.observation_data Returns ------- res_df : pandas.DataFrame """ res_df ...
d569c80d1536c3a46c7f9b6120753e56c118a74e
26,298
import re def dtype_ripper(the_dtype, min_years, max_years): """Extract the range of years from the dtype of a structured array. Args: the_dtype (list): A list of tuples with each tuple containing two entries, a column heading string, and a string defining the data type for th...
1cbcc30cf7760d466187873aa5ea221691b2092d
26,299
import json def test_sensor_query(cbcsdk_mock): """Test the sensor kit query.""" def validate_post(url, param_table, **kwargs): assert kwargs['configParams'] == 'SampleConfParams' r = json.loads(kwargs['sensor_url_request']) assert r == {'sensor_types': [{'device_type': 'LINUX', 'archi...
878a060ad7f532522b8ef81f76701fbe0c7dc11b
26,301
def encoder_apply_one_shift(prev_layer, weights, biases, act_type, name='E', num_encoder_weights=1): """Apply an encoder to data for only one time step (shift). Arguments: prev_layer -- input for a particular time step (shift) weights -- dictionary of weights biases -- dictionary of bia...
19ea3beec271e003f6d9ccadd4d508d97f6b7572
26,303
import uuid def db_entry_generate_id(): """ Generate a new uuid for a new entry """ return str(uuid.uuid4()).lower().replace('-','')
d5e90504a1927623b267082cd228981684c84e8d
26,304
def angle_boxplus(a, v): """ Returns the unwrapped angle obtained by adding v to a in radians. """ return angle_unwrap(a + v)
9434d88d59956eeb4803bbee0f0fb3ad8acd1f5f
26,306
def color_gradient_threshold(img, s_thresh=[(170, 255),(170, 255)], sx_thresh=(20, 100)): """ Apply a color threshold and a gradient threshold to the given image. Args: img: apply thresholds to this image s_thresh: Color threshold (apply to S channel of HLS and B channel of LAB) sx_...
02bdfbd9a95dbfe726eac425e1b6efb78bfedb2b
26,307
def toeplitz(c, r=None): """ Construct a Toeplitz matrix. The Toeplitz matrix has constant diagonals, with c as its first column and r as its first row. If r is not given, ``r == conjugate(c)`` is assumed. Parameters ---------- c : array_like First column of the matrix. Whateve...
00c68daef087fded65e1feee375491db559c792f
26,308
def MQWS(settings, T): """ Generates a surface density profile as the per method used in Mayer, Quinn, Wadsley, and Stadel 2004 ** ARGUMENTS ** NOTE: if units are not supplied, assumed units are AU, Msol settings : IC settings settings like those contained in an IC object (see ...
bd1227f4416d093271571f0d6385c98d263c514e
26,309
def predict(x, P, F=1, Q=0, u=0, B=1, alpha=1.): """ Predict next state (prior) using the Kalman filter state propagation equations. Parameters ---------- x : numpy.array State estimate vector P : numpy.array Covariance matrix F : numpy.array() State Transitio...
fa638183a90583c47476cc7687b8702eb193dffb
26,310
from typing import Dict def footer_processor(request: HttpRequest) -> Dict[str, str]: """Add the footer email me message to the context of all templates since the footer is included everywhere.""" try: message = KlanadTranslations.objects.all()[0].footer_email_me return {"footer_email_me": mes...
3d38c4414cf4ddab46a16d09c0dcc37c57354cb1
26,311
def genome_2_validator(genome_2): """ Conducts various test to ensure the stability of the Genome 2.0 """ standard_gene_length = 27 def structure_test_gene_lengths(): """ Check length requirements for each gene """ gene_anomalies = 0 for key in genome_2: ...
7fe54b51673f3bc71cb8899f9a20b51d28d80957
26,312
def to_poly(group): """Convert set of fire events to polygons.""" # create geometries from events geometries = [] for _, row in group.iterrows(): geometry = corners_to_poly(row['H'], row['V'], row['i'], row['j']) geometries.append(geometry) # convert to single polygon vt_poly =...
5482121dc57e3729695b3b3962339cb51c1613dc
26,314
def get_user(): """ Get the current logged in user to Jupyter :return: (str) name of the logged in user """ uname = env_vars.get('JUPYTERHUB_USER') or env_vars.get('USER') return uname
a7ece43874794bbc62a43085a5bf6b352a293ea2
26,315
import logging import time def get_top_articles(update=False): """ Retrieve 10 most recent wiki articles from the datastore or from memcache :param update: when this is specified, articles are retrived from the datastore :return: a list of 10 most recent articles """ # use caching to avoid run...
b5ac25e8d06acd48e3ee4157fcfcffd580cf421e
26,316
def bucket(x, bucket_size): """'Pixel bucket' a numpy array. By 'pixel bucket', I mean, replace groups of N consecutive pixels in the array with a single pixel which is the sum of the N replaced pixels. See: http://stackoverflow.com/q/36269508/513688 """ for b in bucket_size: assert float(b).is...
8ff3eda1876b48a8bdd4fbfe6b740ed7e3498c51
26,317
def create_msg(q1,q2,q3): """ Converts the given configuration into a string of bytes understood by the robot arm. Parameters: q1: The joint angle for the first (waist) axis. q2: The joint angle for the second (shoulder) axis. q3: The joint angle for the third (wrist) axis. Returns: The string of bytes. ...
26f9954a55686c9bf8bd08cc7a9865f3e4e602e3
26,318
def get_config(): """Provide the global configuration object.""" global __config if __config is None: __config = ComplianceConfig() return __config
cdaa82445b4f260c7b676dc25ce4e8009488603e
26,319
import array def size(x: "array.Array") -> "array.Array": """Takes a tensor as input and outputs a int64 scalar that equals to the total number of elements of the input tensor. Note that len(x) is more efficient (and should give the same result). The difference is that this `size` free function adds ...
2e80223a2468f0d9363ad2aa148d14a090c0d009
26,320
def linspace(start, stop, length): """ Create a pdarray of linearly spaced points in a closed interval. Parameters ---------- start : scalar Start of interval (inclusive) stop : scalar End of interval (inclusive) length : int Number of points Returns -------...
82d90c0f6dcdca87b5c92d2668b289a1db0b2e64
26,321
def _load_corpus_as_dataframe(path): """ Load documents corpus from file in 'path' :return: """ json_data = load_json_file(path) tweets_df = _load_tweets_as_dataframe(json_data) _clean_hashtags_and_urls(tweets_df) # Rename columns to obtain: Tweet | Username | Date | Hashtags | Likes | R...
7113b51ec7e35d2b11697e8b049ba9ef7e1eb903
26,322
def UNTL_to_encodedUNTL(subject): """Normalize a UNTL subject heading to be used in SOLR.""" subject = normalize_UNTL(subject) subject = subject.replace(' ', '_') subject = subject.replace('_-_', '/') return subject
51c863327eec50232d83ea645d4f89f1e1829444
26,323
def parse_cigar(cigarlist, ope): """ for a specific operation (mismach, match, insertion, deletion... see above) return occurences and index in the alignment """ tlength = 0 coordinate = [] # count matches, indels and mismatches oplist = (0, 1, 2, 7, 8) for operation, length in cigarlist: if operation...
4eceab70956f787374b2c1cffa02ea7ce34fe657
26,324
def _decode_token_compact(token): """ Decode a compact-serialized JWT Returns {'header': ..., 'payload': ..., 'signature': ...} """ header, payload, raw_signature, signing_input = _unpack_token_compact(token) token = { "header": header, "payload": payload, "signature": b...
e7dbe465c045828e0e7b443d01ea2daeac2d9b9a
26,325
def _top_N_str(m, col, count_col, N): """ Example ------- >>> df = pd.DataFrame({'catvar':["a","b","b","c"], "numvar":[10,1,100,3]}) >>> _top_N_str(df, col = 'catvar', count_col ='numvar', N=2) 'b (88.6%), a (8.8%)' """ gby = m.groupby(col)[count_col].agg(np.sum) gby = 100 * gby / gb...
d80e5f7822d400e88594a96c9e1866ede7d9843e
26,326
def insert_box(part, box, retries=10): """Adds a box / connector to a part using boolean union. Operating under the assumption that adding a connector MUST INCREASE the number of vertices of the resulting part. :param part: part to add connector to :type part: trimesh.Trimesh :param box: connector ...
76f29f8fb4ebdd67b7385f5a81fa87df4b64d4c7
26,327
def pnorm(x, p): """ Returns the L_p norm of vector 'x'. :param x: The vector. :param p: The order of the norm. :return: The L_p norm of the matrix. """ result = 0 for index in x: result += abs(index) ** p result = result ** (1/p) return result
110fea5cbe552f022c163e9dcdeacddd920dbc65
26,329
def _kneighborsclassifier(*, train, test, x_predict=None, metrics, n_neighbors=5, weights='uniform', algorithm='auto', leaf_size=30, p=2, metric='minkowski', metric_params=None, n_jobs=None, **kwargs): """ For more info visit : https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsCl...
0a8ff00a5fc4978758432df34947895688b225cd
26,331
def overlap(batch_x, n_context=296, n_input=39): """ Due to the requirement of static shapes(see fix_batch_size()), we need to stack the dynamic data to form a static input shape. Using the n_context of 296 (1 second of mfcc) """ window_width = n_context num_channels = n_input batch_x =...
75936fe9ecb0f3e278fd6c990cab297c878006b1
26,332
def eval_on_train_data_input_fn(training_dir, hyperparameters): """ :param training_dir: The directory where the training CSV is located :param hyperparameters: A parameter set of the form { 'batch_size': TRAINING_BATCH_SIZE, 'num_epochs': TRAINING_EPOCHS, 'data_downsize': DATA_D...
07f9b33c936be5914b30697c25085baa25799d0d
26,333