content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def simulate_step(octopus_map: OctopusMap) -> SimulationStep:
"""Perform a simulation step on octopus map returning updated map and flash count"""
om = deepcopy(octopus_map)
incremented = increment_energy_level(om)
return increment_flashes(incremented) | c6a94cb37a43d8f1b7d5e4b2523e1a4a3cf7cbc6 | 3,615,600 |
def categories_portlet_children(request, category):
"""Returns the children of the given category as HTML.
"""
categories = []
for child_category in category.category_set.all():
children = categories_portlet_children(request, child_category)
categories.append({
"id": child_ca... | cc3634fa34bc9d39b2a5f55c6aa22d4819e83136 | 3,615,601 |
from typing import Any
from datetime import datetime
async def queue_task(
*, name: str, arguments: dict[str, Any], run_at: datetime | None
) -> int:
"""
Schedule a task to run at the given time.
"""
return await db.fetchval(
"""
INSERT INTO task (name, arguments, run_at)
... | cf45fe2edd944226c1d8cd014e3c2f2238cbdecb | 3,615,602 |
import io
def create_kernel_from_image(image_path, padding=0):
"""Generates a float image from an image on the disk.
:param image_path: The path to the reference image
:type image_path: string
:param padding: How much to pad the float image (zero-padded), defaults to 0
:type padding: int, opt... | dbc0a36b9e728a437b206536ef209b8110219bce | 3,615,603 |
def segformer_b4_ade(pretrained=True, progress=True):
"""Create a SegFormer-B4 model for the ADE20K segmentation task.
"""
model = create_segformer_b4(num_classes=150)
if pretrained:
_load_pretrained_weights_(model, model_urls['ade']['segformer_b4'], progress=progress)
return model | 1ca38468ff0199e47c7812d26b86ccdeecc42948 | 3,615,604 |
def get_user_id(username: str) -> str:
"""This function gets the User ID from the database
Args:
username (str): Username to get his ID.
Returns:
user_id (str): The user id from the database.
"""
username = str(username)
if not check_user_existence(username):
save_user(... | f545050729f09f17a3bbe1f62c489f18bef8c658 | 3,615,605 |
def secondaryKeywordTest(lines):
"""
How many files get keywords if we limit them by frequency
"""
offset = 3
num = 8 # 3, 4, 5, 6, 7, 8, 9, 10
passNo = []
for i in range(num):
passNo.append(0)
for l in lines:
passed = []
for i in range(num):
passed.a... | 5610a3e0aaead46cea3f03b800423ea29f53d4c5 | 3,615,606 |
from typing import Tuple
from typing import Optional
import os
def create_member(sess: SQLASession, crsid: str, preferred_name: str, surname: str,
email: str, mail_handler: MailHandler, is_member: bool = True,
is_user: bool = True, social: bool = False,
new_passwd... | be8e9dcc116aed17645c5f92c3e3436e76217a90 | 3,615,607 |
def newSplitter(
widget=None, orientation=None, verticalStretch=1, horizontalStretch=None, ori=None
):
"""
input: widget - the central widget
"""
if orientation is not None:
ori = orientation
ori = rectifyQtEnum('Orientation', ori, 'horiz')
splitter = QtWidgets.QSplitter(ori, widget)... | e6063c20bd9255df9f7ce9f0ca63bc3a140bb7a8 | 3,615,608 |
def lagrange_four_point(x, y0, y1, y2, y3):
"""The third order polynomial p(x) with p(-1)=y0, p(0)=y1, p(1)=y2, p(2)=y3."""
a2 = 3 * (y0 + y2 - y1 - y1)
a3 = 3 * (y1 - y2) + y3 - y0
a1 = -a3 + 3 * (y2 - y0)
return y1 + x * (a1 + x * (a2 + x * a3)) * 0.166666666666666666666666 | b60da1f8567c5b9babbc9e158b1444e30424bb1f | 3,615,609 |
def _format_error_message(error):
"""Returns formatted error message based on error type
:param error: cosmos error
:type error: dict
:returns: formatted error
:rtype: str
"""
if error.get("type") == "AmbiguousAppId":
helper = (".\nPlease use --app-id to specify the ID of the app "
... | d449e4fdf09a99e918ab5566d8a602d491266b57 | 3,615,610 |
import torch
def add_randn(x_input, vat_noise):
"""
add normal noise to the input
"""
epsilon = torch.FloatTensor(torch.randn(size=x_input.size())).to(device)
return x_input + vat_noise * epsilon * torch.abs(x_input) | dc8ae9055bd6bd06f0fcc8197c73dc154df30b30 | 3,615,611 |
from typing import Sequence
import yaml
def load(configs: Sequence[str], **kwargs):
"""
Load and join configurations from yaml and kwargs
"""
if not configs and not kwargs:
raise irtm.IRTMError("no configuration provided")
as_path = partial(helper.path, exists=True, message="loading {p... | e43c9b35abf06a1d76b99eca38a826f3b0e7b205 | 3,615,612 |
def capitalize_tag_kv(service: str) -> bool:
"""
Returns true or false depending on if the boto3 service
name needs the key & value values capitalized
"""
return service in ("ec2", "iam", "ssm") | 7a6f16be26fa684f6e906c5f8c5d0a3f87f95b63 | 3,615,613 |
import os
import requests
import json
def get_user_list(token, projectlist):
"""
Get the user list with some role in the list of projects.
:param token: The Admin Token
:param projectlist: The list of projects to requests users.
:return: The list of users with some role in those projects.
"""... | 57cb9e7963bbe57230af521a530382554de9a951 | 3,615,614 |
from pathlib import Path
from typing import Optional
from typing import List
async def get_schedule_timespans(
scenario: schemas.ScenarioID = Path(..., description="The id of the scenario to get data for"),
feeders: Optional[List[str]] = Query(
None, description="The feeders for which the asset data s... | d397bd3b2c9a01b865879b1930e50247f402d546 | 3,615,615 |
def compile_ticker_list(csv_file):
"""
The method reads a .csv file and searches for a column within said csv file
with the name "ticker_symbols" via the pandas data library ".read_csv" method.
If this column is found, the method iterates over each row and extracts each
ticker symbol. Each ticker sy... | bcae15bfd35df428d0c80296cd307af29dc50ec1 | 3,615,616 |
import resource
def health():
"""Our instance health. If queue is too long or we use too much mem,
return 500. Monitor might reboot us for this."""
is_bad_state = False
msg = "Ok"
stats = resource.getrusage(resource.RUSAGE_SELF)
mem = stats.ru_maxrss
if mem > 1024**3:
is_bad_stat... | 98570ba02d6e2438ab2be797c7d2c5862d8dabb9 | 3,615,617 |
def create_default_fake_spikes():
"""Return the default spike times and labels."""
spikes = np.arange(10)
labels = np.array((1, 1, 1, 1, 1, 2, 2, 2, 2, 2))
return spikes, labels | f541acfdf279b0627da26c24e02cdaf57c75a8a9 | 3,615,618 |
def valid_arguments(valip, valch, valc, valii):
"""
Valid the arguments
"""
bvalid = True
# Type converssion
valch = int(valch)
valii = int(valii)
# Valid the parameters
# Valid - IP
if valip == "":
print("IP is invalid.")
bvalid = False
# Valid - Channel
... | 68c39d1f6570236d8dc12eb23d225de3255edd82 | 3,615,619 |
def max_brightness() -> int:
"""Get maximum brightness value using sysfs.
Read the maximum brightness value from the corresponding file in sysfs.
Returns
-------
int
Maximum brightness value.
"""
path = SYS_DIR + GRAPHICS_CARD + MAX_BRIGHTNESS_FILE
return __read_file_as_int(pa... | 7f3e193566f362203caf6d4f650cee724665739e | 3,615,620 |
import os
def _count_files(path):
"""Returns number of files in a given directory."""
return len([filename for filename in os.listdir(path)
if os.path.isfile(os.path.join(path, filename))]) | 1e26135aa64c3569f71913f73a26a73639a08eb7 | 3,615,621 |
def init_label_matrix(y):
"""
:param y: numpy array, shape = (n_nodes,) -1 for the unlabeled data, 0,1,2.. for the labeled data
:return:
"""
y = y.reshape(-1)
labels = list(np.unique(y))
if -1 in labels:
labels.remove(-1)
n_nodes = y.shape[0]
Y = np.ones((n_nodes, len(label... | 1ec9a77adfb6bfda957917f0327e0e6ff911cacc | 3,615,622 |
def fuse_masses(mass1, mass2):
"""
Fuses two probability masses
:returns
"""
# Convert to masses
both_masses = pd.DataFrame({"m1": mass1, "m2": mass2})
# Fuse masses
both_masses["fused"] = both_masses.apply(
lambda row: row["m1"].combine_conjunctive(row["m2"], importance_samplin... | cc38e1ed11535b19b2fcbd70d4430d4eaf875198 | 3,615,623 |
def get_D_inv(adj):
"""Missing docs.
Args:
adj: adjacent matrix.
"""
rowsum = np.array(adj.sum(1))
d_inv = np.power(rowsum, -1).flatten()
d_inv[np.isinf(d_inv)] = 0.0
d_mat_inv = sp.diags(d_inv)
return d_mat_inv | e9597cb9185d72342a56570868114bd73cee94bd | 3,615,624 |
import uuid
def create_filename(prefix='', ext=''):
"""
Create a unique filename.
:param str prefix: Prefix to add to filename.
:param str ext: Extension to append to filename, e.g. 'jpg'
:return: Unique filename.
:rtype: str
"""
suffix = '.' + ext if ext else ''
return prefix + s... | 30cedc7bdcf3fdbf202b8a0d26e64bd6f865094d | 3,615,625 |
def StressngCustomStressorsValidator(stressors):
"""Returns whether or not the list of custom stressors is valid."""
valid_stressors = {
'affinity', 'af-alg', 'aio', 'aio-linux', 'apparmor', 'bigheap', 'brk',
'bsearch', 'cache', 'chdir', 'chmod', 'clock', 'clone', 'context', 'cpu',
'cpu-online', '... | 7563d0a8829aa323e53ff807540cdf281b7df883 | 3,615,626 |
from typing import Dict
import traceback
def route(function_name: str, data: Dict) -> Dict:
"""Route the call to a specific function
Args:
ctx: Invoke context. This is passed by Fn to the function
data: Data passed to the function by the user
Returns:
Response: Fn FDK response obj... | 1af948fcff8e2fd7bcd1080aa51cad0437406e90 | 3,615,627 |
import os
def list_files(directory, hidden=False):
"""Return a list of files in a directory."""
files = []
for item in os.listdir(directory):
if os.path.isfile(os.path.join(directory, item)) and (
hidden or not item.startswith(".")
):
files.append(item)
return f... | c9e1ef221d773dec94acc7997501d17b99700b8d | 3,615,628 |
def TDataXtd_Geometry_GetID(*args):
"""
* Returns the GUID for geometry attributes.
:rtype: Standard_GUID
"""
return _TDataXtd.TDataXtd_Geometry_GetID(*args) | 3646fc3f053d1a7f5e15fc4c08caa7994a76c69e | 3,615,629 |
def set(isamAppliance, enabled, debug, ha, logging, ssl, services, attributes,
check_mode=False, force=False):
"""
Replacing FELB configuration in full
"""
if force is False:
update_required, json_data, warnings = _check(isamAppliance, enabled, debug, ha, logging, ssl, services, attribu... | 2cc0882d92de366f291270c3083b850588b00f15 | 3,615,630 |
def get_its(hparams):
"""Get number of training and validation iterations
"""
# These run for a fixed amount of time. As anchored batch is smaller, we've actually seen fewer examples
train_its = int(np.ceil(hparams.n_train / hparams.n_batch_train))
test_its = int(np.ceil(hparams.n_test / hparams.n_b... | 6abd333927a0c4a6eed3961befe4399a082f176e | 3,615,631 |
def getSentenceList(row, field):
""" return list of sentences from doc object field;
each item will be token span """
return list(row[field].sents) | ecaa1159e6a9390ef2aa310741aae4a58105b8a9 | 3,615,632 |
def diz_oi():
"""Uma função simples que retorna 'oi'"""
return 'oi' | 8210dde23e06d0f475be9aef6113216dc096dbe3 | 3,615,633 |
def dashboard(request):
"""Mock dashboard view"""
return HttpResponse('dashboard') | eaa0b61f4db65429f5ae2918e1d43ffc4fd7ede9 | 3,615,634 |
def std_secao_filter(secao_list):
"""
Takes a words list from a secao filter and standardize the words to the
same pattern as the one used to download the articles' URLs:
extra -> e and suplemento -> a.
"""
return [str(s).lower().replace('extra','e').replace('suplemento','a') for s in secao_lis... | 6c5b1a52bec02078cd8c0e1dc35c97420a424936 | 3,615,635 |
def SecondsDistribution(name):
"""Returns a metric handle for a cumulative distribution named |name|.
The distribution handle returned by this method is better suited than the
default one for recording handling times, in seconds.
This metric handle has bucketing that is optimized for time intervals
(in seco... | f08bc7f88f7e74f1a4f601b59caf6421790cc9e1 | 3,615,636 |
import math
def predict(testlist):
"""Prepare the model input data type
paramters:
testlist: list,[[[u'T'], [u':'],...]
return result_sequences: list,
"""
feature_names, sep, vocs, max_len, use_char_feature, word_len = load_parameters()
data_dict = init_data( feature_names=feature... | e4063fea1862a9d7445a6f0c62ace8128c72b2f3 | 3,615,637 |
def orbit_nearest_point(pos, vel, pos_obs, vel_obs):
"""
Computes the closes value of an orbit to a given 3d point.
Parameters:
-----------
pos : numpy.array
orbits positions
vel : numpy.array
orbits velocities
pos_obs : numpy.array
orbital point
vel_obs : nu... | f995dcc69014df2ca483fa5227697cebf8c1b828 | 3,615,638 |
import sqlite3
def create_connection(db_file):
"""Create a database connection to the SQLite database specified by db_file
:param db_file: database file
:return: connection object or None
"""
conn = None
try:
conn = sqlite3.connect(db_file)
except Error as e:
... | c51079503993cb6cf690fae71748f53b4d30bf69 | 3,615,639 |
def more_than_one_5(number=''):
""" Returns True if there is more than one 5 based numeral (ex: VV) """
prev = ''
repetitions = 0
for letter in number:
if prev == letter and letter in FIVE_BASED:
repetitions += 1
else:
repetitions = 0
if repetitions >= 1:
... | e702f4d8bc92a3db4b31dcab6e79b5a597d7b292 | 3,615,640 |
def bert():
"""bert"""
if request.method == 'POST':
s = request.get_json()['string']
data_type = request.get_json()['type']
print("s is {}".format(s))
print("type is {}".format(data_type))
poem = generate(s, data_type)
return poem | 98547e63e046ba5b7f6ed0ab8098c9b8e34bac01 | 3,615,641 |
def get_pronoun(mode, number, person, conjugated_verb):
"""Return a string with the pronoun to be used depending of the parameters"""
pronoun = ""
if mode == "Gérondif":
pronoun = "en "
elif mode == "Subjonctif":
if number == "s":
if person == "1":
if conjugat... | f905f6755e8a990ff4ff0b1be4246a14c934eb0a | 3,615,642 |
import subprocess
def get_current_branch():
"""Return the current branch we are on or the branch that the detached head
is pointed to"""
current_branch = subprocess.check_output(
['git', 'rev-parse', '--abbrev-ref', "HEAD"]
).decode("utf-8").strip()
if current_branch == 'HEAD':
... | 76f192d26daed7cc7dfafdf22f2d1c8a0a7cb0af | 3,615,643 |
import asyncio
import aiohttp
async def post_async(
endpoints: list[str],
payloads: list[bytes],
max_concurrent_requests: int = 5,
max_retries: int = 5,
headers: dict = None,
) -> list[tuple[str, bytes]]:
"""Given a list of HTTP endpoints and a list of payloads,
make HTTP POST requests asy... | 3ff3f6174dcff1a8a33da66c73016e65302a7274 | 3,615,644 |
def element_volume(domain, element, elevation):
"""
Calculates the volume of water contained an element with a given sea
surface elevation at each of the nodes.
:param domain: :class:`~polyadcirc.run_framework.domain`
:param element: list of nodes defining an element
:type element: array_like ... | d1658844122c213a0bceb8b135152353bbb3b9d3 | 3,615,645 |
def mapsApplyToField(function, field, mapSets,inside):
"""mapSets defines a set of polygons. This procedure fills the areas in the field are enclosed
by each polygon with the average value within that area
"""
if (GridUtil.isTimeSequence(field)):
newData = field.clone()
for timeStep in ... | b5dbca040b7542c71a06340592282664095fab65 | 3,615,646 |
from sys import path
def globalDirectory():
""":return: the global directory"""
return path.join("/etc",_pyFoamDirName) | 5ed5385f5cd75f1296a1a55339afef79edadcdb7 | 3,615,647 |
def poison_graph(graph, venomous_path, config):
"""
Poisons a graph
Function args:
graph -- the graph
venomous_path -- the path from which the poison originates
config -- routing configuration
"""
return PoisonedGraph(graph, venomous_path, config.poison_max_distance,... | ab4cd2a24d453e29fd1c2ef6ebbaccfe09a6f7eb | 3,615,648 |
def generate_timestamp_metadata(release_filename, version,
expiration_date, compressions=()):
"""
<Purpose>
Generate the timestamp metadata object. The 'release.txt' file must exist.
<Arguments>
release_filename:
The required filename of the release metadata file.
... | 4eed549b899cdb42cdd69e657737fbb6ecb00b94 | 3,615,649 |
import math
def gamma_axial_quark(m_med, g_q=0.25):
"""Function to calculate quark width of an axial vector mediator
:param m_med: mediator mass
:type m_med: float
:param g_q: quark coupling, defaults to 0.25
:type g_q: float, optional
"""
gamma = 0
for m_q in m_quarks:
if(m_m... | c9ae31a26feedbe2fedef22cb0f986cc5df6b58d | 3,615,650 |
def should_we_show_version(args: Namespace) -> bool:
"""Should we show version or not?."""
return args.version if args.version is not None else False | e6cbf17c3655826cc9b2f03d3b294cda3fa5f97c | 3,615,651 |
async def sample(sectype, population, k):
"""List of k uniformly random secret elements chosen from population.
Choices are made without replacement.
Given population may contain public and/or secret elements.
If the population contains repeats, then each occurrence is a
possible selection in the... | 6cc1ca8764e351b8d0d5cc2957533e32a858afcd | 3,615,652 |
def _fetch_fixture(f):
"""Fetch dataset (download if missing and requested by environment)."""
download_if_missing = environ.get("SKLEARN_SKIP_NETWORK_TESTS", "1") == "0"
@wraps(f)
def wrapped(*args, **kwargs):
kwargs["download_if_missing"] = download_if_missing
try:
return ... | f11a0e55ab790558ea5dab234abad900705fbd2f | 3,615,653 |
def var_calcs(filenm, varnm, plev, latlon=(-90, 90, 40, 120)):
"""Process a single variable from a single day."""
lat1, lat2, lon1, lon2 = latlon
if varnm == 'DUDP':
nm, dp = 'U', True
elif varnm == 'DOMEGADP':
nm, dp = 'OMEGA', True
else:
nm, dp = varnm, False
with xray.... | c38130040455756f51c004235c47cf5a9310c4a7 | 3,615,654 |
import warnings
def _apply_lines(
self, *args,
stack=None, stacked=None,
negpos=False, negcolor=None, poscolor=None,
color=None, colors=None,
linestyle=None, linestyles=None,
lw=None, linewidth=None, linewidths=None,
**kwargs
):
"""
Apply hlines or vlines command. Support default "... | edcf80edef917d06b6e1c83185261c7422bb6434 | 3,615,655 |
import six
def detector_format_version(address, timestamp):
"""The detector_format_version() function returns a format version
string appropriate for the detector whose address is given by @p
address at the time @p time.
@param address Full data source address of the DAQ device
@param time Time of the e... | 02c94a8b4d2f1e2daf66434f39926944ea932129 | 3,615,656 |
from typing import get_type_hints
def configs() -> st.SearchStrategy[isort.Config]:
"""Generate arbitrary Config objects."""
skip = {
"line_ending",
"sections",
"known_standard_library",
"known_future_library",
"known_third_party",
"known_first_party",
"... | a9c7c0f9b1c03adc19ccde28093f3c1048f8ddd3 | 3,615,657 |
def lissa_inverse_covariance_matrix( # pylint: disable=invalid-name
Phi,
key,
lissa_iterations,
lissa_kappa,
feature_norm=None):
"""Estimates the covariance matrix by LISSA.
By default this method returns a covariance matrix whose norm is equivalent
to a single data point, no need to multipl... | bfc94c4b2735266b5180c4d19c2d5d3cd3020af4 | 3,615,658 |
import os
from pathlib import Path
def input2d(tmpdir):
"""Convert 1D input to 2D output by copying all the time series along a new region dimension."""
ds = _convert_2d(TS)
fn_out = os.path.join(tmpdir, "input2d.nc")
ds.to_netcdf(fn_out)
return Path(fn_out) | 14432e4408b8e17ad6d767a2246c5c47eae8418a | 3,615,659 |
def distribution_score(probs: th.Tensor, nb_samples: int, split_factor: float) -> float:
"""
Get the score of the distribution. Used to find the best cell factory parameters.
O(p, n) = H_n(p) / L(n, T), where
- H_n(p) is the entropy ratio with the uniform distribution: -sum_i p_i*log(p_i)/log(n)
- ... | 02440d8f472a4d1e031727031a62c02619685b24 | 3,615,660 |
import base64
import hashlib
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 ValidationErro... | 0a134ae76f0a6f0acf0006a66b55ec824656a847 | 3,615,661 |
import re
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._... | 8cce0bf0c68601dcbed2c0852a563243cd818743 | 3,615,662 |
import pkg_resources
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') | 1dfde6366c286665deb34bb4c9e3f58fe8b31dd6 | 3,615,663 |
import functools
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"]:
... | c08e3cfda9ef1da8fecc3313a2429c77864161ca | 3,615,664 |
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):
... | f2a73337fdfbf320c79d569ddce2122ae4b81054 | 3,615,665 |
from typing import List
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 | 149737a48d61860744d6f50c65a11d5fe424e24d | 3,615,666 |
import math
import statistics
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))
... | 9103bffe97696f4441a2d6a28352a55ee1be30cb | 3,615,667 |
def recv_meas_outcome(socket):
"""Receive the measurement outcome (0 or 1) of the server's
last measurement.
"""
return int(socket.recv(maxsize=1)) | f49717272722be1476cb9bcc08bcbe7b8525c2ba | 3,615,668 |
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... | c3a53b1d224f4e1109b7b5c92ebe1a8230850bb5 | 3,615,669 |
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... | ca359600a821c7205f483a20c548368755c4e878 | 3,615,670 |
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... | 1dd6d44ffdf067a484940cdbfa7fcfb88289052c | 3,615,671 |
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):
... | 6cdefa5ee98ebc0671bc888d9ea419a965afd68b | 3,615,672 |
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... | 3127b47a2bb8b70f3c42ba33cf0916455b524e9e | 3,615,673 |
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_... | 932f73b46a06838f5e16d4c1969d94734e805459 | 3,615,674 |
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... | 593bedd74e2cd56b212bb70c05fea0860c264fa2 | 3,615,675 |
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... | 4daa4848e2700f2b0cf1ab9924fc5a96b223c93e | 3,615,676 |
def runconfiguration_transformer(values):
"""Calls transform_project_data with corresponding header"""
return transform_project_data(values, "Run configuration") | b95a11e18f2ff1fdaf2f5a45b1f78dc024332a0a | 3,615,677 |
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... | ddd5e9f5c38443a7b82b5b5aa35b58702234a831 | 3,615,678 |
from pathlib import Path
import xml
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(xmlfilen... | bd67af74b99bd1b459214527b815de9f4ae54a4d | 3,615,679 |
import time
import requests
import json
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, head... | 33a8ebd359760bb508da671e8988821816eb36c6 | 3,615,680 |
from glue.core.exceptions import IncompatibleAttribute
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, add... | f64205077c4e76d1990b87cc814237d9eb79e2ab | 3,615,681 |
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... | 8a2abbd93b9a2f6639b9645f70a384f1a1806b67 | 3,615,682 |
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:... | 2fbd85f34feeb1f46895a8f10f03bfd1b5643d01 | 3,615,683 |
import base64
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 ... | 69900bbc73a4df8e0f2f932a30e6acdb08cb9c4d | 3,615,684 |
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) | ba17ef1e0b652580dc05fae4bc21d4f7eb303dd4 | 3,615,685 |
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... | 061a06227421917fd305627620b8759a2a9ce924 | 3,615,686 |
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 Atari. Th... | 0d89c717356065af5c8ef9468aa4bbde8d2b1fc2 | 3,615,687 |
def get_test_data_path():
"""Returns the path to test datasets """
return join(dirname(__file__), "data") | 2e675f82e0bdda99f868c9172c9cf97b1a6d4d4e | 3,615,688 |
from typing import Union
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 corresponde... | f800ec179075f00264d3d797c3df6bcf1e6b80da | 3,615,689 |
import base64
import json
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_CREDENTIA... | 0bd1dbd46cb6d162bd444a42a8ac8aafb938b600 | 3,615,690 |
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 ... | a85e49f082ea3f03ac05a783839a1fe2e6caacf2 | 3,615,691 |
from typing import List
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
retur... | 2839f6a2bcbc335aca82b3cfc5ed81357ba4b37b | 3,615,692 |
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)
"""... | 700619b8f65b9d3d6e9a4dcb6f10eb3b49e42cd2 | 3,615,693 |
import json
import http
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, 'comple... | 6ce2afc57d464de0a09211803eb6376026b2596f | 3,615,694 |
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 ... | 869e71ea3bc31e277ab3a8fbe062d96e84e173d3 | 3,615,695 |
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... | 20083f7ceaa35bd31d62bb9cdd8cfa56d5a0255e | 3,615,696 |
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... | 540dabd4e42eb68ce166f608bfa849b31f1bc2fe | 3,615,697 |
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_... | 3b25081ce3452629de9fdd6afd122bd058ee9acf | 3,615,698 |
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"))
... | 51f2a52fea202fe70ab0d0336bb63c8fe4a39283 | 3,615,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.