content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def feature_importance_mad(clf, alpha=0.05, ignored_percentile=None): """This function fetches the feature importance values and runs a criteria using the median absolute deviation. If a feature importance difference to the median importance is greater t...
fc803527cb1be8eefd7ea62be916aa00b0be637f
65,500
import math def parse_sizes(raw: dict) -> dict: """Pass.""" parsed = {} parsed["disk_free_mb"] = math.floor(raw["disk_free"] / 1024 / 1024) parsed["disk_used_mb"] = math.ceil(raw["disk_used"] / 1024 / 1024) parsed["historical_sizes_devices"] = raw["entity_sizes"].get("Devices", {}) parsed["his...
491169f74ff6393da33b3c436e2aba2a87c26a1f
65,501
def associated_polynomials(cos_theta, sin_theta, max_n, max_m, k=None): """ Specific legendre legrende_polynomials for application in geomagnetic calculation Recursion Constants (k) can be pre-calculated to improve performance, otherwise the function will perform this for you """ if k is None: ...
810bca7f858138864a02d4d3f98ed2ed306788ec
65,502
def cov(x, y, pi): """Covariance of two discretized random variables with supports x and y common probability mass function pi.""" return np.sum(pi * (x - mean(x, pi)) * (y - mean(y, pi)))
0fc31e652f59253aa168d38dc016075fef6d8a13
65,503
def color_validator(input_str): """ A filter allowing only the particular colors used by the Google Calendar API Raises ValidationError otherwise. """ try: assert input_str in VALID_OVERRIDE_COLORS + [''] return input_str except AssertionError: raise ValidationError(...
e5e5c6c3818e1b33cec4b8327bdedc729353f846
65,504
def getError(cur_pose, prev_pose, cur_gt, prev_gt): """ Computes the error of the transformation between 2 poses """ error_t = np.linalg.norm((prev_pose[:3, -1] - cur_pose[:3,-1]) - (cur_gt[:3,-1] - prev_gt[:3,-1])) gt_prev_qt = quaternion.from_rotation_matrix(prev_gt[:3, :3]) gt_qt = quaternion.from_rot...
83cdc05b8f9a81223742e403d7b9da752a102a74
65,505
def Oxygen(): """Create a `PureFluid` object using the equation of state for oxygen.""" return PureFluid('liquidvapor.xml','oxygen')
d641b7e6247192795063120dfeaf837f32848888
65,506
from typing import List from typing import Tuple from typing import Iterator import itertools def find_best_worst_lists(sequence_of_lists: List[SpreadingRatio]) -> BestAndWorstLists: """ This function finds the "best" and "worst" lists from a set of lists. See explanation below. :param sequence_of_lists: ...
0840b9ec6105c97244d4ef38217e0ed6bdd59d78
65,507
def computeSumAbsPerPolarity(jz, jz_err, bz, bz_err, conf_disambig, bitmap, nx, ny, rsun_ref, rsun_obs, cdelt1_arcsec, munaught): """function: computeSumAbsPerPolarity This function computes the sum of the absolute value of the current per polarity. It is defined as follows: The sum of the absolute value...
dee89697cce2a98eb240840c2b1d6f4a1f1dbb80
65,508
def clang_describe_function(func): """Describe the function at the given clang AST node.""" assert func.kind == CursorKind.FUNCTION_DECL sig, defaults = clang_describe_args(func) signatures = {sig: {'return': clang_describe_type(func.result_type, func.location), 'defaults': defau...
3f18952f562af7b9d14c76cff90dde28bfad17a9
65,509
import hashlib def password_hash(password, password_salt=None): """Hashes a specified password""" password_salt = password_salt or oz.settings["session_salt"] salted_password = password_salt + password return "sha256!%s" % hashlib.sha256(salted_password.encode("utf-8")).hexdigest()
9cde58047239e0c770f14b5c803b529dacb651de
65,510
def allowed_file(filename): """Determine if a file has an allowed extension.""" return '.' in filename and \ filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']
7a1093a53a7a7a049a95d1018ab83e3b32dd3c37
65,511
import re import sys def parse_header(header): """ Parses the header to get the link to the next page of issues, checks this isn't the last page. Args: header (str): header as string. Returns: tuple/str: link to the next page and last page to parse or just the next pag...
dd63dfbbc8afcffee918258cbf539c5a0e205ba4
65,512
def affine_jac_obs_element(prep, error, observable): """ Computes the Jacobian matrix element for a Affine error: how the expectation value of `observable` changes with respect to the rate of `error` when preparing state `prep`. Note: Affine error maps leave qubits corresponging to I's in `erro...
3c07be3eb88dbc93c303949370e4baa1628aaf37
65,513
def encode_genotype(nucleotides): """Parses a string representing a set of nucleotides observed at a loci, and returns the corresponding IUPAC code. Commas are allowed, but are simply ignored if found in the string. Does not handle lower-case nucleotides, due to lack of clear criteria for mixed case inp...
3236a3d3ac858d6f10c7a38e82b91c44893928b8
65,514
from typing import Tuple def spatial_transformation(inputs: tf.Tensor, theta: tf.Tensor, output_size: Tuple[int, int] = None ) -> tf.Tensor: """Transform input images according to theta. If `output_size` is provided, also rescales im...
fc02cf4e8afb1d93d4893405b206cb5493a7cfe7
65,515
def _create_dummy_archive(hs): """Create empty archive so that GHC has some input files to work on during linking. See: https://github.com/facebook/buck/blob/126d576d5c07ce382e447533b57794ae1a358cc2/src/com/facebook/buck/haskell/HaskellDescriptionUtils.java#L295 Args: hs: Haskell context. Returns: ...
a686398fc621050400895a2d541f0c41ba65ee98
65,516
import torch def load_robust_model(model_name, device): """loads robust model specified by modelname""" model = models.resnet50(pretrained=True) model_paths = { 'ANT+SIN': './Models/ANT_SIN_Model.pth', 'ANT': './Models/ANT_Model.pth', 'Speckle': './Models/Speckle_Model.pth', ...
3971c0236bdbb09e7258d3f6895779453f38fc78
65,517
def render_html_from_fields(fields, template_url): """Returns html rendering of timeline item with custom fields data.""" template = jinja_environment.get_template(template_url) return template.render(fields)
eff3a5c33a961c3b2ea939b877de4bdf7a00a3f5
65,518
from typing import Optional def greater_sum_bst(root_node: Node) -> Node: """ time complexity: O(n) space complexity: O(n) """ def construct(node: Optional[Node]) -> Optional[Node]: """ Reverse inorder traversal """ nonlocal total if node: const...
d4a4039397f5f41a9723ca7d51e0665d91dcb2dc
65,519
def flatten_df(df): """Flatten the df to an array Args: df(pd.DataFrame): a dataframe Returns: an array """ return df.values.flatten()
4faedf1059fa60c2ee3af95cd6f01e7d3cadd97e
65,520
from typing import List from typing import Dict from typing import OrderedDict def build_bluff_data_year_month_dict(database_connection: mysql.connector.connect ) -> List[Dict]: """Returns an OrderedDict that will be used to populate Bluff the Listener data for all years an...
9fa6131ff57f8ea29fd628a31e7de2c267e0d1ea
65,521
def aes_ecb(key: bytes, b: bytes, decrypt: bool=False) -> bytes: """AES ECB mode. :param key: The cipher key. :param b: The buffer to be encrypted/decrypted. :param decrypt: Whether we should encrypt or decrypt. :returns: The encrypted/decrypted buffer. """ assert len(b) % 16 == 0 asse...
6ca780353ceec49149fffcaa286b4654f2ee243f
65,522
import random def get_random_num(number): """ xxx """ maxnum = int(number) return random.randint(1, maxnum)
9ad5a62ed510f4153b91f2a5c982ef83373dfca3
65,523
def get_auc(labels, preds, n_bins=10000): """ROC_AUC""" postive_len = sum(labels) negative_len = len(labels) - postive_len total_case = postive_len * negative_len if total_case == 0: return 0 pos_histogram = [0 for _ in range(n_bins+1)] neg_histogram = [0 for _ in range(n_bins+1)] ...
4a216bb6b6ce8a992163fe92c2fb3b8642995dfb
65,524
def fastdance(progs, compiled_moves): """Dance faster using parsed moves.""" for (func, args) in compiled_moves: progs = func(progs, *args) return progs
a3d0f68b3a75c79cc489d17aa8eefaf64a351d2b
65,525
from typing import Counter def duplicated(v): """Returns a generator expression of values within v that appear more than once """ return (x for x, y in Counter(v).items() if y > 1)
bf854dfde83c9d998f3f0b5f5553254be6347a4c
65,526
def _readonly_array_copy(x): """Return a copy of x with flag writeable set to False.""" y = x.copy() y.flags["WRITEABLE"] = False return y
ffd973bb354a642362a7382934f879c9dfa95c3b
65,527
def filter_in(values, vmin=None, vmax=None): """ Handles 'in' filters op: ['in', 'not in'] values: iterable of values vmin, vmax: the range to compare within Returns ------- True or False """ if len(values) == 0: return True if vmax == vmin and vmax is not None and ...
e64a5f05216786c618c616e61c562ca1aad78b59
65,528
from typing import Dict import os import yaml def get_config(path: str = os.getcwd()) -> Dict: """Search for settings file in root of project and its parents.""" config = default tries = 0 current_dir = path while current_dir and tries < MAX_CONFIG_SEARCH_DEPTH: potential_path = os.path.jo...
862b6f33c1d6f8309963e5aea95c070b06bbff37
65,529
def _variable_to_parameter(param_list, variable=None, variable_name=""): """ Takes either a Variable object or a the name of a Variable object and returns the corresponding Parameter object. If variable is specified, and it has a value, the parameter's expr is accordingly specified. Args: p...
b720dbcdf6e436f306d4cb0ecc87e810dd569e49
65,530
def control_module_location(form_data): """ """ # TODO : create a function with not set and not valid error errors_dict = get_errors() if not key_in_dict_not_empty('location', form_data): return errors_dict['SustainableLocationNotSet'] location = format_module_location(form_data) ...
dc4382b381b56443b310c07dea0936d4f11855ae
65,531
def parse_na(txt: str) -> (MetarData, Units): # type: ignore """ Parser for the North American METAR variant """ units = Units(**NA_UNITS) # type: ignore clean = core.sanitize_report_string(txt) wxresp = {'raw': txt, 'sanitized': clean} wxdata, wxresp['remarks'] = core.get_remarks(clean) ...
7cad2889d5ddf82368c799c0e9c0cacae30fed23
65,532
import re def str_list_to_list_str(str_list, regex_pattern='[A-Z]\d+'): """ Turn a string of a list into a list of string tokens. Tokens determined by regex_pattern """ p = re.compile(regex_pattern) return p.findall(str_list)
99d3bbccadc0676dac6854ee717f8aef3bb878a6
65,533
import re def parse_readme_unicode_version(readme_content): # type: (str) -> UnicodeVersion """ Parse the Unicode version contained in their `ReadMe.txt` file. """ # "Raw string" is necessary for \d not being treated as escape char # (for the sake of compat with future Python versions). # ...
cae4710a6e8d3ec82dc9398509bdd09f3aeccc8c
65,534
import inspect import logging import functools def _instantiable_base_dists(): """Computes the table of mechanically instantiable base Distributions. A Distribution is mechanically instantiable if - The class appears as a symbol binding in `tfp.distributions`; - The class defines a `_params_event_ndims` met...
1f37f8aafbd079a1a071ec6d2db931f1723a1c14
65,535
def ask(string, **default): """Ask the user a question providing the option to choose "yes", "no", or "cancel". If any of the options are specified as a boolean, then it is assumed that this option will be the default. If the user chooses "cancel", then this value will be returned instead of the va...
a54118950dc893601087db99a72e973e3b263a58
65,536
import os import requests import json def stock_time(symbol, shares): """ Shows the past 20 closing prices with their days """ api_key= os.environ.get("ALPHAVANTAGE_API_KEY") #using the .env variable request_url= f"https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol={symbol}&apikey...
c1ca8eb0aa4a294abd91ffc2c46fc6566d583719
65,537
def samWald(mean=3, scale=2, size=None): # real signature unknown; restored from __doc__ """wald(mean, scale, size=None) Draw samples from a Wald, or inverse Gaussian, distribution. As the scale approaches infinity, the distribution becomes more like a Gaussian. Some references claim that the Wald is...
8900946e11b78201cbd836a026f5bc5bd66fc63a
65,538
from typing import List def get_trace_events(trace_directory: str) -> List[DictEvent]: """ Get the events of a trace. :param trace_directory: the path to the main/top trace directory :return: events """ events: List[DictEvent] = [ _event_to_dict(event) for event in _get_trace_ctf_even...
7e2d9037ac0653fba2d7884dbc3a0b367047c603
65,539
def zero_pad(x, n): """ Pad an array to length `n` with zeros. If the original array length is greater than `n`, a copy of the original array is returned with it's length unchanged. """ nx = len(x) if n < nx: n = nx new = np.zeros((n, *x.shape[1:]), dtype = x.dtype) new[:nx] ...
961b436be4b13fa21099ad4c99d91ec02da071dd
65,540
from typing import Iterator import tqdm def get_statistics(samples: Iterator): """ Input: samples: [{ "text": "summary": }] Output:dict: usage: you can test it with following code: from datalabs import load_dataset from aggregate.summariz...
ba653de272c8207ec7ebc4afd43cdcb659653054
65,541
import os def TemporaryNamedFile(temppath, mode='wb', delete=True, buffer_size=-1): """ Variation on ``tempfile.NamedTemporaryFile(…)``, for use within `clu.fs.filesystem.TemporaryName()` – q.v. class definition sub. Parame...
95123f6cd44401d4dab571c4e4d41809a0f7ca39
65,542
def get_field_names(vector_path, field_id): """Return set of all field names found with vector_path and field_id.""" vector = gdal.OpenEx(vector_path, gdal.OF_VECTOR) layer = vector.GetLayer() field_name_set = set() for feature in layer: LOGGER.debug(f'{vector_path} {field_id}') fiel...
591316a62c2a3a746a4cd8fcc7dd541c89de3695
65,543
def isin(collection) -> InUnit: """ Overview: Containment check, the same as ``in_(keep(), collection)``. :param collection: Collection to be checked. :return: Unit for checking containment. Examples:: >>> from argsloader.units import isin, add, mul >>> u = add.by(2) >> mul...
82f1d3a14b6ed691b3fc9e214195b2521c1e2564
65,544
import logging def make_logger(name, level, handler, format=None, logfile=None): """ get the given logger and configure it with handler, and format loglevels: ------------------------------ Level Numeric value CRITICAL 50 ERROR 40 ...
e14630647ab2960db53835b154bfcd82928c63f3
65,545
def delete_user_id(activation_id, user_id): """ makes request to -> /api/v4/activations/{activation_id}/ users/{user_id} Revoke access of a user from activation Parameters ---------- activation_id : int, required unique id of activation/system user_id : int, required ...
8dcce8a3fd52958d446df504eebac41a0e9ca5a4
65,546
def intrinsic_char(args): """Return the UTF-8 character value for the ordinal number or numbers given in the argument list.""" return MUMPSExpression( lambda a=args: _char(a) )
ae2a3c622908fa73d1df400680e5cc0bb1728df7
65,547
import os def check_file(filename, expected_bytes): """Download a file if not present, and make sure it's the right size.""" if not os.path.exists(filename): print("please make sure {0} exists in the current directory".format(filename)) statinfo = os.stat(filename) if statinfo.st_size == expec...
2db9e5378182feed7b4c692184a0eadc84c4e9cc
65,548
import yaml def get_configuration(config: str) -> dict: """ Open Config YAML file """ with open(config) as f: configuration = yaml.load(f, Loader=yaml.FullLoader) return configuration
c275b80363bca4a8587b7f09ead17a85f9b8dfda
65,549
import json def get_slsr(account_id=None, slr_id=None, slsr_id=None, cursor=None): """ Get one slsr entry from database by Account ID and ID :param slr_id: :param slsr_id: :return: dict """ if account_id is None: raise AttributeError("Provide account_id as parameter") if slr_id...
4da184d7a49956dcb7b991c65fe9499024140851
65,550
def flagger(value): """ Conversion routine for flags. Accepts ints or comma-separated strings. :param str value: The value to convert. :returns: A value of an appropriate type. """ try: # Convert as an integer return int(value) except ValueError: # Convert as ...
cdc3fab338fd7f25499e25593302fb209f9be2a4
65,551
import progressbar def compare_methods(im1,im2, ntests=100, noise=np.std, usfac=201, **kwargs): """ Perform tests with noise added to determine the errors on the 'best-fit' offset Parameters ---------- usfac : int upsampling factor; governs accuracy of fit (1/usfac is best acc...
1606ed610827968f862681df5c0aad60715faa06
65,552
def method_comparison_boxplot(*, title="Accuracy of models created with each method\n", data, # pd.DataFrame with the results, figsize=(10,4), # ... col_with_results, # df colname with values to display, eg: test_accuracy ... col_with_group_names, # df colname with values t...
9dc6d10487f202b8eeb284e0120fa2f6970db847
65,553
def is_present(input: Input) -> bool: """Returns true if the stream for this input is indeed found. If we can't probe this input type, assume it is present.""" return bool(_probe(input, 'stream=index') or input.input_type in TYPES_WE_CANT_PROBE)
90e470dbf5088d19cbb93a5218bbcc6ccc478bdb
65,554
def get_accuracy(testSet, predictions): """Calculate accuracy.""" correct = 0 for x in range(len(testSet)): if testSet[x][-1] in predictions[x]: correct = correct + 1 return correct / float(len(testSet)) * 100
afb8b781fff25373c764d49457422fd3d676019d
65,555
def extract_positive_gfc(c: np.ndarray) -> np.ndarray: """ Extract global functional connectivity from connectivity matrix. The GFC is compute as the mean FC of each time series with all the others. Args: c: 2-dimensional numpy array where each entry is the correlation ...
18acdb5a4d5c801ac4aa2b8704ac615dab003eed
65,556
import time def time_func(func, kwargs): """ Time a function. Return the time it took to finish and subsequent result. """ start = time.time() res = func(**kwargs) finish = time.time() - start return finish, res
78f73058a90048f8de24915f1f8ba56bda79cc6a
65,557
def remove_common_path(path1, path2): """ Removes path that is common in both given paths :param path1: str :param path2: str :return: str, path without the path shared by both given paths """ path1 = clean_path(path1) path2 = clean_path(path2) split_path1 = path1.split('/') sp...
d61c0069c7ed2bf47215a13510d6b2df8263dc7a
65,558
def verify_election_partial_key_challenge( verifier_id: GUARDIAN_ID, challenge: ElectionPartialKeyChallenge ) -> ElectionPartialKeyVerification: """ Verify a challenge to a previous verification of a partial key backup :param verifier_id: Verifier of the challenge :param challenge: Election partial ...
a33c4c1c43122f99d0fd6d4baa65bbc4708dfe0e
65,559
def number_days(year,month,day): """ return the number of days between the date and 0 BC """ monthdays = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334] return year * 365 + monthdays[month-1] + day
8858d8d19b50970aff4b831e62f4335e29722877
65,560
def evaluation(logits, labels): """Evaluate the quality of the logits at predicting the label. Args: logits: Logits tensor, float - [batch_size, NUM_CLASSES]. labels: Labels tensor, int32 - [batch_size], with values in the range [0, NUM_CLASSES). Returns: A scalar int32 tensor with the number of...
7aa6d71ce4d3d222fa0df47e6611dd0e5d222716
65,561
def delete_gif_route(gif_id: int): """DELETE /gifs/<gif_id> Deletes a gif with specified gif id. Token's "sub" must match owner's username of the gif, unless an admin. Args: gif_id (:obj:`int`): The gif id to modify. """ gif = Gif.get_by_id(gif_id) if not gif: return {"erro...
39885946dc34fa6d85b3d03b7fa061ebbbb312d9
65,562
from typing import Tuple def _run_ilp(dataset: str, name: str) -> Tuple[int, float, str]: """Run ILP on all datasets. Parameters ---------- dataset : str Dataset name. name : str FCL name. Returns ------- Tuple[int, float, str] Solution size, time, and certifi...
76b957b762a3661efcb9ac17903d5a05a081edde
65,563
def obtain_combined_clusters(data_a, data_b, label_a = 'Sim A', label_b = 'Sim B', start_frame = 0, algorithm='kmeans', num_clusters=2, min_dist=12, max_iter=100, plot=True, saveas=None): """ Clusters a combination of two data sets. Parameters ...
aabd3fe236927a7a64097c17a49725649816cd76
65,564
def dRELU(x): """if x <= 0: return 0 else: return 1""" #return x * (1 - x) return 1
ade7095133b44f61c3ce6350abdf5b2251e2c6fb
65,565
import torch def flatten_tensors(tensors): """ Flatten dense tensors into a contiguous 1D buffer. Assume tensors are of same dense type. Since inputs are dense, the resulting tensor will be a concatenated 1D buffer. Element-wise operation on this buffer will be equivalent to operating individu...
27ecbb26cf3bb084a0216248f2314519fb735bde
65,566
def calib_constants(det, exp=None, ctype='pedestals', run=None, time_sec=None, vers=None, **kwa) : """Returns calibration constants for specified parameters. To get meaningful constants, at least a few parameters must be specified, e.g.: - det, ctype, time_sec - det, ctype, version - de...
b4cc0ccf2087ea343c10da1da0752df439555cb0
65,567
def gen_end(first_instruction_address): """ Generate an end record. """ # specify the size of each column col2_size = 6 # content for each column col1 = "E" col2 = hex(first_instruction_address)[2:].zfill(col2_size).upper() return col1 + col2
d5df69b33cfb4f99aa9dbc5e003b713637fa1eff
65,568
def zScale(df): """ x= np.linspace(0,50) y, z= np.linspace(0, 50, 50, False, True) T= np.linspace(0, 200, 50, False) b= np.arange(0, 200, 200/50) #same as T 200/50 - gives the increment to create same array as T - 1 to 200, with 50 elements print(b) b.size df = pd.Dat...
f9261d3b7089496068562b8085df5bbfad94e68b
65,569
def interval(f, a, b, *args, **kwargs): """ Return a correct interval to use the brentq method. *args are additionnal parameters used by the function. **kwargs are parameters for this particular function ( #TODO : add different way to define the new interval, either by hand or automatic) Brentq method work...
609647412c975838f3c22e68252a1103f0f1e3a9
65,570
def fit_func_tree(infix,vals): """Passing infix string to posfix notation""" stack = [] stackSize = 0 buff = [] n_vals = len(vals) for ch in infix: if is_operand(ch): if (not stack) or (level_ops[ch] > level_ops[stack[stackSize-1]]): stack.append(ch) stackSize += 1 else: ...
29b1e34a0a1d6757d523805a8025e5c6d48ef21c
65,571
def dashboard(): """Admin dashboard route.""" return render_template('dashboard.html', title='Flask-Blueprint Tutorial | Admin Dashboard', template='dashboard-template account', body="Account")
e90c9f8f7745ac470bec1c798d2183412e340ed9
65,572
def is_equal_2_refactorings_list(a, b): """ This method implement is_equal method which should return True if two instances of Individual class are equal. Otherwise it return False. The duplicate instances are removed from population at each generation. Only one instance is held to speed up the sear...
155248bb60ac560af03edd533d4573c9a5801b78
65,573
import re def split(combined_unit): """ Splits a unit string into magnitude prefix, the base unit, and the power. :param combined_unit: The unit string. :returns: A tuple of prefix, base unit, and power. :rtype: tuple """ prefix_re = "(?P<prefix>{})".format(PREFIXES) unit_re = "(?P<u...
975d9ad2f05583839bad2a3f7dfa0848de83a0fe
65,574
import tqdm def sample_magnetization_average(graph, T, Glauber_Runs , beta,positions=None , T_Burn=0, Initial_State=None,control_field=None) : """ Average magnetization at the end of the chain for a specified number of Glauber runs. For each glauber run we take the average magnetization for the period after ...
e9eeb5a5d929abae44e0e6928cd9d197463829cb
65,575
from typing import Dict from typing import Any def nom_comps( srs: dd.Series, first_rows: pd.Series, ngroups: int, largest: bool, bins: int, top_words: int, stopword: bool, lemmatize: bool, stem: bool, ) -> Dict[str, Any]: """ This function aggregates all of the computation...
1ae2ef8a3f7105518b170419cf413f9c28b35676
65,576
import re def filter_subject(subj, cfg): """Function: filter_subject Description: Filter out strings from the message subject line. Arguments: (input) subj -> Message subject line. (input) cfg -> Configuration settings module for the program. (output) subj -> Filtered message ...
db3e2dcff95ef91b0190e4a3c9a0c9c72113403a
65,577
def name_fmt(name, fmt=NameFormat(0)): """Format name for output. Parameters ---------- name : `ged4py.model.Name` Person name. fmt : `NameFormat`, optional Bitmask combination of `NameFormat` flags. Returns ------- name : `str` Formatted name representation. ...
0d2173c62a36c3fe35e8946dc9ac115b0a342a57
65,578
def filter_remove_background(rgb, red_lower_thresh=235, green_lower_thresh=210, blue_lower_thresh=235, output_type="bool"): """ Create a mask to filter out pixels which are pre-defined as background Args: np_img: RGB image as a NumPy array. red_lower_thresh: Red channel lower threshold value...
0320af3ce1a20501e772a2feec4a4268b5a6d059
65,579
def batch_ispecgram(spec, n_fft=512, hop_length=None, mask=True, log_mag=True, re_im=False, dphase=True, mag_only=False, num_iters=1000): """Computes inverse ...
8e6219385ab9d09743e19501c0f3c642ed02138a
65,580
def makeTable(lid,es,TOTAL,TDIR,FDIR,tag,offset=0): """Overall textual analysis with rendering of tables""" #TDIR="/home/r/repos/artigoTextoNasRedes/tables/" #TDIRf="/home/r/repos/artigoTextoNasRedes/figs/" ds=es.structs[1] timest=es.structs[2] pr=es.structs[-1] nm=es.structs[4] B.LANG=[...
a6024aa699376e576552cfc1fd377f57464be7d0
65,581
def topography_dam(x,y): """Complex topography defined by a function of vectors x and y.""" z = -x/100 N = len(x) for i in range(N): # Step if 2 < x[i] < 4: z[i] += 0.4 - 0.05*y[i] # Permanent pole if (x[i] - 8)**2 + (y[i] - 2)**2 < 0.4**2: z[i]...
1ac128fe8ab0852ca42df9e54168617f47a79bee
65,582
import math def extraterrestrial_irrad(utc_datetime, latitude_deg, longitude_deg, SC=SC_default): """Equation calculates Extratrestrial radiation. Solar radiation incident outside the earth's atmosphere is called extraterrestrial radiation. On average the extraterrestrial irradiance is 1367 Watts/meter2 (...
1f872404b6e3f289a90c05ac8e985c1a37f8512a
65,583
from datetime import datetime import os def product_filename(model=None, product=None, level=None, obs_time=None, init_time=None, fhour=None, valid_time=None, statistic=None, place=None, suffix=None, root_dir=None): """ Construct standard product file name, all parame...
a4d20a08bfc275dc3f5fa84b4d756e319ab91d34
65,584
def get_json(item): """nasty hack to get round requests api change""" if callable(item): return item() else: return item
13b549063503fc1bf8857a23af38d905735c901e
65,585
def variantMetadata_object(processed_request): """ Builds the variantAnnotation object. Since we only have one model for this object we keep it simple. """ beacon_variant_metadata_v1_0 = { "default": { "version": "beacon-variant-metadata-v1.0", ...
4bf6dc519fcca02ea63d0f94af55adffe29ad9f8
65,586
import requests def get_file_from_net(url): """ Gets any file from the net and prints it if possible (i.e if Content-Type is text. :param url: Address of resource to be read :return: Text of possible, otherwise throw exception. """ try: response = requests.get(url) if 200 <= ...
47aa4d3ca8a439c4bbbe90da654193d40ad1a6b5
65,587
def _is_filtering_only_by_id(options): """ Funcao que checa se a query tem como unico filtro o ID de uma entidade. Args: options (str): As opções da query. Returns: (bool): Verdadeiro, se o unico filtro é na propriedade ID. False, do contrário. """ if "$select" in options: ...
984074de92f3dc2fd9b300cdaf7f500c77e96269
65,588
import argparse def arg_parser(): """Defines parser for command line input.""" parser = argparse.ArgumentParser(prog=PROG, description="Command line wrapper to interact with governing contract.") parser.add_argument("--ipc", help="Path to 'geth.ipc'.", default=RPC_IPC, metavar="path/to/ipc", type=str) ...
b0d9746e2d8cbd412c8a479f5406da0cfa42849a
65,589
def BetaBinomial(data, name, shape=1, ranges=(1, np.inf)): """ Constructs a BetaBinomial distributions with RV = X ~ BetaBinomial(n, a, ß) Returns: Tuple[Pymc3.distributions.BetaBinomial, Tuple[String, int, float, float]] ---------- - Returns a tuple with distributions paired with the [name, nu...
de04b84244fbd67377242d549bb668ca46d39fc8
65,590
def to_unicode_repr( _letters ): """ helpful in situations where browser/app may recognize Unicode encoding in the \u0b8e type syntax but not actual unicode glyph/code-point""" return repr(_letters)
379331356ea4f4b3763a16c3d0e531e984ec7a85
65,591
def getExperimentalDataPaths(): """ getExperimentalDataPaths() """ print("------------------------------------------------------------") print("PLEASE ENTER PATHS OF EXPERIMENTAL DATA") print("") print("IF THERE ARE MULTIPLE DATA FILE YOU WANT TO TOMOGRAPHY,") print("ENTER ALL PATHS SE...
f9a63ca89de6c636fc8d6d7499c9eaf9933c9b4c
65,592
import torch def load_pytorch_weights_and_quant(path, config): """ Load the weights from the pytorch checkpoint """ state_dict = torch.load(path, map_location='cpu')["model"] tensor_dict = {onnx_to_trt_name(name):val.numpy() for name, val in state_dict.items()} return get_onnx_weight_dict(tens...
ef7defde0c20eccdc37bf0b13259257f6da26707
65,593
import uuid def correct_captcha(sub): """When a correct control challenge is submitted, the unknown map tile result is recorded""" print("correct captcha") tile = CaptchaTilesTable() tile.year = sub['year'] tile.x_coord = sub['x'] tile.y_coord = sub['y'] tile.uuid = uuid.uuid4().hex t...
1763e866a4a22713b48f0028e090dfcf5e9f3e13
65,594
def find_closest_stores(friends, stores): """ Finds the closest store to each friend based on absolute distance from the store. Parameters: friends: Dictionary with friend names as keys and point location as values. stores: Dictionary with store names as keys and point l...
ca879f6f442a4d734bf9e3c7b0313cd31ea2a026
65,595
def sum_nth_i(seq, n): """ takes a list seq and a number n that is bigger then 0 and takes the sum of the n number """ if n > 0: res = 0 for i in range(n-1, len(seq), n): print(i) res += seq[i] return res else: print("n needs to be bigger then 0 \n...
3ee7eec74b73449038d735355f29b3b57c9402b5
65,596
def levenshtein(s1, s2): """ Given two strings s1 and s2, returns the levenshtein distance between the two strings. Credit: http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance """ if len(s1) < len(s2): return levenshtein(s2, s1) # len(s1) >= len(s2) if len(s2) == 0:...
9fa02d9c0bc43291e8de44ff9101e4afbbef49a5
65,597
def prepare_removepoints_log(mod, target_member, case): """Prepares log for point removal Parameters ---------- mod : discord.Member "Mod who removed the points" target_member : discord.Member "Member whose points were removed" case "Case object" """ ...
31d576acc4349c049dffad99acd6ccf6fcb77c00
65,598
def solve_market_side_with_exogenous_price( bids, price, fees): """ Clears the market based on an external price. First it removes all biders that are not willing to trade at the given price, and then it fits the best allocation. Fees are calculated based on users that were willing b...
408a9e2f1362fa11eb4e85394600aafcf4223936
65,599