text string | label_name string | labels int64 |
|---|---|---|
"""
------------------------------------------------------------------------------------------------------------------------
wfeatures_pandas.py
Copyright (C) 2019-22 - NFStream Developers
This file is part of NFStream, a Flexible Network Data Analysis Framework (https://www.nfstream.org/).
NFStream is free software: y... | Python | 1 |
import random
word_list = ['python', 'java', 'kotlin', 'javascript']
word = random.choice(word_list) # randomly choose a word from the list
print(word)
place_holder = ""
word_length = len(word)
for letter in range(word_length):
place_holder += "_" # create a placeholder for the word
print(place_holder) | Python | 1 |
table(bits: usize) -> Self {
let entries: u64 = 1 << bits;
let size = 1 << bits * 2;
let width = 3;
let key_width = 2;
let mut columns = vec![Vec::with_capacity(size); width];
let mut key_map = Map::with_capacity(size);
let mut row = 0;
for l in 0..entries... | Rust | 0 |
2048.);
}
},
seq::EventType::Noteoff => {
let data: seq::EvNote = ev.get_data().unwrap();
synth.remove_note(data.note);
},
_ => {},
}
Ok(true)
}
fn run() -> Result<(), Box<error::Error>> {
let (audio_dev, rate) = open_audio_dev()?;
l... | Rust | 0 |
(this is probably a bug in the hack_expr macro)",
));
}
};
Ok(out)
}
}
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
enum VarOp {
None,
Id,
Lvar,
Str,
Args,
}
fn prepare_hack(
input: LitStr,
default_pos: &TokenStream,
) -> Result<(String... | Rust | 0 |
import dexml
from dexml import fields
class PatchElement(dexml.Model):
class meta:
tagname = "patch"
order_sensitive = False
name = fields.String(tagname="name")
patchName = fields.String(tagname="patchName")
patchHash = fields.String(tagname="patchHash")
targetHash = fields.String(tagname="targetH... | Python | 1 |
_TYPE_INTERRUPT, endpoint, buffer, &[])
}
/// Create a bulk transfer.
pub fn new_bulk(endpoint: u8, buffer: Vec<u8>) -> Result<Transfer> {
Self::new(usb_sys::USBDEVFS_URB_TYPE_BULK, endpoint, buffer, &[])
}
/// Create an isochronous transfer.
pub fn new_isochronous(endpoint: u8, buffer... | Rust | 0 |
)
except SyntaxError:
traceback.print_exc()
sys.exit(1)
except BaseException as e:
traceback.print_exc()
print("Uncaught exception. Entering post mortem debugging")
print("Running 'cont' or 'step' will restart the program")
t = e.__... | Python | 1 |
name=str(input("¡Hola! cual es tu nombre: " ))
print(f"¡{name}! Vamos a verificar si 2 numeros son diferentes")
num1=int(input("Ingresa el primer valor "))
num2=int(input("Ingresa el segundo valor "))
resultado=(num1!=num2)
print("El resultado es:",resultado)
| Python | 1 |
x0 ~> 0x23333333], [0x0 ~> 0x23333333], [0x0 ~> 0x23333333], [0x0 ~> 0x23333333], [0x0 ~> 0x23333333], [0x0 ~> 0x23333333], [0x0 ~> 0x23333333], [0x0 ~> 0x23333333], [0x0 ~> 0x23333333], [0x0 ~> 0x23333333], [0x0 ~> 0x23333333], [0x0 ~> 0x23333333], [0x0 ~> 0x23333333], [0x0 ~> 0x23333333], [0x0 ~> 0x11999999]]
* Outp... | Rust | 0 |
arts_with("Rss") {
let values: Vec<&str> = l.split_whitespace().collect();
total += values[1].trim().parse::<u32>().unwrap();
}
}
total
}
// 10MB is our maximum accepted overhead.
const MAXIMUM_VMM_OVERHEAD_KB: u32 = 10 * 1024;
#[cfg_attr(not... | Rust | 0 |
CreditData {
campaign_id: 0,
credit: 400,
initial_credit_level: CreditLevel::Four,
rank_in_initial_credit_level: 0,
number_of_referees: 1,
current_credit_level: CreditLevel::Four,
... | Rust | 0 |
the provided storage key).
///
/// Also, that macro adds the code to initialize the structure if it wasn't initialized.
/// That macro requires one input argument - the storage key. It can be any Rust code that returns [u8; 32].
///
/// # Example:
/// ```
/// {
/// use brush::traits::Ac... | Rust | 0 |
: ddsfile::D3DFormat, srgb: bool) -> Option<rend3::types::TextureFormat> {
use ddsfile::D3DFormat as d3F;
use rend3::types::TextureFormat as r3F;
Some(match format {
d3F::A8B8G8R8 => {
if srgb {
r3F::Rgba8UnormSrgb
} else {
... | Rust | 0 |
/// mult_op: "\*|/|%";
///
fn mult_op_68(
&mut self,
tk_mult_op_0: &ParseTreeStackEntry,
parse_tree: &Tree<ParseTreeType>,
) -> Result<()> {
let context = "mult_op_68";
self.process_binary_operator(tk_mult_op_0, parse_tree, context)
}
/// Semantic action for ... | Rust | 0 |
import pandas as pd
def compute_features(df):
df["amount"] = pd.to_numeric(df["amount"], errors="coerce").fillna(0)
grouped = df.groupby("user").agg({
"amount": ["sum", "mean", "std"],
"action": lambda x: x.value_counts().to_dict(),
"timestamp": ["min", "max", "count"]
})
grou... | Python | 1 |
"""Adapted from
https://github.com/oittaa/uuid6-python/blob/main/src/uuid6/__init__.py#L95
Bundled in to avoid install issues with uuid6 package
"""
import random
import time
import uuid
from typing import Optional, Tuple
_last_v6_timestamp = None
class UUID(uuid.UUID):
r"""UUID draft version objects"""
__... | Python | 1 |
_pixel_format = r#try!(read_pixel_format(reader));
let s_caps = r#try!(read_scaps(reader));
let dw_reserved2: u32 = r#try!(reader.read_u32::<LE>());
return Ok(DDSHeader {
dw_magic: dw_magic,
dw_size: dw_size,
dw_flags: dw_flags,
dw_height: dw_height,
dw_width: dw_width,
dw_pitch_or_linear... | Rust | 0 |
;
};
if dep.req.matches(&incompatible_version) {
// If the declared dependency requirement claims this crate
// works with the incompatible future release, we deem the
// dependency silly and constrain it to remain compatible with
/... | Rust | 0 |
LocalName::from(args[0].get_str())),
attrs: args[1]
.get_obj()
.iter()
.map(|(k, v)| Attribute {
name: QualName::new(None, ns!(), LocalName::from(&**k)),
value: v.get_tendril(),
})
.colle... | Rust | 0 |
(self, RNone)
}
/// Replaces the value of `self` with `RSome(value)`.
///
/// # Example
///
/// ```
/// # use abi_stable::std_types::*;
///
/// let mut opt0=RSome(10);
/// assert_eq!(opt0.replace(55),RSome(10));
/// assert_eq!(opt0,RSome(55));
///
/// let mut opt1=R... | Rust | 0 |
# aula 28 de fevereiro de 2024
# métodos utilizados em listas
print('\n') # imprimi linha
lista1 = [0,1,2,3]
lista2 = [-3,-2,-1,0]
print(lista1) # imprimi [0,1,2,3]
print(lista2) # imprimi [-3,-2,-1,0]
print('\n') # imprimi linha
letra = ['a','b','c','d']
print(f'tamanho da lista: {len(letra)}') # tamanho... | Python | 1 |
FRESH_STENCILOP_KEEP: Refresh_StencilOp = 0;
pub const Refresh_StencilOp_REFRESH_STENCILOP_ZERO: Refresh_StencilOp = 1;
pub const Refresh_StencilOp_REFRESH_STENCILOP_REPLACE: Refresh_StencilOp = 2;
pub const Refresh_StencilOp_REFRESH_STENCILOP_INCREMENT_AND_CLAMP: Refresh_StencilOp = 3;
pub const Refresh_StencilOp_REFR... | Rust | 0 |
EN ? AND ?
""", (start_time, end_time))
history = cursor.fetchall()
conn.close()
os.remove(temp_path)
return print_opera_history([(url, utc_to_local(datetime.datetime.utcfromtimestamp(ts)).strftime('%Y-%m-%d %H:%M:%S')) for url, ts in history])
def extract_browsing_history(start_time_str, end... | Python | 1 |
k_val = self.cfg.ik_params["k_val"]
min_singular_value = self.cfg.ik_params["min_singular_value"]
# computation
# U: 6xd, S: dxd, V: d x num-joint
U, S, Vh = torch.linalg.svd(jacobian)
S_inv = 1.0 / S
S_inv = torch.where(S > min_singular_value, S... | Python | 1 |
text=m, channelIndex=ch, destinationId=nodeid
)
# # wait a 500ms to avoid message collision except after last message
# if message_list.index(m) < len(message_list) - 1:
# time.sleep(0.5)
else: # message is less than 160 cha... | Python | 1 |
et mut nums: Vec<Fr> = (0..half).map(|x| Fr::from_int(x as i32)).collect();
// // Act
// settings.das_fft_extension(&mut nums);
// // Assert
// let expected = [
// "40848550508281085032507004530576241411780082424652766156356301038276798860159",
// "6142039928270026418094108197259568351390689035055... | Rust | 0 |
Unable to fetch EC2 Instance info");
let iter = response.reservations.into_iter();
iter.flat_map(|reservations| {
reservations
.into_iter()
.flat_map(|reservation| reservation.instances.unwrap_or_default())
})
.collect()
}
<filename>src/funcs/mod.rs
mod healthnergy;
mod ... | Rust | 0 |
message."""
try:
content, times = spell # The spell can be any object. This Service expects (str, int) tuples.
content = str(content)
times = int(times)
except Exception as e:
content = f'WARNING: spell error {e}'
times = 1
text = f"W... | Python | 1 |
tadata={'token_usage': {'total_tokens': 257}, 'model_name': 'abab6.5-chat', 'finish_reason': 'tool_calls'}, id='run-d897e037-2796-49f5-847e-f9f69dd390db-0', tool_calls=[{'name': 'AnswerWithJustification', 'args': {'answer': 'A pound of bricks and a pound of feathers weigh the same.', 'justification': 'The weight of the... | Python | 1 |
self.visit_node(record_expr.expr);
for &case in record_expr.cases.values() {
self.visit_node(case);
}
}
fn visit_import(&mut self, _id: ir::NodeId, _import: &T) {}
fn visit_ref(&mut self, _id: ir::NodeId, ref_id: ir::NodeId) {
self.visit_node(ref_id)
}
}
<f... | Rust | 0 |
item_at(p, item);
// }
// #[inline]
// fn insert_item_at(&self, pos: usize, item: NodeItem<V>) {
// let mut self_items = self.items.borrow_mut();
// let mut n = self.n.borrow_mut();
// self_items[pos] = item;
// *n += 1;
// }
// #[inline]
// fn clear_node(&self)... | Rust | 0 |
# 1839. Longest Substring Of All Vowels in Order
# Medium
# A string is considered beautiful if it satisfies the following conditions:
# Each of the 5 English vowels ('a', 'e', 'i', 'o', 'u') must appear at least once in it.
# The letters must be sorted in alphabetical order (i.e. all 'a's before 'e's, all 'e's before... | Python | 1 |
#!/usr/bin/env python3
"""
AI Trading System - 安全功能整合演示
此腳本演示所有已實作的安全功能如何協同工作,
提供完整的安全防護體系。
"""
import sys
import time
from pathlib import Path
from decimal import Decimal
# 添加項目根目錄到 Python 路徑
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
def demo_security_workflow():
"""演示完... | Python | 1 |
features: `\"Win32_System_Ole\"`*"]
pub const VT_RESERVED: VARENUM = 32768i32;
#[doc = "*Required features: `\"Win32_System_Ole\"`*"]
pub const VT_ILLEGAL: VARENUM = 65535i32;
#[doc = "*Required features: `\"Win32_System_Ole\"`*"]
pub const VT_ILLEGALMASKED: VARENUM = 4095i32;
#[doc = "*Required features: `\"Win32_Sys... | Rust | 0 |
let disque = conn();
let j1 = disque.addjob(b"queue14", b"job14.1", Duration::from_secs(10), None, None, None, None, None, false).unwrap();
let j2 = disque.addjob(b"queue14", b"job14.2", Duration::from_secs(10), None, None, None, None, None, false).unwrap();
disque.addjob(b"queue14", b"job14.3", Duration:... | Rust | 0 |
);
JsonResponse::InternalServerError
}
}
}
#[put("/", data = "<new_list>")]
fn add(session: Protected, db: DigesterDbConn, new_list: Json<NewList>) -> JsonResponse {
use lists::AddError::*;
match lists::add(&db, session.0.user_id, new_list.name.clone()) {
Err(InvalidName(m... | Rust | 0 |
side_dense, pool = pool,
conv_act = conv_act, conv_bias = conv_bias,
dense_bias = dense_bias, input_type = input_type,
regularizer = self._regularizer,
embedding_dim = embedding_dim,
dropout_rate = dropout_rate,
regul_dense_only = regul_dense_only)... | Python | 1 |
}
});
// Send some numbers and retrieve the results
numbers_in.send(1).await.unwrap();
assert!(generated_stream.next().await == Some(4));
numbers_in.send(5).await.unwrap();
assert!(generated_stream.next().await == Some(8));
numbers_in.send(39).await.unwrap();
... | Rust | 0 |
#!/usr/bin/env python
##
## Author(s):
## - Cedric GESTES <gestes@aldebaran-robotics.com>
##
## Copyright (C) 2010 Aldebaran Robotics
##
#this tools, rewrite c/c++ headers
import sys
import re
import os
import random
regex_pragma_once = re.compile("^\s*\#pragma\s+once\s*$")
def read_header(fname):
""" check fo... | Python | 1 |
ool {
self.stacks[0].is_empty()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn should_switch_underlying_stacks() {
let mut stack_set = SetOfStacks::new(2);
stack_set.push(1);
stack_set.push(2);
assert_eq!(1, stack_set.n_of_stacks());
stack_set.p... | Rust | 0 |
reates a mutable iterator over the containing items.
pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut T> {
self.data.iter_mut().flat_map(|m| m.iter_mut()).map(|(_, v)| v)
}
/// Gets the given key's corresponding entry in the map for in-place
/// manipulation.
pub fn entry(&mut self, ... | Rust | 0 |
c_lang_code
sources_masked_tokenized = tokenizer(
sources_masked,
max_length=max_input_length,
truncation=True,
padding="max_length",
return_tensors="pt",
)
sources_tokenized["input_ids"][
sources_tokenized["input_ids"] == tokenizer.pad_token_id
] = -100
... | Python | 1 |
_stdin("a\n\0b")
.assert()
.success()
.stdout(indoc! {"
a -> _a_
\0b -> _\0b_
"})
.stderr("");
}
}
mod counter {
use super::*;
#[test]
fn local() {
rew()
.arg("--local-counter=2:3")
... | Rust | 0 |
import os
import json
import random
import asyncio
from pathlib import Path
from nonebot.matcher import Matcher
from nonebot.permission import SUPERUSER
from nonebot.params import CommandArg, ArgPlainText
from nonebot.adapters.onebot.v11 import Bot, Message, MessageEvent
from nonebot.adapters.onebot.v11 import GROUP_O... | Python | 1 |
{
false => SMPSEL_A::ABNORMAL,
true => SMPSEL_A::NORMAL,
}
}
#[doc = "Checks if the value of the field is `ABNORMAL`"]
#[inline(always)]
pub fn is_abnormal(&self) -> bool {
**self == SMPSEL_A::ABNORMAL
}
#[doc = "Checks if the value of the field is `NORMA... | Rust | 0 |
# Angle, hub,mean,tip
rotor1.beta2_metal = [beta_exit_flow[1] for _ in range(n_streamlines)]
stator2.beta2_metal = [beta_exit_flow[2] for _ in range(n_streamlines)]
rotor2.beta2_metal = [beta_exit_flow[3] for _ in range(n_streamlines)]
# These are all guessed values
stator1.loss_model = FixedPressureLoss(P0_Loss[0... | Python | 1 |
ment<BaseField = B>,
{
assert!(
evaluations.len().is_power_of_two(),
"number of evaluations must be a power of 2, but was {}",
evaluations.len()
);
assert_eq!(
evaluations.len(),
inv_twiddles.len() * 2,
"invalid number of twiddles: expected {} but received {}"... | Rust | 0 |
"""Module containing Galaxy workflow scheduling plugins. Galaxy's interface
for workflow scheduling is highly experimental and the interface required for
scheduling plugins will almost certainly change.
"""
from abc import (
ABCMeta,
abstractmethod,
)
class WorkflowSchedulingPlugin(metaclass=ABCMeta):
""... | Python | 1 |
import xml.etree.ElementTree as ET
from makewing import *
if __name__ == '__main__':
svgTree = ET.parse(sys.argv[1]).getroot()
span = 100
airfoil = getPoly(svgTree, colorExtract=(0,0,0), precision=.1)
topView = getPoly(svgTree, colorExtract=(1,0,0), precision=.1)
sideView = getPoly(svgTree, c... | Python | 1 |
() {
let mut input = String::new();
std::io::stdin().read_to_string(&mut input).unwrap();
let mut octopodes: Vec<Vec<_>> = input.lines().map(|line| {
line.chars().map(|c| (c.to_digit(10).unwrap() as u8, 0u8)).collect()
}).collect();
let octopus_count = octopodes.iter().flat_map(|row| row).c... | Rust | 0 |
-> &Self::Target {
&self.0
}
}
impl std::convert::From<String> for $name {
fn from(i: String) -> Self {
Self(i)
}
}
impl std::convert::From<&str> for $name {
fn from(... | Rust | 0 |
from llama_index.multi_modal_llms.openai.base import OpenAIMultiModal
__all__ = ["OpenAIMultiModal"]
| Python | 1 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 12 22:07:16 2018
@author: krupa
"""
import numpy as np
import copy
# =============================================================================
# Given Customer set, distance matrix, data information , initialised route, seq, velocity
# set of av... | Python | 1 |
("\nthis is a test msg body\n"),
};
assert_eq!(Ok(expected), build_pr_msg(Some(PR_EDITMSG_PATH)));
// it should preserve newlines
let mut f = File::create(PR_EDITMSG_PATH)?;
f.write_all(
b"test title\nthis is a test msg body\nit has multiple lines\nand \n- formatting\n- with bullets\n- :zap... | Rust | 0 |
Nodes {
left: Blueprint<BuilderComplexNode>,
right: Blueprint<BuilderComplexNode>
},
}
// Fixes in the Arc case:
// error[E0275]: overflow evaluating the requirement
// `std::sync::Arc<(dyn std::any::Any + std::marker::Send + std::marker::Sync + 'static)>: canning::Can<test_arc::BuilderComplexNode>`
#[allow(unsaf... | Rust | 0 |
from datetime import timedelta
from datetime import datetime
# 你需要分析的所有 pod 名字
pod_names = [
"300543077456", "299996111841", "298867645323", "298311908301",
"286904951031", "286898147618", "286893948098", "286860850513",
"286707440750", "286501394514", "285756932049", "285651484130",
"285606169490", "2... | Python | 1 |
arking_area,grid_size,obstacle_list,parking_spot_area)
#cost_map.find_vertices_of_obstacles()
cost_map.plot_original_parking_space()
cost_map.define_obstacle()
cost_map.define_parking_spot()
cost_map.define_vehicle()
cost_map.update_cost_map()
cost_map.turn_cost_map_to_array()
cost_m... | Python | 1 |
lot(phase_map_4iters,
phi0=0.2,
tburn=100,
tmax=100,
show_periodicity=True)
fig_cobweb_4iters.update_xaxes(title="phi_{i}")
fig_cobweb_4iters.update_yaxes(title="phi_{i+4}")
# update PRC plot
fig... | Python | 1 |
54168:
var17 = params[202]
else:
var17 = params[203]
else:
var17 = params[204]
else:
if inputs[0] >= -0.77728826:
var17 = params[205]
else:
if inputs[0] >= -0.80127764:
... | Python | 1 |
from sqlalchemy import Column, Integer, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.sql import func
Base = declarative_base()
class TimestampMixin:
"""Mixin for adding created_at and updated_at timestamps to models"""
created_at = Column(DateTime, default=func.now(),... | Python | 1 |
erver info (tools/resources)
try:
with st.spinner("🔍 Discovering MCP server..."):
# This will use cached discovery if available
tools, resources = get_mcp_server_info()
# If we get here, server is reachable
st.session_... | Python | 1 |
pes::{
Error, GScale16, GScale8, InterruptInfo, InterruptPinLatching, InterruptPinPolarity,
Measurement, OutputDataRate, Resolution, SlaveAddr, UnscaledMeasurement, WakeUpInterruptConfig,
WakeUpOutputDataRate, WakeUpTriggerMotion,
};
const DEVICE_BASE_ADDRESS: u8 = 0xE;
#[derive(Debug, Default, Clone, Cop... | Rust | 0 |
ir(proc_dir.as_path()).expect("mkdir proc");
mount(None, Some(proc_dir.as_path()), Some("proc"), MS_NOSUID|MS_NODEV|MS_NOEXEC);
}
// setup: a chance to populate root.
let setup_result = setup(container_root);
let old_root_name = "oldroot";
{
println!("En... | Rust | 0 |
import numpy as np
import pickle
from utils.AUV_energy_model import water_resistance, thruster_efficiency
import matplotlib.pyplot as plt
class AUV_1:
def __init__(self, env_data_path):
# 初始化函数,加载环境数据并设置AUV初始状态
with open(env_data_path, 'rb') as f:
self.depth_data, self.Vx_total, self.V... | Python | 1 |
est]
fn test_sparse_trigger_sparse_to_normal() {
let builder = PassThroughHasherBuilder {};
let mut hll: HyperLogLogPlus<u64, PassThroughHasherBuilder> =
HyperLogLogPlus::new(4, builder).unwrap();
// We have 5 registers every 4 bytes
// (1 << 4) * 4 / 5 = 12
for... | Rust | 0 |
self.types;
let mut rng = &mut self.rng;
let cells_temp: Tile<CellTemp> = self
.cells
.iter_cells()
.map(|&cell| rules::prepare_step(types, &mut rng, cell))
.collect();
self.cells = cells_temp
.iter_radius_1()
.map(|(temp,... | Rust | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# ds1054z documentation build configuration file
import sys
import os
import shlex
sys.path.insert(0, '..')
# General information about the project.
project = 'ds1054z'
copyright = '2015, Philipp Klaus'
author = 'Philipp Klaus'
version = 'v0.3.dev'
release = 'v0.3.dev'... | Python | 1 |
# The MIT License (MIT)
#
# Copyright (c) 2015-present, Xiaoyou Chen
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, c... | Python | 1 |
# this is the mappings of windows-1252 and utf-8 that MSXML warps
mappings = {0: b'\x00',
1: b'\x01',
2: b'\x02',
3: b'\x03',
4: b'\x04',
5: b'\x05',
6: b'\x06',
7: b'\x07',
8: b'\x08',
9: b'\t',
10: b'\n',
11: b'\x0b',
12: b'\x0c',
13: b'\r',
14: b'\x0e',
15: b'\x0f',
16: b'\x10',
17: b'\x11',
18: b'\x12',
19: b'\x13... | Python | 1 |
f\
1_9\xd9\x1ck\xd1\xdf\xb7!Hd\xeb\x1b\x18a\
\xe6\xac\x82Ud\x13\x95\x1c-^\xa1\x16\xa3\xce\xdbe\
/\x17\xc5\xd4\xab`\x03\xe7\xac\x9c\xff\x92yV\x8bI\
\xed\xfd\xbc\x0c+E\xc9\x18\xe9J41\x1d[Nd\
\xba\x22D|\xb2\xae\x1cT\xb1\x18\x84\x5cEQO\x9c\
sj9\x91U\xd2A\x13\xd5)`\x00h\xde\xb4\x01\
PA,T\x1b,\xd4\xfc\xa5\xe8q\x00A\x18\xd1p\... | Python | 1 |
.y1(2)
.line(ShapeLine::new().color(NamedColor::RoyalBlue).width(3.)),
);
layout.add_shape(
Shape::new()
.shape_type(ShapeType::Line)
.x0(2)
.y0(2)
.x1(5)
.y1(2)
.line(
ShapeLine::new()
... | Rust | 0 |
# Copyright (c) 2019 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 |
fer people");
};
// delete user
User::delete(u.id).expect("Unable to delete user");
return HttpResponse::Found().header("Location", format!("/{}/user_index", &lang)).finish()
} else {
println!("User does... | Rust | 0 |
= batch['target_lens']
for i, target in enumerate(batch['targets']):
target_len = gold_target_lens[i]
gold_targets.append(target[:target_len].tolist())
return OrderedDict([
('targets', targets),
('gold_targets', gold_targets)
... | Python | 1 |
"""Development script to get the multiplicity of the separation facets for some model coordination environments."""
from __future__ import annotations
from pymatgen.analysis.chemenv.coordination_environments.coordination_geometries import AllCoordinationGeometries
__author__ = "David Waroquiers"
__copyright__ = "Cop... | Python | 1 |
# License: BSD 3 clause
import unittest
import numpy as np
from tick.prox import ProxNuclear
from tick.prox.tests.prox import TestProx
class Test(TestProx):
def test_ProxNuclear(self):
"""...Test of ProxNuclear
"""
np.random.seed(seed=123)
a = np.random.randn(10, 10)
pro... | Python | 1 |
l='SDN', marker='o', s=100, alpha=0.6)
# Plot ISM points
ism_orders = []
ism_times = []
for order in range(1, N+1): # 1 to 4 (ISM doesn't have 0th order)
if order in TOA_order_ISM:
ism_orders.append(order)
ism_time... | Python | 1 |
(z.data == vec![50.0, 60.0, 114.0, 140.0, 514.0, 556.0, 706.0, 764.0])
&& (z.shape == vec![2, 2, 2])
)
}
#[test]
fn matmul_4d() {
let x = Tensor::new(
vec![
1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0,
... | Rust | 0 |
import pytest
from ase import Atoms
from ase.build import molecule
from ase.symbols import Symbols
@pytest.fixture()
def atoms():
return molecule('CH3CH2OH')
@pytest.fixture()
def symbols(atoms):
return atoms.symbols
def test_symbols_indexing(atoms):
print(atoms.symbols)
atoms.symbols[0] = 'X'
... | Python | 1 |
mode
pub spi1lpen: En, // SPI1 clock enable during Sleep mode
apb2lpenr_bit13: bit::N1, // Reserved, must be kept at reset value
pub syscfglpen: En, // SYSCFGEN clock enable during Sleep mode
apb2lpenr_bit15: bit::N1, // Reserved, must be kept at reset value
pu... | Rust | 0 |
assert_eq!(round(stats::attempts_to_reach_target(1, 6, 1), 4), 1.0000);
/// assert_eq!(round(stats::attempts_to_reach_target(1, 6, 4), 4), 1.5880);
/// assert_eq!(round(stats::attempts_to_reach_target(1, 6, 30), 4), 9.0476);
/// assert_eq!(round(stats::attempts_to_reach_target(1, 6, 36), 4), 10.7619);
/// assert_eq!(r... | Rust | 0 |
(PEB32, FlsListHead), 528);
assert_eq!(FIELD_OFFSET!(PEB32, FlsBitmap), 536);
assert_eq!(FIELD_OFFSET!(PEB32, FlsBitmapBits), 540);
assert_eq!(FIELD_OFFSET!(PEB32, FlsHighIndex), 556);
assert_eq!(FIELD_OFFSET!(PEB32, WerRegistrationData), 560);
assert_eq!(FIELD_OFFSET!(PEB32, WerShipAssertPtr), 564)... | Rust | 0 |
# Generated by Django 3.2.5 on 2021-07-12 22:28
from django.db import migrations
from django.conf import settings
def ensure_share_system_user(apps, schema_editor):
ShareUser = apps.get_model('share', 'ShareUser')
Source = apps.get_model('share', 'Source')
system_user = ShareUser.objects.filter(username... | Python | 1 |
'1'}],
'variables': [
{
'name': 'click',
'source': 'GOOGLE_ANALYTICS',
'role': 'FEATURE'
},
{
'name': 'subscribe',
'source': 'FIRST_PARTY',
'role': 'FEATURE'
},
{
... | Python | 1 |
from llama_cpp import Llama
import os
# Define the path to the model
model_path = os.path.join("models", "mistral-7b-instruct-v0.2.Q4_K_M.gguf")
# Check if the model file exists
if not os.path.exists(model_path):
print(f"Error: Model file not found at {model_path}")
print("Please download the model and place ... | Python | 1 |
import pytest
from django_prometheus.testutils import assert_metric_diff, save_registry
from testapp.models import Dog, Lawn
def M(metric_name):
"""Make a full metric name from a short metric name.
This is just intended to help keep the lines shorter in test
cases.
"""
return f"django_model_{met... | Python | 1 |
# This program utilizes the psutil library to obtain the MAC address of the network interface
# of the device running it. If the MAC address is an approved MAC address it can "access the network"
# If the MAC address isn't approved, the program will display "Access Denied"
import psutil
def get_mac():
# Get all ne... | Python | 1 |
impl_SET_b_r_x!(self, 5, h);
}
pub fn SET_5_r_l(&mut self) -> CycleType {
impl_SET_b_r_x!(self, 5, l);
}
pub fn SET_5_r_a(&mut self) -> CycleType {
impl_SET_b_r_x!(self, 5, a);
}
pub fn SET_6_r_b(&mut self) -> CycleType {
impl_SET_b_r_x!(self, 6, b);
}
p... | Rust | 0 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Enterprise Resellers',
'version': '1.0',
'summary': 'Enterprise counterpart for Resellers',
'description': 'Enterprise counterpart for Resellers',
'category': 'Website/Website',
'depend... | Python | 1 |
. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#![deny(warnings)]
#![allow(missing_docs)]
use failure::{format_err, Error};
use rand::{self, Rng};
use std;
use std::ffi::{CString, OsStr, OsString};
use std::fs::{read_dir, File, OpenOption... | Rust | 0 |
ut b as *mut B as *mut u8;
unsafe { ap.copy_to_nonoverlapping(bp, size_of::<A>()) };
Ok(b)
} else {
Err(PodCastError::SizeMismatch)
}
}
/// Try to convert a `&T` into `&U`.
///
/// ## Failure
///
/// * If the reference isn't aligned in the new type
/// * If the source type and target type aren't the sa... | Rust | 0 |
{
let instruction = Instruction::Goto(Condition::LessThan(5, 6), 55);
let c_constant = to_c_constant(&instruction);
assert_eq!(c_constant, "BI_GOTO_IF(LT, 5, 6, 55)")
}
#[test]
fn test_label_value() {
let instruction = Instruction::Label(23);
let c_constant = to_c_c... | Rust | 0 |
"""
测试主模块功能
"""
import os
import sys
from unittest.mock import MagicMock, patch
import pytest
# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from yop_mcp.main import (
yeepay_yop_api_detail,
yeepay_yop_download_cert,
yeepay_yop_gen_key_pair,
yeepay... | Python | 1 |
#!/usr/bin/env python
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
... | Python | 1 |
encode_bytes()?,
CallArgs::decode(src)?,
))
}
}
pub trait Call<FIELDS: CallFields> {
fn fields(self) -> FIELDS;
fn flags(&self) -> Flags;
fn args(&mut self) -> &mut CallArgs;
}
pub trait CallFields {
fn headers(&self) -> &HashMap<String, String>;
fn tracing(&self) -> &Traci... | Rust | 0 |
import os
from abc import ABC, abstractmethod
from typing import Any, List, Generator
import openai
import streamlit as st
from openai.openai_object import OpenAIObject
class ApiKey(ABC):
"""Check the Api key is valid or not"""
query = 'This is a test.'
@classmethod
@abstractmethod
def is_valid(... | Python | 1 |
enabled)))
}
fn query_terms(&self, term_set: &mut BTreeSet<Term>) {
for (_occur, subquery) in &self.subqueries {
subquery.query_terms(term_set);
}
}
}
impl BooleanQuery {
/// Helper method to create a boolean query matching a given list of terms.
/// The resulting query... | Rust | 0 |
>, &'static str> {
match cfg.ordering {
SolutionOrdering::BestToWorst => SudokuSolution::leaders_impl(cfg, db, tables::sudoku_solutions::score.desc()),
SolutionOrdering::WorstToBest => SudokuSolution::leaders_impl(cfg, db, tables::sudoku_solutions::score.asc()),
}
}
fn l... | Rust | 0 |
")
unit_tol = 0.001
X_csr = csr_matrix(X)
X_da_csr, y_da = _prep_training_data_sparse(client, X_csr, y, n_parts)
from cuml.dask.linear_model import LogisticRegression as cumlLBFGS_dask
mg = cumlLBFGS_dask(
fit_intercept=fit_intercept,
verbose=True,
standardization=standar... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.