text string | label_name string | labels int64 |
|---|---|---|
# coding: utf-8
"""
KlimAPI - Calculation & Compensation API
This API offers you the possibility to calculate and offset emissions, create checkout links, get statistics and much more.
API Version: v2
Contact: tech@klimapi.com
Do not edit the class manually.
""" # noqa: E501
import unittest
... | Python | 1 |
invalid.
pub fn verify(
&self,
message: &impl AsRef<[u8]>,
signature: &impl AsRef<[u8]>,
) -> error::Result<()> {
self.method().verify(
message.as_ref(),
signature.as_ref(),
&self.method().as_bytes(&self.bytes),
)
}
/// Derive ... | Rust | 0 |
import lightgbm as lgbm
import pandas as pd
import numpy as np
from MLFeatureSelection import sequence_selection, importance_selection, coherence_selection,tools
def score2(pred, real): #针对s2的评分函数
print('score2')
compare = pd.merge(pred, real, how='left', on='user_id')
compare_for_S2 = compare[compare['bu... | Python | 1 |
()
.map(|ref b| b.to_uppercase())
.collect::<Vec<_>>();
if args.len() < 2 {
println!("available commands:");
for key in COMMANDS.iter().map(|s| s.to_lowercase()) {
println!(" - {}", key);
}
p... | Rust | 0 |
+ glXCreateContext;
// - 1.3
// - glXChooseFBConfig (log glXGetFBConfigAttrib) + glxCreateNewContext;
// - 1.4
// - GLX_SAMPLE_BUFFERS, GLX_SAMPLES (formerly ext GLX_ARB_multisample)
// - try glXCreateContextAttribsARB, otherwise same as 1.3;
// - GLX_CONTEXT_ROBUST_ACCESS_BIT_ARB
// - GLX_EXT_create_context... | Rust | 0 |
y_total2 * best_cme.energy_total
):
best_cme = cme
if self.keep_others:
other_cmes.append((cme, extra_info))
assert best_cme is not None
yield best_cme, other_cmes
class SumStage(Stage):
"""! Class that keeps yields only the sum of all cost ... | Python | 1 |
PROMPT_TEMPLATE = """
Answer the question based only on the following context:
{context}
---
Answer the question based on the above context: {question}
"""
| Python | 1 |
_CATEGORY_MASK : UProperty = 0x2000;
const UCHAR_MASK_START : UProperty = 0x2000;
// = UCHAR_GENERAL_CATEGORY_MASK
const UCHAR_MASK_LIMIT : UProperty = 0x2001;
const UCHAR_NUMERIC_VALUE : UProperty = 0x3000;
const UCHAR_DOUBLE_START : UProperty = 0x3000;
// = UCHAR_NUMERIC_VALUE
const UCHAR... | Rust | 0 |
ionHead {
type_id: TYPE_ID,
type_name: "Header",
};
lazy_static! {
/// Box object type companion
pub static ref S_HEADER_TYPE_COMPANION: STypeCompanion = STypeCompanion::new(
&S_HEADER_TYPE_COMPANION_HEAD,
vec
// #[repr(C)]
// #[derive(Default)]
pub struct VkDescriptorSetLayoutCreateFlags: u32 {
/// See [`VkDescriptorSetLayoutCreateFlagBits`](https://www.khronos.org/reg... | Rust | 0 |
import mdtraj
import numpy
parent = mdtraj.load('abl1_i1_eq_drude.pdb', top='abl1_i1_eq_drude.pdb')
traj = mdtraj.load('seg.dcd', top='abl1_i1_eq_drude.pdb')
dist1_parent = mdtraj.compute_distances(parent, [[1965,4239]], periodic=True)
dist1_traj = mdtraj.compute_distances(traj, [[1965,4239]], periodic=True)
dist2_p... | Python | 1 |
encoder.fit(X_copy[[col]])
self.encoders_[col] = encoder
feature_names = [f"{col}_{cat}" for cat in encoder.categories_[0]]
if self.drop == 'first':
feature_names = feature_names[1:]
self.feature_name... | Python | 1 |
PRIMARY_COLOUR = "indigo"
TEXT_COLOUR = "gray"
styles = {
# buttons
"button_primary_small": f"rounded bg-{PRIMARY_COLOUR}-600 px-2 py-1 text-xs font-semibold text-white shadow-sm hover:bg-{PRIMARY_COLOUR}-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-{PR... | Python | 1 |
sample = ((sample + 1) * 127.5).clamp(0, 255).to(th.uint8)
sample = sample.permute(0, 2, 3, 1)
sample = sample.contiguous()
gathered_samples = [th.zeros_like(sample) for _ in range(dist.get_world_size())]
dist.all_gather(gathered_samples, sample)
... | Python | 1 |
{
start: 30,
end: 40,
step: 2,
},
ConstValue::Rectangle(vec![50, -60, 70], vec![80, -90, 100]),
ConstValue::CellStateFilter(CellStateFilter::from_cell_states(100, &[0, 3, 10, 99])),
],
Ok(ConstValue::Void),
);
}
// ... | Rust | 0 |
rc/wrapper.c")
.includes(
str::replace(includes.as_ref(), "-I", "")
.split(' ')
.map(Path::new),
)
.compile("wrapper");
let mut bindgen = bindgen::Builder::default()
.header("src/wrapper.h")
.clang_args(includes.split(' '))
... | Rust | 0 |
.iter() {
cmd.push_char(' ');
append_arg(&mut cmd, *arg);
}
return cmd;
fn append_arg(cmd: &mut ~str, arg: &str) {
let quote = arg.iter().any(|c| c == ' ' || c == '\t');
if quote {
cmd.push_char('"');
}
for i in range(0u, arg.len()) {
... | Rust | 0 |
from abc import abstractmethod
import numpy as np
from artemis.ml.tools.processors import OneHotEncoding
__author__ = 'peter'
class IPredictor(object):
@abstractmethod
def train(self, input_data, target_data):
"""
:param input_data:
:param target_data:
:return:
"""... | Python | 1 |
from oxsConfig import ttk , W , E , fImu, imuPinVar, imuDisplayOffset,imuOffsetXVar,imuOffsetYVar,imuOffsetZVar
#define PIN_INT_6050 2 // Interrupt from 6050 has to be connected to Arduino pin 2 or pin 3 (do not use here the same pin as PPM)
#//#define DISPLAY_ACC_OFFSET // used ONLY in order to display the accele... | Python | 1 |
-------------------------------------------------------------
# ------------------------------------------------------------------------------
# Start code related to/from CPython's pyctype
# From the definition in CPython's Include/pyctype.h
# From: https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01b... | Python | 1 |
= <FilterConverter<Hero, DB, Ctx> as CreateFilter>::Filter;
///
/// # #[cfg(feature = "postgres")]
/// impl<Ctx> BuildFilterHelper<Pg, Filter<Pg, Ctx>, Ctx> for heros::table
/// where
/// Ctx: WundergraphContext + 'static,
/// Ctx::Connection: Connection<Backend = Pg>,
/// {
/// type Ret = Box<dyn BoxableF... | Rust | 0 |
ram
let args: Vec<String> = env::args().into_iter().skip(1).collect();
//Matches passed flag and does appropiate action
match &args[0] as &str {
"-i" | "--input" => {
//Do not run the program until input is specified check is here because -v is also arg
//count of 2
... | Rust | 0 |
pub fn inlink_dscr_bf0_ch2(&self) -> INLINK_DSCR_BF0_CH2_R {
INLINK_DSCR_BF0_CH2_R::new(self.bits as u32)
}
}
#[doc = "DMA_IN_DSCR_BF0_CH2_REG.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available ... | Rust | 0 |
if let Ok(s) = str::from_utf8(header) {
headers.push(s.to_string());
}
true
})?;
transfer.perform()?;
}
let result = String::from_utf8(result)
.map_err(|_| format_err!("response was invalid utf-8"))?... | Rust | 0 |
_panic(Path::new("./tests/data").join(file_name))
}
/// Load an image with the given name from the truth data directory "./tests/data/truth".
/// Panics if unable to find or load an image at this path.
fn load_truth_image(file_name: &str) -> DynamicImage {
load_image_or_panic(Path::new("./tests/data/truth").join(f... | Rust | 0 |
sure,
) -> Self
where
Resources::Wrapped: 'a,
LocalResources::Wrapped: 'a,
Closure:
FnMut(SystemContext<'a>, ResourceRefs, LocalResourceRefs, &mut Queries) + 'closures,
ResourceRefs: Fetch<'a, Resources::Wrapped, Markers> + 'a,
LocalResourceRefs: Fetch<'a, Loc... | Rust | 0 |
format(module.params['portgroup']))
if module.params['props']:
for key in module.params['props'].keys():
command_tokens.append('--prop:{}={}'.format(key, module.params['props'][key]))
if 'vm_password_key' in module.params and 'vm_password' in module.params:
command_tokens.append('--... | Python | 1 |
import cv2 as cv
import numpy as np
def rescale(frame,factor):
blurred_image = cv.GaussianBlur(frame, (5, 5), 0)
newDimensions=(int(blurred_image.shape[1]*factor),int(blurred_image.shape[0]*factor))
return cv.resize(frame,newDimensions,interpolation=cv.INTER_CUBIC)
def grayImg(frame):
return cv.cvtColo... | Python | 1 |
# 引入numpy库
import numpy as np
# 定义opeadd函数
def opeadd(m,b,n):
'''实现加法
参数:
m:是一个数组
b:是一个列表
n:是列表中的索引
你需要做的是 m+b[n]
返回值:
ret: 一个numpy数组
'''
ret = 0
# 请在此添加 创建多维数组 的代码 并赋值给ret
#********** Begin *********#
ret = m + b[n]
#********** End **********#
return ret
# 定... | Python | 1 |
# Copyright 2024 Samsung Electronics Co., Ltd. All Rights Reserved
from typing import List
def partition_layers_by_stage(total_layers: int, num_stages: int) -> List[int]:
"""
Function to partition layers by stage.
Parameters:
total_layers (int): Total number of layers.
num_stages (int): Nu... | Python | 1 |
GradientType=1, startColorstr=#c0ff3300, endColorstr=#ff000000); }\
\n"
)
.unwrap(),
"foo {\
\n filter: progid:DXImageTransform.Microsoft.gradient(GradientType=1, startColorstr=#c0ff3300, endColorstr=#ff000000);\
\n filter: progid:DXImageTransform.Microsoft.gradient... | Rust | 0 |
ution of Linux"""
if os.path.isfile("/etc/os-release"):
with open("/etc/os-release", "r") as f:
info = {}
for line in f:
key, _, value = line.partition("=")
info[key] = value.strip().strip('"')
return f"{info.get('NAME', 'Unknown')} {info.g... | Python | 1 |
assert!(
matches!(first_next, Err(err) if err == nom::error::Error::new(Span::new("+"), ErrorKind::Char))
);
assert!(
matches!(second_next, Err(err) if err == nom::error::Error::new(Span::new("-"), ErrorKind::Char))
);
}
<reponame>RGafiyatullin/reopenconnect<filename>src/cli/reopenconnec... | Rust | 0 |
rter = JsonExporter(indent=2,default = self.myconverter)
d = exporter.export(main_node)
# for bootstrap-treeview.js
d2 = d.replace("children", "nodes")
self.data = "[" + d2 + "]"
def generateHTML(self):
print "Generating HTML file - %s " % (self.output_file)
new_dat... | Python | 1 |
ror("Could not verify signature: {0}")]
Signature(#[source] ed25519_dalek::SignatureError),
}
impl VerificationError {
pub(crate) fn signature_not_found<T: Into<ServerNameBox>>(target: T) -> Error {
Self::SignatureNotFound(target.into()).into()
}
pub(crate) fn public_key_not_found<T: Into<Serv... | Rust | 0 |
"""
There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c.
A province is a group of directly or indirectly connected cities and no other cities outside of the group.
... | Python | 1 |
text_fg: Color,
network_rx_s_text_fg: Color,
network_rx_sparkline_fg: Color,
network_rx_sparkline_baseline_fg: Color,
network_tx_total_text_fg: Color,
network_tx_s_text_fg: Color,
network_tx_sparkline_fg: Color,
network_tx_sparkline_baseline_fg: Color,
stat_title_fg: Color,
stat_bor... | Rust | 0 |
ide_effect=mds._smacof_single)
monkeypatch.setattr("sklearn.manifold._mds._smacof_single", mock)
est = mds.MDS(metric=metric, normalized_stress="auto", random_state=rng)
est.fit_transform(X)
assert mock.call_args[1]["normalized_stress"] != metric
mds.smacof(dist, metric=metric, normalized_stress="... | Python | 1 |
_path) {
Ok(stream) => stream.into(),
Err(e) => proc_macro_error::abort!(attrs_span, format!("{}", e)),
}
}
// deprecated macro for backwards compatibility
#[deprecated(since = "0.6.2", note = "please use the #[marine] macro instead")]
#[proc_macro_error]
#[proc_macro_attribute]
pub fn fce_test(att... | Rust | 0 |
B::Star => {
if check_int_overflow {
InstrSeq::make_mulo()
} else {
InstrSeq::make_mul()
}
}
B::Slash => InstrSeq::make_div(),
B::Eqeq => InstrSeq::make_eq(),
B::Eqeqeq => InstrSeq::make_same(),
B::Starstar => In... | Rust | 0 |
&mut ns),
Err(Error::Undefined("x".to_string())));
let mut ns = CachedCallbackNamespace::new(|_,_| Some(3.0));
assert_eq!(
Parser::new().parse("x + 1", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(4.0));
assert_eq!(
Parser::new().parse("1.2 + int(3.4)", &... | Rust | 0 |
s program.
pub fn into_inner(self) -> CompiledProgram {
CompiledProgram {
modules: self
.modules
.into_iter()
.map(|module| module.into_inner())
.collect(),
script: self.script.into_inner(),
}
}
}
impl<'a> f... | Rust | 0 |
except:
pass # Label might already exist
# Apply label
try:
mail.store(email_id, '+X-GM-LABELS', f'"{label}"')
except Exception as label_err:
logger.info(f"DEBUG: Error applying label '{label}'... | Python | 1 |
case")]
#[serde(deny_unknown_fields)]
pub struct Size {
pub none: Color,
pub small: Color,
pub medium: Color,
pub large: Color,
}
#[derive(Debug, Deserialize, PartialEq)]
#[serde(rename_all = "kebab-case")]
#[serde(deny_unknown_fields)]
pub struct INode {
pub valid: Color,
pub invalid: Color,
}... | Rust | 0 |
def firstMissingPositive_extra_space(nums: list[int]) -> int:
if len(nums) == 1:
if nums[0] > 1:
return 1
elif nums[0] <= 0:
return 1
else:
return 2
tmp = set()
for num in nums:
if num > 0:
tmp.add(num)
if len(... | Python | 1 |
y 17 | Part 2", |b| b.iter(|| calculate_distinct(&input17)));
c.bench_function("Day 21 | Part 1", |b| b.iter(|| calculate_play(&input21)));
c.bench_function("Day 21 | Part 2", |b| b.iter(|| calculate_quantum(&input21)));
c.bench_function("Day 22 | Part 1", |b| b.iter(|| calculate_how_many_on_coords(&input22)));
c... | Rust | 0 |
egen.emit_push_value(value_id); // stack +2
codegen.emit(DbOp::Cmp);
let jmp_loc = codegen.current_location();
if min {
codegen.emit(DbOp::IfLess);
codegen.emit_u32(0);
} else {
codegen.emit(DbOp::IfGreater);
... | Rust | 0 |
chain_id,
epoch,
version,
timestamp_usecs,
}
} else {
todo!()
};
Ok(state)
}
}
use std::cmp::{min, max};
use std::collections::HashMap;
use rand::{Rng, ThreadRng, thread_rng};
use devesim::distributions:... | Rust | 0 |
g::Reg(Reg::RCX), X86Arg::Imm(2)),
X86::Cmp(X86Arg::Reg(Reg::RCX), X86Arg::Imm(0)),
X86::Je(error_label),
X86::Pop(Reg::RCX)]
}
fn ensure_tuple(a: X86Arg) -> Vec<X86> {
let error_label = Rc::new("internal_error_non_tuple".to_string());
vec![X86::Push(Reg::RCX),
X86::Mov(X86A... | Rust | 0 |
for i, omega2 in enumerate(omega2_l):
LOOCV_EPE = self._LOOCV(X, Y, p, omega2, U, W)
if i == 0:
LOOCV_EPE_l = LOOCV_EPE
else:
LOOCV_EPE_l = np.hstack((LOOCV_EPE_l, LOOCV_EPE))
return LOOCV_EPE_l
def _LOOCV(self, X, Y, p, omega2, U,... | Python | 1 |
from typing import Optional
from pip._internal.models.format_control import FormatControl
class SelectionPreferences:
"""
Encapsulates the candidate selection preferences for downloading
and installing files.
"""
__slots__ = ['allow_yanked', 'allow_all_prereleases', 'format_control',
... | Python | 1 |
ip()
if line:
if line.isupper() and not (line.startswith('Q:') or line.startswith('A:')):
if current_theme:
quotes_dict[current_theme] = '\n'.join(current_quote)
current_theme = line
if current_theme not in ... | Python | 1 |
if self.tools is not None:
return self.tools
tools: list[Tool] = []
# get tenant api providers
db_providers: list[ApiToolProvider] = (
db.session.query(ApiToolProvider)
.filter(ApiToolProvider.tenant_id == tenant_id, ApiToolProvider.name == self.ide... | Python | 1 |
_pending_reward,
premium_rate: legacy_pool_info.premium_rate,
short_reward_weight: legacy_pool_info.short_reward_weight,
premium_updated_time: legacy_pool_info.premium_updated_time,
migration_params: None,
};
new_pool_infos_bucket.save(asset.as_slice(), ne... | Rust | 0 |
varsort appears first
if node.type is not None and node.type != 'u':
sortinfo.append(node.type)
if properties and node.properties:
sortinfo.extend('{}={}'.format(k, v)
for k, v in node.properties.items())
if sortinfo:
return ' ' + ' '.join(sortinfo)
return... | Python | 1 |
00gn/T/pip-build-VQoj4y/pip/pip/_vendor/pyparsing.pys <genexpr> s t ]( R R ( R ( ( sf /private/var/folders/vy/31wknkcs30l6xb2fzgwnrkh80000gn/T/pip-build-VQoj4y/pip/pip/_vendor/pyparsing.pyR s R c C so g } xb | j D]W } | r2 | r2 | j | n t | t ... | Python | 1 |
"""
Write a function to convert degrees to radians.
assert radian_degree(90)==1.5707963267948966
"""
import math
def radian_degree(degrees):
"""
:param degrees: float or int
:return: float
"""
return math.radians(degrees)
if __name__ == "__main__":
assert radian_degree(90) == 1.570796326794896... | Python | 1 |
to a response."""
return zlib.compress(response)
def _log_error_once(self, message, message_key):
"""Log message with logging.ERROR level the first time, then log
with given level."""
if message_key not in self.log_message_keys:
self.logger.error(message + ' (further occ... | Python | 1 |
json"))
.remove()
.unwrap()
.take()
.unwrap();
let parser = PathParser::compile("$.store..price").unwrap();
let mut selector = JsonSelector::new(parser);
let result = selector.value(&result)
.select()
.unwrap();
assert_eq!(
result,
vec![
... | Rust | 0 |
import numpy as np
from scipy import linalg
Q = np.zeros((20, 20))
val = np.loadtxt("Data.csv", delimiter=";", encoding="utf-8-sig")
# Create matrix for linalg
for i in range(0, 20, 2):
k = int(i/2) # number of the song
ext_prob = val[k,1]/100 # probability of extending the song
skip_prob = val[k,2]/100... | Python | 1 |
ttps://www.khronos.org/registry/vulkan/specs/1.0-extensions/html/vkspec.html#vkCmdSetDiscardRectangleEXT)
pub fn vkCmdSetDiscardRectangleEXT(commandBuffer: vk::VkCommandBuffer, firstDiscardRectangle: u32, discardRectangleCount: u32, pDiscardRectangles: *const vk::VkRect2D); [pfn_vkCmdSetDiscardRectangleEXT: ext... | Rust | 0 |
import os
import json
from flask import request
def get_base_path():
# retorna o caminho do backend
return os.path.join(os.path.dirname(os.path.abspath('.')), 'backend')
def get_list_sites():
sites_dir = os.path.join(get_base_path(), 'sites')
print(f"Checking if {sites_dir} exists: {os.path.exists(si... | Python | 1 |
熱力圖')
plt.tight_layout()
plt.savefig('restaurant_analysis.png', dpi=300, bbox_inches='tight')
plt.show()
def generate_word_cloud(self):
"""生成詞雲"""
# 合併所有評論文字
all_text = ' '.join(self.reviews_df['text'].dropna())
# 使用jieba進行中文斷詞
... | Python | 1 |
e: hyper::Error },
#[snafu(display("Error serving RPC: {}", source))]
ServingRPC { source: self::rpc::Error },
#[snafu(display(
"Specified {} for the object store, required configuration missing for {}",
object_store,
missing
))]
MissingObjectStoreConfig {
object_st... | Rust | 0 |
import numpy as np
import trimesh
import vedo
from mik_tools import matrix_to_pose, pose_to_matrix, transform_matrix_inverse, tr, eye_pose
from mik_tools.aux.package_utils import get_test_mesh_path
from mik_tools.visualization_tools.vedo_tools import draw_mesh, draw_vectors, draw_points, draw_frame, get_object_mesh
f... | Python | 1 |
= RwLock::new(vec![]);
}
static CONTROLLER : AtomicIsize = AtomicIsize::new(0);
const NO_CONTROLLER : isize = -1;
pub struct GCContext {
immix_space : Option<Arc<ImmixSpace>>,
lo_space : Option<Arc<RwLock<FreeListSpace>>>
}
fn get_roots() -> Vec<ObjectAddr> {
vec![]
}
pub fn init(immix_space: Arc... | Rust | 0 |
**[Activities](trait.CallBuilder.html)**
//! * operations to apply to *Resources*
//!
//! All *structures* are marked with applicable traits to further categorize them and ease browsing.
//!
//! Generally speaking, you can invoke *Activities* like this:
//!
//! ```Rust,ignore
//! let r = hub.resource().activity... | Rust | 0 |
# '%{pattern}' ends with {pattern}
pattern = pattern.replace("*", "%")
sql = f"""SELECT {self.schema['primary_key']} FROM {self.tablename}
WHERE {self.schema['primary_key']} LIKE '{pattern}'"""
async with self.db.connection() as conn:
query_results = aw... | Python | 1 |
)| {
assignment
.consensus_commitments()
.into_iter()
.map(move |commitment| OwnedRightsLeaf(*type_id, commitment))
})
.collect()
}
}
#[derive(Clone, Copy, Ord, PartialOrd, Eq, PartialEq, Hash, Debug, StrictEncode, ... | Rust | 0 |
button(frame, text="Include '@' before each entry", variable=include_at_var,
command=display_ids)
include_at_check.grid(row=0, column=0, columnspan=4, padx=5, pady=5, sticky="w")
# Show names or IDs option
show_names_var = tk.BooleanVar(value=True)
show_names_check = tk.Checkbutton(fr... | Python | 1 |
&f!(&bz * &bz));
let sqc = f!(&f!(&cx * &cx + &cy * &cy) + &f!(&cz * &cz));
let cof1 = f!(&sqa * f!(&cx - &bx));
let cof2 = f!(&sqb * f!(&ax - &cx));
let cof3 = f!(&sqc * f!(&bx - &ax));
f!(f!(&cof1 + &cof2) + &cof3)
}
fn check_sign_det_x_x2y2z2(a: Vec3, b: Vec3, c: Vec3... | Rust | 0 |
dir, 'shortpi.h')).write_text('#define S_PI 3.14')
func = autowrap(expr, backend='cython', tempdir=tmpdir, code_gen=gen)
assert func(4.2) == 3.14 * 4.2
# check that the generated code is correct
for filename in os.listdir(tmpdir):
if filename.startswith('wrapped_code') and filename.endswith('... | Python | 1 |
z)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<RTCDisplacementFunctionNArguments>())).P_x as *const _ as usize
},
64usize,
concat!(
"Offset of field: ",
stringify!(RTCDisplacementFunctionNArguments),
"::",
s... | Rust | 0 |
from webweb import Web
web = Web(
title='oroboros',
adjacency=[[0, 1], [1, 2], [2, 3]],
metadata={
'isHead' : {
'values' : [True, False, False, False],
}
}
)
# oroboros begins chompin'
web.networks.oroboros.add_layer(
adjacency=[[0, 1], [1, 2], [2, 3], [3, 0]],
meta... | Python | 1 |
class JobSummary:
def __init__(self, jobs):
self.jobs = jobs
def get_salary_stats(self):
"""Calculate salary statistics"""
salaries = []
for job in self.jobs:
max_salary = job.get('salary_max', 0) or 0
min_salary = job.get('salary_min', 0) or 0
... | Python | 1 |
Box<ASTMap>),
}
impl AST {
#[no_coverage]
pub fn generate_string_in(&self, s: &mut String, start_index: &mut usize) -> ASTMap {
match self {
AST::Token(c) => {
let len = c.len_utf8();
let orig_start_index = *start_index;
s.push(*c);
... | Rust | 0 |
ttl: Some(1),
priority: None,
proxied: None,
name: domain,
content,
};
self.client
.request(&dns::CreateDnsRecord {
zone_identifier,
params,
})... | Rust | 0 |
else:
mark = 0
if user_input.lower() == 'a':
if complete_info:
user_input1 = auto_chat(history,name,most_prominent_discomfort,role_response,user,role_mood,background,financial_statement,relationship_history,occasion,task,decide,maslow_tips,advice)
else:
user_i... | Python | 1 |
apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Arbitrary implementations for `std::str`.
use crate::std_facade::Vec;
use core::iter::repeat;
use... | Rust | 0 |
.tight_layout()
if SPs['Do_SavePlots']:
plt.savefig(str(SPs['iavg'])+'_'+\
str(SPs['iPar1'])+'_'+str(SPs['iPar2'])+'_'+\
str(SPs['iPar3'])+'_'+str(SPs['iovt'])+'_Fx_on_Wall.png')
plt.show()
def Plot_hs(h,SPs):
if SPs['dimensions'] == 2: nd = 9
if SPs['di... | Python | 1 |
dorm_names.sort(key=lambda d: d, reverse=False)
added = []
# 竖向遍历出效率高到低
if not update:
for dorm in dorm_names:
free_found = False
for _idx, _dorm in enumerate(self.plan[dorm]):
if _dorm.agent == "Free" and _idx <= 1:
... | Python | 1 |
, 120.0);
// right
lowpass_filter(&mut right, mp3_sample_rate, 120.0);
}
// STORE DATA AS WAV
store_data_as_wav(&left, &right, path.as_path(), mp3_sample_rate);
// STORE SPECTRUM AS FILE AFTER LPF
samples_to_spectrum_and_plot(&left, mp3_sample_rate, "mp3-lowpassed-spectrum.png");
... | Rust | 0 |
import glob
import os
import xsearch as xs
from pcmdi_metrics.mean_climate.lib.pmp_parser import PMPParser
from pcmdi_metrics.misc.scripts import parallel_submitter
from pcmdi_metrics.precip_distribution.lib import AddParserArgument
num_cpus = 20
# Read parameters
P = PMPParser()
P = AddParserArgument(P)
param = P.... | Python | 1 |
one:
"""Sends an embed to discord with the new video."""
max_resolution = video.thumbnail.replace("/mqdefault.jpg", "/maxresdefault.jpg")
use_max_resolution = await self.image_exists(max_resolution)
if use_max_resolution:
video.thumbnail = max_resolution
embed = dis... | Python | 1 |
(("io", "parser", "data", "sauron.SHIFT_JIS.csv"), "shiftjis"),
],
)
def test_binary_mode_file_buffers(all_parsers, file_path, encoding, datapath):
# gh-23779: Python csv engine shouldn't error on files opened in binary.
# gh-31575: Python csv engine shouldn't error on files opened in raw binary.
pars... | Python | 1 |
, 3.0, 5.0, std::f64::NAN];
let min = vec.iter().partial_min().unwrap();
assert_eq!(&2.0, min);
}
#[test]
fn normal_min_by() {
let vec = vec![2, 3, 5, 27, 0];
let min_by = vec.iter().min_by(|&&num| num*num).unwrap();
assert_eq!(&0, min_by);
}
/*
#[test]
fn partial_min_by() {
let vec = vec![2.0, 3.0, 5.0, std::f... | Rust | 0 |
amp as (*mut TaiA));
TaiA::uint(&mut deadline as (*mut TaiA), 120u32);
TaiA::add(
&mut deadline as (*mut TaiA),
&mut deadline as (*mut TaiA) as (*const TaiA),
&mut stamp as (*mut TaiA) as (*const TaiA),
);
DnsTramsit::io(
... | Rust | 0 |
service(list_notification_preferences)
}
<reponame>rerkcp/azure-sdk-for-rust
#![allow(clippy::module_inception)]
#![allow(clippy::too_many_arguments)]
#![allow(clippy::ptr_arg)]
#![allow(clippy::large_enum_variant)]
#![doc = "generated by AutoRust"]
#[cfg(feature = "package-2021-12-01")]
pub mod package_2021_12_01;
#[c... | Rust | 0 |
ля по почте из токена
stmt = select(User).options(selectinload(User.role)).where(User.email == user_email)
result_user = await session.scalars(stmt)
user = result_user.first()
# Проверяем у него роль
await session.refresh(user)
user_role_name = user.role.name
if user_role_name not in setting... | Python | 1 |
proposed new observations.
while existing_timestamp.arrival > new_timestamp.arrival:
future_pending_deque.appendleft(existing_timestamp)
existing_timestamp = six.next(existing_timestamp_iter)
future_pending_deque.appendleft(new_timestamp)
# Find the next timestep at which `read` is cal... | Python | 1 |
rr)[y][x] = (*arr)[y+1][x];
}
}
}
for x in 0..NUM_COLS {
self.console.set_cell(x, NUM_ROWS-1, self.fg, self.bg, ' ' as u8);
}
self.x = 0;
self.y = NUM_ROWS - 1;
}
}
impl fmt::Write for Writer {
fn write_str(&mut self, s: &str) -> f... | Rust | 0 |
&mut self,
scalar: Scalar,
key: symmetric::Keypair,
) -> symmetric::Ciphertext
{
unimplemented!("Blinded issuance is not yet supported");
}
/// Append a hidden-at-issuance group element to the eventual
/// `AnonymousCredential` attributes.
///
/// # Returns
... | Rust | 0 |
* Script Input
* can be a file or line(stdin)
*/
pub trait SourceInput
{
//temp/non temp source?
//the lex/parse input
fn read_line(&mut self) -> old_io::IoResult<String>;
fn prompt<'a>(&'a self) -> &'a str; //Option?
fn prompt_update(&mut self, &str);
fn has_prompt(&self) -> bool
{
false
}
//lin... | Rust | 0 |
properties: Properties,
}
pub struct RaqoteTextLayout {
// TODO: Store reference?
font: RaqoteFont,
layout: Layout,
}
pub struct RaqoteTextLayoutBuilder {
// TODO: Store reference?
font: RaqoteFont,
text: String,
}
//We need this struct to avoid lifetime issues with raqote's Image type
pub s... | Rust | 0 |
{ do_something() }`
// test while_stmt
// while (true) {}
// while (5) {}
pub fn while_stmt(p: &mut Parser) -> CompletedMarker {
// test_err while_stmt_err
// while true {}
// while {}
// while (true {}
// while true) }
let m = p.start();
p.expect(T![while]);
condition(p);
stmt(
&mut *p.with_state(ParserSta... | Rust | 0 |
c.registers.a = 0x00;
c.execute();
assert_eq!(c.pc, 2);
assert_eq!(c.registers.a, 0xFF);
assert_eq!(c.flags.p, true);
assert_eq!(c.flags.a, false);
assert_eq!(c.flags.z, false);
assert_eq!(c.flags.s, true);
assert_eq!(c.flags.c, true);
}
... | Rust | 0 |
} else if !show_values {
let list = pushes
.iter()
.map(|d| d.name.clone())
.collect::<Vec<String>>();
println!("{}", list.join("\n"))
} else {
let mut hdr = vec![
"Name",
"Projects",
"Tags",
"Service",
... | Rust | 0 |
e % 20 == 0:
test_scores, test_steps = self.test_play(n_testplay=1)
with self.summary_writer.as_default():
tf.summary.scalar("test_score", test_scores[0], step=steps)
tf.summary.scalar("test_step", test_steps[0], step=steps)
if episode... | Python | 1 |
g", "setup.cfg", "[tox:tox]", id="cfg"),
pytest.param("", "pyproject.toml", '[tool.tox]\nlegacy_tox_ini = """\n[tox]\n"""\n', id="toml-dir"),
pytest.param("pyproject.toml", "pyproject.toml", '[tool.tox]\nlegacy_tox_ini = """\n[tox]\n"""\n', id="toml"),
],
)
def test_conf_arg(tmp_path: Path, conf_arg... | Python | 1 |
.delimiter(b'\t')
.from_path(filename)?;
// FIXME: Generate other op types
for (proc_id, proc_record) in &proc_records {
let proc = state.procs.get(&proc_id).unwrap();
for task in proc.tasks.values() {
let task_name = &state.task_kinds.get(&task.... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.