content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from multi_mesh.components.plotter import create_projection
def find_good_projection(
name: str = "default",
central_longitude: float = 0.0,
central_latitude: float = 0.0,
satellite_height: float = 10000000.0,
lat_extent=(-90.0, 90.0),
lon_extent=(-180.0, 180.0),
):
"""
Function which ... | 88b57ed8910d7dad5f0c2b2f641353def3f7bbc4 | 60,400 |
import torch
def vectorize(ex, model):
"""Torchify a single example."""
word_dict = model.word_dict
# Index words
word_idx = [word_dict[w] for w in ex['sent']]
if len(word_idx) == 0:
print(ex)
if model.args.model_type == 'cnn':
pad = max(model.args.kernel_sizes) - 1
w... | 7ec144048a4dd2cd61edab2b9c5de8697cbabc5b | 60,401 |
def edit_sub(request, proj='', srt1='', id1='', srt2='', id2=''):
"""Edit subitem - let op: theoretisch kan dit bij edit_item() in
"""
# try: # do we have form data?
data = request.POST
# except AttributeError:
# data = {}
obj1 = funcs.get_object(srt1, id1) # my.rectypes[srt1].objects.... | cae5ed830326f6ffd7ec83bcba549721da859a6e | 60,402 |
def main(output, effective_tld_filename):
"""
effective_tld_filename is the effective TLD file to parse.
A C++ array of { domain, exception, wild } entries representing the
eTLD file is then printed to output.
"""
def boolStr(b):
if b:
return "true"
return "false"
for etld in getEffectiveT... | 189449f07847d3121c46a5cf19795dba3f20bb98 | 60,403 |
def byte_convert_(number, original, new, printed=False):
"""Convert from one suffix to another suffix."""
if original == '':
if new == '':
None
elif new == 'kb':
number = number/1_000
elif new == 'mb':
number = number/1_000_000
elif new == 'gb'... | ca5a12308e13fc46dd9bd1de91a7cde8207749e1 | 60,404 |
def filter_none(data, split_by_client=False):
"""This function filters out ``None`` values from the given list (or list of lists, when ``split_by_client`` is enabled)."""
if split_by_client:
# filter out missing files and empty clients
existing_data = [
[d for d in client_data if d ... | 7cc88ecdf7aba245f56598ee1094fed7c1f9f4f7 | 60,405 |
from .main import main as main_blueprint
import logging
def create_app(options, config_name):
"""Create an application instance."""
app = Flask(__name__)
# import configuration
app.config.from_object(config[config_name])
config[config_name].init_app(app)
#cfg = os.path.join(app_dir,... | fb456f79ede6e9b30de9843992fc6fffad96d545 | 60,406 |
def cal_dist(weights, codes, keys_list=[-1, 0, 1]):
""" Compute Distribution of CODES and generate results for PyPlot
Args:
weights (list):
codes (list):
keys_list (list): optional
Returns:
dist_dict (dict): a list of weights for each key
"""
dist_dict = dict.fromke... | 52eb2bd39e0e403ecf130f486c34c51f7b71cd26 | 60,407 |
from typing import List
def get_default_privileges(type: PgObjectType, owner: str) -> List[Privileges]:
"""Return a list of :class:`~pg_grant.types.Privileges` objects matching the
default privileges for that type.
This can be called when the ACL item from PostgreSQL is NULL to determine
the implicit... | 45ce002ec896c60852fe7efa2e05f53d46911109 | 60,408 |
def plot_contours(clf, xx, yy, **params):
"""Plot the inverese-transformed decision boundaries for a classifier.
Parameters
----------
ax: matplotlib axes object
clf: a classifier
xx: meshgrid ndarray
yy: meshgrid ndarray
params: dictionary of params to pass to contourf, optional
""... | 615b453323a30b01bd7b3531c1915c201006e313 | 60,409 |
def test_funding_reorg_remote_lags(node_factory, bitcoind):
"""Nodes may disagree about short_channel_id before channel announcement
"""
# may_reconnect so channeld will restart; bad gossip can happen due to reorg
opts = {'funding-confirms': 1, 'may_reconnect': True, 'allow_bad_gossip': True}
l1, l2... | 5be31fc732cc2ec6fab59ca2586c93a9094dffd0 | 60,410 |
def print_num(n):
""" there must be a package that does this better. oh well"""
if n >= 1000000000:
return "{}{}".format(round(float(n) / 1000000000, 2), "B")
elif n >= 1000000:
return "{}{}".format(round(float(n) / 1000000, 2), "M")
elif n >= 1000:
return "{}{}".format(round... | 7a6e241a60d81515b03e29de595cd192afde7d9a | 60,411 |
def process_row(row):
"""Split a row into the original sentence, its corresponding summary and its rating.
Args:
row: a row in the MS dataset tsv file.
Returns:
current_original_sentence: the original sentence of the row
current_shortened_sentences_list: a list of summaries corresponding to... | bff7a139e34e150210da73928a1dce1c51cfa8c2 | 60,412 |
def update_system(system):
"""
:param system: Dictionary with all the information of the system
Dictionary system already has the indexes of the excited molecules
1. Looks for the neighbourhood of every centre.
2. Chooses a process for every exciton (KMC). This path variables include: dict(centre, p... | 1981423d878e1ba5490f4d68ebc2f57989e31d4a | 60,413 |
def relu(Z):
"""Applies relu function to an array/value
Arguments
---------
Z: float/int/array_like
Original Value
Returns
-------
A: same shape as input
Value after applying relu function
"""
return np.maximum(Z, 0) | 6319f41a73b61911c5c72051cd80f2832b679932 | 60,414 |
import inspect
def calculate_median(dataframe, *args, display=True, to_csv=False, to_html=False) -> DataFrame:
"""
This function calculates the median of all *numeric* columns within a Pandas dataframe. Alternately, users can
specify a list of columns for which they would want to calculate the median. If ... | abccfc2cafd8ae241031f78dba30d4dd53c75c87 | 60,415 |
def have_double_impl(math_name):
"""
Check whether we have an implementation of the math function in libc
for type double (e.g. logf or logl may not be available, but log may be).
"""
return math_suffix(math_name, double) in libc_math_funcs | 76bf591fbe64f4a04805bbd485ff85c91de5fd83 | 60,416 |
def translate_name(name):
"""
因为老数据的缘故,导致有些人名错了,需要翻译一下
:param name: 成员或组合名
:return:
"""
name_dict = {
'ruru_dambara': 'ruru_danbara',
'memi_tamura': 'meimi_tamura',
'chisaki_morito_m': 'chisaki_morito',
'musubu_funaki_a': 'musubu_funaki'
}
return name_dic... | 52b852e9ecd2b1ac4b02288198f2c84986a1ed17 | 60,417 |
import argparse
def parse_args():
""" Parse command line arguments """
parser = argparse.ArgumentParser(
description="This program outputs axt alignments for cases comparing "
"fastas for which the sequences of one file are completely and exactly "
" contained in another. For example, our need for this came ... | a48aadc18d3c28b308490446a121cc9b48128346 | 60,418 |
from typing import Union
from typing import Iterable
from datetime import datetime
def query_unexpired_records(*,
users: Union[User, Iterable[User]]=None,
types: Union[RecordType, Iterable[RecordType]]=None
):
"""
:param users... | 0c32b9a90e5f0f3b2892102db7484963cb2d4b0b | 60,419 |
def _pds_to_de(dict_values):
"""
takes all the pds fields values in dict (PDSxxxx) and creates list of DE strings
:param dict_values: dict containing "PDSxxxx" elements
:return: list of byte strings containing pds data, or None if no fields
"""
# get the PDS field keys in order
keys = sorte... | 15a014a54f80f0e819bd432801438f69a17f30ba | 60,420 |
from bs4 import BeautifulSoup
import re
import logging
def skip_team(soup: BeautifulSoup) -> bool:
"""Skip team if no players meet the minimum
:param soup: BeautifulSoup object for a team
:returns: True if the team should be skipped, False otherwise
"""
pattern = re.compile("No players meet the m... | 023a0a0076f8751f5447acd30e09ac239736e751 | 60,421 |
def _battin_second_equation(u, h1, h2):
"""Battin's second equation.
Parameters
----------
u: float
The dependent variable.
h1: float
The first of the h coefficients.
h2: float
The second of the h coefficients.
Returns
-------
y: float
The dependent ... | a00a6fe572b22cc4e27330667189325223d208fd | 60,422 |
import argparse
def get_arg_parser():
"""Routine for parsing the flags
Returns:
arg_parser: the argument parser
"""
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--savepath', default=DEFAULT_SAVE_PATH, help="specify where to save the processed data")
parser.add_arg... | 26c3d4e8fa0f4987ebea02378f20a65ac31ba99b | 60,423 |
def compute_pca(data2d):
"""
Compute PCA using sklearn
:param data2d: 2d array. PCA will be computed on non-zeros values.
:return: coordsrc: 2d array: centered non-zero coordinates\
pca: object: PCA result.\
centermass: 2x1 array: 2d coordinates of the center of mass
"""
# round... | 1bdbe46c4b709e1a72755ce1b9bfc630b52f886b | 60,424 |
def le(n, alpha, beta=0):
"""
Draw from the Levy-stable ensemble
:param n: size of random matrix
:param alpha: parameter controlling the asymptotic power law of the distribution tails, between 0 and 2
:param beta: skew of the distribution, between -1 and 1
:return: random n by n matrix, drawn f... | 90ae6fc4437acd29ca7125458a8923dce904da1a | 60,425 |
def run_database_command(client, command):
"""
Run a database command using the "mysql -e" command
:param client: String
:param command: String database command
:return:
"""
return mode.run_command(
helper.get_command(client, 'mysql') + ' ' + generate_mysql_credentials(
c... | c256dbcc5a1fe5a8fbdb41eef373570052bc5ede | 60,426 |
def get_kw_active(df):
"""
returns the df with only enabled keyword status
"""
return select_col_equals(df,'Keyword state','enabled') | 38a4bfa4c46a443e2b12c73b6d18055c771ad99b | 60,427 |
import urllib
def _urlencode(items):
"""A Unicode-safe URLencoder."""
try:
return urllib.urlencode(items)
except UnicodeEncodeError:
return urllib.urlencode([(k, smart_str(v)) for k, v in items]) | 5a5e0d90e695433ba3774221d835e44b6e8ad749 | 60,428 |
import os
def escape(pathname):
"""Escape all special characters.
"""
# Escaping is done by wrapping any of "*?[" between square brackets.
# Metacharacters do not work in the drive part and shouldn't be escaped.
drive, pathname = os.path.splitdrive(pathname)
if isinstance(pathname, bytes):
... | 9077c0cf2357c3358e22d81bca0b19535772b0fa | 60,429 |
def LLV(x: pd.Series, n: int):
"""
talib.MIN()
"""
LLV = [np.NAN] * (n - 1)
for index in range(len(x)):
if index < n - 1:
continue
else:
window = x[index - n + 1:index + 1]
LLV.append(min(window))
return pd.Series(LLV) | 9a4591d841c5dbd8cbe704f695e65a2cf5b1a429 | 60,430 |
from typing import List
def find_max_consecutive_ones(numbers: List[int]) -> int:
"""https://leetcode.com/problems/max-consecutive-ones/"""
current_sum, max_sum = 0, 0
for value in numbers:
current_sum += value
if not value:
max_sum = max(max_sum, current_sum)
curr... | 4b2f343553ff4756e21fe13d0b569e78add5b95d | 60,431 |
def _amplitudeFromPeak(peak, x, y, radius, x_0=10, y_0=10):
"""
This function can be used to estimate an Airy disc amplitude from the peak pixel, centroid and radius.
"""
rz = jn_zeros(1, 1)[0] / np.pi
r = np.sqrt((x - x_0) ** 2 + (y - y_0) ** 2) / (radius / rz)
if r == 0.:
return peak
... | a8af3d20fa069e5289feeede93c9969edbb1e88f | 60,432 |
def get_user(token):
"""Find user authenticated by token or return None."""
return USERS.get(token) | c24deed25ec58c3c4495da46815a3e81e18a09d7 | 60,433 |
import urllib
import json
from datetime import datetime
def by_location_id(id):
""" retrieve next appointment by location id
"""
raw = urllib.request.urlopen(SCHED_URL + str(id)).read()
appt = json.loads(raw.decode('utf-8'))
ts = None
if len(appt) > 0:
ts = datetime.datetime.strptime(a... | 7a8a90c11c75ca98529bd266c283fd2cb2b85b66 | 60,434 |
def sieve(limit):
"""
Returns a list of prime numbers up to but not including the given number.
"""
array = [True] * limit
array[0] = array[1] = False
primes = []
for (number, prime) in enumerate(array):
if prime:
primes.append(number)
... | 2b31d824cf8058044fa58de62d88cadf2f473c17 | 60,435 |
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up LoadShedding as config entry."""
suburb = Suburb(
id=entry.data.get("suburb_id"),
name=entry.data.get("suburb"),
municipality=entry.data.get("municipality"),
province=entry.data.get("province... | e6efcd2f3eadb8b893ea9e9f616323f7d4caa0c0 | 60,436 |
from typing import List
from typing import Tuple
def key_exists(key: str, list_keys: List) -> Tuple[int, bool]:
"""
Finds a dict which has `key` defined from a list `list_keys`
Args:
key: the key to find
list_keys: list of dicts
Returns:
index of key if found, whether the key... | 65d0dbb35be5773a6435d639ab218ebe05638c7b | 60,437 |
def combined_threshold_4(color_img, show_dbg=False):
"""Applies different methods to find the thresholds in the image."""
hls = cv2.cvtColor(color_img, cv2.COLOR_RGB2HLS)
s_channel = hls[:, :, 2]
gray = cv2.cvtColor(color_img, cv2.COLOR_RGB2GRAY)
sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0) # Take th... | c8554a9c7fc4123bdd4e39ca57dab2600632c762 | 60,438 |
def mod_rand_invertible(p):
"""Return a random invertible element modulo p for p > 1"""
assert p > 1
while True:
a = randint(1, p - 1)
# Check with the Euclidean algorithm if a is invertible
a2, a1 = p, a
while a1 > 0:
a2, a1 = a1, a2 % a1
# Now a is in... | a0fdf33721a26bbca6517e98318e72d963a686f8 | 60,439 |
def normed_duration(catalog):
"""
One-line description
Full description
Parameters
----------
Returns
-------
Examples
--------
"""
return (catalog['T']/day_hrs)/(catalog['period'])**(1/3.0) | ccdecf9aa4d90f05b8d00ca67bbea621ad604c0b | 60,440 |
def total_ordering_from_cmp(cls):
"""Class decorator that fills in missing ordering methods from __cmp__.
This lets us take a class defined for Python 2's ordering system (using
__cmp__) and use it with minimal changes -- just a decorator -- in Python 3.
This implementation is adapted from the Python 2 versio... | 41d40e6175185a6314ef02fa7bdc58b416957706 | 60,441 |
from typing import Any
from typing import Optional
from typing import Callable
def unmarshal_dict(
obj: dict,
cls: Any,
allow_extra_keys: bool=True,
ctor: Optional[Callable]=None,
):
""" Unmarshal @obj into @cls
Args:
obj: The dict to unmarshal into @cls
cls: ... | fde5db1f612f10266a5ec091e9052f7810f56713 | 60,442 |
import os
import logging
import traceback
def run(type_, input_, output,
altitude=None,
tres=300,
tlim=None,
tshift=0.,
zres=50,
zlim=[0., 15000.],
cloud_detection='default',
cloud_base_detection='default',
noise_removal='default',
calibration='default',
output_sampling=86400,
overlap_file=None,
calibrat... | b56dc9ff75ae27c3757508e4546e58f753926105 | 60,443 |
import sys
def random_float() -> float:
"""Return a random float."""
return uniform(-sys.maxsize, sys.maxsize) | 04b10d2b7558225fa66ea5483c5a360842ba190c | 60,444 |
import os
def retrieve_buff_usages(simdirs, config):
"""
Retrieve all the buff usages simulation result from the dummy simulation directories.
Parameters
----------
simdirs : list(str)
The list of dummy simulation directories.
Returns
-------
dict
The retrieved buff u... | 446fcfe339c2960623a546498eacd4169ddd5960 | 60,445 |
def make_label_df(labels, behavior_subj, psychometric_params):
"""Turns labels into a parsed df"""
label_df = pd.DataFrame(data={"stim_id": labels})
morphs.data.parse.stim_id(label_df)
label_df["behave_data"] = False
for dim, dim_group in label_df.groupby("morph_dim"):
if dim in psychometri... | d7e9cc36c81570d22cc19132fc0213cf828757c8 | 60,446 |
def dwolla_get_url(url):
"""
A helper method for the DwollaClient to retreive any url
Args:
url (str): the url to retreive
Returns:
response
"""
try:
result = DwollaClient.instance().token.get(url)
return result.body
except Exception as e:
logger.err... | 44a4ba68389a3d9017766f05bacb953d0a639947 | 60,447 |
from typing import Optional
from typing import List
from typing import Tuple
def cat1_gt_cat2(
df: pd.DataFrame, cat1: str, cat2: str, drop_levels: Optional[List[str]] = None
) -> Tuple[bool, pd.MultiIndex]:
"""
Checks that values from subset where `category == cat1` are
greater than the values from s... | b3b105e2d2664575c6ea76e7897d8de97a1f570e | 60,448 |
def extract_all(session_path, save=False, bpod_trials=False, settings=False):
"""Extract all datasets from habituationChoiceWorld
Note: only the datasets from the HabituationTrials extractor will be saved to disc.
:param session_path: The session path where the raw data are saved
:param save: If True, ... | 67a6ad5b5f4587b82176d33da9414d12c933fac2 | 60,449 |
def compute_norm_metrics(gradient):
"""Compute the metrics"""
l1 = np.linalg.norm(gradient, ord=1)
l2 = np.linalg.norm(gradient)
Min = np.linalg.norm(gradient, ord=-np.inf) ## min(abs(x))
Max = np.linalg.norm(gradient, ord=np.inf) ## max(abs(x))
Mean = np.average(gradient)
Skewness = skew(... | 7adf9a26eddd56373ddbadf0688411bed11a1749 | 60,450 |
def perform_wavelet_transf(f, Jmin, dir, filter = "9-7",separable = 0, ti = 0):
"""""
perform_wavelet_transf - peform fast lifting transform
y = perform_wavelet_transf(x, Jmin, dir, filter = "9-7",separable = 0, ti = 0);
Implement 1D and 2D symmetric wavelets with symmetric boundary treatements, using
... | fbcfd39bd9564f9040a72436923133beeebac77d | 60,451 |
import os
def loadPeaks(peakFile=None, peakfolder=None, isMacs=True, CTFlist=[], skiprows=0):
"""
will merge them file listed in a MACS2-way in a given MACS2 output folder all into one dataframe
Args:
----
peakFile: str filepaht if just one peakfile that you want to load (else leave it empty)
peakfolder: str... | e361117299aaba3035cb581c614c6ef625b03f28 | 60,452 |
import os
import glob
def get_best_thresh(dat, model):
"""Use validation set to get the best threshold value
"""
# get files for this test set
validation_files = dat.validation_files
test_set_path = test_path()
thresh_vals = np.arange(0.1, 1.0, 0.1)
thresh_scores = {t: [] for t in thresh... | aa46e7ce61d5473eae77758c4751b603a278f5e7 | 60,453 |
def create_channel(n_or_buffer=1):
"""Create a new channel.
As a conveinence, if n_or_buffer is a positive integer then creates a
blocking buffer for the new channel.
"""
buf = n_or_buffer
if isinstance(n_or_buffer, int):
buf = create_blocking_buffer(n_or_buffer)
elif buf.maxsize < ... | 5ebb051159d46c4c5f81e9822b83c470ddeb7ca7 | 60,454 |
def filter(src):
"""Filter a comments and blank lines out of heredoc-style source string"""
lines = src.strip().split("\n")
lines = [L.split("#")[0].strip() for L in lines] # filter comments
lines = [L for L in lines if len(L) > 0] # filter empty lines
return lines | b77ee55f27835a4ba1210b08274969ee060c6c35 | 60,455 |
import sys
def get_unicode_console():
"""
Get Unicode console objects.
@return: stdin, stdout, stderr, argv
@rtype: tuple
"""
# Make Unicode console output work independently of the current code page.
# This also fixes http://bugs.python.org/issue1602.
# Credit to Michael Kaplan
#... | 15ceff0d6ad9e5bfade27095cd32cd66a55fe4e9 | 60,456 |
def lower_convex_hull ( bs ) :
"""Get lower convex hull for BSpline
>>> bspline = ...
>>> lower = bspline.lower_convex_hull ()
>>> lower = lower_convex_hull ( bspline )
- for all values of x: bspline(x) >= lower ( x )
"""
return Ostap.Math.lower_convex_hull ( bs.bspline() ) | 55f6271ff34ad7c8c518ca708b0b9a8778126558 | 60,457 |
import random
def death_with_chance(p_death: float) -> bool:
"""
Takes a float between 0 and 1 and returns a boolean
if the player has survived (based on random chance)
Returns True if death, False if survived
"""
return p_death > random.random() | ad2a88727369e703cee6c345882c873db2104827 | 60,458 |
from datetime import datetime
def make_timestamp():
"""
Generate a timestamp of the current time.
returns:
datetime.datetime: The current time.
"""
return datetime.datetime.now() | 77999688b1af5982a3d4293b92b27549f6e6b1d2 | 60,459 |
def _radix_length(num: int) -> int:
"""Finds the number of digits for a number"""
if num == 0:
return 1
digits: int = 0
while num != 0:
digits += 1
num = int(num / 10)
return digits | 3df84020aae22c7287596103c3615bb039d3e59f | 60,460 |
import imp
def _pip_install():
"""If `pip` isn't installed, install it"""
try: # Check if `pip` installed
imp.find_module('pip')
return True
except ImportError: # If not installed, install it
get_pip = """do shell script "python '{0}/get-pip.py'" """.format(
... | 2083507180c3e8e28397bc83c5d642512f756b68 | 60,461 |
def service():
"""
Returns an instance of the service
"""
return Clickstream() | eb3a28f47f0604778c193968cb4cf86c391bf732 | 60,462 |
def enabled(mapper, args) -> bool:
"""Determine if hooks are enabled for the current method."""
if not settings.HOOKS_ENABLED:
return False
if mapper is None:
return False
if mapper.manual:
return False
if args and isinstance(args[0], str):
if args[0] in {"Meta", "... | 520651b3d1109cc2044b5af001d36b0b63eabbc2 | 60,463 |
from typing import List
from typing import Tuple
from typing import Dict
from typing import Union
from typing import Callable
def optimize_huggingface_model(
model: PreTrainedModel,
tokenizer: PreTrainedTokenizer,
input_texts: List[str],
batch_size: int,
max_input_sizes: List[Tuple[int, ...]],
... | 1cf643afb0b5710f87a7faa9a834061ec01a4bdb | 60,464 |
def cli(ctx, result_id, file_path):
"""Download a result to a file
Output:
None
"""
return ctx.gi.result.download(result_id, file_path) | 09a4a3d6ceab783e248ae53274c0bff8ad1fd249 | 60,465 |
def dummy_encode(df):
"""
Encode any dataframe column of type category or object.
---
df: pandas dataframe
"""
columnsToEncode = list(
df.select_dtypes(include=['category', 'object']))
df1 = df.copy()
for feature in columnsToEncode:
le = LabelEncoder()
try:
... | 6c65383f78727d62175a76aafbaf0140cfee6d8d | 60,466 |
def main(reactor, jid, secret):
"""
Connect to the given Jabber ID and return a L{Deferred} which will be
called back when the connection is over.
@param reactor: The reactor to use for the connection.
@param jid: A L{JID} to connect to.
@param secret: A C{str}
"""
return Client(reactor... | 59544915c9b83ae8cdee3d30a5ce1916f0978bcc | 60,467 |
from pathlib import Path
from typing import List
def get_schema_metadata_error_messages(file_path: Path) -> List[str]:
"""Return a list of error messages for the table schema at file_path
Undefined behaviour if the table schema is valid
"""
s = Schema(descriptor=file_path)
return [err.message for... | 9fe78512e188c14253fc86a60d45ff488bbef519 | 60,468 |
def create_holiday_calendar(
weekend_mask=None,
holidays=None,
start_year=None,
end_year=None):
"""Creates a holiday calendar.
Note: providing bounds for the calendar, i.e. `holidays` and/or `start_year`,
`end_year` yields a better-performing calendar.
Args:
weekend_mask: Boolean `Tensor` ... | fc76a842a293da3e03bad1d95813d1c49a317bc7 | 60,469 |
import copy
def get_object_vector_to(cls, search_cls, subtype, avoid=None):
"""
Returns a list of all possible paths to the given class.
Only searches classes that are subtype of the given class.
"""
# Does the name point to this class? Then we are done.
if search_cls == cls:
return [(... | a1b56bd59e96b4765cb0e75e496dc77eea94fa17 | 60,470 |
from typing import Any
from typing import Optional
import json
import hashlib
def gethash(
value: "Any",
hashtype: str = "sha256",
encoding: str = "utf-8",
json_encoder: "Optional[json.JSONEncoder]" = None,
) -> str:
"""Return a hash of `value`.
Can hash most python objects. Bytes and bytearr... | cdec65a96b068ded153f86af29af53d68fe7b822 | 60,471 |
def subplot(nrows, ncols, plot_number, **kwargs):
"""
Returen a subplot axes positioned by the given grid definition.
:param nrows, nrows: (*int*) Whree *nrows* and *ncols* are used to notionally spli the
figure into ``nrows * ncols`` sub-axes.
:param plot_number: (*int) Is used to identif... | 8d60d315aab7ad77513225848e592fc0f96faae6 | 60,472 |
def sub(a: PipeNumeric, b: PipeNumeric) -> PipeNumeric:
"""
Pipeline node which subtracts b from a.
:param a: parameter a
:param b: parameter b
:return: PipeNumeric
"""
if a.get_type() == b.get_type():
number_type = a.get_type()
if isinstance(number_type, num.FloatingNumberTy... | 6ce937bfad1ac96e7ebd5412f6707070996e0241 | 60,473 |
def get_raw_hcor(thing: dict) -> dict:
"""For an RAW hsilo-like dict, get only the non hmeta part.
This function requires at leat one key that seems an hmeta, but if more
than one exists, will also return None.
Args:
thing (dict): An HSilo-like dictionary
Returns:
dict: An dict wi... | 8247758ef8c223158c6daca69334034bc3a7bc5b | 60,474 |
def decode_message(buf, message_type=None, timestart=None, timeout_after=10):
"""Decode a message to a Python dictionary.
Returns tuple of (values, types)
"""
if message_type is None or isinstance(message_type, str):
if message_type not in known_messages:
message_type = {}
e... | fd90c543cd7e5cb77049c91bfd90dd6898b70e05 | 60,475 |
def makeReturn(items: dict) -> dict:
"""
Format output for alfred
"""
out = {'items': items}
return out | 114866d9fb142e072f77bb8bb1a7417a58fc76b6 | 60,476 |
def yices_bvproduct(n, t):
"""Returns the product of an array on bitvectors, or the NULL_TERM if there's an error.
bvproduct(n, t):
Product of n bitvector terms t[0] ... t[n-1]
- n must be positive
- all t[i]s must be bitvector terms of the same type (same number of bits)
Error reports:
if... | 842d7591aac98f992ccaa02b290df834cf6684cb | 60,477 |
async def spotify(id: str):
"""
A live API call to spotify, to get the information about a certain trackID
:return:
"""
# a random api call to spotify
db = get_db()
songs = db.query(Songdb).order_by(func.random()).limit(1).all()
db.close()
song_id=[]
for song in songs:
s... | c29d75202482a5d0a3a20ee22c7e5142c195a2a0 | 60,478 |
from typing import Iterable
def interquartile_range(data: Iterable[Real]) -> Real:
"""
Calculates the inter-quartile range of an iterable of real values.
:param data: The real values to calculate the inter-quartile range from.
:return: The upper quartile.
"""
ordered = sorted(data)
... | d4381a0720a6743364d788bc710c06b9ada5fda5 | 60,479 |
import json
def read_json(file):
"""
Read JSON file
"""
try:
with open(file, 'r') as f:
data = json.load(f)
except FileNotFoundError:
data = None
return data | 92842612769ae122a46fe90179c58d830534ff84 | 60,480 |
import re
def parse_dot_bands(bands_lines):
"""
Parse an CASTEP bands file
Extract Kpoints and each bands for each kpoints.
This is a generic parsing function. Return python builtin types.
The problems is the order of the kpoints written is parallelisation
dependent and may not be the same as... | 8b230b1a5e440a50a7f18975e47ef8831ee7baab | 60,481 |
import re
def ref2name(transaction, df_securities):
"""Find the security name corresponding to a given reference"""
try:
reference = transaction.findall("security")[0].attrib["reference"]
regex_ = r".*/security\[(\d+)\]"
index = int(re.search(regex_, reference, re.IGNORECASE).group(1))... | 7d8e3a9aa92f76a9a9ce38fc4d347c1e93b90328 | 60,482 |
def read_annotations_brainvision(fname, sfreq='auto'):
"""Create Annotations from BrainVision vrmk.
This function reads a .vrmk file and makes an
:class:`mne.Annotations` object.
Parameters
----------
fname : str | object
The path to the .vmrk file.
sfreq : float | 'auto'
T... | e477205d16319b95f57e1ac29a42f0eb5390d250 | 60,483 |
def redshift_prior(zbins, prior="uniform"):
"""
"""
available_priors = [
"uniform",
"volume",
]
if prior not in available_priors:
msg = ("'{}' is not in the list of available priors".format(prior))
raise ValueError(msg)
if prior == "uniform":
Pz = np.on... | e4819da6844ce97ca38d69152bf9eee4ed2e0096 | 60,484 |
import logging
def get_logger(log_level: str) -> logging.Logger:
"""
Create the default logger according to log level setting of the adapter instance.
"""
level = {
"critical": logging.CRITICAL,
"error": logging.ERROR,
"warning": logging.WARNING,
"info": logging.INFO,
... | 9557b54aa398fac47389614e57b4266f360b5ee3 | 60,485 |
def parse_visualizers(args_parser, args):
"""
Parses argparse arguments for visualizers, returning update_visulization
and connect_visualizers.
"""
def update_visualization(plant, scene_graph):
if args.visualize_collisions:
# Find all the geometries that have not already been ma... | 1f521ff6be1547b68f0bd70250c797cdac79c89c | 60,486 |
def blastwave(t, p0, t0, alpha=0.0):
"""
Acoustic blastwave that can be used as a source
for surface explosions out to several scale
kilometers.
Note: alpha = 0 produces the Friedlander
blastwave model.
Parameters
----------
... | 0689257a367cae577baacfac3724202cb73b987d | 60,487 |
import pickle
import codecs
def pickle_string_to_obj(string: str):
"""Pickle string to object
Arguments:
s {str} -- String object to pickle
Returns:
[pickle] -- base64 encoded pickled object
"""
unmarshal = pickle.loads(codecs.decode(string.encode(), "base64"))
return... | 79b547dd8981a67786dc38adeab96a95f07fc911 | 60,488 |
def get_template(im_source=None, center=None, side=None):
"""
Get a square template from image considering the a central coordinate.
**Input:**
* **im_source** (`ndarray`)
Image source is the image from where the template is retrieved.
* **center** (`list/tuple/ndarray`)
Coordinate... | 4d12d5f7af35c63c6c2efcc1b787676151570d2f | 60,489 |
def tvt_split(X):
"""
X is a pandas dataframe
Function splits data into train, validation and test datasets
with 80-20 split.
"""
train, test = train_test_split(X, train_size=0.8, test_size=0.2)
train, val = train_test_split(train, train_size=0.8, test_size=0.2)
return train, ... | 259dacd2acf58ad0816bf85560c506d9dee04d09 | 60,490 |
def longestCommonPrefix(strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs or not strs[0]:
return ""
start=0
end=len(strs[0])
element=strs[0][start]
result=""
while self.check_str(element,strs,start) and start<end:
result+=element
start+=1
... | 27d60999cf7c2bfbf60928d1ce480b9992c8fa07 | 60,491 |
def credentials_existance(name):
"""
function that checks if a a particular account and its credentials exist based on searched account_name
"""
return Credentials.credentials_exists(name) | a512348f157337879d3850a6fdecc88bf24451f7 | 60,492 |
import struct
from unittest.mock import patch
import types
def load_code(self):
"""
Returns a Python code object like xdis.unmarshal.load_code(),
but in we decrypt the data in self.bufstr.
That is:
* calculate the TEA key,
* decrypt self.bufstr
* create and return a Python code-obje... | 4e34489640698ba46065f79cdc3acc29a2b25e70 | 60,493 |
def _compute_initial_position(A, a, B, b):
"""
Compute initial beam position from two monitor read-outs at different
quadrupole settings.
A, B are the 7D SECTORMAPs from start to the monitor.
a, b are the 2D measurement vectors (x, y)
This function solves the linear system:
Ax = a... | be808e635c43b396adae518a903bd113429505ad | 60,494 |
def normalize_for_evaluation(img):
"""
Normalize an image to range [0,255]
:param img: Image to normalize
:return: Normalized image
"""
old_min, old_max = get_previous_range(img)
# NewValue = (((OldValue - OldMin) * NewRange) / OldRange) + NewMin
# NewMin = 0, NewMax = 255, NewRange = 1 ... | 7ea5fc395377ff99cf9ac8e5a8b48dce81dcd57e | 60,495 |
def user_session_info_rpc(self, api_timeout=''):
"""
This is an auto-generated method for the PySwitchLib.
**Supported Versions**:
* NOS: 6.0.2f, 7.2.0
* SLXOS: 17r.1.01a, 17r.2.00, 17s.1.02
:type api_timeout: long or tuple(long, long)
:param api_timeout: Timeout for connectio... | 287c80486d3a46f21071a120f94a63902f5c15bd | 60,496 |
def list_of_strs(value):
"""
Value must be iterable. All elements will be converted to strings.
"""
if not isiterable(value):
raise ValueError(value)
return list(map(str, value)) | ed94c16dc7bcfa704b70ffdfc68b6b85057e1f25 | 60,497 |
def sample(res_kf, M, Q, u=None, nsamples=1):
"""
Sample from the posterior of the states given the observations.
Parameters
----------
res_kf: results dict from the Kalman filter run
M: np.array or list of np.arrays of shape (n, n), dynamics model matrices
Q: np.array or list of np.arrays ... | f08072d547986ef797c2043448ea0c305d384127 | 60,498 |
def pad_number(number, bits):
"""Pad integer number to bits after converting to binary."""
return f'{bin(number)[2:]:0>{bits}}' | 73353469bad9bfb26b9e9c41f37d88f92e09aa6a | 60,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.