text string | label_name string | labels int64 |
|---|---|---|
exture_id, *matrix, *repeat, new_alpha),
FillState::LinearGradient(_, _, _, _) => self.clone()
}
}
///
/// Updates the fill state with a transformed matrix
///
pub fn transform(&self, transform_matrix: &canvas::Transform2D) -> Self {
let transform_matrix = ... | Rust | 0 |
import base64
import binascii
from datetime import timedelta
from aiogram import Router, F
from aiogram.filters import CommandStart, StateFilter, Command
from aiogram.types import Message, CallbackQuery
from infrastructure.database.repo.requests import RequestsRepo
from tgbot.filters.admin import AdminFilter
from tg... | Python | 1 |
await execute_sql(sql)
admins = list(chain.from_iterable(data))
return admins
async def update_setting(group_id: int, setting_name: str, new_setting_value) -> None:
"""
Update setting to database
Args:
group_id: Group id
setting_name: Setting name
new_setting_value: New se... | Python | 1 |
hungry\n'
'</example>\n'
'<example>\n'
'Antoine is thirsty. Yann is tired. Yann went back to the bedroom. Yann picked up the pajamas there.'
'Jason is thirsty. Antoine went back to the kitchen. Why did antoine go to the kitchen?\n'
'Answer: thirsty\n'
... | Python | 1 |
84),
City::new(10578, "Norway", "Moss", 59.434091, 10.658383, 18.12),
City::new(10579, "Norway", "Haugesund", 59.413581, 5.267987, 15.47),
City::new(10580, "Norway", "Arendal", 58.461757, 8.77245, 19.22),
City::new(10581, "Norway", "Sandefjord", 59.13131, 10.216595, 12.22),
City::new(10582, "Norway", "Bodø", 67.28... | Rust | 0 |
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_consume_0(... | Rust | 0 |
import os
import torch
import numpy as np
# Dataset directory
DATA_DIR = r"C:\\Users\\prajw\\Desktop\\docs\\All Projects\\EEG\\Bon"
# Output directory for processed data
OUTPUT_DIR = r"C:\\Users\\prajw\\Desktop\\docs\\All Projects\\EEG\\EEG-Analysis-Chatbot\\processed_data\\Bon_UKB"
# Mapping of subdirectories to lab... | Python | 1 |
import json
import os
import requests
import numpy as np
import wave
import io
import logging
import pygame
import soundfile as sf
from time import time as ttime
from pygame import mixer
from Synthesizers.base import Base_TTS_Synthesizer, Base_TTS_Task
from importlib import import_module
from src.common_config_manager ... | Python | 1 |
ips64 => {
// copied from `mips64el-linux-gnuabi64-gcc foo.c -c`
let e_flags = elf::EF_MIPS_CPIC
| elf::EF_MIPS_PIC
| if sess.target.options.cpu.contains("r6") {
elf::EF_MIPS_ARCH_64R6 | elf::EF_MIPS_NAN2008
} else {
... | Rust | 0 |
, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fmt::{Debug, Formatter};
use std::fs;
use std::fs... | Rust | 0 |
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class TestContactUsForm:
@pytest.fixture()
def setup_teardown(self):
self.driver = webdriv... | Python | 1 |
ction
if hasattr(app.style(), 'darkMode'):
dark_mode = app.style().darkMode()
else:
# Default to dark mode if can't detect
dark_mode = True
viewer = TopologyViewer(dark_mode=dark_mode)
viewer.show()
screen_geometry = app.primaryScreen().availableGeometry()
# Calculate t... | Python | 1 |
def main():
tiempo = input("What time is it? ")
result = convert(tiempo)
if 7 <= result <= 8:
print("breakfast time")
elif 12 <= result <= 13:
print("lunch time")
elif 18 <= result <= 19:
print("dinner time")
else:
print("Well, nothing to eat yet")
def convert(t... | Python | 1 |
pool: &Mempool, asset_id: &sha256d::Hash) -> AssetStats {
let mut stats = AssetStats::default();
if let Some(history) = mempool.asset_history.get(asset_id) {
let mut seen_txids = HashSet::new();
for info in history {
apply_asset_stats(info, &mut stats, &mut seen_txids)
}
... | Rust | 0 |
from dataclasses import dataclass, field
if __name__ == "__main__":
@dataclass
class Wrapper:
dict_: dict[str, int] = field(default_factory=dict)
set_: set[int] = field(default_factory=set)
list_: list[int] = field(default_factory=list)
dict_a = {"a": 1, "b": 2, "c": 3}
set_a ... | Python | 1 |
as usize
])
.build(
ImageState {
queue,
stage: hal::pso::PipelineStage::TRANSFER,
access: hal::image::Access::TRANSFER_WRITE,
layout: hal::image::Layout::TransferDstOptimal,
},
... | Rust | 0 |
#!/usr/bin/env python3
def showbanner():
print('''
██████ ██▓ █████▒▄▄▄█████▓▓█████ ██▀███
▒██ ▒ ▓██▒▓██ ▒ ▓ ██▒ ▓▒▓█ ▀ ▓██ ▒ ██▒
░ ▓██▄ ▒██▒▒████ ░ ▒ ▓██░ ▒░▒███ ▓██ ░▄█ ▒
▒ ██▒░██░░▓█▒ ... | Python | 1 |
specific to slash commands.
mod argument;
pub use argument::*;
mod track_edits;
pub use track_edits::*;
mod structs;
pub use structs::*;
use core::mem::size_of;
use castflip::{Flip, NE, SE, LE, BE};
use crate::{IData1, UData1};
macro_rules! test {
( $data:expr, $field:ident, $ty:ty ) => {{
{
let data =... | Rust | 0 |
# Generated by Django 5.0 on 2024-02-22 04:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('user', '0018_alter_register_gender'),
]
operations = [
migrations.AlterField(
model_name='register',
name='gender',
... | Python | 1 |
k = Some(i);
anchor_pt = in_pt;
anchor_len = in_len;
}
let d = (in_pt.x * out_pt.x) + (in_pt.y * out_pt.y);
let shift_pt = if d > -0.9375 {
let d = d + 1.0;
le... | Rust | 0 |
Type == SyncType::SyncData {
true
} else {
false
};
let ret = if URING_ENABLE && self.InodeOp.InodeType() == InodeType::RegularFile {
IOURING.Fsync(task,
fd,
datasync
)
} else {
... | Rust | 0 |
F)>,
#[pin]
state: State<SF, Fut, S, Req>,
}
}
pin_project! {
#[project = StateProj]
enum State<SF, Fut, S, Req>
where
SF: ServiceFactory<Req, Config = ()>,
SF::InitError: From<SF::Error>,
Fut: Future<Output = Result<S, SF::InitError>>,
S: Service<Req>,
... | Rust | 0 |
# Create a NewSource folder, with the folders rearranged to our new folder
# structure
# Ensure you have already created a dupliate Source folder
#(run 1CopyFolderContents.py)
# Import Python Libraries
import arcpy, os, sys, shutil
from arcpy import env
python = "C:\Users\edwhitfi\Desktop\Python"
boundary = "C:\User... | Python | 1 |
// SAFETY: old is read from current RCU.
let cloned_old = unsafe { (*old).clone() };
if let Some(x) = new.as_mut() {
*x.as_mut() = cloned_old;
} else {
new = Some(Box::new(cloned_old));
... | Rust | 0 |
# -*- coding: utf-8 -*-
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from langchain.base_language import BaseLanguageModel
from app.schemas.agent_schema import AgentConfig
from app.services.chat_agent.tools.library.sql_tool.sql_tool import SQLTool
from tests.fake.sql_db import FakeDBInfo, FakeS... | Python | 1 |
execute_never: true,
},
},
TranslationDescriptor {
name: "DMA heap pool",
virtual_range: dma_range_inclusive,
physical_range_translation: Translation::Identity,
attribute_fields: AttributeFields {
mem_attributes:... | Rust | 0 |
src.vulkan_memory_model);
dst.vulkan_memory_model_device_scope = vk_to_raw_value(&src.vulkan_memory_model_device_scope);
dst.vulkan_memory_model_availability_visibility_chains = vk_to_raw_value(&src.vulkan_memory_model_availability_visibility_chains);
}
}
impl VkRawType<VkPhysicalDeviceVulkanMemory... | Rust | 0 |
}
pub fn to_angles(&self) -> (f32, f32, f32) {
unsafe {
let mut deg_x = mem::MaybeUninit::uninit();
let mut deg_y = mem::MaybeUninit::uninit();
let mut deg_z = mem::MaybeUninit::uninit();
graphene_sys::graphene_quaternion_to_angles(
self.... | Rust | 0 |
&variant.ident.to_string()),
};
match (&enum_attr.tag, &enum_attr.content, &enum_attr.untag) {
(_, Some(_), true) => panic!("Untagged enums cannot have content tags"),
(Some(_), _, true) => panic!("Untagged enums cannot have tags"),
_ => {}
};
let inline_type = type_def(&name, ... | Rust | 0 |
impl NullDecoder {
pub fn new() -> NullDecoder {
NullDecoder {}
}
}
impl AddressDecoder for NullDecoder {
fn decode(&self, target: usize, _mask: &Mask) -> Vec<usize> {
vec![target]
}
}
#[cfg(test)]
mod tests {
use super::*;
use proptest::prelude::*;
proptest! {
#... | Rust | 0 |
import html
import json
import re
import pytest
from django.contrib.contenttypes.models import ContentType
from adhocracy4.test import helpers
def react_reports_render_template(template, rf, question):
request = rf.get("/")
template = "{% load react_reports %}" + template
context = {"request": request, ... | Python | 1 |
ighbourhood code.
"""
spacing_mm = ensure_tuple_rep(spacing_mm, 2)
first, second = spacing_mm # spacing along the first and second spatial dimension respectively
diag = 0.5 * np.linalg.norm(spacing_mm)
neighbour_code_to_contour_length = np.zeros([16], dtype=diag.dtype)
neighbour_code_to_contou... | Python | 1 |
send_message(f"""Welcome to ShopAI. I am a AI Assisstant and I will help you to find best outfit from flipkart ph no. +91{user_phone}. Let's start with normal questionarrie: \n\n What's your age ?""")
elif message=="clear":
clear()
return send_message("New Session Started: I am ready to... | Python | 1 |
from flask import Flask, jsonify, request, redirect
import os
app = Flask(__name__)
# Shopify OAuth
SHOPIFY_API_KEY = os.getenv('SHOPIFY_API_KEY', 'your_api_key')
SHOPIFY_API_SECRET = os.getenv('SHOPIFY_API_SECRET', 'your_api_secret')
SHOPIFY_REDIRECT_URI = os.getenv('SHOPIFY_REDIRECT_URI', 'https://profitpeek-dashbo... | Python | 1 |
)
# Bottom area
######################################################################
def _renderBottom(self) -> None:
links = [
["O", "opts", tr.actions_options()],
]
is_dyn = self.mw.col.decks.current()["dyn"]
if is_dyn:
links.append(["R", "refres... | Python | 1 |
#!/usr/bin/env python3
# Copyright (C) 2019 Checkmk GmbH - License: GNU General Public License v2
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
# conditions defined in the file COPYING, which is part of this source code package.
from collections.abc import Mapping, Sequence
imp... | Python | 1 |
assert res.status_code == 200, err_msg
def test_cors(self):
"""Test CORS decorator works."""
res = self.app.options('/api/project/1',
headers={'Access-Control-Request-Method': 'GET',
'Access-Control-Request-Headers': 'Authorizat... | Python | 1 |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD 3-Clause license found in the
# LICENSE file in the root directory of this source tree.
from enum import Enum
# can switch to StrEnum (https://docs.python.org/3/library/enum.html#enum.StrEnum)
#... | Python | 1 |
#!/usr/bin/env python3
"""
function that
calculates the intersection of obtaining
this data with the various hypothetical
probabilities
"""
import numpy as np
likelihood = __import__('0-likelihood').likelihood
def intersection(x, n, P, Pr):
"""
x is the number of patients that develop side effects
n is ... | Python | 1 |
}
(cidx, gcount)
}
fn cidx_gidx_from_global_x(
slice: &RopeSlice,
global_x: usize,
tab_width: usize,
past_end: bool,
) -> (usize, usize) {
let (mut gidx, mut ccount) = (0, 0);
let mut len_chars = slice.len_chars();
if !past_end && len_chars > 0 {
len_chars -= 1;
}
for... | Rust | 0 |
import requests
from bs4 import BeautifulSoup
import pandas as pd
def main():
books = []
for i in range(1, 16):
url = f"https://books.toscrape.com/catalogue/page-{i}.html"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
ol = soup.find('ol')
... | Python | 1 |
that does not require compatibility with older versions of
Tornado should use
``twisted.internet.asyncioreactor.install()`` directly.
.. versionchanged:: 6.0.3
In Tornado 5.x and before, this function installed a reactor
based on the Tornado ``IOLoop``. When that reactor
... | Python | 1 |
lonpr::R](us_lonpr::R) reader structure"]
impl crate::Readable for US_LONPR {}
#[doc = "`write(|w| ..)` method takes [us_lonpr::W](us_lonpr::W) writer structure"]
impl crate::Writable for US_LONPR {}
#[doc = "LON Preamble Register"]
pub mod us_lonpr;
#[doc = "LON Data Length Register\n\nThis register you can [`read`](c... | Rust | 0 |
... @attribute height numeric
... @attribute color {red,green,blue,yellow,black}
... @data
... 5.0,3.25,blue
... 4.5,3.75,green
... 3.0,4.00,red
... \"\"\"
>>> f = StringIO(content)
>>> data, meta = arff.loadarff(f)
>>> data
array([(5.0, 3.25, 'blue'), (4.5, 3.75, 'green'), (3.... | Python | 1 |
from yacs.config import CfgNode as CN
_C = CN()
# Drug feature extractor
_C.DRUG = CN()
_C.DRUG.NODE_IN_FEATS = 75
_C.DRUG.PADDING = True
_C.DRUG.HIDDEN_LAYERS = [128, 128, 128]
_C.DRUG.NODE_IN_EMBEDDING = 128
_C.DRUG.MAX_NODES = 290
# Protein feature extractor
_C.PROTEIN = CN()
_C.PROTEIN.NUM_FILTERS = [128, 128,... | Python | 1 |
use plist::Value;
use crate::tables::LaunchdOverridesRow;
impl LaunchdOverridesRow {
pub fn get_specific() -> Vec<LaunchdOverridesRow> {
LaunchdOverridesRow::get_specific_ex().unwrap_or(Vec::new())
}
pub fn get_specific_ex() -> Result<Vec<LaunchdOverridesRow>, String> {
let mut out = Vec:... | Rust | 0 |
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature
def plot_lines_comparison(lines_in_germany_original, lines_in_germany):
"""
Create a Cartopy plot comparing original and straightened network lines.
"""
fig, axes = plt.subplots(1, 2, figsize=(20, 10),
... | Python | 1 |
geWall,
StrangeWall,
// 128
Pendulum, Pendulum, Pendulum, Pendulum, Stocks, Manacles, Grate, Archway,
Cannonballs, Grave, Gravestone, Rack, Trapdoor, Harpsichord, Guillotine,
Lava,
// 144
Chair, Chair, Chair, Chair, Table, Table, Table, MagicDoor,
MagicWindowDoor, Portcullis, TableWith... | Rust | 0 |
from .repositories import UserRepository
class UserService():
def __init__(self):
self.user_repository = UserRepository()
def get_user_by_id(self, user_id):
return self.user_repository.get_user_by_id(user_id)
def create_user(self, name, family_name, email, photo_url):
try:
... | Python | 1 |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# Load the data
data = pd.read_table("ncl.dat", delim_whitespace=True, header=None, names=["Year", "Claim_Count", "Claim_Amount"])
# Adjust the year by adding 1990
data["Year"] = data["Year"] + 1990
# Divide the third column... | Python | 1 |
h.tensor(y_test_eeg).cpu().numpy()
y_test_pred_classes_cpu = y_test_pred_classes.cpu().numpy()
precision = precision_score(y_test_cpu, y_test_pred_classes_cpu, average=None)
precision = 0 if any(element <= 0.1 for element in precision) else 1
f1 = f1_score... | Python | 1 |
(len(instances), len(prev_instances)), LARGE_COST_VALUE)
return self.assign_cost_matrix_values(cost_matrix, bbox_pairs)
def assign_cost_matrix_values(self, cost_matrix: np.ndarray, bbox_pairs: List) -> np.ndarray:
"""
Based on IoU for each pair of bbox, assign the associated value in cost m... | Python | 1 |
("ecl", ecl),
("pid", pid),
];
let bad_fields: Vec<&str> = bad_fields
.into_iter()
.filter_map(|(f, ok)| if ok { None } else { Some(f) })
.collect();
Err(format!("{}\nBAD: {}\n", passport, bad_fields.join(" ")).to_str... | Rust | 0 |
pub fn lua_yieldk(
L: *mut lua_State,
nresults: ::std::os::raw::c_int,
ctx: lua_KContext,
k: lua_KFunction,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn lua_resume(
L: *mut lua_State,
from: *mut lua_State,
narg: ::std::os::raw::c_int,
nres... | Rust | 0 |
ce~gameReport'
response = self.do_request(url, data=json_data)
# print(response)
stu = response.get('success')
if stu:
gameNum = response.get('obj')['gameNum']
print(f'>大冒险成功!剩余次数【{gameNum}】')
time.sleep(2)
g... | Python | 1 |
# Sets Methods
s = {1, 3, 5, 7, 9}
# add() method
s.add(4)
print('Add Method', s)
# remove() method
s.remove(3)
print('Remove Method',s)
# discard() method
s.discard(5)
print('Discard Method', s)
# pop() method
s.pop()
print('Pop Method:', s)
# clear() method
s.clear()
print('Clear Method', s)
# del keyword
del... | Python | 1 |
max127-i2c-6-28 data".format(key),
)
def test_max127_sensor_data_1V_Voltage_range(self):
result = self.get_parsed_result()
value = result["+1 Voltage"]
# '+12.23 V' extract 12.23 form it
value = value.split("+")[1].split(" V")[0]
self.assertAlmostEqual(
... | Python | 1 |
pture</button>
</div>
<!-- Alerts -->
<div id="alert-success" class="alert alert-success">
<strong>Success!</strong> <span id="alert-success-message"></span>
</div>
<div id="alert-error" class="alert alert-error">
... | Python | 1 |
his option will validate the Host header sent by the browser, it is additional security against some attack vectors. Special options: \"all\", \"none\".",
ARG arg_ws_max_connections: (usize) = 100usize, or |c: &Config| c.websockets.as_ref()?.max_connections,
"--ws-max-connections=[CONN]",
"Maximum number of a... | Rust | 0 |
: 5,
};
let js_value = serde_wasm_bindgen::to_value(&request).unwrap();
let bbs_res = bls_to_bbs_key(js_value);
assert!(bbs_res.is_ok());
let bbs = bbs_res.unwrap();
assert!(bbs.is_object());
let public_key_res = serde_wasm_bindgen::from_value::<BbsKeyPair>(bbs);
assert!(public_key_res.i... | Rust | 0 |
NULLBYTES16.as_mut_ptr() as *const libc::c_void,
16,
) != 0
{
return memcmp(
cdata1.checksum.as_ptr() as *const libc::c_void,
cdata2.checksum.as_ptr() as *const libc::c_void,
16,
);
}
... | Rust | 0 |
.#..#.|.....#.
3 .#..#.|#......
4 .#..#.|#......
5 .#....|#......
6 .#~~~~~#......
7 .#######......
8 ..............
9 ..............
10 ....#.....#...
11 ....#.....#...
12 ....#.....#...
13 ....#######..."
);
}
#[test]
fn water_flowed_11_times() {
let mut ground = Ground::from(read_... | Rust | 0 |
ensor(q_list)
# [Batch_size, topK, max_d_len]
doc_tensor = torch.LongTensor(d_list)
return {'q_tensor': q_tensor,
'doc_tensor': doc_tensor,
'ce_tensor': ctx_tensor_out,
'q_tensor_mask': (q_tensor != 0).long(),
'doc_tensor_mask': (d... | Python | 1 |
# -*- coding: utf-8 -*-
{
'name': 'Lunch',
'sequence': 300,
'version': '1.0',
'depends': ['mail'],
'category': 'Human Resources/Lunch',
'summary': 'Handle lunch orders of your employees',
'description': """
The base module to manage lunch.
================================
Many companies or... | Python | 1 |
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let hex = self.red as u32 * 256 * 256 + self.green as u32 * 256 + self.blue as u32;
write!(f, "#{:x}", hex)
}
}
impl FromStr for Rgb {
type Err = YeeError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let val = match s.... | Rust | 0 |
self) -> ADC_IM_MASK3R {
let bits = ((self.bits >> 3) & 1) != 0;
ADC_IM_MASK3R { bits }
}
#[doc = "Bit 8 - SS0 DMA Interrupt Mask"]
#[inline(always)]
pub fn adc_im_dmamask0(&self) -> ADC_IM_DMAMASK0R {
let bits = ((self.bits >> 8) & 1) != 0;
ADC_IM_DMAMASK0R { bits }
... | Rust | 0 |
array(mut self, a: NdArray) -> TensorBuilder
{
self.persistent_array = Some(PersistentArray::Constant(a));
self
}
#[inline]
pub fn set_variable_array(mut self, a: NdArray) -> TensorBuilder
{
self.persistent_array = Some(PersistentArray::Variable(a));
self
}
... | Rust | 0 |
"))]
/// let raw_fd: RawFd = f.as_raw_fd();
/// # Ok::<(), io::Error>(())
/// ```
fn as_raw_fd(&self) -> RawFd;
}
/// A trait to express the ability to construct an object from a raw file
/// descriptor.
pub trait FromRawFd {
/// Constructs a new instance of `Self` from the given raw file
/// d... | Rust | 0 |
cm2pdm_conv_en(&self) -> I2S_PCM2PDM_CONV_EN_R {
I2S_PCM2PDM_CONV_EN_R::new(((self.bits >> 25) & 0x01) != 0)
}
#[doc = "Bit 24"]
#[inline(always)]
pub fn i2s_tx_pdm_dac_mode_en(&self) -> I2S_TX_PDM_DAC_MODE_EN_R {
I2S_TX_PDM_DAC_MODE_EN_R::new(((self.bits >> 24) & 0x01) != 0)
}
#... | Rust | 0 |
-2.0
//! A stack
use std::fmt::Debug;
use std::ops::{Index, IndexMut};
use kas::{event, prelude::*};
/// A stack of boxed widgets
///
/// This is a parametrisation of [`Stack`].
pub type BoxStack<M> = Stack<Box<dyn Widget<Msg = M>>>;
/// A stack of widget references
///
/// This is a parametrisation of [`Stack`].
... | Rust | 0 |
#Add up all the numbers in an Array using recursion
#Count the elements in an Array using Recursion
#Find the Maximum Number in a list
def sum(arr):
#BaseCase
if len(arr) ==0:
return 0
else:
#RecursiveCase
return arr[0]+sum(arr[1:])
def count(arr):
#Base Case
if arr==[]:
return 0;
else:
#R... | Python | 1 |
[cfg(not(feature = "webgl"))]
power_preference: PowerPreference::HighPerformance,
#[cfg(feature = "webgl")]
power_preference: PowerPreference::LowPower,
compatible_surface: surface.as_ref(),
force_fallback_adapter: false,
})
.await
.exp... | Rust | 0 |
up("SIKEp434 KEM (opti)");
let (s, sk3, pk3) = kem.keygen().unwrap();
let (c, _k) = kem.encaps(&pk3).unwrap();
let _k_recovered = kem.decaps(&s, &sk3, &pk3, c.clone()).unwrap();
group.bench_function("Keygen", |b| b.iter(|| kem.keygen()));
group.bench_function("Encapsulation", |b... | Rust | 0 |
Poll events, return the amount read. This drains events from the queue.
pub fn recv_events(&mut self, out: &mut [PtraceEvent]) -> usize {
let len = cmp::min(out.len(), self.events.len());
for (dst, src) in out.iter_mut().zip(self.events.drain(..len)) {
*dst = src;
}
len
... | Rust | 0 |
) -> glib::Source + Send + 'static,
{
type Item = T;
type Error = Never;
fn poll(&mut self, ctx: &mut Context) -> Result<Async<T>, Never> {
let SourceFuture {
ref mut create_source,
ref mut source,
..
} = *self;
if let Some(create_source) = creat... | Rust | 0 |
::SecureRandom)
-> Result<(Ed25519KeyPair, Ed25519KeyPairBytes),
error::Unspecified> {
let mut bytes = Ed25519KeyPairBytes {
private_key: [0; 32],
public_key: [0; 32],
};
try!(rng.fill(&mut bytes.private_key));
unsafe {
... | Rust | 0 |
'''
Object :
45. Write a program to print the following pattern
1
2 3
4 5 6
7 8 9 10
'''
k = 1
for i in range(5):
for j in range(i + 1):
print(k, end=' ')
k = k + 1
print() | Python | 1 |
::SeqCst); // increment 1
// }
// gap if gap > 0 => {
// // maybe it's unlikely to happen
// ();
// }
// gap if gap < 0 => {
// // nonce has changed
// signer_current_nonce.swap(current_nonce, Ordering::Relaxed);
// atomic_nonce.swap(0, Ordering::Relaxed);
// }
// _ => (),
// }
// if trade success, ch... | Rust | 0 |
: Patch = Patch{ offset: 7, length: 5 };
pub const SHAMT: Patch = Patch{ offset: 20, length: 5 };
pub const FUNCT3: Patch = Patch{ offset: 12, length: 3 };
pub const RS1: Patch = Patch{ offset: 15, length: 5 };
pub const RS2: Patch = Patch{ offset: 20, length: 5 };
pub const FUNCT7: Patch = Patch{ offset: 25, length: 7... | Rust | 0 |
sage: from sage.rings.algebraic_closure_finite_field import AlgebraicClosureFiniteField_pseudo_conway
sage: F = AlgebraicClosureFiniteField_pseudo_conway(GF(5), 'z')
sage: F._get_im_gen(2, 4)
z4^3 + z4^2 + z4 + 3
"""
p = self.characteristic()
if m == 1:
... | Python | 1 |
which allows us to avoid computing any U_k values.
// Jacobsen points out that maybe we should just do the full extra strong test:
// "It is also possible to recover U_n using Crandall and Pomerance equation 3.13:
// U_n = D^-1 (2V_{n+1} - PV_n) allowing us to run the full extra-strong test
// at the c... | Rust | 0 |
ize,
db: MongoDb,
#[cfg(feature = "metrics")] counter: bee_metrics::metrics::counter::Counter,
) -> Self {
Self {
id,
db,
#[cfg(feature = "metrics")]
counter,
}
}
}
impl std::fmt::Debug for Solidifier {
fn fmt(&self, f: &mut st... | Rust | 0 |
::string(substr))
}
pub fn string_fill(vm: &mut Vm) -> Result<VCell, Error> {
let argc = pop_argc(vm, 2, Some(4), "string-fill")?;
let end = match argc {
4 => Some(pop_index(vm, "string-fill")?),
_ => None,
};
let start = match argc {
3 | 4 => Some(pop_index(vm, "string-fill")... | Rust | 0 |
_x8, set_bl:set_x8 ],
[ RCX:u8 => get_cl:get_x8, set_cl:set_x8 ],
[ RDX:u8 => get_dl:get_x8, set_dl:set_x8 ],
[ RSI:u8 => get_sil:get_x8, set_sil:set_x8 ],
[ RDI:u8 => get_dil:get_x8, set_dil:set_x8 ],
[ RBP:u8 => get_bpl:get_x8, set_bpl:set_x8 ],
[ RSP:u8 => get... | Rust | 0 |
"""MCP Resources Package.
This package provides the MCP resource framework for consolidating list-type functions
into standardized MCP resources with backward compatibility.
"""
from .base import MCPResource, ResourceResponse, ResourceRegistry
from .admin import AdminUsersResource, AdminRolesResource
from .s3 import ... | Python | 1 |
TryFrom<String> for PassportID {
type Error = PassportParseError;
fn try_from(input: String) -> Result<Self, Self::Error> {
if PID_REGEX.is_match(&input) {
Ok(Self(input))
} else {
Err(PassportParseError::BadStringFormat)
}
}
}
#[derive(Debug, Deserialize)]
... | Rust | 0 |
"""
ISO_C_BINDING maps for f2py2e.
Only required declarations/macros/functions will be used.
Copyright 1999 -- 2011 Pearu Peterson all rights reserved.
Copyright 2011 -- present NumPy Developers.
Permission to use, modify, and distribute this software is given under the
terms of the NumPy License.
NO WARRANTY IS EXPR... | Python | 1 |
time01.zip', formats=['dicom'])
# Now ask for non-existing and existing file
# transport = S3Transport(
# netloc=host,
# root='/{}'.format(bucket),
# opts={
# 'username': access_key,
# 'password': secret_key
# }
# )
... | Python | 1 |
18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
]).0;
check(
&enc_keys,
&[
[0x0001020304050607, 0x08090a0b0c0d0e0f],
[0x1011121314151617, 0x18191a1b1c1d1e1f],
[0xa573c29fa176c498, 0xa97fce93a572c09c],
[0x1651a8cd0244beda, 0x1a5da4c10640bade],
... | Rust | 0 |
; 4] = &["error", "warn", "info", "debug"];
const FILE_TOML_EXTENSION: &'static str = "toml";
const FILE_JSON_EXTENSION: &'static str = "json";
pub fn from_file<P: AsRef<Path>>(path: P) -> ConfigResult<Self> {
let config_file_content = read_file(&path)?;
let config_file_extension = path.as_... | 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 |
# Stability Analysis
# YouTube: https://youtu.be/Y2BxAQxa0Vo
# thanks to Nikos Papadakis for the root locus slider bar
import math
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtons
# open loop
num = [4.0]
den = [1.0,6.0,11.0,6.0]
def dcl(K):
return [1.0,... | Python | 1 |
s[i+1]
first_player_shot = len(list(filter(lambda x: x[0] > lower and x[0] <= upper, first_player_xgs)))
second_player_shot = len(list(filter(lambda x: x[0] > lower and x[0] <= upper, second_player_xgs)))
first_player_shots.append(first_player_shot)
second_player_shots.append(second_player_shot)
fi... | Python | 1 |
from modules.core_files import read_file, update_file, clear_screen, pause_screen
def agregar_activos():
inventario = read_file('inventario.json')
data=[]
from csv import reader
with open("data/activos2.csv","r") as file:
lector=reader(file)
for row in lector:
data.append(ro... | Python | 1 |
redData {
data: HashMap<(TypeId, String), Rc<dyn Any>>,
}
impl SharedData {
fn new() -> SharedData {
SharedData {
data: HashMap::new(),
}
}
pub fn get<T: Any>(name: &str) -> Option<Rc<T>> {
// Check if the shared data exists
let res = SHARED_DATA.with(|sd| {
if let Some(v) = sd.borrow().data.get(&(... | Rust | 0 |
r path tracing
#[derive(Debug)]
pub struct PTCamera {
camera: Camera,
flash: PointLight,
}
impl PTCamera {
pub fn new(camera: Camera) -> Self {
// TODO: allow dynamic intensity and speed
let intensity = 10.0 * camera.scale.powf(1.4) * Color::white();
let flash = PointLight::new(came... | Rust | 0 |
from .fpn import *
# First import each network, and then import helper function.
from .base_neck import build_vision_neck
| Python | 1 |
ul-native-table-row-numbers .__azul-native-table-row
//
// |-> div.__azul-native-table-column-container
// |-> div.__azul-native-table-column (Column 1 ...)
// |-> div.__azul-native-table-column-name
// '-> div.__azul-native-table-row
// '-> di... | Rust | 0 |
# -*- coding: UTF-8 -*-
#!/usr/bin/python
import requests
def vuln_info():
info={
'vuln_name': 'templalte filewrite', #漏洞名称
'vuln_referer':'未知', #漏洞来源
'vuln_author':'未知', #插件作者
'cms_name':'test',#cms_name需要和上级目录保持一致。扫描器自动添加会调用。GUI版本不会调用
'vuln_description':'''漏洞描述''',
... | Python | 1 |
from . import connector
from ..base import (
ClickHouseDialect, ClickHouseExecutionContextBase, ClickHouseCompiler,
)
# Export connector version
VERSION = (0, 0, 2, None)
class ClickHouseExecutionContext(ClickHouseExecutionContextBase):
def pre_exec(self):
# Always do executemany on INSERT with VALU... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.