content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import logging def calc_histogram_bins(value_array, bin_size=0.01): """Calculate histogram bins Parameters ---------- etrf_array : bin_size : float, optional Histogram bin size (the default is 0.01). Returns ------- NumPy array """ bin_min = np.floor(np.nanmin(value_...
2c33bf5f6658aa1c16f3055ed2dd6d344a88a4ad
63,700
import random def rand(plan, num=1): """Shuffle to generate new perm""" def shuffle_tasks(): perm = plan.perm[:] random.shuffle(perm) return perm return [shuffle_tasks() for _ in range(num)]
5c4318e4be1330f0a78eeec30665626eb5802934
63,701
def get_mongo_conn(db="test"): """ use me like this: collection = get_mongo_conn()["collection_name"] collection.insert({}) """ return MONGO_POOL[db]
1ca41703988c4c60e44a2d667404cf40b3423399
63,702
def generate_manifest_header(manifest_id, key_size, manifest_type): """ Create a manifest header :param manifest_id: Manifest id :param key_size: Size of RSA key :param manifest_type: Manifest type :return Instance of a manifest header """ if manifest_type == manifest_types.PFM: ...
08f5a05d89024a7b7067ca9005cd18e0bcd287a1
63,703
def stash_data(data, expire=None): """Stores data in an encrypted form and returns a key and a decryption secret.""" if expire is None: expire = 60*60*24*90 try: expire = int(expire) assert expire > 0 except: raise DAError("Invalid expire value") return server.stash_d...
d51d649e596220957401bc4768277bef6e6c1146
63,704
import logging def _sync_build_in_memory(build, result): """Syncs |build| state with swarming task |result|.""" # Task result docs: # https://github.com/luci/luci-py/blob/985821e9f13da2c93cb149d9e1159c68c72d58da/appengine/swarming/server/task_result.py#L239 if build.status == model.BuildStatus.COMPLETED: # p...
7246de3f925ec2740bef8d8a76baee4202d13725
63,705
def getMembershipDays(membership, onDate, houseDates=housedata.dates): """ Returns the number of days service in a membership up to the given date, excluding periods when the House is in dissolution. The onDate is a datetime.date. """ # Set the start date to the membership start date startDate = convertMnisDat...
4510cddea33a772ffa9999f26caae23dc70d67f6
63,706
def left_to_right_check(input_line: str, pivot: int): """ Check row-wise visibility from left to right. Return True if number of building from the left-most hint is visible looking to the right, False otherwise. input_line - representing board row. pivot - number on the left-most hint of the in...
e528f8d79f136b41fa92de5e9ac17de1fd200258
63,707
def parse_perseus_xml(files): """Parses the given XML files. Returns the parsed files as well as a list of files which couldn't be parsed at all.""" raw_texts = [] failed_to_parse = [] print("Parsing: ", end="") for i, f in enumerate(files): raw_text = "" with open(f) as fp: ...
8879a978a441db2fa4fc2183d627321903414693
63,708
def stetson_kernels(radius, nhalf, nbox, sigsq): """Stetson kernel generation.""" # Mask identifies valid pixels in convolution box mask = np.zeros([nbox, nbox], dtype='int8') g = np.zeros([nbox, nbox]) # Gaussian convolution kernel row2 = (np.arange(nbox)-nhalf)**2 for i in range(nhalf+1): ...
89acc82f196f73b0d41fdbb9f8507e05a2e32dce
63,709
def good_discovery(status, device_name): """Checks the hdisk discovery results for a good discovery. Acceptable LUA discovery statuses are :- DEVICE_AVAILABLE: hdisk discovered on all the ITL paths and available. DEVICE_IN_USE: hdisk discovered on all the ITL paths and is in-use by the server. ...
26e8130b39921faf84f94d6e243b09fffbee8b47
63,710
def okkOokOo(s): """ okkookoo == PEP8, forced mixedCase by CodeWars """ return ''.join(chr(int(''.join(SCORE.get(a, '') for a in word), 2)) for word in s.split('?'))
b59b2c7d6445eb80f0d692c76943220e42c3d20a
63,711
from typing import Optional def multipletests( srs: pd.Series, method: Optional[str] = None, nan_mode: Optional[str] = None, prefix: Optional[str] = None, ) -> pd.Series: """ Wrap statsmodel's multipletests. Returns results in a series indexed like srs. Documentation at https://ww...
325085e348b8aae61228ca36550b8ea5871ed6b1
63,712
from unittest.mock import Mock def _mock_channel(*, name, **kwargs): """Create a mock channel and associated DB record""" if not Channel.objects.filter(name=name).exists(): ChannelFactory.create(name=name) return Mock(display_name=name, **kwargs)
aa0003b47cc2b3382a89cb8e592df62ed91da142
63,713
from typing import List def extract_strings(b: DeltaBytes, min_length, no_filter) -> List[DecodedString]: """ Extract the ASCII and UTF-16 strings from a bytestring. """ ret = [] for s in floss.strings.extract_ascii_strings(b.bytes): if len(s.string) > MAX_STRING_LENGTH: conti...
477f33b1652e5ac25b81f9d70f35ad0aa22d302a
63,714
def import_ori(filename): """ Read in Filename for EJMT Tunnel mock model fault orientations """ #filename = 'Mock_FaultOrientations.csv' """ Extract values and store in nested lists with filename identifier """ with open(filename, 'r') as f: for x in range(1): # Skip header nex...
ad9f8b5c158a372cacbe6f9449c358708af38aa2
63,715
import os import ast def get_version(module='win_tornado_terminals'): """Get version.""" with open(os.path.join(HERE, module, '__init__.py'), 'r') as f: data = f.read() lines = data.split('\n') for line in lines: if line.startswith('VERSION_INFO'): version_tuple = ast.liter...
d862e3a2518ec60cc46f646af996b1be85c75bcd
63,716
import torch def quantile_regression_loss(input, target, tau, weight): """ input: (N, T) target: (N, T) tau: (N, T) """ input = input.unsqueeze(-1) target = target.detach().unsqueeze(-2) tau = tau.detach().unsqueeze(-1) weight = weight.detach().unsqueeze(-2) expanded_input, exp...
808749c54df36a150c18fccd638bf0e85272a458
63,717
from typing import Tuple def settings_credit_callback(update: Update, context: CallbackContext) -> Tuple[str, InlineKeyboardMarkup, int]: """Handles the settings_foto_cane callback. Adds the user_id to the table of credited users, if it wasn't already there Args: update (Update): update event ...
0e90285a52230260d778fe2f0300af21ece802a9
63,718
def get_spotting(ID): """ Function to get one spotting document from Elasticsearch Params: ID::str id of the spotting document Returns: doc::dict The document retrieved from ES """ if not ID: return False try: global INDEX ref...
4d511758cb270f4cf023e40baabc534efadc8d98
63,719
def collect_to(to): """Collect audience to send email to from to object Arguments: to {dict} -- AppInterfaceEmailAudience_v1 object Raises: AttributeError: Unknown alias Returns: set -- Audience to send email to """ audience = set() aliases = to.get('aliases') ...
5525b6fae83ee54cad2f7fb716dbb394774f42ce
63,720
import os def rawdata_root(): """Returns directory root for raw data, i.e. ``$LVM_SPECTRO_DATA`` Raises: AssertionError: if these environment variables aren't set. """ assert 'LVM_SPECTRO_DATA' in os.environ, 'Missing $LVM_SPECTRO_DATA environment variable' return os.environ['LVM_SPECTRO_...
30dee82f52075e49d457eeb00d7e87d0a67935af
63,721
def view_item(key): """ View existing kanji """ kanji = unicode(key, 'utf-8') # TODO: test if such item|kanji exists radicals = store.get_radicals(kanji) session = request.environ.get('beaker.session') return render( 'home', kanji=Peon(db).get_item(kanji), radicals=radica...
55628da11a5de7225a20795d6b3dd9db7e9cb17c
63,722
from typing import List from typing import Callable def parametrize_over_experiments(models: List) -> Callable: """Parametrize a TestCase over different kind of experiments. Args: models: list of model descriptions. The ``TestCase`` will be repeated for each of the entries in the list. ...
351e2a7c8be2e5af61bcd8e06bee288e4504dac6
63,723
def open_opencart_admin_url(driver, request): """Get base URL and attend admin link""" url = 'admin/' return driver.get("".join([request.config.getoption("--address2"), url]))
0c1d0493833b98869324bcbe65ee8f8888fd6c5c
63,724
import copy def GetFilteredEvents(events, filteredIndex): """ returns a class of filered events by index's wanted :param events: class of events in current time :param filteredIndex: indexs of events watned :return: class of filtered events """ eventsPos = copy.deepcopy(events.po...
0e5b93afd95cba439a620a85d8e88ec4ddc90f82
63,725
import copy def build_single_tree(data, data_oob, y_i, y_nn_i, d_i, x_i, w_i, x_type, x_values, x_ind, x_ai_ind, c_dict, mmm, n_min, alpha_reg, node_table, pen_mult, regrf=False): """Build single tree given random sample split. Parameters ---------- data : ...
058858ce2df1be1f5e460ed1b54bd3b94acced52
63,726
import random import base64 def password_encrypt(text: str, key: str): """translate from encrypt.js""" _rds = lambda length: ''.join([random.choice('ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678') for _ in range(length)]) pad = lambda s: s + (len(key) - len(s) % len(key)) * chr(len(key) - len(s) % len(...
17af8d702a536d48e67c40fab3455761746ae1f3
63,727
import json def load_config(path: str): """ Loads a config file as a spec_config object :param path: The path to the config file :return: A loaded spec_config or None """ try: with open(path, 'r') as f: return json.load(f, cls=spec_decoder) except: return None
06d77f27a10872cde047bb96ebcc28733fc763f7
63,728
from re import T def index_fn(model_predict, input_var, target_var): """ Theano function returns an array containing boolean values that indicate whether predicted label matches target_var """ index_temp = T.eq(T.argmax(model_predict, axis=1), target_var) return theano.function([input_var,ta...
dc2ebcc25a5d61f5c12c661a91e12519336f9672
63,729
def change_encoding_improve(infile, outfile, enc1, enc2="utf-8", process=None, fLOG=noLOG): """ Changes the encoding of a text file, removes quotes. By default *process* is @see fn process_line but the function has access to the distribution of the number of columns in th...
829aff6c56d765300a238d4d7c1b754793db4ed7
63,730
import torch def compute_feature(block: torch.Tensor) -> list: """Compute features. Args: block (torch.Tensor): 2D image block. Returns: list: Features with length of 18. """ feat = [] alpha, beta_l, beta_r = estimate_aggd_param(block) feat.extend([alpha, (beta_l + beta_r...
0302d51a07050e516f92120181bc86912b20eaab
63,731
def stop_es(bot, update): """Ends the automaton""" logger.info('%s (@%s) stopped the bot', update.message.from_user.first_name, update.message.chat.username) update.message.reply_markdown(st.strings["force_end"]) return bot.ConversationHandler.END
d920bbfc9986834fa5f869197d592ffc380a6538
63,732
import inspect def get_caller_name(skip: int =3): """Get a name of a caller in the format module.class.method. `skip` specifies how many levels of stack to skip while getting caller name. skip=1 means "who calls me", skip=2 "who calls my caller" etc. An empty string is returned if skipped levels exc...
c5e26ee7533f6686712ec1a6e5088eeb67a8e0af
63,733
def pdf_gaussian_algebraic( returns: np.ndarray, K: float, L: float, N: float, Lambda: float ) -> np.ndarray: """Computes de one dimensional Gaussian-Algebraic PDF. :param returns: numpy array with the returns values. :param K: number of companies. :param L: shape parameter. :param N: strength ...
6508ee67164ce996c4502d6f710e1fb7be690a2b
63,734
def documentation_tests(session): """Run documentation tests.""" return docs(session, batch_run=True)
058f31d789491f392e0eee06e219298519405ac4
63,735
from typing import List from typing import Tuple from typing import Any def paras_to_sents(paras: List[str],) -> Tuple[List[Any], List[Any], str]: """ sent-segment paras sents list, slice_list and lang """ sents: List[str] = [] slice_list: List[slice] = [] lang: str = Text(" ".join(paras[:30])).de...
7ea6e9123acc749d3c0de5e7744980c2ae7172e9
63,736
def export(signature, **kws): """ Construct a decorator that takes a function and exports one A signature is a string with name ret_type(arg_type, argtype, ...) """ name, restype, argtypes = _process_sig(signature) return _internal_export(name=name, restype=restype, argtypes=argtypes, **kw...
faef680517a36f2759cc4c825f9e60ffe6ada335
63,737
def multi_generator(gan, z, num, share_params = True, reuse = False): """ Args: gan : instance of a generative adversarial network num: Number of the generator reuse : Whether you want to reuse variables from previous share_params : Whether weights are tied in initial layers...
2c998300aa0c9331524286bf9d41b06443bae9d0
63,738
import binascii import re import struct import pathlib def ProcessPlugxXORFile(inFile,PlugxData,pos): """ IN: PlugX data to decrypt. OUT: Bool True or False Description: Decrypts PlugX DAT file and assumes files are not compressed """ PlugX_Decrypted = Decrypt_XOR( PlugxData,pos ) if ...
a53a17bde0ed1942cb76f14f58cfe7fb125cda68
63,739
def count_features_type(types, include_binary=False): """ Counts two or three different types of features (binary (optional), categorical, continuous). :param types: list of types from get_type :returns a tuple (binary (optional), categorical, continuous) """ if include_binary: return ( ...
4158122256c9a407f58987d278657e4a006e6a13
63,740
def CRy(control: int, target: int, angle: float) -> QCircuit: """ Convenience initialization CRy (controlled Pauli Y Rotation) Parameters ---------- control: int control qubit target: int target qubit angle: Hashable type (will be treated as Variable) or Numeric type...
e9bd8dd87a32f7ca604c0a05ebb81309176308b5
63,741
def _with_iteration(fn): """Uses iteration to produce vmap-like output.""" def wrapper(*args): outputs = [] # Iterating over the first axis. for inputs in strict_zip(*args): outputs.append(fn(*inputs)) return jax.tree_util.tree_multimap(lambda *x: jnp.stack(x), *outputs) return wrapper
00855ddb1d85304af38152e7961d8b89ef5c09f8
63,742
def optimize(w_p, w_a, w_f, w_e, corpus_weights, scenario, char_set, startsolution="", fixation_constraints=1, coherence_constraints=1, capitalization_constraints=1): """ Optimizes the pre-defined scenario with the given weights. Parameters: w_p, w_a, w_f, w_e: weights for the individu...
34439faa3bef324d3658f64dbdc680eb39cbca7d
63,743
import torch def sequence_cross_entropy_with_logits(logits, targets, mask, label_smoothing, reduce): # type: (Tensor, Tensor, Tensor, float, bool)-> Tensor """ label_smoothing : ``float``, optional (default = 0.0) It should be smaller than 1. """ # shape : (batch * sequence_length, num_cla...
db05c49a15287999a8864fe8b789d671495e82b3
63,744
def raster_pixel_count(dataset_uri): """Determine how many of each unique pixel lies in the dataset (dataset) dataset_uri - a GDAL raster dataset returns - a dictionary whose keys are the unique pixel values and whose values are the number of occurrences """ LOGGER.debu...
eb930ae4b1f45a49eb3900d1a91d77679d03b805
63,745
def areafiltering_remove_larger_objects_binary(image, kernel=None, n=None): """ Removes all objects in the image that have an area smaller than the threshold specified. Additional Arguments -------------------- n : int Specifies the threshold. """ nb_components, output, s...
9e64432afa47bbb8e39455abd83ced27b2504502
63,746
import argparse def get_args() -> argparse.Namespace: """Parse command-line arguments.""" parser = argparse.ArgumentParser(prog="rhasspy-profile") parser.add_argument( "--debug", action="store_true", help="Print DEBUG messages to the console" ) parser.add_argument( "--profile", "-p...
05c408d7702cea588c910ed3afaeff1acd237268
63,747
def dsdlogdp(dp, n, gm, gsd): """ Discrete PDF for a surface-weighted lognormal particle size distribution. :param dp: Particle diameters at which to evaluate the PDF in building the discrete model. :type dp: numpy array :param n: The area under the curve of the continuous PDF ...
ee268df8370a35aada1e3a03c4065e521142e2ff
63,748
def is_pandas_module(fullname: str) -> bool: """Check if a fully qualified name is from the pandas module""" return fullname.startswith("pandas.")
0becdbfd7c1c4f5b7990cbc0466a6e45f25acb14
63,749
import io def starting_metadata(overrides): """Fake the xdata associated with a brand new submission, adding in `overrides` to tweak test cases.""" d = io.get_default_metadata() d["job_id"] = "fake_job_id" d.update(overrides) return d
75ee436b3ef65975d04920ad75ba972af4d39294
63,750
def validate_port_operation(session, row): """Validate port operation based on dependencies. Validate port operation depending on whether it's dependencies are still in 'pending' or 'processing' state. e.g. """ if row.operation in (sdn_const.POST, sdn_const.PUT): network_dict = jsonutils.lo...
41f19871ce074535a50d50242298fa547b7ebdd0
63,751
def sigmoid(z): """The sigmoid function""" try: z=1 / (1 + np.exp(-z)) except OverflowError: pass # print(z) # sys.exit() return z
8dbf9418b97de631fb1081f618ceabfaa2d0ef8d
63,752
import os import json def set_json_app_argument(config_path, key, value): """Writes kv pair to json argument file Arguments: config_path {string} -- path to json config file, example: /var/run/appconfig/streaming_args.json key {string} -- the name of the argument to set value {any} --...
149a013c57db130161612cd3070ceb393ec1a6e7
63,753
from datetime import datetime import os def time_to_string(): """Converts the current time to string so it can be used to save the file.""" now = datetime.datetime.now() # Gives current time. return f"C:\\Users\\{os.getlogin()}\\Pictures\\Screenshots\\{datetime.datetime.strftime(now, '%Y%m%d_%H%M%S')}.png...
69663ef21c0f45277c90fb6fadd63e5a1d95bcd3
63,754
from functools import reduce def unitary_to_monodromy_coordinate(unitary): """ Given a unitary matrix, produces its alcove coordinate. """ unitary = unitary * np.linalg.det(unitary) ** (-1 / 4) sysy = np.array([ [0, 0, 0, 1], [0, 0, -1, 0], [0, -1, 0, 0], [1, 0...
a3901f9f814c3bf09be213288f8cecacd4aab9b0
63,755
from typing import Mapping def _add_empty_values(step: rlds_types.Step, spec: Mapping[str, tf.TensorSpec]) -> rlds_types.Step: """Adds zero elements to step for the keys in spec not present in step. Args: step: Dictionary representing a Step. spec: Tensor spec. Returns: Dicti...
d4aba17659aa84646d7c214b8447a16432f6b2f4
63,756
import pickle import base64 def merge_cart_cookie_to_redis(request, response, user): """ 用户登录时合并购物车数据到redis方法 :param request: 请求的request对象 :param response: 返回的响应response对象 :param user: 登录的用户对象 :return: response对象 """ # 从cookie中取出购物车数据, cookie_cart_str = request.COOKIES.get('cart') ...
039d0e706f55ee7a4cd04361a68a33ef1f7b67bb
63,757
import itertools def _schedule_menu(update, context): # pylint: disable=unused-argument """Present the user the scheduling options""" chat_id = update.callback_query.message.chat_id comics = database_query("SELECT name FROM sources") buttons = [] for name in itertools.chain.from_iterable(comics)...
7cb1b81771f0ef4d60f4b31d0695aa2c9a1fd23d
63,758
from re import A import io def pure(a: A) -> Resource[R, E, A]: """ A Resource that always returns the same constant. """ return Resource(io.pure((a, noop_close)))
10900bd6582d0489cf63d0b9f667d6ddb6819d5a
63,759
def find_func(identifier: str): """Find the function of an identifier that has been registered""" return [k for k, v in _AI_REGISTRY.items() if v == identifier][0]
3c9451ca8596d7c23ee5c360d9cd6bc9d050793a
63,760
def _Scan(): """Checks that license meta-data is present for all third-party code. Returns: Whether the check succeeded. """ third_party_dirs = _FindThirdPartyDirs() # First, check designated third-party directories using src/tools/licenses.py. all_licenses_valid = True for path in sorted(third_part...
3fb2750dcc65d6a8187e32166e4a6e155e1ee0d6
63,761
def set_mapping(joystick, mapping): """Set the button mapping. Note: Hat keys should have a set value for the proper quadrant. Args: joystick (Joystick/str): Joystick object or String GUID mapping (dict): Dictionary of name: Key values to map to the joystick/game controller. R...
065988362e34bb25a4d3013f5a62df5abdfe7403
63,762
import os def mkdir_slashfix_open(filename, mode): """Like common.slashfix_open(), but make directories as needed.""" real_filename = common.slashfix(filename) directory = os.path.dirname(real_filename) os.makedirs(directory, exist_ok=True) return open(real_filename, mode)
9c43653f0108988e63f1a290f583f9049002aa82
63,763
def create_raster(*args, **kwargs): """Shortcut for `Dataset().acreate_raster` >>> help(Dataset.create_raster) See Also -------- - :py:func:`Dataset.create_raster` - :py:meth:`Dataset.acreate_raster` """ return Dataset().acreate_raster(*args, **kwargs)
c6795876482d2c515505123a203675446ec30675
63,764
from typing import Optional import random import io def random_digits(length: int = 32, base: int = 10, upper: bool = False, rnd: Optional[random.Random] = None) -> str: """ Overview: Create random digits. Arguments: - length (:obj:`int`): Length of the digits, default is 32. - ba...
680a5201e183cf57e56adea1e79718026beda052
63,765
def process_manual_category(tag, manual_tag): """ 处理category信息 """ replace_tag = str(manual_tag) if str(manual_tag) in ["1", "1.0"]: replace_tag = tag if "[" and "]" not in replace_tag: tag_list = replace_tag.split(",") else: tag_list = eval(replace_tag) return...
8303cd69df4c5dce47a2dcc4546ef1490f2b2f1b
63,766
def squeeze_first(inputs): """Remove the first dimension in case it is singleton.""" if len(inputs) == 1: inputs = inputs[0] return inputs
c2c0cabc873baf88ce7673f2c8889fedce0f05da
63,767
from rpy2.robjects import numpy2ri import copy def pen_rf_importance(X, y, cost_vec=None, cost_param=0, num_features_to_select=None, imp_type="impurity", min_samples_leaf=1, n_estimators=500, rf_importance_vec=None, is_disc=None): """ Cost-based feature ranking with pen...
637095abac615829d5167eb9185c43ea039c4598
63,768
def estimate_best_parameters(grid, best_grid_pars=None): """ Estimate the best parameters by interpolating the grid parameters: ============ - grid: pd.DataFrame Contains the full grid. Get this by calling read_chi2_output() - best_grid_pars: pd.Series or dict ...
2aa1be84de6f8c8a1000d86ae6bae903743bf1fd
63,769
def get_total_distance_of_path(path, table): """ Calculates the total distance of an individual bee's path. Terminates at starting node to complete cycle. """ # Creates a copy of path, puts head at end of list. # Zip lists to create pairs of neighbor coords, # will create a cycle that termin...
d6c655b7bbed075dc8323d5d60ee128b8693d792
63,770
def shift_point(point, latitude_shift_km, longitude_shift_km):# -> tuple(float, float): """Shifts the coordinates of a given point. Args: point (tuple): Starting point as (latitude, longitude), in degrees latitude_shift_km (float): Latitude offset in kilometers longitude_shift_km (float...
36544b82d10e3bae93f343757fdcd654f7f4a78b
63,771
import time def timing(func): """ Wrapper for class instance methods enabling the timing of execution. Important for measuring speed and performance measurement. Parameters ___________ func : func Function to be wrapped and timed following execution. Returns ________ wrap...
d84d51959be1def284fb7d6a6264c4c1138acd85
63,772
from typing import Dict import torch from typing import Tuple def compute_accuracy(output_tensors_by_model: Dict[str, torch.Tensor], target: torch.Tensor, topk: Tuple = (1,), ) -> Dict[str, Dict[str, torch.Tensor]]: """Computes the accuracy over the k...
68228b68e26f502f162df6fa902401c2e5cda981
63,773
def is_valid_string_minsize(param, minsize=None, required=True): """Checks if the parameter is a valid string and his size is more than minsize. If the parameter minsize is None than the size is ignored If the parameter required is True than the string can not be None @param param: Value to be validate...
b1ed83ef3b44cf94f02fadf31f42ac9fe40679fa
63,774
from typing import Counter def removeInsignificantNodes(dataframe,filename = None,csvSeparator = ';'): """ Removes nodes that occur only once, as they are just the supposed ends of given tube. Parameters ---------- dataframe : pandas.DataFrame() Dataframe containing arranged da...
0aa345d257aba84e67a73845a795f820de9190dd
63,775
def _phaseSpaceThresh(u): """ Implements the Goring+Nikora2002 despiking method, with Wahl2003 correction. """ if u.ndim == 1: u = u[:, None] u = np.array(u) # Don't want to deal with marray in this function. Lu = (2 * np.log(u.shape[0])) ** 0.5 u = u - u.mean(0) du = np.zer...
dd70d5fae352fedc6a6e9519697747d99645aa1e
63,776
import multiprocessing def extract_slice(data, trans, pshape): """optional params meaning - see dice() above Algorithm: 1. find intersections of the plane with the data box edges 2. for these pts, find axis-oriented b-box 3. find the trans (A,T) from R2 to R3, like X' = AX + T use (0,0), (0...
892796f0bae83538c1ea78055c7ce59e3512dd28
63,777
def run_command(cmd_name): """ Executes a single Waf command. Called by :py:func:`waflib.Scripting.run_commands`. :param cmd_name: command to execute, like ``build`` :type cmd_name: string """ ctx = Context.create_context(cmd_name) ctx.log_timer = Utils.Timer() ctx.options = Options.options # provided for conv...
6c0a6b4173b7ea5c0fb63c9a8cdd9c9687771fa5
63,778
import requests def exists(path): """Makes a head request to the given path and returns a status_code""" try: resp = requests.head(path) logger.debug('HEAD request to remote server. Response status_code: %s', resp.status_code) return resp.status_code < 400 except Exception: ...
29637cdb291e79c6c4a2c921dc6280b86727c984
63,779
from analysis_functions import unique from numpy import median,std,cast,float32,any,where def images_zinger_replaced(images,sigma=5.730729): """Returns images_zr after replacing zingers in images with median values. Zingers are identified according to statistical criteria. Also returns the indices for ima...
2ece2c42f4cdcadf4d981de83b0b32d0ad504e61
63,780
def get_constant(name): """Use this to get the value of a VBA constant. @param name (str) The name of the VBA enum constant to get. @return (int) The enum value if the given name names a VBA enum constant, None if not. """ name = safe_str_convert(name).lower() if is_constant(name): ...
b8a165397fc7ac02462f5319bdc3d490c12daab6
63,781
def _create_line2d_collection(coords, indices, infos=None, picker=False, **kwargs): """ Generic function to create a LineCollection from coordinates. :param coords: list of line coordinates (list should look like this: \ `[[(x11, y11), (x12, y12), (x13, y13), ...], [(x21, y21), (x22, x23), ...], .....
d2af45a15f4d180bcca4b144173e00042e2dfd0c
63,782
import os def resize_factor(img, factors, interpolation="auto"): """Resize input image to a new size using resize factors along x and y axes. Inputs: img = RGB or grayscale image data factors = Resizing factors (width, height). E.g. (0.5, 0.5) interpolation = Interpolation method ...
b4b507c9de23f209d542ce8bc9a141839a06ee17
63,783
import pickle import math def fitting_shape_coefficients(filename, bounds='Default', n=5, return_data=False, return_error=False, optimize_deltaz=False, solver='gradient', deltaz=None, objective='hausdorf', ...
d62d4186d3892af622eae1edbe5b64572197d6ae
63,784
def find_executable(executable): """Return the full path to an executable searching PATH.""" for path in _find_executables(executable): return path return None
7beca9f748fe22b0dfb982cb880e6ad858b37faf
63,785
def uniformCostSearch(problem): """Search the node of least total cost first.""" nv = [] # Initialize empty array for visited nodes s = util.PriorityQueue() # Initialize priority queue for fringe s.push((problem.getStartState(), ()),...
c4769a250d618eae055d39b0fe390793f86eca36
63,786
def format_with_bold(s_format, data=None): """ Returns the string with all placeholders preceeded by '_b' replaced with a bold indicator value; :param: s_format: a string format; if contains '_b{}b_' this term gets bolded. :param: s: a string or value Note 1: '... _b{}; s...
07fd31eaeb5cfd4a39d256e3c2d48fe3a97a9564
63,787
def measure_spike_trains_correlation_coefficient_multi(spike_train_dict, std_val=5.0, sample_period=0.01): """ :param spike_train_dict: dictionary where every key is the name of a cell and every value is a numpy array with the spike times in msec :param std_val: standard deviation used to create th...
40d9b00f240191ec587c6888928aaa2f783feee0
63,788
def readData(input_file): """ Read data from an input file. Each line of the file contains tuples of the form (x,y) x is a dictionary of the form: { "feature1": value, "feature2":value, ...} and y is a binary value +1 or -1. The retu...
73647a64259e6f1a3c5535e51f44b48fc8054ef7
63,789
from typing import Dict from typing import Any from typing import Union from typing import List import csv def load_dataclass_dict_from_csv( input_csv_file_path: str, dataclass_class: type, dict_key_field: str, list_per_key: bool = False, ) -> Dict[Any, Union[Any, List[Any]]]: """ Args: ...
fb6b39b60fd15b430d4f39f07110c4f0da299ab6
63,790
def is_part_of_word(word_fragment, wordlist): """Returns True if word_fragment is the beginning of a word in wordlist. Returns False otherwise. Assumes word_fragment is a string.""" for word in wordlist: is_part_of_list = word_fragment == word[:len(word_fragment)] if is_part_of_list == True:...
54f572655fe7bb383cb00d732b57d85156b5f528
63,791
import re def plot_scatter(dfc, dfm, object_level_directory, object_level_files, filename='scatter.pdf'): """Plots BrdU and pH3 scatter and applies gating based on average gating of control wells Parameters ---------- dfc : pandas dataframe table containing well level...
26d3a608b283ac9cd20668cc40b72e3d1b4fb230
63,792
def render_output(data): """Print the formatted output for the list """ output = ['[Dataduct]: '] output.extend(data) return '\n'.join(output)
5e3bee31890f682eca6aa03128dbf8d51e2fe473
63,793
import os import subprocess import sys import re def getSectionInfo(binaryPath, filterSections=None): """This function takes a path to an ELF binary as parameter, executes readelf on it, parsing the output, building then returning a list of sections objects filterSections is a list of sections to consider (i.e. t...
095605811e619c32a75417819407a1b5dc9d84b0
63,794
import torch def processGroundTruth(bounding_box, input_shape, cell_map_shape): """Normalizes and computes the offset to the grid corner""" # Construct normalized, relative ground truth cell_corners = getGrid(input_shape, cell_map_shape) cell_shape = input_shape / cell_map_shape # bounding_box[0, ...
8107a0337c36b3b3e360407ded9d782b0b5cd37e
63,795
from typing import List def simplify_linear_inequalites(iset: List[Rel]): """ :param iset: linear inequalities set to be simplified ( redaundent inequalities would be removed). :return: simplified set of inequalities. >>> eq1 = x + y >= 10 >>> eq2 = x + y >= 20 >>> eq3 = x + y <= 30 >>...
65a35a1921eb12c982a6d1b52843fb0a6fbcdbbc
63,796
import json def loads(string, **kwargs): """ reconstruct configuration object from json string """ dict_from = json.loads(string, **kwargs) return _decode(dict_from)
b6db399002af5db59c8a00338d222ffd699eb189
63,797
import urllib def remote_follow(request): """direct user to follow from remote account using ostatus subscribe protocol""" remote_user = request.POST.get("remote_user") try: if remote_user[0] == "@": remote_user = remote_user[1:] remote_domain = remote_user.split("@")[1] ex...
e49abe36f6a2da6e3b5f2378c187decc31a7304b
63,798
def create_shift_permission(employee_id: str = None, permission_type: str = None, date: str = None, reason: str = None, leaving_time: str = None, arrival_time: str = None) -> dict: """This method creates a shift permission for a given employee. Args: employee (str): employee id permission_type ...
3e359e404847638f1d2e718588e0ad5543ad658a
63,799