text
string
label_name
string
labels
int64
_mut); generate_enum_accessors(cx).subst(st, cx, &bnd) }).collect(); let enum_variants = fields.iter().map(|x| { let enum_field = mk().enum_field(x.ty.clone()); mk().variant(x.ident.expect("expected field name to be populated")...
Rust
0
927 # MOV operation ref_32343 = ref_22872 # MOV operation ref_32461 = ref_32343 # MOV operation ref_32475 = (0x3F & ref_32461) # AND operation ref_32618 = ref_32475 # MOV operation ref_32632 = ((ref_32618 << (0x4 & 0x3F)) & 0xFFFFFFFFFFFFFFFF) # SHL operation ref_32783 = ref_31000 # MOV operation ref_32787 = ref_32632 ...
Python
1
h(0).unwrap(); } else { ones_place = num.to_string().chars().nth(1).unwrap(); } let ones = match ones_place { '1' => "one", '2' => "two", '3' => "three", '4' => "four", '5' => "five", '6' => "six",...
Rust
0
where T: IntoIterator<Item = Rule>, { self.static_rules.extend(iter); self } /// Replace the dynamic rules with the given [Rule]s. pub fn replace_dynamic_rules<T>(mut self, iter: T) -> Self where T: IntoIterator<Item = Rule>, { self.dynamic_rules.clear();...
Rust
0
lambda x: x["factor"].corr(x["noisy1"]) ) pfs2_series = all_data.groupby(level="datetime").apply( lambda x: x["factor"].corr(x["noisy2"]) ) factor_mat = ( data .reset_index() ...
Python
1
#if std_z is None: # std_z = self.std_z(np.vstack(xtrajs)) # compute std of sample trajs in z-space #sample_z_z, sample_z_x, sample_z_energy_z, sample_z_energy_x = self.generate_x(std_z, nsample=nsample) # compute generated energies energies_sample_x_low = [se[np.where(se < max_energy)[0]] for se ...
Python
1
"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Write '1' to enable interrupt for ENDEPIN\\[2\\] event\n\nValue on reset: 0"] #[derive(Clone, Copy, ...
Rust
0
rdy().bit() } // Select PLL as clock source. rcc.cfgr.modify(|_, w| w.sw().pll()); block_until! { rcc.cfgr.read().sws().is_pll() } } <reponame>Nazariglez/nae<filename>crates/notan_egui/src/lib.rs mod config; mod context; mod extension; mod input; mod plugin; pub use config::EguiConfig; pub use context::Eg...
Rust
0
import sys, copy input = sys.stdin.readline # n = 밭의 크기 n*n, m = 나무의 개수, k = 재배년수 n, m, k = map(int, input().split()) a = [list(map(int, input().split())) for _ in range(n)] field = copy.deepcopy(a) # M개의 줄에는 상도가 심은 나무의 정보를 나타내는 세 정수 x, y, z가 주어진다. 처음 두 개의 정수는 나무의 위치 (x, y)를 의미하고, 마지막 정수는 그 나무의 나이를 의미한다. trees = [list...
Python
1
Options for SystemTraits { /// const MTIME_PTR: usize = 0x1001_1000; /// const MTIMECMP_PTR: usize = 0x1001_1000; /// const FREQUENCY: u64 = 1_000_000; /// } /// /// const fn configure_app(b: &mut r3_kernel::Cfg<SystemTraits>) -> Objects { /// SystemTraits::configure_timer(b); /// /* ... */ /// } //...
Rust
0
"type": "json_schema", "json_schema": { "name": "binary_decision_tree_question", "strict": True, "schema": self._response_schema } }, temperature=self._temperature, max_tokens=self._m...
Python
1
::ARCHIVE), is_device: is_flag_set(flags, standard_info_flags::DEVICE), is_normal: is_flag_set(flags, standard_info_flags::NORMAL), is_temporary: is_flag_set(flags, standard_info_flags::TEMPORARY), is_sparse: is_flag_set(flags, standard_info_flags::SPARSE), is...
Rust
0
class Solution: def maxHeight(self, cuboids: List[List[int]]) -> int: for cuboid in cuboids: cuboid.sort() # Ensure each cuboid's dimensions are sorted (l <= w <= h) # Step 2: Sort cuboids by dimensions to ensure stacking order is valid cuboids.sort() # Sorting ensures...
Python
1
kSAI for $SAIX { type Rec = rec::$Rec; /// Current kernel clock - A fn sai_a_ker_ck(prec: &Self::Rec, clocks: &CoreClocks) -> Option<Hertz> { match prec.$get_mux_A() { Val(rec::$AccessA::PLL1_Q) => clocks.pll1_q_ck(), ...
Rust
0
k_field_name, m2m.opposing_type); // Add @relation directive that specifies the local array to hold the FKs. let relation_directive = match m2m.relation_name { Some(name) => format!(r#"@relation(name: "{}", fields: [{}])"#, name, fk_field_name), None => format!(r#"@relation(fiel...
Rust
0
tats_messages_received: u64, } /// Options for the CLUSTER FAILOVER command. #[derive(Clone, Debug, Eq, PartialEq)] pub enum ClusterFailoverFlag { Force, Takeover, } impl ClusterFailoverFlag { pub(crate) fn to_str(&self) -> Str { utils::static_str(match *self { ClusterFailoverFlag::Force => "FORCE", ...
Rust
0
qux", "FooCorp", "BarApp"); println!("ProjectDirs::from(\"qux\", \"FooCorp\", \"BarApp\")\n{:?}", proj_dirs); let proj_dirs = ::ProjectDirs::from("qux.zoo", "Foo Corp", "Bar-App"); println!("ProjectDirs::from(\"qux.zoo\", \"Foo Corp\", \"Bar-App\")\n{:?}", proj_dirs); let proj_dirs = ::P...
Rust
0
[book_id], "id": book_id} # update book by id by Librarian @app.put("/books/{book_id}", response_model=Book) async def update_book(book_id: int, book: Book, role: str = Query(...)): if role != "LIBRARIAN": raise HTTPException(status_code=403, detail="Only librarians can update books") if book_id not ...
Python
1
: &mut Libraries) -> Result<()> { let new_libs = self.shard_acc.read_account()?.libraries(); if new_libs.root() != self.orig_libs.root() { new_libs.scan_diff(&self.orig_libs, |key: UInt256, old, new| { let old = old.unwrap_or_default(); let new = new.unwrap_or...
Rust
0
let salt_len = match salt_len { Some(val) if val == salt_len2 => salt_len2, Some(_) => bail!("The salt length is mismatched: {}", salt_len2), None => salt_len2, }; (input, hash, mgf1_hash, salt_l...
Rust
0
#print "helixManip: initializePlugin for helixManip called" mplugin = OpenMayaMPx.MFnPlugin(mobject) try: mplugin.registerNode(nodeName, helixManipId, helixManipCreator, helixManipInitialize, OpenMayaMPx.MPxNode.kManipContainer) except: print("helixManip: Failed to r...
Python
1
""" Tests for the watch.py module in the SortMate package. """ import os import pytest from unittest.mock import MagicMock, patch from sortmate.watch import start_watch, stop_watch @patch.dict(os.environ, { "GOOGLE_CLOUD_PROJECT": "test-project", "PUBSUB_TOPIC": "test-topic" }) def test_start_watch(): "...
Python
1
# -*- coding: utf-8 -*- # Copyright 2025 Google LLC # # 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...
Python
1
3, 3) backtesting_end = datetime(2023, 3, 10) results = StockOco.backtest( YahooDataBacktesting, backtesting_start, backtesting_end, be...
Python
1
} #[doc = "Writes raw bits to the register."] pub unsafe fn bits(&mut self, bits: u8) -> &mut Self { self.0.bits(bits); self } } #[doc = "Real Time Clock Seconds\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`re...
Rust
0
def recognize_activity(keypoints): NOSE = 0 LEFT_WRIST = 9 RIGHT_WRIST = 10 LEFT_HIP = 11 RIGHT_HIP = 12 LEFT_KNEE = 13 RIGHT_KNEE = 14 LEFT_ANKLE = 15 RIGHT_ANKLE = 16 if len(keypoints) < 17: return "Unknown" nose = keypoints[NOSE] left_wrist = keypoints[LEFT_W...
Python
1
const IFLA_VF_RATE: int = 6; pub const IFLA_VF_RSS_QUERY_EN: int = 7; pub const IFLA_VF_STATS: int = 8; pub const IFLA_VF_TRUST: int = 9; pub const IFLA_VF_IB_NODE_GUID: int = 10; pub const IFLA_VF_IB_PORT_GUID: int = 11; pub const IFLA_VF_VLAN_LIST: int = 12; pub const IFLA_VF_VLAN_INFO_UNSPEC: int = 0; pub const IFL...
Rust
0
"[+] ", 2, 1) + "HTTP Options:" print ' %-27s' % "Always serving EXE" + (enabled if settings.Config.Serve_Always else disabled) print ' %-27s' % "Serving EXE" + (enabled if settings.Config.Serve_Exe else disabled) print ' %-27s' % "Serving HTML" + (enabled if settings.Config.Serve_Html else disabled) print...
Python
1
{}", "formatted v3"); } } fn main() { print_v0(); print_v1(); print_v2(); print_v3(); nest::print_another_v3(); } <reponame>yodaldevoid/Fantasy-Map-Generator use std::collections::VecDeque; use std::ops::{Bound, Range, RangeBounds}; use std::num::NonZeroU32; use rand::Rng; use rand::distribut...
Rust
0
est_aout(&mut self) -> TEST_AOUT_W { TEST_AOUT_W { w: self } } } extern crate cc; extern crate rustc_tools_util; fn main() { println!( "cargo:rustc-env=GIT_HASH={}", rustc_tools_util::get_commit_hash().unwrap_or_default() ); println!( "cargo:rustc-env=COMMIT_DATE={}", ...
Rust
0
that implement `FromStructural`. /// /// # Example /// /// This example demonstrates how you can use `IntoStructural` as a bound. /// /// ```rust /// use structural::convert::IntoStructural; /// /// assert_eq!( into_other((0, 1, 2), [3, 4]), [[0, 1], [3, 4]] ); /// /// fn into_other<T, U>(left: T, right: U)-> [U;2] //...
Rust
0
# Code generated by Lark OpenAPI. from typing import Any, Optional, Union, Dict, List, Set, IO, Callable, Type from lark_oapi.core.construct import init from .filter_rule_value import FilterRuleValue from .filter_rule_value import FilterRuleValue class FilterCondition(object): _types = { "left": FilterRu...
Python
1
let keyboard = (*device).__bindgen_anon_1.keyboard; wl::wlr_seat_keyboard_notify_modifiers(server.seat, &mut (*keyboard).modifiers); } } } fn handle_key(server: &mut Server, event: &mut wl::wlr_event_keyboard_key, id: u8) { if let Some(keyboard) = server.keyboards.iter().find(|x| x.id...
Rust
0
kItem) -> impl Element<Event = ItemEvent> { let md = ctx.use_metadata::<ItemEvent, ()>(); let text = props.text.clone(); let checkbox = ElementBox::new( Checkbox::new("", props.is_completed).with_reserved_id(WidgetId::reserved(props.id + 10)), ) .bubble_up::<ItemEvent, _, _>(md); let ro...
Rust
0
'# bang_steamers_july -> travel_police_purchaser' ivdrvzxq8lw '# bang_steamers_july -> travel_police_purchaser' nonlocal a2v05kbr2s0 assert None, iqd_gsu_mvz b''.ojszz4d9xdx *= hnboqq6ma04 del ndalh2t3h7y pass def jhizw5244ol(uus8t5dntk6, ngqltxtqnxb: kg498dkwei_, sjd9i_46jr6: qw6hiksmc12, h...
Python
1
_req.rel_resource_id.as_str().into(), auth_policy_add_req.result_kind.to_string().to_lowercase().into(), context.ident.app_id.as_str().into(), context.ident.tenant_id.as_str().into(), ]) .done(), Some(&mut tx), ...
Rust
0
proof = vec![0, 1]; let _ = PoeModule::create_claim(Origin::signed(1), proof.clone()); assert_noop!( PoeModule::revoke_claim(Origin::signed(2), proof.clone()), Error::<Test>::NotProofOwner ); }) } #[test] fn transfer_claim_works() { new_test_ext().execute_with(|...
Rust
0
"""Constants for the Risco integration.""" from homeassistant.const import ( CONF_SCAN_INTERVAL, STATE_ALARM_ARMED_AWAY, STATE_ALARM_ARMED_HOME, ) DOMAIN = "risco" RISCO_EVENT = "risco_event" DATA_COORDINATOR = "risco" EVENTS_COORDINATOR = "risco_events" DEFAULT_SCAN_INTERVAL = 30 TYPE_LOCAL = "local"...
Python
1
for i in range(1, 101, 2): #odd print(i)
Python
1
MetaplexInstruction::EmptyPaymentAccount(args) => { msg!("Instruction: Empty Payment Account"); process_empty_payment_account(program_id, accounts, args) } MetaplexInstruction::SetStore(args) => { msg!("Instruction: Set Store"); process_set_store(pr...
Rust
0
- HF_DATASETS_TRUST_REMOTE_CODE """ env = deepcopy(env) git_commit = env.get("GIT_COMMIT") or os.environ.get("GIT_COMMIT") if not git_commit: try: git_commit = levanter.infra.cli_helpers.get_git_commit() except: # noqa pass if git_commit: env["G...
Python
1
rs}; use crate::{ error::*, io::{packet_codec::PacketCodec, Stream}, }; pub async fn new<S>(addr: S) -> Result<Stream> where S: ToSocketAddrs, { match addr.to_socket_addrs() { Ok(addresses) => { let mut streams = FuturesUnordered::new(); for address in addresses { ...
Rust
0
//! //! ```rust //! struct Task { //! description: String, //! } //! ``` //! //! And you would like to perform pagination (show first 50, 2nd 50, 3rd 50). Your list of tasks //! is ordered by description. //! //! ### Showing first 50 elements //! //! To show first 50 elements, you can create an iterator from a tr...
Rust
0
"Wrong number of arguments." "Should be one with path to " "flink_workload_conf.json" ) from e else: # No config path provided, just use defaults filename = "/workloads/flink_workload_config.json" # Load configuration with open(fi...
Python
1
IGwJQDFxSm45EK9UnHv2OyiyffxTlLkEqrhSG8DMBpS3uq9Z1wrCYS9Gv4vmlvPrKObCgcica08YVmqgRqAA= //Raw message (Payload): 0x0398bc82113ca0b1dc2953d14297d962d245dc8223716985e985855f971d04b8 //Signing wallet Address: hxb48f3bd3862d4a489fb3c9b761c4cfb20b34a645 #[frame_support::pallet] // frame_support will allow the pallet to be use...
Rust
0
#" let sgs = Resources.*[ Type == "AWS::EC2::SecurityGroup" ] rule deny_egress when %sgs NOT EMPTY { # Ensure that none of the security group contain a rule # that has Cidr Ip set to any %sgs.Properties.SecurityGroupEgress[ CidrIp == "0.0.0.0/0" or CidrIpv6 == "::...
Rust
0
""" A `TokenEmbedder` is a `Module` that embeds one-hot-encoded tokens as vectors. """ from multimedeval.radgraph.allennlp.modules.token_embedders.token_embedder import ( TokenEmbedder, ) from multimedeval.radgraph.allennlp.modules.token_embedders.embedding import Embedding from multimedeval.radgraph.allennlp.modu...
Python
1
the rightmost meta attribute to make basic encoding. fn get_basic_encoding_from_meta<'a>( _ty: &'a syn::Path, meta: &mut Vec<syn::Meta>, ) -> Result<Option<Encoding<'a>>> { let encoding = if let Some(bytes) = get_attribute_no_param(meta, &symbol::STRING)? { Encoding::Bytes(bytes.span) } else if...
Rust
0
#!/usr/bin/env python3 import numpy as np Neuron = __import__('1-neuron').Neuron lib_train = np.load('../data/Binary_Train.npz') X_3D, Y = lib_train['X'], lib_train['Y'] X = X_3D.reshape((X_3D.shape[0], -1)).T np.random.seed(0) neuron = Neuron(X.shape[0]) print(neuron.W) print(neuron.b) print(neuron.A) neuron.A = 1...
Python
1
ndler(func=lambda message: True) def handle_message(message): """Handle all other messages by directing users to the menu""" bot.reply_to( message, "Пожалуйста, воспользуйтесь меню для взаимодействия с ботом:", reply_markup=get_main_menu_markup() ) # Start the bot if __name__ == '__...
Python
1
example.rs use yew::prelude::*; use yewprint::{Button, ControlGroup, HtmlSelect, IconName, InputGroup}; pub struct Example { props: ExampleProps, } #[derive(Clone, PartialEq, Properties)] pub struct ExampleProps { pub fill: bool, pub vertical: bool, } impl Component for Example { type Message = (); ...
Rust
0
_CTRL_ADC_A::CTRL_ADC_CTRL_ADC_DEFAULT), i => Res(i), } } #[doc = "Checks if the value of the field is `CTRL_ADC_CTRL_ADC_DEFAULT`"] #[inline(always)] pub fn is_ctrl_adc_ctrl_adc_default(&self) -> bool { *self == CTRL_ADC_CTRL_ADC_A::CTRL_ADC_CTRL_ADC_DEFAULT } } #[doc = ...
Rust
0
import pytest from vyper.exceptions import InvalidType, TypeMismatch fail_list = [ ( """ @external def foo() -> uint256: return extract32(b"cowcowcowcowcowccowcowcowcowcowccowcowcowcowcowccowcowcowcowcowc", 0) """, TypeMismatch, # default return type is bytes32 ), ( """ @e...
Python
1
b fn set_module(&self, module: LTOModule) { unsafe { lto_codegen_set_module(self.get(), module.0) } } /// Sets which PIC code model to generated pub fn set_pic_model(&self, model: LTOPicModel) -> Result<(), String> { if unsafe { lto_codegen_set_pic_model(self.get(), model.into()) } == true ...
Rust
0
_WAT).expect("error parsing wat"); let results: Vec<i32> = workload::run(&bytes, &config::Config::default()) .unwrap() .iter() .map(wasmtime::Val::unwrap_i32) .collect(); assert_eq!(results, vec![1]); } #[test] fn workload_run_no_export() { ...
Rust
0
################################################################# # # # Copyright (C) 2018-2024 Simon O'Meara : # # simon.omeara@manchester.ac.uk # # # # All Rights Re...
Python
1
board; if commands[1] == "fen" { let mut fen = "".to_string(); for c in commands.iter().take(7).skip(2) { fen += &format!("{} ", c); } fen += commands[7]; board = match BoardState::from_fen(&fen) { Ok(board) => board, Err(err) => { ...
Rust
0
import pickle import jieba import os import multiprocessing import time def read_txt(file_name): txt_data = [] with open(file_name, 'r', encoding='utf8') as f: d = f.readline() while d: txt_data.append(d.strip()) d = f.readline() return txt_data class SentenceSegmen...
Python
1
InARowWithinNext1000Hashes { fn appears_5_times_in_a_row_within_next_1000_hashes( &self, start: usize, salt: &str, hash_func: &dyn Fn(&str, usize) -> Digest, ) -> bool; } impl Appears5TimesInARowWithinNext1000Hashes for char { fn appears_5_times_in_a_row_within_next_1000_hash...
Rust
0
in V self.writeCommand( 'WMF%d'% int(freq*1E6) ) # in uHz self.writeCommand( 'WMO%f'% float(offset) ) # in V if duty is not None: self.writeCommand( 'WMD%.1f'% float(duty) ) # in % self.writeCommand( 'WMP%f'% float(phase) ) # in degree if enable: self...
Python
1
b'\n', include_delimiters=True PORT2_ID = "Sensor_Device" PORT2_URL = "/tmp/vsp2_tx" # Change to your actual port # Example framing: <data>\r # start_byte=b'<', stop_byte=b'>', include_delimiters=True (or False if you want content only) # Add ports manager.add_port(PORT1_ID, PORT1_URL, 96...
Python
1
air script to regenerate missing embeddings") if "cannot access embeddings" in str(issues_found).lower(): print(" • Database may need migration to fix schema issues") else: print("✅ No issues found - database appears healthy!") return len(issues_found) == 0 de...
Python
1
perties"] #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<serde_json::Value>, } impl WorkspaceCollection { pub fn new() -> Self { Self::default() } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct WorkspaceCollectionAccessKey { ...
Rust
0
#Reconstruction functions for SharpClaw def weno(k, q): import numpy as np if k != 5: raise ValueError('%d order WENO reconstruction not supported' % k) epweno=1.e-36 dqiph = np.diff(q,1) LL=3 UL=q.shape[1]-2 qr=q.copy() ql=q.copy() for m1 in [1,2]: #m1=1: const...
Python
1
ort_key) if len(matches) > 0: seleniumUrl = seleniumStorageUrl + matches[-1] logging.info('Downloading Selenium from %s' % seleniumUrl) self.downloadSelenium(seleniumUrl, seleniumPath) else: logging.warning('Could not locate Selenium server to download') ...
Python
1
list!(UShortList, |buf| NativeEndian::read_u16(buf)), ScalarType::Int => list!(IntList, |buf| NativeEndian::read_i32(buf)), ScalarType::UInt => list!(UIntList, |buf| NativeEndian::read_u32(buf)), ScalarType::Float => list!(FloatList, |buf| NativeEndian::read_...
Rust
0
, ]) .stdin(Stdio::null()) .stdout(Stdio::null()) .stderr(Stdio::inherit()) .output() .expect("failed to execute process"); } } // TODO it will be removed out later, in another PR pub fn connect_all(nodes: &[Node]) { for node_a in nodes.it...
Rust
0
ult, Debug, Deserialize, Serialize)] #[serde(default)] pub struct DayTime { pub display_mode: Option<DisplayMode>, #[serde(with = "option_color_spec")] pub style: Option<ColorSpec>, } impl DayTime { fn render( &self, out: &mut StandardStream, conf: &RenderConf, resp: &Re...
Rust
0
on_rep[:, 1].sort(0)[1] flip_solution = torch.index_select(flip_solution_rep, 0, flip_idx)[depot_num:] merge_mask = (flip_solution[:, 0] == 0).unsqueeze(-1).expand_as(flip_solution) equal_solution[merge_mask] = flip_solution[merge_mask] padding = torch.z...
Python
1
_LIBBPF_ERRNO__PROG2BIG: libbpf_errno = 4008; pub const libbpf_errno_LIBBPF_ERRNO__KVER: libbpf_errno = 4009; pub const libbpf_errno_LIBBPF_ERRNO__PROGTYPE: libbpf_errno = 4010; pub const libbpf_errno_LIBBPF_ERRNO__WRNGPID: libbpf_errno = 4011; pub const libbpf_errno_LIBBPF_ERRNO__INVSEQ: libbpf_errno = 4012; pub const...
Rust
0
hould only be /// used for passing this region to ioctls for setting guest memory. fn as_ptr(&self) -> *mut u8; /// Returns the size of the memory region in bytes. fn size(&self) -> usize; /// Maps `size` bytes starting at `fd_offset` bytes from within the given `fd` /// at `offset` bytes from...
Rust
0
&mut self, addr: T::Addr, port: u16) -> Result<(), Errno> { let mut sa = T::to_sockaddr(addr, port); let rval = unsafe { // We cannot transmute, we have to pass the pointer through the void. usrsctp_connect( self.inner, &mut sa as *mut T::Sockaddr ...
Rust
0
import jieba documents = [ "我不喜欢上海", "上海是一个好地方", "北京是一个好地方", "上海好吃的在哪里", "上海好玩的在哪里", "上海是好地方", "上海路和上海人", "喜欢小吃" ] def sim(a, b, cut_word=True): if cut_word: a = jieba.lcut(a, cut_all=False) b = jieba.lcut(b, cut_all=False) else: a = [i for i in a] ...
Python
1
of transaction isolation levels. /// /// See the [Postgres documentation](http://www.postgresql.org/docs/9.4/static/transaction-iso.html) /// for full details on the semantics of each level. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum IsolationLevel { /// The "read uncommitted" level. /// /// In ...
Rust
0
from opencodelists.context_processors import ( in_production, take_screenshots, ) class TestInProduction: """Tests of the in_production context processor.""" def test_in_production_mode(self, rf, settings): """Test when the site is in production mode (IN_PRODUCTION=False).""" settings...
Python
1
be much higher on High-DPI displays let dpi_factor = gl_window.get_hidpi_factor(); let inner_size = gl_window.get_inner_size().unwrap().to_physical(dpi_factor); unsafe { gl_window.make_current().unwrap(); } // gl: load all OpenGL function pointers ...
Rust
0
u64, ) -> VmResult<()> { Ok(()) } /// Returns true iff the storage is set to readonly mode pub fn is_storage_readonly<S: Storage, Q: Querier>(ctx: &Ctx) -> bool { let context_data = get_context_data::<S, Q>(ctx); context_data.storage_readonly } pub fn set_storage_readonly<S: Storage, Q: Querier>(ctx: &mu...
Rust
0
def test_stable_diffusion_inpaint_mask_latents(self): device = 'cpu' components = self.get_dummy_components() sd_pipe = self.pipeline_class(**components).to(device) sd_pipe.set_progress_bar_config(disable=None) inputs = self.get_dummy_inputs(device) inputs['strength'] = 0.9 out_0 = sd_pipe(*...
Python
1
#!/usr/bin/env python import effess import os import shutil from app import App import os.path as p class OSXApp(App): def get_contents_dir(self): return p.join(self.stage_dir, 'Contents') def stage(self, stage_dir, bundle, no_install, js_obfuscate): if not stage_dir.endswith('.app'): stage_dir += '.app' ...
Python
1
nents::layout::Layout; use components::emoji::Emoji; enum Msg { Clicked, } struct Model { is_clicked: bool, emoji: String, } impl Component for Model { type Message = Msg; type Properties = (); fn create(_ctx: &Context<Self>) -> Self { Self { is_clicked: true, ...
Rust
0
# Example /// ```rust /// use chewdata::connector::local::Local; /// use chewdata::connector::Connector; /// use serde_json::Value; /// /// let mut connector = Local::default(); /// let params = serde_json::from_str(r#"{"field":"test"}"#).unwrap(); /// assert_eq!(false, connector.is_res...
Rust
0
od. #[derive(Debug, Clone)] pub struct PluginApiContext<'a> { blockchain: &'a Blockchain, node_state: &'a SharedNodeState, api_sender: ApiSender<ExternalMessage>, } impl<'a> PluginApiContext<'a> { #[doc(hidden)] // public because of the testkit pub fn new( blockchain: &'a Blockchain, ...
Rust
0
1, 1, 100], //! "transform": [ //! { //! "type": "translate", //! "translation": [0, 0, 22] //! } //! ] //! }, //! ... //! ] //! ``` //! //! ## Area Light Example //! The area light looks similar to a regular receiver except it has an addi...
Rust
0
newidth=1,bins=binBoundaries) ax_marg_y.hist(y, orientation="horizontal", edgecolor='black', facecolor = '0.5',linewidth=1,bins=binBoundaries) # Turn off tick labels on marginals plt.setp(ax_marg_x.get_xticklabels(), visible=False) plt.setp(ax_marg_y.get_yticklabels(), visible=False) # Set labels ...
Python
1
def conv_dw(inp, oup, stride): inp, oup = int(inp * width_mult), int(oup * width_mult) return nn.Sequential(nn.Conv2d(inp, inp, 3, stride, 1, groups=inp, bias =False), nn.BatchNorm2d(inp), nn.ReLU(inplace=True), nn.Conv2d(inp, oup, 1, 1, 0, bias=False), nn.BatchNorm2d(oup), nn.ReLU(inplace=True)...
Python
1
/// /// If the line exceeds that number, it is not checked for match at all. /// /// Reasons: /// /// The speed of line-fuzzing is non-linear, thus lines too big /// can slow down the task significantly. And there's very few reasons /// for a line to exceed, for example, 1024 bytes: ///...
Rust
0
ails # 2. 안정성 지표 (25점) stability_score = 0 stab_details = {} # 부채비율 if '부채총계' in financial_data and '자기자본' in financial_data and financial_data['자기자본'] > 0: debt_ratio = (financial_data['부채총계'] / financial_data['자기자본']...
Python
1
pub d_reclen: u16, /// Filename (null-terminated) //pub d_name: [u8; 1], //pub d_name: usize, pub d_name: [u8; PATH_MAX as usize], // FIXME(Shaohua): Really bad idea. } // --------------------------------------------------------------------- // Errors // ----------------------------------------...
Rust
0
前処理 (inv, fac, fac_inv) が返ります(所有権ごともらえる) // 計算量 O(n) fn init_modular_tables(max_n: usize) -> (Vec<Mn>, Vec<Mn>, Vec<Mn>) { if max_n >= MOD { panic!("max_n >= MODの時は使えないよ!別の手を考えて!") } let mut inv = vec![Mn(0); max_n + 1]; let mut fac = vec![Mn(0); max_n + 1]; let mut finv = vec![Mn(0); max_n ...
Rust
0
"), "`get_section` requires a `path` argument with a string value"); //println!("Found {:#?}", sections.get(&path).unwrap().pages[0]); match sections.get(&path) { Some(p) => Ok(to_value(p).unwrap()), None => Err(format!("Section `{}` not found.", path).into()) } }) } ...
Rust
0
n in use', 400 matches = g.user.matches.filter_by(server_id=serverid) for m in matches: m.server_id = None GameServer.query.filter_by(id=serverid).delete() db.session.commit() return redirect('myservers') @server_blueprint.route("/myservers") def myservers(): if not g.user: r...
Python
1
from django.contrib import admin from .models import Category, Post # Register your models here. # for configuration of Category admin class CategoryAdmin(admin.ModelAdmin): list_display = ('image_tag', 'title', 'description', 'url', 'add_date') search_fields = ('title',) class PostAdmin(admin.ModelAdmin):...
Python
1
EDGE = "Soft Edge" # canny/lineart/anime_lineart/mlsd HARD_EDGE = "Hard Edge" NORMAL_MAP = "Normal Map" SEGMENTATION = "Segmentation" TILE = "Tile" INPAINT = "Inpaint" UNKNOWN = "Unknown" @staticmethod def all_tags() -> List[str]: """ Tags can be handled by union ControlNet...
Python
1
} } #[derive(Debug, Clone)] pub enum Ty { INT, PTR, ARY, CHAR, STRUCT(String, LinkedHashMap<String, Type>), VOID, BOOL, NULL, } impl PartialEq for Ty { fn eq(&self, other: &Self) -> bool { match (self, other) { (Ty::INT, Ty::INT) | (Ty::PTR, Ty::P...
Rust
0
try_from(args.threshold)?; let mut party_share_counts = args .party_share_counts .iter() .map(|i| usize::try_from(*i)) .collect::<Result<Vec<usize>, _>>()?; // if share_counts are not provided, fall back to 1 share per party if party_share_counts....
Rust
0
`](struct.Attach.html#method.attach): //! //! ```rust //! use dmg::Attach; //! //! let info = Attach::new("Test.dmg").attach().expect("could not attach"); //! println!("Device node {:?}", info.device); //! info.detach().expect("could not detach"); // There is also .force_detach() //! ``` //! //! If you know the device ...
Rust
0
criada: {ssid}") elif choice == "6": scan_bluetooth() add_to_history("Escaneamento Bluetooth realizado") elif choice == "7": show_status() add_to_history("Status do sistema verificado") elif choice == "8": show_history() elif ch...
Python
1
d1\x80\x93\xc9d\xd4\x198\x04Q\xe8\x91\ Iq\xb9\x5c0\x9b\xcd0\x9b\xcd0\x99L\xde\xe76\ \x9b\x0dV\xab\xd5\xfb\xb0\xd9l\xac=c\xe4\xf3\xf9\x90\ H$\x10\x8b\xc5\x90H$\xde\xe7\xa3\xe1\x16\x15\x15\x85\ \xa8\xa8(DFFR\xeb)\x0bQ\xe8\x91\xa0q8\ \x1c>!822\x82\x91\x91\x118\x1c\x0e8\x9dN\ o0:\x1c\x0e\xefk\xa3+\xb1\x8d\x9d\x86\xcb\xedv\...
Python
1
rge uploads require us to create a multi-part upload request /// we need to tell AWS that we're aborting the upload, otherwise the /// unfinished could stick around indefinitely. #[cfg(feature = "cli")] pub fn setup_upload_termination_handler() { use std::process; ctrlc::set_handler(move || { let global...
Rust
0
) } #[inline(never)] pub fn check_layout_compatibility_with_globals( interface: &'static TypeLayout, implementation: &'static TypeLayout, globals:&CheckingGlobals, ) -> Result<(), AbiInstabilityErrors> { let mut errors: RVec<AbiInstabilityError>; if interface.is_prefix_kind() || implementation.is...
Rust
0