text
string
label_name
string
labels
int64
import logging from airflow.hooks.postgres_hook import PostgresHook from airflow.models import BaseOperator from airflow.utils.decorators import apply_defaults class HasRowsOperator(BaseOperator): @apply_defaults def __init__(self, redshift_conn_id="", table="", ...
Python
1
, service_fn}; use hyper::{Body, Method, Request, Response, Server, StatusCode}; use rustls::{sign::CertifiedKey, ClientHello, NoClientAuth, ResolvesServerCert, ServerConfig}; use std::pin::Pin; use std::{ collections::HashMap, io, path::PathBuf, sync::{Arc, RwLock, Weak}, vec::Vec, }; use tokio::ne...
Rust
0
# # Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. # Use of this file is governed by the BSD 3-clause license that # can be found in the LICENSE.txt file in the project root. # Provides an empty default implementation of {@link ANTLRErrorListener}. The # default implementation of each method does noth...
Python
1
:OK) .header("content-type", "text/html") .body(Body::from(action.generate_response())) .unwrap()) } action => { println!("Unknown action: {:?}", action); Ok(Response::builder() .status(StatusCode::NOT_IMPLEMENTED) ...
Rust
0
else: return ServiceResultFactory.success( "パーティ編成画面を表示します", data={"panel_type": "party_formation"} ) def _add_party_member(self, params: Dict[str, Any]) -> ServiceResult: """パーティにメンバーを追加""" logger.info(f"[DEBUG] _add_party_member called w...
Python
1
#[derive(Debug)] pub struct RocksDBReducingState { state_key: StateKey, backend_path: String, db: DB, } impl RocksDBReducingState { pub fn new(state_key: &StateKey, backend_path: &str, read_only: bool) -> Self { let path = get_db_path(state_key); info!("Try to open RocksDB [readonly...
Rust
0
DRIVER: ::DWORD = SERVICE_KERNEL_DRIVER | SERVICE_FILE_SYSTEM_DRIVER | SERVICE_RECOGNIZER_DRIVER; pub const SERVICE_WIN32_OWN_PROCESS: ::DWORD = 0x00000010; pub const SERVICE_WIN32_SHARE_PROCESS: ::DWORD = 0x00000020; pub const SERVICE_WIN32: ::DWORD = SERVICE_WIN32_OWN_PROCESS | SERVICE_WIN32_SHARE_PROCESS; pub co...
Rust
0
r()); } if let Some(var_1182) = &input.description { object.key("Description").string(var_1182.as_str()); } if let Some(var_1183) = &input.default_route_settings { let mut object_1184 = object.key("DefaultRouteSettings").start_object(); crate::json_ser::serialize_structure_crate_...
Rust
0
# -*- coding: utf-8 -*- { 'agree': 'setuju', 'all of it': 'semuanya', 'Dear %(person_name)s': 'Kepada %(person_name)s', 'disagree': 'tidak setuju', 'Malaysian': 'Bahasa Melayu', 'most of it': 'kebanyakannya', 'no': 'tidak', 'no change': 'tiada perubahan', 'not at all': 'tidak sama sekali', 'part of it': 'sebahagian dar...
Python
1
-> web_sys::HtmlInputElement { use wasm_bindgen::JsCast; web_sys::window() .unwrap() .document() .unwrap() .get_element_by_id(AGENT_ID) .unwrap() .dyn_into() .unwrap() } #[cfg(target_arch = "wasm32")] fn install_document_events(runner_ref: &AppRunnerRef)...
Rust
0
same_site=parse_cookie_attr_same_site( cookie_entity), max_age=to_nullable_double( cookie_entity['max-age'], 'cookie.maxAge'))) ...
Python
1
s: logger.error( "Input file must be in either .arff, .csv, .jsonlines, " ".ndj, or .tsv format. You specified: " f"{input_extension}" ) sys.exit(1) if output_extension != input_extension: logger.error( "Output file must be in the same...
Python
1
); outpoints_context.insert( ALWAYS_SUCCESS_OUTPOINT_KEY, always_success_out_point.clone(), ); } fn build_input_cell<I, B>( iterator: I, context: &mut Context, outpoints_context: &mut OutpointsContext, inputs: &mut Vec<CellInput>, ) where I: Iterator<Item = B>, B: CellBu...
Rust
0
type Influences = BTreeSet<i32>; type Relations = BTreeMap<Person, Influences>; /** * Auto-generated code below aims at helping you parse * the standard input according to the problem statement. **/ fn main() { let mut input_line = String::new(); io::stdin().read_line(&mut input_line).unwrap(); let n = ...
Rust
0
*x = 1.0; } pub fn fun3_example() { let mut res = 0.0; println!("Before: res = {}", res); modifies(&mut res); println!("After : res = {}", res); } } // entry point pub fn fun_examples() { fun1::fun1_example(); println!("----- Pass by reference -----"); ...
Rust
0
) { let val_sqrt = ((self.sigx2 - self.sigy2).pow2() + self.rho_sigx_sigy.twice().pow2()).sqrt(); let a2 = 0.5 * (self.sigx2 + self.sigy2 + val_sqrt); let b2 = 0.5 * (self.sigx2 + self.sigy2 - val_sqrt); let theta = self.rho_sigx_sigy.atan2(a2 - self.sigy2); // let theta = (a2 - self.sigx2).atan2(s...
Rust
0
def closest_integer(value): """ Returns the closest integer to the given value, rounding away from zero if equidistant. Args: value (str): A string representing a number. Returns: int: The closest integer to the given value. """ try: number = float(value) except V...
Python
1
IO_INTERP0_CTRL_LANE1_ADD_RAW_BITS: u32 = 262144; pub const SIO_INTERP0_CTRL_LANE1_ADD_RAW_MSB: u32 = 18; pub const SIO_INTERP0_CTRL_LANE1_ADD_RAW_LSB: u32 = 18; pub const SIO_INTERP0_CTRL_LANE1_ADD_RAW_ACCESS: &'static [u8; 3usize] = b"RW\0"; pub const SIO_INTERP0_CTRL_LANE1_CROSS_RESULT_RESET: u32 = 0; pub const SIO_...
Rust
0
import tkinter as tk from tkinter import font from OWM import get_weather HEIGHT = 350 WIDTH = 450 def display_weather(): city = entry_field.get() weather = get_weather(city) if "error" in weather: message = f"Error: {weather['error']}" else: temp = weather["temperature"] ...
Python
1
} Ok(()) } // SPDX-License-Identifier: MIT // Copyright (C) 2018-present iced project and contributors use crate::Register; use alloc::string::String; use alloc::vec::Vec; pub(crate) struct VARegisterValue { pub(crate) register: Register, pub(crate) element_index: usize, pub(crate) element_size: usize, pub(crat...
Rust
0
]; arr.extend(page); } } """ code_run_result = session.code_run( code=code, code_language="rust", input_str="", time_limit=2.0, memory_limit=64 * 1024 * 1024 ) assert code_run_result.stdin == "" assert code_run_result.stdout == "" assert code_run_result.st...
Python
1
:load(Vector::new(0, 0, 6), Vector::new(-1, 2, 4)), Body::load(Vector::new(2, 1, -5), Vector::new(1, 5, -4)), Body::load(Vector::new(1, -8, 2), Vector::new(0, -4, 0)), ], ); assert_eq!(system.run(3), expected); } #[test] fn step_4() { let system = System::new(vec![ Body::ne...
Rust
0
# Problem: Jump Game - https://leetcode.com/problems/jump-game/ class Solution: def canJump(self, nums: List[int]) -> bool: max_jump = 0 for i in range(len(nums) - 1): max_jump = max(max_jump, nums[i] + i) if max_jump <= i: return False r...
Python
1
try_magic_method("__trunc__", vm, &value) } /// Applies ceiling to a float, returning an Integral. /// /// # Arguments /// /// * `value` - Either a float or a python object which implements __ceil__ /// * `vm` - Represents the python state. fn math_ceil(value: PyObjectRef, vm: &VirtualMachine) -> PyResult { if obj...
Rust
0
from sqlalchemy import ( create_engine, ) from starlette.applications import Starlette from starlette.responses import HTMLResponse from starlette.routing import Route from starlette_admin.contrib.sqla import Admin from starlette_admin.contrib.sqla.ext.pydantic import ModelView from .config import ENGINE_URI from ...
Python
1
a([[1], [1], [1], [1]], mp_dtype) master_params = [p.astype(mp_dtype) for p in params] return ( params, grads, lrs, moment1s, moment2s, moment2s_max, beta1_pows, beta2_pows, master_params, ...
Python
1
neric::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rcmr](index.html) module"] pub struct RCMR_SPEC; impl crate::RegisterSpec for RCMR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [rcmr:...
Rust
0
store .filesystem() .graveyard() .queue_tombstone(store.store_object_id(), self.object_id()); } } } impl DirectoryEntry for FxFile { fn open( self: Arc<Self>, scope: ExecutionScope, flags: fio::OpenFlags, _mode: u32, ...
Rust
0
# Copyright 2024 The GLIGEN Authors and HuggingFace Team. 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 re...
Python
1
}, Foo::from_raw_bytes(&[0, 8, 123, 0, !0, 0, !0, 0, !0, 0, !0], &Settings::default()).unwrap()); } #[test] fn can_read_length_prefix_3_elements() { assert_eq!(WithElementsLength { count: 3, foo: true, data: vec![1, 2, 3], }, WithElementsLength::from_raw_bytes( ...
Rust
0
hen setting properties, all artists are affected; when querying the allowed values, only the first instance in the sequence is queried. For example, two lines can be made thicker and red with a single call: >>> x = arange(0, 1, 0.01) >>> lines = plot(x, sin(2*pi*x), x, sin(4*pi...
Python
1
import hashlib import random import sys import pysam def sig(seed, x): seed = f'{seed}'.encode('utf-8') bytes = f'{x}'.encode('utf-8') hash = hashlib.sha256() hash.update(seed) hash.update(bytes) hash = hash.digest() res = 0.0 for b in hash: res = (res + b) / 256.0 return re...
Python
1
# Port By @VckyouuBitch From GeezProject # Perkontolan Dengan Hapus Credits # Recode By : @AyiinXd from asyncio import sleep from telethon.tl.types import ChatBannedRights from telethon.tl.functions.channels import EditBannedRequest from telethon.tl.types import ChannelParticipantsKicked from Lumiere import CMD_HELP...
Python
1
ulptura", "statua"], }, #[cfg(feature = "ca")] crate::Annotation { lang: "ca", tts: Some("moai"), keywords: &["cara", "estàtua", "moai"], }, #[cfg(feature = "chr")] crate::Annotation { lang: "chr", tts: Some("ᎼᎢ"...
Rust
0
import torch import numpy as np import pandas as pd import matplotlib.pyplot as plt def get_conv_output(model, input_shape): """Compute the flattened output size of a CNN model after conv layers.""" with torch.no_grad(): x = torch.zeros(1, *input_shape) # e.g. (1, 224, 224) x = model._forward_...
Python
1
::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [lpi2c0](lpi2c0) module"] pub type LPI2C0 = crate::Reg<u32, _LPI2C0>; #[allow(missing_docs)] #[doc(hidden)] pub struct _LPI2C0; #[doc = "...
Rust
0
), Dynamic::new(element.num_nodes())); assemble_element_elliptic_vector( output, &element, &MockVectorEllipticEnergy, u, &weights, &points, &quadrature_data, MatrixSliceMut::from(&...
Rust
0
, density: f64, } pub fn hash_id<T: Hash>(t: &T) -> u64 { let mut s = DefaultHasher::new(); t.hash(&mut s); s.finish() } /// Try to get memory usage (resident set size) in bytes using the `getrusage()` function from libc. // from https://github.com/digama0/mm0/blob/bebd670c5a77a1400913ebddec2c6248e76f...
Rust
0
_base_ = ['yolo_model_base.py', 'yolo_dataset_base.py', 'yolo_optimizer_base.py', 'yolo_scheduler_base.py'] batch_size = 16 max_epoch = 12 log_interval=10 eval_interval=12 checkpoint_interval = 1 stride=32 imgsz=640 imgsz_test=640 dataset_type = 'YoloDataset' model = dict( type='YOLOv5S', ema=True, imgsz=i...
Python
1
onvert_opt = Some("vtt"); } else if matches.is_present("srt") { convert_opt = Some("srt"); } let (mut input_path, mut output_path, mut rename_opt) = match helpers::get_paths(input, seconds, partial, rename, output_opt, convert_opt) { Ok(paths) => paths, ...
Rust
0
w::RawEncodingBuf>() where <T::Slice as RawEncoding>::Trit: Serialize, { let (a, a_i8) = gen_buf::<T>(0..1000); assert_eq!( serde_json::to_string(&a).unwrap(), format!("[{}]", a_i8.iter().map(|t| t.to_string()).collect::<Vec<_>>().join(",")), ); } fn serialize_generic_unbalanced<T: raw:...
Rust
0
} } unsafe impl<T: MediaFileImpl> IsSubclassable<T> for MediaFile { fn class_init(class: &mut glib::Class<Self>) { <MediaStream as IsSubclassable<T>>::class_init(class); let klass = class.as_mut(); klass.close = Some(media_file_close::<T>); klass.open = Some(media_file_open::<...
Rust
0
!("Connected on shard {}", id); //! } //! (_, Event::MessageCreate(msg)) => { //! if msg.content == "!ping" { //! http.create_message(msg.channel_id).content("Pong!").await?; //! } //! } //! _ => {} //! } //! //! Ok(()) //! } //! ``` //! //...
Rust
0
# before { # open key# key : # colon value# value } # close # after {**d} {**a, # leading ** # middle b # trailing } { ** # middle with single item b } { # before ** # between b, } { **a # comment before preceding node's comma , # before ** # between b, } {} {1:2,} {1:2, 3:4,...
Python
1
ub device-identity delete -d {} --login {}".format( device, connection_string ) ) for device in device_ids: cli.invoke( "iot hub device-identity delete -d {} -n {} -g {}".format( device, HUB_NAME, RG ) ...
Python
1
) if "Generated workflow files" in response or "Workflow Code Generated Successfully" in response: print("🎉 Demo completed! E-commerce workflow generated successfully!") break except Exception as e: print(f"❌ Demo error: {e}") ...
Python
1
e can get matched up // to them. // // One day this may look a little less ad-hoc with the compiler helping out to // hook up these functions, but it is not this day! #[allow(improper_ctypes)] extern { fn __rust_maybe_catch_panic(f: fn(*mut u8), data: *mut u8, ...
Rust
0
t = H::Input, Output = H::Output>>, } impl<H> Clone for HandlerLink<H> where H: StateHandler, { fn clone(&self) -> Self { Self { link: self.link.clone(), } } } type HandlerMsg<H> = <H as StateHandler>::Message; type HandlerInput<H> = <H as StateHandler>::Input; type HandlerOutp...
Rust
0
θ_target = τ*θ_local + (1 - τ)*θ_target Params ====== local_model (PyTorch model): weights will be copied from target_model (PyTorch model): weights will be copied to tau (float): interpolation parameter """ for target_param, local_param in zi...
Python
1
# program to display a user entered name followed by good afternoon using input() name= input("Enter your name") print("good afternoon",name) # f is new style of writing variable in a string print(f"good afternoon {name}") # another method print("good afternoon " + name)
Python
1
reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PETEMC_A { #[doc = "0: Disabled"] CONST_0 = 0, #[doc = "1: Enabled"] CONST_1 = 1, } impl From<PETEMC_A> for bool { #[inline(always)] fn from(variant: PETEMC_A) -> Self { variant as u8 != 0 } } #[doc = "Field `PETEMC` reade...
Rust
0
m(first); let offset: BigInt = (BigInt::from(check_before) - first - 1)*index/(sample_points - 1); (bfirst + offset).to_i64().unwrap() }) .map (| input | (input, evaluate_at_fractional_input (& coefficients, input, input_shift).unwrap())) .collect() ; assert...
Rust
0
import pandas as pd import numpy as np def load_individual_timeseries(name): base_url='https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series' url = f'{base_url}/time_series_covid19_{name}_global.csv' df = pd.read_csv(url, index_c...
Python
1
dhcsr.set_c_halt(true); dhcsr.set_c_debugen(true); memory.write_word_32(Dhcsr::ADDRESS, dhcsr.into())?; } Ok(()) } pub fn enable_debug_mailbox( interface: &mut ArmCommunicationInterface<Initialized>, dp: DpAddress, ) -> Result<(), DebugProbeError> { log::info!("LPC55xx connect src...
Rust
0
#print('\n\n-----Invoking activity_log microservice-----') print('\n\n-----Publishing the (order info) message with routing_key=order.info-----') # invoke_http(activity_log_URL, method="POST", json=order_result) channel.basic_publish(exchange=exchangename, routing_key="o...
Python
1
o() /// # } /// # wasm_bindgen_test_configure!(run_in_browser); /// # #[wasm_bindgen_test] /// # fn run() { /// # App::render_single(ui()); /// # } /// ``` pub fn push<U>(self, component: U) -> Self where U: component::Component, { self.elem .as_re...
Rust
0
Rs = R[id_s] Rt = R[id_t] # ReLU prevents negative numbers in sqrt if offsets_st is None: V_st = Rt - Rs # s -> t else: V_st = Rt - Rs + offsets_st # s -> t D_st = torch.sqrt(torch.sum(V_st**2, dim=1)) V_st = V_st / D_st[..., None] return D_st, V_st def inner_product...
Python
1
�嗵恸潼砼", "tou :头投透偷钭骰", "tu :图土突途徒凸涂吐兔屠秃堍荼菟钍酴", "tuan :团湍抟彖疃", "tui :推退腿颓蜕褪煺", "tun :吞屯臀氽饨暾豚", "tuo :脱拖托妥椭鸵陀驮驼拓唾乇佗坨庹沱柝橐砣箨酡跎鼍", "wa :瓦挖哇蛙洼娃袜佤娲腽", "wai :外歪", "wan :完万晚弯碗顽湾挽玩豌丸烷皖惋宛婉腕剜芄菀纨绾琬脘畹蜿", "wang :往王望网忘妄亡旺汪枉罔尢惘辋魍", ...
Rust
0
_case(b"body=")); let is8bit = alt(( value(true, tag_no_case(b"8bitmime")), value(false, tag_no_case(b"7bit")), )); preceded(preamble, is8bit)(buf) } fn is8bitmime(buf: &[u8]) -> IResult<&[u8], bool> { body_eq_8bit(buf).or(Ok((buf, false))) } fn mail(buf: &[u8]) -> IResult<&[u8], Cmd> ...
Rust
0
= 'none' vec1 = 0 vec2 = 0 sent_A = tokenize(sent_A) sent_B = tokenize(sent_B) for word in sent_A: if word not in ", . ? ! # $ % ^ & * ( ) { } [ ]".split(): try: vec1 += vec[word] except: continue for word in sent_B: i...
Python
1
1, Fq2, Fq2, fq2); f_bench!(2, Fq12, Fq12, fq12); f_bench!(Fq, Fq, FqRepr, FqRepr, fq); f_bench!(Fr, Fr, FrRepr, FrRepr, fr); pairing_bench!(Bls12_377, Fq12, prepared_v); use super::super::CaptivePortalError; use super::options::*; // Fixed magic cookie of this implementation const COOKIE: [u8; 4] = [99, 130, 83, 99];...
Rust
0
fields(&mut self) -> &mut ::protobuf::UnknownFields { &mut self.unknown_fields } fn as_any(&self) -> &dyn (::std::any::Any) { self as &dyn (::std::any::Any) } fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { self as &mut dyn (::std::any::Any) } fn into_any(self: ...
Rust
0
_path != '': from vehicle_reid_pytorch.utils.visualize import reid_html_table query = valid_loader.dataset.meta_dataset[:query_length] gallery = valid_loader.dataset.meta_dataset[query_length:] # distmat = np.random.rand(query_length, len(valid_loader.dataset.meta_dataset)-query_length)...
Python
1
import json import torch from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, pipeline from sentence_transformers import SentenceTransformer from openai import OpenAI from tenacity import retry, stop_after_attempt, wait_random_exponential from utils import get_fov_types, compute_l_score, ll...
Python
1
&page.content()[..sig_len] != sig { return Err( FileDecodingError::new(FileType::Vorbis, "File missing magic signature").into(), ); } Ok(()) } pub(self) fn find_last_page<R>(data: &mut R) -> Result<Page> where R: Read + Seek, { let mut last_page = Page::read(data, true)?; while let Ok(page) = Page::read...
Rust
0
u8, 02u8, 01u8, 00u8]).unwrap(); rotate180_in_place(&mut image); assert_pixels_eq!(&image, &expected); } #[test] fn test_flip_horizontal() { let image: GrayImage = ImageBuffer::from_raw(3, 2, vec![00u8, 01u8, 02u8, 10u8, 11u8, 12u8]).unwrap(); let expected: Gr...
Rust
0
morphised_functions: HashMap<FunctionSig, FunctionDecl>, functions: HashMap<FunctionSig, FunctionDecl>, morphised_classes: HashMap<(String, Vec<LisaaType>), FunctionDecl>, classes: HashMap<String, ClassDecl>, current_replacements: HashMap<String, LisaaType>, } impl Monomorphiser { pub fn new(prog...
Rust
0
from pydantic import BaseModel class ImageOutput(BaseModel): image: str = "" extra_image: dict = {}
Python
1
# Copyright 2020 Onestein (<https://www.onestein.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, models class IrActionsReport(models.Model): _inherit = "ir.actions.report" @api.model def _prepare_account_financial_report_context(self, data): lang = dat...
Python
1
/// (see [collect_internal_defines]). fn parse_define( arena: &Arena, vms: &Interpreter, env: &RcEnv, af_info: &RcAfi, rest: &[PoolPtr], ) -> Result<SyntaxElement, String> { // TODO the actual check should not be on activation frame altitude, but on syntactic // toplevelness. (eg `(defi...
Rust
0
# Copyright 2013 IBM Corp. # # 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 writing, so...
Python
1
/// <p>Set this field to <code>PHI</code> to identify personal health information in the transcription output.</p> pub fn content_identification_type( &self, ) -> std::option::Option<&crate::model::MedicalContentIdentificationType> { self.content_identification_type.as_ref() } } impl std::...
Rust
0
# Copyright (c) 2023 PaddlePaddle Authors. 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 required by appli...
Python
1
fn from_str(v: &str) -> Self { Self::Str(WString::from_str(v)) } pub fn from_ptr(ptr: *const u16) -> RtStr { if IS_INTRESOURCE(ptr) { Self::Rt(co::RT(ptr as _)) } else { Self::Str(WString::from_wchars_nullt(ptr)) } } pub fn as_ptr(&self) -> *const u16 { match self { Self::Rt(id) ...
Rust
0
de_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/inputs/24.txt")); fn main() { Day24::default().solve_print(INPUT); } #[derive(Default)] struct Day24; impl Part1 for Day24 { type A = usize; fn solve(&self, input: &str) -> Self::A { BlackTiles::flip_tiles(&Tiles::from(input)).0.len() } } impl P...
Rust
0
'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } impl R { #[doc = "Bits 6:31 - 31:6\\] Software should not rely on the value of a reserved. Writing any other value than the reset value may result in undefined behavior."] #[inline(always)] pub fn reserv...
Rust
0
works, got it from internet forum // Need to check ;-) #[inline(always)] pub fn ceil_log_2(a: u32) { return (num_bits::<i32>() as u32 - x.leading_zeros() - 1); } /* #################################### ######### HELPER FUNCTIONS ######### #################################### */ #[inline(always)] def two_power(n: u...
Rust
0
"""Basic tests for the Quantum ML module.""" from __future__ import annotations import importlib import numpy as np import pytest pytest.importorskip("torch") pytest.importorskip("qiskit") pytest.importorskip("qiskit_machine_learning") import torch from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap i...
Python
1
oth", }; format!("<mi>{}</mi>", inner) } } impl ToMathML for Logical { fn to_mathml(&self) -> String { let inner = match self { Logical::And => "and", Logical::Or => "or", Logical::Not => "&not;", Logical::Implies => "&rArr;", ...
Rust
0
from datetime import datetime from decimal import Decimal from zoneinfo import ZoneInfo from energy.consumption.models_factory import EnergyQuantileFactory from energy.customers.models import Customer from energy.customers.models_factory import CustomerFactory from energy.tariffs.models import EnergyType from energy.u...
Python
1
except NotThisMethod: pass try: root = os.path.realpath(__file__) # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. for _ in cfg.versionfil...
Python
1
fn erc20_invalid_operation() { ExtBuilder::default().build().execute_with(|| { assert_noop!( Currencies::deposit(ERC20, &alice(), 1), Error::<Runtime>::ERC20InvalidOperation ); assert_noop!( Currencies::withdraw(ERC20, &alice(), 1), Error::<Ru...
Rust
0
is one half of the number of symbols that can be stored in a /// symbol table node. A symbol table node is the leaf of a symbol table tree /// which is used to store a group. When symbols are inserted randomly into a /// group, the group's symbol table nodes are 75% full on average. That is, /// they c...
Rust
0
or rare circumstances Low, /// May be indicative of overall quality issues #[serde(rename = "medium")] Medium, /// Possibly exploitable behavior in some circumstances #[serde(rename = "high")] High, /// Should fix as soon as possible, may be under active exploitation #[serde(rename ...
Rust
0
in_query = all_shortcuts_paras_that_is_necessary_in_query[URL] else: shortcut_paras_that_is_necessary_in_query = {} desc_str = generate_shortcutdesc( WFWorkflowActions, identifier2return_value, all_api2paraname2paratype, all_api2parasummary, ...
Python
1
Self::Error> { match addr { x if x == Self::Tv as u8 => Ok(Self::Tv), x if x == Self::RecDev1 as u8 => Ok(Self::RecDev1), x if x == Self::RecDev2 as u8 => Ok(Self::RecDev2), x if x == Self::Tuner1 as u8 => Ok(Self::Tuner1), x if x == Self::PlaybackDev...
Rust
0
st must call LV2UI_Descriptor::cleanup(). * If host wants to make the UI visible again, the UI must be reinstantiated. * * @note When using the depreated URI LV2_EXTERNAL_UI_DEPRECATED_URI, * some hosts will not call LV2UI_Descriptor::cleanup() as they should, * and may call show() ...
Rust
0
import numpy as np from ContourToMesh import ContourToMesh from GetAreas import GetAreas from meshprocessoutsiderifts import meshprocessoutsiderifts from ProcessRifts import ProcessRifts def meshprocessrifts(md, domainoutline): """meshprocessrifts - process mesh when rifts are present split rifts inside mes...
Python
1
x_read_bytes = fs::read("/tmp/x_com.bytes").expect("Unable to read file"); let x_com: CompressedRistretto; let x_com = CompressedRistretto::from_slice(&x_read_bytes); let proof_read_bytes = fs::read("/tmp/proof-bytes").expect("Unable to read file"); println!("verify - Byte Size = {}",...
Rust
0
plit(|&x| is_word_separator(x)).count(); let char_count = line.iter().filter(|c| c.is_ascii()).count(); (word_count, char_count) } /// Create a [`WordCount`] from a sequence of bytes representing a line. /// /// If the last byte of `line` encodes a newline character (`\n`), /// then...
Rust
0
class Fraction(): def __init__(self, numerator=0, denominator=1): self.numerator = numerator self.denominator = denominator def compute_gcd(x, y): while(y): x, y = y, x % y return x def compute_lcm(x, y): lcm = (x*y) // Fraction.compute_gcd(x, y...
Python
1
lties formatted_song["category"] = song.version return formatted_song def merge_song(self, existing: Dict[str, Any], new: Song) -> Dict[str, Any]: new_song = super().merge_song(existing, new) if existing["difficulties"][new.chart] == 0: new_song["difficulties"][new.chart...
Python
1
{% if token.blood and token.blood == 'Ok' %} match self.execute({{token.name | to_snake}}.as_ref())? { Some(json) => Ok({{token.blood}}::from_json(json)?), None => Err(rtdlib::errors::RTDError::custom(tip::no_data_returned_from_tdlib())), } {% else %} self.send({{token.name | to_snake}}.as...
Rust
0
)] struct MyError { details: String } impl MyError { fn new(msg: &str) -> MyError { MyError{details: msg.to_string()} } } impl fmt::Display for MyError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f,"{}",self.details) } } impl Error for MyError { fn descript...
Rust
0
=> &mut self.development, dependency::DepKind::Build => &mut self.build, } } } #[derive(Debug, Default)] struct DependencyNamesValue { by_extern_crate_name :HashMap<String, InternedString>, by_lib_true_snakecased_name :HashMap<String, HashSet<InternedString>>, by_package_id :HashMap<PackageId, InternedString>...
Rust
0
# import streamlit, pandas and ipyvizzu from streamlit.components.v1 import html import pandas as pd from ipyvizzu import Chart, Data, Config, Style, DisplayTarget def create_chart(): # initialize Chart chart = Chart( width="640px", height="360px", display=DisplayTarget.MANUAL ) # create and ...
Python
1
from selenium.webdriver.common.by import By from appium.webdriver.common.appiumby import AppiumBy class AuthPageLocators: """Locators for authentication page elements""" # Login page elements LOGIN_BUTTON = (By.XPATH, '//XCUIElementTypeButton[@name="Log in / Join Wikipedia"]') USERNAME_FIELD = (By...
Python
1
et of modules Args: model_name (str) - name of model to check module_names (tuple, list, set) - names of modules to search in """ assert isinstance(module_names, (tuple, list, set)) return any(model_name in _module_to_models[n] for n in module_names) def has_model_default_key(model_nam...
Python
1
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
Python
1
''' Kattis - Roman Holidays This is why they said adhoc problems aren't always easy... While no superb optimisation or insane algorithm is needed, it's hard to wrap your head around the new number ordering C.....M,MC...MM ,MMC..............INF.........MMV.....MMXXXVIII, MV,...,MXXXVIII, V... XXXVIII 1 946 947 94...
Python
1