content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def decay_value(base_value, decay_rate, decay_steps, step):
""" decay base_value by decay_rate every decay_steps
:param base_value:
:param decay_rate:
:param decay_steps:
:param step:
:return: decayed value
"""
return base_value*decay_rate**(step/decay_steps) | 17,900 |
def setup_flask_app(manager_ip='localhost',
driver='',
hash_salt=None,
secret_key=None):
"""Setup a functioning flask app, when working outside the rest-service
:param manager_ip: The IP of the manager
:param driver: SQLA driver for postgres (e.g.... | 17,901 |
def download_file(file_id, unique_id, credentials):
"""Downloads a file from google drive if user has been authenticated using oauth2
Args:
file_id (str): [The google drive id of the file]
unique_id (str): [The name of the video that is to be used for stored file]
Returns:
bool: [w... | 17,902 |
def scantree(path):
# type: (str) -> os.DirEntry
"""Recursively scan a directory tree
:param str path: path to scan
:rtype: DirEntry
:return: DirEntry via generator
"""
for entry in scandir(path):
if entry.is_dir(follow_symlinks=True):
# due to python2 compat, cannot use ... | 17,903 |
def join_lines(new_lines, txt):
"""Joins lines, adding a trailing return if the original text had one."""
return add_ending('\n'.join(new_lines), txt) | 17,904 |
def read_db_mysql(db_conn, tablename):
""" Read data from My SQL """
conn = db_conn
cursor = conn.cursor()
cursor.execute('SELECT * FROM %s' % tablename) | 17,905 |
def get_components_with_metrics(config):
"""
:type: config mycroft_holmes.config.Config
"""
storage = MetricsStorage(config=config)
components = []
for feature_name, feature_spec in config.get_features().items():
feature_id = config.get_feature_id(feature_name)
metrics = config... | 17,906 |
def test_show_source_option(tmpdir, capsys):
"""Ensure that --show-source and --no-show-source work."""
with tmpdir.as_cwd():
tmpdir.join("tox.ini").write("[flake8]\nshow_source = true\n")
tmpdir.join("t.py").write("import os\n")
_call_main(["t.py"], retv=1)
expected = """\
t.py:1:1... | 17,907 |
def parse_container_args(field_type: type) -> types.Union[ParamType, types.Tuple[ParamType]]:
"""Parses the arguments inside a container type (lists, tuples and so on).
Args:
field_type (type): pydantic field type
Returns:
types.Union[ParamType, types.Tuple[ParamType]]: single click-compat... | 17,908 |
def test_get_submitted_posts(scheduler, schedule):
"""Test getting submitted posts."""
scheduler.schedule = schedule
schedule.posts[0].submission_id = "cute_id_1"
schedule.posts[1].submission_id = "cute_id_2"
assert len(scheduler.get_submitted_posts()) == 2
posts = scheduler.get_submitted_pos... | 17,909 |
def decrypt_from_base64(ciphertext_bs64, decrypt_key: str , iv : str) -> str:
"""From base64 ciphertext decrypt to string.
"""
aes: AES_Turbe = AES_Turbe(decrypt_key,iv)
content_str = aes.decrypt_from_base64(ciphertext_bs64)
return content_str | 17,910 |
def download_wave_interim(path, N, W, S, E):
"""Download wave data."""
server = ECMWFDataServer()
server.retrieve({
"class": "e4",
"dataset": "interim",
"date": "2016-05-01/to/2016-08-01",
"levtype": "sfc",
"param": "229.140/230.140/232.140",
"step": "0",
... | 17,911 |
def _resize_data(image, mask):
"""Resizes images to smaller dimensions."""
image = tf.image.resize_images(image, [480, 640])
mask = tf.image.resize_images(mask, [480, 640])
return image, mask | 17,912 |
def testopen():
"""Tests that the RDF parser is capable of loading an RDF file
successfully."""
r = RDFParser(open("tests/resources/rdf/pass.rdf"))
assert r.rdf | 17,913 |
def dist_Mpc_to_geo(dist):
"""convert distance from Mpc to geometric units (i.e., metres)"""
return dist * Mpc | 17,914 |
def setup_virtualenv():
"""
Setup a server virtualenv.
"""
require('settings', provided_by=[production, staging])
run('virtualenv -p %(python)s --no-site-packages %(virtualenv_path)s' % env)
run('source %(virtualenv_path)s/bin/activate' % env) | 17,915 |
def upload_to_bucket(file_path, filename):
"""
Upload file to S3 bucket
"""
s3_client = boto3.client('s3')
success = False
try:
response = s3_client.upload_file(file_path, AWS_S3_BUCKET_NAME, filename)
success = True
except ClientError as e:
logger.error('Error at %s'... | 17,916 |
def osqueryd_log_parser(osqueryd_logdir=None,
backuplogdir=None,
maxlogfilesizethreshold=None,
logfilethresholdinbytes=None,
backuplogfilescount=None,
enablediskstatslogging=False,
... | 17,917 |
def generate_windows(image, windowsize, stride):
"""creates an generator of sliding window along the width of an image
Args:
image (2 or 3 dimensional numpy array): the image the sliding windows are created for
windowsize (int): width of the sliding window
stride (int): stepsize of the sliding
... | 17,918 |
def validate_json(value):
"""Validates a JSON snippet.
"""
try:
json.loads(value)
except:
raise ValidationError(_('Ivalid JSON syntax')) | 17,919 |
def get_filenames(data_dir, mode, valid_id, pred_id, overlap_step, patch_size):
"""Returns a list of filenames."""
if mode == 'train':
train_files = [
os.path.join(data_dir, 'subject-%d.tfrecords' % i)
for i in range(1, 11)
if i != valid_id
]
for f in train_files:
assert os.path.isfile(f), \
('... | 17,920 |
def downsample_data( data, factor, hdr ):
"""Resample data and update the header appropriately
If factor < 1, this is *upsampling*.
Use this function to just return the data and hdr parts in case you want to do further operations prior to saving.
order=3 appears to crash Python 64-bit on ... | 17,921 |
def plot_hexplot(star_pars, means, covs, chain, iter_count, prec=None,
save_dir='', file_stem='', title=''):
"""
Generates hex plot in the provided directory
Paramters
---------
star_pars : dict
'xyzuvw'
'xyzuvw_cov'
'times'
'something else...'
... | 17,922 |
def check_if_present(driver: webdriver.Firefox, selector: str):
""" Checks if element is present on page by css selector """
return bool(driver.find_elements_by_css_selector(selector)) | 17,923 |
def test_matcher_end_zero_plus(en_vocab):
"""Test matcher works when patterns end with * operator. (issue 1450)"""
matcher = Matcher(en_vocab)
pattern = [{"ORTH": "a"}, {"ORTH": "b", "OP": "*"}]
matcher.add("TSTEND", [pattern])
nlp = lambda string: Doc(matcher.vocab, words=string.split())
assert... | 17,924 |
def save(ps, save_path):
"""
Save function saves the parameters as a side effect
"""
os.makedirs(save_path, exist_ok=True)
save_file = os.path.join(save_path, "saved")
with open(save_file, "wb") as file_to_save:
pickle.dump(ps, file_to_save) | 17,925 |
def list_pdf_paths(pdf_folder):
"""
list of pdf paths in pdf folder
"""
return glob(os.path.join(pdf_folder, '*', '*', '*.pdf')) | 17,926 |
def entities(hass):
"""Initialize the test switch."""
platform = getattr(hass.components, "test.switch")
platform.init()
yield platform.ENTITIES | 17,927 |
def cmi(x, y, z, k=3, base=2):
"""Mutual information of x and y, conditioned on z
x,y,z should be a list of vectors, e.g. x = [[1.3], [3.7], [5.1], [2.4]]
if x is a one-dimensional scalar and we have four samples
"""
assert len(x)==len(y), 'Lists should have same length.'
assert k <= len(x) - 1, 'Set k smal... | 17,928 |
def test_question_shows_choices(browser: DriverAPI, registry, web_server, dbsession):
"""If question has active choices they are shown on Show screen, albeit not editable."""
from .tutorial import Question
from .tutorial import Choice
with transaction.manager:
q = Question(question_text="What ... | 17,929 |
def connected_plate():
"""Detects which plate from the PMA is connected to the device.
Returns:
FirmwareDeviceID: device ID of the connected plate. None if not detected
"""
for plate_id in (
FirmwareDeviceID.pt4_foundation_plate,
FirmwareDeviceID.pt4_expansion_plate,
):
... | 17,930 |
def plot_image(dataset, choice=None):
"""
Visual image and label
"""
if choice:
idx = int(choice)
else:
idx = random.randint(0, len(dataset))
image = dataset[idx][0]
face = int(dataset[idx][1])
mouth = int(dataset[idx][2])
eyebrow = int(dataset[idx][3])
eye = int... | 17,931 |
def islogin(_a=None):
"""
是否已经登录,如果已经登录返回token,否则False
"""
if _a is None:
global a
else:
a = _a
x=a.get(DOMAIN+"/apps/files/desktop/own",o=True)
t=a.b.find("input",{"id":"request_token"})
if t is None:
t = a.b.find("input",{"id":"oc_requesttoken"})
... | 17,932 |
def discrete_coons_patch(ab, bc, dc, ad):
"""Creates a coons patch from a set of four or three boundary
polylines (ab, bc, dc, ad).
Parameters
----------
ab : list[[float, float, float] | :class:`~compas.geometry.Point`]
The XYZ coordinates of the vertices of the first polyline.
bc : li... | 17,933 |
def w(shape, stddev=0.01):
"""
@return A weight layer with the given shape and standard deviation. Initialized with a
truncated normal distribution.
"""
return tf.Variable(tf.truncated_normal(shape, stddev=stddev)) | 17,934 |
def lr_mult(alpha):
"""Decreases the learning rate update by a factor of alpha."""
@tf.custom_gradient
def _lr_mult(x):
def grad(dy):
return dy * alpha * tf.ones_like(x)
return x, grad
return _lr_mult | 17,935 |
def get_png_string(mask_array):
"""Builds PNG string from mask array.
Args:
mask_array (HxW): Mask array to generate PNG string from.
Returns: String of mask encoded as a PNG.
"""
# Convert the new mask back to an image.
image = PIL.Image.fromarray(mask_array.astype('uint8')).convert('... | 17,936 |
def rotate90ccw(v):
"""Rotate 2d vector 90 degrees counter clockwise
"""
return (-(v[1]), v[0]) | 17,937 |
def GetListOfCellTestPointsNearestListOfPointsV5(inInputFilter, pointList):
"""for each point in the list, find the cell test point (e.g. center of
cell bounding box) which is nearest the test point. Use MPI to work
in parallel"""
thisProcessNearestCellPointList, thisProcDistSqrdList = \
GetCellsClo... | 17,938 |
def main(to_dir, from_dir):
"""Copy CWL files."""
num = copy_cwl_files(from_dir=from_dir, to_dir=to_dir)
if num > 0:
click.echo('Copied {} CWL files to "{}".'.format(num, to_dir))
else:
msg = 'No CWL files found in "{}". Copied 0 files'.format(from_dir)
click.echo(msg) | 17,939 |
def _BuildBaseMTTCmd(args, host):
"""Build base MTT cmd."""
remote_mtt_binary = _REMOTE_MTT_BINARY_FORMAT % host.context.user
remote_cmd = [remote_mtt_binary]
if args.very_verbose:
remote_cmd += ['-vv']
elif args.verbose:
remote_cmd += ['-v']
# We copy the mtt binary inside mtt_lab to remote host,
... | 17,940 |
def get_service(credentials=get_credentials()):
"""Gets GMail service, given credentials"""
return apiclient.discovery.build("gmail", "v1", credentials=credentials) | 17,941 |
def stageTweets(df_tweets, df_update):
"""This function appends downloaded tweets to the staging table."""
try:
engine = start_engine()
df_tweets.to_sql(name='tweetsstaging', con=engine, schema='tweets_db', if_exists='append', index=False)
df_update.to_sql(name='updates', con=engine, schema='tweets_db', if_exi... | 17,942 |
def test_write_config():
"""
Unit test of write_config.
"""
write_config(**config_params) | 17,943 |
def assert_almost_equal(
actual: numpy.ndarray,
desired: numpy.ndarray,
decimal: int,
err_msg: Literal["zolotarev"],
):
"""
usage.scipy: 1
"""
... | 17,944 |
def edb_client_server_info(edb: ElectrolyteDB) -> dict:
"""
Perform an operation that ensures that the `edb` fixture has a client that:
- Is able to connect to the server (non-mock), or
- Is a "convincing fake" (mock), so that test functions using `edb` can expect a realistic behavior
Additiona... | 17,945 |
def _localoffload(offline, docs, errordocs=None, debug=False):
"""
Setup the offloading of data into pickles.
Prepares data to be pickled and generates a message on how to correctly modify target data, should a misconfiguration have occurred.
Keyword arguments:
offline -- dictionary of offline ES c... | 17,946 |
def test_get_pylintrc_path(pylintrc_files, mocker):
"""Test that get_pylintrc_path finds the expected one in the hiearchy."""
search_paths, expected_path, __ = pylintrc_files
mocker.patch("pylint.config.os.path.expanduser",
return_value=search_paths[HOME_DIR])
actual_path = get_pylintrc... | 17,947 |
def convert_to_int_list(dataframe: pd.Series) -> "list[list[int]]":
"""
Takes a dataframe with a string representation of a list of ints
and converts that into a list of lists of ints
"""
result_list = []
for row in dataframe:
result_list.append([int(x) for x in row[1:-1].split(", ")])
... | 17,948 |
def test_data_no_missing_envvar_data():
"""Ensure the ENVVAR_DATA covers all entries"""
entry_names = [entry.name for entry in NavigatorConfiguration.entries]
data_names = [entry[0] for entry in ENVVAR_DATA]
assert entry_names == data_names | 17,949 |
def get_prism_daily_single(variable,
date,
return_path=False,
**kwargs):
"""Download data for a single day
Parameters
----------
variable : str
Either tmean, tmax, tmin, or ppt
date : str
The d... | 17,950 |
def handle_filestreams(list_of_contents, list_of_names):
"""
Args:
list_of_contents:
list_of_names:
"""
if len(list_of_contents) == 1:
content = list_of_contents[0]
filename = list_of_names[0]
else:
raise Exception("Multiple files not supported") # TODO
... | 17,951 |
def grid_count(grid, shape=None, interpolation='linear', bound='zero',
extrapolate=False):
"""Splatting weights with respect to a deformation field (pull adjoint).
Notes
-----
{interpolation}
{bound}
Parameters
----------
grid : ([batch], *inshape, dim) tensor
T... | 17,952 |
def check_spf_record(lookup, spf_record):
"""
Check that all parts of lookup appear somewhere in the given SPF record, resolving
include: directives recursively
"""
not_found_lookup_parts = set(lookup.split(" "))
_check_spf_record(not_found_lookup_parts, spf_record, 0)
return not not_found_l... | 17,953 |
def local_tz2() -> pytz.BaseTzInfo:
"""
Second timezone for the second user
"""
return pytz.timezone("America/Los_Angeles") | 17,954 |
def get_chemistry_info(sam_header, input_filenames, fail_on_missing=False):
"""Get chemistry triple information for movies referenced in a SAM
header.
Args:
sam_header: a pysam.Samfile.header, which is a multi-level dictionary.
Movie names are read from RG tags in this header.
... | 17,955 |
def json_catalog(request, domain='djangojs', packages=None):
"""
Return the selected language catalog as a JSON object.
Receives the same parameters as javascript_catalog(), but returns
a response with a JSON object of the following format:
{
"catalog": {
# Translat... | 17,956 |
def init_scp_large_resource_from_kwargs(resource, uri, archive, scp_host, user_dict):
"""
Method initializes scp resource from resource informations and user
credentials.
Parameters
----------
resource : str
resource name, same as LargeResource.RESOURCE_NAME
uri : str
resour... | 17,957 |
def read_global_config() -> Dict[Text, Any]:
"""Read global Rasa configuration."""
# noinspection PyBroadException
try:
return rasa.utils.io.read_yaml_file(GLOBAL_USER_CONFIG_PATH)
except Exception:
# if things go south we pretend there is no config
return {} | 17,958 |
def test_print_empty_tree():
"""
Проверка, что если в дереве нет ни одного сохраненного значения, оно распечатывается в виде "болванки".
"""
tree = NamedTree()
assert str(tree) == '<NamedTree empty object>' | 17,959 |
def test_pid_uparrow1():
"""
"""
d = bivariates['boom']
pid = PID_uparrow(d)
assert pid[((0,), (1,))] == pytest.approx(0.666666666666666667, abs=1e-4)
assert pid[((0,),)] == pytest.approx(0.0, abs=1e-4)
assert pid[((1,),)] == pytest.approx(0.0, abs=1e-4)
assert pid[((0, 1),)] == pytest.a... | 17,960 |
def get_uuid_hex(digest_size: int = 10) -> str:
"""Generate hex of uuid4 with the defined size."""
return blake2b(uuid4().bytes, digest_size=digest_size).hexdigest() | 17,961 |
def crc16(data):
"""CRC-16-CCITT computation with LSB-first and inversion."""
crc = 0xffff
for byte in data:
crc ^= byte
for bits in range(8):
if crc & 1:
crc = (crc >> 1) ^ 0x8408
else:
crc >>= 1
return crc ^ 0xffff | 17,962 |
def _unlink_f(filename):
""" Call os.unlink, but don't die if the file isn't there. This is the main
difference between "rm -f" and plain "rm". """
try:
os.unlink(filename)
return True
except OSError, e:
if e.errno not in (errno.ENOENT, errno.EPERM, errno.EACCES,errno.EROFS):... | 17,963 |
def get_member_expr_fullname(expr: MemberExpr) -> str:
"""Return the qualified name representation of a member expression.
Return a string of form foo.bar, foo.bar.baz, or similar, or None if the
argument cannot be represented in this form.
"""
if isinstance(expr.expr, NameExpr):
initial = ... | 17,964 |
def _read_dino_waterlvl_metadata(f, line):
"""read dino waterlevel metadata
Parameters
----------
f : text wrapper
line : str
line with meta dictionary keys
meta_dic : dict (optional)
dictionary with metadata
Returns
-------
meta : dict
dictionary with metad... | 17,965 |
def enumerated_endec(v, x):
"""Pass the value to Enumerated, construct a tag from the hex string,
and compare results of encode and decoding each other."""
if _debug: enumerated_endec._debug("enumerated_endec %r %r", v, x)
tag = enumerated_tag(x)
if _debug: enumerated_endec._debug(" - tag: %r, %... | 17,966 |
def walk_files( source, paths ):
"""
accept a list of files and/or directories and yeild
each file name. recursivley drops into each directory found looking
for more files.
"""
paths = [ (p,None) for p in paths ]
while len(paths):
path,base = paths.pop(0)
if not base:
... | 17,967 |
def async_get_url(
hass: HomeAssistant,
*,
require_ssl: bool = False,
require_standard_port: bool = False,
allow_internal: bool = True,
allow_external: bool = True,
allow_cloud: bool = True,
allow_ip: bool = True,
prefer_external: bool = False,
prefer_cloud: bool = False,
) -> st... | 17,968 |
def validate_local_model(models_path: str, model_id: str) -> bool:
"""Validate local model by id.
Args:
models_path: Path to the models folder.
model_id: Model id.
"""
model_correct = True
model_path = os.path.join(models_path, model_id)
if not os.path.exists(model_path... | 17,969 |
def strip(prefix: Seq, seq: Seq, partial=False, cmp=NOT_GIVEN) -> Iter:
"""
If seq starts with the same elements as in prefix, remove them from
result.
Args:
prefix:
Prefix sequence to possibly removed from seq.
seq:
Sequence of input elements.
partial:
... | 17,970 |
def test_table_model():
"""Get a table model instance for each test function."""
# Create the device under test (dut) and connect to the database.
dut = RAMSTKOpStressTable()
yield dut
# Unsubscribe from pypubsub topics.
pub.unsubscribe(dut.do_get_attributes, "request_get_opstress_attributes")... | 17,971 |
def _read_unicode_table(instream, separator, startseq, encoding):
"""Read the Unicode table in a PSF2 file."""
raw_table = instream.read()
entries = raw_table.split(separator)[:-1]
table = []
for point, entry in enumerate(entries):
split = entry.split(startseq)
code_points = [_seq.de... | 17,972 |
def runner():
"""Provides a command-line test runner."""
return CliRunner() | 17,973 |
def matsubara_exponents(coup_strength, bath_broad, bath_freq, beta, N_exp):
"""
Calculates the exponentials for the correlation function for matsubara
terms. (t>=0)
Parameters
----------
coup_strength: float
The coupling strength parameter.
bath_broad: float
A parameter cha... | 17,974 |
def reverse(array):
"""Return `array` in reverse order.
Args:
array (list|string): Object to process.
Returns:
list|string: Reverse of object.
Example:
>>> reverse([1, 2, 3, 4])
[4, 3, 2, 1]
.. versionadded:: 2.2.0
"""
# NOTE: Using this method to reverse... | 17,975 |
def compute_segregation_profile(gdf,
groups=None,
distances=None,
network=None,
decay='linear',
function='triangular',
precomput... | 17,976 |
def calculate_lbp_pixel(image, x, y):
"""Perform the LBP operator on a given pixel.
Order and format:
32 | 64 | 128
----+-----+-----
16 | 0 | 1
----+-----+-----
8 | 4 | 2
:param image: Input image
:type: numpy.ndarray
:param x: ... | 17,977 |
def test_gradient_sparse_var():
"""
https://www.tensorflow.org/beta/guide/effective_tf2
"""
target = tf.constant([[1., 0., 0.], [1., 0., 0.]])
v = tf.Variable([0.5, 0.5])
x = tx.Lambda([],
fn=lambda _: tf.SparseTensor([[0, 0], [1, 1]], v, [2, 3]),
n_units=3,... | 17,978 |
def get_setup_and_moves(sgf_game, board=None):
"""Return the initial setup and the following moves from an Sgf_game.
Returns a pair (board, plays)
board -- boards.Board
plays -- list of pairs (colour, move)
moves are (row, col), or None for a pass.
The board represents the posi... | 17,979 |
def add_timeseries(
platform: Platform, server: str, dataset: str, constraints
): # pylint: disable=too-many-locals
"""Add datatypes for a new dataset to a platform.
See instructions in Readme.md"""
e = ERDDAP(server)
info = pd.read_csv(e.get_info_url(dataset, response="csv"))
info_vars = info... | 17,980 |
def help_text_metadata(label=None, description=None, example=None):
"""
Standard interface to help specify the required metadata fields for helptext to
work correctly for a model.
:param str label: Alternative name for the model.
:param str description: Long description of the model.
:param exa... | 17,981 |
def conv1d_stack(sequences, filters, activations, name=None):
"""Convolve a jagged batch of sequences with a stack of filters.
This is equivalent to running several `conv1d`s on each `sequences[i]` and
reassembling the results as a `Jagged`. The padding is always 'SAME'.
Args:
sequences: 4-D `Jagged` ten... | 17,982 |
def dh_mnthOfYear(value, pattern):
"""
Helper for decoding a single integer value.
The value should be >=1000, no conversion,
no rounding (used in month of the year)
"""
return dh_noConv(value, pattern, _formatLimit_MonthOfYear[0]) | 17,983 |
def build_team(datafile, salary_col, position_col, prediction_col, cap=60000, legal_teams=None):
"""
Construct teams from a set of prediction data
:param str datafile: saved prediction data (pickle file)
:param str salary_col: name of salary column
:param str position_col: name of position column
:param str... | 17,984 |
def serialize_remote_exception(failure_info):
"""Prepares exception data to be sent over rpc.
Failure_info should be a sys.exc_info() tuple.
"""
tb = traceback.format_exception(*failure_info)
failure = failure_info[1]
kwargs = {}
if hasattr(failure, 'kwargs'):
kwargs = failure.kw... | 17,985 |
def ai_turn(board: Board, n: int, player: int) -> None:
"""Process ai's turn."""
print("(AI's turn.)")
non_sym_enemy_pawns = get_non_sym_pawns(board, n, player)
# if AI plays the very first turn, put pawn at center of board
if board == new_board(n):
x = (n-1) // 2
y = x
# othe... | 17,986 |
def build_eval_graph(features, model):
"""
builds evaluation graph
"""
_params = {}
logger.debug("building evaluation graph: %s.", _params)
with tf.variable_scope("loss"):
loss = tf.losses.sigmoid_cross_entropy(multi_class_labels=tf.expand_dims(features["sentiment"], axis=1),
... | 17,987 |
def in_common(routes):
"""routes is a list of lists, each containing a route to a peer."""
r = []
branch = False
for n in izip_any(*routes): #itertools.izip(*routes):
# strip dead nodes
f = [i for i in n if i != '*']
# ignore all dead nodes
if len(f) == 0:
c... | 17,988 |
def process_polygon(coordinates):
"""Pass list of co-ordinates to Shapely Polygon function and get polygon object"""
return Polygon(coordinates) | 17,989 |
def split_function(vector, column, value):
"""
Split function
"""
return vector[column] >= value | 17,990 |
def merge_ribo_files(destination_file, source_file_list):
"""
Merges the experiments in the given source files and writes
the result in the destination file.
The ribo files need to be compatible
(same left / right span, same metagene radius, same reference)
Because of the compatibility, parame... | 17,991 |
def blackwell(Sv, theta, phi, r,
r0=10, r1=1000,
tSv=-75, ttheta=702, tphi=282,
wtheta=28 , wphi=52):
"""
Detects and mask seabed using the split-beam angle and Sv, based in
"Blackwell et al (2019), Aliased seabed detection in fisheries acoustic
data". Comple... | 17,992 |
def test_1D_rows_in_simplex_invariant():
"""Test 1D rows in simplex unchanged."""
n_features = 1
n_samples = 15
X = np.ones((n_samples, n_features))
projection = simplex_project_rows(X) # pylint: disable=no-value-for-parameter
assert np.all(projection == X) | 17,993 |
def setWindowRectangle(x, y=None, w=None, h=None, mngr=None, be=None):
""" Position the current Matplotlib figure at the specified position
"""
if y is None:
y = x[1]
w = x[2]
h = x[3]
x = x[0]
if mngr is None:
mngr = plt.get_current_fig_manager()
be = matplo... | 17,994 |
def _excitation_operator( # pylint: disable=invalid-name
edge_list: np.ndarray, p: int, q: int, h1_pq: float
) -> SparsePauliOp:
"""Map an excitation operator to a Pauli operator.
Args:
edge_list: representation of graph specifying neighboring qubits.
p: First Fermionic-mode index.
q: Se... | 17,995 |
def quota():
"""Show current youtube calculated quota usage."""
limit = ConfigManager.get(Provider.youtube).data["quota_limit"]
usage = YouService.get_quota_usage()
pt_date = YouService.quota_date(obj=True)
next_reset = timedelta(
hours=23 - pt_date.hour,
minutes=59 - pt_date.minute... | 17,996 |
def send_message( message, node, username, password, resource, max_attempts=1 ):
""" broadcast this message thru lvalert """
tmpfilename = "tmpfile.json"
tmpfile = open(tmpfilename, "w")
tmpfile.write( message )
tmpfile.close()
cmd = "lvalert_send -a %s -b %s -r %s -n %s -m %d --file %s"%(user... | 17,997 |
def test_default_contribution():
"""
verify DEFAULT_CONTRIBUTION is an InitialContribution
with a starting_value of 1
"""
assert DEFAULT_CONTRIBUTION.get_contribution_for_year(0) == 10000
assert DEFAULT_CONTRIBUTION.get_contribution_for_year(1) == 0 | 17,998 |
def create_bcs(field_to_subspace, Lx, Ly, solutes,
V_boundary,
enable_NS, enable_PF, enable_EC,
**namespace):
""" The boundary conditions are defined in terms of field. """
boundaries = dict(wall=[Wall()])
bcs = dict(
wall=dict()
)
bcs_pointwise... | 17,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.