text
string
label_name
string
labels
int64
2 = 1446u32; #[doc = "*Required features: 'Win32_Data_Xml_MsXml'*"] pub const DISPID_SOM_LENGTH: u32 = 1447u32; #[doc = "*Required features: 'Win32_Data_Xml_MsXml'*"] pub const DISPID_SOM_MAXEXCLUSIVE: u32 = 1448u32; #[doc = "*Required features: 'Win32_Data_Xml_MsXml'*"] pub const DISPID_SOM_MAXINCLUSIVE: u32 = 1449u32...
Rust
0
split("_to_") if cfg["TRAIN_TYPE"] == "train": # rename best_models to modelname on disk shutil.move( best_paths[1], os.path.join( "models", cfg["RUN_ID"], f"TRANSLATE_TO_{to_input_key}_VAE.pt" ), ) shutil.move( best_pa...
Python
1
x2e, 0x78, 0x25, 0x3b, 0x17)] interface ISpPhoneticAlphabetConverter(ISpPhoneticAlphabetConverterVtbl): IUnknown(IUnknownVtbl) { fn GetLangId( pLangID: *mut WORD, ) -> HRESULT, fn SetLangId( LangID: WORD, ) -> HRESULT, fn SAPI2UPS( pszSAPIId: *const SPPHONEID, pszUPSI...
Rust
0
# Part (a) Queue = [0] * 100 # Array to hold up to 100 integers HeadPointer = 0 # Points to first element TailPointer = 0 # Points to next free space # Part (b) def Enqueue(value): global Queue, HeadPointer, TailPointer if TailPointer < 100: Queue[TailPointer] = value TailPointer += 1 ...
Python
1
skip_serializing_if = "Option::is_none")] pub tunnel_id: Option<String>, } #[derive(Default, Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "deserialize_structs", derive(Deserialize))] pub struct UntagResourceRequest { /// <p>The resource ARN.</p> #[serde(rename = "resourceArn")] pub resourc...
Rust
0
evals tmp_out_len = ctypes.c_int(0) string_buffers = [ctypes.create_string_buffer(255) for i in range_(self.__num_inner_eval)] ptr_string_buffers = (ctypes.c_char_p * self.__num_inner_eval)(*map(ctypes.addressof, string_buffers)) _safe_call(_LIB.LGBM_Boost...
Python
1
"""Tests to show that the benchmarks we based our speed optimizations on are still valid""" import unittest from functools import partial from timeit import timeit timeit = partial(timeit, number=500000) class TestBenchmarks(unittest.TestCase): def test_lists_vs_dicts(self): """See what's faster at int ke...
Python
1
lost; /// struct sample_id sample_id; /// }; pub const PERF_RECORD_LOST: i32 = 2; /// ```c /// struct { /// struct perf_event_header header; /// /// u32 pid, tid; /// char comm[]; /// struct sample_id sample_id; /// }; /// ``` pub const PERF_RECORD_COMM: i32 = 3; /// struct { /// struct perf_event_h...
Rust
0
from pyspark.sql import SparkSession from pyspark.conf import SparkConf APP_NAME = f"(Spill - AQE - 450m - 0.60) {__file__}" spark_conf = SparkConf().setAppName(APP_NAME)\ .set("spark.executor.memory", "450m")\ .set("spark.memory.fraction", 0.60)\ .set("spark.sql.shuffle.partitions", 1)\ .set("spark.d...
Python
1
class Solution: def trap(self, height: List[int]) -> int: n = len(height) l = [0] * n # l[i] := max(height[0..i]) r = [0] * n # r[i] := max(height[i..n)) for i, h in enumerate(height): l[i] = h if i == 0 else max(h, l[i - 1]) for i, h in reversed(list(enumerate(height))): r[i] = h ...
Python
1
d::cell::RefCell; use std::collections::BTreeMap; use std::fmt::Write; use super::run::RunCtx; use rd_agent_intf::Report; use rd_util::*; mod iolat; mod rstat; pub use iolat::StudyIoLatPcts; pub use rstat::{ResourceStat, ResourceStatStudy, ResourceStatStudyCtx}; pub const DFL_PCTS: &[&'static str] = &[ "00", "0...
Rust
0
"Negative", "easy wildcards": "Wildcards", "easy prompt": "Prompt", "easy promptList": "PromptList", "easy promptLine": "PromptLine", "easy promptConcat": "PromptConcat", "easy promptReplace": "PromptReplace", "easy stylesSelector": "Styles Selector", "easy portraitMaster": "Portrait Ma...
Python
1
target_ecs_instance_type: The target_ecs_instance_type of this UpdateNodeGroupEcsSpecRequest. # noqa: E501 :type: str """ if self._configuration.client_side_validation and target_ecs_instance_type is None: raise ValueError("Invalid value for `target_ecs_instance_type`, must not be ...
Python
1
octest: .. doctest:: >>> adjust_point(0, 0, 0, 10, 5) (0, 5) >>> adjust_point(0, 0, 10, 0, 5) (5, 0) """ sign_x = 1 if x1 > x0 else -1 sign_y = 1 if y1 > y0 else -1 if y0 == y1: return (x1 - dt * sign_x, y0) if (x0 == x1): return (x0, y1 - dt * s...
Python
1
notify::resource", transmute(notify_resource_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _) } } fn connect_property_stock_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe { let f: Box_<Box_<Fn(&Self) + 'static>> = Box_::new(Box_::ne...
Rust
0
re, header, payload, }) } /// Return the payload of the token if the token is valid. If the token is not valid `Ok(None)` /// is returned. An error may occured while deserializing the paylaod if the payload is not /// valid json. /// /// # Example /// ///...
Rust
0
/winmsg/wm-setfont) /// message parameters. /// /// Return type: `()`. pub struct SetFont { pub hfont: HFONT, pub redraw: bool, } impl MsgSend for SetFont { type RetType = (); fn convert_ret(&self, _: isize) -> Self::RetType { () } fn as_generic_wm(&self) -> WndMsg { WndMsg { msg_id: c...
Rust
0
tainer)) ); assert_eq!( ::std::mem::align_of::<_GtkContainer>(), 8usize, concat!("Alignment of ", stringify!(_GtkContainer)) ); assert_eq!( unsafe { &(*(::std::ptr::null::<_GtkContainer>())).widget as *const _ as usize }, 0usize, concat!( "Offset of field: ", stringify!(_GtkC...
Rust
0
`2014-07-08T09:10:11.012Z` //! let dt = Utc.ymd(2014, 7, 8).and_hms_milli(9, 10, 11, 12); //! assert_eq!(dt, Utc.ymd(2014, 7, 8) //! .and_hms_micro(9, 10, 11, 12_000)); //! assert_eq!(dt, Utc.ymd(2014, 7, 8) //! .and_hms_nano(9, 10, 11, 12_000_000)); //! //! // dynamic verification //! assert_eq!(Utc.ymd_opt(2014,...
Rust
0
(); if self.system_resources.slice()[self.free_list_overflow_count].len() < val.mem.len() { core::mem::replace(&mut self.system_resources.slice_mut()[self.free_list_overflow_count], val.mem); return; } ...
Rust
0
//////////////// fn into_slice_range(len: usize, range: impl RangeBounds<usize>) -> Range<usize> { let start = match range.start_bound() { Bound::Included(&start) => start, Bound::Excluded(&start) => start .checked_add(1) .unwrap_or_else(|| slice_start_index_overflow_fail()),...
Rust
0
word(request.session_researcher.username, current_password): messages.warning(request, WRONG_CURRENT_PASSWORD) return redirect('manage_researcher_endpoints.self_manage_credentials_page') success, msg = check_password_requirements(request.session_researcher, new_password) if msg: mes...
Python
1
xtension string") } } pub struct NvShaderSmBuiltinsFn {} unsafe impl Send for NvShaderSmBuiltinsFn {} unsafe impl Sync for NvShaderSmBuiltinsFn {} impl ::std::clone::Clone for NvShaderSmBuiltinsFn { fn clone(&self) -> Self { NvShaderSmBuiltinsFn {} } } impl NvShaderSmBuiltinsFn { pub fn load<F>(...
Rust
0
{ // Denormal let mut fp = float::ExtendedFloat { mant: 1 << 63, exp: f64::DENORMAL_EXPONENT - 15, }; rounding::round_to_float::<f64, _>(&mut fp, rounding::round_nearest_tie_even); assert_eq!(fp.mant, 1 << 48); assert_eq!(fp.exp, f64::DENORMAL_EXPONENT); // Halfway, round-d...
Rust
0
""" Run script for Career Path Generator """ import os from app import app if __name__ == '__main__': # Get port from environment variable or default to 5000 port = int(os.environ.get('PORT', 5000)) # Get debug mode from environment debug_mode = os.environ.get('FLASK_DEBUG', '1') == '1' #...
Python
1
on/trajectory.rs<gh_stars>1-10 /* * Copyright (C) 2022 Open Source Robotics Foundation * * 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....
Rust
0
# 1768. Merge Strings Alternately # You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string. # Return the merged string. # Example 1: # Input: wor...
Python
1
reading out a new key z1013.kbd_matrix_bits = z1013.next_kbd_matrix_bits; } z1013.kbd_column_nr_requested = val as usize; }, _ => () } } // cpu_inp() is called when the CPU executes an IN instruction, // it simply reads...
Rust
0
#[derive(Debug, Clone, Copy, Default, QueryId, SqlType)] #[postgres(oid = "1184", array_oid = "1185")] pub struct Timestamptz; /// The `Array` SQL type. /// /// This wraps another type to represent a SQL array of that type. /// Multidimensional arrays are not supported, /// nor are arr...
Rust
0
blur = cv2.blur(img, (kernel_size, kernel_size)) cv2.imwrite("img/dist/blur.png", blur, [cv2.IMWRITE_JPEG_QUALITY, 100]) cv2.waitKey(0) cv2.destroyAllWindows() except: pass def imageSmoothingGaussianImg(self, kernel_size): try: im...
Python
1
(); if d_sender.is_some() { return Err(FreenectError::new("Depth Stream already created")); } let (res, sender) = FreenectDepthStream::new(self)?; *d_sender = Some(sender); Ok(res) } pub fn set_depth_mode( &self, resol: FreenectResolution, ...
Rust
0
n in self.foreign_keys: description.append(f"- {table}.{column} -> {ref_table}.{ref_column}") # Common Joins description.append("\nCOMMON JOIN PATTERNS:") for fk in self.foreign_keys: description.append( f"- To get data from {fk[0]} with {fk[2]}:" ...
Python
1
def fizzbuzz(n): assert n>0 and n%1==0, "n must be a positive integer" i=1 while i<=n: if i%3!=0 and i%5!=0: print(i) if i%3==0 and i%5!=0: print("Fizz") if i%5==0 and i%3!=0: print("Buzz") if i%3==0 and i%5==0: print("FizzBuzz"...
Python
1
define(self.serialize()); let trap_data_id = module.declare_data(&trap_sym, ClifLinkage::Local, false, false, None)?; module.define_data(trap_data_id, &trap_sym_ctx)?; Ok(trap_data_id) } pub fn len(&self) -> usize { self.traps.len() } } impl cranelift_codegen:...
Rust
0
_bench(c: &mut Criterion) { let mut rng = rand::thread_rng(); c.bench_function( "Split random iterator n=10e7 (generalized), 3 partitions", |b| b.iter(|| split_iterator_big(&mut rng)), ); } fn split_iterator_ttv_bench(c: &mut Criterion) { let mut rng = rand::thread_rng(); c.bench_fu...
Rust
0
# 컴퓨터랑 가위바위보를 하는 게임만들기 # 조건 # 1. 가위, 바위, 보 중 하나를 입력한다. # 2. 결과를 출력한다. # 3. 컴퓨터와 플레이 중 한명이 3승을 하면 게임이 끝난다. import random list = ["가위", "바위", "보"] com_count = 0 user_count = 0 def count(s1, s2): global com_count global user_count if s1 == "가위": if s2 == "가위": print("컴퓨터: 가위") ...
Python
1
File, }; pub async fn tagged(args: &ArgMatches<'static>) -> Result<Arc<TaggedFilterer>> { let (project_origin, workdir) = super::common::dirs(args).await?; let vcs_types = super::common::vcs_types(&project_origin).await; let ignores = super::common::ignores(args, &vcs_types, &project_origin).await; let filterer =...
Rust
0
.provides_aircraft_variable("PLANE LONGITUDE", "degree longitude", 0)? .provides_aircraft_variable("PUSHBACK STATE", "Enum", 0)? .provides_aircraft_variable("PUSHBACK ANGLE", "Radians", 0)? .provides_aircraft_variable("SEA LEVEL PRESSURE", "Millibars", 0)? .provides_aircr...
Rust
0
me in the current test (in dna_ribbon_view.py). ###KLUGE: use ORIGIN (which we know) in place of center of view (which we don't) -- only correct when no trackballing self._newobj.motion = point_in_newobj_coords ###KLUGE since it centers new obj on mouse, even if mousedown was not centere...
Python
1
from flask import Flask, render_template from sqlalchemy import create_engine, text import os import random from dotenv import load_dotenv load_dotenv() app = Flask(__name__) # קריאת משתני הסביבה DB_USER = os.getenv("DB_USER") DB_PASSWORD = os.getenv("DB_PASSWORD") DB_HOST = os.getenv("DB_HOST", "mysql") DB_PORT = o...
Python
1
self.position + idx; self.position = self.position + idx + 1; Some(found) } None => { self.position = self.haystack.len() + 1; None } } } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { ...
Rust
0
# coding=utf-8 """ ====================================================================== Programa: ColonizacionMarteDiccionario Contacto: Juan Dario Rodas - juand.rodasm@upb.edu.co Propósito: ---------- - Crear una aplicación de consola que permita monitoreo 4 lanzamientos a las diferentes planici...
Python
1
Rng::seed_from_u64(SEED); (0..len).map(move |i| { let rand: f32 = rng.gen(); if rand < DEFAULT_SEP_RATIO { Choice::DefaultSeparator } else if rand < SEP_RATIO { Choice::Separator(format!("Separator {}", i)) } else { Choice::Choice((format!("Choice...
Rust
0
usize }, 12usize, concat!( "Offset of field: ", stringify!(PartitionBoundSpec), "::", stringify!(remainder) ) ); assert_eq!( unsafe { &(*(::std::ptr::null::<PartitionBoundSpec>())).listdatums as *const _ as usize }, 16usize...
Rust
0
differentiate between expressions and ranges. #Series of plots with same range for i in range(len(args)): if isinstance(args[i], Tuple) and len(args[i]) != expr_len: break if not isinstance(args[i], Tuple): args[i] = Tuple(args[i]) else: ...
Python
1
oundedMiner, BenchmarkMissing, MinerNotFounded, MinerNotBounded, MinerNotInReadyState, MinerNotMining, CoolingDownNotPassed, InsufficientStaking, } type BalanceOf<T> = <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance; #[pallet::call] impl<T: Config> Pallet<T> ...
Rust
0
queues/queues_evts vector. pub const STATS_INDEX: usize = 2; // The feature bitmap for virtio balloon. const VIRTIO_BALLOON_F_MUST_TELL_HOST: u32 = 0; // Tell before reclaiming pages. const VIRTIO_BALLOON_F_STATS_VQ: u32 = 1; // Enable statistics. const VIRTIO_BALLOON_F_DEFLATE_ON_OOM: u32 = 2; // Deflate balloon on ...
Rust
0
(borrow_date_str, return_date_str, self.user_id), ) peminjaman_id = cursor.lastrowid # Insert ke tabel peminjaman_detail cursor.execute( "INSERT INTO peminjaman_detail (peminjaman_id, buku_id) VALUES ...
Python
1
lm( sorted_items, descriptions_collected ) # If we go for another loop, reset values to new if i != len(descriptions) - 1: descriptions_collected = [result] usable_tokens = ( self._max_in...
Python
1
` * ``_mymod-f2pywrappers.f`` (if it was generated in Step 1) * ``fortranobject.c`` See Also -------- numpy.get_include : function that returns the numpy include directory """ return os.path.join(os.path.dirname(__file__), 'src') def __getattr__(attr): # Avoid importing things t...
Python
1
word) as usize] ^= pattern >> px_in_dest_low_word; } else { fb[(base + dest_high_word) as usize] &= 0xffff_ffff ^ (pattern >> px_in_dest_low_word); } } fb[(base + WORDS_PER_LINE as i32 - 1) as usize] |= 0x1_0000; // set the dirty bit on the line } let widt...
Rust
0
import sys input_ = sys.stdin.readline def minput(): return map(int, input_().split()) answer = [-1, int(1e9)] def solution(): n = int(input_()) fruits = [0] + list(minput()) adj_ls = [[] for _ in range(n+1)] for _ in range(n-1): a, b = minput() adj_ls[a].append(b) adj_ls[b].ap...
Python
1
(validator_stake_data.as_slice()).or(Err("Invalid stake account data"))?; if config.verbose { println!("Depositing into stake account {:?}", validator_stake_data); } else { println!("Depositing into stake account {}", validator_stake_account); } let mut instructions: Vec<Instruction> = ...
Rust
0
distribution.append(list(f.get_best(method="sumsquare_error").keys())[0]) yaml_dict_lab = { "random": args.random, "n_each_class": args.n, "color_space": args.color_space, "methods": args.methods, "{}".format(args.color_space[0]): { # lab-L/hed-H "avg": { ...
Python
1
import numpy as np def getMedia(lista): lista = np.array(lista) #Verificamos que la lista de datos no estes vacia if not lista.size: return None, None, None else: #Asignamos los resulados de las operaciones a una variable: # rA_A = Resultado del agente A # rA_B = Resulta...
Python
1
, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Softwar...
Rust
0
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: protos/event/notification.proto """Generated protocol buffer code.""" from google.protobuf.internal import builder as _builder from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as...
Python
1
g if there are resources, also by type self.assertTrue(self.slide_3.with_user(self.user_public)._has_additional_resources()) self.assertTrue(self.slide_3.with_user(self.user_public)._has_additional_resources('file')) self.assertTrue(self.slide_3.with_user(self.user_public)._has_additional_resour...
Python
1
memory::ldtu, memory::ldtui, memory::ldo, memory::ldoi, memory::ldou, memory::ldoui, float::ldsf, float::ldsfi, memory::ldht, memory::ldhti, system::cswap, system::cswapi, system::ldunc, system::ldunci, system::ldvts, system::ldvtsi, system::preld, sys...
Rust
0
let action: f64 = match action { ActionType::Discrete(a) => a as f64 - 1.0, ActionType::Continuous(a) => { assert_eq!(a.len(), 1, "action vector has to have length of 1"); // continuous action in range [-1.0, 1.0] if a[0] < -1.0 { ...
Rust
0
rg1: ::c_int), pub sa_mask: sigset_t, pub sa_flags: ::c_int, } pub struct dirent { pub d_ino: ino_t, pub d_type: ::c_uchar, pub d_name: [::c_char; 256usize], } pub struct stack_t { pub ss_sp: *mut ::c_void, pub ss_flags: ::c_int, pub ss_s...
Rust
0
greement_percentage, 2), 'total': total, 'agreed': agreed, 'disagreed': label_stats['agreement']['disagreed'] } }) # Add relation annotations f...
Python
1
where else it is C/C++'s `Bool`. /// /// As a result, this type is a `#[repr(transparent)]` wrapper around /// [`c_schar`] (a.k.a. [`i8`]) or [`bool`] respectively. /// /// This crate uses a [newtype] instead of a [type alias] because aliasing /// [`bool`] would allow for `if x` on some platforms but not others. When u...
Rust
0
from apps.user.models import User, TypeRole from django.contrib.auth.models import Permission from django.contrib.contenttypes.models import ContentType class ChangePermissionAdmin: def __init__(self, user: User) -> None: self.user = user if user.role != TypeRole.admin: raise ValueError(f"El usuario debe tene...
Python
1
# -*- coding:utf-8 -*- # !/usr/bin/env python """ Date: 2022/6/5 22:14 Desc: """
Python
1
kind: solver::GetInfoKind<'c>) -> Self { use self::GetInfoKind::*; use solver::GetInfoKind as Flag; match kind { Flag::AllStatistics => AllStatistics, Flag::AssertionStackLevels => AssertionStackLevels, Flag::Authors => Authors, Flag::ErrorBehaviou...
Rust
0
e_', 'continue') encoding.AddCustomJsonFieldMapping( StandardQueryParameters, 'f__xgafv', '$.xgafv') encoding.AddCustomJsonEnumMapping( StandardQueryParameters.FXgafvValueValuesEnum, '_1', '1') encoding.AddCustomJsonEnumMapping( StandardQueryParameters.FXgafvValueValuesEnum, '_2', '2') encoding.AddCustomJso...
Python
1
sorted_population)//2): parent1 = random.choice(top_half) parent2 = random.choice(top_half) child = (parent1 + parent2) / 2 new_population[vehicle_id].append(child) # Mutation for i in range(len(new_population[vehicle_i...
Python
1
# src/shared/exceptions.py """Definição de exceções personalizadas para o HarvestLink.""" class HarvestLinkException(Exception): """Exceção base para o HarvestLink.""" pass class DeviceNotFoundException(HarvestLinkException): """Exceção lançada quando um dispositivo não é encontrado.""" pass clas...
Python
1
data = data.append(_today_ticks(symbol, date, pNo, retry_count, pause), ignore_index=True) except Exception as er: print(str(er)) else: return data raise IOError(ct.NETWORK_URL_ERROR_MSG) def _today_ticks(symbol, tdate, pag...
Python
1
(0x11b369f1232f25b43e75837ccfffffffff3b667f8fb56572b84a3585ba93d79ff539cf4b5105390a4f83e05ec, 0xb8ebf66046b652875b15d38787b3212abe53f5522ca0c0bb7ea105150aa4f32302bea46d5bb69951caa686a925d44b5c ), (0x6ffd6743a8b3a6ccc58bb412ffffffff3b70ac9d530698865026291ff0304a1a6fe93a555f9391a8fe10a02c...
Python
1
tps://www.rfc-editor.org/rfc/rfc4388.html#section-6.1 AssociatedIp, /// 93 Client System Architecture - <https://www.rfc-editor.org/rfc/rfc4578.html> ClientSystemArchitecture, /// 94 Client Network Interface - <https://www.rfc-editor.org/rfc/rfc4578.html> ClientNetworkInterface, /// 97 Client Ma...
Rust
0
from typing import List import numpy as np from smanim.mobject.vmobject import VMobject import svgelements as se from smanim.typing import ManimFloat, Point3D __all__ = ["VMobjectFromSVGPath"] def _to_3d(x, y, z=0) -> np.ndarray: return np.array([x, -y, 0.0]) # assumes points are in manim units class VMobject...
Python
1
import filecmp import gzip import os from itertools import product from time import sleep from typing import Final, List, Tuple import pytest # These are the relations exported by PAInterface. _GOLDEN_RELATIONS: Final[List[str]] = [ "allocation_size", "subset.callgraph.callgraph_edge", "unification.callgr...
Python
1
: # 检查文件是否存在 if not os.path.exists(self.ini_file): MessageBox.show_error("测试配置文件不存在") return None config = configparser.ConfigParser() config.read(self.ini_file, encoding='utf-8') # 检查 Test 部分是否存在 ...
Python
1
= metadata(&file_name)?; let mut offset_start = 0 as u64; let range_size = (metadata.len() / thread_count as u64) as u64; // To keep contention among threads low, each generator owns/updates their // stats. The "main" thread holds a // reference to these stats so that, when ready, it can print th...
Rust
0
import signal import weakref from functools import wraps __unittest = True class _InterruptHandler(object): def __init__(self, default_handler): self.called = False self.original_handler = default_handler if isinstance(default_handler, int): if default_handler == signal.SIG_D...
Python
1
#!/usr/bin/python3 word = "Holberton" word_first_3 = word[0:3] word_last_2 = word[-2:] middle_word = word[1:-1] print(f"First 3 letters: {word_first_3}") print(f"Last 2 letters: {word_last_2}") print(f"Middle word: {middle_word}")
Python
1
# -*- coding: utf-8 -*- import torch import re import json import numpy as np from collections import defaultdict from config import Config from model import TorchModel """ 模型效果测试 """ class SentenceLabel: def __init__(self, config, model_path): self.config = config self.schema = self.load_schema(co...
Python
1
dh_callback(|_, _, _| { CALLED_BACK.store(true, Ordering::SeqCst); EcKey::from_curve_name(Nid::X9_62_PRIME256V1) }); let ssl = Ssl::new(&ctx.build()).unwrap(); let mut stream = ssl.accept(stream).unwrap(); stream.write_all(&[0]).unwrap(); }); let stream =...
Rust
0
map_err(|err| warn!("カレントディレクトリの取得 {:?}", err)) .ok()?; let (tx, rx) = mpsc::channel(); let mut watcher: RecommendedWatcher = Watcher::new(tx, Duration::from_millis(delay_millis)) .map_err(|err| warn!("ファイルウォッチャーの作成 {:?}", err)) .ok()?; watcher ...
Rust
0
2index(v2)) def calcSyndrome(RS_block, index): s = 0b00000000 #Vector representation for i in range(len(RS_block)): s ^= mulGF256(RS_block[i], index2vector(index * i)) #print( index, bin(s)) return s #Determinant of matrix A_ij with elements in GF(2^8) def detGF256(A): if len(A) != len(...
Python
1
ingResourceRateInfo; use frame_benchmarking::{account, benchmarks, impl_benchmark_test_suite, whitelisted_caller}; use frame_support::traits::{Currency, Get}; use frame_system::RawOrigin; use orml_traits::BasicCurrencyExtended; use primitives::{staking::RoundInfo, Balance, BlockNumber, FungibleTokenId}; use sp_runtime:...
Rust
0
.send(Message::SetStart((track_index, start as u32))) .unwrap(); self.tracks_meta[track_index].set_start(start as isize); } fn set_end(&mut self, track_index: usize, end: usize) { self.sender .send(Message::SetEnd((track_index, end as u32))) .unwrap(); ...
Rust
0
# SPDX-FileCopyrightText: 2021 Dan Halbert for Adafruit Industries # SPDX-FileCopyrightText: 2021 James Carr # # SPDX-License-Identifier: Unlicense from adafruit_simplemath import map_range, map_unconstrained_range, constrain print("map_range() examples") # Map, say, a sensor value, from a range of 0-255 to 0-1023. s...
Python
1
iles, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. # html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes an...
Python
1
import yaml, inspect, os, sys, subprocess, pprint, shutil, argparse from copy import deepcopy import matplotlib.pyplot as plt import csv from parse_timeloop_output import parse_timeloop_stats import numpy as np import random import matplotlib.pyplot as plt import math from parse_timeloop_output import parse_timeloop_st...
Python
1
import tensorflow as tf from dso.policy_optimizer import PolicyOptimizer from dso.policy import Policy class PGPolicyOptimizer(PolicyOptimizer): """Vanilla policy gradient policy optimizer. Parameters ---------- cell : str Recurrent cell to use. Supports 'lstm' and 'gru'. num_layers : in...
Python
1
.0; // error, can't mutate while borrowed /// assert_eq!(*value_to, TotallyOrdered::new(1.0)); /// ``` /// respect the lifetime of the borrow on the original value. fn from(v: &F) -> Self { // TotallyOrdered is repr(transparent) unsafe { &*(v as *const _ as *const _) } } } impl<'a, F: TotallyOrderab...
Rust
0
import pytest from services.doctor_service import DoctorService from repositories.in_memory.doctor_in_memory import InMemoryDoctorRepository from doctor import Doctor @pytest.fixture def doctor_service(): repo = InMemoryDoctorRepository() return DoctorService(repo) def test_register_and_get_doctor(doctor_serv...
Python
1
00); const DEFAULT_AVERAGE_ACK_DELAY: Duration = Duration::from_millis(200); pub(crate) struct Chunker { rng: OsRng, message_preparer: MessagePreparer<OsRng>, } impl Chunker { pub(crate) fn new(tested_mix_me: Recipient) -> Self { Chunker { rng: OsRng, message_preparer: Mess...
Rust
0
@din.handler_falling def on_falling_clock(): """Handler for the falling edge of the input clock Turn off all of the CVs so we don't stay on for adjacent pulses """ turn_off_all_cvs() @b1.handler def on_b1_press(): """Handler for ...
Python
1
(1)), s_sub(m, gt_hi, RI_R(un_hi)), s_sub(m, hi, RI_R(m)), s_add(m, m, RI_I(1)), s_sub(t1, n, RI_R(lo)), s_sub(t2, hi, RI_R(m)), ...
Rust
0
put_sample_rate ) uniform_bps, learned_bps = get_compression_rate( dense_model_name, units, waveform, args.vocab_size, encoder.expected_sample_rate ) print( f"Audio of length {round(waveform.size(0) / 16_000, 1)} seconds represented as {units.numel()} tokens" ) print( f...
Python
1
messages(msgs).add_attributes(vec![ attr("action", "sponsorship"), attr("sponsor", info.sender.to_string()), attr("sponsorship_amount", sponsor_amount), ])) } pub fn execute_sponsor_withdraw( deps: DepsMut, env: Env, info: MessageInfo, ) -> Result<Response, ContractError> { ...
Rust
0
"""Network endpoint helpers for WiiM Coordinator. Each helper isolates *one* HTTP-API call, returning a fully-typed Pydantic model. Splitting them out keeps complex device-I/O away from `coordinator_polling.py` and ensures the core coordinator stays below the 300-LOC soft cap. """ from __future__ import annotations ...
Python
1
# Project EmbodiedGen # # Copyright (c) 2025 Horizon Robotics. All Rights Reserved. # # 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 # # Un...
Python
1
h=input('What is your name?\n') print('Hello,', h+'!')
Python
1
//or "NOT-simplified" sexprs.push(" (let NOR (NOT ( NAND ( NOT A ) ( NOT B ))))"); //An [XOR](https://en.wikipedia.org/wiki/NAND_logic#XOR) //TODO simplify this? sexprs.push( " (let XOR (NAND ( NAND A ( NAND A B ) ) ( NAND B ( NAND A B ) ) ) )", ...
Rust
0
if (g_parsed_args.build is not None): g_users_build_dir = os.path.join(g_parsed_args.build, g_parsed_args.type.lower()) else: g_users_build_dir = os.path.join(g_users_build_dir, g_parsed_args.type.lower()) def _set_asdk_env(): global g_cmake global g_ninja cmake_exists = False n...
Python
1