text
string
label_name
string
labels
int64
(|escape| match escape { 'n' => Ok('\n'), 'r' => Ok('\r'), 't' => Ok('\t'), '\\' => Ok('\\'), '\"' => Ok('\"'), _ => Err(StreamErrorFor::<I>::message_message(format!("Invalid escape sequence: '\\{}'",...
Rust
0
pub fn variant(&self) -> Option<SSTOP_A> { match self.bits { 0 => Some(SSTOP_A::SSTOP_0), 2 => Some(SSTOP_A::SSTOP_2), 3 => Some(SSTOP_A::SSTOP_3), _ => None, } } #[doc = "Checks if the value of the field is `SSTOP_0`"] #[inline(always)] ...
Rust
0
} #[doc = "Bits 0:7 - Permitted RFC modes. More than one mode can be permitted."] #[inline] pub fn avail(&self) -> AVAILR { AVAILR::_from({ const MASK: u8 = 255; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) as u8 }) } } // LeetCode 14...
Rust
0
ideal value (defined by balance_ratio). pub deviation_threshold: Rate, /// Balance Ration represents the percentage of Working pool value to be covered by value in /// Liquidation Poll. pub balance_ratio: Rate, /// Maximum ideal balance during pool balancing pub max_ideal_balance_usd: Option<Balance>, } type Ba...
Rust
0
as Box_; use std::fmt; use std::mem::transmute; use webkit2_webextension_sys; glib_wrapper! { pub struct DOMHTMLParamElement(Object<webkit2_webextension_sys::WebKitDOMHTMLParamElement, webkit2_webextension_sys::WebKitDOMHTMLParamElementClass, DOMHTMLParamElementClass>) @extends DOMHTMLElement, DOMElement, DOMNode...
Rust
0
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the terms described in the LICENSE file in # the root directory of this source tree. from typing import Optional from llama_stack.apis.telemetry import * # noqa: F403 from .config import ConsoleConfig ...
Python
1
Ext, CallApiAt, ConstructRuntimeApi, ProvideRuntimeApi, StorageProof}; use sp_block_builder::BlockBuilder; use sp_consensus::{BlockOrigin, NoNetwork, Proposal}; use sp_consensus_babe::BabeApi; use sp_core::traits::CodeExecutor; use sp_core::H256; use sp_inherents::{CreateInherentDataProviders, InherentDataProvider}; us...
Rust
0
round_truth: {item[1]}, reward: {reward}" # ) out_dict = tokenize_for_trainer( self.tokenizer, item["messages"], item["finish_reason"] ) tokens = out_dict["tokens"] masks = out_dict["masks"] # remove obvi...
Python
1
.get_queue_availability() == 0 { return Err("Queue full for worker"); } let q = self.get_queue_in(); q.send(j); self.queue_available.fetch_sub(1, Ordering::SeqCst); Ok(()) } } <gh_stars>0 // Copyright (c) 2018-2020 MobileCoin Inc. //! Core SGX Types #![cfg_attr(...
Rust
0
""" USP Desenho com # """ # Recebe as dimensões do retângulo largura = int(input("Digite a largura: ")) altura = int(input("Digite a altura: ")) # Laços aninhados para desenhar o retângulo for i in range(altura): # Loop externo para as linhas (altura) for j in range(largura): # Loop interno para as colunas (lar...
Python
1
class Solution: def maximumTripletValue(self, nums: List[int]) -> int: ans = 0 left = nums[0] for j in range(1, len(nums)): if left < nums[j]: left = nums[j] continue for k in range(j+1, len(nums)): ans = max(ans, (left ...
Python
1
let cups = play_crab_cups( part2_cups(input), 10_000_000, ); let a = cups.cups[1]; let b = cups.cups[a]; Ok((a as u64) * (b as u64)) } fn destination_cup(cur: usize, max: usize, a: usize, b: usize, c: usize) -> usize { let dest = { if cur == 1 { max ...
Rust
0
deref_mut(&mut self) -> &mut TaskRef { &mut self.taskref } } impl RoundRobinTaskRef { /// Creates a new `RoundRobinTaskRef` that wraps the given `TaskRef`. pub fn new(taskref: TaskRef) -> RoundRobinTaskRef { RoundRobinTaskRef { taskref: taskref, context_switches: 0, ...
Rust
0
ize=(12, 4)) axes[0].plot(train_errors_without, label="gbm_full") axes[0].plot(train_errors_with, label="gbm_early_stopping") axes[0].set_xlabel("Boosting Iterations") axes[0].set_ylabel("MSE (Training)") axes[0].set_yscale("log") axes[0].legend() axes[0].set_title("Training Error") axes[1].plot(val_errors_without, l...
Python
1
IoSliceMut::new(&mut []); let buffer = ioslice .iter_mut() .find(|slice| !slice.is_empty()) .unwrap_or(&mut empty); self.read(buffer) } #[inline] pub fn is_read_vectored(&self) -> bool { false } pub fn write(&self, buffer: &[u8]) -> io::...
Rust
0
# Copyright 2012 OpenStack Foundation # 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 # # Unless requ...
Python
1
ghtX) * 8.0) as i32, y + 104 + (window.gamepad_axis_movement(gamepad, GamepadAxis::RightY) * 8.0) as i32, 9.0, Color::GRAY, ); } else { canvas.draw_circle( x + 204 + (window.gamepad_axis_movement(gamepad, GamepadAxis::RightX) * 8.0) as i32, ...
Rust
0
::new( 200, EnemyType::Follower, vec![ Vec2F32::new(-200.0,-SPAWN_DISTANCE), Vec2F32::new(-100.0,-SPAWN_DISTANCE), Vec2F32::new(0.0,-SPAWN_DISTANCE), Vec2F32::new(100.0,-SPAWN_DISTANCE), Vec2F32::new(200.0,-SPAWN_DISTANCE), ])); data.push(PhaseData::new( 500, EnemyType::Ballrider, vec![Vec...
Rust
0
from abk_aapl.solution import solution k = 3 a = [1, 6, 8, 2, 4, 9, 12] result = solution(k, a) print(f"Result: {result}") print("Expected: 3") # Verify pairs manually pairs = [] for i in range(len(a)): for j in range(len(a)): if i != j and a[j] - a[i] == k: pairs.append((a[i], a[j])) print(f...
Python
1
'$R_Z$') # plt.title('XZ') # plt.figure(3) # plt.plot(rx_vec, ry_vec) # plt.xlabel('$R_X$') # plt.ylabel('$R_Y$') # plt.title('XY') # plt.figure(4) # plt.plot(ry_vec, rz_vec) # plt.xlabel('$R_Y$') # plt.ylabel('$R_Z$') # plt.title('YZ') # def plot3D(): # fig = plt.figure(...
Python
1
squeezed = self.rate - rate_start_index; output[..num_elements_squeezed].clone_from_slice( &self.state[rate_start_index..(num_elements_squeezed + rate_start_index)], ); // Unless we are done with squeezing in this call, permute. if output.len() != self.rate { sel...
Rust
0
; e.enc64_func( iconst.bind(I64), rec_pu_id.opcodes(&MOV_IMM).rex(), |encoding| encoding.inst_predicate(is_unsigned_int32.clone()), ); e.enc64_func(iconst.bind(I64), rec_pu_id.opcodes(&MOV_IMM), |encoding| { encoding.inst_predicate(is_unsigned_int32) }); // Sign-ext...
Rust
0
fmt::Formatter) -> core::fmt::Result { f.debug_struct("USB0_EP5").finish() } } #[doc = "Universal Serial Bus"] pub struct USB0_EP6 { _marker: PhantomData<*const ()>, } unsafe impl Send for USB0_EP6 {} impl USB0_EP6 { #[doc = r"Pointer to the register block"] pub const PTR: *const usb0_ep1::Regis...
Rust
0
slice((hdr_size - 4) as usize)?; Ok(Header { major, minor, hdr_size, off_size, }) } } impl WriteBinary<&Self> for Header { type Output = (); fn write<C: WriteContext>(ctxt: &mut C, header: &Header) -> Result<(), WriteError> { U8::wri...
Rust
0
import os from pymongo import MongoClient # Загрузка переменных окружения из .env файла from dotenv import load_dotenv load_dotenv() # Получение данных для подключения из переменных окружения MONGO_USERNAME = os.getenv('MONGO_INITDB_ROOT_USERNAME') MONGO_PASSWORD = os.getenv('MONGO_INITDB_ROOT_PASSWORD') MONGO_HOST ...
Python
1
l[AsyncCallbackManagerForLLMRun] = None, **kwargs: Any, ) -> AsyncIterator[ChatGenerationChunk]: params = self._get_invocation_params(stop=stop, **kwargs) stream = await self.async_client.chat.completions.create( **get_chat_request(messages), stream=True, model=self.model, **para...
Python
1
_objects(map: &Map, room: Rect, objects: &mut Vec<Object>) { let num_monsters = rand::thread_rng().gen_range(0, MAX_ROOM_MONSTERS + 1); for _ in 0..num_monsters { let x = rand::thread_rng().gen_range(room.x1 + 1, room.x2); let y = rand::thread_rng().gen_range(room.y1 + 1, room.y2); let ...
Rust
0
bit."] #[inline(always)] pub fn rdwr_clr_st(&mut self) -> RDWR_CLR_ST_W { RDWR_CLR_ST_W { w: self } } #[doc = "Bit 28 - Clear program operation finished interrupt status bit for EEPROM device 1. 0 leave corresponding bit unchanged. 1 clear corresponding bit."] #[inline(always)] pub fn p...
Rust
0
import discord, re from utils import CYBER_COLOR class Announcement(discord.ui.Modal, title="Annonce"): Title = discord.ui.TextInput(label="Titre", placeholder="Hello World !") Description = discord.ui.TextInput(label="Description", placeholder="<@id> to mention someone", style=discord.TextStyle.long) a...
Python
1
Context, local_var_map: &HashMap<String, u32>, consume_result: bool, wasm_module: &mut WasmModule, wasm_expr: &mut WasmExpr, errors: &mut Vec<Error> ) { let bin_op = bin_op_for_ass_op(ass_op); compile_l_value_pre(l_value, context, local_var_map, wasm_module, wasm_expr, errors); compile_b...
Rust
0
Int b Int @@unique([a, b]) } "#]]; let schema = with_header(input, Provider::SqlServer, &["extendedIndexes"]); let (config, dml) = datamodel::parse_schema(&schema).unwrap(); let rendered = datamodel::render_datamodel_to_string(&dml, Some(&config)); expected.assert_e...
Rust
0
if !neighbor_map.contains_key(&b) { neighbor_map.insert(b.clone(), HashSet::new()); } neighbor_map.get_mut(&a).unwrap().insert(b.clone()); neighbor_map.get_mut(&b).unwrap().insert(a.clone()); } neighbor_map } fn get_visitable_nodes<'a, F>( node: &Node, ne...
Rust
0
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # Written by Hao Du and Houwen Peng # email: haodu8-c@my.cityu.edu.hk and houwen.peng@microsoft.com # This file is to demonstrate how to generate subImagenet. import os data_path = './data' ImageNet_train_path = os.path.join(data_path, 'imagenet...
Python
1
import torch from collections import OrderedDict from argparse import ArgumentParser from transformers import AutoModelForCausalLM, AutoTokenizer from accelerate import dispatch_model from accelerate.utils import get_balanced_memory, infer_auto_device_map def parse_args(): parser = ArgumentParser() parser.add_...
Python
1
> { let mut m = RepeatedField::new(); if blkiodata.is_empty() { return m; } // blkio.time_recursive and blkio.sectors_recursive have no op field. let op = "".to_string(); for d in blkiodata { m.push(BlkioStatsEntry { major: d.major as u64, minor: d.minor ...
Rust
0
value!({ "internal_error": errmsg }), // ) // } // // err @ Error::TokioIOError { .. } => { // let errmsg = format!("{}", err); // FieldError::new( // "Tokio IO Error", // graphql_value!({ "internal_error": e...
Rust
0
Matrix1x3::from_iterator( y.iter() .map(|&x| x + normal.sample(&mut rand::thread_rng()) as Fxx), ); assert_eq!(model.update_bulk(&x, &y), Ok(())); let x0 = Matrix2x1::new(0.5, 1.0); let _yh = model.predict(&x0); } // A wrapper for optimizing a 2-variable linear model through least...
Rust
0
from itertools import permutations, product def f(x, y, z, w): return (not(not(x<=(not w)) and z)) and (not(w<=z)) and (x<=(not z)) arr = [] for a1, a2, a3, a4, a5 in product([1, 0], repeat=5): table = [ (1, 0, a1, 0), (1, 0, a2, a3), (a4, 1, a5, 1) ] if len(set(table)) == le...
Python
1
,255,255,64)); vg.text_align(CENTER|MIDDLE); vg.text(x+h*0.55, y+h*0.55, ICON_SEARCH.as_slice()); vg.font_size(20.0); vg.font_face("sans"); vg.fill_color(rgba(255,255,255,32)); vg.text_align(LEFT|MIDDLE); vg.text(x+h*1.05,y+h*0.5,text); vg.font_size(h*1.3); vg.font_face("icons"); vg.fill_color(rg...
Rust
0
)) } fn rotation_z(radians: f64) -> matrix::Matrix4 { let r = radians; matrix::Matrix4::new(( (r.cos(), -r.sin(), 0.0, 0.0), (r.sin(), r.cos(), 0.0, 0.0), (0.0, 0.0, 1.0, 0.0), (0.0, 0.0, 0.0, 1.0), )) } fn shearing( x_to_y: f64, x_to_z: f64, y_to_x: f64, y_...
Rust
0
} } } } pub fn generate_random_db_and_get_item<'a>( params: &'a Params, item_idx: usize, ) -> (PolyMatrixRaw<'a>, AlignedMemory64) { let mut rng = get_seeded_rng(); let instances = params.instances; let trials = params.n * params.n; let dim0 = 1 << params.db_dim_1; le...
Rust
0
ethod, path, response_class, headers, body=b''): path = normalize_path(path) self._responses[(method, path)] = [(response_class, headers, body)] def register_next_response(self, method, path, response_class, headers, body=b''): resp_key = (method, normalize_pa...
Python
1
il configuration instance""" return EmailConfig() def get_email_template(template_name: str) -> Dict[str, str]: """Get email template by name""" if template_name not in EMAIL_TEMPLATES: raise ValueError(f"Template '{template_name}' not found. Available templates: {list(EMAIL_TEMPLATES.keys())}") ...
Python
1
�离。如果节点已经加入到了Vnew中,则置为-1 v 数组,表示V中节点的访问情况,最开始全部为0,表示未加入到Vnew中,若某节点加入到了Vnew中, 则将其置为-1 Part3. 步骤: 随机选择一个起点,并将其加入到Vnew中。同时,更新此时的lowcost和v 遍历lowcost,寻找lowcost中的最小值min(假设索引为 j ),将与索引 j 相对应的节点加入到Vnew中,更新lowcost[j]和v[j]。 找到最小值 j 后,此时lowcost中的所有节点都要更新,因为此时Vnew节点增加了,V集合中的节点离Vnew集合的距离可能会缩短。 此时已更新完所有的lowcost。 重复步骤2,直到访问了所有的节点。 ...
Rust
0
, ustack_top: usize, kstack_top: usize, _is32: bool, ttbr: usize) -> Self { InitStack { context: ContextData::new(), tf: TrapFrame::new_user_thread(entry_addr, ustack_top), }.push_at(kstack_top, ttbr) } pub unsafe fn new_fork(tf: &TrapFrame, kstack_top: usize, ttbr: usize...
Rust
0
Self(plugin_config) } } impl Default for PluginsConfig { fn default() -> Self { Self::get_plugins_with_default(PluginsConfig::new()) } } impl TryFrom<PluginsConfigFromYaml> for PluginsConfig { type Error = PluginsConfigError; fn try_from(yaml: PluginsConfigFromYaml) -> Result<Self, ...
Rust
0
rt download try: summary = downloader.download_user_videos(args.url, args.max_videos) downloader.print_summary(summary) if summary['success'] and summary['downloaded'] > 0: print(f"\nDownload completed successfully!") print(f"Files saved to: {summary['downloa...
Python
1
0x01) != 0) } } impl W { #[doc = "Bits 0:13 - Content of command 6. For more information, please refer to the register I2C_COMD6_REG in Chapter I²C Controller."] #[inline(always)] pub fn command6(&mut self) -> COMMAND6_W { COMMAND6_W { w: self } } #[doc = "Writes raw bits to the register...
Rust
0
(&format!( "href {} my_ws_uid {}", href, my_ws_uid, )); logmod::log1_str(&"before reconnect"); let ws = websocketcommunication::setup_ws_connection(href, my_ws_uid); websocketcommunication::setup_all_ws_events(&ws,vdom.clon...
Rust
0
=> &cmds.right, Edge::BOTTOM => &cmds.bottom, _ => &None, }; if opts.debug { println!("{:?}: {:?}", edge, cmd); } if cmd.is_none() { return; } // Split to C strings for execvp let s: String = cmd.as_ref().unwrap().to_string(); let split: Vec<&str> = s.split_whitespace().collect(); let vec: Vec<CStr...
Rust
0
pub normals: Option<Handle<Texture>>, pub occlusion: Option<Handle<Texture>>, // PBR factors pub metallic_roughness: Option<Handle<Texture>>, pub metallic: f32, pub roughness: f32, } impl Material { pub fn builder() -> MaterialBuilder { MaterialBuilder::new() } pub fn new...
Rust
0
decode(&mut input).unwrap(); let expected = vec!["abcdefghijklmnopqrstuvwxyz"; size]; assert_eq!(expected, result); } #[test] fn deserialize_list_of_int() { let size = 3; let mut input = Cursor::new( vec![m::TINY_LIST_NIBBLE + size as u8, m::IN...
Rust
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """步驟 4.3 效能監控系統測試腳本 此腳本用於測試效能監控系統的功能,包括: 1. 監控系統初始化測試 2. 效能指標記錄測試 3. 系統資源監控測試 4. 警報系統測試 5. 優化建議測試 Usage: python scripts/test_step4_3_performance_monitoring_system.py """ import sys import os import logging import time import random from datetime import datetime, ti...
Python
1
Execution Domain (included) pub (crate) const MK_MAX_PROCESS_ID : u16 = 0x3FFF ; /// Minimal stack size supported for a Process, given in /// StackType_t units pub (crate) const MK_MIN_SUPPORTED_STACK : u16 = 512 ; // 512 StackType_t units (2KB if 32bit) // Cross-Execution Domain Composite Identifiers (Table 7-13) ...
Rust
0
writeln!(writer, "{}", res)?; } SubCommand::Set(set) => { ffx_config::set( (CONFIG_KEY_DEFAULT, &set.level, &set.build_dir), serde_json::Value::String(set.name.clone()), ) .await? } SubCommand::Unset(unset) => {...
Rust
0
t是否均已计算 node_can_be_processed = lambda node: all(successor in optimistic_cost_table for successor in dag.successors(node)) while visit_queue: node = visit_queue.pop() # 找到后续节点的oct均已计算的队列中的node while node_can_be_processed(node) is not True: try: node2 = visit_...
Python
1
# # Copyright (c) 2023 Airbyte, Inc., all rights reserved. # import sys from airbyte_cdk.entrypoint import launch from source_mailjet_sms import SourceMailjetSms def run(): source = SourceMailjetSms() launch(source, sys.argv[1:])
Python
1
locity(delta) + self.get_next_right_velocity(delta) + self.get_next_left_velocity(delta) + self.get_next_jump_velocity(delta) + self.get_next_sneak_velocity(delta); let next_velocity = self.limit_velocity(next_velocity); let angle = Quaternion::from(Euler...
Rust
0
Container::new( Column::new() .push(Container::new(Text::new("Installed !"))) .push(Container::new( button::primary( &mut self.action_button, bu...
Rust
0
event"] #[inline(always)] pub fn pwr_flash_discharge(&mut self) -> PWR_FLASH_DISCHARGE_W { PWR_FLASH_DISCHARGE_W { w: self } } #[doc = "Bit 5 - Mask for GPIO wakeup event detect"] #[inline(always)] pub fn pwr_iowakeup(&mut self) -> PWR_IOWAKEUP_W { PWR_IOWAKEUP_W { w: self } ...
Rust
0
> { use rspotify::{ clients::{BaseClient, OAuthClient}, scopes, AuthCodeSpotify, Config, Credentials, OAuth, }; let creds = Credentials::from_env().unwrap(); let scopes = scopes!( "user-top-read", "user-read-recently-played", "user-follow-read", "user-lib...
Rust
0
import cython from shapely import measurement from app.models.db.changeset import Changeset from app.models.db.user import user_avatar_url from app.models.proto.shared_pb2 import RenderChangesetsData, SharedBounds class LeafletChangesetMixin: @staticmethod def encode_changesets(changesets: list[Changeset]) -...
Python
1
'a [T] } pub struct DenseBroadcast<'a, T: 'a> { bshape: Vec<usize>, shape: Vec<usize>, tshape: Vec<usize>, buf: &'a [T] } pub struct Zip<S1, S2> { shape: Vec<usize>, spec1: S1, spec2: S2 } pub struct Map<S, F> { shape: Vec<usize>, tshape: Vec<usize>, spec: S, f: F } impl<'a, T: 'a> Dense<'a, T...
Rust
0
h rcx mov rbx, [rcx + {8*3}] ; gp neu setzen mov rax, [rcx + {8*1}] ; Adresse der Funktion nach rax laden jmp rax ; und den PC auf diesen Wert setzen ''' case ('popenv'): code +=f''';;; popenv ...
Python
1
# -*- coding: utf-8 -*- """ const ~~~~~ Implements CONSTS :author: Feei <feei@feei.cn> :homepage: https://github.com/wufeifei/cobra :license: MIT, see LICENSE for more details. :copyright: Copyright (c) 2017 Feei. All rights reserved """ # Match-Mode mm_find_extension = 'find-exten...
Python
1
u32; if inlen == 4 { mem_cost = match parsed_input[1].parse::<u32>() { Ok(val) => val * 1024, Err(err) => return Err(HashError::AtoiConv(err)), }; time_cost = match parsed_input[2].parse::<u32>() { Ok(val) => val, ...
Rust
0
t_posix_error(self): e = OSError(EEXIST, "File already exists", "foo.txt") self.assertEqual(e.errno, EEXIST) self.assertEqual(e.args[0], EEXIST) self.assertEqual(e.strerror, "File already exists") self.assertEqual(e.filename, "foo.txt") if os.name == "nt": sel...
Python
1
ntation which has the following properties ///shape (3, nelems), memory order = fortran/column major. ///This operation is done inplace and does not create a new structure fn to_ang_axis_comp_inplace(&self, ang_axis_comp: &mut AngAxisComp){ let mut ori = ang_axis_comp.ori_view_mut(); let ne...
Rust
0
into() } unsafe extern "C-unwind" fn downgrade(ptr: NonNullConst<T>) -> Weak<T> { let arc = std::sync::Arc::from_raw(ptr.as_ptr()); let weak = std::sync::Arc::downgrade(&arc); forget(arc); weak.into() } } /// A weak reference to a value. #[repr(C)] pub struct Weak<T: ?Sized...
Rust
0
""" Plot colors =========== .. moduleauthor:: Benjamin Ye <GitHub: @bbye98> This module provides functions to select colors for plots. """ import colorsys from typing import Union import matplotlib.colors as mc def adjust_lightness( colors: Union[str, tuple[float], list[Union[str, tuple[float]]]], amount: floa...
Python
1
ounce::Debouncer<matrix::PressedKeys<RCOLS, ROWS>>, debouncer_knob: debounce::Debouncer<bool>, debouncer_ext_l: debounce::Debouncer<bool>, debouncer_ext_r: debounce::Debouncer<bool>, } #[init] fn init(mut cx: init::Context) -> (Shared, Local, init::Monotonics) { cx.device.FL...
Rust
0
indent.push(' '); } indent } pub mod command; pub mod http; /// Functions for parsing a DKIM dns record pub mod dns_record; /// Encode or decode strings with dkim-quoted-printable. pub mod quoted_printable; /// Functions for parsing a DKIM-Signature header pub mod signature_header; /// Common functions...
Rust
0
e::primitives::sample::Sample; use crate::primitives::scalars::scalar::{BaseScalar, Scalar}; use crate::primitives::signal::Signal; use anyhow::Error; use chrono::prelude::*; use plotters::prelude::*; pub struct GraphGenerator; impl GraphGenerator { pub fn draw_signal(self, mut signal: Signal, filepath: &str, id:...
Rust
0
from flask import Flask, request, jsonify from models.task import Task app = Flask(__name__) tasks = [] task_id_control = 1 @app.route('/tasks', methods=['POST']) def create_task(): global task_id_control data = request.get_json() new_task = Task(id=task_id_control, title=data['title'], description=data.g...
Python
1
use typed_html::html; pub const TIMO_GET_TWITTER_COMMAND_FLAG: &str = "get:twitter"; pub struct TimoGetTwitterCommand {} impl TerminalCommand for TimoGetTwitterCommand { fn run(&self) -> Result<String, String> { let body: DOMTree<String> = html!( <div style="margin:0.5rem 0 1rem 2.5rem;displ...
Rust
0
o`](https://crates.io/crates/chrono) //! //! Requires the `chrono` Cargo feature flag. //! //! | Rust type | Postgres | MySQL | SQLite | //! |------------------------------|------------------|------------------|--------------------| //! | `chrono::DateTime<Utc>` | ...
Rust
0
_: ExecutionScope, _: u32, _: fidl::AsyncChannel, ) -> Result<(), zx::Status> { Err(zx::Status::NOT_SUPPORTED) } // `register_watcher` is unsupported so this is a no-op. fn unregister_watcher(self: Arc<Self>, _: usize) {} async fn get_attrs(&self) -> Result<NodeAttribu...
Rust
0
import itertools import json import os import sys source_tag = os.getenv("SOURCE_TAG") target_tag = os.getenv("TARGET_TAG") dev_acr = os.getenv("DEV_ACR") prod_acr = os.getenv("PROD_ACR") dev_aws = os.getenv("DEV_AWS") prod_aws = os.getenv("PROD_AWS") aws_region = os.getenv("AWS_REGION") components = json.loads(os.ge...
Python
1
self) -> Style { Style::default() .fg(self.msg.border_fg) .bg(self.msg.border_bg) } fn get_title_style(&self) -> Style { Style::default() .fg(self.msg.title_fg) .bg(self.msg.title_bg) } } impl <'a>Widget for MessageBox<'a> { fn render(se...
Rust
0
let telemetry = TelemetryValue::Table( maplit::hashmap! { "place".to_string() => TelemetryValue::Table(maplit::hashmap! { "foo".to_string() => 37.into(), "bar".to_string() => 19.into(), }.into()) } .into(), ...
Rust
0
let bet_list = GameGuessHashModule::bet_list(1); let user = bet_list[0].user; let game_id = bet_list[0].game_id; let amount = bet_list[0].amount; let game_mode = bet_list[0].game_mode; // check player ok assert_eq!(user, 2); // check game id ok as...
Rust
0
# python import difflib import re import unicodedata from typing import List, Tuple, Dict, Optional # word_to_id: mevcut vocab sözlüğünüzü buraya verin # Örn: word_to_id = {...} # id_to_word = {v: k for k, v in word_to_id.items()} def _simple_normalize(text: str) -> str: text = unicodedata.normalize("NFKC", text)...
Python
1
import numpy as np # Define the linear equation system A = np.array([[4, -1, 0], [-1, 4, -1], [0, -1, 4]]) # matrix b = np.array([1, 2, 3]) # right-hand side vector # Define the tolerance and maximum number of iterations tol = 1e-6 max_iter = 100 # Initialize the solution vector x = np.zeros_like(b) # Conjugate G...
Python
1
ieval': {'q_prompt': 'Represent the Android question for retrieving answers: ', 'd_prompt': 'Represent the Android answer for retrieval: '}, 'cqadupstack-android': {'q_prompt': 'Represent the Android question for retrieving answers: ', 'd_prompt': 'Represent the Android answer for retrieval: '}, 'CQADupstackWor...
Python
1
i, value, n) { // if let Some((_, k_dist)) = self.find_next_transit(&brightness_vals, j, value, n) { // if j_dist == k_dist { // return true; // } // } // } // } // } // } // false // } } fn parse_stars<'a>(mut iter:...
Rust
0
pub const ERROR_WSMAN_SUBSCRIPTION_LISTENER_NOLONGERVALID: u32 = 2150858905u32; #[doc = "*Required features: `\"Win32_System_RemoteManagement\"`*"] pub const ERROR_WSMAN_SUBSCRIPTION_NO_HEARTBEAT: u32 = 2150858763u32; #[doc = "*Required features: `\"Win32_System_RemoteManagement\"`*"] pub const ERROR_WSMAN_SYSTEM_NOT_F...
Rust
0
: Str previousFundingRate: Num info: Dict[str, Any] interval: Str class LeverageTier: tier: Num symbol: Str currency: Str minNotional: Num maxNotional: Num maintenanceMarginRate: Num maxLeverage: Num info: Dict[str, Any] class LedgerEntry: id: Str info: Any ti...
Python
1
), dropping: false }; let me = Slab(Arc::new(inner)); net.register_local_slab(&me); let weak_self = me.weak(); // TODO: this should really be a thread pool, or get_memo should be changed to be nonblocking somhow *me.memoref_dispatch_thread.write().unwrap() ...
Rust
0
import os import sys import json import requests import pyttsx3 from datetime import datetime import random import shutil VERSION = "1.2.1" MEMORY_FILE = "memory.json" UPDATE_URL = "https://raw.githubusercontent.com/Dinesh488/MyHackTools/main/main.py" try: engine = pyttsx3.init() engine.setProperty('rate', 17...
Python
1
); ParentContainer { ion_type, is_exhausted: false, } } /// Returns the IonType associated with this container. The IonType will always be `List`, /// `SExpression`, or `Struct`. pub fn ion_type(&self) -> IonType { self.ion_type } /// If...
Rust
0
r'../data/metropolis/GF5_AHSI_E121.45_N31.31_20191228_008714_L10000071208_VN.geotiff'}, } # land_types = ['village', 'mountain_village', 'forest', 'desert', 'township', 'forest_village', 'snowfield', 'metropolis'] patch_size = [9, 15, 23, 31] land_types = ['snowfield', 'metropolis'] # patch_size = ...
Python
1
gle_env = gym.make("CartPole-v0") obs_space = single_env.observation_space act_space = single_env.action_space ev = RolloutWorker( env_creator=lambda _: MultiAgentCartPole({"num_agents": 2}), policy_spec={ "p0": (ModelBasedPolicy, obs_space, act_space, {})...
Python
1
replicate(txn, source).await, } } async fn write_ahead(&self, txn_id: &TxnId) { match self { Self::Block(chain) => chain.write_ahead(txn_id).await, Self::Sync(chain) => chain.write_ahead(txn_id).await, } } } #[async_trait] impl Transact for Chain { async...
Rust
0
{ fn map_address(&self, address: u32) -> &[u8] { match address { // why doesnt rust allow exclusive pattern matching :despair: // https://github.com/rust-lang/rust/issues/37854 0x00000000..=0x01FFFFFF => println!("Read from TCM address {}", address), 0x020000...
Rust
0
, pyty_sbvalue, pyfn_evaluate_in_frame, pyfn_modules_loaded, pyfn_format_exception, }); Ok(py_interface) } impl PythonInterface for PythonInterfaceImpl { fn evaluate(&self, expr: &str, is_simple_expr: bool, context: &SBExecutionContext) -> Result<SBValue, String> { l...
Rust
0
import setuptools with open("README.md", "r") as fh: longdescription = fh.read() with open('igv_notebook/VERSION') as version_file: version = version_file.read().strip() setuptools.setup(name='igv-notebook', packages=['igv_notebook'], version=version, descr...
Python
1
#!/usr/bin/python # takes: genop.tab from erlang/otp # returns list of dicts{name:str(), arity:int(), opcode:int()} import string MIN_OPCODE = 1 MAX_OPCODE = 158 def load_opcodes(): global ops ops = [] for ln in file("genop.tab"): ln = ln.strip() if not ln: continue if ln.startswi...
Python
1
D'] + "#######"+ predicted[index] + "\n") output = classification_report(test[index]['CAPECName'], predicted, output_dict = True) probs = clf.predict_proba(test[index].iloc[:, 4:(numOfColumns)]) if top_n_class == 2: auc.append(roc_auc_score( test[in...
Python
1
edges::Edges, faces::{Face, Faces}, }, Shape, }, math::Point, }; impl Shape for fj::Sweep { fn bounding_volume(&self) -> AABB { let mut aabb = self.shape.bounding_volume(); aabb.maxs.z = self.length; aabb } fn faces(&self, tolerance:...
Rust
0
# Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn]. # Return the array in the form [x1,y1,x2,y2,...,xn,yn]. # Example 1: # Input: nums = [2,5,1,3,4,7], n = 3 # Output: [2,3,5,4,1,7] # Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7]. cl...
Python
1