text string | label_name string | labels int64 |
|---|---|---|
s variable time with respect to `rhs` *ONLY*.
///
/// When used with a fixed `rhs`, this function is constant-time with respect
/// to `self`.
fn shr(self, rhs: usize) -> UInt<LIMBS> {
self.shr_vartime(rhs)
}
}
impl<const LIMBS: usize> Shr<usize> for &UInt<LIMBS> {
type Output = UInt<LI... | Rust | 0 |
rupt:
self.stop_reminder()
print("\n👋 Goodbye!")
break
except EOFError:
break
def main():
app = EyeCareReminder()
if len(sys.argv) > 1:
if sys.argv[1] == '--test':
app.test_reminder()
elif sys.argv[1] ... | Python | 1 |
print("Laser is switched off")
def deliver_tone_shock():
"""
Activates tone signal via digital trigger. Cycle is optional
:param rep: Number of repetitions for signal [int]
:param duration: Duration in seconds of signal for each rep [float]
:param inter_time: Time in seconds between reps [float]
... | Python | 1 |
Long,
pub family_name: *mut FT_String,
pub style_name: *mut FT_String,
pub num_fixed_sizes: FT_Int,
pub available_sizes: *mut FT_Bitmap_Size,
pub num_charmaps: FT_Int,
pub charmaps: *mut FT_CharMap,
pub generic: FT_Generic,
pub bbox: FT_BBox,
pub units_per_EM: FT_UShort,
pub asce... | Rust | 0 |
ne:
mocker.patch(
"cmk.gui.watolib.hosts_and_folders.PermissionChecker.need_permission",
side_effect=MKAuthException("hands off this host"),
)
assert (
aut_user_auth_wsgi_app.call_method(
"get",
urljoin(_HOST_CONFIG_INTERNAL_BASE, "heute"),
headers... | Python | 1 |
# -*- coding: utf-8 -*-
import pygcb
def CreateDBObject():
dbObj=pygcb.tcWeaponDamage()
dbObj.databaseClass='BlastFragMis420kg'
dbObj.maxRange_m=5184.650879
dbObj.probDetonate=0.850000
dbObj.blastCharge_kg=63.432175
dbObj.fragCharge_kg=201.311890
dbObj.radCharge_kg=6.343217
dbObj.fragMet... | Python | 1 |
);
let size = u8_size as usize;
for (i, byte) in out.iter_mut().enumerate().take(size) {
*byte = ((n >> ((size - 1 - i) * 8)) & 0xFF) as u8;
}
out[0] |= ((size - 1) as u8) << 6;
u8_size
}
/// Decode a byte array as a varint.
pub fn decode(out: &[u8]) -> ParseResult<u32> {
if out.is_empt... | Rust | 0 |
8; 14],
}
#[cfg(any(target_os = "ios", target_os = "macos"))]
#[repr(C)]
#[derive(Debug, Copy, Clone)]
struct sockaddr_in {
pub sin_len: u8,
pub sin_family: sa_family_t,
pub sin_port: u16,
pub sin_addr: super::in_addr,
pub sin_zero: [c_char; 8],
}
#[cfg(any(target_os = "netbsd", target_os = "openb... | Rust | 0 |
[x as usize][y as usize - 1] == 0 {
heap.push(Location {
score: score
+ (turb_noise(fx, fy - dy) + CONSTANT)
+ EDGE_WEIGHT * distance_to_centre(x, y, w, h),
x: x,
y: y - 1,... | Rust | 0 |
}
fn block_on_given<F>(f: F, runtime: &Runtime) -> F::Output
where
F: futures::future::Future,
{
let _g = runtime.enter();
tokio::task::block_in_place(|| runtime.block_on(async { f.await }))
}
/// Run a blocking thread on `TOKIO` with a timeout.
pub fn block_on<F>(
f: F,
timeout: std::time::Durat... | Rust | 0 |
#!/usr/bin/env python3
"""
Test for Buy and Hold strategy with quiet logs functionality
"""
import os
import sys
import io
import pytest
import datetime as dt
import logging
from unittest.mock import patch, MagicMock
import pytz
from lumibot.backtesting import BacktestingBroker
from lumibot.traders import Trader
from... | Python | 1 |
nwrap_or_else(|e| {
error!("{:?}", e);
std::process::exit(1);
});
}
fn run() -> Result<()> {
let start_time = Instant::now();
let args = Args::from_args();
logsetup::init_logger(args.verbose, args.timestamps, args.color);
let parse_start = Instant::now();
let mut flights: Vec... | Rust | 0 |
from .command import Command
import os
from pathlib import Path
class MkdirCommand(Command):
"""
Command class for creating a new directory and subdirectories.
"""
def __init__(self) -> None:
"""
Initializes a new instance of the MkdirCommand class.
Args:
None
... | Python | 1 |
from transformers import AutoModelForCausalLM, AutoTokenizer
from llmcompressor import oneshot
from llmcompressor.modifiers.quantization import QuantizationModifier
from llmcompressor.modifiers.transform import SpinQuantModifier
from llmcompressor.utils import dispatch_for_generation
# Select model and load it.
MODEL... | Python | 1 |
Credentials,
/// The AWS credentials provider.
credentials_provider: rusoto_credential::EnvironmentProvider,
}
impl S3Config {
pub(crate) fn client(&self) -> rusoto_s3::S3Client {
rusoto_s3::S3Client::new_with(
rusoto_core::request::HttpClient::new().unwrap(),
self.credentia... | Rust | 0 |
="15"} 2.31805973e+08
node_schedstat_timeslices_total{cpu="2"} 2.27593082e+08
node_schedstat_timeslices_total{cpu="3"} 2.46201381e+08
node_schedstat_timeslices_total{cpu="4"} 2.58191107e+08
node_schedstat_timeslices_total{cpu="5"} 2.6442866e+08
node_schedstat_timeslices_total{cpu="6"} 2.52569908e+08
node_schedstat_time... | Rust | 0 |
conds and nanoseconds
#[cfg_attr(feature = "const", const_fn::const_fn)]
pub fn from_timespec(unix_time: i64, nanoseconds: u32) -> Result<Self, OutOfRangeError> {
let seconds = match unix_time.checked_sub(UNIX_OFFSET_SECS) {
Some(seconds) => seconds,
None => return Err(OutOfRange... | Rust | 0 |
import torch
import numpy as np
def get_random_problems(batch_size, problem_size):
depot_xy = torch.rand(size=(batch_size, 1, 2))
# shape: (batch, 1, 2)
node_xy = torch.rand(size=(batch_size, problem_size, 2))
# shape: (batch, problem, 2)
if problem_size == 20:
demand_scaler = 30
e... | Python | 1 |
ary Stats
st.subheader("📊 Summary Metrics")
col1, col2, col3 = st.columns(3)
col1.metric("Total Restaurants", filtered_df['Restaurant'].nunique())
col2.metric("Avg Rating", f"{filtered_df['Avg ratings'].mean():.2f}")
col3.metric("Avg Price", f"₹{filtered_df['Price'].mean():.0f}")
# Top Restaurants by Total Ratings
st... | Python | 1 |
import sys
import urllib.request
import os
from html.parser import HTMLParser
from pathlib import Path
import time
import multiprocessing
base_url = 'http://ocw.mit.edu'
lec_url_list = []
video_url_list = []
vid_name_list = []
def findName(url):
cut_position = url.rfind("/")
name = url[cut_position + 1:]
return na... | Python | 1 |
# Copyright (c) 2023, Nirali and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
class DesignerAssignment(Document):
pass
| Python | 1 |
"""
Write a function to find the nth newman–shanks–williams prime number.
assert newman_prime(3) == 7
"""
def newman_prime(n):
"""
>>> newman_prime(3)
7
>>> newman_prime(4)
11
>>> newman_prime(5)
17
>>> newman_prime(6)
29
>>> newman_prime(7)
41
>>> newman_prime(8)
59... | Python | 1 |
# work 1
# def most_frequent_char(s):
# max_count = 0
# max_char = ''
# for char in s:
# count = s.count(char)
# if count > max_count:
# max_count = count
# max_char = char
# return max_char
# print(most_frequent_char("banana"))
# print(most_fre... | Python | 1 |
ed image, but got an arrayed image",
Self::WrongDescriptorType => "expected one type of resource but got another",
}
)
}
}
// Part of the DescriptorSetError for the case
// of missing usage on a buffer.
#[derive(Debug, Clone)]
pub enum MissingBufferUsage {
StorageBuffer,
... | Rust | 0 |
net_cifar': nasnet.nasnet_cifar_arg_scope,
'nasnet_mobile': nasnet.nasnet_mobile_arg_scope,
'nasnet_large': nasnet.nasnet_large_arg_scope,
'pnasnet_large': pnasnet.pnasnet_large_arg_scope,
}
def get_network_fn(name, num_classes, weight_decay=0.0, ... | Python | 1 |
te(chapters) if ch.start is None]
if missing:
errors.append(f"Chapters {missing} missing timestamps")
# Check timestamps are in order and non-negative
for i, ch in enumerate(chapters):
if ch.start is None:
continue
if ch.start < 0:
... | Python | 1 |
::svm_byte_array_destroy(spawn_receipt);
let _ = api::svm_byte_array_destroy(exec_receipt);
let _ = api::svm_imports_destroy(imports);
let _ = api::svm_runtime_destroy(runtime);
let _ = api::svm_state_kv_destroy(state_kv);
assert_eq!(tracking::total_live(), 0);
tracking... | Rust | 0 |
import torch
import scallopy
import unittest
class TestSparseDigitForward(unittest.TestCase):
def setUp(self):
self.ctx = scallopy.ScallopContext(provenance="difftopkproofs")
self.ctx.add_relation("digit_1", int, range(10))
self.ctx.add_relation("digit_2", int, range(10))
self.ctx.add_rule("sum_2(a +... | 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 unde... | Python | 1 |
tep = epoch * len(eval_loader) + batch_idx + 1
writer.add_scalar('eval/loss', loss.item(), current_step)
writer.add_scalar('eval/word_loss', word_loss.item(), current_step)
writer.add_scalar('eval/struct_loss', struct_loss.item(), current_step)
writer.add_... | Python | 1 |
::{Digest, Sha256};
use simple_logger;
fn hash256_to_fixed_array(s: &'static str) -> [u8; 32] {
let mut hasher = Sha256::new();
hasher.input(s);
let mut result: [u8; 32] = std::default::Default::default();
result.clone_from_slice(hasher.result().as_slice());
result
}... | Rust | 0 |
f> {
self.v.apply_ref(sub).map(|v| Property {
k: self.k.clone(),
v,
})
}
fn free_vars(&self, vars: &mut Vec<Tvar>) {
self.v.free_vars(vars)
}
}
impl<T> MaxTvar for Property<T> {
fn max_tvar(&self) -> Option<Tvar> {
self.v.max_tvar()
}
}
/// R... | Rust | 0 |
import pandas as pd
from matplotlib import pyplot as plt
import numpy as np
import os
def plot_curve(dirname,
fig=None,
ax=None,
title=None,
curve="mean",
confidence_interval=True,
label=None,
window_size=1,
... | Python | 1 |
hue, chroma)
}
#[inline]
pub fn RGB_to_HSL(color: Vec3, _wp: WhitePoint) -> Vec3 {
RGB_to_HSX(color, |_, x_max, x_min, _| {
let lightness = (x_max + x_min) / 2.0;
let saturation = if lightness <= 0.0 || lightness >= 1.0 {
0.0
} else {
... | Rust | 0 |
s(&self) -> u8 {
match *self {
DIVR::DIV1 => 1,
DIVR::DIV2 => 2,
DIVR::DIV4 => 4,
DIVR::DIV8 => 8,
DIVR::DIV16 => 16,
DIVR::DIV32 => 32,
DIVR::DIV64 => 64,
DIVR::DIV128 => 128,
DIVR::_Reserved(bits) => bi... | Rust | 0 |
(fsdp_loss, base_loss)
class TestComm(FSDPTest):
@property
def world_size(self) -> int:
return 2
@skip_if_lt_x_gpu(2)
def test_comm(self):
self.run_subtests(
{"input_size": [512, 2048]},
self._test_comm,
)
def _test_comm(self, input_size: int):
... | Python | 1 |
, []),
prompt_override=prompt_subtitles
)
stream.ListItem.setSubtitles(subtitles)
duration = iso8601_duration_to_seconds(content_details.get('duration', ''))
info_tag = ListItemInfoTag(stream.ListItem, 'video')
if snippet:
published_arrow = arrow.get(snippet['publishedAt']).to('loc... | Python | 1 |
texture_handle: Handle<ColorMaterial>,
pub laser_audio_handle: Handle<AudioSource>,
pub meteor_big_handle: Handle<ColorMaterial>,
pub meteor_med_handle: Handle<ColorMaterial>,
pub meteor_small_handle: Handle<ColorMaterial>,
}
impl RunState {
pub fn new(
asset_server: &AssetServer,
m... | Rust | 0 |
,
}
/// Task's execution priority. Low priority numbers denote low priority tasks.
#[derive(Debug, Copy, Clone)]
#[repr(transparent)]
pub struct TaskPriority(pub u8);
/// Task notify actions that can be performed
///
/// Corresponds to the same variants in [`TaskNotification`]
#[derive(Clone, Copy)]
#[repr(C)]
enum N... | Rust | 0 |
st.markdown("3. 发送问题获得AI回答")
st.markdown("4. 点击回答下方的 **\"提取知识图谱\"** 按钮")
# 如果没有相关图谱数据,显示提示并尝试加载全局图谱
st.info("🔄 尝试加载全局知识图谱作为备选...")
with st.spinner("加载全局知识图谱..."):
... | Python | 1 |
= Backup::new_with_names(
&src,
DatabaseName::Attached("my_attached"),
&mut dst,
DatabaseName::Main,
)?;
backup.run_to_completion(5, Duration::from_millis(250), None)?;
}
let the_answer: i64 = dst.query_row("SELECT... | Rust | 0 |
bit integers in a across lanes using the corresponding index in idx, and store the results in dst. Note that this intrinsic shuffles across 128-bit lanes, unlike past intrinsics that use the permutevar name. This intrinsic is identical to _mm512_permutexvar_epi32, and it is recommended that you use that intrinsic name.... | Rust | 0 |
core::ics24_host::identifier::{ChainId, Identifier, PortId},
model::{ChainConfig, ChainKey, Fee},
service::ChainService,
DbPool, Event, ToPublicKey,
};
use structopt::StructOpt;
use tendermint::block::Height as BlockHeight;
use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor};
use toki... | Rust | 0 |
be paired with an
/// [`HFILEMAPVIEW::UnmapViewOfFile`](crate::prelude::KernelHfilemapview::UnmapViewOfFile)
/// call.
#[must_use]
fn MapViewOfFile(self,
desired_access: co::FILE_MAP,
offset: u64,
number_of_bytes_to_map: Option<usize>) -> WinResult<HFILEMAPVIEW>
{
unsafe {
kernel::ffi::MapVie... | Rust | 0 |
.0f32, y: -7223650.5f32)
/// );
/// ```
fn transform_crs_to_crs(
&self,
source_crs: &str,
target_crs: &str,
) -> Result<Self::Output, TransformError>;
}
impl<T, G> Transform<T> for G
where
T: crate::CoordFloat,
G: crate::algorithm::map_coords::TryMapCoords<T, T, proj::Pr... | Rust | 0 |
x.partial_cmp(&t).unwrap()) - 1
} else if t == last {
self.grid.len() - 2
} else {
t = last;
self.segments.len() - 1
};
(t, self.grid[idx], self.grid[idx + 1], &self.segments[idx])
}
fn segment_velocity(t: S, t0: S, t1: S, a: &[V; 4]) -> V {
... | Rust | 0 |
white, //.clone(),
));
box1 = Arc::new(RotateY::new(box1, 15.0));
box1 = Arc::new(Translate::new(box1, Vec3::new(265.0, 0.0, 295.0)));
objects.push(box1);
let glass_sphere = Arc::new(Sphere::new(
Vec3::new(190.0, 90.0, 190.0),
90.0,
Arc::new(Dielectric::new(1.5)),
... | Rust | 0 |
libc!(libc::mmap(addr, length, prot, flags, fd, offset));
mmap64(addr, length, prot, flags, fd, offset as off64_t)
}
#[no_mangle]
unsafe extern "C" fn mmap64(
addr: *mut c_void,
length: usize,
prot: c_int,
flags: c_int,
fd: c_int,
offset: off64_t,
) -> *mut c_void {
libc!(libc::mma... | Rust | 0 |
-rs. DO NOT EDIT.
pub use error_meta::Error;
pub use config::Config;
mod aws_endpoint;
/// Client and fluent builders for calling the service.
pub mod client;
/// Configuration for the service.
pub mod config;
/// Errors that can occur when calling the service.
pub mod error;
mod error_meta;
/// Input structures for ... | Rust | 0 |
"""
Preprocess C files.
Change c_re() c_im() under some circumstances.
"""
import sys
def errlog(msg):
sys.stderr.write(str(msg))
sys.stderr.write("\n")
def proc_c_xx(oldline):
l = list()
idx = -1
while 1:
idx = oldline.find("c_", idx+1)
if idx < 0:
break
if oldline[idx+2:].startswith(... | Python | 1 |
_chain.append("math.copysign", 1, -1)
task_chain.append("math.floor", 2)
assert task_chain.length() == 3
assert task_chain.current() is None
task_chain.run()
r = task_chain.result(wait=1000)
assert task_chain.current() == task_chain.length()
assert len(r) == task_chain.length()
t = task_... | Python | 1 |
self.usercodes = []
def generateContent(self, f, messages, user_code_content):
f.write("#include <stdint.h>\n\n")
f.write("// Function prototypes for decoding signal value\n\n")
for message in messages:
code = genSigTypeDecode.generateSignalTypeDecodeFuncPrototypes(message)
... | Python | 1 |
f"アイテムの預け入れに失敗しました: {str(e)}"
)
if not item_found:
return ServiceResult(False, "指定されたアイテムが見つかりません")
return ServiceResult(False, "アイテムの預け入れに失敗しました")
def _withdraw_item(self, params: Dict[str, Any]) -> ServiceRe... | Python | 1 |
.free_in_buffer = (*dest).bufsize;
(*dest).buffer = nextbuffer;
(*dest).bufsize = nextsize;
return crate::jmorecfg_h::TRUE;
}
/*
* Terminate destination --- called by jpeg_finish_compress
* after all data has been written. Usually needs to flush buffer.
*
* NB: *not* called by jpeg_abort or jpeg_destro... | Rust | 0 |
for _ in range(int(input())):
n, x = map(int, input().split())
if n > 6 and n % 6 != 0:
print(((n // 6) + 1) * x)
if n > 6 and n % 6 == 0:
print((n // 6) * x)
if n != 0 and n <= 6:
print(x)
| Python | 1 |
sert_eq!(result, &[4, 5, 6, 7, 8, 9, 6, 7, 8, 9]);
}
#[test]
fn copy_nonoverlapping() {
let mem = create_memory(&[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
mem.copy_nonoverlapping(0, 10, 10)
.expect("Successfully copy the elements");
let result = mem.get(10, 10).expect("Successful... | Rust | 0 |
#set up your parameter here
ema_fast=7
ema_slow=50
symbol='BTCUSDT'
timeframe=['1m','3m']
balance=150
| Python | 1 |
gv[1])
}
/// # for *start* *test* *next* *command*
///
/// A standard "for" loop. start, next, and command are scripts; test is an expression
///
pub fn cmd_for(interp: &mut Interp, argv: &[Value]) -> MoltResult {
check_args(1, argv, 5, 5, "start test next command")?;
let start = &argv[1];
let test = &ar... | Rust | 0 |
always)]
pub fn is_0(&self) -> bool {
**self == LXTSTB_A::_0
}
#[doc = "Checks if the value of the field is `_1`"]
#[inline(always)]
pub fn is_1(&self) -> bool {
**self == LXTSTB_A::_1
}
}
impl core::ops::Deref for LXTSTB_R {
type Target = crate::FieldReader<bool, LXTSTB_A>;
... | Rust | 0 |
def priority(op):
if op == '(' or op == ')':
return 0
elif op == '+' or op == '-':
return 1
elif op == '*' or op == '/':
return 2
elif op == '^':
return 3
return 0
def InfixToPrefix(s):
# Step 1: Reverse the infix expression
s = s[::-1]
# Step 2: Rep... | Python | 1 |
peeked)) = input.peek().copied() {
end = index;
if peeked.is_alphanumeric() || peeked == '_' || peeked == '-' {
buffer.push(peeked);
input.next(); // eat char
// NOTE: This could be implemented using `input.next_if`.
} else {
break;
}
... | Rust | 0 |
Ok(Response::new(ListReply {
id: list.id.to_hyphenated().to_string(),
name: list.name,
}))
}
Err(err) => err,
};
let status = match error.downcast_ref::<ServiceError>() {
Some(ServiceError::NotFound(_)) => {
... | Rust | 0 |
mple:
```python
!pip install trl[mergekit]
from trl.mergekit_utils import MergeConfig
from trl import MergeModelCallback
config = MergeConfig()
merge_callback = MergeModelCallback(config)
trainer = DPOTrainer(..., callbacks=[merge_callback])
```
"""
def __init__(
self... | Python | 1 |
DE_16: u32 = 0x00004000; /* 16 VFs 8 queues per VF */
pub const IXGBE_GPIE_VTMODE_32: u32 = 0x00008000; /* 32 VFs 4 queues per VF */
pub const IXGBE_GPIE_VTMODE_64: u32 = 0x0000C000; /* 64 VFs 2 queues per VF */
/*... | Rust | 0 |
t__( self, QtWidgets.QTabBar(), plug, **kw )
self._qtWidget().setDrawBase( False )
self._qtWidget().currentChanged.connect( Gaffer.WeakMethod( self.__currentChanged ) )
self.__ignoreCurrentChanged = False
plug.node().plugSetSignal().connect( Gaffer.WeakMethod( self.__plugSet ) )
# Borrow the styling from ... | Python | 1 |
the `Cors` wrapper from the configured settings.
///
/// This step isn't *required*, as the `Builder` itself can be passed
/// to `Filter::with`. This just allows constructing once, thus not needing
/// to pay the cost of "building" every time.
pub fn build(self) -> Cors {
let expose_header... | Rust | 0 |
np.random.RandomState(101))
ter_simple = PropagationTerSimple(np.random.RandomState(101))
loss_ter = ter_simple.get_loss(d, freq, indoor_stations, loc_percentage)
loss_fs = free_space.get_free_space_loss(freq, d)
fig = plt.figure(figsize=(8, 6), facecolor='w', edgecolor='k')
plt.semilogx(np.sque... | Python | 1 |
import socketpool
import wifi
import pwmio
import board
import time
# Conectar a la red Wi-Fi
wifi.radio.connect("Oh_rigth", "culoacido")
pool = socketpool.SocketPool(wifi.radio)
print("wifi.radio:", wifi.radio.hostname, wifi.radio.ipv4_address)
s = pool.socket()
s.bind(('', 80))
s.listen(5)
# Configuración del serv... | Python | 1 |
(&self) -> HashMap<String, String> {
let mut m = HashMap::new();
m.insert("axis".to_string(), self.axis.to_snake_case());
m
}
}
impl Default for SpruceWoodData {
fn default() -> Self {
Self {
axis: SpruceWoodAxis::Y,
}
}
}
impl Value for SpruceWoodData {
... | Rust | 0 |
import pygame
import random
import sys
import numpy as np
# Initialize Pygame
pygame.init()
# Game settings
WIDTH, HEIGHT = 800, 600
FPS = 60
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
TRANSPARENT_GRAY = (128, 128, 128, 128) # 50% transparency
# Load the image
image_path = "assets/draw/apple.png" # Replac... | Python | 1 |
all(feature = "serde", feature = "strum"), test))]
impl serde::Serialize for Resource {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&self.to_string().to_lowercase())
}
}
#[cfg(any(all(feature = "serde", feature = "strum"), test))]
impl<... | Rust | 0 |
ity = pl & 0x7;
let old_priority = (self.F[8] & 0xE) >> 1;
if new_priority > old_priority {
self.pl_set(new_priority, ssr7, bus);
true
} else {
false
}
}
fn pl_retn(&mut self, bus: &mut Bus) {
// restore old priority level
let mut error = false;
loop {
let link_block_of... | Rust | 0 |
erive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub enum PinkEnvironment {}
impl Environment for PinkEnvironment {
const MAX_EVENT_TOPICS: usize = <ink_env::DefaultEnvironment as Environment>::MAX_EVENT_TOPICS;
type AccountId = <ink_env::DefaultEnvironment as Env... | Rust | 0 |
Y, sid.0 as u32),
UnifyCmd::Hyp => w.write_u8(UNIFY_HYP),
}
}
}
impl ProofCmd {
/// Serialize a `ProofCmd` to the given writer. Uses the `PROOF_*` commands in
/// [`mmb::export::cmd`](cmd/index.html).
#[inline] fn write_to(self, w: &mut impl Write) -> io::Result<()> {
match self {
... | Rust | 0 |
####################### Get a closer look of the object ########################
target = obj_bl_coords
target[1] += 0.4 # offset in y (backwards)
target[2] += 0.065 # offset in z (upwards)
if target[2] < 0.4:
wp = robot.get_named_eef_position(name="low_wp")
... | Python | 1 |
import pymysql
conn = pymysql.connect(host="localhost", user="root", password="", database="playersdb", port=3306)
cursor = conn.cursor()
query = "update player set plyname = 'Pusarla Venkata Sindhu' where plyid = 'PLY520'"
cursor.execute(query)
conn.commit()
conn.close() | Python | 1 |
visitor.visit_newtype_struct(self)
}
}
// Copyright 2020-2021, The Tremor Team
//
// 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... | Rust | 0 |
available, return `"unknown"`.
3 **version**: The document’s version (this field can also contain a date if no version number is found).
- Extract version identifiers such as 1.0, v2, Rev. 3, Edition B, Release 2024-A.
- Do not include any other characters than numbers or dots or dashes in the version.
... | Python | 1 |
iangle $t$ error bounds
let delta_e =
2.0 * (gamma(2) * max_xt * max_yt + delta_y * max_xt + delta_x * max_yt);
// Compute $\delta_t$ term for triangle $t$ error bounds and check _t_
let max_e = Vector3f::new(e0, e1, e2).abs().max_component();
let delta_t = 3.0 *
... | Rust | 0 |
&redis::PubSub) {
// block until a new message is received
let res = get_chan_message(ps);
// block again until the message is consumed
// this prevents the tx from dropping since .send() is async
let _ = tx.send(res);
}
pub fn get_pubsub(host: &str, channel: &str) -> redis::PubSub {
let clien... | Rust | 0 |
+ Send,
{
pub conn: C,
pub(crate) context: Context,
pub(crate) cache: &'a Cache,
}
/// Interface for Toql functions
#[async_trait]
impl<'a, C> Backend<Row, ToqlMySqlAsyncError> for MySqlAsyncBackend<'a, C>
where
C: Queryable + Send,
{
fn registry(&self) -> std::result::Result<RwLockReadGuard<'_, Ta... | Rust | 0 |
{}'", g.name),
};
details.push_str(format!("\nFrom user with display_name '{}'", msg.author.name).as_str());
if let Some(cname) = msg.channel_id.name(&ctx.cache).await {
details.push_str(format!("\nFrom channel '{}'", cname).as_str());
}
msg.reply(ctx, format!("Ping received.\n{}", details))... | Rust | 0 |
ult<IpAddr>>,
#[serde(
default,
rename = "listenerPort",
deserialize_with = "try_deserialize_u16"
)]
pub server_port: Option<anyhow::Result<u16>>,
#[serde(default, rename = "tlsCertificateFile")]
pub server_tls_cert_file: Option<PathBuf>,
#[serde(default, rename = "tlsPri... | Rust | 0 |
, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub type PF_NPAddConnection3 = ::core::option::Option<unsafe extern "system" fn(hwndowner: super::super::Foundation::HWND, lpnetresource: *const NETRESOURCEW, lppassword: ::windows_sys::core::PCWSTR, lpusername: ::windows_sys::core::PCWSTR, dwflags: u32) ... | Rust | 0 |
=> Some(Country::RS),
196 => Some(Country::RU),
197 => Some(Country::RW),
198 => Some(Country::SA),
199 => Some(Country::SB),
200 => Some(Country::SC),
201 => Some(Country::SD),
202 => Some(Country::SE),
203 => Some(Country... | Rust | 0 |
ALICE_PKEY_K256,
ALICE_MSG_ED25519_P256_K256,
);
fn _verify_works_multiple_signatures<K: FromJwk + KeySigVerify>(
kid: &str,
key: &str,
msg: &str,
) {
let res = _verify::<K>(kid, key, msg);
let res = res.expect("res is err"... | Rust | 0 |
import logging
import staketaxcsv.saga.constants as co
import staketaxcsv.common.ibc.handle
import staketaxcsv.common.ibc.processor
from staketaxcsv.saga.config_saga import localconfig
from staketaxcsv.settings_csv import SAGA_NODE
def process_txs(wallet_address, elems, exporter):
for elem in elems:
proc... | Python | 1 |
write_json_escaped_string(writer, entry.suffix)?;
write!(writer, "\"")?;
if index != entries.len() - 1 {
write!(writer, ",")?;
}
writeln!(writer)?;
}
writeln!(writer, "}}")?;
Ok(())
}
fn write_json_escaped_string<W>(writer: &mut W, string: &str) -> an... | Rust | 0 |
e_b": np.array(list(range(100, 200)), dtype=np.int32),
"feature_e": np.array(["Orange", "Apple"]),
"feature_f": np.array(["orange "]),
}
feature_manager = FeatureManager(
config_path="./examples", config_name="nested_features", log_transformation_chain=False
)... | Python | 1 |
_interface! {
$cls,
$field,
interface $base {
$($base_definition)*
}
}
};
(
$cls:ident, $field:ident,
interface $iface:ident {
vtable: $vtable:ident,
$($fs:tt)*
}
) => {
$crate:... | Rust | 0 |
}
}
unsafe extern "C" fn plug_added_trampoline<P>(this: *mut ffi::GtkSocket, f: glib_ffi::gpointer)
where P: IsA<Socket> {
let f: &&(Fn(&P) + 'static) = transmute(f);
f(&Socket::from_glib_borrow(this).downcast_unchecked())
}
unsafe extern "C" fn plug_removed_trampoline<P>(this: *mut ffi::GtkSocket, f: glib_ff... | Rust | 0 |
class Solution:
"""
@param: K: An integer
@param: P: An integer array
@return: Maximum profit
"""
def maxProfit(self, K, P):
if not K or not P:
return 0
n = len(P)
"""
if `K >= n`, this problem is just
`./lintcode/150_best_time_to_buy_and_sel... | Python | 1 |
icate=get_certificate(movie.releases),
runtime=movie.runtime,
stageDirector=build_full_name(movie.credits[0].person) if movie.credits else None,
synopsis=movie.synopsis,
title=movie.title,
type=movie.type,
visa=movie.releases[0].data.visa_number if movie.releases else Non... | Python | 1 |
me:8800/testdatabasename?tls=false"
);
settings.use_tls = None;
assert_eq!(
settings.uri(),
"mysql://test:testpassword@testhostname:8800/testdatabasename"
);
settings.hostname = "".to_string();
assert_eq!(
settings.uri(),
"m... | Rust | 0 |
-c", "import tkinter"], check=True, capture_output=True
)
print(" ✓ tkinter available")
except subprocess.CalledProcessError:
print(" ❌ tkinter NOT FOUND")
print(" This application REQUIRES tkinter, which is not installed.")
print(" Install it and re-run setup:")
... | Python | 1 |
from django.db import models
from django.contrib.auth.models import User
import shortuuid
from PIL import Image
import os
class ChatGroup(models.Model):
group_name = models.CharField(max_length=128, unique=True, blank=True)
groupchat_name = models.CharField(max_length=128, null=True, blank=True)
admin = mo... | Python | 1 |
>) -> Result<Response, ContractError> {
let cfg = CONFIG.load(deps.storage)?;
let astro = AssetInfo::Token {
contract_addr: cfg.astro_token_contract.clone(),
};
let mut response = Response::default();
// Collect assets
let mut assets_map: HashMap<String, AssetInfo> = HashMap::new();
... | Rust | 0 |
import cv2
import numpy as np
import matplotlib.pyplot as plt
# 读取图像
image = cv2.imread(
'Harris_watershed/text_image/2_10.png')
# 将图像转换为灰度图像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 对图像进行二值化处理
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
cv2.imshow('thresh',thresh)
cv2.waitKey(0)
cv2.... | Python | 1 |
= a / n
se = 1.96 * (math.sqrt((sensitivity * (1 - sensitivity)) / n))
SLCI = sensitivity - se
SUCI = sensitivity + se
except:
sensitivity = np.nan
SLCI = np.nan
SUCI = np.nan
n = b + d
t... | Python | 1 |
points1.len();
for i in 0..n {
for j in 0..n {
println!(
"{} to {}: {} | {}",
i,
j,
distance_matrix[i][j],
points1[i].distance_to(points2[j])
);
assert!... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.