text string | label_name string | labels int64 |
|---|---|---|
async-aware MutexGuard.
///
/// ### Why is this bad?
/// The Mutex types found in std::sync and parking_lot
/// are not designed to operate in an async context across await points.
///
/// There are two potential solutions. One is to use an async-aware Mutex
/// type. Many asynchronous found... | Rust | 0 |
adeInfos,
pub admin_enabled: bool,
pub spawn_shield_duration: Duration,
pub shield_duration: Duration,
pub inferno_duration: Duration,
pub view_radius: Distance,
}
impl Index<Plane> for PlaneInfos {
type Output = PlaneInfo;
fn index(&self, idx: Plane) -> &PlaneInfo {
&self.0[&idx]
}
}
impl Index<Mob> for M... | Rust | 0 |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
dat=pd.read_csv("data/gpu.dat",delimiter=",")
n=dat["N"].values
t=dat["t_s"].values
std=dat["std_s"].values
plt.errorbar(n,t,yerr=std,color="C0",fmt="*",label="A:$\\Delta \\nu = 100 \\mathrm{cm^{-1}}, N_\\nu=10^4$")
plt.plot(n,t,color="C0",alpha=0... | Python | 1 |
ut, parent)
def save_cluster_video(self, parent, fps, num_frames_gif):
"""
Write frames from each cluster to a different video (*.avi)
"""
cumframes, Ly, Lx, capture = utils.get_frame_details(parent.filenames)
capture = capture[0][0]
num_clusters = len(np.unique(self... | Python | 1 |
:Public>("Alice"),
//initial authorities & invulnerables
vec![
(
get_account_id_from_seed::<sr25519::Public>("Alice"),
get_from_seed::<AuraId>("Alice"),
),
(
get_account_id_from_seed::<sr25519::Public>("Bob"),
get_from_seed::<AuraId>("Bob"),
),
],
// Pre-funde... | Rust | 0 |
// we might encounter this type with a more specific type for the associated type, e.g. &'1 [i32][0]
// to account for this variation, we use normalize_erasing_regions
//
// we also want any index to be treated the same, so we replace [i] => [0]
let param_env = tcx.param_env(def_id);
let... | Rust | 0 |
> None:
proto = parse(bitproto_filepath("message_field_name_keyword.bitproto"))
message = cast_or_raise(Message, proto.get_member("PayloadDataT"))
field = cast_or_raise(MessageField, message.get_member("type"))
assert field.number == 1
def test_constants() -> None:
proto = parse(bitproto_filepath(... | Python | 1 |
#!/usr/bin/env python
"""
This script converts XML file generated by OpenCover code coverage
tool for .NET into a set of html files for easy browsing of the results.
Usage:
opencover-to-html.py <opencover-output.xml> <outdir>
<opencover-output.xml> is an XML file with code coverage information
generated by PartCov... | Python | 1 |
actor_images_flow_route(req: ActorTmdbImageFlowRequest):
"""统一的、流程驱动的演员TMDB图片获取接口"""
task_cat = "API-画廊"
try:
logic = get_tmdb_logic()
return logic.get_actor_images_flow(req)
except Exception as e:
ui_logger.error(f"获取演员TMDB图片流程({req.emby_person_id})失败: {e}", task_category=task_c... | Python | 1 |
token returned from a prior request. Use this token for pagination of results from this action. If this parameter is specified, the response only includes results beyond the token, up to the value specified by MaxResults. When the end of results is reached, the response has a value of null.</p>
#[serde(rename = "N... | Rust | 0 |
m_vec, n_batch, n_dim).permute(1,0,2,3).contiguous().flatten(0,1)
attn_index += 1
identity = query
elif layer == 'norm':
query = self.norms[norm_index](query)
norm_index += 1
elif layer == 'cross_attn':
que... | Python | 1 |
_7Bit: ::libc::c_uint = 0;
pub const kMIDIControlType_14Bit: ::libc::c_uint = 1;
pub const kMIDIControlType_7BitRPN: ::libc::c_uint = 2;
pub const kMIDIControlType_14BitRPN: ::libc::c_uint = 3;
pub const kMIDIControlType_7BitNRPN: ::libc::c_uint = 4;
pub const kMIDIControlType_14BitNRPN: ::libc::c_uint = 5;
pub type MI... | Rust | 0 |
import akshare as ak
stock_zh_a_daily_qfq_df = ak.stock_zh_a_daily(symbol="sz000002", start_date="20101103", end_date="20201116", adjust="qfq")
print(stock_zh_a_daily_qfq_df)
#
#
# url = "http://77.push2.eastmoney.com/api/qt/clist/get"
# params = {
# "cb": "jQuery112406285914172501668_1590386857513",
# "pn": "1... | Python | 1 |
from subsync.translations import _
from subsync.data import languages
from subsync import error
class AssetList(list):
"""List of assets.
Used mainly to select assets required for synchronization.
"""
def missing(self):
"""Get missing assets (as new `AssetList`).
Missing assets are ... | Python | 1 |
HostedGitInfo, Provider};
//!
//! let url = "https://github.com/foo/bar.git#branch";
//! let info = HostedGitInfo::from_url(url).unwrap();
//! assert_eq!(info.provider(), Provider::GitHub);
//! assert_eq!(info.user(), Some("foo"));
//! assert_eq!(info.project(), "bar");
//! assert_eq!(info.committish(), Some("branch"))... | Rust | 0 |
ityError, match="Access to 'pickle' is not allowed"
):
tree = parser.parse("pd.io.pickle.pickle.codecs")
interpreter.execute(tree)
# Test pickle access via pandas
with pytest.raises(SecurityError, match="Access to 'io' is not allowed"):
tree = parser.parse("pd.io.pickle.pc.io.abc")
... | Python | 1 |
p1jt_base",
"Op1jt_base",
"RexOp1indirect_jmp",
"Op1indirect_jmp",
"Op2trap",
"debugtrap",
"trapif",
"trapff",
"Op1pu_id_ref",
"RexOp1pu_id_ref",
"Op1is_zero",
"RexOp1is_zero",
"Op1is_invalid",
"RexOp1is_invalid",
"safepoint",
"elf_tls_get_addr",
"macho_tl... | Rust | 0 |
import pytest
from requests import get
from thirdweb.common.error import DuplicateFileNameException
from thirdweb.constants.urls import DEFAULT_IPFS_GATEWAY
from thirdweb.core.classes.ipfs_storage import IpfsStorage
from thirdweb.core.sdk import ThirdwebSDK
@pytest.mark.usefixtures("sdk")
@pytest.fixture()
def stora... | Python | 1 |
if weapon_slot.is_none() {
*weapon_slot = Some(WeaponInstance::from_drop(self.weapons.remove(i)));
}
}
}
let mut deads = Vec::new();
for (p, pickup) in self.pickups.iter().enumerate() {
if (pickup.pos - player.obj.pos).norm() <= 16. {
... | Rust | 0 |
esult["score"] = score
result["ground_truth"] = self.id2info[qid.split("@")[0]]["answer"]
if ground_truth_aug is not None:
score_aug = max(score_aug, score)
result["score"] = score * 0.7 + score_aug * 0.3
result["ground_truth_aug"] = g... | Python | 1 |
wait?;
if !results[0] {
return Err(RsmqError::QueueExists);
}
redis::cmd("SADD")
.arg(format!("{}QUEUES", self.ns))
.arg(qname)
.query_async(conn)
.await?;
Ok(())
}
/// Deletes a message from the queue.
///
/... | Rust | 0 |
sage}", subscribed_info['line_notify_token'])
def send_to_line_bot(msg_type, sub_num, author, message, video_url=None, thumbnail_url=None,
audio_url=None, audio_duration=None):
"""Send message to line bot.
Use zmq to send messages to line bot.
:param msg_type: Message type, can be '... | Python | 1 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | Python | 1 |
import time
import pytest
from lunar_tools.fps_tracker import FPSTracker
def test_segment_duration():
# Set update_interval to 0 so update() always triggers display update.
tracker = FPSTracker(update_interval=0)
tracker.start_segment("test")
# Sleep for 100ms
time.sleep(0.1)
# Call update to r... | Python | 1 |
st recent call last):
...
TypeError: Expected 'int', got: 'str'
test='hello'
^^^^^^^
>>> import polars as pl
>>> import pandas as pd
>>> df = pl.DataFrame([[1], [2], [3], [4], [5]], schema=[*"abcde"])
>>> ensure_type(df, pd.DataFrame, para... | Python | 1 |
hub.com/repos/{}/{}/actions/artifacts",
repo_user, repo_name
))
.body(Body::default())
.unwrap_or(Request::new(Body::default()));
let client_req_headers = client_req.headers_mut();
client_req_headers.append(
AUTHORIZATION,
HeaderValue::from_str(&format!("Bas... | Rust | 0 |
import numpy as np
from tensorflow import keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
#Učitavanje podataka MNIST
(train_images, train_labels), (test_images, test_label... | Python | 1 |
from rdkit import Chem
from rdkit.Chem import AllChem
def is_difluorobenzene(smiles: str):
"""
Determines if a molecule contains a difluorobenzene moiety (benzene ring with exactly 2 fluorine substituents).
Args:
smiles (str): SMILES string of the molecule
Returns:
bool: T... | Python | 1 |
c ref DEFAULT_MATERIALS: Vec<&'static str> = vec![
"BMC_Hidden",
"BMC_Ghost",
"BMC_Ghost_Fail",
"BMC_Plastic",
"BMC_Glass",
"BMC_Glow",
"BMC_Metallic",
"BMC_Hologram",
];
pub static ref BRICK_SIZE_MAP: HashMap<&'static str, (u32, u32, u32)> = vec![... | Rust | 0 |
_kerbosch2a_gp::explore(graph, reporter),
3 => bron_kerbosch2b::explore(graph, reporter),
4 => bron_kerbosch2b_gp::explore(graph, reporter),
5 => bron_kerbosch2b_gpx::explore(graph, reporter),
6 => bron_kerbosch2b_rp::explore(graph, reporter),
7 => bron_kerbosch3_gp::explore(grap... | Rust | 0 |
(m128_1, m128_1), sum128_1);
let m128_2 = _mm_loadu_ps(ptr.add(4));
sum128_2 = _mm_add_ps(_mm_mul_ps(m128_2, m128_2), sum128_2);
let m128_3 = _mm_loadu_ps(ptr.add(8));
sum128_3 = _mm_add_ps(_mm_mul_ps(m128_3, m128_3), sum128_3);
let m128_4 = _mm_loadu_ps(ptr.add(12));
... | Rust | 0 |
Link assets
if let Some(assets_path) = &target_config.assets_path {
aapt_package_cmd.arg("-A").arg(assets_path);
}
aapt_package_cmd.cwd(&target_directory).exec()?;
// Add shared libraries to the APK
for shared_library in shared_libraries {
// Copy the s... | Rust | 0 |
BaseOxmlElement):
"""
``<w:u>`` element, specifying the underlining style for a run.
"""
@property
def val(self):
"""
The underline type corresponding to the ``w:val`` attribute value.
"""
val = self.get(qn('w:val'))
underline = WD_UNDERLINE.from_xml(val)
... | Python | 1 |
},
Return { res: Option<Expr<'tcx>> },
Panic,
NeverReturn,
}
fn traverse_path<'tcx>(path: &mut Path<'tcx>, vars: &mut Map<Var, Ty<'tcx>>, n_nonces: &mut usize) {
match path {
Path::Var(var, ty) => {
if let Var::Nonce(i) = var {
assert!(i.is_none());
*i = Some(*n_nonces);
*n_n... | Rust | 0 |
ter)
size_score = 1.0 - min(obj.size / (2 * 1024 * 1024), 1.0)
# Recency component
if self.access_history[obj.key]:
time_since = current_time - self.access_history[obj.key][-1]
recency_score = math.exp(-time_since / 3600) # 1 hour decay
... | Python | 1 |
from 臺灣言語工具.語音合成.閩南語音韻.變調判斷 import 變調判斷
from 臺灣言語工具.音標系統.閩南語.臺灣閩南語羅馬字拼音 import 臺灣閩南語羅馬字拼音
def 台灣話口語講法(句物件):
結果句物件 = 句物件.轉音(臺灣閩南語羅馬字拼音, 函式='音值')
判斷陣列 = 變調判斷.判斷(結果句物件)
這馬所在 = 0
for 詞物件, 原底詞 in zip(結果句物件.網出詞物件(), 句物件.網出詞物件()):
新陣列 = []
for 字物件, 原底字 in zip(詞物件.內底字, 原底詞.內底字):
變調... | Python | 1 |
!(write_binary_section(writer, cipher, key, value));
}
for (key, value) in &entry.strings {
try!(write_string_section(writer, cipher, key, value));
}
if state == EntryState::Active {
try!(write_history_section(writer, cipher, &entry.history));
}
xml::write_end_tag(writer)
}
fn... | Rust | 0 |
加载用户配置"""
global current_user_info
config_file = os.path.join(base_save_path, 'user_config666.json')
if os.path.exists(config_file):
try:
with open(config_file, 'r', encoding='utf-8') as f:
saved_config = json.load(f)
current_user_info.update(saved_config)... | Python | 1 |
frame_for_ts: Option<Instant> = None;
let frame_delta = Duration::new(0, (1_000_000_000u64 / config.fps) as u32);
let frame_for_offset = config.data_window() / 2;
loop {
let now = Instant::now();
for event in event_pump.poll_iter() {
match event {
Event::Quit { .... | Rust | 0 |
#!/bin/usr/env python3
# coding: utf-8
"""Main class of the application"""
from datetime import datetime, timedelta
import time
from importlib import import_module
import os
# import socket
from flask import Flask, render_template, Response
import tlconfig
# import camera driver
if os.environ.get('CAMERA'):
print... | Python | 1 |
#=========================================================================
# BehavioralTranslatorL5.py
#=========================================================================
# Author : Peitian Pan
# Date : March 22, 2019
"""Provide L5 behavioral translator."""
from pymtl3.passes.rtlir.behavioral.BehavioralRTLIRG... | Python | 1 |
"""
Patch for daytona_api_client compatibility issue.
The daytona-sdk 0.18.1 (required by openhands-ai 0.40.0) expects certain classes to be
available in daytona_api_client, but in newer versions of daytona_api_client (0.21.0+),
these have been renamed from Workspace* to Sandbox*:
- WorkspaceState -> SandboxState
-... | Python | 1 |
Ok(Self::from_str_unsafe(alphabet, encode_order))
}
pub const fn from_str(alphabet: &str) -> Result<Self, ParseAlphabetError> {
Self::from_str_order(alphabet, EncodeOrder::OrderNormal)
}
}
#[derive(Debug, Eq, PartialEq)]
pub enum ParseAlphabetError {
/// Alphabets must be 64 ASCII bytes
... | Rust | 0 |
import _thread
import logging
import random
import time
import pytest
from redis import client, exceptions
import portalocker
from portalocker import redis, utils
logger = logging.getLogger(__name__)
try:
client.Redis().ping()
except (exceptions.ConnectionError, ConnectionRefusedError):
pytest.skip('Unable ... | Python | 1 |
in_x = a.mulmod(&t, &*SCALAR_FIELD); // t^7
}
// Return adds key again as blinding factor
(in_x + in_k) % &*SCALAR_FIELD
}
// Sponge mode instantiated by MiMC permutation with a fixed key
fn mimc_pe7_mp(in_x: Vec<&U256>, in_k: &U256, in_seed: U256, round_count: u64) -> U256 {
let mut r = in_k.... | Rust | 0 |
def merge(low, mid, high):
b = [0] * len(a)
h = low
j = mid + 1
i = low
while h <= mid and j <= high:
if a[h] <= a[j]:
b[i] = a[h]
h += 1
else:
b[i] = a[j]
j += 1
i += 1
while h <= mid:
b[i] = a[h]
h += 1
... | Python | 1 |
ing-1/src/main.rs<gh_stars>0
// Based on: https://github.com/linebender/druid/issues/1990 but
// use Label instead of TextBox as the data is immutable.
use druid::widget::{Flex, Label};
use druid::{AppLauncher, Widget, WidgetExt, WindowDesc};
use std::env;
pub fn main() {
let args: Vec<String> = env::args().collec... | Rust | 0 |
# Copyright 2025 The Marin Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | Python | 1 |
:
pass
for wordId, word in enumerate(outText):
if word in self.contractions:
outText[wordId] = self.contractions[word]
outText = ' '.join(outText)
return outText
def setAccuracy(self, accQA, accQuesType, accAnsType):
self.accuracy['overall... | Python | 1 |
Self {
hive_slide,
last_block: 0,
edge_set: HashSet::with_capacity(1000),
}
}
}
impl CoverageTracker for EdgeHashSetCoverageInfo {
fn name(&self) -> &'static str {
"EdgeHashSetCoverageInfo"
}
fn record_block(&mut self, block: usize) {
... | Rust | 0 |
operation_put_lifecycle_configuration(
input: &crate::input::PutLifecycleConfigurationInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_put_life... | Rust | 0 |
#!/usr/bin/env python
"""
Copyright (c) 2006-2024 sqlmap developers (https://sqlmap.org/)
See the file 'LICENSE' for copying permission
"""
from lib.core.data import logger
from plugins.generic.enumeration import Enumeration as GenericEnumeration
class Enumeration(GenericEnumeration):
def getBanner(self):
... | Python | 1 |
encoder().decoded_len(vector.base64).unwrap(), out.len());
assert_eq!(vector.raw, &out[..]);
}
}
#[test]
fn encode_and_decode_various_lengths() {
let data = [b'X'; 64];
for i in 0..data.len() {
let encoded = encoder().encode(&data[..i]);
// Make... | Rust | 0 |
s_when_idle() {
let timeout = Duration::from_millis(100);
let (service, mut handle) = mock::pair::<(), ()>();
let mut service = IdleLayer::new(timeout).layer(service);
run(move || {
// The inner starts available.
handle.allow(1);
assert!(service.poll_... | Rust | 0 |
assert_eq!(buffer.len(), SERIALIZED_BLOCK_HEADER_BUFFER_SIZE);
}
}
<reponame>jeparlefrancais/run-in-roblox
//! This file should slowly be factored away into smaller pieces. It came from
//! rbx-dom's generate_rbx_reflection crate.
use std::{
collections::HashMap,
fs::{self, File},
process::{self, Comma... | Rust | 0 |
print!("Creating Download Authorization ... ");
let download_auth = {
let file_name_prefix: FileNamePrefix = "".to_string().try_into().unwrap();
let req = GetDownloadAuthorizationRequest::builder()
.bucket_id(test_bucket.bucket_id())
.file_name_prefix(&file_name_prefix)
... | Rust | 0 |
urn
### continuous check
while self.imagicproc.poll() is None:
if waittime > 10:
sys.stderr.write(".")
time.sleep(waittime)
waittime *= 1.1
self.logf.flush()
if waiting is True:
tdiff = time.time()-self.starttime
if tdiff > 20:
tstr = self.timeString(tdiff)
sys.stderr.write("\nIMAGIC... | Python | 1 |
False)),
('is_premium', models.BooleanField(default=False)),
('premium_expiry', models.DateTimeField(blank=True, null=True)),
('privacy_dms', models.BooleanField(default=False)),
('privacy_posts', models.BooleanField(default=False)),
('grou... | Python | 1 |
if j >= xp_f.len() {
return None
}
if i >= xp_f.len() {
return None
}
let d_f = Self::get_d(xp_f, ann_f)?;
let mut c = d_f;
let mut s = zero;
// Calculate s and c
// p is implicitly calculated as part of c
// note that loop makes n - 1 iterations
for (k, xp_k) in xp_f.iter().enu... | Rust | 0 |
use enumset::*;
//! #[derive(EnumSetType, Debug)]
//! pub enum Enum {
//! A, B, C, D, E, F, G,
//! }
//! ```
//!
//! # Working with EnumSets
//!
//! EnumSets can be constructed via [`EnumSet::new()`] like a normal set. In addition,
//! `#[derive(EnumSetType)]` creates operator overloads that allow you to create Enu... | Rust | 0 |
elf, input, errors='strict'):
(object, consumed, byteorder) = \
codecs.utf_16_ex_decode(input, errors, 0, False)
if byteorder == -1:
self.decode = codecs.utf_16_le_decode
elif byteorder == 1:
self.decode = codecs.utf_16_be_decode
elif consumed>=2:
... | Python | 1 |
ations = relationship("ProductSpecification", back_populates="specification")
class ProductSpecification(Base):
__tablename__ = "product_specifications"
id = Column(Integer, primary_key=True, index=True)
product_id = Column(Integer, ForeignKey("products.id", ondelete="CASCADE"), nullable=False)
speci... | Python | 1 |
nformation."]
#[doc = r" Use the `Deref` and `DerefMut` implementations if possible."]
pub fn build_dangling(self) -> AndroidHardwareBufferPropertiesANDROID {
self.0
}
}
impl<'a> std::default::Default for AndroidHardwareBufferPropertiesANDROIDBuilder<'a> {
fn default() -> AndroidHardwareBufferPr... | Rust | 0 |
20_ZXY: u64 = 0b1000;
pub const JS3_ROT120_MASK: u64 = 0b1100;
pub const JS3_ROT180_ID: u64 = 0b00;
pub const JS3_ROT180_Z: u64 = 0b01;
pub const JS3_ROT180_X: u64 = 0b10;
pub const JS3_ROT180_Y: u64 = 0b11;
pub const JS3_ROT180_MASK: u64 = 0b11;
impl Symmetry3 {
#[inline]
... | Rust | 0 |
import _plotly_utils.basevalidators
class HovertemplatesrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self, plotly_name="hovertemplatesrc", parent_name="funnelarea", **kwargs
):
super(HovertemplatesrcValidator, self).__init__(
plotly_name=plotly_name,
... | Python | 1 |
meta_data.csv.gz'), index_col=0)
meta_data = meta_data.dropna(axis=1, how='any')
meta_data['bmi'] = pd.Categorical(meta_data['bmi'], categories=['obese', 'overweight', 'lean'])
# run ancom-bc reimplemented in python for the HITChip Atlas dataset
res = ancombc(table+1, meta_data, "age + ... | Python | 1 |
result_u256)
.map_err(|_| DispatchError::from(Error::<T>::MathOverflow))?;
log!(
info,
"calculate_sell_price: ({}, {}, {}) -> {}",
input_reserve,
output_reserve,
sell_amount,
result
);
Ok(result)
}
pub fn calculate_sell_price_no_fee(
// Callculate amount of tokens to be received by selll... | Rust | 0 |
import pandas as pd
import cv2
import os
import shutil
df=pd.read_csv("labels1.csv")
#label=str(df["emotion"])+str(df["skintone"])+str(df["age"])
df["label"]=df["emotion"].astype(str)+df["skintone"].astype(str)+df["age"].astype(str)+df["race"].astype(str)
distribution=df["label"].value_counts()
#convert to dict
print(... | Python | 1 |
thede's data.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Thede {
#[serde(skip)]
#[serde(default = "dummy_id")]
id: Id,
hash: u64,
language: Language,
}
impl Thede {
/// Returns a reference to the language.
pub fn language(&self) -> &Language {
&self.la... | Rust | 0 |
#!/usr/bin/env python
"""
Example with short term plasticity,
with event-driven updates defined by differential equations.
"""
from brian import *
tau_e = 3 * ms
taum = 10 * ms
A_SE = 250 * pA
Rm = 100 * Mohm
N = 10
eqs = '''
dx/dt=rate : 1
rate : Hz
'''
input = NeuronGroup(N, model=eqs, threshold=1., reset=0)
input... | Python | 1 |
gba_idx]; // left
let b = if is_first_row {
0
} else {
above[pixel_idx][rgba_idx]
}; // above
let c = if is_first_row {
0
} else {
... | Rust | 0 |
#User function Template for python3
class Solution:
#Function to rotate an array by d elements in counter-clockwise direction.
def rotateArr(self, arr, d):
#Your code here
n=len(arr)
d%=n # Handling the case when d>size of array
# reverse the d elements
reverse(arr,0,d-... | Python | 1 |
derive(Clone)]
struct RepositoryMock {
persist: Mock<Person, Option<String>>,
}
impl RepositoryMock {
fn new() -> RepositoryMock {
RepositoryMock {
persist: Mock::new(),
}
}
}
impl Repository for RepositoryMock {
fn persist(&self, person: Person) -> Option<String> {
... | Rust | 0 |
seds=(1,))
#lines.set_facecolors(cm.jet(np.random.rand(1))) #随机颜色
lines.set_facecolors(cm.jet(0.02))
lines.set_edgecolors('g')
lines.set_linewidth(0.3)
ax.add_collection(lines)
# 从Txt中读取环境建模保存的信息
squareprolist = []
with... | Python | 1 |
ControlCharacterWhileParsingString,
/// Object key is not a string.
KeyMustBeAString,
/// Lone leading surrogate in hex escape.
LoneLeadingSurrogateInHexEscape,
/// JSON has a comma after the last value in an array or map.
TrailingComma,
/// JSON has non-whitespace trailing characte... | Rust | 0 |
"""
Copyright 2025 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
d... | Python | 1 |
hese should be a 4D tensor with shape
``(num_filters, num_input_channels, filter_rows, filter_columns)``.
See :func:`lasagne.utils.create_param` for more information.
b : Theano shared variable, expression, numpy array, callable or ``None``
Initial value, expression or initializer for the b... | Python | 1 |
#!/usr/bin/env python3
from os import PathLike
from typing import Union, Any, Dict, Callable
import torch as th
from pathlib import Path
from presto.util.path import ensure_directory
def step_from_ckpt(ckpt_file: str) -> float:
"""
Brittle string-parse operation to get the `global_step`
parameter from t... | Python | 1 |
cfg(test)]
mod tests {
use crate::pattern_matching::{
destruct_enums, destruct_structs, destruct_tuples, get_number_value, report_age,
use_binding, use_guard, Color, Foo,
};
#[test]
fn test_get_number_value() {
assert_eq!("One", get_number_value(1));
assert_eq!("Prime", ... | Rust | 0 |
import pyautogui
import time
campoAtleta = pyautogui.locateCenterOnScreen("aula10/atleta.png", grayscale=True, confidence=0.9)
pyautogui.click(campoAtleta,duration=0.3)
pyautogui.write("Tainá Lemes")
campoModalidade = pyautogui.locateCenterOnScreen("aula10/modalidade.png", grayscale=True, confidence=0.9)
pyautogui.cli... | Python | 1 |
param_untilTime is not None:
params["untilTime"] = str(param_untilTime).lower() if isinstance(param_untilTime, bool) else param_untilTime
if param_filter is not None:
params["filter"] = str(param_filter).lower() if isinstance(param_filter, bool) else param_filter
if param_kind is not None:
... | Python | 1 |
from re import compile
from ast import literal_eval
from io_scs_tools.utils.printout import lprint
def read_data(filepath, print_info=False):
"""Reads data from mat file and returns it's attributes as dictionary.
:param filepath: material file path
:type filepath: str
:param print_info: switch for p... | Python | 1 |
the size from the type descr found in the cbox
let cbox_in = PointerCast(bcx, cbox_in, llopaquecboxty);
let tydescptr = GEPi(bcx, cbox_in, ~[0u, abi::box_field_tydesc]);
let tydesc = Load(bcx, tydescptr);
let tydesc = PointerCast(bcx, tydesc, T_ptr(ccx.tydesc_type));
let sz = Loa... | Rust | 0 |
'runs_range_min': outcome.runs_range_min,
'runs_range_max': outcome.runs_range_max,
'total_outcomes': outcome.total_outcomes,
'successful_chases': outcome.successful_chases,
'win_probability': float(outcome.win_probability),
... | Python | 1 |
d_list = load_data(out_fname)
eval_mode = {'check_doc_id_correct': True, 'standard': False}
# print(fever_score(d_list, d_list, mode=eval_mode, error_analysis_file=Path(out_fname).parent / "analysis.log"))
print(fever_score(d_list, d_list, mode=eval_mode, verbose=False))
def used_func_for_fast_key_word_ma... | Python | 1 |
help with
/// error detection, and you could potentially use `derive` over the
/// relevant subregion to calculate such a checksum.
pub fn derive<F, T>(&mut self, rng: std::ops::Range<u64>, f: F) -> Result<T>
where
F: FnOnce(&mut derive::DeriveRead<W>) -> Result<T>,
{
if rng.end < r... | Rust | 0 |
l6-30p")]
NemaL630p,
#[serde(rename = "nema-l6-50p")]
NemaL650p,
#[serde(rename = "nema-l10-30p")]
NemaL1030p,
#[serde(rename = "nema-l14-20p")]
NemaL1420p,
#[serde(rename = "nema-l14-30p")]
NemaL1430p,
#[serde(rename = "nema-l14-50p")]
NemaL1450p,
#[serde(rename = "nema-... | Rust | 0 |
{
print_chr(' ');
}
input.name = 19;
t_print!("( ");
open_parens += 1;
rust_stdout.as_mut().unwrap().flush().unwrap();
} else {
input.name = 18;
input.synctex_tag = 0;
};
}
/// converting the current string into a token list.
///
/// The `str_t... | Rust | 0 |
,
"basement", "null"]
# %%
geo_model.add_features("Formations")
one_formation_every = 3
geo_model.add_surfaces(formations[0:4*one_formation_every:one_formation_every])
geo_model.map_stack_to_surfaces({"Formations": ["etchegoin", "macoma", "chanac", "mclure"],
"Default se... | Python | 1 |
style.fg(Cyan),
"37" => style = style.fg(White),
"38" => if let Some(c) = parse_into_high_colour(&mut iter) { style = style.fg(c) },
// Background colours
"40" => style = style.on(Black),
"41" => style = style.on(Red),
"42... | Rust | 0 |
j1 = psi[n1]['j']
U_1_c = cdgmm(U_0_c, psi[n1][0])
if j1 > 0:
U_1_c = periodize(U_1_c, k=2 ** j1)
U_1_c = compute_fft(U_1_c, 'C2C', inverse=True)
U_1_c = compute_fft(modulus(U_1_c), 'C2C')
# Second low pass filter
U_2_c =... | Python | 1 |
WBS, (60, 2900.))]
fn test_optimizer(#[case] segmentation_type: SegmentationType, #[case] expected: (usize, f64)) {
let control = Control::default();
let optimizer = testing::TrivialOptimizer { control: &control };
let mut segmentation = Segmentation::new(segmentation_type, &optimizer);
... | Rust | 0 |
))?;
Ok(())
}
fn setup_home() -> Result<PathBuf, SolcVmError> {
let home_dir = SVM_HOME.to_path_buf();
if !home_dir.as_path().exists() {
fs::create_dir_all(home_dir.clone())?;
}
Ok(home_dir)
}
fn setup_version(version: &str) -> Result<(), SolcVmError> {
let v = version_path(version);
... | Rust | 0 |
test_name!())
.mount(TEST_MOUNT_NAME, "test-data/small-collection")
.build();
ctx.index.update().unwrap();
let albums = ctx.index.get_random_albums(1).unwrap();
assert_eq!(albums.len(), 1);
}
#[test]
fn can_get_recent_albums() {
let ctx = test::ContextBuilder::new(test_name!())
.mount(TEST_MOUNT_NAME, "test-... | Rust | 0 |
rr(Error::<T>::GeneticAnalysisOrderNotFound)
}
let genetic_analysis_order_can_be_refunded =
Self::genetic_analysis_order_can_be_refunded(genetic_analysis_order.clone().unwrap());
if !genetic_analysis_order_can_be_refunded {
return Err(Error::<T>::GeneticAnalysisOrderNotYetExpired)
}
let genetic_analys... | Rust | 0 |
[test]
fn write_does_nothing () {
let mut memory = Rom::new("c64/kernal.rom");
memory.set(0x0123, 0x55);
assert!(memory.get(0x0123) != 0x55);
}
}
#[cfg(test)]
mod streaming_tests {
use mockall::{mock, predicate::*};
use parking_lot::RwLock;
use pico_common::{
Cha... | Rust | 0 |
s(loadCombinations.ULSPartialSafetyFactors(0,1.35,0,1), loadCombinations.SLSPartialSafetyFactors(0,1))
#### Eurocode 7 variable load. Table AN.9 [table A2.4(B)]. Live load on backfill surfaces.
partial_safety_factors['load_on_backfill_set_b']= loadCombinations.PartialSafetyFactors(loadCombinations.ULSPartialSaf... | Python | 1 |
t(df['i (A/cm²)'], Hydro_com, 'bo', label='Hydrogen Consumption Data')
plt.plot(i_fit, hydro_fit, 'r-', label='Hydrogen Consumption (fitted)')
plt.xlabel('Current Density (A/cm²)', fontsize=12)
plt.ylabel('Hydrogen Consumption (g/s)', fontsize=12)
plt.title('Hydrogen Consumption vs Current Density', fon... | Python | 1 |
# import google.generativeai as genai
# import os
# from dotenv import load_dotenv
# # Load API Key
# load_dotenv()
# API_KEY = os.getenv("GEMINI_API_KEY")
# # Check if API key is loaded
# if not API_KEY:
# print("❌ GEMINI_API_KEY not found! Check your .env file.")
# else:
# print("✅ GEMINI_API_KEY loaded suc... | Python | 1 |
pub fn init( param: Param<TS,TC,TObs>,
param_obs: ParamObstacles<TObs>,
param_tree: ParamTree ) -> PlannerBasic<TS,TC,TObs> {
use zpatial::mazth::i_shape::IShape;
let mut obs_tree = Bvh::init(10);
//get bounds as [(idx,aabb_bound)]
let bo... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.