text string | label_name string | labels int64 |
|---|---|---|
e_event(),
nvic::I2C1_ER => self.i2c1.handle_error(),
nvic::SPI3 => self.spi3.handle_interrupt(),
nvic::EXTI0 => self.exti.handle_interrupt(),
nvic::EXTI1 => self.exti.handle_interrupt(),
nvic::EXTI2 => self.exti.handle_interrupt(),
nvic::EXTI3 =... | Rust | 0 |
import time
import schedule
import pickle
import os
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support imp... | Python | 1 |
, end_context: None }
}
}
thread_local! {
#[doc(hidden)]
static PARSE_TREE: RefCell<Tree<Info>> = RefCell::new(Tree::new());
}
fn debug_print(sibling_map: &mut Vec<bool>, node: Index) {
let parent_count = sibling_map.len();
for (i, &has_siblings) in sibling_map.iter().enumerate() {
if i < ... | Rust | 0 |
ple2() {
let test_result = vec![
HandEggScore::new(0, 1, 7),
HandEggScore::new(0, 3, 4),
HandEggScore::new(0, 5, 1),
HandEggScore::new(1, 0, 5),
HandEggScore::new(1, 2, 2),
HandEggScore::new(2, 1, 0),
];
let score = find_score(17);
assert_eq!(test_result, score);
}
#[test]
fn test_same_... | Rust | 0 |
# 测试
# 开发时间:2023/3/7 15:17
#!/usr/bin/env python3
import os
import torch
import torch.nn as nn
import torch.utils.cpp_extension as cpp_extension
# import _depthwise_conv2d_implicit_gemm_C as _extension
__all__ = ["DepthWiseConv2dImplicitGEMM"]
class _DepthWiseConv2dImplicitGEMMFP32(torch.autograd.Function):
@... | Python | 1 |
Convenience function for getting JSON from return string via `serde`
pub fn get_json(mut reqwest_res: reqwest::Response) -> Result<Value, Box<dyn std::error::Error>> {
let data: Value = serde_json::from_str(&reqwest_res.text()?)?;
Ok(data)
}
/*
Copyright (C) 2018-2019 <EMAIL>
Permission is hereby granted, free ... | Rust | 0 |
import numpy as np
from worldscore.benchmark.metrics.base_metrics import BaseMetric
from worldscore.common.optional_dependencies import handle_module_not_found_error
try:
from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity
except ModuleNotFoundError as e:
handle_module_not_found_error(e,... | Python | 1 |
new();
for (alias, canonical) in by_alias {
by_canonical.entry(&**canonical).or_insert(vec![]).push(&**alias);
}
for (canonical, mut aliases) in by_canonical {
aliases.sort();
println!("{} (aliases: {})", canonical, aliases.join(", "));
}
Ok(())
}
#[macro_export] // #[macro_e... | Rust | 0 |
my_pred = np.append(my_r_final, my_t_final)
my_r = my_r_final
my_t = my_t_final
# Here 'my_pred' is the final pose estimation result after refinement ('my_r': quaternion, 'my_t': translation)
my_result.append(my_pred.tolist())
except ZeroDivisionEr... | Python | 1 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The setup script."""
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
readme = readme_file.read()
requirements = ["reframed>=1.6.0", "pandas>=2.0.0"]
test_requirements = requirements + ['cplex']
script_list = [
"scripts/sm... | Python | 1 |
#!/usr/bin/env python
"""
Configuration file for DeepMASC
"""
# Path to the conda python interpreter
# Update this path to point to your conda environment's python executable
# Example: "/path/to/conda/envs/your_env/bin/python"
# CONDA_PYTHON_PATH = "/usr/bin/python" # Default to system python, update as needed
CONDA... | Python | 1 |
r i in flow.keys()]) + "\n"
f.write(header.encode("utf-8"))
values = anon.process(flow)
csv_converter(values)
to_export = ",".join([str(i) for i in values]) + "\n"
f.write(to_export.encode("utf-8"))
total_flows = total_f... | Python | 1 |
ub fn new(sound: usize) -> Self {
SynthVoice {
sound,
volume: 1.,
step: 0,
playing: false,
}
}
fn apply_gate(&mut self, gate: bool) {
if gate {
self.step = 0;
self.playing = true;
}
}
fn step(&mut s... | Rust | 0 |
def save_models(model_dir, models, global_step, max_to_keep=15, keep_latest
=True):
with DelayedKeyboardInterrupt():
name_to_model = _get_name_to_model_map(models)
for name, model in name_to_model.items():
save(model_dir, model, name, global_step, max_to_keep, keep_latest)
| Python | 1 |
let address = self.node_config.p2p_listen_address().to_string();
let tokens: Vec<&str> = address.split('/').collect();
assert_eq!(
tokens.get(3),
Some(&"tcp"),
"expected a tcp part in p2p.public_address"
);
let port_str = tokens
.get... | Rust | 0 |
= "Option::is_none")]
pub field: Option<Field>,
/// What criteria to apply. CONTAIN or EQUAL. Note CONTAIN is recommended due to some SMTP servers adding new lines to fields and body content.
#[serde(rename = "should", skip_serializing_if = "Option::is_none")]
pub should: Option<Should>,
/// The va... | Rust | 0 |
" @return The value of the close flag."]
#[doc = ""]
#[doc = " @errors Possible errors include @ref GLFW_NOT_INITIALIZED."]
#[doc = ""]
#[doc = " @thread_safety This function may be called from any thread. Access is not"]
#[doc = " synchronized."]
#[doc = ""]
#[doc = " @sa @ref window... | Rust | 0 |
he 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 crate::any::{Any, Error, Inner};
use ordered_float::NotNan;
use serde::de::{
Deseria... | Rust | 0 |
# ver_settings.py
# Copyright (C) 2024 CESNET z. s. p. o.
# Author(s): Vladislav Valek <valekv@cesnet.cz>
# SPDX-License-Identifier: BSD-3-Clause
SETTINGS = {
"default" : { # The default setting of verification
"MVB_ITEMS" : "2",
"MVB_ITEM_WIDTH" : "32",
"RX_STREAMS" ... | Python | 1 |
ew())
},
}
}
async fn process_commands(mut secret: Vec<u8>, commands: &[String]) -> Result<String> {
for command in commands {
let mut child = Command::new("sh")
.arg("-c")
.arg(command)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.... | Rust | 0 |
odos os seus valores
// possuem o mesmo tipo.
// O tipo de dado para uma matriz é [T;N], onde T é o tipo dos valores e N é o
// comprimento fixo conhecido em tempo de compilação.
// Os elementos podem ser recuperados individualmente com o operador [x], onde
// x é o indice do tipo usize (começando de 0) do elemento ... | Rust | 0 |
-> xmlAutomataStatePtr;
}
extern "C" {
pub fn xmlAutomataNewCountTrans2(
am: xmlAutomataPtr,
from: xmlAutomataStatePtr,
to: xmlAutomataStatePtr,
token: *const xmlChar,
token2: *const xmlChar,
min: ::std::os::raw::c_int,
max: ::std::os::raw::c_int,
data: *mut ::std::os::raw::c_void,
... | Rust | 0 |
Days=156
a=Days//7
r=Days%7
print(Days,'days are equal to',a,'weeks and',r,'days')
| Python | 1 |
flow::input::InputSession;
use differential_dataflow::operators::iterate::Iterate;
use differential_dataflow::operators::reduce::Threshold;
use differential_dataflow::operators::join::JoinCore;
use differential_dataflow::operators::arrange::arrangement::ArrangeByKey;
use st2_timely::connect::Adapter;
fn main() {
... | Rust | 0 |
core::HRESULT;
#[doc = "*Required features: `\"Win32_System_Ole\"`, `\"Win32_System_Com\"`*"]
#[cfg(feature = "Win32_System_Com")]
pub fn SafeArrayAllocDescriptorEx(vt: u16, cdims: u32, ppsaout: *mut *mut super::Com::SAFEARRAY) -> ::windows_sys::core::HRESULT;
#[doc = "*Required features: `\"Win32_Syste... | Rust | 0 |
, 0x06, 0x02, 0x10, 0x11, 0x12, 0x13, 0x14,
0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F,
]));
}
#[test]
fn read_by_group_type_request_16() {
let mut sink = RecordingSink::new();
{
let mut fixture = Fixture::new(&mut sink);
fixture
.act(|controller| {... | Rust | 0 |
import torch
class OmnidirectionalPointRobotDynamics:
def __init__(self, dt=0.05, device="cuda:0") -> None:
self._dt = dt
self._device = device
def step(self, states: torch.Tensor, actions: torch.Tensor) -> torch.Tensor:
x, y, theta = states[:, :, 0], states[:, :, 1], states[:, :, 2]
... | Python | 1 |
import calculate
import requests
from multiprocessing import Process, Manager
from decimal import Decimal
def get_story(story_id, stories):
url = 'https://hacker-news.firebaseio.com/v0/item/%d.json' % story_id
resp = requests.get(url)
story_data = resp.json()
user_data = get_user(story_data.get('by'))... | Python | 1 |
10
#[deprecated(
since = "1.4.0",
note = "moved to [`f16::LN_10`](../struct.f16.html#associatedconstant.LN_10)"
)]
pub const LN_10: f16 = f16::LN_10;
/// [`f16`](../struct.f16.html) 𝗅𝗇 2
#[deprecated(
since = "1.4.0",
note = "moved to [`f16::LN_2`](../struct.f16.htm... | Rust | 0 |
e].repeat(1, nF, 1).reshape(nE * nF, -1),
quat_conjugate(next_target_state["wrist_quat"]),
).reshape(nE, -1)
next_target_state["wrist_quat"] = next_target_state["wrist_quat"].reshape(nE, -1)
target_wrist_ang_vel = indicing(self.demo_data["wrist_angular_velocity"], cur_idx)
c... | Python | 1 |
import os
import sys
import gevent
import gevent.core
import subprocess
if sys.argv[1:] == []:
os.environ['GEVENT_BACKEND'] = 'select'
# (not in Py2) pylint:disable=consider-using-with
popen = subprocess.Popen([sys.executable, __file__, '1'])
assert popen.wait() == 0, popen.poll()
else: # pragma: no co... | Python | 1 |
"""
Convert a Kafka schema to an Avro schema.
"""
import json
def kafka_type_to_avro_type(kafka_field):
"""Convert a Kafka field type to an Avro field type."""
kafka_to_avro_types = {
'int32': 'int',
'int64': 'long',
'string': 'string',
'boolean': 'boolean',
'bytes':... | Python | 1 |
from typing import Optional
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
"""
- Time Complexity: O(n), n = The number of nodes in tree
- Space Com... | Python | 1 |
},
'ProductFields': { 'Product Name': 'Trivy' },
'Resources': [
{
'Type': 'Container',
'Id': containerName + ':' + containerTag,
... | Python | 1 |
bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << ... | Rust | 0 |
import torch
import einx
import math
from typing import Optional, Callable
class SGD(torch.optim.Optimizer):
def __init__(self, params, lr=1e-3)-> None:
assert lr > 0, ValueError(f"Invalid learning rate: {lr}")
super().__init__(params, {"lr": lr})
def step(self, closure: Optional[Callabl... | Python | 1 |
olor(c4d.VIEWCOLOR_C4DBACKGROUND_GRAD1, presets['dark'][0])
c4d.SetViewColor(c4d.VIEWCOLOR_C4DBACKGROUND_GRAD2, presets['dark'][1])
# If alt pressed, cycle through user gradients
if keyMod == "Alt":
path, fn = os.path.split(__file__) # Get path of the script
data = os.path.join(path, 'A... | Python | 1 |
dummy_inp = (dummy_real, dummy_imag)
in_names = ['real', 'imag']
dyn_axes_ist = {
'real' : {2: 'signal_len'},
'imag' : {2: 'signal_len'},
'output_audio': {2: 'audio_len'}
}
torch.onnx.export(
istft_model, d... | Python | 1 |
"""
NOTE: this tests are also meant to be run as PyPy "applevel" tests.
This means that global imports will NOT be visible inside the test
functions. In particular, you have to "import pytest" inside the test in order
to be able to use e.g. pytest.raises (which on PyPy will be implemented by a
"fake pytest module")
""... | Python | 1 |
pub unsafe fn _mm512_maskz_gf2p8mul_epi8(k: __mmask64, a: __m512i, b: __m512i) -> __m512i {
let zero = _mm512_setzero_si512().as_i8x64();
transmute(simd_select_bitmask(
k,
vgf2p8mulb_512(a.as_i8x64(), b.as_i8x64()),
zero,
))
}
/// Performs a multiplication in GF(2^8) on the packed b... | Rust | 0 |
ations( input_data: &str ) -> String{
let mut result: String = String::new();
let mut last_char: char = ' ';
for new_char in input_data.chars(){
if ![' ', '|', '(', '\\'].contains( &last_char ) && ![')', '*', '|'].contains( &new_char ) {
result.push('\u{22C5}');
}
resul... | Rust | 0 |
1.2
>>> x[1]
1
>>> x[1] = 1.2j
<type 'exceptions.TypeError'>: can't convert complex to long; use
long(abs(z))
Unlike some of the references (such as array and mask indices)
assignments are always made to the original data in the array
(indeed, nothing else would make sense!). Note though, that some
actions may ... | Python | 1 |
import tensorflow as tf
def build_model(input=(512, 512, 3), nbrclass=2, backbone='resnet101', lr=0.0001):
import segmentation_models as sm
sm.set_framework('tf.keras')
sm.framework()
model = sm.Unet(backbone,
classes=nbrclass,
input_shape = input,
acti... | Python | 1 |
mA"]
pub ARIIsTXDEN: UCHAR,
#[doc = " non-zero if port A uses RI as RS485 TXDEN"]
pub BRIIsTXDEN: UCHAR,
#[doc = " non-zero if port B uses RI as RS485 TXDEN"]
pub CRIIsTXDEN: UCHAR,
#[doc = " non-zero if port C uses RI as RS485 TXDEN"]
pub DRIIsTXDEN: UCHAR,
#[doc = " non-zero if port D ... | Rust | 0 |
= os.path.join(debug_dir, "input_file.svg")
shutil.copy2(sys.argv[-1], out_file)
else:
out_file = in_file
# Script to run Inkscape Extension as a Python script.
with open(os.path.join(debug_dir, f"{base_name}.sh"), "w") as fid:
fid.write("#!/usr/bin/env bash")
fid.write("\n... | Python | 1 |
// As mentioned in the `Safety` section of this function's documentation, the caller of
// this function needs to guarantee that the passed-in lifetime is sufficiently long
// for the lifetime of the thread.
//
// Similarly, the `sys` implementation must guarantee that no referenc... | Rust | 0 |
"""The location of a variable, tag or filter in a template."""
from dataclasses import dataclass
@dataclass
class Span:
"""The location of a variable, tag or filter in a template."""
template_name: str
"""The template name."""
index: int
"""A start index into the template source text."""
d... | Python | 1 |
room, msg):
qDebug('lisa is processing relay msg...' + str(room.group_number))
tmsg = msg
for cmd in self.handlers.keys():
if tmsg.startswith(cmd):
qDebug('matched lisa cmd:' + cmd)
ctx = HandlerContext(cmd, tmsg, room, None, None)
wo... | Python | 1 |
cache_key = format!("{}:{}", key, current_minute);
let hits: Option<u64> = conn.get(&cache_key)?;
if let Some(hit_count) = hits {
if hit_count > max_req_per_min {
// Rate limit for the current minute has already been exceeded,
// so just report the error alo... | Rust | 0 |
# This file is automatically generated. Please do not modify.
from . import AsciiArt
darkos = AsciiArt(match=r'''"DarkOs"''', color='1 6 5 3 2', ascii=r"""
${c3}⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⠢⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
${c1}⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣶⠋⡆⢹⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
${c5}⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡆⢀⣤⢛⠛⣠⣿⠀⡏⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
${c6}⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀... | Python | 1 |
# ClydeBank Coffee Shop Simulator 4000
# Copyright 2022 (C) ClydeBank Media, All Rights Reserved.
# Import all functions from the utility module
from utilities import *
# Import the game class from the coffee_shop_simulator module
from coffee_shop_simulator import CoffeeShopSimulator
# Print welcome message
welcome(... | Python | 1 |
# -*- coding:utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, api
class L10nItDdt(models.Model):
_name = 'l10n_it.ddt'
_description = 'Transport Document'
invoice_id = fields.One2many('account.move', 'l10n_it_ddt_id', string='Invoice Re... | Python | 1 |
ate.loop > rerun_limit
):
exec_outputs = self.runtime.get_execution_data_outputs(current_node_id)
exec_outputs["ex_data"] = "node execution exceed rerun limit {}".format(rerun_limit)
self.runtime.set_execution_data_outputs(curr... | Python | 1 |
, None),
};
let req = fidl_mlme::AssociateRequest {
peer_sta_address: bssid.0,
cap_info: capabilities.map_or(0, |c| c.0.cap_info.raw()),
rates: capabilities.map_or_else(|| vec![], |c| c.0.rates.as_bytes().to_vec()),
// TODO(fxbug.dev/43938): populate `qos_capable` field from devi... | Rust | 0 |
// parse error
(_, Some(Err(r))) => Err(r),
})
})
}
<gh_stars>0
use crate::row::{self, Row};
use sauron::{
html::{attributes::*, events::*, *},
prelude::*,
Component, Node,
};
use sauron::Cmd;
#[derive(Debug, PartialEq, Clone)]
pub enum Msg {
TabClick,
RowMsg(... | Rust | 0 |
_10 SW PAD Control Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--wr... | Rust | 0 |
import re
import os
import lyricsgenius
from pyrogram import Client, filters
from pyrogram.types import Message
from youtubesearchpython import VideosSearch
from Tamilini import MUSIC_BOT_NAME, app
__MODULE__ = "Lyrics"
__HELP__ = """
/Lyrics [Music Name]
- Searches Lyrics for the particular Music on web.
**Note**:... | Python | 1 |
.hexpand(true)
.build();
vbox.pack_start(¶ms_box, false, false, 0);
params_box.attach(
>k::LabelBuilder::new().label("Learning Rate").build(),
0,
0,
1,
1,
);
let lr_text = gtk::TextViewBuilder::new()
.buffer(>k::TextBufferBuilder::new().te... | Rust | 0 |
let mut app = self.projection()?;
loop {
let sp = app.span;
if let Ok(ty) = self.ty_app() {
// Full type inference for System F is undecidable
// Additionally, even partial type reconstruction,
// where only type application types ... | Rust | 0 |
G["y"])
np.savez(TEST_DIR_PATH / "test_datasets/data", x=x, y=y)
else:
data = np.load(TEST_DIR_PATH / "test_datasets/data.npz")
x, y = data["x"], data["y"]
x_1D, y_1D = jnp.squeeze(x[:, 1, :]), jnp.squeeze(y[:, 1, :])
_measure = dist_type.create_instance(name)
inputs = (x_1D, y_... | Python | 1 |
e_date_found = True
break
except ValueError:
continue
# Nếu vẫn không tìm thấy và có ít nhất 2 ngày trong văn bản, giả định ngày đầu tiên là ngày cấp
if not issue_date_found and len(all_dates... | Python | 1 |
asset as JPEG: {:?}",
asset.to_full_path()
));
}
}
AssetLoadResult::Data(Box::new(ImageAsset {
descriptor,
width,
height,
depth: list.l... | Rust | 0 |
i < self.len() {
Ok(Variant::ref_from_raw_mut((*self.0).rgvarg.offset(i as isize)))
} else {
bail!("no param at index: {}", i)
}
}
}
unsafe fn dispatch_server_start(server: &Server, params: Params) -> Result<()> {
server.server_start(IRTDUpdateEventWrap::new(params.get(... | Rust | 0 |
import streamlit as st
from utils.utils import *
from prompts import cover_letter_prompts
import pyperclip
from dotenv import load_dotenv
load_dotenv()
def main():
if 'cover_letter' not in st.session_state:
st.session_state.cover_letter = None
st.title("Cover Letter Generator")
# Upload Resume
... | Python | 1 |
import numpy as np
import matplotlib.pyplot as plt
def show_result(x, y, pred_y, plot_name):
fig, axs = plt.subplots(1, 2, figsize=(12, 5))
axs[0].set_title("Ground truth", fontsize=10)
for i in range(x.shape[0]):
if y[i] == 0:
axs[0].plot(x[i][0], x[i][1], "ro")
else:
... | Python | 1 |
ck outgoing email headers (those are put into outgoing email
# not in the mail.mail record)
email = self._find_sent_mail_wemail(contact.email)
headers = email.get("headers")
unsubscribe_oneclick_url = test_mailing._get_unsubscribe_oneclick_url(contact.email, contact.id)
... | Python | 1 |
import bson
import fastapi
import fastapi_chameleon
from starlette.requests import Request
from db.job import JobActions
from infrastructure import webutils
from services import background_service
from viewmodels.ai.check_job_viewmodel import CheckJobViewModel
from viewmodels.ai.start_job_viewmodel import StartJobView... | Python | 1 |
butionAnalysis):
def __init__(self):
super().__init__()
self._char_to_freq_order = JIS_CHAR_TO_FREQ_ORDER
self._table_size = JIS_TABLE_SIZE
self.typical_distribution_ratio = JIS_TYPICAL_DISTRIBUTION_RATIO
def get_order(self, byte_str):
# for euc-JP encoding, we are inter... | Python | 1 |
# Question 3
num = int(input("Enter a number: "))
i = 1
while i < 11:
print(f"{num} x {i} = {num*i}")
i += 1 | Python | 1 |
decoded_cmd:
print(f"[agent] Post-processed decoded_cmd -> {final_cmd!r}", flush=True)
print(f"[agent] Decoded command: {final_cmd!r}", flush=True)
if AUTO_EXEC:
print("[agent] AUTO_EXECUTE=true → launching command...", flush=True)
subprocess.Popen(final_cmd, shell=True, executable="/b... | Python | 1 |
request=request,
schema=schema,
)
@room_message_router.put(
"/{room_id}",
status_code=status.HTTP_200_OK,
responses=responses,
response_model=DeleteRoomMessageResponseDto,
dependencies=[Depends(validate_logout_status)],
)
async def delete_messages(
request: Request,
room_id:... | Python | 1 |
Ok(_)=> Err(Error::<T>::AlreadyMember.into()),
Err(index)=>{
members.insert(index,new_member.clone());
Members::<T>::put(members);
Self::deposit_event(RawEvent::MemberAdded(new_member));
Ok(())
... | Rust | 0 |
"""Crear tabla naturaleza
Revision ID: 95e3f1435596
Revises: eaeb22837af1
Create Date: 2024-11-04 02:01:59.396941
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = "95e3f1435596"
down_revision: Union[str, None] = None
bra... | Python | 1 |
enable = "avx2")]
pub unsafe fn avx2_page_xor3(dst: *mut u8, v1: *const u8, v2: *const u8, v3: *const u8) {
let mut dst: *mut __m256i = dst as *mut __m256i;
let mut v1: *const __m256i = v1 as *const __m256i;
let mut v2: *const __m256i = v2 as *const __m256i;
let mut v3: *const __m256i = v3 as *const __m... | Rust | 0 |
*MILLIW.value_unsafe, "Watt";
V: MilliVolt = KILO*MILLIV.value_unsafe, "Volt";
F: KiloFarad = MILLI*KILOF.value_unsafe, "Farad";
OHM: MilliOhm = KILO*MILLIOHM.value_unsafe, "Ohm";
SIE: KiloSiemens = MILLI*KILOSIE.value_unsafe, "Siemens";
WB: MilliWeber = ... | Rust | 0 |
s' --tlsv1.2 -sSf https://sh.rustup.rs | sh;"
"source $HOME/.cargo/env;"
"sudo apt install librust-openssl-dev;"
"cd RVuln;sudo su;cargo build --release;mv target/release/RVuln"
]
RUN_COMMANDS = ["RVuln"]
PROJECT_URL = "https://github.com/iinc0gnit0/RVuln"
class XSSAttackTools(Hack... | Python | 1 |
"""HTTP cache implementation.
"""
import os
from contextlib import contextmanager
from typing import Iterator, Optional
from pip._vendor.cachecontrol.cache import BaseCache
from pip._vendor.cachecontrol.caches import FileCache
from pip._vendor.requests.models import Response
from pip._internal.utils.filesystem impor... | Python | 1 |
unwrap_or("127.0.0.1");
let port = uri.port_u16().unwrap_or(80);
HttpClient::connect((host, port))?
};
let mut s = String::new();
for _ in 0..100 {
let uri = uri.clone();
let mut rsp = client.get(uri)?;
rsp.read_to_string(&mut s)?;
println!("get rsp={}", s);
... | Rust | 0 |
(_ctx, @arg 4 => x0, x1, x2, x3; $function) };
(5, $function:expr) => { $crate::wrap_fn!(_ctx, @arg 5 => x0, x1, x2, x3, x4; $function) };
(6, $function:expr) => {
$crate::wrap_fn!(_ctx, @arg 6 => x0, x1, x2, x3, x4, x5; $function)
};
(7, $function:expr) => {
$crate::wrap_fn!(_ctx, @arg ... | Rust | 0 |
from typing import Union
import click
import requests
from rich.console import Console
from yaramanager import version as ver
try:
from yaramanager import commit
IS_BINARY = True
except ImportError:
IS_BINARY = False
@click.command(help="Displays the current version.")
@click.option("-c", "--check", i... | Python | 1 |
}
// The packet header should fit inside the head descriptor.
if head.len < VSOCK_PKT_HDR_SIZE as u32 {
return Err(VsockError::HdrDescTooSmall(head.len));
}
// All RX descriptor chains should have a header and a data descriptor.
if !head.has_next() {
... | Rust | 0 |
from bungiesearch.fields import DateField, NumberField, StringField
from bungiesearch.indices import ModelIndex
from core.models import Article, NoUpdatedField, User
from .analysis import edge_ngram_analyzer
class ArticleIndex(ModelIndex):
effective_date = DateField(eval_as='obj.created if obj.created and obj.pu... | Python | 1 |
efault: 96
Returns:
niqe_metrics (torch.Tensor): NIQE metrics
"""
def __init__(self, crop_border: int,
niqe_model_path: str,
block_size_height: int = 96,
block_size_width: int = 96) -> None:
super().__init__()
self.crop_border = cro... | Python | 1 |
#!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Make sure exception handling settings are extracted properly.
"""
import TestGyp
import sys
if sys.platform == 'win32':
test = Test... | Python | 1 |
soto_dynamodb::DynamoDb> DynamoDb for D {}
<gh_stars>1-10
fn main() {
use std::process::Command;
let project_root = std::env::current_dir()
.unwrap()
.parent() // flatbuffers/tests/rust_usage test
.unwrap()
.parent() // flatbuffers/tests
.unwrap()
.parent() // ... | Rust | 0 |
class process:
def __init__(self,process_id,arrival_time,burst_time,priority,q,ready):
self.process_id=process_id
self.arrival_time=arrival_time
self.burst_time=burst_time
self.priority=priority
self.ready=ready
self.q=q
def Queue(t1):
t1=int(t1)
if(... | Python | 1 |
Args:
recall (list): The recall curve.
precision (list): The precision curve.
Returns:
The average precision as computed in py-faster-rcnn.
"""
# correct AP calculation
# first append sentinel values at the end
mrec = np.concatenate(([0.], recall, [1.]))
mpre = np.con... | Python | 1 |
0])
u_b = l / norm(l) # Normalise directions
R = np.eye(3)
if not np.allclose(l, u_a, rtol=tol, atol=tol):
u_v = np.cross(u_a, u_b)
u_v_mat = np.array([[0, -u_v[2], u_v[1]], [u_v[2], 0, -u_v[0]], [-u_v[1], u_v[0], 0]])
R = R + u_v_mat + np.dot(u_v_mat, u_v_... | Python | 1 |
MemoryDataDelegate>> {
let agency = CachedDataAgency::new(device, allot_infos)?;
Ok(Box::new(agency))
}
fn to_update_agency(&self) -> VkResult<Box<dyn MemoryDataDelegate>> {
/// Cached memory is unable to update directly.
unreachable!()
}
}
impl ImageMemoryAbs for GsCached... | Rust | 0 |
cs.GLsizei,_cs.GLenum,ctypes.c_void_p,_cs.GLsizei)
def glDrawElementsInstanced(mode,count,type,indices,instancecount):pass
@_f
@_p.types(None,_cs.GLuint,_cs.GLuint,_cs.GLsizei,arrays.GLsizeiArray,arrays.GLcharArray)
def glGetActiveUniformBlockName(program,uniformBlockIndex,bufSize,length,uniformBlockName):pass
@_f
@_p.... | Python | 1 |
n_stdout)
if match_stderr:
filenames.append(constants.gem5_simulation_stderr)
super().__init__(regex, filenames)
class NoMatchRegex(MatchRegex):
"""
Checks that the given pattern does *not* match
"""
def __init__(self, regex, match_stderr=True, match_stdout=True):
... | Python | 1 |
.unwrap()
.set_val,
)
.unwrap()
== GridConnectModeKind::VsiPq),
Err(err) => Err(err),
}
})))
}
/// Check if the inverter is in Grid Forming mode
pub async fn is_grid_forming(&mut self) -> S... | Rust | 0 |
id, db),
AttrDefId::MacroDefId(it) => attrs_from_ast(it.ast_id, db),
AttrDefId::ImplId(it) => attrs_from_ast(it.lookup_intern(db).ast_id, db),
AttrDefId::ConstId(it) => attrs_from_loc(it.lookup(db), db),
AttrDefId::FunctionId(it) => attrs_from_loc(it.lookup(db), db),
... | Rust | 0 |
ies = num_try + 1
return is_ssh_connected, ssh_retry_res, num_tries
def collect_mgmt_config_by_console(duthost, localhost):
logger.info("check if dut is pingable")
localhost.shell(f"ping -c 5 {duthost.mgmt_ip}", module_ignore_errors=True)
logger.info("Start: collect mgmt config by console")
creds... | Python | 1 |
0.0, 0.0]
# commands = [0.0, 0.0, 0.0]
# prev = time.time()
# last_control = time.time()
prev = data.time
last_control = data.time
control_freq = 60 # hz
i = 0
# data.qpos[3 : 3 + 4] = [1, 0, 0.08, 0]
# init_rot = [0, -0.1, 0]
# init_rot = [0, 0, 0]
# init_quat = R.from_euler("xyz", init_rot, degrees=False).as_quat()... | Python | 1 |
'''person=input("whats your name")
person'''
year=int(input("enter the year"))
while True:
if year%4==0:
if year%100==0:
if year%400==0:
print(f"{year}is a leap yeaar")
else:
print(f"{year}is not a leap year")
else:
print(... | Python | 1 |
# test the lexer
try:
eval
exec
except NameError:
print("SKIP")
raise SystemExit
# __debug__ is a special symbol
print(type(__debug__))
# short input
exec("")
exec("\n")
exec("\n\n")
exec("\r")
exec("\r\r")
exec("\t")
exec("\r\n")
exec("\nprint(1)")
exec("\rprint(2)")
exec("\r\nprint(3)")
exec("\n5")... | Python | 1 |
set_event_loop_policy(uvloop.EventLoopPolicy())
>>> asyncio.get_event_loop()
<uvloop.Loop running=False closed=False debug=False>
"""
def _loop_factory(self) -> Loop:
return new_event_loop()
if _typing.TYPE_CHECKING:
# EventLoopPolicy doesn't implement these, but since they are mar... | Python | 1 |
#!/usr/bin/env python3
'''Task 6's module.
'''
from typing import List, Union
def sum_mixed_list(mxd_lst: List[Union[int, float]]) -> float:
'''Computes tha sum of tha list of integers and floating-point numbers.
'''
return float(sum(mxd_lst))
| Python | 1 |
let texture = glium::Texture2d::empty_with_format(&display,
glium::texture::UncompressedFloatFormat::U8U8U8U8,
glium::texture::MipmapsOption::NoMipmap,
128, 128).unwrap();
le... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.