text
string
label_name
string
labels
int64
OS bits into a usable VCoreRange pub trait Vos: private::Sealed { /// Get the range based on the type fn range() -> VCoreRange; } #[doc(hidden)] /// Helper trait to correlate vcore ranges with maximum frequencies pub trait FreqLimit: private::Sealed { fn max_freq() -> Hertz; } /// Range 1 is the "high per...
Rust
0
or polled"] #[derive(Debug)] pub struct SyncBlockingPermitFuture<'a> { futr: Mutex<BlockingPermitFuture<'a>> } impl<'a> SyncBlockingPermitFuture<'a> { /// Construct given `Semaphore` reference. pub fn new(semaphore: &'a Semaphore) -> SyncBlockingPermitFuture<'a> { SyncBlockingPermitFuture { ...
Rust
0
eption as ex: public.print_log("error info: {}".format(ex)) return public.return_message(-1, 0, str(ex)) if not hasattr(get, 'product_id'): return public.return_message(-1, 0, public.lang("product_id Parameter ERROR!")) product_id = get.product_id # ikey = ...
Python
1
_v = arg.pop("ticksuffix", None) _v = ticksuffix if ticksuffix is not None else _v if _v is not None: self["ticksuffix"] = _v _v = arg.pop("ticktext", None) _v = ticktext if ticktext is not None else _v if _v is not None: self["ticktext"] = _v ...
Python
1
#[doc(no_inline)] pub use core::prelude; #[doc(no_inline)] pub use core::{Result, Error, ErrorKind}; #[doc(no_inline)] pub use core::{PortSettings, BaudRate, CharSize, Parity, StopBits, FlowControl}; #[doc(no_inline)] pub use core::{SerialPort, SerialPortSettings}; pub use core::BaudRate::*; pub use core::CharSize::*...
Rust
0
onal[List[int]] = None ) -> List[int]: """ Create a mask from the two sequences passed to be used in a sequence-pair classification task. An XLM sequence pair mask has the following format: ``` 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 | first sequence | second sequ...
Python
1
import numpy as np from HE import histogram_equalization def adaptive_histogram_equalization(img_arr, level=256, window_size=32, affect_size=16): arr = img_arr.copy() m, n = img_arr.shape # Caculate the number of rows and columns rows = (m - window_size) // affect_size + 1 cols = (n - window_size) ...
Python
1
amPConf, ) cs.store( group="optimizer", name="aggmo", node=AggMoConf, ) cs.store( group="optimizer", name="apollo", node=ApolloConf, ) cs.store( group="optimizer", name="diffgrad", node=DiffGradConf, ) cs.store( ...
Python
1
); (*log).file = bindings::ngx_conf_open_file((*cf).cycle, &mut ngx_http_access_log); if (*log).file.is_null() { return NGX_CONF_ERROR!(); } lmcf = *ngx_http_conf_get_module_main_conf!(cf, ngx_http_log_module) as *mut ngx_http_log_main_conf_t; fmt = (*lmcf).formats.elts as *mut ngx...
Rust
0
nput)); Ok(()) } fn part2(input: &[(usize, usize, char, String)]) -> usize { input .iter() .filter(|e| { let pos1 = e.0; let pos2 = e.1; let mut count = 0; e.3.chars().enumerate().for_each(|(idx, ch)| { if (pos1 == idx || pos2 == ...
Rust
0
pper case for c in buf[0..count].iter_mut() { if 0x61 <= *c && *c <= 0x7a { *c &= !0x20; } } let mut write_offset = 0; while write_offset < count { match serial.write(&buf[...
Rust
0
await data_pipeline.fetch_asset_universe(symbol_list, start_date, end_date) features_data = await data_pipeline.create_features_dataset(symbol_list, start_date, end_date) # Train HMM click.echo(f"🔍 Training HMM with {regimes} regimes...") hmm_model = AdvancedBaumWelchHMM(n_components=regimes, ran...
Python
1
eaves = 32; let setup_params = compound_proof::SetupParams { vanilla_params: &porc::SetupParams { leaves, sectors_count: 2, challenges_count: 2, }, engine_params: params, partitions: None, }; let pu...
Rust
0
nv3x3 if depthwise else conv3x3 stem = conv3x3(input_ch, stem_ch[0], "stem", "1", 2) stem += conv_type(stem_ch[0], stem_ch[1], "stem", "2", 1) stem += conv_type(stem_ch[1], stem_ch[2], "stem", "3", 2) self.add_module("stem", nn.Sequential((OrderedDict(stem)))) current_stirde = 4 ...
Python
1
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # -------------------------------------------------------- # References: # DeiT: https://github.com/facebookresearch/deit #...
Python
1
# External imports import segmentation_models_pytorch as smp def Unet(cfg, input_size, num_classes): return smp.Unet( encoder_name=cfg["encoder"]["model_name"], encoder_weights="imagenet", in_channels=input_size[0], classes=num_classes, decoder_attention_type="scse", ) ...
Python
1
rt), '--model', args.model, '--output_type', args.output_type, '--max_new_tokens', str(args.max_new_tokens), '--temperature', str(args.temperature), '--presence_penalty', str(args.presence_penalty), ] if len(device) < len(gpus): cmd...
Python
1
new_post_in_user(user_id: Path<Id>) -> impl Responder { format!("POST /post/user/{}", user_id.into_inner()) } pub async fn get_all_posts_in_topic(db: Data<Db>, topic_id: Path<Id>) -> impl Responder { match Post::get_in_topic(&db.pool, topic_id.into_inner()).await { Ok(p) => respond::ok(p), Err(...
Rust
0
V_A_H(images_path=val_images_path, audio_path=val_audio_path, haptic_path=val_tactile_path, images_class=val_images_label, transform=None) #print(train_data_set) tra...
Python
1
new(tx).to_row()); rows.push(TxConfRow::new(tx, blockhash).to_row()); let txid = full_hash(&tx.txid()[..]); for (txo_index, txo) in tx.output.iter().enumerate() { if !txo.script_pubkey.is_provably_unspendable() { rows.push(TxOutRow::new(&txid, txo_index, txo).to_row()); } } ...
Rust
0
u32) & 0x01) << 11); self.w } } impl R { #[doc = "Bit 0 - PIOn_0."] #[inline(always)] pub fn isense0(&self) -> ISENSE0_R { ISENSE0_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - PIOn_1."] #[inline(always)] pub fn isense1(&self) -> ISENSE1_R { ISENSE1_R::new((...
Rust
0
arsed, &new, rcx) } fn recover_node_and_children(reparsed: &Self, new: &Self, rcx: RewriteCtxtRef) { <[T] as RecoverChildren>::recover_node_and_children(&reparsed, &new, rcx) } fn recover_node_restricted(old_span: Span, reparsed: &Self, new: &Self, rcx: RewriteCtxtRef) { <[T] as Recove...
Rust
0
""" ================================================= Copyright (C) 2018 Vikash Kumar Author :: Vikash Kumar (vikashplus@gmail.com) Source :: https://github.com/vikashplus/robohive License :: Under Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may ob...
Python
1
yew::html! { <li class="page-item disabled"> <a class="page-link" href="#">{ "»" }</a> </li> } } } </ul> } } fn changed(&mut self, ctx: &yew::Context<Self>...
Rust
0
system_tests() { // Get all files in the tests/source directory. let files = fs::read_dir("tests/source").expect("Couldn't read source dir"); // Turn a DirEntry into a String that represents the relative path to the // file. let files = files.map(get_path_string); let (_reports, count, fails) =...
Rust
0
MIPS_ARCH_32R2: u32 = 0x7000_0000; /// MIPS64r2 code. pub const EF_MIPS_ARCH_64R2: u32 = 0x8000_0000; // MIPS values for `Sym32::st_shndx`. /// Allocated common symbols. pub const SHN_MIPS_ACOMMON: u16 = 0xff00; /// Allocated test symbols. pub const SHN_MIPS_TEXT: u16 = 0xff01; /// Allocated data symbols. pub const S...
Rust
0
, 2, yeelight::CfAction::Recover) } fn police(brightness: i8) -> PresetValue { let duration = 300; let (red, blue) = (0xFF_00_00, 0x00_00_FF); let expr = FlowExpresion(vec![ FlowTuple::rgb(duration, red, brightness), FlowTuple::rgb(duration, blue, brightness), ]); PresetValue::Flow(...
Rust
0
func.collide(curr_bot.as_mut(), that_bot.as_mut()); } } active.push(curr_bot); } } fn find_bijective_parallel<A: Axis, F: ColMulti<T = I>>( &mut self, axis: A, cols: (PMut<[I]>, PMut<[I]>), func: &mut F, ) { ...
Rust
0
util::error::*, util::pdv_utilities::*, validator::pdv_trust_anchor::PDVTrustAnchorChoice, validator::policy_utilities::*, CertificationPath, NameConstraintsSet, }; use const_oid::db::rfc5280::ANY_POLICY; use const_oid::db::rfc5912::*; use der::{asn1::ObjectIdentifier, Decode, Encode}; use x509_cert::ext::pkix:...
Rust
0
shape.is_fully_defined(): initializer = init_ops.zeros_initializer() return create_slot_with_initializer( primary, initializer, slot_shape, dtype, name, colocate_with_primary=colocate_with_primary, copy_xla_sharding=copy_xla_sharding) else: if isinstance(primary, variables.Variable...
Python
1
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import odoo.addons.web.tests.test_js import odoo.tests @odoo.tests.tagged("post_install", "-at_install") class WebSuite(odoo.tests.HttpCase): def setUp(self): super().setUp() env = self.env(user=sel...
Python
1
import math import vsketch class LissajousSketch(vsketch.SketchClass): n_points = vsketch.Param(100) radius = vsketch.Param(264.0) # ~ WIDTH/4 at 96 DPI freq_x = vsketch.Param(2.0) freq_y = vsketch.Param(3.0) def draw(self, vsk: vsketch.Vsketch) -> None: # Letter size in landscape, measur...
Python
1
ole_id: web::Path<i64>, auth: AuthToken, ) -> Result<HttpResponse> { auth.require_permission(Permission::role__delete)?; role_service::role_delete(&pool, role_id.into_inner()).await?; Ok(HttpResponse::NoContent().finish()) } #[api_v2_operation(summary = "Assign a specific role to an user", tags(Roles))...
Rust
0
s None: abort(400, 'Invalid game_id') if user.expires_at < time(): user = refresh_access_token(user) channel_id = game.channel_id if channel_id is None: create_match_data = { 'access_tokens': [user.access_token], 'nicks': {user.discord_id: user.id} ...
Python
1
import io from avro.io import DatumReader, BinaryDecoder import json import logging class AvroDeserializer(): """ Decodes the given schema for the user and returns the decoded data. Wrapper for the AvroDeserializer. Attributes: schema (Schema): the schema loaded from a schema file """ ...
Python
1
::rb_cTime); define_class!(TrueClass => ffi::rb_cTrueClass); define_class!(UnboundMethod => ffi::rb_cUnboundMethod); define_class!(ArgError => ffi::rb_eArgError); define_class!(EOFError => ffi::rb_eEOFError); define_class!(EncCompatError => ffi::rb_eEncCompatError); define_class!(EncodingError => ffi::rb_eEncodingError...
Rust
0
// The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR P...
Rust
0
ProviderKey], kid: &str) -> Result<SupportedPublicKey, ()> { let matching: Vec<&ProviderKey> = key_set .iter() .filter(|key| key.use_ == "sig" && key.kid == kid) .collect(); // Verify that we found exactly one key matching the key ID. if matching.len() != 1 { return Err(());...
Rust
0
pub mod parse; pub fn parse(buf: &[u8]) -> parse::Lines<'_> { parse::Lines::new(buf) } use crate::access_control; use serum_common::pack::Pack; use serum_lockup::accounts::Safe; use serum_lockup::error::LockupError; use solana_sdk::account_info::{next_account_info, AccountInfo}; use solana_sdk::info; use solana_...
Rust
0
_bool().unwrap(); assert_eq!(verify_ok, false); // Recoverable signature let output = setup.cli(&format!( "util sign-data --binary-hex 0xdeadbeef --privkey-path {} --recoverable", account_privkey )); let value: serde_yaml::Value = serde_yaml::from_str(&ou...
Rust
0
# Copyright 2022 Webull # # 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software...
Python
1
d { self.kind } pub fn to_code(&self) -> &'static str { self.kind.to_code() } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum PunctuationKind { Backslash, BraceLeft, BraceRight, BracketLeft, BracketRight, ChannelSetLeft, ChannelSetRight, Comma, Equal, LeftArrow, Ampersand, ParenLeft, P...
Rust
0
r mkv files in subdirectories as well") args = vars(parser.parse_args()) set_ref_file_vars(args["reference_file"], args["chapter_reference_file"] ) if args["directory"] is None: args["directory"] = getcwd() set_mapping(load_json_file(episodes_ref_file), load_json_file(chapters_ref_file)) ...
Python
1
s_with("missing field")) } _ => panic!("Expecting error to be InvalidConfigFile."), }; Ok(()) } #[test] fn test_parse_config_file_no_server_port() -> Result<()> { let config_file = Tempfile::create( r#" { "server": "127.0.0.1",...
Rust
0
import py from unityparser.utils import UnityDocument class TestSmartScalarValueTypes: def test_types(self, fixtures): base_file_path = py.path.local(fixtures['MultipleTypesDoc.asset']) doc = UnityDocument.load_yaml(str(base_file_path), try_preserve_types=True) multi_types = doc.entry ...
Python
1
nodes: vec![0; num_nodes], visited_flag: 1, } } pub fn is_visited(&self, node: NodeId) -> bool { self.nodes[node] == self.visited_flag } pub fn set_visited(&mut self, node: NodeId) { self.nodes[node] = self.visited_flag; } pub fn unvisit_all(&mut se...
Rust
0
amazing title"); assert_eq!( true, adr_sut .content .contains("== This is a new completly amazing title") ); } #[test] fn test_split_path() { let base_path = Path::new("/tmp/adr-samples/src"); let file_path = Path::new...
Rust
0
jd}tjj|} tjj|d} tjj| dttjj!| dtj"...
Python
1
ame: &str, namespace: &str, body: &crate::api::core::v1::Pod, optional: crate::ReplaceOptional<'_>, ) -> Result<(crate::http::Request<Vec<u8>>, fn(crate::http::StatusCode) -> crate::ResponseBody<crate::ReplaceResponse<Self>>), crate::RequestError> { let __url = format!("/api/v1/names...
Rust
0
path.leading_colon = Some(Token![::](Span::call_site())); } } } fn expand_trait_object( trait_object: &mut TypeTraitObject, mod_path: &Path, params: &[&GenericParam], ) { trait_object.bounds.iter_mut().for_each(|bound| { if let TypeParamBound::Trait(bound) = bound { ...
Rust
0
nan_labs = np.isnan(labels) keep = ~np.isin(group_inds, np.where(nan_labs)[0]) group_inds = group_inds[keep] order = order[keep] labels = labels[~np.isnan(labels)] except TypeError: # if labels are strings pass if labels is not None: # remove gr...
Python
1
} })); } }); let server_listening_address = SocketAddr::from(([0, 0, 0, 0], waf_settings.port)); let server = Server::bind(&server_listening_address) .serve(service); server.await?; return Ok(()); } fn l...
Rust
0
None => { // This will only occur if something deleted the repo // right after we checked that it was initialized (unlikely) write!(w, "Could not find devlog file to rollover\n")?; exit(1) } } }) } fn status_cmd<W: Write>(w: &mut W...
Rust
0
S|SdS(NtNFKCu(RRt normalizetjoin(tataltbtchtblR((s stringprep.pyt map_table_b2s ( cCs |dkS(Nu ((R((s stringprep.pyt in_table_c11scCstj...
Python
1
sert_URM_ICM_mapper_consistency(URM_DICT = self.SPLIT_URM_DICT, user_original_ID_to_index=self.SPLIT_GLOBAL_MAPPER_DICT["user_original_ID_to_index"], item_original_ID_to_index=self.SPLIT_GLOBAL_MAPPER_DICT["item_original_ID_to_index"], ...
Python
1
6, 7, 8, // Rates 50, 2, 9, 10, // Extended rates ][..]); } #[test] fn send_disassoc_frame() { let mut fake_device = FakeDevice::new(); let mut fake_scheduler = FakeScheduler::new(); let mut ctx = make_context(fake_device.as_device(), fake_scheduler.as_scheduler...
Rust
0
Exception as e: print("Extracting feature fails because of error : ", e) with open('log.txt', 'a') as file: file.write(f"FILE:{feature_dict['video_path']}\n REASON:{e}\n\n") if __name__ == "__main__": train_test = 'train' dataset =...
Python
1
from dlms_cosem.connection import XDlmsApduFactory from dlms_cosem.protocol.xdlms import DataNotification, GeneralGlobalCipher from dlms_cosem.security import SecurityControlField def test_gen_glo_cipher_load(): dlms_data = b"\xdb\x08/\x19\"\x91\x99\x16A\x03;0\x00\x00\x01\xe5\x02\\\xe9\xd2'\x1f\xd7\x8b\xe8\xc2\x0...
Python
1
rgs.property) kwargs = {} if parsed_args.name: kwargs['display_name'] = parsed_args.name if parsed_args.description: kwargs['display_description'] = parsed_args.description if kwargs: volume_client.volumes.update(volume.id, **kwargs) if not k...
Python
1
.glsl".into(), ShaderKind::Vertex, "main", )?, compiler.compile_and_return_file( "vk_tracer/examples/shaders/model.frag.glsl".into(), ShaderKind::Fragment, "main", )?, ) }; let event_loop...
Rust
0
self.MockLazyResult(self.MockModel(data=mock)) response2 = Response('mock', mock2) self.assertEqual({'data': [{'data': None}]}, response2.as_json()) def test_supports_cookie(self): mock = self.MockLazyResult('hello world') response = Response('mock', mock, cookie='Chocolate Chip') ...
Python
1
d) = __jni_env.require_class_static_method("java/util/GregorianCalendar\0", "from\0", "(Ljava/time/ZonedDateTime;)Ljava/util/GregorianCalendar;\0"); __jni_env.call_static_object_method_a(__jni_class, __jni_method, __jni_args.as_ptr()) } } /// public static final [AD](https:/...
Rust
0
ge(self): # Arrange item = "MESSAGE" # Act: Send 6 items self.throttler.send(item) self.throttler.send(item) self.throttler.send(item) self.throttler.send(item) self.throttler.send(item) self.throttler.send(item) # Act: Trigger refresh to...
Python
1
use std::borrow::ToOwned; pub(crate) use std::collections::BTreeMap; pub(crate) use std::convert::Into; pub(crate) use std::default::Default; #[cfg(test)] pub(crate) use std::env; pub(crate) use std::fmt; pub(crate) use std::fs; pub(crate) use std::io; pub(crate) use std::net::IpAddr...
Rust
0
import cv2 from locate_pixelcolor_zig import find_rgba_colors import numpy as np import cv2 import time picx = r"C:\Users\hansc\Downloads\imgaspng\pexels-alex-andrews-2295744.png" pic = cv2.imread(picx, cv2.IMREAD_UNCHANGED) if not pic.flags["C_CONTIGUOUS"]: pic = np.ascontiguousarray(pic) colors0 = np.array( ...
Python
1
#[inline] fn bitor(self, other: Self) -> Self { net_device_flags(self.0 | other.0) } } impl ::std::ops::BitOrAssign for net_device_flags { #[inline] fn bitor_assign(&mut self, rhs: net_device_flags) { self.0 |= rhs.0; } } impl ::std::ops::BitAnd<net_device_flags> for net_device_flags...
Rust
0
let mut contents = String::new(); f.read_to_string(&mut contents) .expect("something went wrong reading the file"); let mut inp: InputData = serde_json::from_str(&contents).unwrap(); let res = multiply(inp.a.as_mut_slice(), inp.b.as_mut_slice()); println!("res: {:?}", res); } <reponame>hellow554/...
Rust
0
from prisma.models import User def get_buttons(user: User, current: str = "dashboard"): buttons = [] buttons.append( { "type": "button", "text": {"type": "plain_text", "text": "Dashboard", "emoji": True}, "action_id": "dashboard", **({"style": "primary"...
Python
1
tId.setter def RequestId(self, RequestId): self._RequestId = RequestId def _deserialize(self, params): self._ErrCode = params.get("ErrCode") self._ErrMessage = params.get("ErrMessage") if params.get("Result") is not None: self._Result = PayeeFundingAccountResult() ...
Python
1
__title__ = 'starbase.client.transport.status_codes' __author__ = 'Artur Barseghyan' __copyright__ = 'Copyright (c) 2013-2014 Artur Barseghyan' __license__ = 'GPL 2.0/LGPL 2.1' # See the full list (http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html). STATUS_CODE_OK = 200 STATUS_CODE_CREATED = 201 STATUS_CODE_ACCEP...
Python
1
let refresh = {*(args.offset(3) as *const i32)}; (implementation.mode)(evq, idata, self, flags, width, height, refresh); }, 2 => { (implementation.done)(evq, idata, self); }, 3 => { let fact...
Rust
0
def calculate_price( num_people: int, agreement: bool = False, long_distance: bool = False, elderly_ratio: float = 0.0, student_ratio: float = 0.0, partner_hotel: bool = False, employee: bool = False, ) -> float: if num_people <= 0: return 0.0 # 各类价格(单位:元/人),默认为 0,可根据实际情况调整 ...
Python
1
import time num_tests = 100000000 x = 7 str_val = "seven" result = 0 # Measure time for if-else with int start = time.time() for _ in range(num_tests): if x == 1: result = 1 elif x == 2: result = 2 elif x == 3: result = 3 elif x == 4: result = 4 elif x == 5: ...
Python
1
Vector3::unit_y(), d_pos), // Rotate with arrow keys VirtualKeyCode::Up => self.rotate_x(angle), VirtualKeyCode::Down => self.rotate_x(-angle), VirtualKeyCode::Left => self.rotate_y(angle), VirtualKeyCode::Right => self.rotate_y(-angle), ...
Rust
0
roid.com/reference/android/app/admin/SecurityLog.html#TAG_REMOTE_LOCK) pub const TAG_REMOTE_LOCK : i32 = 210022; /// public static final [TAG_SYNC_RECV_FILE](https://developer.android.com/reference/android/app/admin/SecurityLog.html#TAG_SYNC_RECV_FILE) pub const TAG_SYNC_RECV_FILE : i32 = 21000...
Rust
0
ssert_eq!( parsed, value, "Parsed value does not match for {}", test_name ); } #[test] fn g2_serde_should_match_identity_test_vector() { g2_serde_should_be_correct( test_vectors::g2::INFINITY, G2Projective::identity(), "Number 0 (infinity)", ); } #[test] fn ...
Rust
0
main/diffusers_xl_canny_mid.safetensors"} ], "18. Diffusers XL Depth Mid": [ {'url': "https://huggingface.co/lllyasviel/sd_control_collection/resolve/main/diffusers_xl_depth_mid.safetensors"} ], "19. Controlnet Union SDXL 1.0": [ {'url': "https://huggingface.co/xinsir/controlnet-union-sd...
Python
1
-> Recorded transaction: {event['transaction']} ({event['duration']:.2f}ms)") except Exception as e: print(f"Worker {worker_id} processing error: {e}") except KeyboardInterrupt: pass finally: consumer.close() print(f...
Python
1
""" Character models """ import random from django.db import models from django.urls import reverse_lazy from .constants import CHARACTER_TYPES, EXTRA class Character(models.Model): name = models.CharField(max_length=100) description = models.TextField() profession = models.CharField(max_length=50) # ...
Python
1
# (C) Copyright SaashaJoshi 2024. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must ret...
Python
1
""" Write a function to get the sum of the digits of a non-negative integer. assert sum_digits(345)==12 """ def sum_digits(n): """ :param n: a non-negative integer :return: the sum of the digits of n """ if n < 10: return n else: return n % 10 + sum_digits(n // 10) if __name_...
Python
1
efault(); let steps_size_props = Props::new(ContentBoxItemLayout { anchors: Rect { left: 0.0, right: 0.0, top: 0.0, bottom: 0.0, }, align: Vec2 { x: 0.0, y: 0.0 }, offset: Vec2 { x: 0.0, y: 40.0 }, ..Default::default() }) ...
Rust
0
import os import re from datetime import datetime, timedelta import pandas as pd import matplotlib.pyplot as plt fomc_release_dates = sorted([re.search(r'monetary(.*)a.htm', x).group(1) for x in os.listdir('data/fomc_statements')]) fomc_release_dates = [datetime(year=int(date[0:4]), month=int(date[4:6]), day=int(date[...
Python
1
oding() { // Empty encoding let accept_encoding = HeaderValue::from_static(""); let encoding = get_prior_encoding(&accept_encoding); assert_eq!(encoding, IDENTITY); // Deprecated encoding. let accept_encoding = HeaderValue::from_static("compress"); let encoding =...
Rust
0
ub for {Rgb<T>, T} where Output = Rgb<T> { #[doc = "Piecewise subtraction of each component. Each channel of the result is clamped between zero and one."] #[inline] fn sub(self, other) { Rgb::with_components( self.r - other, self.g - o...
Rust
0
e_time / 2 - self.depot_end / 3) * torch.rand(batch_size, problem_size) + self.depot_end / 3 tw_start = torch.clamp(time_centers - time_half_width, min=self.depot_start, max=self.depot_end) tw_end = torch.clamp(time_centers + time_half_width, min=self.depot_start, max=self.depot_end) # shape: (b...
Python
1
# cook your dish here x = int(input()) print(x//6)
Python
1
from io import StringIO import xml.dom.minidom import xml.dom.pulldom import xml.sax x = "some xml" # minidom xml.dom.minidom.parse(StringIO(x)) # $ decodeFormat=XML decodeInput=StringIO(..) xmlVuln='XML bomb' decodeOutput=xml.dom.minidom.parse(..) getAPathArgument=StringIO(..) xml.dom.minidom.parse(file=StringIO(x))...
Python
1
ShuntingYard::new(); assert_eq!(7f64, yard.calculate("2 + 20 / 4").unwrap()); assert_eq!("2 + 20 / 4 ", yard.to_string_ast()); assert_eq!("2 20 4 / + ", yard.to_string()); } #[test] fn parenthesis_overrides_divide_before_add() { let mut yard = s_y::ShuntingYard::new(); assert_eq!(6f64, yard.calcula...
Rust
0
https://github.com/pandas-dev/pandas/issues/10673 ser = Series(list("aabbcde"), dtype=any_string_dtype) with pytest.raises(AttributeError, match="You cannot add any new attribute"): ser.str.xlabel = "a" def test_cat_on_bytes_raises(): lhs = Series(np.array(list("abc"), "S1").astype(object)) rh...
Python
1
#!/usr/bin/env python3 # -*-coding:utf8-*- # 注意demo无法直接运行,需要pip安装sdk后才能运行 # 使能机械臂 from typing import ( Optional, ) import time from piper_sdk import * def enable_fun(piper:C_PiperInterface_V2, enable:bool): ''' 使能机械臂并检测使能状态,尝试5s,如果使能超时则退出程序 ''' enable_flag = False loop_flag = False # 设置超时时间...
Python
1
from typing import TypedDict, Annotated from langchain_core.messages import MessageLikeRepresentation from pydantic import BaseModel, Field from deep_research.utils import override_reducer class SupervisorState(TypedDict): """ 主管智能体 上下文 """ # 主管智能体消息列表 supervisor_messages: Annotated[list[MessageLikeRep...
Python
1
descriptor: wallet.descriptor.to_string(), signature: signature.clone(), verified, }; return Ok(result); } } Err(Error::WalletSignatureNotVerified) } fn sign_message_with_key<T: Signing>( secp: &Secp256k1<T>, private_key: ...
Rust
0
.ndarray if isinstance(point_cloud, np.ndarray): points = point_cloud else: # Extract points from the point cloud points = np.asarray(point_cloud.points) if('avg_min_depth' in config): z1 = config['avg_min_depth'] z2 = config['avg_max_depth'] else: z1 = n...
Python
1
</html> """ with open(file=html_path, mode="w") as html_file: html_file.write(f"{pre_html}{mid_html}{post_html}") return html_path @staticmethod def write_trend_html() -> None: return ReportVD._common_html_contents(is_trend=True) @s...
Python
1
ny) -> Any: # Respawn dead players if they're still in the game. if isinstance(msg, bs.PlayerDiedMessage): # Augment standard behavior... super().handlemessage(msg) self.respawn_player(msg.getplayer(Player)) # Respawn dead pucks. elif isinstance(msg,...
Python
1
new_ucmd!() .args(&["-w2", "-b"]) .pipe_in("1234\n") .succeeds() .stdout_is("12\n34\n"); } #[test] fn test_bytewise_should_preserve_final_newline_when_line_equal_to_fold() { new_ucmd!() .args(&["-w2", "-b"]) .pipe_in("1\n") .succeeds() .stdout_is("1\n...
Rust
0
#[derive(Serialize)] pub struct ErrorJson { message: String, } #[derive(Serialize)] pub struct FileResponse { item: File, } #[derive(Serialize)] pub struct FileListResponse { items: Vec<File>, } #[derive(Responder)] pub enum UpdateFileResponse { Created(Created<Json<FileResponse>>), Deleted(Json...
Rust
0
topic 0x00, 0x01, 'p' as u8, // will payload 0x00, 0x06, 'i' as u8, 'a' as u8, 'm' as u8, 'a' as u8, 'z' as u8, 'y' as u8, // username 0x00, 0x06, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, ]; match parse(vec) { Ok(res) => { println!("{:?}", res)...
Rust
0
,30).until( EC.presence_of_all_elements_located((By.XPATH, "//mat-cell[contains(@class, 'mat-mdc-cell mdc-data-table__cell cdk-cell cdk-column-Power-drawn7223763 mat-column-Power-drawn7223763 ng-star-inserted')]")) ) # Get Time Period Data array_time = WebDriverWait(driver, 30).unti...
Python
1