content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def compute_transpose(x):
""" given a matrix, computes the transpose """
xt=[([0]*len(x)) for k in x[0]]
for i, x_row in enumerate(x):
for j, b in enumerate(x_row):
xt[j][i]=x[i][j]
return xt | 22988bc9802deaf1bc07182a5e85c56d54c94436 | 3,621,731 |
def make_psf_map(psf, pointing, geom, exposure_map=None):
"""Make a psf map for a single observation
Expected axes : rad and true energy in this specific order
The name of the rad MapAxis is expected to be 'rad'
Parameters
----------
psf : `~gammapy.irf.PSF3D`
the PSF IRF
pointing ... | ebfe470724d1977b59b6e4126d11660187cca643 | 3,621,732 |
def test_get_and_modify_user(cbcsdk_mock):
"""Tests retrieving and modifying a user."""
def check_put(url, body, **kwargs):
assert body['login_id'] == 6942
assert body['login_name'] == 'jsheridan@babylon5.com'
assert body['email'] == 'jsheridan@zhadum.net'
return None
cbcsdk... | e3644d9013c98fbc26d56dffbd45f7bb5b8c100d | 3,621,733 |
def sort_articles(articles):
"""Sort articles based on score.
:param articles:
:return:
"""
if len(articles) < 1:
raise ValueError('No news')
sorted_articles = sorted(articles, key=lambda x: x.score, reverse=True)
return sorted_articles | f8cbd9a1437a463e49269e65a440d51fdc7c0dd1 | 3,621,734 |
def get_interface_sequence(ip_addr_output):
"""
output interface sequence paired to eth0, None on not found
ip_addr_output will be like:
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 ... | 2203604fd11077c02896ca422de07d1ff1ee04a2 | 3,621,735 |
def body_id(b_name):
"""Return the body id"""
return bodies['id'][where(bodies['name'] == b_name.encode())] | 693a49a23ab1253f0cf389981220c7c6df634536 | 3,621,736 |
def build_dict_det_pair(det_df):
"""
Build the dictionary that converts from detector pair to index and angle
Parameters
----------
det_df : pandas dataFrame
dataFrame of detector pair indices and angles
Returns
-------
dict_pair_to_index : dict
keys: detecto... | f9da588341f8940221d76cd82bfaa88b81348f82 | 3,621,737 |
import numpy as np
def random_layout(H, center=None, dim=2, seed=None):
"""Position nodes uniformly at random in the unit square. Exactly as networkx does.
For every node, a position is generated by choosing each of dim
coordinates uniformly at random on the interval [0.0, 1.0).
NumPy (http://scipy.or... | 88b613f6a8cfd53eccf2a9397d926d254445761f | 3,621,738 |
def test_close_handles_odbql_error(monkeypatch):
"""Test that the close method handles ODBQL_ERROR."""
def mock_odbql_close(connection):
"""mock odbql_close"""
return py3odb.odbql.ODBQL_ERROR
monkeypatch.setattr("py3odb.odbql.odbql_close", mock_odbql_close)
conn = py3odb.connect("")
... | f68522b7f8d6fe19a31b543aafd16b5c75ee4da0 | 3,621,739 |
from typing import Optional
from typing import Callable
from typing import Any
def _get_serializer(meta: Optional[AttributeMetadata]) -> Callable[[Any], str]:
"""Get a serializer function from the given attribute metadata."""
serializer = None if meta is None else SERIALIZER_MAP.get(meta.attribute_type)
i... | f2f383e502b4dfdc1fc28d962c4e65c1923b1915 | 3,621,740 |
def client():
"""
Create the configuration that we will have to use to be able to run our test cases, with this method we won't be able to run our test cases
"""
app = create_app()
return app.test_client() | d964539af223b6def7c0d248523037a68b5e1477 | 3,621,741 |
def WR(df, n):
"""威廉指标"""
hn = df["high"].rolling(n).max()
ln = df["low"].rolling(n).min()
df["wr"] = (hn - df["close"]) / (hn - ln) * (-100)
return df | 38ed4b05d970b4359d50103b7a54a91780dff3aa | 3,621,742 |
import math
def volume_correction(distance_values, temperature=298.15):
"""Calculates the volume correction of the free energy
Parameters
-------------
distance_values : numpy.array
1-D numpy.array containing the distance
of the ligand from the protein (center of mass - center of mass... | d0d47781ec88a8820faf641ad0b09f6c34b8c19d | 3,621,743 |
def key_released(key: int) -> bool:
"""Determines if the given key is released."""
# Handle the queued keys."""
for event in pygame_queued_events:
if event.type == pygame.KEYUP:
if event.key == key:
pygame_queued_events.remove(event)
return True
# Time... | 1e3fb0448d994c1eccb6b2f68af3617518e101ab | 3,621,744 |
def extract_mocha_summary(lines):
"""
Example mocha summary lines (both lines can be missing if no tests passed/failed):
✔ 3 tests completed
✖ 1 test failed
"""
passes, fails = 0, 0
for line in lines:
if line and line[0] == '✔':
passes = int(line.split()[1])
elif ... | 53d671c3d18f0421cbb512835a84f71a9588f947 | 3,621,745 |
def vote(request, ballot_url):
"""
For ballots with tokens.
"""
display_ballot = get_object_or_404(BallotPaper, ballot_url=ballot_url)
queryset = Category.objects.filter(ballot_paper=display_ballot)
caty = get_list_or_404(queryset)
user = request.user
for cat in caty:
try:
selected_choice = cat.choice_set... | c5750ab8007ba31c4a4db28166ba04ad3c323208 | 3,621,746 |
def index():
"""Homepage"""
dishes = Dishes.query.all()
if not dishes:
flash("No dishes are available in Mess!",
category='warning')
return render_template(
'index.html',
year=year,
dishes=dishes
) | 49bdfd39e03078824cc65ac7c26036216338c6b4 | 3,621,747 |
def get_gts(init_weight, aft_weight):
"""
"""
gts = np.where(init_weight != aft_weight)
return gts | b440502da72017ccdc80b47a864cf678cf637d75 | 3,621,748 |
import re
def get_headword(tag):
"""
Extract the content of a BeautifulSoup element Tag object.
Args:
tag (Tag): a BeautifulSoup element tag, obtained by extracting from a soup
Returns:
short, long ([str]): short and long form of a word in dictionary definition
Modules:
b... | 7f98d90973527901f9b87658dd5b29916d94cecf | 3,621,749 |
def _boundary(sample, n_i, n_g, n_t, b):
"""
Find matrix for R and T for air/glass/slab interface.
The resulting matrix is a diagonal matrix that is represented as an
array.
The reflection matrix is the same entering or exiting the slab. The
transmission matrices should differ by a factor of
... | 118088bc466aa9a474dc173c70d1d78d42e3b3d3 | 3,621,750 |
def get_obo() -> Obo:
"""Get ITIS as OBO."""
return Obo(
ontology=PREFIX,
name='Integrated Taxonomic Information System',
iter_terms=iter_terms,
auto_generated_by=f'bio2obo:{PREFIX}',
data_version=_get_version(),
) | 5c312d32b08b8a4d3fe34f0bc914dbfa51f3b752 | 3,621,752 |
def _calculate_discount_for_last_element(
lines_total_prices, total_price, total_discount_amount, currency
):
"""Calculate the discount for last element.
If the given line is last on the list we should calculate the discount by difference
between total discount amount and sum of discounts applied to re... | 704b2b451f0062595846ae64daa2d704305f273e | 3,621,753 |
import re
def tfprint(tensor, prefix=None, summarize=256):
"""tf.Printのショートカットメソッド
Return:
tf.Print(tensor, [tensor],・・・・)
の復帰値をそのまま返す。
"""
if stop:
# stopならprint無し
return tensor
if prefix is None:
prefix = tensor.name
if not re.match(out_n... | 3dbb229bc3a796f8423b218bcac9eddbdcf39618 | 3,621,754 |
def replace_text(text):
"""
Android资源文件英文的双引号或单引号需要加斜杠,否则会报错,中文的双引号和单引号不需要
:param text:
:return:
"""
temp_text = text.replace(r' \ "', r' \"').replace(r' / ', r'/').replace(r'% ', r' %') \
.replace(r' $ ', r'$').replace(r'$ ', r'$').replace(r'¥ ', r'¥ ').replace(r'¥ ', r'¥ ').replace(r... | cddb558dabb34442fe6e5118229e3ea092c144d2 | 3,621,755 |
import json
def change_pwd(username, password):
"""
修改密码
@param self 绑定为当前对象
@param username 要修改密码的账户名
@param password 新密码
"""
try:
sock = socksPool.get()
cmd = [[{'op': '5'}, {'name': username}, {'pwd': password}]]
json_data = _assembly_request(cmd)
if js... | 8c43f064a1926825cc0fbdadb56c07524d9d76ed | 3,621,756 |
from typing import List
from typing import Union
def quantity_list_validator(
item: List[Union[unyt.unyt_quantity, unyt.unyt_array, str]]
) -> List[unyt.unyt_quantity]:
"""
Converts a list of either strings (as ``FloatValue UnitX / UnitY``) or unyt quantities
and arrays to a list of unyt quantities.
... | 2b7e51b40dded76ba95f3e71806ad6bf5bc6339f | 3,621,757 |
import importlib
def _import_from_path(name, path):
"""A helper function that imports a module from the given path."""
spec = importlib.util.spec_from_file_location(name, path)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod | eeaefe11f28077c390c5974e3d7e11ca3179c72c | 3,621,759 |
def netstat():
"""
Return information on open ports and states
.. note::
On BSD minions, the output contains PID info (where available) for each
netstat entry, fetched from sockstat/fstat output.
.. versionchanged:: 2014.1.4
Added support for OpenBSD, FreeBSD, and NetBSD
.... | f382061415948c936a18af1fbc220fb1e8f39264 | 3,621,760 |
from typing import Mapping
def add_package_headings(toc: Toc, root_pkg: str, labels: Mapping[str,
str]) -> Toc:
"""Breaks up a flat structure with headings for each 1st-level package."""
new_toc = []
current_section = None
for entry in toc.get(... | bc9879c2b0a1f75a461ce341b4a12fdb5c47a23e | 3,621,761 |
def wrap_deepmind(env, episode_life=True, clip_rewards=True, stack=4):
"""Configure environment for DeepMind-style Atari.
Note: this does not include frame stacking!"""
assert 'NoFrameskip' in env.spec.id # required for DeepMind-style skip
if episode_life:
env = EpisodicLifeEnv(env)
# env ... | e8ab549e44f6faf45dbf45917847406f386853ac | 3,621,762 |
from typing import Optional
def build_dataset(
x: np.ndarray,
y: np.ndarray,
num_classes: int,
shuffle_buffer_size: int = 0,
augment: bool = False,
augment_color: bool = False,
augment_horizontal_flip: bool = False,
augment_offset: int = 0,
seed: Optional[int] = None,
normaliza... | 5dcab33148b4fce8215f5ab8c4272c836de054f1 | 3,621,763 |
def factorial(n):
""" Returns the factorial of n.
e.g. factorial(7) = 7x6x5x4x3x2x1 = 5040
"""
answer = 1
for i in range(n, 1, -1):
answer = answer * i
return answer | 98c0530e4e0f1de8c1c0f622e7d62a5feb042bcb | 3,621,764 |
def get_available_holidays_in_countries(
countries,
year_start,
year_end):
"""Returns a dictionary mapping each country to its holidays
between the years specified.
:param countries: List[str]
countries for which we need holidays
:param year_start: int
first ... | ecdc6f8c20bed2ce8be16a1c50803c8033ef82b1 | 3,621,765 |
def vfun(self, parr="", func="", par1="", con1="", con2="", con3="",
**kwargs):
"""Performs a function on a single array parameter.
APDL Command: *VFUN
Parameters
----------
parr
The name of the resulting numeric array parameter vector. See *SET
for name restrictions.
... | dba87cb721ba79a797c357160a2ebed425b3239f | 3,621,767 |
def reverse_colors(frame):
"""
Reverse the order of colors in a frame from RGB to BGR and from BGR to
RGB.
"""
return frame[:, :, ::-1] | 210deca283c373d02c0d114daad2e23ba822b3ab | 3,621,768 |
def extract_geohash_from_path(paths):
"""
:param paths: Sentinel2 paths;Shape = (batch_size, no_of_timestamps=3)
:return: 1d list of geohashes for which imputation is made
"""
return [i[i.find('9q'):i.find('9q')+5] for i in paths] | 4920e611bbb1e3f9c1ee2aef4efb93832a9b0c9b | 3,621,769 |
def chl_decision(uncorrected_chl_value, regression_table, sample_date):
"""
Decision tree for correcting Chl values using a linear model regression results
:param uncorrected_chl_value: the value to correct
:param regression_table: the table to look up the rsquared, a coeff, b coeff for given date
:param sample_da... | 7b1e10241a303dcc973808148323d8444a78d17c | 3,621,770 |
from typing import Counter
def getunknownwordmodel(tagged_sents, unknownword,
unknownthreshold, openclassthreshold):
"""Collect statistics for an unknown word model.
:param tagged_sents: the sentences from the training set with the gold POS
tags from the treebank.
:param unknownword: a function that returns ... | 1f687ee95de99c34e7b731e32bf411e84378687c | 3,621,772 |
import threading
import time
import math
def __alive_bar(config, total=None, *, calibrate=None, _cond=threading.Condition):
"""Actual alive_bar handler, that exposes internal functions for configuration of
both normal operation and overhead estimation."""
if total is not None:
if not isinstance(t... | 813af4025db0dd24838dcacfdde9572374b866bf | 3,621,773 |
from .msg import info
def read_lattice(filename='lattice.in'):
"""Reads the lattice.in file.
Args:
filename (str, optional): The filename to be read in. Default is 'lattice.in'.
Returns:
result (dict): A dictionary with the following fields:
"sizes": the range of cell sizes,
... | 0b5a1362db06053dd51a1ea97b43ae0d94b38a7e | 3,621,774 |
def counter_unit():
"""Unit symbol of a counter, motor or EPICS record"""
return unit(counter_name) | a17a3fc9769b33246f76e3dfb5b9850b8463fe04 | 3,621,776 |
from typing import Optional
def algo_parts(name: str) -> tuple[str, Optional[int]]:
"""Return a tuple of an algorithm's name and optional number suffix.
Example::
>>> algo_parts('rot13')
('rot', 13)
>>> algo_parts('whirlpool')
('whirlpool', None)
"""
base_algo = name.r... | c3231da2bc3f96091b6f07d38fdd2caa414e59a1 | 3,621,778 |
def get_page_ids_by_slug(slug, parents=None):
"""
Return all the page id according to a slug
"""
if not parents:
sql = '''
SELECT c.page_id, c.language, MAX(c.creation_date)
FROM pages_content c
WHERE c.type = 'slug' AND c.body = %s
GROUP BY c.page_id, c.language
... | e60b51247e7f06d4e4c23876451f439d97a1ccdf | 3,621,780 |
def linear_q_learning(env, max_episodes, eta, gamma, epsilon, seed=None):
"""
Initialize coefficients, Q values and random state.
Iterating through max episodes: start game.
Until game over, choose action, play action to get rewards and new features.
Use new features to select best new action.
... | 75ba9bbe08632400b94beeae07d42fa714ec3cd9 | 3,621,781 |
def get_non_zero_deplexed_samples(sample_sheet):
"""
Given a sample sheet return the names of the samples for which one
or more reads were found.
The sample sheet is assumed to have columns, ``SampleID``,
``TagRead`` and ``NumReads``. Rows whose ``SampleID`` values are
``Unassigned`` or ``Total... | fea0e622a60d69f425f24f2de76eb70184b7e5db | 3,621,783 |
def getGateEstimates():
""" Returns a list of gate estimates for the current_user's company """
if request.method == 'GET':
gates = dbSession.query(Gate)
gates = gates.filter(Gate.company_name == current_user.company_name).all()
if len(gates) == 0:
return bad_request('No gate... | 7751e1f5ef0216d919f421207d29f8f6f5d639ac | 3,621,784 |
def calculate_rsi(analysis_df, column, window):
"""
Calculates relative stength index.
Args:
analysis_df: Pandas dataframe with a closing price column
column: String representing the name of the closing price column
window: Integer representing the number of periods used in the RSI ... | 7c32751bc4aeb5583caa69397f1c19b88a208039 | 3,621,785 |
def has_slide_type(cell, slide_type):
"""
Select cells that have a given slide type
:param cell: Cell object to select
:param slide_type: Slide Type(s): '-', 'skip', 'slide', 'subslide', 'fragment', 'notes'
:type slide_type: str / set / list
:return: a bool object (True if cell should be select... | edb1323331317d53502179fe357c151a5b59af0b | 3,621,786 |
from typing import Tuple
def yolo_head(feats: tf.Tensor,
input_shape: tf.Tensor,
calc_loss: bool = False
) -> Tuple[tf.Tensor, tf.Tensor, tf.Tensor, tf.Tensor]:
"""Convert final layer features to bounding box parameters."""
# Reshape to batch, height, width, num_anchor... | 5bf1a097d2c4aafba98a996664f109f05f7ba705 | 3,621,787 |
from re import T
def shelter():
""" RESTful CRUD controller
>>> resource="shelter"
>>> from applications.sahana.modules.s3_test import WSGI_Test
>>> test=WSGI_Test(db)
>>> "200 OK" in test.getPage("/sahana/%s/%s" % (module,resource))
True
>>> test.assertHeader("Content-Type", "text/html"... | 951511dc701eddd68e8225e3b5e464eb3ddeabfb | 3,621,788 |
def clip_matrix(left, right, bottom, top, near, far, perspective=False):
"""Returns a matrix to obtain normalized device coordinates from a
frustum.
The frustum bounds are axis-aligned along x (left, right),
y (bottom, top) and z (near, far).
Normalized device coordinates are in the range [-1, 1] ... | af1d259e0b0e2f1a1b44caa86d342a6e52875518 | 3,621,789 |
def metadata(request):
"""
Add some generally useful metadata to the template context
"""
return {'display_version': getattr(settings, 'DISPLAY_VERSION', False),
'version': getattr(settings, 'VERSION', 'N/A'),
'shop_name': settings.OSCAR_SHOP_NAME,
'shop_tagline': set... | f6094bd1b769bb9a8b75020abef760490ed1d1d3 | 3,621,790 |
def engine(request):
"""Create an SQLAlchemy engine with a disposable PostgreSQL database."""
if request.param == 'postgresql':
postgresql = request.getfixturevalue('postgresql')
return create_engine('postgresql://',
poolclass=StaticPool,
... | 7793b3d8d56e4e2c067d623310872d751c61bb54 | 3,621,791 |
def rigids_to_tensor_flat12(
r: Rigids # shape (...)
) -> paddle.Tensor: # shape (..., 12)
"""Flat12 encoding: rotation matrix (9 floats) + translation (3 floats)."""
return paddle.stack(list(r.rot) + list(r.trans), axis=-1) | 88f13bd0e31de5befd4ce548bf9532218560454a | 3,621,792 |
def auto_expand(list_or_value):
"""Given a list return it, given a scalar return a corresponding broadcasted 'infinite list'"""
if isinstance(list_or_value, list):
return list_or_value
else:
class Expanded:
def __init__(self, value):
self.value = value
def __getitem__(self, i):
... | d56288adf0c0275e8539c9ba12026bb23a27fb64 | 3,621,793 |
import re
import inspect
def defined(var):
"""Returns true if the variable has already been defined. Otherwise, returns false."""
str(var)
if not isinstance(var, str):
raise Exception("defined() must be given a string")
if not re.search(r'[A-Za-z][A-Za-z0-9\_]*', var):
raise Exception... | 222ce53db53cb2fedefb29ad1a3ccbb9ef6e938e | 3,621,794 |
def add_category(
name: str, description: str = None, position: int = 0
) -> flask.Response:
"""
This is the endpoint for forum category creation. The ``forums_forums_modify`` permission
is required to access this endpoint.
.. :quickref: ForumCategory; Create a forum category.
**Example reques... | 0a5b9e94557ab4abbffc0c6ebdebf75220c574b0 | 3,621,797 |
import sqlite3
def query(x,db,v=True):
""" A function that takes in a query and returns/ prints the result"""
conn = sqlite3.connect(db)
curs = conn.cursor()
my_result = list(curs.execute(x).fetchall())
curs.close()
conn.commit()
if v is True:
print(my_result)
return my_result | 8b914224429bdfd8d167327bf6cc0e3afaf94b3c | 3,621,798 |
def build_url(selector, child_key, parent_key):
"""Return url string that's conditional to `selector` ("site" or "area")."""
if selector == "site":
return "https://%s.craigslist.org/" % child_key
return "https://%s.craigslist.org/%s/" % (parent_key, child_key) | f8f00d4f9d20c3312f2b36d014365dbcf08242bc | 3,621,799 |
import pickle
def get_data():
"""Get data in form suitable for episodic training.
Returns:
Train and test data as dictionaries mapping
label to list of examples.
"""
with tf.gfile.GFile(DATA_FILE_FORMAT % 'train', 'rb') as f:
processed_train_data = pickle.load(f)
with tf.gfile.GFile(DATA_FILE_F... | b5c53df37de518401270c59f003ac71efb5eb056 | 3,621,800 |
def svd(a, full_matrices=True, algo='svd', **kwargs):
""" ctypes wrapper for LAPACK SVD (DGESVD)
Factorizes the matrix a into two unitary matrices U and Vh and
an 1d-array s of singular values (real, non-negative) such that
a == U S Vh if S is an suitably shaped matrix of zeros whose
main diagonal ... | 6b58789fe8ef1a83cc602868aaff8d56606985d3 | 3,621,802 |
def reshape(fd: DahliaFuncDef) -> str:
"""https://tvm.apache.org/docs/api/python/relay/index.html#tvm.relay.reshape"""
data, res = fd.args[0], fd.dest
newshape = fd.attributes.get_int_tuple("newshape")
ddims = get_dims(data.comp)
rdims = get_dims(res.comp)
assert (
# See the TVM Relay A... | bbb3f1a5b9d6da3915295122a3bded891feac9db | 3,621,803 |
def convert(digits, base1, base2):
"""Convert given digits in base1 to digits in base2.
digits: str -- string representation of number (in base1)
base1: int -- base of given number
base2: int -- base to convert to
return: str -- string representation of number (in base2)"""
# Handle up to base 3... | 01638a1a356af60549f7520f1dd4f5deb7fffeca | 3,621,804 |
import requests
def _nanuq_get(url, username="", password="", logprefix=""):
"""returns an open request object to a NANUQ download"""
# nanuq has a non-standard form auth
log.info("%s GET %s (username=%s)", logprefix, url, username or "")
if username:
r = requests.post(url, data={'j_username'... | 96e7351bb452f23e87558a1257eccff99099b09b | 3,621,805 |
def initMap(llCrds,urCrds,figsize=(16,16)):
"""
Function for initializing a figure using a cartopy map projection.
Parameters
----------
llCrds : tuple
Tuple of (lat,lon) at the lower left corner of the desired
domain.
urCrds : tuple
Tuple of (lat,lon) at the up... | 16ea6ca2437ebad1e8277e53a0687ad57bb9cfc7 | 3,621,806 |
def validate(number):
"""Check if the number provided is a valid NCF."""
number = compact(number)
if len(number) != 19:
raise InvalidLength()
if number[0] not in 'AP' or not number[1:].isdigit():
raise InvalidFormat()
if number[9:11] not in (
'01', '02', '03', '04', '11',... | 90622ec2597d25de7e354a637db7bd9e733a3f21 | 3,621,807 |
def pressure_broad_coefs(Te):
"""
Defines the values of the constants :math:`a` and :math:`\\gamma` that go into the collisional broadening formula
of Salgado et al. (2017).
:param Te: Electron temperature.
:type Te: float
:returns: The values of :math:`a` and :math:`\\gamma`.
:rtype: l... | 0e5e18bd444721eab783ad499fcef6d5061129c8 | 3,621,808 |
from typing import Union
def parse_sources(sources: dict) -> Union[SourcesV1, SourcesV2, SourcesV3]:
"""Parse sources.json
Args:
sources: A dict of sources.json
Returns:
Union[SourcesV1, SourcesV2, SourcesV3]
"""
dbt_schema_version = get_dbt_schema_version(artifact_json=sources)
... | a0d7d1b2b5fed6671bea17ddb65c8da27808548c | 3,621,809 |
def _get_indices_from_highest(highest_indices):
"""Return a list of coordinates from a set of highest indices.
Parameters
----------
highest_indices : list, tuple, or numpy.ndarray
Highest indices to consider.
Returns
-------
indices : numpy.ndarray
An array of indices sort... | ecc1acf6c341c148b6edfadf7737dd6d5e3fdb4b | 3,621,810 |
def reports_ovc_rawdata(request):
"""Method to do adhoc pivot reports."""
try:
ext = 'Pivot'
# time_now = int(datetime.now().strftime('%H'))
user_id = request.user.id
report_variables = get_variables(request)
if request.method == 'POST':
ext = request.POST.get... | 2ece9fa8d6adf7136d985194efabf65b3363a516 | 3,621,811 |
def get_config(arguments=None, events=None):
"""
Retruns a pre-formatted configuration block for supervisor
"""
if arguments is None:
arguments = ''
if events is None:
events = 'PROCESS_STATE'
configuration_string = '''
[eventlistener:logstash-notifier]
command = ./logstash_not... | cf548a31393a05a4f7a474b193e5752c5406233d | 3,621,813 |
def sieve_of_eratosphenes(n: int) -> list[int]:
"""
Finds prime numbers <= n using the sieve of Eratosphenes algorithm.
:param n: the upper limit of sorted list of primes starting with 2
:return: sorted list of primes
Integers greater than 2 are considered good input that gives
meaningful ... | 4dbfdffe0ff6e360361daccdcd39fb7fb3d09a03 | 3,621,814 |
def load_test_set(
filename=DATA_FILE,
add_target=True,
target_species=DEFAULT_TARGET):
"""Load the test set"""
df = load_data(filename, add_target, target_species)
train, test = get_train_test_split(df)
return test | 2eadc2d9f7d7924463db7ae8f5874b4f1e3170a2 | 3,621,815 |
from datetime import datetime
def create_observation(host_since, property_type, room_type, accommodates,
bathrooms, bed_type, cancellation_policy, cleaning_fee,
city, host_identity_verified, instant_bookable,
review_scores_rating, zipcode, bedrooms,... | 2203afcf23fa32f1173c59284e4029ee9453bfd4 | 3,621,816 |
import unittest
def net():
"""Run all network tests"""
suite = ServiceTestSuite()
suite.addTest(unittest.makeSuite(AttributeTestCase, 'test_net'))
return suite | 0901faf9cd3d753341cb48a303df30b7fe94eaff | 3,621,820 |
def xor_decipher(text, key):
"""
Decipher a message using XOR.
text -- a list of integers corresponding to the ASCII value of characters.
key -- a list of characters used as keys.
"""
deciphered = []
key_length = len(key)
key_ascii = [ord(_k) for _k in key]
for i, _ascii in enumerate... | 99edcb7a08f9c22772305d70f5d4830828c2bbbf | 3,621,821 |
def _get_expanded_variable_list(var_list):
"""Given an iterable of variables, expands them if they are partitioned.
Args:
var_list: An iterable of variables.
Returns:
A list of variables where each partitioned variable is expanded to its
components.
"""
returned_list = []
for variable in var_l... | 4baae6fbdb145ecc09c42090fcca26298cddcd61 | 3,621,824 |
import fcntl, termios, struct, os
def get_terminal_size() -> (int, int):
"""
Get size of the terminal in symbols and lines.
:return: height (lines), width (symbols)
"""
def ioctl_GWINSZ(fd):
try:
cr = struct.unpack(
"hh", fcntl.ioctl(fd, termios.TIOCGWINSZ, "12... | c06b40c7a19268bfae85d73bbf20f295f468eeba | 3,621,825 |
import string
import random
def name_generator(size=9, chars=string.ascii_uppercase + string.digits):
"""
this method is for generating a randndom name for the downloaded files
@param size: number of random characters
@param chars: type of the random characters
"""
return ''.join(random.choice... | afe91c39ed5d985f93e1aa4ab72bf7ff7c1b75e0 | 3,621,826 |
def recovery_secret_to_ksk(recovery_secret):
"""Turn secret and salt to the URI.
>>> recovery_secret_to_ksk("0123.4567!ABCD")
'KSK@babcom-recovery-0123.4567!ABCD'
"""
if isinstance(recovery_secret, bytes):
recovery_secret = recovery_secret.decode("utf-8")
# fix possible misspellings... | a8832a9e970e4728dcb5f779fd4463abf142e69e | 3,621,827 |
import click
from datetime import datetime
def validate_end_date(ctx, param, value):
"""
Validator for the 'click' command line interface, checking whether the entered date as argument 'start_date' is
later than argument 'end_date' and 'end_date' argument is later than current date.
"""
# option w... | b1416fdc614aad53ffab537275b7ae2cb15eddce | 3,621,829 |
def transform_uppercase(val, mode=None):
"""
Convert to uppercase
<dotted>|uppercase string to uppercase
<dotted>|uppercase:force string to uppercase or raises
"""
try:
return val.upper()
except TypeError:
if mode == 'force':
raise
return v... | f043674932bf900c0654b1be64ac80b6f4ec54fa | 3,621,830 |
import glob
def get_installer_packages(installer_dirs):
"""
Returns a list of nipkg files in the provided directories.
:param installer_dirs: List of directories containing nipkgs.
:return The list of nipkg files.
"""
installers = []
for dir in installer_dirs:
packages = glob... | 60b85fdaff214d287d8673df71389159484f943a | 3,621,831 |
def get_H2_surface_density_error(co_error: np.array, inclination: int) -> np.array:
"""Calculate the error on the H2 surface density from the CO emission maps from Heracles, this follows Leroy, et al. 2008/2009
Args:
co_error (np.array): error on the CO emission in [K km/s]
inclination (int): i... | 04f1a14435d1e60ebfcd521723120739a2ee37df | 3,621,832 |
from typing import Mapping
def _copy_object(obj: Mapping):
"""
Performs a deep copy of a Mapping.
Converts to a basic dict to avoid problems with kopf Body mapping type.
Pykube expects json-serializable types, i.e. basic types.
"""
new_obj = deepcopy(dict(obj))
for key in [
"resour... | dcf1e30142469986acc95ed0b1513aeaf077dbd2 | 3,621,833 |
def dmoist_bdz(th, th_ref, p, q_v, q_cl, z, zn, thresh = 1.0e-5):
"""
Vertical Gradient of (buoyancy including cloud condensation).
Derived variable name: dmoist_bdz
MONC approximation.
This is db/dz with b = beta_t theta_l + beta_q q_t.
Note - not to be used for vertical buoyancy flux.
P... | fc369a2a9789a32ce3122f8e3a022e6b49dd895a | 3,621,834 |
def tag_list(page=None):
"""
标签列表
"""
if page is None:
page = 1
page_data = Tag.query.order_by(
Tag.addtime.desc()
).paginate(page=page, per_page=3)
return render_template('admin/tag_list.html', page_data=page_data) | 922128c0e4130e116475b17bd52fdd16fa824e0a | 3,621,835 |
from typing import Union
def _parse_handler(handler: Union[callable, object, Subscriber]):
"""Parse handler name and body.
Function accept functions, callable object and instance of Subscriber.
If Subscriber has been given, parser will extract its name and handler.
:param handler: Function or callab... | f68fc8609058b38790a3a25bc2df9653c18d8a96 | 3,621,836 |
def string_pair_list_to_dictionary_no_json(spl):
"""
Covert a mongodb_store_msgs/StringPairList into a dictionary, ignoring content
:Args:
| spl (StringPairList): The list of (key, value) to pairs convert
:Returns:
| dict: resulting dictionary
"""
return dict((pair.first, pair.s... | fdcaa23eed195d389456a6ceb0fdde2d06d932d6 | 3,621,837 |
import re
def sanitize(inStr):
"""Hide any sensitive info from the alert"""
# Key-value pairs of patterns with what to replace them with
patterns = {
"https\:\/\/oauth2\:[\d\w]{64}@gitlab\.pavlovia\.org\/.*\.git": "[[OAUTH key hidden]]" # Remove any oauth keys
}
# Replace each pattern
... | 62c55f7d0af7c458d66e426fc9366c8ec84379df | 3,621,838 |
def str2dict(s):
"""Convert a "foo=bar, blah=baz" type string into a dictionary"""
if type(s) not in (str, unicode):
s = str(s)
d = {}
for kv in [[x.strip() for x in i.split('=', 1)] for i in s.split(',')]:
if (len(kv[0]) > 0) and (len(kv[1]) > 0):
d[kv[0]] = kv[1]
retur... | 2ce80c4f0da1d0b4487f7806778c5a3e11ef78db | 3,621,839 |
def get_techniques_of_tactic(tactic, techniques):
"""Given a tactic and a full list of techniques, return techniques that
appear inside of tactic
"""
techniques_list = []
for technique in techniques:
for phase in technique['kill_chain_phases']:
if phase['phase_name'] == tact... | 15efe8788bc4e45170f9d02c452482422ec8cf9f | 3,621,840 |
def unabc(msg):
"""
Add dummy methods to a class to satisfy abstract base class constraints.
Usage::
@unabc
class NotAbstract(SomeAbstractClass):
pass
@unabc('Fake {}')
class NotAbstract(SomeAbstractClass):
pass
"""
# Handle the possibility... | 3101fe4284b2695e76a8d4481ebcf12ee1b55055 | 3,621,841 |
def extract_logic_free_variables(expression):
"""Extract variables from expression assuming it's in logic format.
Parameters
----------
expression : Expression
Returns
-------
OrderedSet
set of all free variables in the expression.
"""
efvw = ExtractFreeVariablesWa... | 4a9c846795070a2a7a20e9547a2b6f212925b801 | 3,621,842 |
import warnings
def train_val_test_split_adjacency(A, p_val=0.10, p_test=0.05, seed=0, neg_mul=1,
every_node=True, connected=False, undirected=False,
use_edge_cover=True, set_ops=False, asserts=False):
"""
Split the edges of the adjacency m... | 78bd771e0e4812e8978b3d736a69b22b6a73c938 | 3,621,844 |
def odia_to_other_lang(text: str, dest_language_code: str = "en") -> str:
"""Translate from Odia to other language"""
return _hit_google_api(text, "or", dest_language_code) | c4989c6eac300f57f9ad45da53c6bc72fade5cb0 | 3,621,846 |
def _invoke_with_properties(callable_obj, all_props, environ, prop_defs,
arg_names, **additional_args):
"""Internal version of invoke_with_properties.
The main difference is it gets passed the argument names as `arg_names`.
This allows us to reuse this logic elsewhere, without definin... | 44a5dddf460d0a22ec67c2ca7d4ac88c1a4f6679 | 3,621,847 |
def initial_time():
"""
Real Name: b'INITIAL TIME'
Original Eqn: b'1960'
Units: b'Year'
Limits: (None, None)
Type: constant
b'The initial time for the simulation.'
"""
return 1960 | 7e731a15c0fa128c5c3858d98ae2f9ac0bc04ca8 | 3,621,848 |
import pickle
def get_y_eval(dataset_id):
"""
retrieves the y value of the eval set
:param dataset_id: id of the dataset
:return: y values
"""
#
return pickle.load(open(get_dataset_folder(dataset_id) + '/y_eval.pkl', 'rb')) | 15fc4892ade6b5661f4276535f081dc989fc8f0b | 3,621,849 |
import time
from typing import OrderedDict
import inspect
import pickle
def main():
"""Scripty bits"""
t0 = time.time()
kwargs = parse_args()
if "histo_data_dir" in kwargs:
histo_data_dir = expand(kwargs["histo_data_dir"])
if basename(histo_data_dir) != "histo_data":
hist... | 17ee583dceb569e462fbadd64747ea1ab99f679a | 3,621,850 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.