text
string
label_name
string
labels
int64
detailed (major, minor, patch) version supported by the platform. // CL_VERSION_3_0 pub fn numeric_version(&self) -> Result<cl_version, cl_int> { Ok(platform::get_platform_info( self.id, platform::PlatformInfo::CL_PLATFORM_NUMERIC_VERSION, )? .to_uint()) } ...
Rust
0
_event_in(0.25 * 1.0, "pause_me", sprite=sprites["main_src"], sweep=sweep) sweep.bus.on("pause_me", lambda **kw: on_main_src_paused(**kw)) sweep.bus.on("sweep_completed", lambda **kw: on_main_src_compile_completed()) sweep.bus.on("sweep_completed", lambda **kw: sprites["main_src"].layers.pop(Layer.COMPILING...
Python
1
oves.iter().for_each(|(old_x, old_y)| { if fold_dir == FoldDir::X { let new_x = 2 * fold_val - old_x; self.dots.remove(&(*old_x, *old_y)); self.dots.insert((new_x, *old_y)); } else if fold_dir == FoldDir::Y { let new_y = 2 * fold_va...
Rust
0
import os import sys from shutil import which from subprocess import Popen, PIPE, call def shell(args, msg=None): # Fix Windows error if passed a string proc = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE) out, err = proc.communicate(input=msg) exitcode = proc.returncode if exitcode!=0: ...
Python
1
words = [item["keyword"] for item in tool_response["keywords"]] response = "推荐关键词:" + ",".join(words) + "。" else: assert False except IndexError as e: response = "抱歉,未检索...
Python
1
let plugins_dir: String = env .get_string(plugins_dir) .expect("Couldn't get plugins dir") .into(); debug!("----------- START ------------"); let mut engine: MutexGuard<LightorosEngine> = env.get_rust_field(obj, "enginePtr").unwrap(); debug!("----------- CONFIG: {} ------------...
Rust
0
t (*captures).0 }; let text = unsafe { slice::from_raw_parts(haystack, len) }; if it.last_end > text.len() { return false; } let (s, e) = match re.read_captures_at(slots, text, it.last_end) { None => return false, Some((s, e)) => (s, e), }; ...
Rust
0
(): beam = sk.Beam(photon_energy=PHOTON_ENERGY, focus_radius=DIM, focus_shape="circle", fluence=FLUENCE) assert np.isclose(beam.get_photons_per_pulse(), FLUENCE) assert np.isclose(beam.get_photons_per_pulse_per_area(), FLUENCE / (np.pi * DIM**2)) def test_file(): ...
Python
1
, query_status.task_id) celery.app.control.revoke(query_status.task_id) logger.info("Revoked task id %s", query_status.task_id) except QueryNotFoundError: # Continue, to attempt to cancel the query even if it's not a task pass if dequeue_only: message = "Only tr...
Python
1
let mut physics: smallvec::SmallVec<[Physics; 4]> = smallvec![ Physics { position: smallvec![206, 446, 84], velocity: smallvec![-19, 29, -23] }, Physics { position: smallvec![-748, 129, 280], velocity: smallvec![-27, -48...
Rust
0
on(self, fb_native): """ Copy this FrameBuffer into a native framebuffer (e.g. a picodvi.Framebuffer), then attach it to the display. """ # fb_native must implement .pixel(x,y,color) or expose a buffer protocol for y in range(self.size.y): for x in range(self....
Python
1
o possible to write compile-time initialization functions that suit your specific needs // with "complex" logic taking advantage of various methods you might typically expect to only be // available at runtime. Note that depending on what you're doing exactly, and whether or not you // want to directly *return* a Stati...
Rust
0
#coding:utf8 import efinance as ef import pandas as pd from autoxd.pinyin import stock_pinyin3 as jx def get_5min_kline(stock_code, start_date, end_date): df = ef.stock.get_quote_history(stock_code, klt=5, start_date=start_date, end_date=end_date) return df def run(): stock_code = jx.DSFS第四范式hk start_...
Python
1
; /// } /// /// assert_eq!(vec.len(), 128); /// ``` /// pub fn push(&mut self, value: T) -> &mut T { let (len, capacity) = (self.len(), self.capacity()); if len == capacity { if let Err(TryReserveErrorKind::AllocError { layout }) = self .grow(next_capacity::<T>(capacity)) .map_...
Rust
0
let mut cloned = self.clone(); cloned.types.extend(other.types.iter().cloned()); cloned.types.sort_unstable(); cloned.types.dedup(); cloned } pub fn unify_single(&self, typed: Type) -> Self { let mut cloned = self.clone(); if let Err(idx) = cloned.types.bin...
Rust
0
s(args.test_file_cache): # file_path = args.test_file_cache # read_from_cache = True # logger.info(f'[CorefDataset][get_dataset] args.max_seq_length {args.max_seq_length}') # if read_from_cache: # logger.info(f"[READ FROM CACHE ] Reading dataset from {file_path}") # with open(f...
Python
1
s_DeltaChunk>>( "deltaChunks", |m: &ContentDeltaChunks| { &m.deltaChunks }, |m: &mut ContentDeltaChunks| { &mut m.deltaChunks }, )); fields.push(::protobuf::reflect::accessor::make_option_accessor::<_, ::protobuf::types::ProtobufTypeEnum<EContentDe...
Rust
0
{}", self.energy_used); } fn amphipod_positions(&self, amphipod_index: usize) -> u16 { match amphipod_index { 0 | 1 => self.amphipods_position_a, 2 | 3 => self.amphipods_position_b, 4 | 5 => self.amphipods_position_c, 6 | 7 => self.amphipods_position_d, ...
Rust
0
hild is not None: load(child, prefix + name + '.') load(model, prefix=prefix) warn_missing_keys = [] ignore_missing_keys = [] for key in missing_keys: keep_flag = True for ignore_key in ignore_missing.split('|'): if ignore_key in key: keep_fl...
Python
1
_arch = "arm", target_feature(enable = "v7"))] #[cfg_attr(test, assert_instr(nop))] pub unsafe fn vreinterpretq_u8_s8(a: int8x16_t) -> uint8x16_t { transmute(a) } /// Unsigned shift right #[inline] #[target_feature(enable = "neon")] #[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))] #[cfg_attr(all(tes...
Rust
0
GLenum, pixels: *const GLvoid, ); } extern "C" { pub fn glTexSubImage2D( target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type_: GLenum, pixels: *const GLvoid, ); } ...
Rust
0
ddressMultiDevice: VkBool32, pub vulkanMemoryModel: VkBool32, pub vulkanMemoryModelDeviceScope: VkBool32, pub vulkanMemoryModelAvailabilityVisibilityChains: VkBool32, pub shaderOutputViewportIndex: VkBool32, pub shaderOutputLayer: VkBool32, pub subgroupBroadcastDynamicId: VkBool32, } #[repr(C)] ...
Rust
0
warning([f"Smallest area is larger than the highest price in the table. Please input no more than {max_value}"]) continue else: while True: max_area_input = get_int_input("Enter the biggest area (or 'back' to FILTER MENU): ") ...
Python
1
qr.v = self.v return qr # # # def tr(self): # """Return an equivalent rotation matrix. # # @rtype: 4x4 homogeneous transform # @return: equivalent rotation matrix # """ # # return T.r2t( self.r() ) # # def r(self): # """Re...
Python
1
.name("storage-thread".to_owned()) .spawn(move || Self::run_worker(log, persistent_storage, responder)) .unwrap(); Self { worker_channel: requester, } } } impl StorageService for StorageServiceDefault { #[inline(always)] fn request_send( &...
Rust
0
let dir = tempfile::tempdir()?; let yaml = File::create(dir.path().join("Pulumi.yaml"))?; yaml.sync_all()?; let rendered = ModuleRenderer::new("pulumi") .path(dir.path()) .logical_path(dir.path()) .config(toml::toml! { [pulumi] ...
Rust
0
# -*- coding: utf-8 -*- # # Copyright 2020 Google LLC. 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 requir...
Python
1
data.lines().collect(); let mut cfg = Config::default(); for line in lines { let parts: Vec<&str> = line.split("=").collect(); if parts.len() == 2 { let name = parts[0].trim(); let value_str = parts[1].trim(); let value_i32_r = va...
Rust
0
import tkinter as tk from tkinter import ttk import json # Leer el modelo de datos desde JSON with open("modelo.json", "r", encoding="utf-8") as f: modelo = json.load(f) # Obtener campos de clientes campos = modelo["clientes"] # Crear ventana principal root = tk.Tk() root.title("Gestión de Clientes") root.geomet...
Python
1
} impl EnumDefinition { /// Create a new instance of Enum Definition. pub fn new(name: String) -> Self { Self { name, description: None, values: Vec::new(), directives: Vec::new(), extend: false, } } /// Set the enum type as a...
Rust
0
# GENERATED BY INSIGHT-PLUGIN - DO NOT EDIT import insightconnect_plugin_runtime import json class Component: DESCRIPTION = "Update the scan engine/scan engine pool associated with a site" class Input: ENGINE_ID = "engine_id" SITE_ID = "site_id" class Output: LINKS = "links" class UpdateSiteScan...
Python
1
[s] * (1 - self.supply_capacity_variability), f"Supply_{s}_MaxZoneCapacityRobust" ) start_time = time.time() model.optimize() end_time = time.time() return model.getStatus(), end_time - start_time, model.getObjVal() if __name__ == '__main__': seed = 42...
Python
1
import pinocchio as pin import numpy as np import simple import time from sim_utils import ( addSystemCollisionPairs, SimulationArgs, createVisualizer, setupSimulatorFromArgs, plotContactSolver, subSample, runMujocoXML, printSimulationPerfStats, ) args = SimulationArgs().parse_args() mo...
Python
1
tTargets.append( [actualTarget, type] ) tExtra = [a.get() for a in tConst.getWeightAliasList()] targets = [] weights = [] modes = [] for (rT, mode), weight in zip(rTargets, rExtra): # Point/Orient const will be in both lists so alter the mdoe ...
Python
1
from tabulate import tabulate def log_config_options(opt, logger): logger.debug("Config Options") table = [ ["Manifest Mode", opt.manifest_mode], ["Experimental Mode", opt.experimental_mode], ["Nagios Output Mode", opt.nagios_mode], ["Ubuntu Vulnerability DB File Path", opt.db_...
Python
1
don't know if this exists in any particular Lisp, // but it allows me to reach into our local environment through an invoke LexicalEvalFn, PersistentList(PersistentList), PersistentVector(PersistentVector), PersistentListMap(PersistentListMap), Condition(std::string::String), // Macro bod...
Rust
0
{ return None; } else { return Some(Err(e.into())); } }; if self.tmp_record.is_secondary() || self.tmp_record.is_supplementary() { p = false; } // Get original read sequence from rec...
Rust
0
n = 0x8004102c, wbemErrInvalidCimType = 0x8004102d, wbemErrInvalidMethod = 0x8004102e, wbemErrInvalidMethodParameters = 0x8004102f, wbemErrSystemProperty = 0x80041030, wbemErrInvalidProperty = 0x80041031, wbemErrCallCancelled = 0x80041032, wbemErrShuttingDown = 0x80041033, wbemErrPropaga...
Rust
0
1 sec and a half ///assert_eq!(Nanos.convert(duration), 1_500_000_000); ///assert_eq!(Micros.convert(duration), 1_500_000); ///assert_eq!(Millis.convert(duration), 1_500); ///assert_eq!(Secs.convert(duration), 1); /// ``` #[inline] pub fn convert(self, duration: Duration) -> u64 { ma...
Rust
0
""" " Methods for fueltech groups """ from opennem.core.loader import load_data from opennem.schema.fueltech_group import FueltechGroupSchema class FueltechGroupException(Exception): ... def _load_fueltech_groups() -> list[FueltechGroupSchema]: fixture = load_data("fueltech_groups.json", from_fixture=True) ...
Python
1
await self._analyze_test_coverage() # 6. Dependency analizi await self._analyze_dependencies() # 7. API analizi await self._analyze_api_endpoints() # 8. Database analizi await self._analyze_database() # 9. Frontend analiz...
Python
1
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed May 29 07:16:22 2024 @author: era """ """ This file have functionality to put text and shapes on videos """ import cv2 import datetime #Open The vidoe file cap = cv2.VideoCapture("/home/era/Desktop/Work/Opencv_projects/Images/videos/donkey.mp4") #...
Python
1
nfiguration /// can violate the constraint slightly. The joint translation is zero /// when the local anchor points coincide in world space. Using local /// anchors and a local axis helps when saving and loading a game. #[derive(Clone)] pub struct B2prismaticJointDef<D: UserDataType> { pub base: B2jointDef<D>, ...
Rust
0
/// Creates a new `Supercow` which owns the given value. /// /// This can create a `Supercow` with a `'static` lifetime. pub fn owned(inner: OWNED) -> Self where OWNED : SafeBorrow<BORROWED> { // Safety: The invalid `ptr` does not escape; either the function sets // it properly, or pan...
Rust
0
placementDeferred(reg, v as i8)), None => Err(OperandParseError::OutOfBytes), } } 14 => { match get_u16_from_stream(bytes) { Some(v) => Ok(OperandMode::WordDisplacementDeferred(reg, v as i16)), ...
Rust
0
table.add_row(key, str(value)) console.print() console.print(table) env_app = AsyncTyper() app.add_typer(env_app, name="env") async def _list_env(provider: Provider): async with configuration.use_platform_client(): variables = await provider.list_variables() with create_table(Column("...
Python
1
AudioPlayer, audio_table: &'a AudioTable, player_coord: GameCoord, config: &'a Config, } impl<'a> EffectContext<'a> { fn next_frame(&mut self) { *self.screen_shake = self.screen_shake.and_then(|screen_shake| screen_shake.next()); } fn play_audio(&self, audio: Audio, volume: f32) { ...
Rust
0
# while True: # try: # x = int(input("What is x? ")) # except ValueError: # print("x not valid num") # else: # break # def get_user_int(): # while True: # try: # x = int(input("What is x? ")) # return x # except ValueError: # ...
Python
1
import flet as ft # criar espaçamentos verticais personalizados def main(page: ft.Page): page.window.always_on_top = True page.padding = ft.padding.all(10) # page.bgcolor = ft.Colors.BLUE_GREY_100 # page.scroll = ft.ScrollMode.AUTO page.add(ft.Row( expand=True, spacing=0, ...
Python
1
#!/usr/bin/env python3 import socket import sys from datetime import datetime def scan_port(target, port): try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(1) result = sock.connect_ex((target, port)) sock.close() return result == 0 except: ...
Python
1
from __future__ import annotations from dataclasses import dataclass from typing import Optional PROMOTION_PIECES = {"q", "r", "b", "n"} @dataclass(frozen=True) class Move: """Engine-internal move type. - Squares are 0..63 (a1 = 0, h8 = 63) or use algebraic via helpers. - Promotion uses lowercase piec...
Python
1
fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { self } fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor { Self::descriptor_static() } fn new() -> CBroadcast_GetClipDetails_Request { CBroadcast_GetClipDetails_Reques...
Rust
0
::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pll_sys_ss...
Rust
0
to the 'hops' field. pub fn hops_mut(&mut self) -> &mut u8 { &mut self.as_mut()[3] } /// Sets the 'xid' field. pub fn set_xid(&mut self, xid: u32) { NetworkEndian::write_u32(&mut self.as_mut()[4..], xid) } /// Sets the 'secs' field. pub fn set_secs(&mut self, secs: u16) { ...
Rust
0
: ptr::null::<vsb>() as *mut vsb, vsl: ptr::null::<vsl_log>() as *mut vsl_log, vcl: ptr::null::<VCL_VCL>() as VCL_VCL, ws: std::ptr::null_mut::<ws>(), sp: ptr::null::<sess>() as *mut sess, req: ptr::null::<req>() as *mut req, ...
Rust
0
e, ready: bool, } #[derive(Debug, Clone, PartialEq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] struct Edge { target_vertex: usize, left_face: usize, next_edge: usize, previous_edge: usize, twin_edge: usize, ready: bool, } #[derive(Debug, Clone, PartialEq)] #[cfg_attr(f...
Rust
0
use std::fs::File; use std::io::Write; use std::path::PathBuf; use file_utils::hash_file; use file_exclude::FileExclude; #[test] pub fn test_hash_file_none() { let file_path = String::from("/tmp/test"); let hash1 = { let mut file = File::create(file_path.clone(...
Rust
0
<'_, R>, context: &Self::Context) -> Result<Self::Output> { Ok(Self { name: ConstantIndex::read(reader, context)?, descriptor: ConstantIndex::read(reader, context)?, }) } } #[derive(Debug, Clone, PartialEq)] pub struct InvokeDynamicRef { pub bootstrap: MethodIndex, p...
Rust
0
<gio::File>, save_mode: SaveMode, cancellable: Option<&impl IsA<gio::Cancellable>>, callback: P, ); fn save_to_file_future( &self, file: &(impl IsA<gio::File> + Clone + 'static), save_mode: SaveMode, ) -> Pin<Box_<dyn std::future::Future<Output = Result<(), glib::Error>> + 'static>>; #...
Rust
0
et_all_users_for_scanning() if users: await self.bot.send_message( chat_id, f"🔍 Found {len(users)} users in database to scan..." ) for user in users: # Skip if user is an admin if user.id in admin_i...
Python
1
from sentence_extractor import extract_answer_with_citation from flask import jsonify def baseline(query,results): contexts = [] best_answer = None best_similarity = -1 for res in results: answer, similarity, citation = extract_answer_with_citation(query, res) contexts.append({ ...
Python
1
def solution(brown, yellow): # ❶ 격자의 총 개수 (갈색 격자 + 노란 격자) total_size = brown + yellow # ❷ 세로 길이의 범위는 3부터 (갈색 격자 + 노란 격자)의 제곱근 for vertical in range(3, int(total_size**0.5) + 1): # ❸ 사각형 구성이 되는지 확인 if total_size % vertical == 0: horizontal = (int)(total_size / vertical) # ❹ 사각형의 가로 길이 # ❺ 카펫...
Python
1
// println!("ex class : {}",(*meta.unwrap()).borrow().java_name()); { let method = frame.method_ptr(); let class = (*object).borrow().class(); } if !Self::find_and_goto_exception_handler(frame, object.clone()) { Self::handle_uncaught_exception(thr...
Rust
0
speedx = np.load('../data/speedx_arr_big.npz')['arr_0'] targets = np.load('../data/targets_arr_big.npz')['arr_0'] nb_epoch = 40 mini_epoch = 5 num_steps = int(nb_epoch/mini_epoch) for step in range(0,num_steps): h = M.fit([speedx, imgs], {'steer_out':targets[:,0]}, batch_size = 32, nb_epoch=min...
Python
1
::new(func); let expected = expected_from_file("test_fib10_bb.txt"); assert_eq!(expected.trim_end(), format!("{:#?}", cfg.basic_blocks)); } #[test] fn fn_call_test() { let ir = ir_build( r#" fn foo() -> i32 { let a = 3 + 4; a } fn bar(c: i32) { ...
Rust
0
or<filename>src/bin/alg/alg/trie.rs /* 79. 单词搜索 给定一个二维网格和一个单词,找出该单词是否存在于网格中。 单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。 示例: board = [ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ] 给定 word = "ABCCED", 返回 true 给定 word = "SEE", 返回 true 给定 word = "ABCB", 返回 false 提示: boa...
Rust
0
deps" => self.avoid_dev_deps = parse_empty(k, v)?, "minimal-versions" => self.minimal_versions = parse_empty(k, v)?, "package-features" => self.package_features = parse_empty(k, v)?, "advanced-env" => self.advanced_env = parse_empty(k, v)?, "config-profile" => self.config...
Rust
0
, true); let x = WINDOW_WIDTH / 2.0; let mut y = 300.0; let w = 750.0; let h = 100.0; let padding = 25.0; let texts = ["Beginner", "Intermediate", "Expert"]; for (i, text) in texts.iter().enumerate() { vk_util::push_rect_color( cmd, Rect::center_extent((x, y +...
Rust
0
elude::*; pub trait WeightToFeeConverter { fn convert_weight_to_fee(location: &MultiLocation, weight: Weight) -> Option<u128>; } pub trait FixedConversionRateProvider { fn get_fee_per_second(location: &MultiLocation) -> Option<u128>; } pub trait AssetProcessor<AssetId, Metadata> { fn pre_register(id: Option<Asset...
Rust
0
from dynatrace import Dynatrace from datetime import datetime from dynatrace.environment_v2.audit_logs import AuditLogEntry, EventType, Category, UserType from dynatrace.pagination import PaginatedList def test_list(dt: Dynatrace): audit_logs = dt.audit_logs.list() assert isinstance(audit_logs, PaginatedList...
Python
1
s", because calling them uses up the iterator. One example is the `sum` method, which takes ownership of the iterator and iterates through the items by repeatedly calling `next`. As it does this it adds each item into a running total and returns the the total when the iteration is complete *...
Rust
0
# Copyright 2018, OpenCensus Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in w...
Python
1
Prompt.ask("分类 (可选,如: HighEndDuty)", default="") if category: condition.category = category # 执行搜索 console.print(f"\n[yellow]使用过滤器 '{filter_name}' 搜索中...[/yellow]") if self.monitor is None: await self.initialize() # Check...
Python
1
} #[derive(Clone)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] /// A partial device descriptor pub struct DeviceDescriptor { /// The frame counter associated with this device pub frame_counter: u32, /// Whether this device is allowed to override the minimum security level pub exempt: bool, } ...
Rust
0
iter() { let insert_string_encoded_value = format!( "INSERT INTO ks.{} (id, val) VALUES (0, {})", type_name, test ); session .query(insert_string_encoded_value, &[]) .await .unwrap(); let insert_bound_value = format!("INSERT IN...
Rust
0
session_state.current_file_context: with st.expander("📎 Current File", expanded=True): st.write(f"File: {st.session_state.current_file_context['name']}") if st.session_state.file_summary: st.write("Summary:") st.write(st.session_state....
Python
1
ty, inputs, start_to_close_timeout=dt.timedelta(minutes=1), retry_policy=temporalio.common.RetryPolicy(maximum_attempts=3), ) total_conditions = count_result.count if total_conditions == 0: workflow_logger.warning("No conditions found") ...
Python
1
ast(out.reborrow())?; self.group_by.walk_ast(out.reborrow())?; self.order.walk_ast(out.reborrow())?; self.locking.walk_ast(out.reborrow())?; Ok(()) } } impl<Col, Expr> InsertValues<Col::Table, Fb> for ColumnInsertValue<Col, Expr> where Col: Column, Expr: Expression<SqlType =...
Rust
0
df::Hkdf<sha2::Sha256>, prk_3e2m : Vec<u8>, } impl PartyI<Msg3Sender> { /// Returns the bytes of the third message, as well as the OSCORE master /// secret and the OSCORE master salt. pub fn generate_message_3( self, ) -> Result<(PartyI<Msg4ReceiveVerify>,Vec<u8>), OwnError> { //f...
Rust
0
): fail_count.append(index) marcos[marco_categoria][ "Estado" ] = f"{Fore.RED}NO CUMPLE{Style.RESET_ALL}" elif finding.status == "PASS" and i...
Python
1
rt_eq!(sched3.queued_count(), 1); } #[test] fn join_returns() { let sched1 = TestScheduler::new(); let sched2 = TestScheduler::new(); let sched3 = TestScheduler::new(); let a = Task::from_fn(&sched1, || {1i32} ); let b = Task::from_fn(&sched2, || {2i32} ); ...
Rust
0
rcp_message_t, ) -> ffi::apt_bool_t { let channel_data = &mut *((*channel).method_obj as *mut Arc<Mutex<Channel>>); let channel_data_weak = Arc::downgrade(channel_data); let request = SendPtr::new(request); channel_data .lock() .unwrap() .runtime .spawn_blocking(move || ...
Rust
0
def merge_purge(s1, s2): merged = sorted(s1+s2, key = lambda x:(x[0],-x[1])) result = [] max_profit = -1 for profit, weight in merged: if profit > max_profit: result.append((profit, weight)) max_profit = profit return result def trace_back(s,p,w,m,n,x): for i in ...
Python
1
#problem #Find the total number of customers from each country in the table (customer ID, customer name, country) using group by( python interface through MYSQL). #solution #creating table table through python interface import mysql.connector con=mysql.connector.connect(host="localhost", ...
Python
1
eam(ServiceTitanStream): """Define scheduler performance stream.""" name = "scheduler_performance" primary_keys: t.ClassVar[list[str]] = ["id"] parent_stream_type = SchedulersStream ignore_parent_replication_key = True schema = th.PropertiesList( th.Property("id", th.StringType), ...
Python
1
} fn mouse_interaction( &self, tree: &Tree, layout: Layout<'_>, cursor_position: Point, viewport: &Rectangle, renderer: &Renderer, ) -> mouse::Interaction { pane_grid::mouse_interaction( tree.state.downcast_ref(), self.state, ...
Rust
0
ormat.apply_operation(self, operation) } /// Reverses the most recently applied operation. #[allow(unused_variables)] pub fn undo(&mut self) -> Result<()> { self.format.undo(self) } /// Reverses the most recently applied undo operation. #[allow(unused_variables)] pub fn redo(&mut self) -> Result<()> { sel...
Rust
0
} } #[inline(always)] fn zero() -> Self::Instant { Self::Instant::from_ticks(0) } } <reponame>xrayzh/MoonZoon use zoon::{named_color::*, *}; fn root() -> impl Element { Column::new() .s(Padding::all(20)) .s(Width::fill().max(500)) .s(Align::center()) ...
Rust
0
::Storage; use super::Encoder; use super::Targets; pub struct Trace { x:u32, z:u32, angle:f32, color:[f32;4], mesh_id:TraceMeshID } impl Trace { pub fn new( x:u32, z:u32, angle:f32, color:[f32;4], mesh_id:TraceMeshID ) -> Self { Trace { ...
Rust
0
with(|s| self.sdl_video_system.gl_get_proc_address(s) as _); self.sdl_video_system.gl_set_swap_interval(SwapInterval::Immediate); self.immediate_gui = Some(T::new( &self.sdl_video_system, self.debug_window.as_ref().unwrap(), self.storage.clone(), ...
Rust
0
_v1.mock_group_responses.append(GROUP_RESPONSE) mock_api_v1.mock_scene_responses.append(SCENE_RESPONSE) await setup_bridge(hass, mock_bridge_v1, mock_config_entry_v1) await setup_bridge(hass, mock_bridge_v2, mock_config_entry_v2) with patch.object( hue.services, "hue_activate_scene_v2", return...
Python
1
def calculate_tax(names): try: new_dict = {} for name in names: a = [0, 1000, 10000, 20200, 30750, 50000] b = [1000, 10000, 20200, 30750, 50000, 100000] p = [0, .1, .15, .2, .25, .3] amount = names[name] tax = 0 i = 0 ...
Python
1
:box_free::<dyn alloc::boxed::FnBox<(), Output = ()>>" ); } #[test] fn demangle_const_generics_preview() { // NOTE(eddyb) this was hand-written, before rustc had working // const generics support (but the mangling format did include them). t_nohash_type!( "INtC8a...
Rust
0
pub fn dirpol(&mut self) -> DIRPOL_W { DIRPOL_W { w: self } } } <gh_stars>10-100 use sheeit_storage::{CoreDocument, EvalErrorVal, Value}; use std::cmp::Ordering; /// A trait that has the same API as PartialOrd, just used for evaluating values. // TODO: Determine if we want this to be inherent to Value...
Rust
0
#!/usr/bin/env python # coding:utf-8 """ @author: nivic ybyang7 @license: Apache Licence @file: api_server @time: 2024/02/02 @contact: ybyang7@iflytek.com @site: @software: PyCharm # code is far away from bugs with the god animal protecting I love animals. They taste delicious. ┏┓ ┏┓ ...
Python
1
unreachable!(), } return; } ("report", Some(arg)) => { match arg.value_of("sheet_or_session") { Some("session") => sheet.report_last_session(), Some("sheet") => { let timestamp: Option<u64> = ...
Rust
0
han 1Hz pub fn start_reading(&mut self) -> Result<(), Error<E>> { self.reg_reset_bits(Register::CTRL_REG1, ONE_SHOT).map_err(Error::I2c)?; self.reg_set_bits(Register::CTRL_REG1, ONE_SHOT).map_err(Error::I2c)?; //We are now waiting for data self.mode = Mode::TakingReading; Ok(()) } /// Check the...
Rust
0
api::WINDOW_BUFFER_SIZE_RECORD; unsafe { ws = irec.WindowBufferSizeEvent(); } Event::Resize( ws.dwSize.X as i32, ws.dwSize.Y as i32, ) }, winapi::MOUSE_EVENT => { let ms: &winapi::MOUSE_EVENT_...
Rust
0
ValueQuery>; #[pallet::storage] pub(crate) type Spaces<T: Config> = StorageMap<_, Twox64Concat, u32, Space<T::AccountId, T::BlockNumber>>; #[pallet::event] #[pallet::metadata(T::AccountId = "AccountId")] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event<T: Config> { } // Errors info...
Rust
0
self.pcie_bridge = LitePCIeWishboneBridge(self.pcie_endpoint, base_address = self.mem_map["csr"]) self.bus.add_master(master=self.pcie_bridge.wishbone) # DMA0 self.pcie_dma0 = LitePCIeDMA(self.pcie_phy, self.pcie_endpoint, with_buffering = Tru...
Python
1