text
string
label_name
string
labels
int64
"""Tests for EQ3 Max! component.""" from unittest.mock import create_autospec, patch from maxcube.device import MAX_DEVICE_MODE_AUTOMATIC, MAX_DEVICE_MODE_MANUAL from maxcube.room import MaxRoom from maxcube.thermostat import MaxThermostat from maxcube.wallthermostat import MaxWallThermostat from maxcube.windowshutter...
Python
1
from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('', views.index, name='home'), path('game_1/', views.game_1, name='game_1'), path('game_2/', views.game_2, name='game_2'), path('game_3/', views.game_3, name='game_3'), path('static_game/', views...
Python
1
from behave import use_fixture from fixtures import fixture_map import helper import shutil import os import time def before_tag(context, tag): tag_parts = tag.split(".", 2) match tag_parts[0].lower(): case "fixture": if len(tag_parts) > 1: try: use_fix...
Python
1
nedness { Unsigned = 0, Signed = 1, } #[derive(Debug, PartialEq, Hash, Eq, Copy, Clone)] enum LocalType { Scalar { kind: crate::ScalarKind, width: Bytes, }, Vector { size: crate::VectorSize, kind: crate::ScalarKind, width: Bytes, }, Pointer { ...
Rust
0
-> std::fmt::Result { write!( f, "session: {}\nclient: {}", self.session, self.client.as_deref().unwrap_or_default() ) } } impl Context { pub fn new(session: String, client: Option<String>) -> Self { let mut path = std::env::temp_dir(); ...
Rust
0
let config = config.clone(); let pool = pool.clone(); async move { deadmanswitch::run(pool, config).await; } }); } match config.api { true => { if let Err(err) = run_api(pool, config, keys).await { log::error!("{:#}", err); } } false => future::...
Rust
0
from urllib.parse import urlparse def is_basic_valid_url(url): """Check if URL has basic validity (proper scheme and netloc) without domain restrictions.""" parsed = urlparse(url) return parsed.scheme in ('http', 'https') and bool(parsed.netloc) def is_valid_url(url, allowed_prefixes_or_domains): """C...
Python
1
vert the argument of Basic.find() into a callable""" try: query = _sympify(query) except SympifyError: pass if isinstance(query, type): return lambda expr: isinstance(expr, query) elif isinstance(query, Basic): return lambda expr: expr.match(query) is not None return ...
Python
1
from ultralytics import YOLO if __name__ == '__main__': # Load a model model = YOLO("yolov8s.pt") # build from YAML and transfer weights # Train the model results = model.train(data="coco128.yaml", epochs=100, imgsz=2048, batch=8, device='xpu')
Python
1
self, world: &world::World) { let messages = match self.inbox { Some(ref drain) => drain.drain(), None => Vec::new(), }; self.picked.clear(); for message in messages { if let Message::Event(Event::PickMinion(position)) = message { let picked = self.pick(position); if let Some(picked_id) = pick...
Rust
0
GenericErr { msg, .. }) => { assert_eq!(msg, "Deposit amount must be greater than 0 uusd") } _ => panic!("DO NOT ENTER HERE"), } let env = mock_env( "addr0000", &[Coin { denom: "uusd".to_string(), amount: Uint128::from(55_555_555_000_000u128),...
Rust
0
from django.db import models class Scheme(models.Model): schemename = models.CharField(max_length=255) ministry = models.CharField(max_length=255) desc = models.TextField() place = models.CharField(max_length=255) moneygranted = models.DecimalField(max_digits=15, decimal_places=2) moneyspent = ...
Python
1
# test_error_calculation.py import unittest import sys from project_ppchem_tools_kit.error_calculation_interface import calculate_error_propagation class TestErrorCalculation(unittest.TestCase): def test_calculate_error_propagation(self): derivatives = [1.0, 2.0, 3.0] uncertainties = [0.1, 0.2, ...
Python
1
import matplotlib.pyplot as plt from pprint import pprint gpu_nums = [1, 2, 4, 8, 16, 32] latencies = { "2.6B": { 1: [0.145, 0.145, 0.144, 0.145, 0.146, 0.154], 2: [0.187, 0.184, 0.182, 0.185, 0.197, 0.213], 4: [0.368, 0.363, 0.362, 0.373, 0.383, 0.426], 8: [0.736, 0.733, 0.733, 0.7...
Python
1
itable: caps.clone(), permitted: caps.clone(), ambient: caps, }; Ok(Some(capabilities)) } serde_json::Value::Object(o) => { let capabilities = LinuxCapabilities { bounding: cap_from_object::<D>(&o, "bounding")?, ...
Rust
0
} } } eprintln!("{}", unique_beacons.len()); let mut max_distance = 0; for i in 0..offsets.len() { for j in 0..offsets.len() { if i != j { let distance = (offsets[i][0] - offsets[j][0]).abs() + (offsets[i][1] - offsets[j][1])....
Rust
0
new(self.app().as_middleware().call(&mut request)) } /// Create a get request fn get_request(&self, path: &str) -> MockRequest { self.request_builder(Method::GET, path) } /// Issue a GET request fn get<T>(&self, path: &str) -> Response<T> where for<'de> T: serde::Deserializ...
Rust
0
�度器里面还有睡眠任务 // 如果等待时间过长,则下一次时间中断的时候切换地址空间 return TaskResult::NoWakeTask; } // 睡眠状态,将当前任务放到调度队列尾部 let sleep_task = scheduler.next_task().unwrap(); let add_ret = scheduler.add_task(sleep_task); ...
Rust
0
cense, use of this software will be governed // by the Apache License, Version 2.0. use super::InvalidValue; use thiserror::Error; /////////////////////////////////////////////////////////////////////////////// #[repr(u32)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] #[allow(non_camel_case_ty...
Rust
0
eduler Process Died", "Incremental sync scheduler stopped unexpectedly", "Attempting automatic restart") # Wait a bit and restart time.sleep(60) scheduler_process = self.start_continuous_scheduler() ...
Python
1
import struct import pandas as pd def write_string(f, s): if pd.isna(s): f.write(struct.pack("B", 0)) else: encoded = s.encode("utf-8") f.write(struct.pack("B", len(encoded))) f.write(encoded) def write_int(f, value, size=4): f.write(bytes.fromhex(value)) def write_byte(f,...
Python
1
ces in alphabetical order.", "Write a Python program that prints the first 10 Fibonacci numbers.", "Write a program that prints the numbers from 1 to 100. But for multiples of three print 'Fizz' instead of the number and for the multiples of five print 'Buzz'. For numbers which are multiples of both thr...
Python
1
"深": 0x64, "森": 0x65, "水": 0x66, "若": 0x67, "美": 0x68, "探": 0x69, "今": 0x6A, "士": 0x6B, "店": 0x6C, "好": 0x6D, "代": 0x6E, "名": 0x6F, "迷": 0x70, "立": 0x...
Python
1
on a set of boards each consisting of a 5x5 grid of numbers. //! Numbers are chosen at random, and the chosen number is marked on all boards //! on which it appears. (Numbers may not appear on all boards.) If all numbers //! in any row or any column of a board are marked, that board wins. (Diagonals //! don't count.) ...
Rust
0
F: Fn(i32) -> i32, { tokens.consume().ok_or(CONSUME_ERR)?; let register_idx = tokens.expect_register()?; registers[register_idx] = { tokens.consume().ok_or(CONSUME_ERR)?; if let Ok(integer) = tokens.expect_integer() { fun(integer) } else { let float = token...
Rust
0
from tkinter import * from tkinter import messagebox from PIL import Image, ImageTk root = Tk() root.title("Авторизация") w = root.winfo_screenwidth() h = root.winfo_screenheight() w = w // 2 h = h // 2 w = w - 480 h = h - 270 root.geometry(f'500x540+{w}+{h}') root.resizable(width=False, height=False) root.configure...
Python
1
items.len()); let mut spreading = false; for item in items { match item { Calcit::Symbol { sym: s, .. } if &**s == "&" => { spreading = true; } _ => { let v = evaluate_expr(item, scope, file_ns.to_owned(), call_stack)?; if spreading { match v { Ca...
Rust
0
= f"\n{Colors.BOLD}{Colors.MAGENTA}{title}{Colors.END}\n" chart += f"{Colors.YELLOW}{'='*70}{Colors.END}\n" # Posterior statistics if 'posterior_stats' in results: stats = results['posterior_stats'] chart += f"{Colors.CYAN}Posterior Distribution Statistics:{Colo...
Python
1
""" Point Pillar's Scatter. Converts learned features from dense tensor to sparse pseudo image. This replaces SECOND's second.pytorch.voxelnet.SparseMiddleExtractor. :param output_shape: ([int]: 4). Required output shape of features. :param num_input_features: <int>. Number of in...
Python
1
WasmPastaFp(x.0 * y.0) } #[wasm_bindgen] pub fn caml_pasta_fp_div(x: WasmPastaFp, y: WasmPastaFp) -> WasmPastaFp { WasmPastaFp(x.0 / y.0) } #[wasm_bindgen] pub fn caml_pasta_fp_inv(x: WasmPastaFp) -> Option<WasmPastaFp> { x.0.inverse().map(|x| { WasmPastaFp(x) }) } #[wasm_bindgen] pub fn caml_pasta_fp_sq...
Rust
0
AsyncMock() mock_ws_instance.register_callback = MagicMock() mock_ws_instance.websocket = mock_websocket with ( patch( "homeassistant.components.weatherflow_cloud.coordinator.WeatherFlowWebsocketAPI", return_value=mock_ws_instance, ), patch( "hom...
Python
1
r other materials provided # with the distribution. # * Neither the name of Novartis Institutes for BioMedical Research Inc. # nor the names of its contributors may be used to endorse or promote # products derived from this software without specific prior written permission. # # THIS SOFTWARE I...
Python
1
res.par_iter().cloned()) .with_min_len(2) .mapfold_reduce_into( &mut names, |names, (name, score)| { names.push(name); score }, Default::default, |left_names, mut right_names| { left_names.append(...
Rust
0
use crate::{ errors::catch, raw::{cx_ecfp_private_key_t, cx_ecfp_public_key_t}, }; use core::mem::MaybeUninit; use zeroize::{Zeroize, Zeroizing}; pub fn cx_edward_compress_point(curve: Curve, p: &mut [u8]) -> Result<usize, Error> { let curve: u8 = curve.into(); cfg_if...
Rust
0
here::new(Point3::new(0.0, -1000.0, 0.0), 1000.0, Box::new(Lambertian::new(Box::new(checker)))))); for a in -10..10 { for b in -10..10 { let center = Point3::new(a as f32 + 0.9*random_float_from_0_to_1(), 0.2, b as f32 + 0.9*random_float_from_0_to_1()); if (center.to_vec() - vec...
Rust
0
def build_scheduler(cfg, optimizer): name = cfg.SCHEDULER.TYPE if name == '': warnings.warn('No scheduler is built.') return None elif hasattr(torch.optim.lr_scheduler, name): scheduler = getattr(torch.optim.lr_scheduler, name)(optimizer, ** cfg.SCHEDULER.get(name, dict()...
Python
1
import os from celery import Celery, signature os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings") app = Celery("sessiontrackr") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() app.conf.update( task_serializer="json", accept_content=["json"], res...
Python
1
= 0; let mut res = hv_vmx_read_capability(VMXCap::PINBASED, &mut vmx_cap_pinbased); if res != 0 { panic!("vmx read capability res: {}", res); } res = hv_vmx_read_capability(VMXCap::PROCBASED, &mut vmx_cap_procbased); if res != 0 { panic!("vmx read capability res: {}", res); } res = hv_vmx_read_cap...
Rust
0
x = (non_cfg_x, cond_token) x.append(non_cfg_x) if cfg_scale[0] > 1.0: x.append(torch.concat([cond_token, uncond_token])) else: x.append(cond_token) sample_pre = sample_pre[:, cond_len:] sample_post = sample_post[:, cond_len:] sample = (sample_pre...
Python
1
import frappe __version__ = "15.13.1" def refetch_resource(cache_key: str | list, user=None): frappe.publish_realtime( "hrms:refetch_resource", {"cache_key": cache_key}, user=user or frappe.session.user, after_commit=True, )
Python
1
use serde::{Deserialize, Serialize}; use crate::network::internal::NetworkError; use crate::types::dag::Operation; use crate::types::{CudaKernelId, EventId, SyncId, TaskletOutput, WorkerInfo}; #[derive(Debug, Serialize, Deserialize)] pub(crate) enum DriverMsg { Submit(Vec<Operation>), Compile(CudaKernelId, Cu...
Rust
0
[3] ); assert_eq!( LocalToken::decrypt( &test_local_sk, &invalid_local, Some(FOOTER.as_bytes()), None ) .unwrap_err(), Error::TokenValidation ); } #[test] fn err_on_modif...
Rust
0
rkers, plan=plan) def rfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *, plan=None): return rfftn(x, s, axes, norm, overwrite_x, workers, plan=plan) def irfftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *, plan=None): return _execute_nD(...
Python
1
= (500 - COG[1]) * 1.08 # 更新 COG_height 為當前 COG 的 y 值 else: COG_height = COG_last_height ###------右下角高度表示------___________________________________________________________________________________________________________________________________ # 提取 CT 和 COG 的 y 座標 CT_2dy = projected_p...
Python
1
t_params( time_series_df_default_index, dataset_id, id_col_name ): model = forecasting.ARIMAPlus( horizon=100, auto_arima=True, auto_arima_max_order=4, auto_arima_min_order=1, data_frequency="daily", holiday_region="US", clean_spikes_and_dips=False, ...
Python
1
avaliable fields see [scgccan](scgccan) module"] pub type SCGCCAN = crate::Reg<u32, _SCGCCAN>; #[allow(missing_docs)] #[doc(hidden)] pub struct _SCGCCAN; #[doc = "`read()` method returns [scgccan::R](scgccan::R) reader structure"] impl crate::Readable for SCGCCAN {} #[doc = "`write(|w| ..)` method takes [scgccan::W](s...
Rust
0
# -*- coding: utf-8 -*- """ Created on Tue Feb 21 14:50:19 2023 @author: dell """ """ MC simulation """ import scipy.io as scio import numpy as np import matplotlib.pyplot as plt import tensorflow as tf import os os.environ['KMP_DUPLICATE_LIB_OK']='True' ###系统参数 alpha=-0.5 beta=0.1 omega=1.4 D1=0.01 D2=0.01 #噪声...
Python
1
et_as("idVars")?; let value_vars: Vec<String> = params.get_as("valueVars")?; ldf.melt(id_vars, value_vars).try_into_js(&cx) } #[js_function(1)] pub fn tail(cx: CallContext) -> JsResult<JsExternal> { let params = get_params(&cx)?; let ldf = params.get_external::<LazyFrame>(&cx, "_ldf")?.clone(); let...
Rust
0
:*; <gh_stars>100-1000 use specs::prelude::*; use crate::{EquipmentChanged, Item, InBackpack, Equipped, Pools, Attributes, gamelog::GameLog, AttributeBonus, gamesystem::attr_bonus, StatusEffect}; use std::collections::HashMap; pub struct EncumbranceSystem {} impl<'a> System<'a> for EncumbranceSystem { #[allow...
Rust
0
from random import randint, uniform combat_side_cal = (1, 0.4, 0.1) # for melee attack target defend side modifier 0 = Front, 1 = Side, 2 = Rear infinity = float("inf") def cal_charge_hit(self, target, hit_side, hit_angle): """Calculate charge attack hit chance and defence chance, then damage""" attacker_lu...
Python
1
let client = context.data.read().await.get::<ReqwestContainer>().cloned().unwrap(); let search_endpoint = "https://api.themoviedb.org/3/search/tv"; let search_query = ("query", &show.replace(" --cast", "").replace(" -c", "")); let search_response = client.get(search_endpoint).query(&[("api_key", &api_...
Rust
0
tly_chart(price_fig, use_container_width=True) # Display RSI chart st.subheader("Relative Strength Index (RSI)") rsi_fig = create_rsi_chart(hist_data, rsi_window) st.plotly_chart(rsi_fig, use_container_width=True) # Display financial data table s...
Python
1
void main() { gl_Position = vec4(position, 0.0, 1.0); v_tex_coords = tex_coords; v_color = color; v_mode = mode; } "; /// The fragment shader used within the `glium::Program` for OpenGL ES. pub const FRAGMENT_SHADER_300_ES: &'static str = " #version 300 es precision mediu...
Rust
0
>) -> Point { let q = p.right(); if q.x >= mat.width() as isize { point(0, q.y) } else { q } } #[cfg(test)] mod test { use super::*; #[test] fn solution() { let a = solve(&input()); assert_eq!(a, 530); } } extern crate gtk; extern crate gio; extern crate...
Rust
0
JSON blob is emitted to stdout is valid. try: json.loads(stdout) except ValueError as e: raise AssertionError( f"Could not generate CLI skeleton for command: {command_name} " f"{operation_name}\n stdout:\n{stdout}\nstderr:\n{stderr}\n" ) def _run_cmd(cmd, expec...
Python
1
len_site { let aa : char = ( *site )[ i ]; let add : f64 = freq[ &aa ] + ( *weight_list )[ i ]; freq.insert( aa, add ); } //println!( "{:?}", freq ); freq } /////////////////////////////////////////////////////////////////////////////////////////// // SHANNON'S ENTROPY WITH 7 AMINO ACID TYPES ////////////...
Rust
0
from GridWorld import * from library import * import matplotlib.pyplot as plt # Environment goals = [(3,3)] # Task goals env = GridWorld(goals=goals) ### Load WVF WVF = load_WVF("WVF.npy") ### Planning using inferred dynamics fig = plt.figure(1, figsize=(20, 20), dpi=60, facecolor='w', edgecolor='k') params = {'font...
Python
1
Vnew = spsolve( M, V + B ) scale = np.maximum( np.abs( Vnew ), np.ones_like( Vnew ) ) residuals = np.abs( Vnew - Vhat ) / scale if np.all( residuals[:-1] < tol ): V = Vnew break else: Vhat = Vnew ...
Python
1
wd_zmm_k1z_zmm_zmmm512 MemorySize::Unknown,// Punpckldq_mm_mmm32 MemorySize::Unknown,// Punpckldq_xmm_xmmm128 MemorySize::Unknown,// VEX_Vpunpckldq_xmm_xmm_xmmm128 MemorySize::Unknown,// VEX_Vpunpckldq_ymm_ymm_ymmm256 MemorySize::Broadcast128_UInt32,// EVEX_Vpunpckldq_xmm_k1z_xmm_xmmm128b32 MemorySize::Broadcast2...
Rust
0
即 [`crate::MultiPartsV1Uploader`]。 V1, /// 分片上传器 V2 /// /// 即 [`crate::MultiPartsV2Uploader`]。 #[default] V2, } impl AutoUploaderObjectParams { /// 创建自动上传器对象参数构建器 #[inline] pub fn builder() -> AutoUploaderObjectParamsBuilder { Default::default() } /// 获取期望的分片上传调度器...
Rust
0
result["value"] = value # rule_schema["then"] = result # # return rule_schema # # # def build_index_list(cconjs, if_docs): # index_list = [0] # for c in cconjs: # index_list.append(c.i) # index_list.append(len(if_docs)) # return index_list # # # def root_match(nlp, rul...
Python
1
# cook your dish here t=int(input()) for i in range(t): x,y,z=map(int,input().split()) a1=x*y a2=y*z a3=x*z b1=z b2=x b3=y if a1%b1==0 : print(f"{a1} {b1}") elif a2%b2==0: print(f"{a2} {b2}") elif a3%b3==0: print(f"{a3} {b3}") else: print(-1...
Python
1
fn check_pragma_directives(&self, solidity: &mut Vec<&str>, abicoder: &mut Vec<&str>) { let mut op = None; let mut lower: Option<f32> = None; let mut upper: Option<f32> = None; for &literal in solidity.iter() { match literal { "^" | ">" | ">=" | "<=" | "<" ...
Rust
0
/// Writes out a C++ wrapper class for the given type, which contains various utilities to access /// the underlying C-mapped type safely avoiding some common memory management issues by handling /// resource-freeing and prevending accidental raw copies. pub fn write_cpp_wrapper(cpp_header_file: &mut File, ty: &str, h...
Rust
0
", } return make_response(jsonify(response), 400) for key, value in update_fields.items(): setattr(interface_obj, key, value) BaseDao.safe_commit() return jsonify(interface_obj.as_dict()) @interface_bp.route("/<hostname>/<if_name>", methods=["DELETE"]) @check_access(["admin"]) def...
Python
1
tree = let_tree return tree @Walker def fix_columns(tree, stop, elt_aliases, **kw): """if the "columns" name isn't attribute accessed, replace it with the same name witn '_alias' appended.""" if (type(tree) is ast.Attribute and type(tree.value) is ast.Name and any(map(lambda elt: elt.id...
Python
1
matches!( result.body_location, optic_engine::BodyAnalysisLocation::MatchedQueryParameters { .. } ) }); for result in results { let pointers = { let mut set = HashSet::new(); set.insert(interaction_pointer.clone()); set }; learned_shape_dif...
Rust
0
 c@s5ddlTddlZddlZdZdZdZdZdd dYZdd!d YZd d"d YZd d#d YZ dd$dYZ dd%dYZ dd&dYZ dd'dYZ dd(dYZdd)dYZdd*dYZdd+dYZdd,dYZdS(-i(...
Python
1
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the Apache License, Version 2.0 # found in the LICENSE file in the root directory of this source tree. import math import logging import os from omegaconf import OmegaConf import dinov2.distributed as distributed from dinov2....
Python
1
Box<dyn std::error::Error>> { let path = path.as_ref(); let mut file = BufReader::new(File::open(path)?); let mut header = [0; 80]; file.read_exact(&mut header)?; let tri_count = file.read_u32::<LittleEndian>()?; eprintln!("loading stl with {} triangles", tri_count); ...
Rust
0
return _SessionRequestContextManager( session._request( method, url, params=params, data=data, json=json, headers=headers, skip_auto_headers=skip_auto_headers, auth=auth, allow_redirects=allow_redir...
Python
1
from .financial_calculator import FinancialCalculator class MortgageCalculator(FinancialCalculator): """ A class for calculating mortgage-related values. Inherits from FinancialCalculator to utilize financial calculation methods. Attributes ---------- loan_amount : float The total loa...
Python
1
from typing import Tuple import numpy as np # Tile graphics structured type compatible with Console.tiles_rgb. graphic_dt = np.dtype( [ ("ch", np.int32), # Unicode codepoint. ("fg", "3B"), # 3 unsigned bytes, for RGB colors. ("bg", "3B"), ] ) # Tile struct used for statically define...
Python
1
from rest_framework.serializers import ModelSerializer from .models import household from .models import citizen class citizenSerializer(ModelSerializer): class Meta: model = citizen fields = '__all__' class householdSerializer(ModelSerializer): class Meta: model = household f...
Python
1
import re dbg = False term_regex = r'''(?mx) \s*(?: (?P<brackl>\()| (?P<brackr>\))| (?P<num>\-?\d+\.\d+|\-?\d+)| (?P<sq>"[^"]*")| (?P<s>[^(^)\s]+) )''' def parse_sexp(sexp): stack = [] out = [] if dbg: print("%-6s %-14s %-44s %-s" % tuple("term value out...
Python
1
Cell::with_key(b"password")?.token_protect(); /// /// let (encrypted, token) = cell.encrypt_with_context(b"byte string", b"context")?; /// let decrypted = cell.decrypt_with_context(&encrypted, &token, b"context")?; /// assert_eq!(decrypted, b"byte string"); /// # Ok(()) /// # } /// ``` /...
Rust
0
.value_name("PEM|DER|JWK") .help("Type of output file") .required(false) .takes_value(true), ) .arg( Arg::with_name("kid") .long("kid") .value_name("NAME") .help("Key ID for JWT") ...
Rust
0
.clone() } pub fn get_material( &mut self, renderer: &r3::Renderer, mark: Option<DebugMark>, ) -> r3::MaterialHandle { if let Some(mark) = mark { self.get_color_material(renderer, mark.color) } else { self.base_material.clone() ...
Rust
0
var)) } pub fn abs_rc(var: Variable, term: RcTerm) -> RcTerm { Rc::new(Term::Abs(var, term)) } pub fn appl_rc(l: RcTerm, r: RcTerm) -> RcTerm { Rc::new(Term::Appl(l, r)) } pub fn num_lit_rc(val: isize) -> RcTerm { Rc::new(Term::Lit(Literal::Num(val))) } pub fn...
Rust
0
rr.errors.first_mut().unwrap()), NomErr::Failure(err) => map(err.errors.first_mut().unwrap()), NomErr::Incomplete(_) => {} } } result } } */ /// Adds additional error context to any error. /// This does the error prone work for you of stashing /// the inp...
Rust
0
ddress; fn following_address(&self) -> Option<btc::Address>; fn nearest_lect(&self, height: u64) -> Option<AnchoringTx>; } impl AnchoringApi for TestKitApi { fn actual_lect(&self) -> Option<AnchoringInfo> { self.get(ApiKind::Service(ANCHORING_SERVICE_NAME), "/v1/actual_lect/") } fn curre...
Rust
0
= user_info.get('signature') avatar_url = get_array_first(user_info.get('avatar_larger', {}).get('url_list', [])) factor_hot_value = star_json.get('factor_hot_value') hot_value = star_json.get('hot_value') if id: return Star( id=id, nickname=nickname, signatur...
Python
1
$s.regs.$x); return 2; }; } macro_rules! impl_LD_r_n_x { ($s: ident, $x: ident) => { $s.regs.$x = $s.fetch_byte(); return 2; }; } // --- Helper macros --- // TODO: use more methods instead macro_rules! inc_byte { ($s: ident, $b: expr) => {{ let r = $b.wrapping_add(1);...
Rust
0
// // 默认是1,因为总是包含一位(nums[i] 自身)。 // let mut dp = vec![1; nums.len()]; // let mut max_len = 1; // for i in 1..nums.len() { // // 在 i 之前找一个比 nums[i] 小的数,则可以把 num 插入到该数后面。 // for j in 0..i { // if nums[j] < nums[i] { // dp[i] = dp[i...
Rust
0
''' This is my improved code on Lab 1 ''' from Project1_gui import * def main(): window = Tk() window.title('') window.geometry('360x320') window.resizable(False, False) GUI(window) window.mainloop() if __name__ == "__main__": main()
Python
1
12rdyie_1(self) -> &'a mut W { self.variant(ADC12RDYIE_A::ADC12RDYIE_1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { ...
Rust
0
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from api.routers import byProfile, byScenario, postVideo from dotenv import load_dotenv load_dotenv() app = FastAPI() # 허용할 도메인 리스트 origins = [ "http://localhost:8080", "http://43.203.209.38:8080", "http://localhost:3000", ...
Python
1
(&mut store, ())?, (0, 1) ); let f1 = instance.get_func(&mut store, "f1").unwrap(); assert_eq!( f1.typed::<(i32, i32, i32), (f32, f64), _>(&store)? .call(&mut store, (1, 2, 3))?, (2., 3.) ); Ok(()) } #[test] fn trap_doesnt_leak() -> anyhow::Result<()> { #[de...
Rust
0
if !handlers.is_empty() { error!(ctx.get_logger("dispatcher"), "message handler not invoked"; "unhandled" => ?handlers); return Err(modules::core::Error::MessageHandlerNotInvoked); } Ok(()) } fn save_emitted_message_handlers<S: storage::Store>( store: ...
Rust
0
usb_dev.poll(&mut [serial]); let mut buf = [0u8; 64]; if let Ok(count) = serial.read(&mut buf) { for (i, c) in buf.iter().enumerate() { if i > count { break; } match ...
Rust
0
现在的x坐标取反 # print("combinated_trajs3 ",combinated_trajs ) # combinated_trajs = combinated_trajs[..., 4::5, :] b, a, s, _, t, d = combinated_trajs.shape # b:2 a:42 s:42 _:2 t:30 d:2 # # 1. 过滤自车后方车辆(纵向位置判断) # # 自车轨迹y轴(原x轴)始终大于他车时为后方车辆 # 1. 后方车辆判断(所有时间步) # ego_y = combinated_trajs[:, :, :, 0, ...
Python
1
return else: break # dont retry on HTTP errors 4xx, 5xx except Exception as e: logger.error(f"Attempt {attempt + 1}/{RETRY_ATTEMPTS} failed for {url}: {e}") if attempt < RETRY_ATTEMPTS - 1: await asyncio.sleep(RETRY_DE...
Python
1
} } impl From<LiteralToken> for Token { fn from(l: LiteralToken) -> Self { Token::Literal(l) } } impl From<AssignmentToken> for Token { fn from(a: AssignmentToken) -> Self { Token::Assignment(a) } } impl From<ComparisonToken> for Token { fn from(a: ComparisonToken) -> Self { ...
Rust
0
Vec<Bundle>> { let mut bundles = Vec::new(); let package_types = settings.package_types()?; for package_type in &package_types { let bundle_paths = match package_type { #[cfg(target_os = "macos")] PackageType::MacOsBundle => macos::app::bundle_project(&settings)?, #[cfg(target_os = "macos")] PackageTy...
Rust
0
# tools/weekly_report.py import argparse, os, glob, re, pandas as pd, numpy as np, matplotlib.pyplot as plt from datetime import datetime def find_runs(root): paths = sorted(glob.glob(os.path.join(root, "asof_*"))) rows = [] for p in paths: m = re.search(r"asof_(\d{4}-\d{2}-\d{2})", p) if n...
Python
1
) { const SPEED_CELLS_PER_SEC: f64 = 20.0; const RANGE: usize = 6; const COUNT: usize = 32; const STEP: f64 = 2.0 * f64::consts::PI / COUNT as f64; let mut angle = 0.0; for _ in 0..COUNT { let v = Vector2::from_radial(10.0, angle); let velocity = RealtimeVelocity::new(Coord::new(...
Rust
0
doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bo...
Rust
0
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { for idx in 0..buf.len() { buf[idx] = match self.pin.recv() { Ok(v) => v, Err(e) => return Err(std::io::Error::new(ErrorKind::BrokenPipe,e)), } } Ok(buf.len()) } } impl Write...
Rust
0
from random import choice as c list = ['head', 'tail'] print(f"Congrats!!! it is {c(list)}.") print("Nice!!")
Python
1
tialEq, ::prost::Message)] pub struct MsgExec { #[prost(string, tag = "1")] pub grantee: ::prost::alloc::string::String, /// Authorization Msg requests to execute. Each msg must implement Authorization interface /// The x/authz will try to find a grant matching (msg.signers[0], grantee, MsgTypeURL(msg))...
Rust
0