text
string
label_name
string
labels
int64
e>physx/src/articulation_joint_base.rs // Author: <NAME> <<EMAIL>> // Copyright © 2019, Embark Studios, all rights reserved. // Created: 16 April 2019 #![warn(clippy::all)] #![warn(rust_2018_idioms)] /*! */ use super::transform::{gl_to_px_tf, px_to_gl_tf}; use super::{ articulation_joint_reduced_coordinate::Art...
Rust
0
]) }; error.loc_trace.label_macro_invocation(diagnostic) } } impl From<Error> for Vec<Diagnostic<FileId>> { fn from(error: Error) -> Self { vec![error.into()] } } impl error::Error for Error {} impl Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Resu...
Rust
0
let (number_of_bytes, src_addr) = socket.recv_from(&mut buffer).expect("Didn't receive data"); *(&buffer[0]) // gets the first integer }; println!("Player number: {:?}",player_number); (socket, player_number) } pub fn send(socket: &UdpSocket, inputs: &InputValues,){ println!("Sending Data...
Rust
0
&mut Self::Target { &mut self.0 } } impl From<crate::W<IRAM_DRAM_AHB_SEL_SPEC>> for W { #[inline(always)] fn from(writer: crate::W<IRAM_DRAM_AHB_SEL_SPEC>) -> Self { W(writer) } } #[doc = "Field `MASK_PRO_IRAM` reader - "] pub struct MASK_PRO_IRAM_R(crate::FieldReader<bool, bool>); impl...
Rust
0
{ left: Some(left), right, hash } } pub fn new_leaf(value: usize) -> Self { let hash = hash_value(value); Node { left: None, right: None, hash } } } fn to_parents(nodes: &mut Vec<Node>) -> Vec<Node> { ...
Rust
0
ine_width; StrokeTessellator::new().tessellate( cmd.path.iter(), &options, &mut BuffersBuilder::new(&mut geometry, WithId(1)) ).unwrap(); } if let Some(hatch) = cmd.hatch { let mut path = Path::builder(); let mut hatcher = Hatcher::new(); ...
Rust
0
ด้วยการปรับ timing ของ request""" session = await self.setup_stealth_session() # Randomized timing patterns timing_patterns = [ [0.5, 1.2, 0.8, 2.1], # Human-like pattern [0.1, 0.1, 0.1, 5.0], # Burst then pause [random.uniform(0.5, 3.0) for _ in range(4)]...
Python
1
status = unsafe { sys::napi_call_function( raw_env, recv, js_callback, args.len(), args.as_ptr(), ptr::null_mut(), ) }; } Err(e) if ES::VALUE == ErrorStrategy::Fatal::VALUE => { status = unsafe { sys::napi_fatal_excep...
Rust
0
import os import json import argparse # remove some tasks from the list parser = argparse.ArgumentParser() parser.add_argument( "--files", "-f", type=str, default="exps" ) args = parser.parse_args() data_path = "prompts/data" generated_task_path = os.path.join(data_path, "generated_tasks.json") generated_task_...
Python
1
device=device, batch_size=bs, bounds=bounds, octree_depth=octree_depth, num_chunks=num_chunks, disable=not self.zero_rank ) # 3. decode texture for i, ((mesh_v, mesh_f), is_surface) in enumerate(zip(mesh_v_f, has_surface)): ...
Python
1
0x33, 0x33, 0x33, 0x33, 0xb3, 0x11, 0xab, 0x40, 0xee, 0x53, 0x48, 0x41, 0x50, 0x07, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x08, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x81, 0x03, 0x0c, 0x80, 0x02, 0xd0, 0x0f, 0...
Rust
0
libjvm.so` to `LD_LIBRARY_PATH` environment variable. //! //! The exact relative path to `jvm` library is version-specific. //! //! For more information - see documentation in [build.rs](https://github.com/jni-rs/jni-rs/tree/master/build.rs). //! //! ## See Also //! //! ### Examples //! - [Example project][jni-rs-examp...
Rust
0
Location}; use crate::utils::{compile_shader, link_program, set_panic_hook,log_num}; #[macro_export] macro_rules! float_32_array { ($arr:expr) => {{ let memory_buffer = wasm_bindgen::memory() .dyn_into::<WebAssembly::Memory>()? .buffer(); let arr_location = $arr.as_ptr() as...
Rust
0
involve fetching the Node from a remote /// machine; consider setting a deadline to stop it. fn get(&self, cid: &Cid) -> T; } /// NodeAdder adds nodes to a DAG. pub trait NodeAdder<T: Node> { /// Add adds a node to this DAG. fn add(&self, node: T); } /// NodeGetters can optionally implement this inte...
Rust
0
#!/usr/bin/env python3 """ Download the face swap model from alternative sources. """ import os import urllib.request import hashlib from pathlib import Path def download_with_progress(url, destination): """Download file with progress bar.""" def download_hook(block_num, block_size, total_size): downl...
Python
1
rom_cbor_value(_value: Value) -> coset::Result<Self> { unreachable!("Unimplemented.") } fn to_cbor_value(self) -> coset::Result<Value> { macro_rules! fields { ($map: ident { $($num: literal => $field: ident),* }) => { $( if let Some(ref v) = self. $fi...
Rust
0
_ERR_INVALID_PURPOSE: c_int = 26; pub const X509_V_ERR_CERT_UNTRUSTED: c_int = 27; pub const X509_V_ERR_CERT_REJECTED: c_int = 28; pub const X509_V_ERR_SUBJECT_ISSUER_MISMATCH: c_int = 29; pub const X509_V_ERR_AKID_SKID_MISMATCH: c_int = 30; pub const X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH: c_int = 31; pub const X509_V...
Rust
0
ate::format::problem::*; use crate::helpers::*; use hashbrown::HashSet; #[test] fn can_group_jobs() { let problem = Problem { plan: Plan { jobs: vec![ create_delivery_job_with_group("job1", (1., 0.), "one"), create_delivery_job("job2", (2., 0.)), ...
Rust
0
; acc.nb_array_containers += sub.nb_array_containers; acc.nb_bitmap_containers += sub.nb_bitmap_containers; acc.nb_values_array_containers += sub.nb_values_array_containers; acc.nb_values_bitmap_containers += sub.nb_values_bitmap_containers; acc.nb_bytes_arra...
Rust
0
= format!( // "{:.2?}", // Duration::from_nanos(self.producer_latency_histogram.value_at_percentile(50.0)) //); //let producer_latency_p90 = format!( // "{:.2?}", // Duration::from_nanos(self.producer_latency_histogram.value_at_percentile(90.0)) //); ...
Rust
0
import cv2 as cv import numpy as np import argparse W = 52 # window size is WxW C_Thr = 0.43 # threshold for coherency LowThr = 35 # threshold1 for orientation, it ranges from 0 to 180 HighThr = 57 # threshold2 for orientation, it ranges from 0 to 180 ## [calcGST] ## [calcJ_header] ## [calcGST_pro...
Python
1
p=None, inplanes=64, input_3x3=False, downsample_kernel_size=1, downsample_padding=0, last_stride=2, fc_dims=None, **kwargs ) if pretrained == 'imagenet': model_url = pretrained_settings['se_resnet152']['imagenet']['url'] init_pretrained_we...
Python
1
from typing import Any, Dict, List, Type, TypeVar, Union from attrs import define as _attrs_define from attrs import field as _attrs_field from ..types import UNSET, Unset T = TypeVar("T", bound="NotificationUpdateRequest") @_attrs_define class NotificationUpdateRequest: """Request schema for update operations...
Python
1
Err(e) => { info!("Failed to get price history: {}", e.to_string()); return Vec::new(); } }; resp.candles } /// get_daily_candle is responsible for fetching a daily candle for a given symbol pub fn get_daily_candle(&self, symbol: Stri...
Rust
0
乔瑟","愚人众小兵d","愚人众小兵a","愚人众小兵b","愚人众小兵c","吴老五","吴老二","滑头鬼","言笑","吴老七","士兵h","士兵i","士兵a","士兵b","士兵c","士兵d","士兵e","士兵f","士兵g","奏太","斯坦利","掇星攫辰天君","小头","大武","陶义隆","杉本","苏西","嫌疑人a","嫌疑人b","嫌疑人c","嫌疑人d","斯万","剑客a","剑客b","阿二","忠胜","忠夫","阿敬","孝利","鹰司进","高山","九条孝行","毅","竹内","拓真","卓也","太郎丸","泰勒","手岛","哲平","哲夫","托克","大boss","阿强",...
Python
1
import logging import torch from torch.utils.dlpack import from_dlpack, to_dlpack import cupy as cp class _TorchOperator(torch.autograd.Function): """operators into Torch functions""" @staticmethod def forward(ctx, x, forw, adj, device, devicetorch): ctx.forw = forw ctx.adj = adj ...
Python
1
data['message'] # Generate AI response ai_response = vietnamese_teacher.generate_response(user_message) return jsonify({ 'response': ai_response, 'status': 'success' }) except Exception as e: return jsonify({'error': str(e)}...
Python
1
import requests from icecream import ic def search_song_by_name(name: str, limit: int = 10): # TODO: url encode query = "%20".join(name.split()) url = f'https://www.chosic.com/api/tools/search?q={query}&type=track&limit={limit}' headers = { 'authority': 'www.chosic.com', 'app': 'playlis...
Python
1
= root_dir2_dir1_sub.join("file2.txt"); let root_dir2_dir3_file3 = root_dir2_dir3.join("file3.txt"); assert!(root_dir2_dir1_file1.exists()); assert!(root_dir2_dir1_sub_file2.exists()); assert!(root_dir2_dir3_file3.exists()); }).join(); loop { match rx.try_recv() { ...
Rust
0
} pub fn create_with_config<T: Number, B: BufferBuilder>( context: &Context, creator: B, mem_config: MemConfig, ) -> Output<Buffer> { Buffer::create::<T, B>( context, creator, mem_config.host_access(), mem_config.kernel_access(...
Rust
0
22348568320908e-04] ] if orbitCase == 'circular' and planetCase == 'Jupiter' and useBias == False and useBounds == True: trueMag = [ [-1.6819836450589402e-04, -2.2784371297700405e-04, -3.5000000000000000e-04], [1.9468153473841567e-04, 2.7464566890817013e-04, 1.928536102860046...
Python
1
84be] 0x003a, 0x84be, // --> [RexOp2ldWithIndexDisp8#84be] 0x0042, 0x84be, // --> [RexOp2ldWithIndexDisp32#84be] and stop 0x004b, 0x84be, // end of sload8_complex.i64 (I64) // 000116: spill.i64 (I64) // --> [RexOp1spillSib32#8089] and stop // 000116: spill.r64 (I64) // --> [RexOp...
Rust
0
y['title']}_part{entry['index']}.zip" part_path = os.path.join(save_dir, part_name) self.log(f"下载 {i+1}/{len(volumes)}:{part_name}") download_file(file_id, part_path, self.update_progress) downloaded_parts.append(part_path) # 合并为 zip 文件 merged_zip = os.pa...
Python
1
error!("Requested key size is not supported ({})", attributes.bits); Err(Error::InvalidArgument) } }, // Curve used primarily in France and elsewhere in Europe. EccFamily::Frp => match attr...
Rust
0
let value: i32 = row.get(0); assert_eq!(value, 1); } } <filename>src/core/object/noneobj.rs use std::cell::RefCell; use std::rc::Rc; use object::{PyObject, PyInnerObject}; use object::typeobj::*; thread_local! ( pub static PY_NONE_TYPE: Rc<PyObject> = { let nonetp = PyTypeObject { ...
Rust
0
; } } /// Algorithms for rounding decimal numbers. /// /// The rounding modes are precisely defined in [The Arithmetic Model][model] /// chapter of the General Decimal Arithmetic specification. /// /// [model]: http://speleotrove.com/decimal/damodel.html #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] pub enum ...
Rust
0
import pytest import time from fakeredis import FakeStrictRedis from celery import Celery from celery_once import QueueOnce, AlreadyQueued from redis.lock import Lock as RedisLock @pytest.fixture() def redis(monkeypatch): fake_redis = FakeStrictRedis() fake_redis.flushall() monkeypatch.setattr("celery_on...
Python
1
change_grant(olsenbanden_organization) == (False, "too many credentials available")) def test_ews_grant_selection6( self, *, olsenbanden_organization, ews_grant_with_password, another_ews_grant_with_password): """Given two EWSGrants with passw...
Python
1
&Path) -> &PathSegment { path.segments .iter() .last() .expect("expected at least one segment in path") } use std::fs::File; use zen_archive::Vdfs; fn main() -> Result<(), Box<dyn std::error::Error>> { let vdf_file = File::open("/home/tom/Steam/common/Gothic II/Data/Anims.vdf")?; le...
Rust
0
x = 10 y = 20 print(x + y)
Python
1
..Default::default() }; assert_eq!( AuthMechanism::from_stream_description(&description_both), AuthMechanism::ScramSha256 ); } #[test] fn negotiate_sha1_only() { let description_sha1 = StreamDescription { sasl_supported_mechs: Some(MECHS[0..=0].to_vec()), ..Default::...
Rust
0
| | iNum | Point number to modify. | iX | X coordinates of new point. | iY | Y coordinates of new point. | Example: ...
Python
1
, Eq, PartialOrd, Ord)] pub struct KeyApiResponse { pub server_name: String, pub valid_until_ts: u64, pub verify_keys: BTreeMap<String, VerifyKey>, pub tls_fingerprints: Vec<TlsFingerprint>, } <gh_stars>1-10 use diesel::prelude::*; use diesel::result::Error as DieselError; use diesel::BelongingToDsl; us...
Rust
0
S3BucketServerSideEncryptionConfiguration, ) { if let Some(var_1911) = &input.rules { let mut array_1912 = object.key("Rules").start_array(); for item_1913 in var_1911 { { let mut object_1914 = array_1912.value().start_object(); crate::json_ser::serialize_...
Rust
0
; fn deref(&self) -> &String { &self.0 } } impl fmt::Display for Code { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", &self.0) } } #[derive(Debug, PartialEq, Clone)] pub struct EncryptedMessage { pub side: TheirSide, pub phase: Phase, pub body: ...
Rust
0
"<< ipv6_prefixes >>", &Self::sanitize_prefixes(&self.configuration.ipv6_prefixes).join(",\n"), ) } /// Writes a given content to a file at the given path fn write_to_file(file_path: &PathBuf, content: &str) -> NodeManagerResult<()> { write_atomically(file_path, |...
Rust
0
let query_string = { #[serde_with::skip_serializing_none] #[derive(Serialize)] struct QueryParams<'b> { debug: Option<bool>, error_trace: Option<bool>, #[serde(serialize_with = "crate::client::serialize_coll_qs")] ...
Rust
0
"""Util that calls Twilio.""" from typing import Any, Dict, Optional from langchain_core.utils import get_from_dict_or_env from pydantic import BaseModel, ConfigDict, model_validator class TwilioAPIWrapper(BaseModel): """Messaging Client using Twilio. To use, you should have the ``twilio`` python package i...
Python
1
::send_message(self.id, &self.sender)?; } else if signal.is_member(MEMBER_PROPERTIES_CHANGED)? { // wait for /sys/class/power_supply files updates thread::sleep_secs(2); communication::send_message(self.id, &self.sender)?; } Ok(()) ...
Rust
0
ssion: Option<String>, #[serde(flatten)] extra: JsonObject, } impl Outgoing for CustomAuthData<'_> { type Incoming = IncomingCustomAuthData; } /// Identification information for the user. #[derive(Clone, Debug, PartialEq, Eq, Outgoing, Serialize)] #[serde(from = "user_serde::IncomingUserIdentifier", into ...
Rust
0
ker`) /// If `overwrite_client_id` is `false`, the message's `sender` won't be touched (for broker forwarding) #[inline(never)] // Not inlined to make cpu-level reodering (hopefully?) improbable unsafe fn send(&mut self, msg: *mut LlmpMsg, overwrite_client_id: bool) -> Result<(), Error> { // dbg!("S...
Rust
0
float(motion_length), axis=-1) obs = np.concatenate([obs, progress_ob], axis=-1) if config['env_motion_ob'] and not config['env_motion_ob_onehot']: motion_id_ob = np.expand_dims(motion_id.astype(np.float) / float(num_motion), axis=-1)...
Python
1
市场地位,争取行业内的认可和尊重。 * 自我实现需求:公司追求创新、持续改进和扩展,实现长期的战略目标和使命。 ## Output format {name}关于{task}的需求等级: 1、生理需求(相关性:高、中、低)(解释)\n 2、安全需求(相关性:高、中、低)(解释)\n 3、社交需求(相关性:高、中、低)(解释)\n 4、尊重需求(相关性:高、中、低)(解释)\n 5、自我实现需求(相关性:高、中、低)(解释) """} ], stream=True ) for chunk in completion: content = chunk...
Python
1
!( match_start_end_empty_rep_rev, r"(?:$^)*", "a\nb\nc", (0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5) ); // Test negated character classes. mat!(negclass_letters, r"[^ac]", "acx", Some((2, 3))); mat!(negclass_letter_comma, r"[^a,]", "a,x", Some((2, 3))); mat!(negclass_letter_space...
Rust
0
unsafe { &(*(::std::ptr::null::<rte_fbarray>())).name as *const _ as usize }, 0usize, concat!( "Offset of field: ", stringify!(rte_fbarray), "::", stringify!(name) ) ); assert_eq!( unsafe { &(*(::std::ptr::null::<rte_fbarray>())).co...
Rust
0
}) .collect(); self.digest.min = digests .iter() .min_by(|a, b| a.min.partial_cmp(&b.min).unwrap()) .unwrap() .min; self.digest.max = digests .iter() .max_by(|a, b| a.max.partial_cmp(...
Rust
0
00); } } <gh_stars>0 use super::*; use crate::models::kernel::{Kernel, NewKernel}; use crate::models::storage::Storage; #[derive(Copy, Clone)] pub struct KernelService {} impl KernelService { pub fn new() -> Self { KernelService {} } pub fn all(&self, conn: &DbConnection) -> Result<Vec<Kernel...
Rust
0
import os import argparse import torch import torch.nn as nn import torch.nn.functional as F from collections import OrderedDict from srcs.models.modnet_torchscript import MODNet if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--input_path', type=str, default='saved_model/di...
Python
1
# Вывод элементов матрицы в порядке: слева направо снизу вверх n, m = map(int, input().split()) mtrx = [] for i in range(n): mtrx.append([int(x) for x in input().split()]) [print(*x) for x in mtrx[::-1]]
Python
1
Self { level .clamp(MIN_PRIORITY, MAX_PRIORITY) .try_into() // something has gone very wrong if the level is out of bounds .expect(&format!("{} is not a valid priority", level)) } } #[cfg(test)] mod tests { use chrono::NaiveDateTime; use num_traits::...
Rust
0
Label(ref label) => { let off = memlabel_finalize(insn_off, label); (vec![], MemArg::Label(MemLabel::PCRel(off))) } _ => (vec![], mem.clone()), } } /// Helper: get a ConstantData from a u64. pub fn u64_constant(bits: u64) -> ConstantData { let data = bits.to_le_bytes(); ...
Rust
0
let mut w = 0.0; let mut v = 1.0; u = t; for _i in 0..8 { let x = ((ax * u + bx) * u + cx) * u; if (x - t).abs() < epsilon { return ((ay * u + by) * u + cy) * u; } ...
Rust
0
a.unwrap().target_url, claims.metadata.unwrap().target_url ); assert!(vres.is_ok()); } #[test] fn full_validation() { let kp = KeyPair::new_account(); let claims = Claims { metadata: Some(Actor::new( "test".to_string(), ...
Rust
0
lImpl<TI2, O2>, HashMap<OutletId, OutletId>)> where TI1: Fact + Clone + 'static, TI2: Fact + Clone + 'static, O1: Display + Debug + AsRef<dyn Op> + AsMut<dyn Op> + Clone + 'static + Translate<TI1, O1, TI2, O2, Ctx>, O2: Display + Debug + AsRef<dyn Op> + As...
Rust
0
) if self.use_abs_pos_embed: x = x + self.absolute_pos_embed x = self.drop_after_pos(x) outs = [] for i, stage in enumerate(self.stages): x, hw_shape, out, out_hw_shape = stage(x, hw_shape) if i == 0 and self.return_stereo_feat: out = ...
Python
1
# encoding: utf-8 """ @author: liaoxingyu @contact: sherlockliao01@gmail.com """ import copy import logging from collections import OrderedDict import torch from fastreid.evaluation.evaluator import DatasetEvaluator from fastreid.utils import comm logger = logging.getLogger(__name__) class AttrEvaluator(DatasetEv...
Python
1
Lh"ddlmZmZmZddlZddlZddlmZddlZedeZ ej dde_ ddd d Z e d d g dZe dd g dZe ddg ...
Python
1
# model settings model = dict( type='TSN3D', backbone=dict( type='InceptionV1_I3D', pretrained=None, modality='RGB'), spatial_temporal_module=dict( type='SimpleSpatialTemporalModule', spatial_type='avg', temporal_size=-1, spatial_size=-1), segmenta...
Python
1
._gcd_import(name[level:], package, level) _RELOADING = {} def reload(module): """Reload the module and return it. The module must have been successfully imported before. """ if not module or not isinstance(module, types.ModuleType): raise TypeError("reload() argument must be a module") ...
Python
1
self) -> TSTCTL_W { TSTCTL_W { w: self } } #[doc = "Bit 7 - Set Global Non-periodic IN NAK"] #[inline(always)] pub fn sgnpinnak(&mut self) -> SGNPINNAK_W { SGNPINNAK_W { w: self } } #[doc = "Bit 8 - Clear Global Non-periodic IN NAK"] #[inline(always)] pub fn cgnpinnak(&mut self) -> CGNPINNAK_W ...
Rust
0
_query_system) // type mismatch resolving `for<'w, 's> <ReadFetch<B> as Fetch<'w, 's>>::Item == bool` // required because of the requirements on the impl of `FilterFetch` for `ReadFetch<B>` .add_system(missing_brackets_in_query_system) // NOTE: The errors for these two systems do not app...
Rust
0
USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. use crate::{ compone...
Rust
0
} } } #[test] fn test_fib_fri_iop_verifier() { use ff::Field; use crate::Fr; use crate::air::Fibonacci; use crate::air::TestTraceSystem; use crate::air::IntoAIR; use crate::fft::multicore::Worker; use crate::transcript::Transcript; use crate::arp::*; use crate::ali::*; use ...
Rust
0
_dispatch(disp); // create the attribs let attribs = GlContextRule::convert_ctx_attrib_to_classic(rules) .into_iter() .map(|c| c as u32) .collect(); // get xid from server let xid = dpy.display().create_context_attribs_arb( glx::Fbconfig::c...
Rust
0
from .. import Provider as DateTimeProvider class Provider(DateTimeProvider): DAY_NAMES = { "0": "Воскресенье", "1": "Понедельник", "2": "Вторник", "3": "Среда", "4": "Четверг", "5": "Пятница", "6": "Суббота", } MONTH_NAMES = { "01": "Январ...
Python
1
class Segment(Element,IDisposable): """ This element represents a segment of an MEP curve object. """ def AddSize(self,size): """ AddSize(self: Segment,size: MEPSize) Adds a new MEPSize to the segment. size: The new MEPSize to be added. """ pass def Dispose(self): """ Dispose(self: Element,A_0:...
Python
1
objective: best_objective = insert_objective best_solution = insert_solution best_request_blank = insert_request_blank # 模拟退火接受准则更新当前解 if insert_objective <= current_objective: current_solution = {id: insert_solution[id].truck_copy() for id in insert_solut...
Python
1
ese functions are only used if the API uses base64-encoded properties, so allow them to be // dead code. #[allow(dead_code)] pub fn serialize_with<S>(obj: &Vec<u8>, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer { serializer.serialize_str(&encode(obj)) } #[allow(dead_code)] pub fn deserialize_w...
Rust
0
import carla import numpy as np class WaypointSearch: def __init__(self): pass def get_lane_center(self, waypoint, distance=15): left_lane_waypoint = waypoint.get_left_lane() if waypoint.lane_change & carla.LaneChange.Left else None right_lane_waypoint = waypoint.get_r...
Python
1
) def simulate(self, node): current_state = node.state.copy() current_player = self.player_number while True: valid_moves = self.get_valid_moves(current_state) if not valid_moves: return 0 # Draw move = random.choice(valid_moves) ...
Python
1
/// something usable by wlroots pub trait ToMS { fn to_ms(self) -> u32; } impl ToMS for Duration { fn to_ms(self) -> u32 { let seconds_delta = self.as_secs() as u32; let nano_delta = self.subsec_nanos(); (seconds_delta * 1000) + nano_delta / 1000000 } } /// Converts a Rust string ...
Rust
0
Only Regs that actually appear in the Block (or are // live-in to it) are mapped. This has the advantage of economy, since // most Regs will not appear in (or be live-in to) most Blocks. // struct ProtoRangeFrag { // The InstPoint in this Block at which the associated Reg most // recen...
Rust
0
= ELAD.socketDict[self.getNid()] except: print("Cannot retrieve socket") raise MDSplus.mdsExceptions.TclFAILED_ESSENTIAL try: sock.send(b'TRS') print(sock.recv(2)) except: print("Socket communication failed") raise MDSplus...
Python
1
= r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "GPIO Group 0 interrupt.\n\nValue on reset: 1"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ...
Rust
0
in 0..3 { for k in 0..3 { let x = i as f64 * bbox.maximum.x + (1.0 - i as f64) * bbox.minimum.x; let y = j as f64 * bbox.maximum.y + (1.0 - j as f64) * bbox.minimum.y; let z = k as f64 * bbox.maximum.z + (1.0 - k as f64) * bbox...
Rust
0
println!("> {}", i); } // `skip(n)`メソッドは`Iterator`のはじめから`n`番目までの要素をとばす。 println!("The next four terms of the Fibonacci sequence are: "); for i in fibonacci().skip(4).take(4) { println!("> {}", i); } let array = [1u32, 3, 3, 7]; // `iter`メソッドは配列やスライスからイテレータを作成する。 println!("Iter...
Rust
0
s::new(vec![(STAGING_TELEMETRY_URL.to_string(), 0)]) .expect("Staging telemetry url is valid; qed"), ), Some(DEFAULT_PROTOCOL_ID), get_properties(), Default::default(), )) } #[cfg(feature = "contextfree")] pub fn contextfree_testnet_config() -> Result<ContextFreeChai...
Rust
0
LayerChallenges, PrivateInputs, PublicInputs, SetupParams, StackedCompound, StackedDrg, TemporaryAux, TemporaryAuxCache, BINARY_ARITY, EXP_DEGREE, }, PoRep, }; #[test] fn test_stacked_porep_circuit_poseidon_base_2() { test_stacked_porep_circuit::<DiskTree<PoseidonHasher, U2, U0, U0>>(22, 1_20...
Rust
0
1 c1.04,0,2.08-0.35,3-1c1.83,1.3,4.17,1.3,6,0c1.83,1.3,4.17,1.3,6,0c0.91,0.65,1.96,1,3,1h1v2H21z M17,1.5c-1.1,0-2,0.9-2,2 s0.9,2,2,2s2-0.9,2-2S18.1,1.5,17,1.5z M14.43,8.48L12.18,10L16,13v3.84c0.53,0.38,1.03,0.78,1.49,1.17C16.81,18.59,15.94,19,15,19 c-1.2,0-2.27-0.66-3-1.5c-0.73,0.84-1.8,1.5-3,1.5c-0.33,0-0.65-0.05-0.96...
Rust
0
{DbPool, jwt}; use crate::errors::ApiError; use crate::jwt::Claims; #[get("/ping")] pub async fn ping( config: web::Data<Config>, db_pool: web::Data<DbPool> ) -> Result<HttpResponse, ApiError> { Ok(HttpResponse::Ok().body("Pong!")) } #[get("/secure-ping")] pub async fn secure_ping( config: web::Data<C...
Rust
0
""" CommandLine: pytest tests/test_corner_pool.py """ import pytest import torch from mmdet.ops import CornerPool def test_corner_pool_device_and_dtypes_cpu(): """ CommandLine: xdoctest -m tests/test_corner_pool.py \ test_corner_pool_device_and_dtypes_cpu """ with pytest.raise...
Python
1
st = [] logging_list=[] t = 0 # initialize meta: beta = np.zeros(wb.size+1) beta[-1] = np.log(wb.size) alpha = softmax(beta) alpha[-1] = 0 h = 0.0 clip0 = lambda x: np.clip(x, a_min=0.0, a_max=None) clip_eps = lambda x: np.clip(x, a_min=1e-8, a_max=None) N=0.0 meta_et...
Python
1
import json contents = [ "1. 一辆汽车制动时,在 $2s$ 内速度由 $12m/s$ 减至 $0$,则该汽车加速度大小为\n A. $1m/s^2$ \\quad B. $0m/s^2$ \\quad C. $6m/s^2$ \\quad D. $8m/s^2$", "2. 可拆式变压器原线圈两端电压为 $4V$,副线圈接在0和4之间,输出电压为 $2V$,则原线圈接于\n A. 0和2之间 \\quad B. 2和8之间 \\quad C. 4和8之间 \\quad D. 8和14之间", "3. 下图为某冰箱贴磁感线分布,则\n A. b处磁感应强度大于a处 \\quad B...
Python
1
2, 24), ] def __new__(cls, *args, **kwargs): if args: return cls.from_buffer_copy(args[0].to_bytes(4, byteorder=sys.byteorder)) return super().__new__() def __str__(self): elements = [] if self.SIZE == 0: elements...
Python
1
#!/usr/bin/env python import array import vtkmodules.vtkCommonCore from vtkmodules.vtkCommonCore import vtkSOADataArrayTemplate # types can be specified either with one of the strings listed below, # or with a numpy dtype. You can get a list of types by calling the # method vtkSOADataArrayTemplate.keys(). types = ['...
Python
1
# Natural Language Toolkit: Chatbots # # Copyright (C) 2001-2024 NLTK Project # Authors: Steven Bird <stevenbird1@gmail.com> # URL: <https://www.nltk.org/> # For license information, see LICENSE.TXT # Based on an Eliza implementation by Joe Strout <joe@strout.net>, # Jeff Epler <jepler@inetnebr.com> and Jez Higgins <j...
Python
1
from sys import setrecursionlimit setrecursionlimit(4000) def f(n): if n == 1: return 1 elif n > 1: return n**3 + f(n - 1) print(f(2025) - f(2022))
Python
1
&Symbol, quantity: Decimal) -> Decimal { trace!("adj_quantity_verify_lot_size"); match symbol.get_lot_size() { Some(mls) => { trace!("mls: {:?}", mls); let mut adj_qty = if mls.step_size > dec!(0) { // We are NOT rounding: // (quantity + (mls.s...
Rust
0
ether the __str__ method works correctly.""" l_str = "Line((10.1, 10.2), (4.3, 56.4))" line = Line(10.1, 10.2, 4.3, 56.4) self.assertEqual(str(line), l_str) self.assertEqual(line.__str__(), l_str) def test__repr__(self): """Checks whether the __repr__ method works correctly....
Python
1
def solution(num1, num2): return divmod(num1, num2)[0] # 다른사람 풀이 solution = int.__floordiv__ # operator.__ifloordiv__(a, b) # a = ifloordiv(a, b)는 a //= b와 동등합니다. def solution(num1, num2): answer = num1 / num2 return int(answer) def solution(num1, num2): return num1 // num2 def solution(x, y):...
Python
1