text
string
label_name
string
labels
int64
) << 1), (((3 << 3) + 1) << 2) - 1, (((7 << 2) - 1) << 2), ((((3 << 2) + 1)) << 3) + 1, (7 << 4), (3 << 5) + (1 << 1), (7 << 4) - 1, (3 << 5) + 1, (7 << 4) + (1 << 1), (((3 << 3) + 1) << 2), (5 << 4) + (1 << 1), (((3 << 3) + 1) << 2) + 1, (3 << 5) + 1, (((3 << 3) + 1) << 2), (((1 << 4) + 1) << 1), (((3 << 3) - 1) << 2)...
Python
1
def get_model(session, batch_size): session._batch_size = batch_size thpt_msg = session.measure_throughput() return (thpt_msg.peak_usage_bytes.slope, thpt_msg.peak_usage_bytes.bias), ( thpt_msg.run_time_ms.slope, thpt_msg.run_time_ms.bias)
Python
1
Inflation = 9, ManageData = 10, BumpSequence = 11, ManageBuyOffer = 12, PathPaymentStrictSend = 13, CreateClaimableBalance = 14, ClaimClaimableBalance = 15, BeginSponsoringFutureReserves = 16, EndSponsoringFutureReserves = 17, RevokeSponsorship = 18, } // CreateAccountOp is an XD...
Rust
0
nwrap(); } else { println!("{}", text); } } fn one_rep(args: OneRepArgs) { let OneRepArgs { weight, reps } = args; let rounded = round_weight((weight * reps as f32 * 0.0333) + weight); println!("{}", rounded); } static HTML: &str = include_str!("templates/plan.html"); fn generate(gen_args...
Rust
0
from datetime import datetime from venv import logger from sqlalchemy import CheckConstraint, Integer, String, Numeric, DateTime, ForeignKey, BigInteger from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship from typing import Optional from project.db.schemas.category import CategoryOut from p...
Python
1
.is_empty()) } fn lookup(&self, rv: RegVal) -> i64 { match rv { RegVal::Reg(r) => self.regs[r], RegVal::Val(v) => v, } } } fn main() { let start = Instant::now(); let instrs = { let f = File::open("18.txt").expect("coudn't open input ...
Rust
0
println!("Y {:?}", step); } if m1.same_z() && m2.same_z() && m3.same_z() && m4.same_z() { m1.save_step_z(step); m2.save_step_z(step); m3.save_step_z(step); m4.save_step_z(step); println!("Z {:?}", step); } let m1_reached = ...
Rust
0
from flask import Flask, render_template from src.main import Warehouse app = Flask(__name__, template_folder='src/templates') @app.route('/') def index(): # Initialize the warehouse warehouse = Warehouse(5, 5) warehouse.add_pick_location(1, 2) warehouse.add_pick_location(3, 4) warehouse.set_obs...
Python
1
import jax.numpy as jnp from typing import Optional from ivy.functional.backends.jax import JaxArray def l1_normalize( x: JaxArray, /, *, axis: Optional[int] = None, out: Optional[JaxArray] = None, ) -> JaxArray: if not isinstance(x, JaxArray): x = jnp.array(x) if axis is None: ...
Python
1
tps_port} ssl;" if not "ipv6_http3_ssl_port_conf" in get.proxy_json_conf: get.proxy_json_conf[ "ipv6_http3_ssl_port_conf"] = "{ipv6_port_conf}\n listen [::]:{https_port} quic;\n listen [::]:{https_port} ssl ;" if not "ipv4_ssl_port_conf" in get.proxy_json_conf: ...
Python
1
err(|e| Error::from(DatabaseIntegrityError::from(e)))? .into(), ), 0x42 => VariantDictionaryValue::ByteArray(value_buffer.to_vec()), _ => { return Err(DatabaseIntegrityError::InvalidVariantDictionaryValueType { ...
Rust
0
your range. Using default instead.")) } } fn check_min(min: String) -> Result<(), String> { let num_or_err = is_u8(min); match num_or_err { Ok(num) => { if num < 255 { return Ok(()) } else { return Err(String::from("Minimum can't be 255.")) ...
Rust
0
PathBuf::new()), number: None, nested_items: Vec::new(), } } } /// An item in `SUMMARY.md` which could be either a separator or a `Link`. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub enum SummaryItem { /// A link to a chapter. Link(Link), /// A separato...
Rust
0
ccuracy_Coverage_Plot': acc_cov_plot, 'Calibration_Plot': calib_plot, 'Distribution_Plot': dist_plot } import csv file_exists = os.path.isfile(summary_path) with open(summary_path, 'a', newline='') as f: writer = csv.DictWriter(f, fieldnames=row.keys()) if not file_exists...
Python
1
ItemData.PlayerTriggerListDialogTopics, StoryItemData.ChangeDisposition, StoryItemData.NpcStartFollow, StoryItemData.NpcStopFollow, StoryItemData.NpcActivate, StoryItemData.NpcTravel, StoryItemData.NpcPickUpItem, StoryItemData.NpcAttack, StoryItemData.NpcCome, StoryItemData.NpcDeath,...
Python
1
for key, (image_root, json_file) in _PREDEFINED_SPLITS_YTVIS_2021.items(): # Assume pre-defined datasets live in `./datasets`. register_ytvis_instances( key, _get_ytvis_2021_instances_meta(), os.path.join(root, json_file) if "://" not in json_file else json_file, ...
Python
1
'''Babbage problem''' from math import (floor, sqrt) from itertools import (islice) # squaresWithSuffix :: Int -> Gen [Int] def squaresWithSuffix(n): '''Non finite stream of squares with a given suffix.''' stem = 10 ** len(str(n)) i = 0 while True: i = until(lambda x: isPerfectSquare(n + (ste...
Python
1
let buf = vec![0; width as usize * height as usize * pixel_format.byte_count()]; gl.active_texture(GL::TEXTURE0); gl.bind_texture(GL::TEXTURE_2D, Some(&texture)); gl.pixel_storei(GL::UNPACK_ALIGNMENT, 1); gl.pixel_storei(GL::PACK_ALIGNMENT, 1); gl.tex_image_2d_with_i32_and_i32...
Rust
0
ject_dir.name info_file = project_dir / 'project_info.json' if info_file.exists(): try: info = json.loads(info_file.read_text()) workspace_basename = info.get('workspace_basename', '') workspace_path = info....
Python
1
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations from typing_extensions import Literal, Required, TypedDict __all__ = ["ImageFileParam"] class ImageFileParam(TypedDict, total=False): file_id: Required[str] """ The [File](https://pl...
Python
1
e() { use zeroize::Zeroize; let mut a = Fp::one(); a.zeroize(); assert!(bool::from(a.is_zero())); } //! The goal of this crate is to match Instagram's parsing of hashtags. So if you find strings that //! aren't parsed correctly please open an issue 😃 //! //! ## Example //! //! ``` //! use hashtag::{Ha...
Rust
0
ObserveOption::Register as u8]); let mut subject: Subject<Endpoint> = Subject::default(); subject.set_unacknowledged_limit(5); subject.register(&request1); subject.resource_changed(resource_path); subject.resource_changed(resource_path); subject.resource_changed(resourc...
Rust
0
and does /// the position translation. pub struct PruneList { path: Option<String>, /// Bitmap representing pruned root node positions. bitmap: Bitmap, /// Bitmap representing all pruned node positions (everything under the pruned roots). pruned_cache: Bitmap, shift_cache: Vec<u64>, leaf_shift_cache: Vec<u64>, }...
Rust
0
in range(num_folds): new_seed=seed_list[num_fold] info(f"Seed{new_seed}") torch.manual_seed(new_seed) np.random.seed(new_seed) random.seed(new_seed) model = MultiMixedInformationNetwork(dataset_type, task_num, fp_Linear_dim, dropout_FPN, cuda, hidden_size, ...
Python
1
:to_writer(&mut out_docs, &title).expect("write docs.txt"); out_docs.push(b'\0'); for term in terms { out_terms.append(&mut term.into_bytes()); out_terms.push(b'\0'); }; out_terms.push(b'\0'); }; File::create(out_dir.join("docs.txt")) .expect("open...
Rust
0
e: Vec<i32>, } let opts = Opts::parse_args_default(&["1", "2", "3"]).unwrap(); assert_eq!(opts.free, [1, 2, 3]); } #[test] fn test_multi_free() { #[derive(Options)] struct Opts { #[options(free, help = "alpha help")] alpha: u32, #[options(free, help = "bravo help")] ...
Rust
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Python项目通用打包脚本 将Python项目打包为单个EXE可执行文件 使用方法: python build.py 功能: 1. 检查所需依赖并自动安装 2. 清理旧的构建文件 3. 获取用户打包偏好设置(界面模式、图标、输出文件名) 4. 自动检测项目文件和结构 5. 打包项目为单个EXE可执行文件 """ import os import sys import subprocess import shutil import glob import traceback im...
Python
1
in owner_changed { let args = signal.args().unwrap(); if args.name() == well_known { // Meant for the this testcase. assert_eq!(*args.new_owner().as_ref().unwrap(), *unique_name); break; } } // `NameAcquired` is emitted...
Rust
0
ty: Type) -> Inst { match ty { types::B1 | types::B8 | types::I8 => Inst::Store8 { rd: from_reg, mem }, types::B16 | types::I16 => Inst::Store16 { rd: from_reg, mem }, types::B32 | types::I32 => Inst::Store32 { rd: from_reg, mem }, types::B64 | types::I64 | types...
Rust
0
3::ZERO, Vec3::Y); camera.perspective_projection.near = 1.0; camera.perspective_projection.far = 10000.0; commands.spawn_bundle(camera); } fn limit_length(v: &mut DVec3, len: f64) { if v.length() > len { *v = v.normalize() * len; } } fn moving(time: Res<Time>, mut query: Query<(&mut Star, ...
Rust
0
: expected_certify_info_qualified_name .clone() .try_into() .expect("failed to convert qualified name to tss type"), } .try_into() .expect("Failed to convert TPMS_CERTIFY_INFO to CertifyInfo"), }; let (attest, expected_tpms_attest) = ...
Rust
0
target_i = char_target_i.replace(self.blank, "") char_pred.append(char_pred_i) char_target.append(char_target_i) return char_pred, char_target def calculate_cer( self, char_pred: torch.Tensor, char_target: torch.Tensor ) -> float: """Calculate sentence-level CE...
Python
1
# Copyright 2018,2019,2020,2021 Sony Corporation. # # 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 a...
Python
1
<String, SnippextTemplate> = HashMap::new(); loop { let identifier = Text::new("Template identifier:") .with_validator(required!("This field is required")) // .with_validator(&|id| { // let now = chrono::Utc::now().naive_utc().date(); // // ...
Rust
0
None, } } } pub struct TableInCBuilder<'a: 'b, 'b> { fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>, start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>, } impl<'a: 'b, 'b> TableInCBuilder<'a, 'b> { #[inline] pub fn add_refer_to_a1(&mut self, refer_to_a1: flatbuffers::WIPOffset<super:...
Rust
0
from dotenv import load_dotenv from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine from sqlalchemy.orm import sessionmaker, declarative_base from sqlalchemy import MetaData import os load_dotenv() SQLALCHAMY_DATABASE_URL = os.getenv("DATABASE_URL") print(SQLALCHAMY_DATABASE_URL) Base = declarative_b...
Python
1
from .base import Randomize from typing import Dict, Any from ..tasks.task import BaseTask import numpy as np from omni.isaac.core.prims import XFormPrim from omni.isaac.core.utils.prims import get_prim_parent, get_prim_at_path @Randomize.register("RobotBaseRandom") class RobotBaseRandom(Randomize): def __init__(...
Python
1
(0f64) as u32; let right = bbox.max().x.min(image_width as f64) as u32; let top = bbox.min().y.max(0f64) as u32; let bottom = bbox.max().y.min(image_height as f64) as u32; let mut feature_image: RgbImage = ImageBuffer::new(bbox.width().ceil() as u32, bbox.height().ceil() as u32); for x in ...
Rust
0
import torch import requests import os try: slack_url = os.environ["SLACK_URL"] except: slack_url = None def lr_iteration(optimizer,writer): def print_lr(engine): for i, pg in enumerate(optimizer.param_groups): writer.experiment.log_metric(f'train/lr{i}', engine.state.iteration - 1...
Python
1
PCs = [] NPCs.append(NPC([865,745])) player = Player(743, 254, PLAYER_SPEED, 100, "Player 1", 15, 1) camera_x = player.pos[0] - WIDTH // 2 camera_y = player.pos[1] - HEIGHT // 2 #Initialize enemies enemy_start = [WIDTH / 2 - (camera_x - (BACKGROUND_WIDTH - WIDTH) / 2), HEIGH...
Python
1
profiler::Event<M, L>) -> profiler::Event<M, L> { // If you define a new Event variant, this will fail to compile to remind you to: // - Create a new test covering deserialization of the previous format, if necessary. // - Update `TEST_LOG` in this test to cover every variant of the...
Rust
0
.get_vlq_int() .expect("get_vlq_int() should return OK"); assert_eq!( v as u32, values[i], "[{}]: expected {} but got {}", i, values[i], v ); } } #[test] fn test_put_zigzag_vlq_int() { le...
Rust
0
if np.all(action_error < 0.05): reward += 1.0 print(f"Computed reward: {reward} for expected action: {action}, actual action: {self.current_velocity}, goal distance: {goal_distance}") return reward def is_done(self): collision = self.check_collision_condition() ...
Python
1
ter().enumerate().for_each(|(x, foobar)| { loops += 1; match foobar.sibling.as_ref() { Some(old_bar) => { assert_eq!(old_bar.time, 123456 + (x as i32)); assert_eq!(old_bar.ratio, 3.14159 + (x as f32)); ...
Rust
0
""" Temporary shim module to indirect the bits of distutils we need from setuptools/distutils while providing useful error messages beyond `No module named 'distutils' on Python >= 3.12, or when setuptools' vendored distutils is broken. This is a compromise to avoid a hard-dep on setuptools for Python >= 3.12, since m...
Python
1
# Requirements /// /// `from` must be no greater than `upto`. /// /// [`RangeBounds`]: core::ops::RangeBounds /// [`Range<BitIdx<R>>`]: core::ops::Range pub fn range( self, upto: BitEnd<R>, ) -> impl Iterator<Item = Self> + DoubleEndedIterator + ExactSizeIterator + FusedIterator { let (from, upto) = (s...
Rust
0
mation." msg = OpenAIChatMessage.create_empty("user") if refer_image: msg = msg.add(ContentSegment.image_content(source_image_data)) if not config.USE_SYSTEM_ROLE: msg = msg.add( ContentSegment.text_content( f"{system_content}\n\nCarefully analyze...
Python
1
raft_serverpb::RaftLocalState; use protobuf::Message; use raft::eraftpb::Entry; use raft_log_engine::RaftLogEngine; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use std::{cmp, fs}; use tikv::config::TiKvConfig; const BATCH_THRESHOLD: usize = 32 * 1024; fn get_pat...
Rust
0
let remaining_gens: isize = (total_gens - gen) as isize; return pots.sum_of_pot_numbers() + remaining_gens * pot_sum_diff_per_gen; } else { // println!("{:2}: {}", gen, pots.to_string()); } } pots.sum_of_pot_numbers() } #[cfg(test)] mod tests { use supe...
Rust
0
uper().__init__(*args, **kwargs) def __iter__(self): fk = getattr(self.formset, "fk", None) for field in self.fields: if fk and fk.name == field: continue yield Fieldline(self.form, field, self.readonly_fields, model_admin=self.model_admin) class AdminError...
Python
1
표시합니다.""" try: if not result or not hasattr(result, 'info_log'): st.warning("분석 결과가 없습니다.") return # 주식명 표시 if hasattr(result, 'stock_name') and result.stock_name: st.subheader(f"📋 분석 결과 - {result.stock_name}({result.stock_code})") else:...
Python
1
# # This file is part of Cynthion # import logging from .board import CynthionBoard # Ensure that we have access to all Cynthion boards. Normally, we'd avoid # importing an entire namespace, but in this case, this allows us to ensure # that all board modules are loaded for autoidentification. from .boards import * ...
Python
1
!` requires a value for all fields. As // /// events are recorded immediately when the macro is invoked, there is no // /// opportunity for fields to be recorded later. A trailing comma on the final // /// field is valid. // /// // /// For example, the following does not compile: // /// ```rust,compile_fail // /// # #[...
Rust
0
eck", hidden_act="relu", downsample_in_first_stage=False, downsample_in_bottleneck=False, out_features=None, out_indices=None, **kwargs, ): super().__init__(**kwargs) if layer_type not in self.layer_types: raise ValueError(f"layer_type={lay...
Python
1
curacy: # accuracy_threshold = args.accuracy #else: # accuracy_threshold = 4 if args.reply_threshold: reply_threshold = args.reply_threshold # File to store the last processed tweet ID LAST_TWEET_FILE = f'last_tweet_id_{username}.txt' RESTART_DELAY = 10 backoff_multiplier = 1 # The main loop def main(): ...
Python
1
ved_docs, ["persona", "NLP", "language model"]) noise_robustness = calculate_noise_robustness(retrieved_docs, sample_noisy_inputs) # Calculate generation metrics faithfulness = calculate_faithfulness(sample_generated_answer, sample_ground_truth) answer_relevance = calculate_answer_relevance(sample_gene...
Python
1
_CREATE_INFO_NV , 1000026000]; stype![DEDICATED_ALLOCATION_BUFFER_CREATE_INFO_NV , 1000026001]; stype![DEDICATED_ALLOCATION_MEMORY_ALLOCATE_INFO_NV , 1000026002]; // Provided by VK_EXT_transform_feedback stype![PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_FEATURES_EX...
Rust
0
a d@sVddlTddlZGdddeZGdddeZGdddejZed krRedS) )*Ncs8eZdZdefdefgZdZfddZddZZS)XabFcst|}d|_|S)NT)super__new__new_was_called)clsresult...
Python
1
, {'retailer_id': '10539634', 'method': 'DELETE'} ] mock_response = Mock() mock_response.raise_for_status.side_effect = requests.exceptions.HTTPError( "400 Client Error: Bad Request for url") with patch("kairon.meta.processor.requests.post", return_value=mock_re...
Python
1
item=all_data_items[doc_id], response_item=all_response_items[doc_id], ): doc_id for doc_id in all_data_items.keys() } for future in concurrent.futures.as_completed(future_to_doc): doc_id = future_to_doc[...
Python
1
import envi.bits as e_bits class BinaryTree: ''' A simple binary search tree capable of using integers or string representations of binary integers as inputs. NOTE: the lookup routines assume once a node is found which has nodeinfo, we have matched. It does *not* need to walk the rest of the ...
Python
1
_none_mut().0, self.into_glib()); } value } fn value_type(&self) -> glib::Type { Self::static_type() } } #[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Clone, Copy)] #[non_exhaustive] #[doc(alias = "GDriveStartStopType")] pub enum DriveStartStopType { #[doc(alias = "G_DR...
Rust
0
from ricedb.rice import installer, package import unittest, os class testInstaller(unittest.TestCase): """ Testing the Rice download and installer methods """ def setUp(self): self.test_package_data = { 'name': 'test1', 'program': 'i3', 'upstream': 'http://gi...
Python
1
th = "../test-lib", features = ["bar"] } [target.'cfg(target_arch = "wasm32")'.dependencies] # issue #9, #11 test-lib-dep = { path = "../test-lib-dep", features = ["test-lib"] } "#, )); } #[test] fn ui_not_exist() { let mut cmd = bin(); cmd.arg("not-exists").arg("+foo"); cmd.assert().failure().stderr(...
Rust
0
import re m = re.search(r"a+", "caaab") assert m.group(0) == "aaa" assert m.group() == "aaa" m = re.match(r"(?ms)foo.*\Z", "foo\nbar") assert m.group(0) == "foo\nbar" assert re.match(r"a+", "caaab") is None m = re.match(r"a+", "aaaab") assert m.group(0) == "aaaa" assert re.sub("a", "z", "caaab") == "czzzb" assert r...
Python
1
ata by dividing into smaller chunks and waiting for acknowledge after the last chunk""" if len(dat) > 0xFF: raise ValueError("Packet longer than 255 bytes not supported") # Prepend length payload = struct.pack(">H", len(dat)) + dat while payload: last = ...
Python
1
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without eve...
Python
1
from pyro.Constant import Constant class FlagsName(Constant): FO4: str = 'Institute_Papyrus_Flags.flg' SF1: str = 'Starfield_Papyrus_Flags.flg' SSE: str = 'TESV_Papyrus_Flags.flg' TES5: str = 'TESV_Papyrus_Flags.flg' class GameName(Constant): FO4: str = 'Fallout 4' SF1: str = 'Starfield' ...
Python
1
)] fn reset_value() -> Self::Ux { 0 } } <reponame>rbatis/fast_log use std::time::Duration; use fast_log::appender::{FastLogFormatRecord, LogAppender, FastLogRecord}; use fast_log::filter::NoFilter; use log::Level; use std::thread::sleep; use chrono::{DateTime, Local}; struct CustomLog {} impl LogAppen...
Rust
0
e all items with the key before insertion pub fn insert(&mut self, key: String, value: String, replace_all: bool) { if replace_all { self.items .iter() .position(|(k, _)| k == &key) .map(|p| self.items.remove(p)); } self.items.push((key, value)) } /// Removes all items with a key, returning an...
Rust
0
print('\33c') student = list( ) data = list() grades = list() view = 0 print('\33[1m=\33[m'*30) print(f"\33[1m{'[':<}{'CADRASTRO DE ALUNOS':^28}{']':>}\33[m") print('\33[1m=\33[m'*30) while True: print('-'*30) data.append(str(input('[Aluno(a)]: '))) n1 = float(input('[Nota 1ª]: ')) n2 = float(inpu...
Python
1
t OUT_LINK_CH0_SPEC; impl crate::RegisterSpec for OUT_LINK_CH0_SPEC { type Ux = u32; } #[doc = "`read()` method returns [out_link_ch0::R](R) reader structure"] impl crate::Readable for OUT_LINK_CH0_SPEC { type Reader = R; } #[doc = "`write(|w| ..)` method takes [out_link_ch0::W](W) writer structure"] impl crate...
Rust
0
olymorphic_union( util.OrderedDict([("a", t1), ("b", t2), ("c", t3)]), None ), "SELECT t1.c1, t1.c2, t1.c3, CAST(NULL AS INTEGER) AS c4, " "CAST(NULL AS INTEGER) AS c5 FROM t1 UNION ALL SELECT t2.c1, " "t2.c2, t2.c3, t2.c4, CAST(NULL AS INT...
Python
1
: ErrorKind, error: Box<dyn error::Error + Send + Sync>) -> CborError { CborError { kind, error } } fn new_err<T>(kind: ErrorKind, error: Box<dyn error::Error + Send + Sync>) -> Result<T> { Err(CborError::new(kind, error)) } } impl fmt::Display for CborError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Resu...
Rust
0
k). Self::from_vec(vec) } #[inline] pub(crate) fn overhead_bytes() -> usize { RcUtils::meta_overhead::<TConfig::TCounter>() } } pub struct AnyRcConfigForNonSync; impl AnyRcImplConfig for AnyRcConfigForNonSync { type TCounter = NsRcCounter; #[inline] fn table() -> &'static...
Rust
0
fn default() -> Self { Self::None } } impl TryInto<(Self, InitialConsonant)> for FinalConsonant { type Error = Self; fn try_into(self) -> Result<(Self, InitialConsonant), Self> { match self { Self::GS => Ok((Self::G, InitialConsonant::S)), Self::NJ => Ok((Self::N...
Rust
0
_eq!("ndls1".parse(), Ok(Name(String::from("ndls1")))); assert_eq!("".parse::<Name>(), Err(ParseError::Empty)); assert_eq!("🍜".parse::<Name>(), Err(ParseError::Invalid)); let s = "n".repeat(MAX_LENGTH + 1); assert_eq!(s.parse::<Name>(), Err(ParseError::Invalid)); } } // Copyright ...
Rust
0
InboundBandwidthInformation: NL_BANDWIDTH_INFORMATION, OutboundBandwidthInformation: NL_BANDWIDTH_INFORMATION, }} pub type PMIB_IP_NETWORK_CONNECTION_BANDWIDTH_ESTIMATES = *mut MIB_IP_NETWORK_CONNECTION_BANDWIDTH_ESTIMATES; extern "system" { pub fn GetIfStackTable( Table: *mut PMIB_IFSTACK_TABLE, ...
Rust
0
""" Bellman-Ford Algorithm """ from typing import Dict, List, Tuple def bellman_ford(graph: Dict[str, Dict[str, int]], start: str) -> Dict[str, int]: """ Find shortest paths from start vertex to all vertices using Bellman-Ford algorithm. Args: graph (Dict[str, Dict[str, int]]): Dictionary of vert...
Python
1
::time::{Duration, Instant}; use tokio::sync::Mutex; pub mod constants { use std::time::Duration; /// Default file ttl (time since last touched) before until closing (2.5 min) pub const DEFAULT_FILE_TTL: Duration = Duration::from_secs(60 * 2.5 as u64); /// Default proc ttl (time since last touched) b...
Rust
0
currentTurPos += changeTur if currentTurPos > 8: currentTurPos = 8 elif currentTurPos < 0: currentTurPos = 0 if mainTankX - (tankWidth/2) < xlocation+barrier_width: mainTankX += 5 gameDisplay.fill(white) gun = tank(ma...
Python
1
rpl!(RPL_ENDOFNAMES[366] { global(msg _a) {} (this) ["The original query."] query: String [&str] get { &this.query } parse { from_cstring(*msg) } }); //todo RPL_LINKS/ENDOFLINKS rpl!(RPL_BANLIST[367] { global(msg _a) {} (this) ["The channel being queried."] channel: I...
Rust
0
# Copyright (c) Meta Platforms, Inc. and affiliates. # This software may be used and distributed according to the terms of the Llama 2 Community License Agreement. # For dataset details visit: https://huggingface.co/datasets/samsum import copy import datasets def get_preprocessed_samsum(dataset_config, tokenizer, s...
Python
1
correct on 26 May 2020, but I give no promises about maintaining this forever :-) cargo run /path/to/a/csv/file.csv >massaged_destination.csv The code autodetects whether it is a BOM or a PickAndPlace coordinate file. */ fn rot_adjust(rot: &str, delta: i32) -> String { let rot = rot.parse::<i32>().unwrap(); ...
Rust
0
.get_node_id(), serverID: ServerID { host: self.options.vertx_host.clone(), port: self.event_bus_port as i32, }, }); } None => {} } } fn create_net_server(&mut self) -> &mut N...
Rust
0
.reader())) } fn length(&self) -> u64 { self.file.size } } const ACCESS_KEY_ID: &str = "minioadmin"; const SECRET_ACCESS_KEY: &str = "minioadmin"; const PROVIDER_NAME: &str = "Static"; const MINIO_ENDPOINT: &str = "http://localhost:9000"; // Test that a SQL query can be executed on a Parquet file...
Rust
0
else: resp.entries = os.listdir(path) resp.status.result = Status.SUCCESS resp.status.error = Status.NO_ERROR return resp def write_records(self): pass def load_records(self): pass if __name__ == '__main__': rospy.init_node('librar...
Python
1
y < 0 { overflow = true; continue; } x = y; scale *= 10f64; i += 1; } (x, scale, &s[i..]) } #[cfg(test)] mod tests { use super::*; #[test] fn test_parse_duration() -> Result<(), Error> { assert_eq!(parse_duration("50ns")?, 50); ...
Rust
0
TILE_DIM as usize) { let tile_min_y = (tile_index_y * (TILE_DIM as usize)) as i32; let tile_max_y = tile_min_y + (TILE_DIM as usize) as i32 - 1; if bb_max_y < tile_min_y || bb_min_y > tile_max_y { contin...
Rust
0
""" Write a python function that takes in a tuple and an element and counts the occcurences of the element in the tuple. assert count_X((10, 8, 5, 2, 10, 15, 10, 8, 5, 8, 8, 2),4) == 0 """ def count_X(tup, x): return tup.count(x) assert count_X((10, 8, 5, 2, 10, 15, 10, 8, 5, 8, 8, 2),4) == 0 assert count_X((10, ...
Python
1
raw_pressure as i32, temperature: raw_temperature as i32, }; Ok(sample) } fn reset(&mut self, delay_source: &mut impl DelayMs<u8>) -> Result<(), E> { self.send(Command::RESET.address())?; delay_source.delay_ms(3); Ok(()) } fn read_coefficients(&mut...
Rust
0
LineStatus::Added => self.added, LineStatus::Modified => self.modified, LineStatus::Error => self.error, LineStatus::ErrorDescription => self.error, } } } //! A simple abstraction around a single Ether Dream DAC. pub mod stream; pub use self::stream::Stream; use crate::...
Rust
0
return vehicle_objects # transforms a vehicle data record as String into a {@link Vehicle} object # @param vehicle data record as String # @return {@link Vehicle} object def transform_to_vehicle_object(self, vehicle_as_string_array: str) -> Vehicle: # TODO transform the vehicle as string in...
Python
1
ms) time_elapsed = time() - time_elapsed print('Simulation finished in ' + '%.2f' % time_elapsed + ' s') # In[19]: # Remove the context from the audio inputs and reshape to 1D arrays audio_nh = audio_input_nh[:,context_size:].flatten() audio_hl = audio_input_hl[:,context_size:].flatten() # Reshape the ICNet respons...
Python
1
} pub struct JsonArray(Vec<JsonValue>); pub struct JsonObject(BTreeMap<String, JsonValue>); impl JsonValue { #[allow(dead_code)] pub fn string(&self, key: &str) -> Result<String, JsonError> { match self { JsonValue::Object(o) => match o.get(key).ok_or(JsonError::MissingValue)? { ...
Rust
0
rams = {'num_columns': len(features), 'num_labels': 5, 'hidden_units': [96, 96, 896, 448, 448, 256], 'dropout_rates': [0.03527936123679956, 0.038424974585075086, 0.42409238408801436, 0.10431484318345882, 0.49230389137187497, 0.32024444956111164, 0.2716856145683449, 0.4379233941604448], ...
Python
1
debug.error("A Hive offset must be provided (--hive-offset)") h = hivemod.HiveAddressSpace(addr_space, self._config, self._config.hive_offset) return rawreg.get_root(h) def render_text(self, outfd, data): outfd.write("{0:20s} {1}\n".format("Last Written", "Key")) self.print_key(o...
Python
1
Client for Client { fn make_client(client_id: String) -> Self { Client { client_id } } } impl<'a, 'r> rocket::request::FromRequest<'a, 'r> for Client { type Error = (); fn from_request( request: &'a rocket::request::Request<'r>, ) -> rocket::request::Outcome<Client, Self::Error> { ...
Rust
0
rage, _>(&revision_id) } /// Properties accessor for zome config. fn read_foreign_index_zome(conf: DnaConfigSliceObservation) -> Option<String> { Some(conf.satisfaction.index_zome) } /// Properties accessor for zome config. fn read_foreign_event_index_zome(conf: DnaConfigSliceObservation) -> Option<String> { ...
Rust
0
.0, 4.0, 8.0, 2.0, 4.0, 8.0, 16.0, 4.0, 8.0, 16.0, 32.0]); let matrix2 = Matrix::new(4, &[1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0]); let expected_result = Matrix::new(4, &[0.0, 1.0, 2.0, 4.0, 1.0, 2.0, 4.0, 8.0, 2.0, 4.0, 8.0, 16.0, 4.0, 8.0, 16.0, 32.0]); ...
Rust
0