content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def verify_signature(
public_key: ecdsa.VerifyingKey, signature_base64: str, message: str
):
"""
Verifies the given bas64-encoded signature with the base64-encoded public
key and serialized message. The message should not contain any whitespaces.
Raises ValidationError if unsuccessful.
"""
... | 5,294,600 |
def generate_layer_name(layer):
"""
Generates unique name for layer.
Parameters
----------
layer : BaseLayer
Returns
-------
str
"""
cls = layer.__class__
layer_id = cls.global_identifiers_map[cls]
cls.global_identifiers_map[cls] += 1
classname = cls.__name__
... | 5,294,601 |
def get_costs_gas_pipeline():
"""Return the full path with file name and extension to the default costs per km to gas connect to pipelines."""
return pkg_resources.resource_filename('cerf', 'data/costs_gas_pipeline.yml') | 5,294,602 |
def _tsvector_column(*columns):
""" Creates an expression for tsvector values with weights from a number of
columns.
"""
vectors = []
for column, weight in columns:
tsvector = db.func.to_tsvector("english", column)
if weight in ["A", "B", "C", "D"]:
tsvector = db.func... | 5,294,603 |
def test_get_cve_id(org_admin_headers):
""" the first ID from 1999 should always exist """
res = requests.get(
f'{env.AWG_BASE_URL}{CVE_ID_URL}/{cve_id}',
headers=org_admin_headers
)
ok_response_contains(res, cve_id) | 5,294,604 |
def minimum_weighted_distances(df1, df2, weights):
"""
Compute minimum weighted distance from one DataFrame to another.
Args:
df1 (pandas.DataFrame):
The fixed reference points. Each column is a dimension, and
each row is a point.
df2 (pandas.DataFrame):
... | 5,294,605 |
def merge_kwargs(config: ConfigType, markers: List[Mark]) -> ConfigType:
"""Merge all kwargs into a single dictionary to pass to `vcr.use_cassette`."""
kwargs = deepcopy(config)
for marker in reversed(markers):
kwargs.update(marker.kwargs)
return kwargs | 5,294,606 |
def access_control(req):
"""
Check administrator privilege in request headers to protect resources from invalid access
:param req: HTTP request
:return: HTTPError if invalid else None
"""
if 'USER-UUID' not in req.headers or \
not isinstance(req.headers['USER-UUID'], str) or \
... | 5,294,607 |
def calculate_mean(arr, log):
"""Calculate mean and sd of arr values."""
n = len(arr)
if log:
logged_arr = [math.log10(value) for value in arr if value > 0]
if not logged_arr:
return 0, 0, n
mean = math.pow(10, statistics.mean(logged_arr))
if len(logged_arr) > 1:
... | 5,294,608 |
def recv_meas_outcome(socket):
"""Receive the measurement outcome (0 or 1) of the server's
last measurement.
"""
return int(socket.recv(maxsize=1)) | 5,294,609 |
def profil():
"""Prikaži stran uporabnika"""
username = get_user()
cur.execute("SELECT COUNT(*) FROM recept JOIN uporabnik ON uporabnik.id = recept.uporabnik WHERE uporabnik.ime=%s", [username])
[[st_receptov]] = cur.fetchall()
cur.execute("SELECT id FROM uporabnik WHERE ime=%s", [username])
[[i... | 5,294,610 |
def siteManagerAdapter(ob):
"""Look-up a site manager/component registry for local component
lookup. This is registered in place of the one in zope.site so that
we lookup using acquisition in addition to the ``ILocation`` API.
"""
site = findSite(ob)
if site is None:
return zope.compone... | 5,294,611 |
def convert_to_excel_data(lines_: list[Line]) -> tuple[list[float], list[float]]:
"""直線のリストをx座標のリストとy座標のリストに変換します。
Args:
lines_ (list[Line]): 直線のリスト
Returns:
typle[list[float], list[float]]:
x座標のリストとy座標のリスト
Examples:
>>> convert_to_excel_data([((0, 0), (1, 2)), ((1... | 5,294,612 |
def create_seasons(session, start_yr, end_yr):
"""
Adds Years and calendar and European Seasons records to database.
:param session: Transaction session object.
:param start_yr: Start of year interval.
:param end_yr: End of year interval, inclusive.
"""
def exists(model, **conditions):
... | 5,294,613 |
def mean_orientation(data: pd.DataFrame, static_moments: pd.DataFrame) -> pd.DataFrame:
"""Compute mean orientation of acceleration signal within static moment windows.
Parameters
----------
data : :class:`~pandas.DataFrame`
input data
static_moments : :class:`~pandas.DataFrame`
dat... | 5,294,614 |
def set_pump(kettle_id, onoff):
"""Set pump on or off."""
requests.put(
f"http://127.0.0.1:5000/api/devices/Kettle/{kettle_id}/pumpstate",
json={"state": onoff},
) | 5,294,615 |
def get_cse_policy_display_name(policy_name):
"""Remove cse specific prefix from the given policy name.
:param str policy_name: name of the policy
:return: policy name after removing cse specific prefix
:rtype: str
"""
if policy_name and \
policy_name.startswith(CSE_COMPUTE_POLICY_... | 5,294,616 |
def top_percentile(year=now().year, percentile_groups=PERCENTILE_GROUPS):
""" This is calculate top percentile of top_percentile_value
:return: list of (officer_id, percentile_value)
# """
if any(t not in PERCENTILE_GROUPS for t in percentile_groups):
raise ValueError("percentile_group is invali... | 5,294,617 |
def test_big_download2():
"""A test with attribute"""
pass | 5,294,618 |
def get_shortest_dist(this_point, other_points):
"""Get shortest (distance, index of other point) from this_point (x,y) and list of other_points [(x,y), (x,y), ...]"""
dists = get_all_dists(this_point, other_points)
min_dist, other_point_ind = min((val, idx) for (idx, val) in enumerate(dists))
return mi... | 5,294,619 |
def runconfiguration_transformer(values):
"""Calls transform_project_data with corresponding header"""
return transform_project_data(values, "Run configuration") | 5,294,620 |
def get_provider_manager(osid, runtime=None, proxy=None, local=False):
"""
Gets the most appropriate provider manager depending on config.
If local is True, then don't bother with the runtime/config and
try to get the requested service manager directly from the local
service implementations known t... | 5,294,621 |
def read_xml_file(xmlfilename, decode='utf-8'):
"""
读取xmlfile文件,并指定文件的解码方式,默认为utf-8
返回dom树
:param xmlfilename:
:param decode:
:return:
"""
if isinstance(xmlfilename, Path):
xmlfile: Path = xmlfilename
else:
xmlfile = Path(xmlfilename)
with xmlfile.open('rb') as xf... | 5,294,622 |
def get_cap_key():
"""
获取验证码初始化 ID
:return:
"""
url = 'https://shieldcaptain.mogu.com/gettoken'
params = {
'auth': get_auth({}),
'_': int(time.time() * 1000),
'callback': ''
}
resp = requests.get(url, params=params, headers=headers)
try:
result = jso... | 5,294,623 |
def test_launch_native(mock_harness: MagicMock, mock_subprocess: MagicMock) -> None:
"""
entrypoint: None
Native enabled -> launch harness.py
"""
native = {"internal": {"native": {"command": ["script.py"]}}}
launch.launch(det.ExperimentConfig(native))
mock_harness.assert_called_once_with(tr... | 5,294,624 |
def import_bibfiles(conn, bibfiles, *, ref_id_field=REF_ID_FIELD):
"""Import bibfiles with raw dbapi."""
log.info('importing bibfiles into a new db')
insert_file = dbapi_insert(conn, File,
column_keys=['name', 'size', 'mtime', 'priority'])
insert_entry = dbapi_insert(conn... | 5,294,625 |
def facet_subsets(data_collection, cid, lo=None, hi=None, steps=5,
prefix='', log=False):
"""Create a series of subsets that partition the values of
a particular attribute into several bins
This creates `steps` new subet groups, adds them to the data collection,
and returns the list o... | 5,294,626 |
def kl_test(df_in: DataFrame, df_out: DataFrame, attr: str):
"""
df_in: the sensitive dataset
df_out: the synthetic dataset
attr: the attribute that will be calculated for KL-divergence.
"""
distribution_in = get_distribution_of_categorical_attribute(df_in[attr])
distribution_out = get_distr... | 5,294,627 |
def get_or_create_data_version(paper_id: str) -> int:
"""
Get the index for the version of data produced by the current pipeline session. If a version
index hasn't yet been created for this session, create one by incrementing the last version
number found for this paper in the database.
"""
try:... | 5,294,628 |
def make_basic_auth_header(username, password):
"""
create a basic authentication header
:param username: user name [unicode on py2, str on py3]
:param password: password [unicode on py2, str on py3]
:return: basic auth header [str on py2, str on py3]
"""
# note: the coding dance in the nex... | 5,294,629 |
def xavier_init(fan_in, fan_out, const=1, dtype=tf.float32):
"""Xavier initialization."""
low = -const * np.sqrt(3.0 / (fan_in + fan_out))
high = const * np.sqrt(3.0 / (fan_in + fan_out))
return tf.random_uniform((fan_in, fan_out), minval=low, maxval=high, dtype=dtype) | 5,294,630 |
def plot_g_e(sco, log=False):
"""
plot log expression sum and detected gene counts
for cell inspect
should not be applyed to normalized expression
log:
if input data already log transformed
"""
expression = sco.expression_matrix
bm = expression > 0
if log:
x = log... | 5,294,631 |
def wrap_deepmind(env: gym.Env,
episode_life: bool = True,
clip_rewards: bool = True,
frame_stack: int = 4,
scale: bool = False,
warp_frame: bool = True,
channel_first: bool = True):
"""Configure environment for DeepMind-style At... | 5,294,632 |
def get_test_data_path():
"""Returns the path to test datasets """
return join(dirname(__file__), "data") | 5,294,633 |
def alfa_key(alfa: Union[str, int]) -> Union[str, None]:
"""
Return the numeric value of a possible alfanumeric key name. See "alfanumeric key names".
Parameters
----------
alfa : str | int
The package name from "alfa numeric names" list
or the correspondent index
Ret... | 5,294,634 |
def test_list_g_day_enumeration_1_nistxml_sv_iv_list_g_day_enumeration_2_5(mode, save_output, output_format):
"""
Type list/gDay is restricted by facet enumeration.
"""
assert_bindings(
schema="nistData/list/gDay/Schema+Instance/NISTSchema-SV-IV-list-gDay-enumeration-2.xsd",
instance="ni... | 5,294,635 |
def get_config() -> Config:
"""Reads environment variables to a Config object."""
gcs_bucket_name = env_require("GCS_BUCKET_NAME")
gcs_bucket_prefix = env_require("GCS_BUCKET_PREFIX")
gcp_service_account_credentials_base64 = env_require(
"GCP_SERVICE_ACCOUNT_CREDENTIALS"
)
gcp_service_ac... | 5,294,636 |
def log_in():
"""
The Simplest API login.
:param requestBody: require passing correct login and password of
existing user
:return JWT: encoded authorization token for given user on success,
401/404 on incorrect credentials
"""
user = request.get_json()
lgn = user['login']
pwd ... | 5,294,637 |
def truncate_blocks_text(blocks: List[SlackBlock]) -> List[SlackBlock]:
"""Modifies blocks to restrict all text to 3000 characters."""
for block in blocks:
try:
block['text']['text'] = block['text']['text'][:3000]
except KeyError:
pass
return blocks | 5,294,638 |
def generate_magic(s: int, bits: int, bishop: bool):
"""Generate magic bitboards for fast lookups on sliding piece attacks.
Taken from: https://www.chessprogramming.org/Looking_for_Magics
We are precomputing the attack set considering
all variations of blockers (max 4096 == 2**12, rook on a1)
"""... | 5,294,639 |
def user_inputsAPI():
"""API for storing new user input
payload is json style of shape:\n
{
"data": [float, float]
}
"""
data = json.loads(request.get_data())
accepted, complete = processor.process(data["data"])
content = {"clear": not accepted, 'complete': complete}
return... | 5,294,640 |
def truncated_pareto_expval(alpha, m, b):
"""
Expected value of truncated Pareto distribution.
"""
if alpha <= 1:
return inf
part1 = (m ** alpha) / (1. - (m / b) ** alpha)
part2 = 1. * alpha / (alpha - 1)
part3 = (1. / (m ** (alpha - 1)) - 1. / (b ** (alpha - 1.)))
return part1 ... | 5,294,641 |
def update_team(
*,
db_session: Session = Depends(get_db),
team_contact_id: PrimaryKey,
team_contact_in: TeamContactUpdate,
):
"""Update a team contact."""
team = get(db_session=db_session, team_contact_id=team_contact_id)
if not team:
raise HTTPException(
status_code=sta... | 5,294,642 |
def word_to_col(w):
"""Splits a hexadecimal string to a bytes column.
Parameters
----------
w : str
Hexadecimal 32-bit word.
Returns
-------
list
4 bytes column containing integers representing the input string.
"""
x = int(w, 16)
return [x >> 24, (x >> 16) & 0... | 5,294,643 |
def _create_documents_per_words(freq_matrix: dict) -> dict:
"""
Returns a dictionary of words and the number of documents in which they
appear.
:param freq_matrix: The frequency matrix to be summarized.
:return: A dictionary of words and the number of documents in which they appear.
"""
doc_... | 5,294,644 |
def odin_connection():
"""Connects to the database, returns a connection"""
connection_string = (
"host={0} ".format(environ.get("PGHOST")) +
"dbname={0} ".format(environ.get("PGDBNAME")) +
"user={0} ".format(environ.get("PGUSER")) +
"password={0}".format(environ.get("PGPASS"))
... | 5,294,645 |
async def test_ws_current_user(hass, hass_ws_client, hass_access_token):
"""Test the current user command."""
assert await async_setup_component(hass, 'auth', {
'http': {
'api_password': 'bla'
}
})
with patch('homeassistant.auth.AuthManager.active', return_value=True):
... | 5,294,646 |
def is_mass_profile_class(cls):
"""
Parameters
----------
cls
Some object
Returns
-------
bool: is_mass_profile_class
True if cls is a class that inherits from mass profile
"""
return inspect.isclass(cls) and issubclass(cls, mass_profiles.MassProfile) | 5,294,647 |
def pyats(**kwargs):
"""
generates a pyats testbed config for a lab
"""
server = VIRLServer()
client = get_cml_client(server)
current_lab = get_current_lab()
if current_lab:
lab = safe_join_existing_lab(current_lab, client)
if lab:
if kwargs.get("output"):
... | 5,294,648 |
def superuser_required_or_403():
"""
Decorator to make a view only accessible as a superuser or it will raise
PermissionDenied.
Usage::
@superuser_required_or_403()
def a_view(request):
# I can assume now that the view is only accessible as a superuser.
"""
def deco... | 5,294,649 |
def configure(ctx, project_name, project_user):
"""Configures PostgreSQL for the given project."""
version_ = '.'.join(get_version(ctx)[:-1])
path_confs = Path(f'/etc/postgresql/{version_}/main/')
config_name = 'postgresql.conf'
target_name = f'{project_name}.conf'
config_linked = link_config... | 5,294,650 |
def pullback(b, c, d, b_d, c_d, inplace=False):
"""Find the pullback from b -> d <- c.
Given h1 : B -> D; h2 : C -> D returns A, rh1, rh2
with rh1 : A -> B; rh2 : A -> C and A the pullback.
"""
if inplace is True:
a = b
else:
a = type(b)()
# Check homomorphisms
check_ho... | 5,294,651 |
def corr_therm2_sp(omega, x, y, disp=True):
"""Remove the thermal component in an OMEGA spectrum, with simultaneous retriving
of reflectance and temperature.
Parameters
==========
omega : OMEGAdata
The OMEGA observation data.
x : int
The x-coordinate of the pixel.
y : int
... | 5,294,652 |
def ward_test_more(n=100,k=5,verbose=0):
"""
Check that two implementations give the same result
"""
np.random.seed(0)
X = randn(n,2)
X[:np.ceil(n/3)] += 5
G = fg.WeightedGraph(n)
G.knn(X,5)
import time
t1 = time.time()
u,c = ward_segment(G,X,stop=-1,qmax=1,verbose=verbose)
... | 5,294,653 |
def amplitude_rate_modulation(y, sr, difficulty):
"""This function uses the average amplitude (i.e., 'loudness') of a beat and the difficulty level to determine
how many blocks will be placed within the beat. Returns a list of beat numbers."""
#Make amplitude matrix
D = np.abs(librosa.stft(y))
db =... | 5,294,654 |
def write(file: Union[str, Path], flow: Tensor, fmt="middlebury") -> None:
"""Write optical flow to a file.
Supported are several common formats used to store optical flow data:
- KITTI
- Middlebury
- PFM
Args:
flow: the optical flow array or tensor of shape (2, H, W)
file: a ... | 5,294,655 |
def _raise_missing_if_result_is_none(function):
"""
Raise MissingAccountData if function's result is None.
adapted from https://github.com/Backblaze/b2-sdk-python/blob/v1.5.0/b2sdk/account_info/in_memory.py
"""
@wraps(function)
def getter_function(*args, **kwargs):
assert function.__nam... | 5,294,656 |
def nb_pixels(info_dict):
""" Compute the number of pixels affected by the target light
Parameters
----------
info_dict: dictionnary
wavelength: float
wavelength in angstrom
Returns
--------
npix: float
number of pixels affected by the target light (ceiled)
... | 5,294,657 |
def test_create_report_with_comment(client, user, angler):
"""if we post data with a comment, the report should
be created and have that comment associated with it."""
url = reverse("tfat:create_report", kwargs={"angler_id": angler.id})
data = {"reported_by": angler.id, "comment": "My Fake Comment"}
... | 5,294,658 |
def proposed_weight_norm_g_init(wn_layer, gain=2., version=1):
"""
Initialize WN's g to preserve the norm of the forward pass
"""
if version == 1:
fan_in, fan_out = _calculate_fan_in_and_fan_out(wn_layer.weight)
wn_layer.weight_g = Parameter(torch.ones_like(wn_layer.weight_g) * math.sqrt... | 5,294,659 |
def showdumb(bot, msg):
"""Show the notification group, but don't expand subgroups."""
slug = msg.match.group(1)
with db.cursor(password=bot.mysql_password) as c:
group = get_group(c, slug)
if group is None:
msg.respond(f'{slug} not found.')
return
for attr in... | 5,294,660 |
def token_refresh():
"""Handler for refreshing access token."""
MSGRAPHAPI.refresh_access_token()
redirect(request.query.redirect_to) | 5,294,661 |
def get_rnn_layer(reservoir_weight: Optional[np.ndarray] = None,
reservoir_params: Optional[Dict[str, Any]] = None,
layer_name: str = "LSTM",
units: int = 200,
return_sequences: bool = False) -> tf.keras.layers.Layer:
"""Build an RNN layer.
Ar... | 5,294,662 |
def generate_regenet_arch(initial_width, width_slope, quantilize, width_m, depth, bottleneck_ratio, group_width):
"""
Inspired by the observation from AnyNetXd and AnyNetXe
"""
assert width_m > 0, 'width_m must be greater than 0'
# Generate block widths and depths via Eq.2 ~ Eq.4 in the paper
w... | 5,294,663 |
def fetch(dataset, annot, cat=(0, 0, 0, 0), evt_type=None, stage=None,
cycle=None, chan_full=None, epoch=None, epoch_dur=30,
epoch_overlap=0, epoch_step=None, reject_epoch=False,
reject_artf=False, min_dur=0, buffer=0):
"""Create instance of Segments for analysis, complete with info ab... | 5,294,664 |
def test_transaction_receipt(buffer: str, status: int, cumulative_gas_used: int, logs: tuple, should_pass: bool):
""" Unit test for receipt module. """
buffer_bytes = bytes.fromhex(buffer) if buffer is not None else None
if should_pass:
receipt_instance = rlp.decode(buffer_bytes, receipt.Transaction... | 5,294,665 |
def tail():
""" tail syslog on remote server """
with _service.ssh_ctx():
api.sudo('tail /var/log/syslog') | 5,294,666 |
def __main__():
"""
Unit test.
"""
try:
path = sys.argv[1]
except:
path = os.path.join(".", "images", "sudoku3.png")
img = cv2.imread(path)
img = detect_edges(img)
cv2.imshow("Edges:", img)
cv2.waitKey(0) | 5,294,667 |
def polar(a, side="right", compute_p=False):
"""
Compute the polar decomposition. This is a transcription of the
SciPy code - check scipy.linalg.polar for documentation.
"""
if side not in ['right', 'left']:
raise ValueError("must be either 'right' or 'left'")
a = np.asarray(a)
if a... | 5,294,668 |
def main(args):
"""
Eval for totaltext dataset
"""
dbnet = load_model(args.model_path, args.device)
test_img_fps = sorted(glob.glob(os.path.join(args.image_dir, "*")))
result_poly_preds = []
img_fns = []
for test_img_fp in tqdm(test_img_fps):
try:
test_img_fn = tes... | 5,294,669 |
def replace_file_type(file_name, new_type):
"""
:param file_name:
:param new_type:
:return:
"""
file_name_parts = file_name.split(".")
return file_name.replace(file_name_parts[len(file_name_parts)-1], new_type) | 5,294,670 |
def _text_to_df(text_file, encoding=None):
"""
Convert a raw E-Prime output text file into a pandas DataFrame.
"""
# Load the text file as a list.
if encoding is None:
with open(text_file, 'rb') as fo:
text_data = list(fo)
# Remove unicode characters.
filtered_d... | 5,294,671 |
async def unload(ctx, what: str):
"""Unload Modules"""
bot.unload_extension(what)
await ctx.send("Unloaded {}".format(what)) | 5,294,672 |
def unescape_response():
""" Unescape the html body which escaped by ``_cpcompat.escape_html()``. """
response = cherrypy.serving.response
if not is_closable_iterator(response.body): # Dont do this for stream
response.body = bytes(unescape_html(response.collapse_body())) | 5,294,673 |
def findmatch1(x, xsearch, tol=1e-4):
"""RETURNS THE INDEX OF x WHERE xsearch IS FOUND"""
i = argmin(abs(x - xsearch))
if tol:
if abs(x[i] - xsearch) > tol:
print(xsearch, 'NOT FOUND IN findmatch1')
i = -1
return i | 5,294,674 |
def profile(func):
"""Decorator for run function profile"""
def wrapper(*args, **kwargs):
global i
profile_filename = 'profile/' + func.__name__ + '%06d' % i + '.prof'
i += 1
profiler = cProfile.Profile()
result = profiler.runcall(func, *args, **kwargs)
profiler.d... | 5,294,675 |
def main():
""" Main """
session = tf.Session()
W = tf.Variable([0.3], tf.float32)
b = tf.Variable([-0.3], tf.float32)
x = tf.placeholder(tf.float32)
y = tf.placeholder(tf.float32)
linear_model = W * x + b
squared_detas = tf.square(linear_model - y)
loss = tf.reduce_su... | 5,294,676 |
def test_cached_coherence():
"""Testing the cached coherence functions """
NFFT = 64 # This is the default behavior
n_freqs = NFFT // 2 + 1
ij = [(0, 1), (1, 0)]
ts = np.loadtxt(os.path.join(test_dir_path, 'tseries12.txt'))
freqs, cache = tsa.cache_fft(ts, ij)
# Are the frequencies the rig... | 5,294,677 |
def nonced(method):
""" Decorates a handler to only accept requests with nonce header.
If the request is missing the request handler we set the status as 400 with
a malformed message.
"""
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
if self.nonce_service.provided(request=... | 5,294,678 |
def userToJson(user):
"""Returns a serializable User dict
:param user: User to get info for
:type user: User
:returns: dict
"""
obj = {
"id": user.id,
"username": user.username,
"name": user.get_full_name(),
"email": user.email,
}
return obj | 5,294,679 |
def create_checkbox_group(names, kind, button_dict):
"""Creates a dictionary containing all checkboxes for set selection and a group
widget containing all of them for display."""
box_dict = {}
if kind == "Sets":
names = [set_ for set_ in names if set_ not in ["Intrigue", "Base"]]
tooltip... | 5,294,680 |
def cmr_search(short_name, version, time_start, time_end,
bounding_box='', polygon='', filename_filter='', quiet=False):
"""Perform a scrolling CMR query for files matching input criteria."""
cmr_query_url = build_cmr_query_url(short_name=short_name, version=version,
... | 5,294,681 |
def dijkstra(source: OrientedWay) -> SingleSourceMap:
"""Dijkstra algorithm."""
info: DefaultDict[OrientedWay, _NodeInfo]
node: OrientedWay
visited: Set[OrientedWay]
queue = FibonacciHeap()
visited = set()
source_info = _NodeInfo(0.0)
source_info.entry = queue.enqueue(source, 0)
inf... | 5,294,682 |
def upgrade(migrate_engine):
"""Map quotas hard_limit from NULL to -1"""
_migrate_unlimited(migrate_engine, None, -1) | 5,294,683 |
def start_bot() -> None:
"""Start VK bot."""
session = vk_api.VkApi(token=env_settings.vk_bot_token)
api = session.get_api()
longpoll = VkLongPoll(session)
with exception_logger(Exception, vk_logger, raise_=True):
for event in longpoll.listen():
if event.type == VkEventType.MESS... | 5,294,684 |
def gcv(data, channels=None):
"""
Calculate the geometric CV of the events in an FCSData object.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
channels : int or str or... | 5,294,685 |
def compute_fail_probability(rankings, mtable):
"""
This computes experimentally how many of the M rankings fail to satisfy the mtable
:param rankings: rankings that are checked (list of lists of FairScoreDoc)
:param mtable: an mtable to check against (list of int)
:return: the ra... | 5,294,686 |
def copy_group(source_globals_file, source_groupname, dest_globals_file, delete_source_group=False):
""" This function copies the group source_groupname from source_globals_file
to dest_globals_file and renames the new group so that there is no name
collision. If delete_source_group is False the ... | 5,294,687 |
async def price(message: types.Message):
"""return the current price of $Joe"""
if not timer.canMessageOnChatId(message.chat.id):
return
msg = message.text.lower().replace("/price", "").replace(" ", "")
if msg != "" and msg != "joe":
if msg == "avax":
avaxp = JoeSubGraph.getA... | 5,294,688 |
def show_seg(seg, ds9, header=None, seed=1):
"""
Show segmentation image in DS9 with randomized segments
"""
from grizli.catalog import randomize_segmentation_labels
ds9.view(randomize_segmentation_labels(seg, random_seed=seed)[1],
header=header) | 5,294,689 |
def check_estimation_data(df, options):
"""Check data for estimation.
Parameters
----------
options : dict
Dictionary containing model options.
df : pd.DataFrame
Data for estimation.
Raises
------
AssertionError
If data has not the expected format.
"""
... | 5,294,690 |
def boot(status):
"""Enable or disable the systemd service which activates the ir emitter
Args:
status (string): "enable" or "disable" or "status"
Raises:
Exception: status arg can only be equal to enable or disable
"""
if status in ("enable", "disable", "status"):
os.syste... | 5,294,691 |
def test_atomic_time_min_inclusive_3_nistxml_sv_iv_atomic_time_min_inclusive_4_2(mode, save_output, output_format):
"""
Type atomic/time is restricted by facet minInclusive with value
19:31:35.
"""
assert_bindings(
schema="nistData/atomic/time/Schema+Instance/NISTSchema-SV-IV-atomic-time-min... | 5,294,692 |
def build_client(username=None):
"""Build a Spotipy client scoped for use."""
username = get_username(username)
auth = util.prompt_for_user_token(
username,
scope='playlist-modify-private playlist-modify-public',
)
return spotipy.Spotify(auth=auth) | 5,294,693 |
def do_declare():
"""Makes a f5-declarative-onboarding declaration from the generated file"""
if is_rest_worker('/mgmt/shared/declarative-onboarding') and \
os.path.isfile(DO_DECLARATION_FILE):
dec_file = open(DO_DECLARATION_FILE, 'r')
declaration = dec_file.read()
dec_file.c... | 5,294,694 |
def classify_peaks(bed, min_count, a_region_size, a_ratio, a_stretch,
can_region, noncan_seqs, out_cols, size):
"""classify the peak sequences."""
res = ["chrom", "start", "stop", "name", "count", "strand", "seq"]
for i, l in enumerate(reader(bed, header=res), start=1):
# filter ... | 5,294,695 |
def write_score(func: Callable[[Any, Any], Any]) -> (Tuple[Any, ...], Dict[str, Any]):
"""
Save the store data of the decorated function in a file.
:param func: a function
:precondition: input parameter must be a function
:postcondition: correctly writes the store data to the file
:return: a fu... | 5,294,696 |
def get_places_around_centroid(point, radius, place_type):
"""
Find places of place_type within a radius around a centroid
and add to database.
:param point: the centroid, of type Point
:param radius: radius (in metres)
:param place_type: type of place to be searched for
:return: list of pla... | 5,294,697 |
def generate_empty_config_file():
""" Reset the config file."""
with open(get_config_file_path(), 'w') as datafile:
json.dump({}, datafile) | 5,294,698 |
def safe_import(path, default=None):
"""Import a given path as efficiently as possible and without failure."""
module = sys.modules.get(path, default)
for exclude_name in IGNORE_MODULES:
if path.startswith(exclude_name):
return default
if module is default and __import_unknown_module... | 5,294,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.