content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def delete_directory(path):
"""
Deletes a ticket attachments directory from disk
"""
path = '{}/{}'.format(settings.MEDIA_ROOT, path)
try:
shutil.rmtree(path)
return path
except:
logger.error('Error removing folder{}'.format(path))
return False | 5,294,500 |
def get_tile_from_lon_lat(lon: float, lat: float, zoom: int) -> tuple[int, int]:
"""
Turns a lon/lat measurement into a Slippy map tile at a given zoom.
"""
# Clamps lon, lat to proper mercator projection values
lat = min(lat, 85.0511)
lat = max(lat, -85.0511)
lon = min(lon, 179.9999)
l... | 5,294,501 |
def _add_to_comment_graph(graph, msg, prop, uri):
"""
Add a distiller message to the graph.
@param graph: RDFLib Graph
@param msg: message of an exception
@type msg: RDFLIb Literal
@param prop: the property to be used
@type prop: string, must be one of 'warning', 'error', 'info', 'debug'
... | 5,294,502 |
def simpson_integral(f, a, b):
"""辛普森求积公式
"""
return (b - a) * (f(a) + 4 * f((a + b) / 2) + f(b)) / 6 | 5,294,503 |
def api_subscribe_pull_request(repo, requestid, username=None, namespace=None):
"""
Subscribe to an pull-request
----------------------------
Allows someone to subscribe to or unsubscribe from the notifications
related to a pull-request.
::
POST /api/0/<repo>/pull-request/<request id>/... | 5,294,504 |
def save_data_and_metadata_to_s3_csv(
subfolder_path: str,
existing_csv_files: List[str],
s3_bucket_name: str,
headers: List[str],
content: Dict,
path_to_csvs_folder: str,
region: str,
cols_to_use: List[str],
unwanted_partial_strings_list: List[str],
combine_hashtags_usernames: b... | 5,294,505 |
def _group_lst(lst, n):
"""Split the lst into sublists of len n."""
return (lst[i : i + n] for i in range(0, len(lst), n)) | 5,294,506 |
def get_cincinnati_channels(major, minor):
"""
:param major: Major for release
:param minor: Minor version for release.
:return: Returns the Cincinnati graph channels associated with a release
in promotion order (e.g. candidate -> stable)
"""
major = int(major)
minor = int(minor... | 5,294,507 |
def translate_batch(exe,
src_words,
encoder,
enc_in_names,
enc_out_names,
decoder,
dec_in_names,
dec_out_names,
beam_size,
max_length,
... | 5,294,508 |
def set_ribo_info(ribo,
length_min, length_max,
reference_name,
metagene_radius,
left_span, right_span):
"""
Essential ribo metadata is stored
in the atrributes of the hdf5 file.
These attributes are crucial and shouldn't be change... | 5,294,509 |
def load_audio(
file: str, sr: Optional[int], verbose=True, **kwargs
) -> Tuple[Tensor, AudioMetaData]:
"""Loads an audio file using torchaudio.
Args:
file (str): Path to an audio file.
sr (int): Optionally resample audio to specified target sampling rate.
**kwargs: Passed to torcha... | 5,294,510 |
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return MetaConv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) | 5,294,511 |
def comparer(player, stat, year1, year2):
"""
Takes command line input, compares a player between game editions showing print statement and barplot
Parameters
----------
player
The player being assessed (str)
stat
The stat being assessed (str)
year1
The more recent g... | 5,294,512 |
def get_value(seq, index):
"""Get the value of a nested sequence using index.
"""
if index == ():
return seq
if isinstance(seq, Storage):
return seq[index]
assert isinstance(seq, (tuple, list)), type(seq)
value = seq
for i in index:
value = value[i]
return value | 5,294,513 |
def indices_client():
"""Returns an Elasticsearch indices client that is responsive
to the environment variable ELASTICSEARCH_ENDPOINT"""
es_connected = False
while not es_connected:
try:
ES = Elasticsearch(
hosts=[HOSTNAME]
)
es_connected = Tr... | 5,294,514 |
def test_find_and_run_next_batch_chunks(mock_import_chunk, batch, valid_user):
"""Assert that if a batch is not running that this starts the next chunk."""
for chunk_number in range(1, 3):
factories.ImporterXMLChunkFactory.create(batch=batch, chunk_number=chunk_number)
tasks.find_and_run_next_batch... | 5,294,515 |
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) | 5,294,516 |
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... | 5,294,517 |
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)
VALUES ($1, $2, $3) RETURNING id;
""",
... | 5,294,518 |
def info_callback(update, context):
"""Return the issues search parameters to user"""
try:
info = firedb.get_document("search")
update.message.reply_text("Actual parameters")
for key, item in info.items():
update.message.reply_text(f"{key}: {item}")
except Exception as e:... | 5,294,519 |
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, optional
:r... | 5,294,520 |
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 | 5,294,521 |
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(... | 5,294,522 |
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... | 5,294,523 |
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: bool = False) -> Collect[Tuple[Member, Optional[Password]]]:
... | 5,294,524 |
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)... | 5,294,525 |
def django_response(request):
"""
The Django.core.mail#mail_admins and Django.core.mail#mail_managers functions source code can be found in the link below:
https://github.com/django/django/blob/ca9872905559026af82000e46cde6f7dedc897b6/django/core/mail/__init__.py#L90-L121
"""
mail_admins("Subject", ... | 5,294,526 |
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 | 5,294,527 |
def test_report_integrated_data(dials_data, tmpdir):
"""Simple test to check that dials.report completes when given integrated data."""
result = procrunner.run(
[
"dials.report",
dials_data("l_cysteine_dials_output") / "20_integrated_experiments.json",
dials_data("l_... | 5,294,528 |
def write_local_file(file_today: str, data: dict) -> None:
"""
store data to local file
Args:
file_today: today json filename
data: json data
"""
json.dump(data, open(file_today, 'w', encoding='utf-8')) | 5,294,529 |
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 "
... | 5,294,530 |
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) | 5,294,531 |
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 {path_abbrv}")
# first join all yaml co... | 5,294,532 |
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") | 5,294,533 |
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.
"""
print('Get the list of users with s... | 5,294,534 |
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 should be retrieved."
),
asset_name: Optional[str] = Query(
None... | 5,294,535 |
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... | 5,294,536 |
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"
import resource
stats = resource.getrusage(resource.RUSAGE_SELF)
mem = stats.ru_maxrss
if mem > 1024**3:
is_bad_st... | 5,294,537 |
def timeliness_run_check(columns, value, df, dateFormat=None, timeFormat=None):
"""
Check for consistency between parameters and the dataframe, an assertion
error will incur if the check is not passed.
:param columns: Columns on which to run the metric
:type columns: list
:param value: Value of... | 5,294,538 |
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 | 5,294,539 |
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
... | 5,294,540 |
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... | 5,294,541 |
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))]) | 5,294,542 |
def main(args):
"""Handle user args and act accordingly."""
wiki, fish = update_data()
if args.update:
wiki, fish = force_update()
if args.players:
display_pls(wiki)
print ''
if args.player:
get_player_info(args.player, wiki, fish)
print ''
if args.fuzzyre... | 5,294,543 |
def _configure_bitwidths_keras_model(model_mp: Model,
sorted_configurable_nodes_names: List[str],
mp_model_configuration: List[int],
node_idx: List[int]):
"""
Configure a dynamic Keras model (namely, m... | 5,294,544 |
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... | 5,294,545 |
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... | 5,294,546 |
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 | 5,294,547 |
def test_both_auth_types(sut: SystemUnderTest):
"""Perform test for Assertion.SEC_BOTH_AUTH_TYPES."""
ba_response = sut.get_response('GET', sut.sessions_uri,
request_type=RequestType.BASIC_AUTH)
sess_response = sut.get_response('GET', sut.sessions_uri)
ba_result, ba_ms... | 5,294,548 |
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 + str(uuid.uuid4(... | 5,294,549 |
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', '... | 5,294,550 |
def rfc_in_breastCancer():
"""
随机森林在乳腺癌数据集上的调参
:return:
"""
from sklearn.model_selection import GridSearchCV # 网格搜索调参
from sklearn.datasets import load_breast_cancer
#导入数据集
data = load_breast_cancer()
print(data.data.shape)
# 建模:初始化准确率
rfc = RandomForestClassifier(n_estimat... | 5,294,551 |
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 object containing function call data
a... | 5,294,552 |
def recordWeights (sim, t):
""" record the STDP weights during the simulation - called in trainAgent
"""
#lRcell = [c for c in sim.net.cells if c.gid in sim.net.pops['ER'].cellGids]
sim.WeightsRecordingTimes.append(t)
sim.allRLWeights.append([]) # Save this time
sim.allNonRLWeights.append([])
for cell in ... | 5,294,553 |
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 files | 5,294,554 |
def TDataXtd_Geometry_GetID(*args):
"""
* Returns the GUID for geometry attributes.
:rtype: Standard_GUID
"""
return _TDataXtd.TDataXtd_Geometry_GetID(*args) | 5,294,555 |
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... | 5,294,556 |
def test(action_set):
"""Test."""
with tf.Graph().as_default():
# Get EnvironmentFactory
env_sampler = env_factory.EnvironmentFactory(
FLAGS.recipes_path, FLAGS.hints_path, max_steps=FLAGS.max_steps,
reuse_environments=FLAGS.reuse_environments, seed=1, visualise=True)
dummy_env = env_sam... | 5,294,557 |
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... | 5,294,558 |
def getSentenceList(row, field):
""" return list of sentences from doc object field;
each item will be token span """
return list(row[field].sents) | 5,294,559 |
def _check_window_lengths(
y: ACCEPTED_Y_TYPES,
fh: ForecastingHorizon,
window_length: NON_FLOAT_WINDOW_LENGTH_TYPES,
initial_window: NON_FLOAT_WINDOW_LENGTH_TYPES,
) -> None:
"""Check that combination of inputs is compatible.
Parameters
----------
y : pd.Series, pd.DataFrame, np.ndarra... | 5,294,560 |
def train(model: tf.keras.Model, train_data: List[Tuple[int, int, int]], test_data: List[Tuple[int, int, int]],
topk_data: TopkData, optimizer=None, loss_object=None, epochs=100, batch=512, execution='eager') -> None:
"""
通用训练流程。
:param model: 模型
:param train_data: 训练集
:param test_... | 5,294,561 |
def p_root(p):
"""root : ROOT_TYPE IDENTIFIER ';' """
setattr(fbs_stack[-1], "root", p[2]) | 5,294,562 |
async def test_rising_edge(dut):
"""Test that a rising edge can be awaited on"""
dut.clk.value = 0
await Timer(1, "ns")
test = cocotb.start_soon(do_single_edge_check(dut, 1))
await Timer(10, "ns")
dut.clk.value = 1
fail_timer = Timer(1000, "ns")
result = await First(fail_timer, test.join... | 5,294,563 |
def diz_oi():
"""Uma função simples que retorna 'oi'"""
return 'oi' | 5,294,564 |
def dashboard(request):
"""Mock dashboard view"""
return HttpResponse('dashboard') | 5,294,565 |
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... | 5,294,566 |
def _shape_check(shape_a, shape_b, shape_bias, src_dtype, trans_a, trans_b):
"""
Check the given input if legal
Parameters:
shape_a: list or tuple
Shape of the first tensor a with rank > 1
shape_b: list or tuple
Shape of the second tensor b with the same type with a,
... | 5,294,567 |
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... | 5,294,568 |
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_names,
... | 5,294,569 |
def load(filename):
"""
Load a compressed pickle from disk
"""
pass | 5,294,570 |
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... | 5,294,571 |
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:
raise e
... | 5,294,572 |
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:
... | 5,294,573 |
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 | 5,294,574 |
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... | 5,294,575 |
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':
# This means we a... | 5,294,576 |
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 asynchronously
Args:
e... | 5,294,577 |
def antlr_cc_library(name, src, package = None, listener = False, visitor = True):
"""Creates a C++ lexer and parser from a source grammar.
Args:
name: Base name for the lexer and the parser rules.
src: source ANTLR grammar file
package: The namespace for the generated code
listener: ge... | 5,294,578 |
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 ... | 5,294,579 |
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 ... | 5,294,580 |
def globalDirectory():
""":return: the global directory"""
return path.join("/etc",_pyFoamDirName) | 5,294,581 |
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,... | 5,294,582 |
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.
... | 5,294,583 |
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_med >= 2 * m_q)... | 5,294,584 |
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 | 5,294,585 |
def prune(tree, nodes, const_depth=True, keep_root=False):
"""
We provide a customized alternative to ete3.Tree.prune to increase the speed of tree
pruning for the special case of
- nodes being specified by node name
- branch lengths always 1 for Glottolog trees
"""
to_keep = set(n for n in ... | 5,294,586 |
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... | 5,294,587 |
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 ... | 5,294,588 |
def annotate_gene_sparsity(adata):
"""
Annotates gene sparsity in given Anndatas.
Update given Anndata by creating `var` "sparsity" field with gene_sparsity (1 - % non-zero observations).
Args:
adata (Anndata): single cell or spatial data.
Returns:
None
"""
mask = adata.X ... | 5,294,589 |
def check_ip_fwd(duthosts, all_cfg_facts, nbrhosts, tbinfo):
"""
Checks basic IP connectivity through the voq system.
Args:
duthosts: duthosts fixture
all_cfg_facts: all_cfg_facts fixture
nbrhosts: nbrhosts fixture
"""
for porttype in ["ethernet", "portchannel"]:
for... | 5,294,590 |
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.... | 5,294,591 |
def test_graphpartition():
""" test GraphPartition correctly handles graph whose
nodes are strings"""
graph = nx.Graph()
graph.add_edge('a','b')
graph.add_edge('c','d')
index = {0:set([0,1]), 1:set([2,3])}
gpart = mod.GraphPartition(graph, index)
assert gpart._node_set == set([0,1,2,3])
... | 5,294,592 |
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 "minima" at zero.
... | 5,294,593 |
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 event, in numb... | 5,294,594 |
def run_change_reporter(accounts):
""" Runs Reporter """
accounts = __prep_accounts__(accounts)
reporter = Reporter(accounts=accounts, alert_accounts=accounts, debug=True)
for account in accounts:
reporter.run(account) | 5,294,595 |
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",
"known_local_folder",
"extra_... | 5,294,596 |
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... | 5,294,597 |
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) | 5,294,598 |
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)
- ... | 5,294,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.