text
string
label_name
string
labels
int64
#!/usr/bin/env python import logging from securitybot.bot import SecurityBot from securitybot.chat.slack import Slack from securitybot.tasker.sql_tasker import SQLTasker from securitybot.auth.duo import DuoAuth from securitybot.sql import init_sql import duo_client CONFIG = {} SLACK_KEY = 'slack_api_token' DUO_INTEGR...
Python
1
='FILENAME', required=False, \ help='Filename to be read. If not supplied, read from stdin.') group = parser.add_mutually_exclusive_group() group.add_argument('-o', '--output', metavar='FILENAME', required=False, \ help='Optional filename into which output will be written. ' \ ...
Python
1
import parakeet from parakeet import jit, testing_helpers, c_backend, config import numpy as np c_backend.print_function_source = True c_backend.print_module_source = True @jit def avg1d(x): return sum(x) / float(len(x)) def test_avg1d(): x = np.random.randn(20) testing_helpers.eq(x.mean(), avg1d(x)) @jit ...
Python
1
ASH.to_string(); let rpc_call_json = get_transaction_receipt_json(&tx_hash) .unwrap(); let reqwest_response = make_rpc_call(WORKING_ENDPOINT, rpc_call_json) .unwrap(); let response_text = get_response_text(reqwest_response) .unwrap(); let rpc_result_st...
Rust
0
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 [ch0ctrl](ch0ctrl) module"] pub type CH0CTRL = crate::Reg<u32, _CH0CTRL>; #[allow(missing_docs)] #[doc(hidden)] pub stru...
Rust
0
1; static tycat_char: int = 2; static tycat_int: int = 3; static tycat_float: int = 4; static tycat_raw_ptr: int = 6; static opcat_add: int = 0; static opcat_sub: int = 1; static opcat_mult: int = 2; static opcat_shift: int = 3; static opcat_rel: int = 4; static opcat_eq: int = ...
Rust
0
from setuptools import setup, find_packages setup( name="TimelineSubWindow", version="1.0.0", description="TimelineSubWindow", author="Ariesta Putra", author_email="ikadekagusariestaputra@gmail.com", url="", packages=find_packages(), entry_points={ "console_scripts": ["TimelineS...
Python
1
b orphan: Option<bool>, pub path_suffix: Option<String>, pub renewable: Option<bool>, pub token_bound_cidrs: Option<Vec<String>>, pub token_explicit_max_ttl: Option<String>, pub token_no_default_policy: Option<bool>, pub token_num_uses: Option<u64>, pub token_period: Option<String>, pub ...
Rust
0
! { //! struct MyFeattles { //! /// Is this usage considered cool? //! is_cool: bool = true, //! /// Limit the number of "blings" available. //! /// This will not change the number of "blengs", though! //! max_blings: i32, //! /// List the actions that should not be a...
Rust
0
ining) # self.linear3 = nn.Linear(256, output_channels) pred = tf_util.fully_connected(features, NUM_CLASSES, bn=False, bias=True, activation_fn=None, scope='linear3', is_training=self.is_training) ret...
Python
1
t_eq!(to_vec::<BE,_>(&test).unwrap(), vec![0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF]); assert_eq!(to_vec::<LE,_>(&test).unwrap(), vec![0xEF, 0xCD, 0xAB, 0x90, 0x78, 0x56, 0x34, 0x12]); } #[test] fn test_i64() { let test: i64 = 0x12345678_90ABCDEF; assert_eq!(to_vec::<BE,_>(&test).unwrap(), vec![...
Rust
0
v, FieldElement::one(), )?; } //Enforce cert_data_hash let cert_data_hash_g = { let wcert_sysdata_hash_g = PoseidonHashGadget::enforce_hash_constant_length( cs.ns(|| "H(sc_id, epoch_number, bt_root, valid_sigs, end_cumulative_sc_tx_comm_tr...
Rust
0
s dbus gtk zeroconf"',), } test_cases = ( ResolverPlaygroundTestCase( ["@world"], options={"--deep": True, "--update": True}, success=True, mergelist=[ "app-text/ghostscript-gpl-10.01.2", ...
Python
1
let (_, listener) = unwrap!(UtpSocket::bind(&addr!("127.0.0.1:0"), &handle)); let listener_addr = unwrap!(listener.local_addr()); let accept_connections = listener .incoming() .into_future() .map_err(|(e, _)| e) .and_then(move |(stream, _incoming)| { ...
Rust
0
e: refund(paid_tinkoff_order, -1) assert "Amount to refund should be more or equal 0" in str(e) @pytest.mark.freeze_time("2032-12-01 15:30Z") def test_set_order_unpaid_and_unshipped(paid_order, refund): refund(paid_order, paid_order.price) paid_order.refresh_from_db() assert paid_order.paid ...
Python
1
# Copyright (c) IBM Corporation # SPDX-License-Identifier: MIT import orchestrator.core import orchestrator.modules.module from ado_ray_tune.config import RayTuneConfiguration from ado_ray_tune.operator import RayTune from orchestrator.core.discoveryspace.space import DiscoverySpace from orchestrator.core.operation.c...
Python
1
ust tolerance as needed name = "Unknown" if True in matches: first_match_index = matches.index(True) name = known_faces_names[first_match_index] else: winsound.Beep(1000, 500) # Beep when an unknown person is detected (Adjust the frequency and duration of the...
Python
1
false); hardcoded.set(0, true); hardcoded.set(1, true); hardcoded.set(3, true); hardcoded.set(4, true); hardcoded.set(7, true); hardcoded.set(10, true); hardcoded.set(14, true); hardcoded.set(15, true); hardcoded.set(21, true); assert_eq!(...
Rust
0
t_comms = &proof.stmt_commitments; let mut fs_rng = FiatShamirRng::<D>::from_seed( &to_bytes![&Self::PROTOCOL_NAME, &index_vk, statement_comms].unwrap(), ); // -------------------------------------------------------------------- // First round let first_comms = &pro...
Rust
0
gpytorch.settings.fast_pred_var(), gpytorch.settings.debug(False): # We're manually going to set the hyperparameters to something they shouldn't be likelihood = GaussianLikelihood(noise_prior=SmoothedBoxPrior(exp(-3), exp(3), sigma=0.1)) gp_model = ExactGPModel(train_x, train_y, lik...
Python
1
| Method::POST => {}, _ => return (None, Out::Bad("Invalid Request")), } if !http::is_host_allowed(&req, &self.allowed_hosts) { return (None, Out::Bad("Disallowed Host header")); } let cors_header = http::cors_allow_origin(&req, &self.cors_domains); if cors_header == http::AllowCors::Invalid { ret...
Rust
0
| IDL_PRIM_int64 | IDL_PRIM_float64 => { buf.advance(8); } IDL_PRIM_text => skip_text(buf), IDL_PRIM_empty => { idl_trap_with("skip_any: encountered empty"); } IDL_REF_principal => { if read_byte_tag(buf) != 0 {...
Rust
0
51189, total_pages_per_node: vec![51189, 123], file_pages: 50175, file_pages_per_node: vec![50175, 123], anon_pages: 1014, anon_pages_per_node: vec![1014, 123], unevictable_pages: 0, unevictable_pages_per_no...
Rust
0
# Copyright 2017 The TensorFlow 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 applica...
Python
1
import re from pydantic import BaseModel, validator class RevertDebtPaymentPOSTResponse(BaseModel): codigoRespuesta: str nombreCliente: str numOperacionERP: str descripcionResp: str @validator('codigoRespuesta') def validate_codigo_respuesta(cls, value): if len(value) != 2: ...
Python
1
macro_rules! with_field { ($(($ident: ident, $name: expr, $bname: expr )),*) => { match field_name { $( $bname => Some(&self.$ident), )* _ => None, } } }; for_field_in_user_extensible!(with_field) } ...
Rust
0
ostname).send().unwrap(); println!("Status: {}", res.status); let dom = parse_document(RcDom::default(), Default::default()).from_utf8().read_from(&mut res).unwrap(); println!("Parsed dom!"); let csslinks = get_css_links(dom.document.clone()); println!("CSS links: {:?}", csslinks...
Rust
0
tions /// /// QPixmap supports a number of functions for creating a new pixmap /// that is a transformed version of the original: /// /// The scaled(), scaledToWidth() and scaledToHeight() functions /// return scaled copies of the pixmap, while the copy() function /// creates a QPixmap that is a plain copy of the origi...
Rust
0
ADME.md")] extern crate self as proto_vulcan; #[macro_use] extern crate proto_vulcan_macros; pub use proto_vulcan_macros::{ compound, lterm, proto_vulcan, proto_vulcan_closure, proto_vulcan_query, }; #[macro_use] extern crate derivative; pub mod compound; use compound::CompoundObject; #[cfg(feature = "debugger...
Rust
0
# # Copyright 2010 Zuza Software Foundation # # This file is part of the Translate Toolkit. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your optio...
Python
1
/// Treat locations with DW_OP_GNU_entry_value as missing in the main file #[structopt(long = "no-entry-value")] no_entry_value: bool, /// Treat locations with DW_OP_GNU_entry_value as missing in the baseline file #[structopt(long = "no-entry-value-baseline")] no_entry_value_baseline: bool, ...
Rust
0
"failed" => Ok(Failed), "dependency" => Ok(Dependency), "skipped" => Ok(Skipped), t @ _ => Err(TaskError::ActionError(format!("Invalid job result {}", t))), } } } #[derive(Debug, Clone)] pub struct SystemdUnit { unit: String, conn: Connection, } impl SystemdUn...
Rust
0
# le script sert à supprimer les portails des pages d'homonymies de Vikidia import pywikibot import mwparserfromhell def has_homonymie(wikicode): for template in wikicode.filter_templates(): if template.name.strip().lower() == "homonymie": return True return False def remove_portail_templ...
Python
1
, rhs)), _ => None } } fn try_fold_bin_long_long<F: Fn (i64, i64) -> MilOperand>(lhs: &MilOperand, rhs: &MilOperand, f: F) -> Option<MilOperand> { match (lhs, rhs) { (&MilOperand::Long(lhs), &MilOperand::Long(rhs)) => Some(f(lhs, rhs)), _ => None } } fn try_fold_bin_long_int<F: Fn ...
Rust
0
Type(423, "Err-32695", "Locked"); pub const FAILED_DEPENDENCY: ErrorType = ErrorType(424, "Err-19693", "Failed Dependency"); pub const UPGRADE_REQUIRED: ErrorType = ErrorType(426, "Err-22991", "Upgrade Required"); pub const PRECONDITION_REQUIRED: ErrorType = ErrorType(428, "Err-02452", "Precondition Require...
Rust
0
#!/usr/bin/python3 import time from picamera2 import Picamera2 from picamera2.encoders import H264Encoder, MJPEGEncoder picam2 = Picamera2() video_config = picam2.create_video_configuration(main={"size": (1280, 720), "format": "RGB888"}, lores={"size": (640, 480), "for...
Python
1
s new on-demand service. pub fn new(checker: Arc<dyn FetchChecker<B>>) -> Self { let (requests_send, requests_queue) = mpsc::unbounded(); let requests_queue = Mutex::new(Some(requests_queue)); OnDemand { checker, requests_queue, requests_send, } } /// Get checker reference. pub fn checker(&self) ...
Rust
0
ogress'] and total_time > 0: now = perf_counter() - start_perf progress = max(0.0, min(100.0, (now / (total_time / max(0.01, self.current_tempo))) * 100)) try: self.playback_callbacks['on_progress'](progress) except ...
Python
1
and=727,1063,4909,1062,1062,1063&text=_mm512_mask_cmpge_epi32) #[inline] #[target_feature(enable = "avx512f")] #[cfg_attr(test, assert_instr(vpcmp))] pub unsafe fn _mm512_mask_cmpge_epi32_mask(m: __mmask16, a: __m512i, b: __m512i) -> __mmask16 { _mm512_cmpge_epi32_mask(a, b) & m } /// Compare packed signed 32-bit ...
Rust
0
ism because of incompatible server ('%s')" % kb.serverHeader) conf.disablePrecon = True if not kb.originalPage and wasLastResponseHTTPError(): errMsg = "unable to retrieve page content" raise SqlmapConnectionException(errMsg) elif wasLastResponseDBMSError(): ...
Python
1
request_body = WorksQuery::build_query(works_query::Variables { publishers }); let res = self.post_request(&request_body).await.await?; let response_body: Response<works_query::ResponseData> = res.json().await?; match response_body.data { Some(data) => Ok(data.works.iter().map(|w| w...
Rust
0
tual_info_score(true_labels, predicted_clusters) # ari = adjusted_rand_score(true_labels, predicted_clusters) # purity = clustering_purity(predicted_clusters, true_labels) # print("Normalized Mutual Information (NMI):", nmi) # print("Adjusted Rand Index (ARI):", ari) # print("Clustering Purity (ACC):", purity) def ...
Python
1
Plot Orig Scale', fig, i) plt.close() def plots_img(eta, render_img, target_img, eta_true, writer, i): res = 64 fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(21., 5.)) # plot ray image ax1.set_title('Model Image') sns.heatmap(render_img.reshape(64, 64).reshape(res, res)[::-1, ::-1].T, ax=ax1) # plot ray ...
Python
1
_ttl(86400) .set_rr_type(RecordType::A) .set_dns_class(DNSClass::IN) .set_rdata(RData::A(Ipv4Addr::new(198, 51, 100, 35))) .clone(), 0, ); authority } #[test] fn test_lookup_ipv4_like() { let authority = create_ip_like_example(); let mut catalog ...
Rust
0
686018427388416, 9), (1066 + INVALID_FP, 9223372036854776832) ); assert_eq!( compute_error_scaled64(0, 4611686018427388928, 9), (1066 + INVALID_FP, 9223372036854777856) ); assert_eq!( compute_error_scaled64(0, 4611686018427389440, 9), (1066 + INVALID_FP, 922337203...
Rust
0
_LENGTH + 3])?; minute = read_u32(&bs[DATE_TIME_FORMAT_MIN_LENGTH + 4..DATE_TIME_FORMAT_MIN_LENGTH + 6])?; second = read_u32(&bs[DATE_TIME_FORMAT_MIN_LENGTH + 7..DATE_TIME_FORMAT_MIN_LENGTH + 9])?; } else { hour = 0; minute = 0; second = 0; } let nano: u32; let t...
Rust
0
(prefetch_table_offset as u64); super_block.set_compressor(ctx.compressor); super_block.set_digester(ctx.digester); if ctx.explicit_uidgid { super_block.set_explicit_uidgid(); } if ctx.source_type == SourceType::StargzIndex { super_block.set_block_size(STA...
Rust
0
"""A simple web server to handle OAuth 2.0 redirects. Partial code taken from google api python client. see: https://code.google.com/p/google-api-python-client/source/browse/oauth2client/tools.py Original author: jcgregorio@google.com (Joe Gregorio) """ import BaseHTTPServer import socket import sys try: from urlpa...
Python
1
: Vec<(usize, usize, G::Scalar)> = Vec::new(); let mut B: Vec<(usize, usize, G::Scalar)> = Vec::new(); let mut C: Vec<(usize, usize, G::Scalar)> = Vec::new(); let mut num_cons_added = 0; let mut X = (&mut A, &mut B, &mut C, &mut num_cons_added); let num_inputs = self.num_inputs(); let num_cons...
Rust
0
vailable languages: {', '.join(result)}"}]} elif name == "get_greeting_for_language": result = get_greeting_for_language(arguments.get("language", "")) return {"content": [{"type": "text", "text": result}]} else: return {"error": f"Unknown tool: {name}"} except Ex...
Python
1
For { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl<'a, I> From<&'a I> for XForwardedFor where &'a I: IntoIterator<Item = &'a IpAddr>, { fn from(ips: &'a I) -> Self { XForwardedFor(ips.into_iter().cloned().collect()) } } impl IntoIterator for XForwardedFor { ...
Rust
0
(p).unwrap(); println!("result: {:?}", t); assert_eq!(t, LINUX_FS); } impl Type { /// Lookup a partition type by uuid pub fn from_uuid(u: &uuid::Uuid) -> Result<Self, String> { let uuid_str = u.to_hyphenated().to_string().to_uppercase(); trace!("looking up partition type guid {}", uuid_...
Rust
0
); let mut query = keywords::table.into_boxed(); if sort == "crates" { query = query.order(keywords::crates_cnt.desc()); } else { query = query.order(keywords::keyword.asc()); } let data = query.paginate(limit, offset).load::<(Keyword, i64)>(&*conn)?; let total = data.get(0).m...
Rust
0
if printer == 'presentation': return MathMLPresentationPrinter(settings).doprint(expr) else: return MathMLContentPrinter(settings).doprint(expr) def print_mathml(expr, printer='content', **settings): """ Prints a pretty representation of the MathML code for expr. If printer is prese...
Python
1
import unittest import torch from torch_xla.core import xla_builder class PythonBackendTest(unittest.TestCase): def test_flatten_func(self): def func_that_takes_dict_and_list(nested_dict, nested_list): return nested_dict['a']['b'] + nested_list[2][3] dict1 = {'a': {'b': 5}} list1 = [0, 0, [0, 0...
Python
1
#!/usr/bin/python # -*- coding:utf-8 -*- import os import re import time from copy import deepcopy import subprocess from data.pdb_utils import Peptide, Protein, merge_to_one_chain from configs import CACHE_DIR from data.pdb_utils import Protein, AgAbComplex, merge_to_one_chain, merge_to_one_protein # def exec_bin(mod...
Python
1
2_EV_W { w: self } } #[doc = "Bits 8:13 - AON_PROG1_EV"] #[inline(always)] pub fn aon_prog1_ev(&mut self) -> AON_PROG1_EV_W { AON_PROG1_EV_W { w: self } } #[doc = "Bits 0:5 - AON_PROG0_EV"] #[inline(always)] pub fn aon_prog0_ev(&mut self) -> AON_PROG0_EV_W { AON_PROG0_EV_...
Rust
0
## aero2_read_all_sensor_data_task_qscope.py # This examples shows how to read data from all the sensors on the Aero2 using task-based (time-based I/O) mode # where you do not have to handle the timing yourself. It also shows how to plot the data in real-time with the # q_scopes library. #------------------------------...
Python
1
# 24 PATRONES DE DISEÑO: DECORADORES # Ejercicio """ Estructura: Se crea una función llamada decorador que toma como argumento a otra función llamada func. Al interior del decorador, se crea otra función que se llama wrapper, que tiene como objetivo “envolver” la función func. Los argumentos de la función wrapper s...
Python
1
&camera as &[_]}); } } } <filename>kernel/src/cpu/gdt.rs use crate::paging::*; pub static mut PTR: DescriptorTablePointer = DescriptorTablePointer { limit: 0, base: 0 }; pub static mut GDT: GlobalDescriptorTable = GlobalDescriptorTable::new(); #[derive(Debug)] #[repr(C, packed)] pub struct DescriptorTable...
Rust
0
pub const UIO_MAXIOV: ::std::os::raw::c_uint = 1024; pub const PF_UNSPEC: ::std::os::raw::c_uint = 0; pub const PF_LOCAL: ::std::os::raw::c_uint = 1; pub const PF_UNIX: ::std::os::raw::c_uint = 1; pub const PF_FILE: ::std::os::raw::c_uint = 1; pub const PF_INET: ::std::os::raw::c_uint = 2; pub const PF_AX25: ::std::os:...
Rust
0
from fastapi import FastAPI from contextlib import asynccontextmanager from database import create_database_if_not_exists import uvicorn from models import Base from database import engine from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine from sqlalchemy.orm import sessionmaker from account_router i...
Python
1
power 2) def main(): x = int(input("what's x?")) print("x squared is:", square(x)) def square(n): return n ** 2 main() # ---------//calculator.py (using pow()) def main(): x = int(input("what's x?")) print("x squared is:", square(x)) def square(n): return pow(n, 2) ...
Python
1
0: raise ValueError("The number of iterations must be a non-negative integer.") if not isinstance(self.num_trial, int) or self.num_trial < 0: raise ValueError("The number of trials must be a non-negative integer.") if not isinstance(self.sample_size, int) or self.sample_size <...
Python
1
# deck.py import random from typing import List, Optional from pigsattack.card import Card class Deck: """Represents the deck of 52 cards, handling shuffling and dealing.""" def __init__(self): self.cards: List[Card] = [] self.discard_pile: List[Card] = [] self._create_deck() se...
Python
1
import os import logging from pathlib import Path from sentence_transformers import SentenceTransformer import torch import numpy as np from typing import List logger = logging.getLogger(__name__) class CustomSentenceTransformerEmbeddings: def __init__(self): current_dir = os.path.dirname(os.path.abspath(_...
Python
1
fn align(mat: &Mat3x3, ax: &Axis) -> Axis { Axis { p: mat.prod_vec(&ax.p), direction: mat.prod_vec(&ax.direction), ref_direction: mat.prod_vec(&ax.ref_direction), } } // TODO: robustize fn get_size_and_origin(axes: &(V3, V3, V3), plane_axes: &[Axis]) -> (V3, V3) { let mut mins = [...
Rust
0
determine when N < 8 (or shift + N < 8); if so, don't consume a byte at all unless N+shift wraps over the byte boundary if shift == 0 { let mut data: GenericArray<u8, Quot<Sum<N, U8>, U8>> = GenericArray::from_iter(repeat(0)); let l = (N::to_usize() + 8) / 8; for i in 0..(l -...
Rust
0
rhs)), Object::Bool(rhs) => Ok(Object::Int(1 - if rhs { 1 } else { 0 })), _ => binary_opr_error_msg!("-", "Bool", rhs.type_name()), }, Object::Bool(lhs) if !lhs => match rhs { Object::Int(rhs) => Ok(Object::Int(-rhs)), Object::Float(rhs) => Ok(Object::F...
Rust
0
rt!(paths.try_migrate_from_newsbeuter()); assert_eq!( &configpaths_helpers::file_contents(&config_dir.join("config")), &sentries.config ); assert_eq!( &configpaths_helpers::file_contents(&config_dir.join("urls")), &sentries.urls ); assert_eq!( &configpaths_h...
Rust
0
Self { owner_id: String::from("__default_value__"), campaigns: UnorderedMap::new(b"__default__".to_vec()), counter: 0, } } } #[near_bindgen] impl Contract { #[init] pub fn new(owner_id: AccountId) -> Self { return Self { owner_id: owner_i...
Rust
0
a = dr.asinh(C(i + 0.1, j)) b = C(cmath.asinh(complex(i + 0.1, j))) assert dr.allclose(a, b) a = dr.acosh(C(i, j)) b = C(cmath.acosh(complex(i, j))) assert dr.allclose(a, b, atol=1e-7) if abs(i) != 1 or j != 0: a = dr.atanh(...
Python
1
} } pub fn read_u8(&self, address: usize) -> u8 { if address >= 0x8000_0000 && address < 0x8180_0000 { return self.mem1[address - 0x8000_0000]; } else if address >= 0x9000_0000 && address < 0x9400_0000 { return self.mem2[address - 0x9000_0000]; } else { ...
Rust
0
_characteristics()?; // Find characteristics for communicating with the cube. There are two different // versions of the GAN cubes with different characteristics. let mut v1_version = None; let mut v1_hardware = None; let mut v1_cube_state = None; let mut v1_last_moves = None; let mut v1_ti...
Rust
0
# Scale offset inversely with distance (closer = more 3D effect) offset = max(5, int(30 / max(distance, 1))) # Draw 3D effect lines # Top face cv2.line(img, (x1, y1), (x1 - offset, y1 - offset), color, 2) cv2.line(img, (x2, y1), (x2 - offset, y1 - offset...
Python
1
w - last_received_message > config.idle: logger.debug( 'Ingress flow %s is idle, processing action %s', buffer, config.action ) await process_action(docker_client, config.action, config.container_labels) await asyncio.sleep(config.cooldown) else: ...
Python
1
meep_port = &env::var("MEEP_PORT").expect("`MEEP_PORT` must be set to run this server"); let save_dir = &env::var("SAVE_DIR").expect("`SAVE_DIR` must be set to run this server"); async_std::fs::create_dir_all(&save_dir).await?; let bind_addr = meep_ip.to_owned() + ":" + &meep_port; let save_dir2 = s...
Rust
0
} } impl std::ops::Add for Orientation { type Output = Self; fn add(self, rhs: Self) -> Self::Output { match (self, rhs) { (Self::Normal, Self::Normal) => Self::Normal, (Self::Normal, Self::Flipped) => Self::Flipped, (Self::Flipped, Self::Normal) => Self::Flippe...
Rust
0
= rand::distributions::LogNormal::new(mean, stddev); gen_rnd_array(shape, dist) } /// Gamma distribution. #[inline] pub fn gamma( shape: &[usize], shape_param: f64, scale: f64, ) -> ndarray::Array<f32, ndarray::IxDyn> { let dist = rand::distributions::Ga...
Rust
0
from discord.ext import commands import discord from datetime import datetime class UserInfo(commands.Cog): def __init__(self, bot): self.bot = bot @commands.hybrid_command(description="Get information about a user.") async def userinfo(self, ctx, user: discord.Member = None): """Get infor...
Python
1
*, events::*, *}, Component, Effects, Node, }; #[derive(Debug, PartialEq, Clone)] pub enum Interaction { Click, Modify(String), } #[derive(Debug, PartialEq)] pub enum Msg { FieldClick, InputChange(String), Interacted(Interaction), } pub struct Field<XMSG> { field_clicks: u32, field_na...
Rust
0
Editor { /// Invert n characters next to the cursor in the buffer. pub fn invert_chars(&mut self, n: usize) { for _ in 0..n { let (x, y) = self.pos(); let current = self.current(); if let Some(cur) = current { self.buffers.current_buffer_mut()[y].rem...
Rust
0
= bytes_from_data(image_data); let input_stream = gio::MemoryInputStream::new_from_bytes(&bytes); let not_cancellable: Option<gio::Cancellable> = None; gdk_pixbuf::Pixbuf::new_from_stream(&input_stream, not_cancellable.as_ref()).unwrap() } /// /// Creates a pixbuf from SVG data /// fn pixbuf_from_svg(i...
Rust
0
t peers_lock = self.p2p.peers.lock().unwrap(); let state = or!(peers_lock.get_mut(&peer), return); logic::handshake::handle_version(&mut self.react, &self.p2p, peer, state, ver); if state.handshake.finished() { drop(state); drop(peers_lock); self.dispatch(Event::Connected(peer)); } return; ...
Rust
0
Bator" => 47.92, 106.92, 1330.; "Ulaanbaatar" => 47.92, 106.92, 1330.; "Vaduz" => 47.13, 9.52, 463.; "Valletta" => 35.9, 14.52, 48.; "Vienna" => 48.2, 16.37, 171.; "Vientiane" => 17.97, 102.6, 171.; "Vilnius" => 54.63, 25.32, 156.; "<NAME>" => 17.33, -61.8, 0.; ...
Rust
0
n = int(input()) #число голосовавших voices = dict() i_max = -1 first_film = '' for i in range(n): name_of_film = input() if voices.get(name_of_film) is None: voices[name_of_film] = 1 else: voices[name_of_film] += 1 if voices[name_of_film] > i_max: i_max = voices[name_of_film] ...
Python
1
new(mut base_msat_arg: u32, mut proportional_millionths_arg: u32) -> RoutingFees { RoutingFees { inner: Box::into_raw(Box::new(nativeRoutingFees { base_msat: base_msat_arg, proportional_millionths: proportional_millionths_arg, })), is_owned: true } } #[no_mangle] pub extern "C" fn RoutingFees_read(ser: crate::c_t...
Rust
0
into a pipeline n_samples, n_features = 50, 3 X, y = make_regression(n_samples, n_features, random_state=0) # pipeline in SFS pipe = make_pipeline(StandardScaler(), LinearRegression()) sfs = SequentialFeatureSelector(pipe, cv=2) sfs.fit(X, y) sfs.transform(X) # SFS in pipeline sf...
Python
1
estoy_ocupado = False # cuando es Cero estoy trabajando cuando es uno estoy ocupado cuarto_oscuro = False # cuando es cero estoy adentro cuando es uno estoy afuera if estoy_ocupado and cuarto_oscuro: print("Estoy trabajando dentro del cuarto oscuro.") elif estoy_ocupado and not cuarto_oscuro: print("Puedes ing...
Python
1
Tag(0x0018, 0x6011), len: Length::UNDEFINED, }, DataToken::ItemStart { len: Length::UNDEFINED, }, DataToken::ElementHeader(DataElementHeader { tag: Tag(0x0018, 0x6012), vr: VR::US, len: Lengt...
Rust
0
.scan(Point { x: 0, y: 0 }, |prev, cmd| { let point: Point = match cmd.chars().nth(0).unwrap() { 'R' => Point { x: prev.x + &cmd[1..].parse::<i64>().unwrap(), y: prev.y, }, 'D' => Point { x: prev.x,...
Rust
0
use rtic::cyccnt::U32Ext; use asm_delay::{bitrate, AsmDelay}; use embedded_hal::digital::v2::OutputPin; use stm32f1xx_hal::{ gpio::gpioa::*, gpio::*, pac, prelude::*, usb::{Peripheral, UsbBus, UsbBusType}, }; use crate::hardware::{ButtonMatrix, ButtonMatrixPins, EncoderPins, Encoders, LedPins,...
Rust
0
edDigestOutput, { fn default() -> Self { Self { outpoint: Outpoint::default(), sequence: 0xffffffff, } } } impl<M> ByteFormat for TxInput<M> where M: MarkedDigestOutput + ByteFormat, { type Error = SerError; fn serialized_length(&self) -> usize { let...
Rust
0
, (85, 400), (0, 255, 0), 3) cv2.rectangle(image, (50, int(vol_bar)), (85, 400), (0, 255, 0), cv2.FILLED) cv2.putText(image, f'{int(vol_per)} %', (40, 450), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 255, 0), 3) def run_keyboard_mode(self, image, hand_landmarks): """حالت کیبورد پیشرفته""" ...
Python
1
continue # Check if this client is opposing party in another case # This is a simplified check - in a real system, you would have a more # comprehensive opposing party tracking system if hasattr(other_case, 'opposing_parties'): for party in other_case.o...
Python
1
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed ...
Python
1
e_values, bins=20, color='skyblue', alpha=0.7, label='Confidence Distribution') # Calculate and plot KDE curve kde = gaussian_kde(confidence_values) x_range = np.linspace(min(confidence_values), max(confidence_values), 100) kde_values = kde(x_range) * len(confidence_values) * (m...
Python
1
"""add oauth devices [f3b3964e3a0f]. Revision ID: f3b3964e3a0f Revises: 3b68abe58f44 Create Date: 2023-10-03 22:06:04.452359 """ import sqlalchemy as sa import sqlmodel from alembic import op # revision identifiers, used by Alembic. revision = "f3b3964e3a0f" down_revision = "3b68abe58f44" branch_labels = None depen...
Python
1
|_MM_FROUND_NO_EXC) // round down, and suppress exceptions /// (_MM_FROUND_TO_POS_INF |_MM_FROUND_NO_EXC) // round up, and suppress exceptions /// (_MM_FROUND_TO_ZERO |_MM_FROUND_NO_EXC) // truncate, and suppress exceptions /// _MM_FROUND_CUR_DIRECTION // use MXCSR.RC; see _MM_SET_ROUNDING_MODE...
Rust
0
.map(|idx| if idx < chars.len() { chars[idx] } else { '0' }) .collect() } /// Ensures that the vector of chars is only 4 chars in length /// /// # Arguments /// /// * chars: Vec<char> - The vector of chars to size.</br> /// /// #Example /// /// ```rust /// use ...
Rust
0