content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_filter_institution(add_text, add_citation, add_institution):
"""
Filter by institution.
"""
t1 = add_text()
t2 = add_text()
t3 = add_text()
i1 = add_institution()
i2 = add_institution()
for i in range(3):
c = add_citation(text=t1)
Institution_Document.cre... | 5,295,700 |
def ma(method, series, ma_period):
"""MA均线,直接调用pandas_ma的均线方法"""
return ta.ma(method, series, length=ma_period, min_periods=1) | 5,295,701 |
def test_vectorization_series_to_panel_proba(method, mtype):
"""Test that forecaster vectorization works for Panel data, predict_proba.
This test passes Panel data to the ARIMA forecaster which internally has an
implementation for Series only, so the BaseForecaster has to vectorize.
"""
n_instances... | 5,295,702 |
def update_db(ml_model, participation_type, heavy_genes):
"""
Update database based on heavy_genes. An exception will be raised
if any error is detected.
"""
for sig_name, genes_weights in heavy_genes.items():
try:
signature = Signature.objects.get(name=sig_name, mlmodel=ml_mod... | 5,295,703 |
def test_check_the_bucket():
"""test the bucket function."""
from man_in_west import check_the_bucket
test_value = check_the_bucket(['stone', 'stone', 'gold', 'stone'])
assert test_value == True | 5,295,704 |
def resnet152(num_classes, pretrained=False, **kwargs):
"""Constructs a ResNet-152 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
encoder = ResNetEncoder(Bottleneck, [3, 8, 36, 3])
if pretrained:
encoder.load_state_dict(model_zoo.load_url(model_u... | 5,295,705 |
def request_server_option():
"""
Is used to request the option and prints it.
Returns
-------
option: int
The option that has to be returned
"""
colors = decorators.Colors()
option = 0
try:
option = int(input(f"{colors.OK}Select what do you want to do: {colors.ENDC}"... | 5,295,706 |
async def get_all_actors(
details: bool = False, sw: ServiceWorker = Depends(get_sw)
) -> GenResponse[List[Union[ActorSimpleOut, ActorBase]]]:
"""
Retrieve all actors. Choice between 2 response types. With details or not (default: false).
**Without details:**
- registered_name
- public_... | 5,295,707 |
def getRectangles(conn, image):
"""
Returns a list of (x, y, width, height, zStart, zStop, tStart, tStop) of
each rectangle ROI in the image
"""
rois = []
roiService = conn.getRoiService()
result = roiService.findByImage(image.id, None)
for roi in result.rois:
x = None
... | 5,295,708 |
def _parse_rptfiles_from_log(log_filename):
"""Parses Red stdout log and returns a list with
the names of output files with repeat coordinates"""
rpt_files = []
try:
logfile = open(log_filename)
except OSError as error:
print("# ERROR: cannot open/read file:", log_filename, error)
... | 5,295,709 |
def test_str():
"""str(Schedule) -> str"""
schedule = Schedule([
TimeRange(Time(1000), Time(2000)),
TimeRange(Time(2500), Time(3000))
])
assert str(schedule) == "Sunday, 16:40 - Monday, 9:20; Monday, 17:40 - Tuesday, 2:00" | 5,295,710 |
def plot_rates(reaction):
"""Function to plot k(t) as a function of time
Args:
reaction representing a Reaction object
Returns:
None
"""
if hasattr(reaction, 'model'):
rates = reaction.rates
with rc_context(fname=rc_fname):
for i, column in enumerate(rates):
... | 5,295,711 |
def IRONMAN_user(user):
"""helper to determine if user is associated with the IRONMAN org"""
# NB - not all systems have this organization!
iron_org = Organization.query.filter_by(name='IRONMAN').first()
if iron_org:
OT = OrgTree()
for org_id in (o.id for o in user.organizations if o.id)... | 5,295,712 |
def parse_date(text):
""" Attempts to parse date from text. Returns None on failure.
"""
result = dateparser.parse(text.strip())
if (result is not None) and hasattr(result,'date'):
return result.date()
else:
print("Could not parse %s as date. Returning None."%text)
return | 5,295,713 |
def train_model(lrmodel, X, Y, devX, devY, devscores, verbose=0, epochs=100):
"""
Train model, using pearsonr on dev for early stopping
"""
done = False
best = -1.0
r = np.arange(1,6)
while not done:
# Every 300 epochs, check Pearson on development set
lrmodel.fit(X, Y,
... | 5,295,714 |
def _get_current_time():
"""Gets the current timestamp."""
return datetime.datetime.now() | 5,295,715 |
def controller_put(id):
"""
Thing Manager Data Handler for PUT requests # Use type to know the serialization
"""
# Get the elements of the request
service = Service(request, id) # Call processRDF
service.put()
return 'put' | 5,295,716 |
def positionalencoding2d(pos_embed_dim, height, width):
"""
:param pos_embed_dim: dimension of the model embeddings
:param height: height of the positions
:param width: width of the positions
:return: height * width * pos_embed_dim matrix
"""
if pos_embed_dim % 4 != 0:
raise ... | 5,295,717 |
def gen_homedir(username, usertype):
"""Construct a user's home directory path given username and usertype."""
if usertype in ('member', 'associat'):
letter = username[0] + os.sep
else:
letter = ''
return '%s/%s/%s%s' % (dir_home, usertype, letter, username) | 5,295,718 |
def starred(ctx):
"""List all categories"""
pc = PocketCast(ctx.obj["email"], ctx.obj["password"])
print(json.dumps(pc.categories, cls=PocketcastsJsonEncode, indent=4)) | 5,295,719 |
def delete_transactions():
"""
Delete operation: delete any row not present in the last snapshot
"""
# Get all ppr_raw_all transaction ids
raw_transaction_ids = session.query(PprRawAll.transaction_id)
# Filter all the ppt_clean_all table transactions that are not present in the ppr_raw_all tabl... | 5,295,720 |
async def test_entity_id_update(hass, mqtt_mock):
"""Test MQTT subscriptions are managed when entity_id is updated."""
registry = mock_registry(hass, {})
mock_mqtt = await async_mock_mqtt_component(hass)
assert await async_setup_component(hass, camera.DOMAIN, {
camera.DOMAIN: [{
'pla... | 5,295,721 |
def test_get_header():
""" Test of the get header function of the DataTable Class """
test_dictionary={'Data_Description':{'x':'X Distance in microns.',
'y':'y Distance in microns.','Notes':'This data is fake'},'Data':[[1,2],[2,3]]}
new_table=DataTable(**{'data_dictionary':test_dictionary})
header=n... | 5,295,722 |
def main():
"""Convert json file(s) to the project format standards"""
logging.basicConfig(level=logging.WARNING) # WARNING or DEBUG
parser = argparse.ArgumentParser()
parser.add_argument("path", help="path to data repository")
args = parser.parse_args()
category_paths, video_paths = get_json_f... | 5,295,723 |
def config_parser(p, sub=False):
"""Configure the command line arguments passed the reconstruct CLI command.
Args:
p (ArgumentParser): The argument parser
sub (Optional[bool]): True if this is a resources subparser
"""
# Subparser info
if sub:
p = p.add_parser(
'... | 5,295,724 |
def sorted_list_to_BST(head: ListNode) -> TreeNode:
"""
- can have an empty head
Assumptions:
- values of the linked list are integers
Input: head = ListNode(-10)
list = [-10,-3, 0, 5, 9]
^ ^ ^ ^
Intuition:
- recursively split the linke... | 5,295,725 |
def conv3x3(in_planes: int, out_planes: int, stride: int = 1, groups: int = 1, dilation: int = 1) -> nn.Conv1d:
"""3x3 convolution with padding"""
return nn.Conv1d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=dilation, groups=groups, bias=False, dilation=dilation) | 5,295,726 |
def short_desc(event, words=25, strip_html=False):
"""Takes an event object and returns a shortened description."""
if event.short_description:
description = event.short_description
else:
description = event.description
if strip_html:
description = unhtml(description)
return ... | 5,295,727 |
def ja_to_arabic(s: str, enable_validation: bool = True, accept_daiji: bool = True) -> int:
"""convert japanese number to arabic number
Args:
s (str): number in japanese format
enable_validation (bool, optional): Whether to enable validation or not. Defaults to True.
accept_daiji (bool,... | 5,295,728 |
def sec_group_delete(cloud_name, sec_group_ids, dry_run=False):
""" This function takes a list of security group and delete them if dry_run
is False.
"""
conn = openstack.connect(cloud=cloud_name)
if sec_group_ids:
if dry_run:
logger.info("DRY RUN: Security group to delete: %... | 5,295,729 |
def shades_of_jop():
"""Return a pretty colour."""
c1 = random.randint(127, 255)
c2 = random.randint(0, 127)
c3 = random.randint(0, 255)
return tuple(random.sample([c1, c2, c3], 3)) | 5,295,730 |
def _step(context, value, dropdown):
"""
:type context: HackedContext
"""
element = context.driver.simple_find(dropdown)
assert element, u'No dropdown found that matched "{}"'.format(dropdown)
select_element = Select(element)
select_element.select_by_value(value) | 5,295,731 |
def check(func=None, *, dt='', n=0):
""" A Decorator function that checks if the arguments are of the correct type an the right amount
n: --> number of arguments
dt: --> Data types of the arguments
"""
if func is None:
return partial(check, dt=dt, n=n)
@wraps(func)
def check... | 5,295,732 |
def sigmoid(z):
"""The sigmoid function."""
return 1.0/(1.0+np.exp(-z)) | 5,295,733 |
def genDynamicsComp(mirList, blkFlag=True, printFigs = False, genNum = 0):
"""Plot all dynamic responses from generators
does not block by default - blkFlag ignored
"""
import matplotlib.pyplot as plt
import numpy as np
import psltdsim as ltd
plt.rcParams.update({'font.size': 9}) # used to s... | 5,295,734 |
def lambda_handler(event, context):
"""Sample pure Lambda function
Parameters
----------
event: dict, required
API Gateway Lambda Proxy Input Format
Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-fo... | 5,295,735 |
def _final_frame_length(header, final_frame_bytes):
"""Calculates the length of a final ciphertext frame, given a complete header
and the number of bytes of ciphertext in the final frame.
:param header: Complete message header object
:type header: aws_encryption_sdk.structures.MessageHeader
:param ... | 5,295,736 |
async def main():
"""
The async main method.
Connects to a node and requests a single sweep to be performed. Prints the result to stdout.
"""
# Connect to the node.
async with await ncplib.connect(NODE_HOST) as connection:
# Send a single DSPC command to the node.
response = con... | 5,295,737 |
def real2complex(input_data):
"""
Parameters
----------
input_data : row x col x 2
Returns
-------
output : row x col
"""
return input_data[..., 0] + 1j * input_data[..., 1] | 5,295,738 |
def fileConfig(fname):
"""
Read the logging configuration from a ConfigParser-format file. This can
be called several times from an application, allowing an end user the
ability to select from various pre-canned configurations (if the
developer provides a mechanism to present the choices and load th... | 5,295,739 |
def get_metrics(
resource: celtypes.MapType, request: celtypes.MapType
) -> celtypes.Value:
"""
Reach into C7N and make a statistics request using the current C7N filter.
This builds a request object that is passed through to AWS via the :func:`get_raw_metrics`
function.
The ``request`` parame... | 5,295,740 |
def test_api_user_login():
""" Test user login with good data
"""
url = helper.api.user.create.auth_url
user = helper.api.user.create.current
data = {"id": user["username"], "password": user["password"]}
response = requests.post(url=url, headers=None, json=data)
result = assert_api_success(r... | 5,295,741 |
def test_create_user_db(prepare_create_user):
"""Ensure a user is correctly created in the database."""
user_id = uuid.uuid4().bytes
username = prepare_create_user
password_hash = bcrypt.hashpw(TEST_USERS[0][1].encode(), bcrypt.gensalt())
create_user_db(user_id, username, password_hash)
assert i... | 5,295,742 |
def dy_static_file_server_dynamic_sidecar_service(
docker_registry: str, node_meta_schema: Dict
) -> Dict[str, str]:
"""
Adds the below service in docker registry
itisfoundation/dy-static-file-server-dynamic-sidecar
"""
return _pull_push_service(
"itisfoundation/dy-static-file-se... | 5,295,743 |
def check_is_paired(df, subject, group):
"""
Check if samples are paired.
:param df: pandas dataframe with samples as rows and protein identifiers as columns (with additional columns 'group', 'sample' and 'subject').
:param str subject: column with subject identifiers
:param str group: column with ... | 5,295,744 |
def norm_mac(mac):
"""Normalize a MAC Address from the pypowervm format to the neutron format.
That means that the format will be converted to lower case and will have
colons added.
:param mac: A pypowervm mac address. E.g. 1234567890AB
:returns: A mac that matches the standard neutron format.
... | 5,295,745 |
def hyperellipsoid(P, y=None, z=None, pvalue=.95, units=None, show=True, ax=None):
"""
Prediction hyperellipsoid for multivariate data.
The hyperellipsoid is a prediction interval for a sample of a multivariate
random variable and is such that there is pvalue*100% of probability that a
new observat... | 5,295,746 |
def get_mesh_laplacian_matrix_igl(mesh, fix_boundaries=True):
"""
Gets the laplace operator of the mesh
Parameters
----------
mesh: :class: 'compas.datastructures.Mesh'
fix_boundaries: bool
Returns
----------
:class: 'scipy.sparse.csr_matrix'
sparse matrix (dimensions: #V x... | 5,295,747 |
def qsgd_compress(t, pnorm="inf", quan_bits=8):
"""
Quantize float32 into uint8 using QSGD algorithm.
Arguments:
* `t` - Input PyTorch CUDA Tensor to be quantized.
* `pnorm` - Order of norm used for QSGD compression. Default value is `inf`.
* `quan_bits` - Number of quantization bit... | 5,295,748 |
def img_path(img):
""" Get absolute path to img resource, works for dev and for PyInstaller """
return path.join(resource_path('img'), img) | 5,295,749 |
def write_union(writers_schema, datum, encoder):
"""
A union is encoded by first writing a long value indicating
the zero-based position within the union of the schema of its value.
The value is then encoded per the indicated schema within the union.
"""
selected_schema = None
index_of_sch... | 5,295,750 |
def permission_denied(request, exception, *args, **kwargs):
"""
Catch all 403 - Forbidden/Permission Denied
"""
return HttpResponseForbidden(**exception_response(request, 400, exception)) | 5,295,751 |
def generate_io_files(gtc_paths, output_vcf_path, manifest_file):
"""
Generate input/output files for processing
Args:
gtc_paths (list(string)) : List of GTC files to process, may be None
output_vcf_path (string) : Path to host output VCF files
manifest_file (string) : Path to manif... | 5,295,752 |
def test_download() -> None:
"""Binary can be downloaded"""
binary = random.choice(BINARIES)
assert binary.path.exists()
binary.path.unlink()
assert not binary.path.exists()
binary.download()
assert binary.path.exists() | 5,295,753 |
def validate_callable_args(value: Any, n_args: int, name: str) -> None:
"""Check that an object is a callable taking a given number of arguments."""
if not callable(value):
raise TypeError(f"'{name}' must be callable.")
if len(signature(value).parameters) != n_args:
raise ValueError(f"'{name... | 5,295,754 |
def get_host_os():
"""Determines the name of the host operating system"""
import rospkg.os_detect
os_detector = rospkg.os_detect.OsDetect()
return (os_detector.detect_os())[0] | 5,295,755 |
def ascii(object: object) -> str:
"""ascii."""
return repr(object) | 5,295,756 |
def perc(tags):
"""This function returns the ratio of the total of tags in repository
Args:
tags (List): Tags that are in the repository
Returns:
sum_of_perc*100 [float]:
"""
sum_of_perc=0
for tag in tags:
# print(tag)
if tag in store_tag:
sum_... | 5,295,757 |
def encode_labelmap(colour_img, colourlabelmap):
"""
Takes a colour image, where each colour represents one specific label-class and replaces
the colour value with label ids. The mapping is defined by array `colourlabelmap`.
"""
colour_img = colour_img.astype(int)
labels = np.zeros((colour_img.s... | 5,295,758 |
def _ddpg_demos(demos_path, agent, memory, algo='DDPG', lim_exp_samples=10000):
"""Use demonstrations with DDPG or IMIT.
Assumes we populate the buffer first, and then we are done w/teacher
samples. We can 'tell' the memory so it doesn't overwrite info.
See `gym-cloth/analysis/check_demo_data.py` for ... | 5,295,759 |
def create_bucket(s3, bucket_name, region_name=None):
"""
Purpose:
Create an S3 Bucket by name
Args:
s3 (S3 Resource Object): S3 Object owning the Bucket
bucket_name (String): Name of bucket to return
region_name (String): Region to create bucket in
Return:
N/A
... | 5,295,760 |
def _calc_intersection_of_gamut_and_lines(
cl_point, cl_src, l_focal, c_focal, hue):
"""
gamut boundary と Lines の交点を求める。
Parameters
----------
cl_point : array_like (2d array)
gamut boundary data(Chroma, Lightness)
cl_src : array_like (2d array)
src chroma-lightness poin... | 5,295,761 |
def check_combinations3_task(infiles, outfile,
prefices,
subpath,
subdir):
"""
Test combinations with k-tuple = 3
"""
with open(outfile, "w") as outf:
outf.write(prefices + ",") | 5,295,762 |
def build_json_sensor_file(xlsx_ffp, json_ffp):
"""
Converts the xlsx sensor file into a json file.
:param xlsx_ffp: full file path to xlsx sensor file
:param json_ffp: full file path to the output json sensor file
:return: None
"""
si = _read_xlsx_sensor_file(xlsx_ffp)
para = json.dump... | 5,295,763 |
def check_timestamp(timestamp):
"""Check if the string contains proper timestamp value.
The following four formats are supported:
2017-07-19 13:05:25.041688
2017-07-17T09:05:29.101780
2017-07-19 13:05:25
2017-07-17T09:05:29
"""
is_string(timestamp)
# some attributes contains timest... | 5,295,764 |
def sol_rad_from_sun_hours(dl_hours, sun_hours, et_rad):
"""
Calculates incoming solar (or shortwave) radiation [MJ m-2 day-1]
(radiation hitting a horizontal plane after scattering by the atmosphere)
from relative sunshine duration based on FAO equations 34 and 35.
If measured radiation data a... | 5,295,765 |
def compute_corrected_dhf(mp_entry: ComputedEntry) -> float:
"""
Compute corrected :math:`\\Delta H_f(0K)` in ev/atom for a material in
the Materials Project.
We apply two corrections as follows:
1. Elemental contributions as used in the Materials Project.
2. For carbonates, we apply a correct... | 5,295,766 |
def tmux(ctx):
"""
Show some informantion in your tmux status.
Output for tmux's status-right. As in, put this in ~/.tmux.conf::
set-option -g status-utf8 on
set-option -g status-fg green
set -g status-right '#(carml tmux)'
set -g status-interval 2
"""
cfg = ctx.obj... | 5,295,767 |
def makefleetopts():
""" create option parser for events. """
parser = optparse.OptionParser(usage='usage: %prog [options] [list of bot names]', version=version)
parser.add_option('', '--apiport', type='string', default=False, dest='apiport', help="port on which the api server will run")
parser.add_opti... | 5,295,768 |
def collect_clusteroperator_relatedobjects():
"""
Returns a list of every namespace listed as a relatedObject by every clusterOperator. This captures
managed namespaces that aren't defined in the OCP manifests.
"""
co_namespaces = []
try:
result = subprocess.run(["oc", "get", "co", "-o",... | 5,295,769 |
def main():
"""Main function"""
# Hyper-parameters
input_size = 1
output_size = 1
num_epochs = 60
learning_rate = 0.001
# Toy dataset
x_train = tf.constant(
[
[3.3],
[4.4],
[5.5],
[6.71],
[6.93],
[4.168],
... | 5,295,770 |
def write_summarize_taxa(summary, header, output_fp, delimiter=';', transposed_output=False):
""" """
# Fixing headers
#pattern = compile('\W')
#header = [sub(pattern, '.', label) for label in header]
if transposed_output:
# transposing the summary
summary = [[r[col] for r in summ... | 5,295,771 |
def InitSharedStorage():
"""
Shared vars
"""
'''
All the methods in Python threading.events are atomic operations.
https://docs.python.org/3/library/threading.html
'''
SharedEvents = {}
SharedEvents['update'] = threading.Event()
SharedEvents['update'].clear() # not upd... | 5,295,772 |
def fetch():
"""Search the catalog using STAC format.
Fetch a link from the catalog
Args:
query parameter:
api_key, used to filter query results, must have READ:* or
READ:[catalog] access to get results from that catalog.
body parameters include:
cat... | 5,295,773 |
def translate_mav(wxdata: MavData, units: Units) -> List[MavPeriodTrans]:
"""Returns translations for a TafData object"""
data = []
for line in wxdata.forecast:
_data = _gfs_shared(line, units, MavPeriodTrans)
return data | 5,295,774 |
def test_lindbladian_superop_loc_deph_correct(dims, deph_rate, exp):
"""
Tests that the correct dephasing Lindbladian superoperator
is constructed for the number of sites N.
"""
dyn = 'local dephasing lindblad'
superop = lind.lindbladian_superop(dims, dynamics_model=dyn,
... | 5,295,775 |
def plot_task_structure(task_ranges=None, event_lines=None, range_colors=None, line_colors=None,
range_kwargs={}, event_kwargs={}, ax=None, **plt_kwargs):
"""Plot task structure, shaded ranges of event durations, and lines of point events.
Parameters
----------
task_ranges : lis... | 5,295,776 |
async def twitter(ctx):
"""sends the link to the twitter in chat!"""
await ctx.send('https://twitter.com/pythonexplained') | 5,295,777 |
def test__validate_assortativity():
"""Testing validation of assortativity attribute."""
# assortativity must be either 'positive' or 'negative'
invalid_assortativity = 'invalid_assortativity'
with nose.tools.assert_raises(AttributeError):
mod = model.AssortativeMatchingModelLike()
mod... | 5,295,778 |
def detect_serial_devices():
""" detect correct serial devices and
return tuple with devices
https://stackoverflow.com/questions/24214643/python-to-automatically-select-serial-ports-for-arduino
"""
pass | 5,295,779 |
def main():
"""
This comand line utility attaches a SageMaker Notebook to either an existing EMR cluster or
attaches the notebook to an EMR cluster after creating it.
Arguments:
--emrClusterId, -e: The EMR cluster JobFlowID if the cluster is already running. It ignores all other parameters.... | 5,295,780 |
def train_agent_fit_single_batch(args: Namespace,
model: Agent,
dataloaders: dict,
opt: Optimizer,
scheduler: _LRScheduler,
acc_tolerance: float = 1.0,
... | 5,295,781 |
def specific_heat(mat):
"""Calculate specifc heat"""
cw = 4183
mr = mat['m_heat']
mw = mat['m_w']
Tr = mat['Tr']
Tw = mat['Tw']
Te = mat['Te']
return (mw * cw * (Te - Tw)) / (mr * (Tr - Te)) | 5,295,782 |
def get_first_day(histories: pd.DataFrame) -> pd.Timestamp:
"""
get_first_day gets the first day of the histories DataFrame in a way that is robust to outliers - for some
reason, a small number of user summaries are very far into the past or future
"""
return histories.day.nsmallest(50).iloc[-1] | 5,295,783 |
def netlist_from_yaml(
yaml: str,
*,
models: Optional[Models] = None,
settings: Optional[Settings] = None,
default_models=None,
) -> Tuple[Netlist, Models]:
"""Load a sax `Netlist` from yaml definition and a `Models` dictionary"""
default_models = default_sax_models if default_models is Non... | 5,295,784 |
def inner(A, B):
"""Inner product of matrix A with matrix B.
Parameters
----------
A : ndarray
First matrix of the inner product.
B : ndarray
Second matrix of the inner product.
Returns
-------
result : ndarray
Result of the inner product.
Examples
---... | 5,295,785 |
async def chance(ctx: commands.Context, risk: Optional[float]):
"""Sets or display the dadjoking risk."""
gid = ctx.guild.id
if risk is None:
await ctx.send(f"ℹ️ Current risk of dadjoking is `~{joke_chance.get(gid):.2%}`.")
return
try:
joke_chance.set(gid, risk)
await ct... | 5,295,786 |
def _parse_series(
study: xml.etree.ElementTree.Element,
) -> xml.etree.ElementTree.Element:
"""Get series xml element from study xml element."""
expected_length = 3 if len(study) == 7 else 4
return _check_xml(study[5], "series", expected_length) | 5,295,787 |
def insertion_sort(a: list[int], debug=False) -> list[int]:
"""
Time complexity: O(n^2)
"""
if debug:
print("insertion sort")
arr = a.copy()
n = len(arr)
for i in range(1, n):
el = arr[i]
j = i - 1
while j >= 0 and arr[j] > el:
arr[j + 1] = arr[j]... | 5,295,788 |
def tail_correction(r, V, r_switch):
"""Apply a tail correction to a potential making it go to zero smoothly.
Parameters
----------
r : np.ndarray, shape=(n_points,), dtype=float
The radius values at which the potential is given.
V : np.ndarray, shape=r.shape, dtype=float
The potent... | 5,295,789 |
def case_detail(request, pk):
"""
Retrieve, update, or delete an AssuranceCase, by primary key
"""
try:
case = AssuranceCase.objects.get(pk=pk)
except AssuranceCase.DoesNotExist:
return HttpResponse(status=404)
permissions = get_case_permissions(case, request.user)
if not per... | 5,295,790 |
def wikitable(page):
"""
Exports a Wikipedia table parsed by BeautifulSoup. Deals with spanning:
multirow and multicolumn should format as expected.
"""
mediawikiapi = MediaWikiAPI()
page = mediawikiapi.page(page)
soup = BeautifulSoup(page.html(), 'html.parser')
rows=table.findAll("tr"... | 5,295,791 |
def _flatten(suitable_for_isinstance):
"""
isinstance() can accept a bunch of really annoying different types:
* a single type
* a tuple of types
* an arbitrary nested tree of tuples
Return a flattened tuple of the given argument.
"""
types = set()
if not isinstance(sui... | 5,295,792 |
def attach_tasks(queryset, as_field="tasks_attr"):
"""Attach tasks as json column to each object of the queryset.
:param queryset: A Django user stories queryset object.
:param as_field: Attach tasks as an attribute with this name.
:return: Queryset object with the additional `as_field` field.
"""... | 5,295,793 |
async def directors_reply(message: Message):
"""When director replied to message from user."""
ids = get_ids_from_text_mentions(message.reply_to_message)
if len(ids) < 1:
return
await message.bot.send_message(
chat_id=ids[0],
**MessageFromChat('Директорат', message.parse_entiti... | 5,295,794 |
def create_padding_mask(seq):
"""
The padding mask is used in the Encoder and Decoder layers to mask padding tokens.
"""
seq = tf.cast(tf.math.equal(seq, 0), tf.float32)
# add extra dimensions to add the padding to the attention logits.
return seq[:, tf.newaxis, tf.newaxis, :] | 5,295,795 |
def decode_text(s):
"""
Decodes a PDFDocEncoding string to Unicode.
Adds py3 compatibility to pdfminer's version.
"""
if type(s) == bytes and s.startswith(b'\xfe\xff'):
return str(s[2:], 'utf-16be', 'ignore')
else:
ords = (ord(c) if type(c) == str else c for c in s)
retur... | 5,295,796 |
def create_schema(client):
"""The query which creates the schema
Parameters - it uses variables rather than the fluent style as an example
==========
client : a WOQLClient() connection
"""
base = WOQLQuery().doctype("EphemeralEntity", label="Ephemeral Entity", description="An... | 5,295,797 |
def process_cpc_testdata(path, variable='pr', lead_option='weekly', day_init=15, day_end=21, region=None):
"""
Open and process the CPC data for 11 ensemble members for training.
Args:
path (str): directory path to data.
variable (str): variable for analysis.
lead_option (str): ... | 5,295,798 |
def trimap(
X,
triplets,
weights,
knn_tuple,
use_dist_matrix,
n_dims,
n_inliers,
n_outliers,
n_random,
distance,
lr,
n_iters,
Yinit,
weight_temp,
apply_pca,
opt_method,
verbose,
return_seq,
):
"""Apply TriMap."""
opt_method_dict = {"sd": 0... | 5,295,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.