text
string
label_name
string
labels
int64
versing for a particular app, use that namespace ns = current_app elif ns not in app_list: # The name isn't shared by one of the instances (i.e., the default) # so just pick the first instance as the default. ns = app_list[0...
Python
1
alueError as e: msg = str(e) # Check that the message matches expected format assert msg == "ConfigurationProfile Validator Type must be one of: JSON_SCHEMA, LAMBDA" # Property 5: Test with special characters and edge cases @given(st.one_of( st.text(alphabet="!@#$%^&*()[]{}|\\:;\"'<>,.?/",...
Python
1
: u64, pub tx_packets: u64, pub tx_dropped: u64, pub rx_packets: u64, pub tx_errors: u64, pub tx_bytes: u64, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct MemoryStats { pub max_usage: u64, pub usage: u64, pub failcnt: u64, pub limit: u64, pub stats: MemoryStat, } ...
Rust
0
import subprocess import json def update(json_file_path, type, new): # 读取JSON文件内容 with open(json_file_path, 'r', encoding='utf-8') as file: data = json.load(file) # 加载JSON数据到Python字典中 # 修改的值 data[type] = new # 将更新后的数据写回到JSON文件中 with open(json_file_path, 'w', encoding='utf-8') as file:...
Python
1
ckT> { metrics: Option<SubscribersGauge>, next_id: SubscriberId, wildcard_listeners: FnvHashSet<SubscriberId>, listeners: HashMap<StorageKey, FnvHashSet<SubscriberId>>, child_listeners: HashMap< StorageKey, (HashMap<StorageKey, FnvHashSet<SubscriberId>>, FnvHashSet<SubscriberId>), >, sinks: FnvHashMap< Sub...
Rust
0
// struct to yaml serde_yaml::to_string(&WixConfig::default()).expect("Error: Could not convert wix config to yaml.") } }; // convert yaml to struct wix_config = serde_yaml::from_str(&config_yaml).expect("Error: Could not convert yaml to wix config."...
Rust
0
./bin/node-template/octopus-pallets/lpos/src/weights.rs // --template // ./.maintain/frame-weight-template.hbs #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// We...
Rust
0
GS: HashMap<&'static str, &'static str> = [ ("i16", "i16"), ("u16", "u16"), ("i32", "i32"), ("u8", "u8"), ("u32", "u32"), ("bool", "bool"), ("lv_opa_t", "lv_opa_t"), ("lv_anim_enable_t", "lv_anim_enable_t"), ("lv_arc_mode_t", "lv_arc_mode_t"), ...
Rust
0
empty() { res.push(GeneralizedItem::Bytes(bytes.clone())); bytes.clear(); } res.push(GeneralizedItem::Gap); } Some(b) => { bytes.push(*b); } } }...
Rust
0
# # This file is part of the Chemical Data Processing Toolkit # # Copyright (C) Thomas Seidel <thomas.seidel@univie.ac.at> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # versi...
Python
1
ame>aclysma/puffin //! An [imgui-rs](https://crates.io/crates/imgui-rs) interface for [`puffin`]. //! //! Usage: //! //! ``` ignored //! fn main() { //! puffin::set_scopes_on(true); // you may want to control this with a flag //! let mut puffin_ui = puffin_imgui::ProfilerUi::default(); //! //! // game loop ...
Rust
0
Err(why) => println!("Error while loading web feed: {}", why), //! } //! ``` match get_feed(&url) { Ok(value) => { let file: String = str::replace(value.title.as_str(), "/", "-"); Ok(StreamRSS{url: url.clone(), name: file.clone(), items: value.items.clone(), object: value, last_upd...
Rust
0
import requests headers = { "sec-ch-ua-platform": "\"Windows\"", "Referer": "https://whucourses.cn/search/", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0", "Accept": "application/json, text/plain, */*", ...
Python
1
::new(UdpConn::new( SocketAddr::from_str("0.0.0.0:1234")?, None, obs, )); conn_map.insert(Arc::clone(&conn_in)).await?; let addr = SocketAddr::from_str("192.168.0.1:1234")?; let conn_out = conn_map.find(&addr).await; assert!(conn_out.is_some(), "should succeed"); if let...
Rust
0
1, 2), (-1, 0), (-1, 1), (0, -2), (-1, -2), ( 1, 0), ( 1, -1), (0, 2), ( 1, 2), ]; #[rustfmt::skip] const SRSS_RIGHT: [XY; 16] = [ (-1, 0), (-1, 1), (0, -2), (-1, -2), (-1, 0), (-1, -1), (0, 2), (-1, 2), ( 1, 0), ( 1, 1), (0, -2), ( 1, -2), ( 1, 0), ( 1, -1), (0, 2), ( 1, 2), ]; fn srss_left(dir...
Rust
0
""" Metrc API URLs | Cannlytics Module Copyright (c) 2021-2022 Cannlytics and Cannlytics Contributors Authors: Keegan Skeate <https://github.com/keeganskeate> Created: 11/5/2021 Updated: 11/5/2021 License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE> """ METRC_API_BASE_URL = 'https://api-%s.metrc.com'...
Python
1
self.assertRaises(TypeError, f, 2, LenOnly()) def test_cmp_err(self): seq = [CmpErr(), CmpErr(), CmpErr()] for f in (self.module.heapify, self.module.heappop): self.assertRaises(ZeroDivisionError, f, seq) for f in (self.module.heappush, self.module.heapreplace): ...
Python
1
", action="store_true", help="If it's OSS build, add a fake _PyImport_FrozenModules", ) parser.add_argument( "--symbol-name", "--symbol_name", help="The name of the frozen module array symbol to generate", default="_PyImport_FrozenModules_torch", ) args =...
Python
1
import pytest import student def does_function_exist(function_name): return function_name in dir(student) def if_function_exists(function_name): return pytest.mark.skipif(not does_function_exist(function_name), reason=f'{function_name} not found in student module') test_data = [ ([], []), ([None],...
Python
1
"\"{}\"", &set.iter() .map(|h| h.to_hex().to_string()) .collect::<Vec<String>>() .join("\", \""), ) } fn diff_set(set_a: BlakeHashSet, set_b: &BlakeHashSet) -> BlakeHashSet { set_a.difference(set_b).into_iter().copied().collect() } /// Accepts optional comma-separat...
Rust
0
process_subscription(i.0, i.1) { sr_primitives::print(e); } } } pub fn subscribe(origin, recipient: T::AccountId, period: T::BlockNumber, blog_id: T::Hash) -> Result { let sender = ensure_signed(origin)?; // pay initial price let subscription_info = Self::subscription_info() <balances::Modu...
Rust
0
All); is_special = true; } if let Some(x) = get_key(map, "clear_scopes", |x| x.as_i64()).ok() { context.clear_scopes = Some(ClearAmount::TopN(x as usize)); is_special = true; } if !is_special { if let Some(x)...
Rust
0
"link"][0] == "Some": link_data = organic_data["link"][1] result_item = { "title": link_data.get("title", ""), "url": link_data.get("url", [None, {}])[1].get("url", ""), "position": item.g...
Python
1
.type_().is_a(return_type.into()), "Signal has a return type of {} but handler returned {}", Type::from(return_type), handler_return.type_() ); let res = (accumulator.1)(&SignalInvocationHint(*ihint), return_accu, handler_return) ....
Rust
0
(), Self::Call(r) => r.returndata(), } } /// Returns the gas used for the transaction. pub fn gas_used(&self) -> Gas { match self { Self::Deploy(r) => r.gas_used, Self::Spawn(r) => r.gas_used, Self::Call(r) => r.gas_used, } } ...
Rust
0
use core::fmt::Write; write!(s, "{:<08}", m.score).unwrap(); putstr(win, buf, 10, 0, 7, &s.s); if m.high < m.score { m.high = m.score; putstr(win, buf, 27, 0, 7, &s.s); } ...
Rust
0
Ok(level) => notifiers.push(NotificationType::Log(level)), Err(e) => warn!( "could not parse specified log notifier level string ({}): {}", log_level, e ), } } info!("{} notifiers", notifiers.len()); Notifier ...
Rust
0
import numpy as np import torch import matplotlib.pyplot as plt from imu_test import Model as VQ_VAE_Model from train_ae import set_seed, resize_data, CONFIG # Reusing from train script # Set random seed set_seed(CONFIG["random_seed"]) # Load dataset root_path = "/home/lala/Downloads/" dataset = "oppo_33hz_w10_o5" X...
Python
1
ue, p2: Value) -> Value { match (p1, p2) { (Int(i), Int(j)) => Bool(i <= j), (Float(i), Int(j)) => Bool(i <= j as f64), (Int(i), Float(j)) => Bool((i as f64) <= j), (Float(i), Float(j)) => Bool(i <= j), _ => fail!(format!("Can't leq")) } } fn geq_val(p1: Value, p2: Value) -> Value { match (p...
Rust
0
ontext[n])] temp_rt = _ddm_trial(v_t[n], theta[2], theta[3], theta[4]) # while np.abs(temp_rt) < min_rt or np.abs(temp_rt) > max_rt: # temp_rt = _ddm_trial(v_t[n], theta[2], theta[3], theta[4]) rt[n] = temp_rt return rt[:, np.newaxis] def standard_levy_process(theta, ...
Python
1
═", "╬", "╢"); writeln!(&mut stdout, "{}", first).unwrap(); for line in 1..=self.metrics.get_nb_line() { write!(&mut stdout, "║").unwrap(); for column in 1..=self.metrics.get_nb_column() { let pos = self.acc.coordconverter.coord_to_pos(line, column); ...
Rust
0
::Error> { o_cleanup_thread_handle.as_ref().map_or_else( || remove_or_compress_too_old_logfiles_impl(cleanup_config, file_spec), |cleanup_thread_handle| { cleanup_thread_handle .sender .send(MessageToCleanupThread::Act) .ok(); ...
Rust
0
# -*- coding: utf-8 -*- # Scrapy settings for JDSpider project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # http://doc.scrapy.org/en/latest/topics/settings.html # http://scrapy.readthedocs.org/en/lates...
Python
1
"custom"] # adjust lr according to batch size cfg.num_nodes = omegaconf_select(cfg, "num_nodes", 1) scale_factor = cfg.optimizer.batch_size * len(cfg.devices) * cfg.num_nodes / 256 cfg.optimizer.lr = cfg.optimizer.lr * scale_factor if cfg.data.val_path is not None: assert not OmegaConf.is_...
Python
1
::new(), OPEN_FLAG_DIRECTORY | OPEN_RIGHT_READABLE | OPEN_RIGHT_WRITABLE, MODE_TYPE_DIRECTORY, Path::empty(), ServerEnd::new(dir_server_end.into_channel()), ); let inputs = vec!["hello, ", "world!"]; let expected_output = "hello, world!"; ...
Rust
0
"policies": _unmanaged_policies } ) # Example of unmanaged policy payload: # [ # { # "switch": [ # { # "ip": '<ip_address>', ...
Python
1
# Copyright (C) 2016-2024 RhodeCode GmbH # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License, version 3 # (only), as published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WIT...
Python
1
import requests import pandas as pd import time def geocode_address(df): lat = [] lon = [] confidence = [] # OpenRouteService API key mykey = 'open-route-service-key' headers = {'Accept': 'application/json'} for i in df.index: try: # Build URL with structured parameter...
Python
1
middle_content = ''' String the_json_data_that_honors_yingshaoxo = """{}"""; '''.format(content_string).strip() self._io.write(file_path=generated_file_path, content=template1 + "\n\n" + middle_content + "\n\n" + template2) if __name__ == "__main__": """ from pprint import ppri...
Python
1
# -*- coding: utf-8 -*- # Copyright (c) 2020 Kumagai group. import pytest from pydefect.chem_pot_diag.chem_pot_diag import CompositionEnergy, \ CompositionEnergies from pydefect.cli.vasp.make_composition_energies_from_mp import \ make_composition_energies_from_mp, remove_higher_energy_comp from pymatgen.core ...
Python
1
ith '_' will be excluded. # # When 1: all 'magic' names (``__foo__``) will be excluded. # # When 0: nothing will be excluded. #c.IPCompleter.omit__names = 2 #------------------------------------------------------------------------------ # ScriptMagics(Magics) configuration #--------------------------------------...
Python
1
axis] = umap_df clusterer.fit(umap_mat) Y = clusterer.single_linkage_tree_.to_numpy() Z = hier.dendrogram(Y, no_plot=True) Z = hier.dendrogram(Y, no_plot=True) inst_clust_order = Z['leaves'] return inst_clust_order, Y def sort_rank_nodes(net, rowcol, rank_type): import numpy as np from operato...
Python
1
long time. let eta_matrices_nnz = self.basis_solver.eta_matrices.coeff_cols.nnz(); if eta_matrices_nnz < self.basis_solver.lu_factors.nnz() { self.basis_solver .push_eta_matrix(&self.col_coeffs, pivot_elem.row, pivot_coeff); } else { self.basis_solver ...
Rust
0
ispatcherBuilder, Read, System, SystemData, World, Write}, network::simulation::{tcp::TcpNetworkBundle, NetworkSimulationEvent, TransportResource}, prelude::*, shrev::{EventChannel, ReaderId}, utils::application_root_dir, Result, }; use log::{error, info}; use std::net::TcpListener; fn main() -> Re...
Rust
0
CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (strategy_id) REFERENCES strategies (id) ON DELETE CASCADE ); CREATE TABLE IF NOT EXISTS strategy_performance ( id INTEGER PRIMARY KEY AUTOINCREMENT, strategy_id INTEGER NOT NULL, total_trades INTEGER DEFAULT 0, winn...
Python
1
from pathlib import Path # Root of the repository project_root: Path = Path(__file__).parent.parent benchmarks_root: Path = project_root / "benchmarks" data_root: Path = project_root / "data" outputs_root: Path = project_root / "outputs" # Hugging Face cache directory cache_dir: Path = project_root / ".cache" # Plac...
Python
1
retain(|(rt, to)| tr.1 != *rt || tr.2 != *to); } pub fn move_intersection( &mut self, id: OriginalIntersection, point: Pt2D, ) -> Option<Vec<OriginalRoad>> { self.intersections.get_mut(&id).unwrap().point = point; // Update all the roads. let mut fixed = Vec...
Rust
0
break_in_true = body.true_branch.does_contain_break if body.true_branch else False break_in_false = body.false_branch.does_contain_break if body.false_branch else False if break_in_true ^ break_in_false: if break_in_true: body.switch_branches() return True ...
Python
1
ện thuật toán so khớp nguồn for file_name, chunks in chunks_and_sources.items(): file_score = 0 # Điểm số cho mỗi file content_matched = False # Đánh dấu xem có nội dung khớp quan trọng không exact_sentences_found = 0 # Số câu khớp hoàn toàn ...
Python
1
ace: O(1) def find_set(self, node): while node != self.parent[node]: # path compression self.parent[node] = self.parent[self.parent[node]] node = self.parent[node] return node # Time: O(1) | Space: O(1) def union_set(self, node1, node2): root1...
Python
1
, vec![ FunderField::FunderId.to_string(), FunderField::FunderName.to_string(), FunderField::FunderDoi.to_string(), FunderField::UpdatedAt.to_string(), ], FunderOrderBy, FunderField, } <filename>protocol/src/types/game/interactive/zaap/mod.rs use protocol_derive::{Decode,...
Rust
0
)); canvas.set_draw_color(Color::RGB(pixel, pixel, pixel)); canvas.fill_rect(sprite).unwrap(); } } canvas.present(); } } pub(crate) fn draw_sprite(&mut self, x: usize, y: usize, n: usize) -> bool { s...
Rust
0
class Glass: capacity = 250 def __init__(self) -> None: self.content = 0 def fill(self, ml) -> str: if self.content + ml > Glass.capacity: return f"Cannot add {ml} ml" self.content += ml return f"Glass filled with {ml} ml" def empty(self) -> str: ...
Python
1
from ...utils import get_graphql_content PRODUCT_CHANNEL_LISTING_UPDATE_MUTATION = """ mutation UpdateProductVariantChannelListing( $productVariantId: ID!, $input: [ProductVariantChannelListingAddInput!]! ) { productVariantChannelListingUpdate(id: $productVariantId, input: $input) { errors { field ...
Python
1
# TYPE CONVERSION a1,b1 = 10,20.0 c1 = a1 + b1 print(c1) # In the above code snippet, the value of a is 10 and the value of b is 20.0. The value of c is the sum of a and b. The value of a is an integer and the value of b is a float. The value of c is the sum of an integer and a float. The value of c is 30.0. The type ...
Python
1
sert result == sorted([ 'ceph', ]) def test_install_only_one_component(self): self.args.install_osd = True result = install.detect_components(self.args, self.distro) assert result == ['ceph-osd'] def test_install_a_couple_of_components(self): self.args.insta...
Python
1
from trame.app import get_server from trame.ui.html import DivLayout from trame.widgets import trame # ----------------------------------------------------------------------------- # Trame app # ----------------------------------------------------------------------------- server = get_server() state = server.state s...
Python
1
(SessionWindow, on_delete=models.CASCADE, help_text="会话") event = models.ForeignKey(Event, on_delete=models.CASCADE, help_text="事件") assigned_at = models.DateTimeField(auto_now_add=True, help_text="分配时间") class Meta: db_table = 'alerts_session_event_relation' unique_together = ['session', '...
Python
1
iorDepth = -7, NegativeRefDepth = -8, NotProcessed = -9 } <filename>src/melee.rs //! Processes pending melee combat events use super::{CombatStats, Name, SufferDamage, WantsToMelee}; use specs::prelude::*; pub struct MeleeCombatSystem {} impl<'a> System<'a> for MeleeCombatSystem { type SystemData = ( ...
Rust
0
ng two dicts using "file_name" field to match their entries. Args: detection_dicts (list[dict]): lists of dicts for object detection or instance segmentation. sem_seg_dicts (list[dict]): lists of dicts for semantic segmentation. Returns: list[dict] (one per input image): Each dict cont...
Python
1
) + inst.imm.unwrap()); }, OP_SLTI => { cpu.regs.write(inst.rd, (cpu.regs.read(inst.rs1) < inst.imm.unwrap()) as i32); }, OP_SLTIU => { cpu.regs.write(inst.rd, ((cpu.regs.read(inst.rs1) as u32) < inst.imm.unwrap() as u32) as i32...
Rust
0
import sys import math import logging from features.feature import Feature class BackwardPacketLengthStd(Feature): def __init__(self, name): super().__init__(name, "flow") # Please implement the following function def extract_feature(self, window): pkts = window.get_packets("backward") ...
Python
1
self.variant(REGION20_A::DISABLED) } #[doc = "Protection enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(REGION20_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc...
Rust
0
from discord import app_commands from discord.ext import commands import discord import asyncio class Dom(commands.Cog): def __init__(self, bot): self.bot = bot self.model = bot.model self.generation_config = bot.generation_config self.chats = bot.chats self.client = bot.cli...
Python
1
d_platform_init_display(base_ea) pc_ea = find_putchar(base_ea, base_end) # # just to be sure # if br_flag == false: # if pc_ea != ida_idaapi.BADADDR and mv_ea == ida_idaapi.BADADDR: # # this is a SecureROM image # segm = ida_segment.getseg(base_ea) # if seg...
Python
1
s.is_human_readable() { serde::Serialize::serialize(v, s) } else { let mut seq = s.serialize_seq(Some(v.len()))?; for pair in v.iter() { seq.serialize_element(&pair)?; } seq.end() } } pub fn deserialize<'de, D, T, U>(d:...
Rust
0
`` /// # fn main() -> Result<(), themis::Error> { /// use themis::secure_cell::SecureCell; /// /// let cell = SecureCell::with_key(b"password")?.seal(); /// /// let encrypted = cell.encrypt_with_context(b"byte string", b"context")?; /// let decrypted = cell.decrypt_with_context(&encrypted, b...
Rust
0
&MAGIC_NUMBER)?)?; stream.write_all(&bincode::serialize(&RESPONSE_HDR_SIZE)?)?; stream.write_all(&bincode::serialize(&self)?)?; Ok(()) } /// Deserialise a response header from the given stream. /// /// # Errors /// - if either the magic number or the header size are inval...
Rust
0
m32f3xx_hal::{self as hal, pac, prelude::*}; const CYCLES_PER_SECOND: u32 = 8_000_000; const CYCLES_PER_MS: u32 = 8_000; #[entry] fn main() -> ! { let cp = cortex_m::Peripherals::take().unwrap(); let mut itm = cp.ITM; let dp = pac::Peripherals::take().unwrap(); let mut flash = dp.FLASH.constrain(); ...
Rust
0
(not(feature = "doc"))] pub const INTERRUPTS: [crate::Interrupt; 1] = [crate::interrupt::CAN3]; /// The interrupts associated with CAN3 /// /// Note: the values are invalid for a documentation build. #[cfg(feature = "doc")] pub const INTERRUPTS: [crate::Interrupt; 0] = []; } /// Raw pointer to...
Rust
0
ator pool allocator_clone: CommandAllocator, free_allocators: Weak<Mutex<Vec<CommandAllocator>>>, } pub struct Pipeline { pipeline_state: wrappers::PipelineState, root_signature: wrappers::RootSignature, } // Right now, each descriptor set gets its own heap, but we'll move // to a more sophisticated a...
Rust
0
member to rejoin /// when rebalancing the group. #[fluvio_kf(min_version = 1, ignorable)] pub rebalance_timeout_ms: i32, /// The member id assigned by the group coordinator. pub member_id: String, /// The unique name the for class of protocols implemented by the group we want to join. pub...
Rust
0
onst u8).add(1252usize) as *const crate::Reg<sbkey_key_code13::SBKEY_KEY_CODE13_SPEC>) } } #[doc = "0x4e4 - ."] #[inline(always)] pub fn sbkey_body11(&self) -> &crate::Reg<sbkey_body11::SBKEY_BODY11_SPEC> { unsafe { &*(((self as *const Self) as *const u8).add(...
Rust
0
from django.db.models import Q from rest_framework.filters import BaseFilterBackend class OwnedByOrganisation(BaseFilterBackend): def filter_queryset(self, request, queryset, view): org_id = request.parser_context['kwargs'].get('pk') return queryset.filter(organisation_id=org_id) class OwnedByGr...
Python
1
contents.trim())?; Ok(uuid) } #[cfg(target_os = "windows")] pub async fn get_os_machine_id() -> Result<Uuid> { use winreg::enums::{HKEY_LOCAL_MACHINE, KEY_READ, KEY_WOW64_64KEY}; use winreg::RegKey; let key: &str = "SOFTWARE\\Microsoft\\Cryptography"; let hklm = RegKey::predef(HKEY_LOCAL_MACHINE)...
Rust
0
ner AsyncRead. #[inline] pub fn get_mut(&mut self) -> &mut R { &mut self.inner } /// Returns the inner AsyncRead, consuming this structure. #[inline] pub fn into_inner(self) -> R { self.inner } } impl<R: Read> Read for LimitedAsyncRead<R> { #[inline] fn read(&mut se...
Rust
0
et location_list = LocationListBuilder::new() .with_locations(filtered_locations) .build() .map_err(|err| { ApplyError::InvalidTransaction(format!("Cannot build location list: {:?}", err)) })?; let serialized = match locati...
Rust
0
Formatter.html#RFC_1123_DATE_TIME) /// /// Required feature: java-time-format-DateTimeFormatter #[cfg(any(feature = "all", feature = "java-time-format-DateTimeFormatter"))] pub fn RFC_1123_DATE_TIME<'env>(env: &'env __jni_bindgen::Env) -> __jni_bindgen::std::option::Option<__jni_bindgen:...
Rust
0
t_flat_list() processed = set(a.artisthash for a in SimilarArtistTable.get_all()) # filter out artists that already have similar artists using generator def artist_generator(): for artist in storeArtists: if artist.artisthash in processed: yield a...
Python
1
tf16... // So I decided to simply... print an error message and call it a day. // <.< DirsError::ParseError(String::from("invalid utf-16")) } } use self::DirsError::*; impl ErrorTrait for DirsError { fn description(&self) -> &str { match self { &HomeMissing => "unabl...
Rust
0
(img_path)) characters = sub_images[:3] cards = sub_images[3:] current_character_feats = [get_image_feature(character) for character in characters] current_card_feats = [get_image_feature(card) for card in cards] character_feats, card_feats = init_img_feat() res = do_one_img( character_...
Python
1
value:", maxRank print " Some of unexpected specialties having high PageRank values:" for specialty, cnt in specialtyCount.items(): if specialty in falsePositives: continue _, descr = `Specialty($specialty, descr)`.next() print " %s:%d"%(descr, cnt) # We print top ...
Python
1
g: 0, b: (255 - position * 3), } } } } #[entry] fn main() -> ! { let mut peripherals = Peripherals::take().unwrap(); let core = CorePeripherals::take().unwrap(); let mut clocks = GenericClockController::with_internal_32kosc( peripherals.GCLK, ...
Rust
0
fiat_secp256k1_scalar_cmovznz_u64(&mut x199, x198, x189, x181); let mut x200: u64 = 0; fiat_secp256k1_scalar_cmovznz_u64(&mut x200, x198, x191, x183); let mut x201: u64 = 0; fiat_secp256k1_scalar_cmovznz_u64(&mut x201, x198, x193, x185); let mut x202: u64 = 0; fiat_secp256k1_scalar_cmovznz_u...
Rust
0
transaction / unsigned payload (raw) // // By default unsigned transactions are disallowed, so we need to whitelist this case // by writing `UnsignedValidator`. Note that it's EXTREMELY important to carefuly // implement unsigned validation logic, as any mistakes can lead to opening DoS or spam // attac...
Rust
0
from __future__ import annotations # Standard Library Imports from copy import deepcopy from datetime import datetime # Third Party Imports import pytest from pydantic import ValidationError # RESONAATE Imports from resonaate.scenario.config.time_config import DEFAULT_TIME_STEP, TimeConfig TEST_START = datetime(202...
Python
1
itHub webhooks. */ #[endpoint { method = POST, path = "/print", }] #[instrument] #[inline] async fn listen_print_requests(_rqctx: Arc<RequestContext>, body_param: TypedBody<String>) -> Result<HttpResponseAccepted<String>, HttpError> { let url = body_param.into_inner(); let printer = get_rollo_printer();...
Rust
0
steps train_losses.append(loss.item()) loss.backward() global_step += 1 if global_step % args.gradient_accumulation_steps == 0: optimizer.step() optimizer.zero_grad() model.eval() metrics = model_eval(i_epoch, val_loader, ...
Python
1
} #[test] #[should_panic] fn new_tcp_connect_loopback_test() { let mut buf: [u8; 20] = [0; 20]; new_tcp_connect(&mut buf, &"127.0.0.1:8080".parse().unwrap()).unwrap(); } #[test] fn new_tcp_connect_ok_test() { let mut buf: [u8; 12] = [0; 12]; let r = new_tcp_...
Rust
0
''' map() ''' def fun(arg): return f"{arg} passed to fun()" if __name__ == "__main__": # another way to create a list. # range() returns a list: res = map(fun, list(range(1, 101))) # output each element of result list: for i in res: print(i)
Python
1
3192], [0.1632, 0.0423, 0.2478]] ).to(torch_device) self.assertTrue(torch.allclose(outputs.target_pred_boxes[0, :3, :3], expected_slice_boxes, atol=1e-4)) @slow @require_torch_gpu def test_inference_one_shot_object_detection_fp16(self): model_name = "google/owlvit-base-patch32" ...
Python
1
from docx import Document from hanlp_restful import HanLPClient import os from tqdm import tqdm def read_docx(file_path): doc = Document(file_path) full_text = [] for para in doc.paragraphs: full_text.append(para.text) return ''.join(full_text) ################################################...
Python
1
Power>, /// new validator addresses or whose bonded amount changed in the current block pub power_changed_in_block: BTreeMap<StakedStateAddress, TendermintVotePower>, /// new nodes proposed in the block pub new_nodes_in_block: BTreeMap<StakedStateAddress, CouncilNode>, /// proxy for processing trans...
Rust
0
Err(anyhow!("Module \"{}\" unavailable.", specifier)), ), } } impl Graph { /// Create a new instance of a graph, ready to have modules loaded it. /// /// The argument `handler` is an instance of a structure that implements the /// `SpecifierHandler` trait. /// pub fn new( handler: Arc<Mutex<dyn ...
Rust
0
wnloading checkpoint from `{url}` ...') subprocess.call(['wget', '--quiet', '-O', checkpoint_path, url]) print(f' Finish downloading checkpoint.') checkpoint = torch.load(checkpoint_path, map_location='cpu') if 'generator_smooth' in checkpoint: generator.load_state_dict(checkpoint['gene...
Python
1
error occured!") print("Some error occured!") def open_AI(prompt): print("On it, Sir...") speak("On it, Sir...", rate=185) file_name = openAI.chat_with_gpt(prompt) # dir_ = f"{os.getcwd()}\{file_loc}" speak(f"Prompt in file: {prompt}", rate=160) os.system(fr"notepad.exe {file_name}...
Python
1
", "100011101011", ]; <filename>runtime/src/xpay_diner.rs use support::{StorageValue, StorageMap, dispatch::Result,ensure}; use super::xpay::Trait; use super::xpay; use runtime_primitives::traits::{CheckedAdd}; use rstd::vec::Vec; pub fn insert_into_diner<T:Trait>(item_id:T::ItemId, diner: u32)->Result{ if <xpay:...
Rust
0
e itertools::Itertools; use num_traits::sign::Signed; fn main() -> Result<(), Box<dyn std::error::Error>> { let data = generate_random_data(); let down_sampled = down_sample(&data[..]); let root = BitMapBackend::new("plotters-doc-data/errorbar.png", (1024, 768)).into_drawing_area(); root.fil...
Rust
0
from __future__ import annotations import pytomography import torch class PETTOFMeta(): """Class for PET time of flight metadata. Contains information such as spatial binning and resolution. Args: num_bins (int): Number of bins used to discretize time of flight data tof_range (floa...
Python
1
from collections import deque with open("puzzle_input.txt") as puzzle_input: puzzle_input = puzzle_input.read() deck_1, deck_2 = puzzle_input.split("\n\n") deck_1, deck_2 = deck_1.split("\n")[1:], deck_2.split("\n")[1:] # Deque is preferred over list in the cases where we need quicker append # and pop operations...
Python
1