text string | label_name string | labels int64 |
|---|---|---|
insert((x - min_x + 1, y - min_y), Tile::Clay);
});
Ok(grid)
}
}
impl Grid {
pub fn get_square_metres_water(&mut self) -> (usize, usize) {
let left = 500 - self.min.0 + 1;
self.get_tile(left, 0, &Direction::Both);
self.tiles
.values()
.map(|... | Rust | 0 |
lf }
}
#[doc = "Bit 15 - 15:15\\]
Write 1 to clear EVTOMCUFLAGS.AUX_TIMER2_PULSE. Read value is 0."]
#[inline(always)]
pub fn aux_timer2_pulse(&mut self) -> AUX_TIMER2_PULSE_W {
AUX_TIMER2_PULSE_W { w: self }
}
#[doc = "Bit 14 - 14:14\\]
Write 1 to clear EVTOMCUFLAGS.AUX_TIMER2_EV3. Read... | Rust | 0 |
from django.urls import path
from .views import (
post_list_and_create,
load_post_data_view,
post_detail,
like_unlike_post,
post_detail_data_view,
delete_post,
update_post,
)
app_name = 'posts'
urlpatterns = [
path('', post_list_and_create, name='main-board'),
path('like-unl... | Python | 1 |
n=int(input("enter number to find the sum"));
i=1
sum=0
while (i<=n):
sum=sum+i*i
i=i+1
print("sum=",sum)
| Python | 1 |
lf.binary(other, BinaryOp::Log)
}
/// Takes the squared root of this variable.
pub fn sqrt(&self) -> Var<K, Binary> {
self.pow_const(0.5)
}
}
impl<S> Var<Scalar, S> {
/// Initializes a new scalar variable.
pub(crate) fn scalar(tape: &Rc<Tape>, index: usize) -> Self {
Var::new(t... | Rust | 0 |
("Respects")),
created: Utc::now(),
updated: Utc::now(),
};
let mut g = Graph::<User, UserRelation>::new(GraphKind::Directed);
let chris = g.insert_node(chris);
let keewa = g.insert_node(keewa);
let jazi = g.insert_node(jazi);
let brian = g.insert_node(brian);
let fred = g.in... | Rust | 0 |
ion._applicableStyles), len(r1._styles))
self.assertEqual(NamedColors.red.value, r1.get_style(StyleProperties.BackgroundColor))
self.assertEqual(2.0, r1.get_style(StyleProperties.LuminanceGain))
body1 = list(r1)[0]
div1 = list(body1)[0]
p1 = list(div1)[0]
span1 = list(p1)[0]
self.assertEqu... | Python | 1 |
huntc/embassy<filename>embassy-traits/src/delay.rs
use core::future::Future;
pub trait Delay {
type DelayFuture<'a>: Future<Output = ()> + 'a;
/// Future that completes after now + millis
fn delay_ms<'a>(&'a mut self, millis: u64) -> Self::DelayFuture<'a>;
/// Future that completes after now + micros... | Rust | 0 |
::std::mem::size_of::<rte_bus_list>(),
16usize,
concat!("Size of: ", stringify!(rte_bus_list))
);
assert_eq!(
::std::mem::align_of::<rte_bus_list>(),
8usize,
concat!("Alignment of ", stringify!(rte_bus_list))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<... | Rust | 0 |
, Clone, PartialEq)]
pub struct Delay(u64);
impl Delay {
// Be more explicit about what kind of value we are expecting
pub const fn new_from_nanos(value: u64) -> Self {
Delay(value)
}
pub fn to_nanos(&self) -> u64 {
self.0
}
pub fn to_duration(&self) -> Duration {
Dura... | Rust | 0 |
= FileAttr {
ino: 1,
size: 0,
blocks: 0,
atime: UNIX_EPOCH, // 1970-01-01 00:00:00
mtime: UNIX_EPOCH,
ctime: UNIX_EPOCH,
crtime: UNIX_EPOCH,
kind: FileType::Directory,
perm: 0o755,
nlink: 2,
uid: 501,
gid: 20,
rdev: 0,
flags: 0,
};
const HELLO_TXT_ATTR: FileAttr ... | Rust | 0 |
)
if insert_pos > 0:
# Find the end of the if block
next_line_pos = content.find("\n", insert_pos)
next_line_pos = content.find("\n", next_line_pos + 1)
content = (
content[:next_line_pos]
+ "\n"
... | Python | 1 |
0;
#[doc = "`read()` method returns [acstat0::R](acstat0::R) reader structure"]
impl crate::Readable for ACSTAT0 {}
#[doc = "Analog Comparator Status 0"]
pub mod acstat0;
#[doc = "Analog Comparator Control 0\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](c... | Rust | 0 |
rank == 0:
# delete useless fields
fields.pop('tick'); fields.pop('step'); fields.pop('time'); fields.pop('reward', None); fields.pop('gsm_reward', None); fields.pop('math_reward', None); fields.pop('loss', None)
# convert string to float
wandb.log({k: float(v) for k, v i... | Python | 1 |
Ok(mapper(value))
}
/// Virtual address.
#[inline(always)]
pub fn virtual_address(&self) -> VirtualAddress
{
self.mapped_memory.virtual_address()
}
/// Size in bytes.
#[inline(always)]
pub fn size_in_bytes(&self) -> u64
{
self.mapped_memory.mapped_size_in_bytes() as u64
}
/// Size in bytes.
#[... | Rust | 0 |
_df.columns:
new_df = new_df.set_index("date")
ts = str(new_df.index[0])
time_unit = detect_time_unit(ts)
new_df.index = pd.to_datetime(new_df.index, unit=time_unit)
new_df = new_df[~new_df.index.duplicated(keep="first")]
new_df = new_df.sort_index()
columns_to_drop = ["ignore", "dat... | Python | 1 |
urn self._process_layer_image(layer_image, layer.name)
except Exception as e:
logger.debug(f"Method 2 failed for {layer.name}: {e}")
# 方法3: PSD全体の状態制御による抽出
logger.debug(f"Trying method 3 for {layer.name}")
# 全レイヤーを非表示にして状態を保存
original_states ... | Python | 1 |
from ..node_base import (
PhMaterialMathNode,
PhColorSocket,
PhColorSocketWithFloatDefault)
from psdl import sdl
from bmodule import naming
import bpy
class PhClampNode(PhMaterialMathNode):
bl_idname = 'PH_CLAMP'
bl_label = "Clamp"
def to_sdl(self, b_material, sdlconsole):
... | Python | 1 |
Promise = future_to_promise(async move {
client
.publish_diff(&message, diff.deref())
.await
.wasm_result()
.and_then(|receipt| JsValue::from_serde(&receipt).wasm_result())
});
Ok(promise)
}
/// Publishes arbitrary JSON data to the specified index on the Tangle.
#[... | Rust | 0 |
import pydantic
import typing_extensions
class V1PhotoColorizerCreateBodyAssets(typing_extensions.TypedDict):
"""
Provide the assets for photo colorization
"""
image_file_path: typing_extensions.Required[str]
"""
The image used to generate the colorized image. This value is either
- a dir... | Python | 1 |
# Copyright 2020 Open Source Robotics Foundation, Inc.
# All rights reserved.
#
# Software License Agreement (BSD License 2.0)
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must ... | Python | 1 |
warp::get()
.and(user_api_v1_path_prefix())
.and(warp::path::end())
.boxed()
}
// $curl localhost:8000/api/user/v1
pub fn do_login() -> BoxedFilter<(LoginRequest,)> {
warp::post()
.and(user_api_v1_path_prefix())
.and(path("login"))
.and(path::end())
.and... | Rust | 0 |
Get the optional `EventFd` object to inject interrupt to the virtual machine.
fn notifier(&self) -> Option<&EventFd>;
/// Clone a boxed dyn trait object.
fn clone_boxed(&self) -> Box<dyn InterruptNotifier>;
/// Convert `self` to `std::any::Any`.
fn as_any(&self) -> &dyn Any;
}
#[cfg(feature = "l... | Rust | 0 |
import tkinter as tk
from tkinter import ttk
from app.config import Config
def init_styles(theme: str, root_config = None) -> None:
style = init_main_theme(root_config)
match theme:
case "Dark":
load_dark_theme(style, root_config)
case "Light":
load_light_theme(style, r... | Python | 1 |
import requests
import json
import os
from config import Config
def get_access_token():
"""
使用 API Key,Secret Key 获取access_token,替换下列示例中的应用API Key、应用Secret Key
"""
API_Key = Config.API_Key
Secret_Key = Config.Secret_Key
url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentia... | Python | 1 |
ntage >= min
})
&& defaults
.max_buy_base_royalty_percentage
.map_or(true, |max| token_bonding.buy_base_royalty_percentage <= max)
&& defaults
.max_sell_base_royalty_percentage
.map_or(true, |max| {
token_bonding.sell_base_royalty_percentage <= max
})
&& defaults
... | Rust | 0 |
Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct InstantiateMsg {
pub staking_token: String, // lp token of PSI-UST or nAsset-PSI pair contract
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ExecuteMsg {
Receive(Cw20Recei... | Rust | 0 |
(missing_docs)]
Spam = 2,
#[allow(missing_docs)]
Privacy = 3,
#[allow(missing_docs)]
JiTapGameNotPlaying = 4,
#[allow(missing_docs)]
Other = 5,
}
impl JigReportType {
#[allow(missing_docs)]
pub fn as_str(&self) -> &'static str {
match self {
JigReportType::Offens... | Rust | 0 |
as u16;
let val = val as u8 as u16;
let mut unit_field_val: u16 = unsafe { ::std::mem::uninitialized() };
unsafe {
::std::ptr::copy_nonoverlapping(&self._bitfield_2 as *const _ as
*const u8,
... | Rust | 0 |
-> Poll<Option<VecDiff<Self::Item>>> {
let GroupByKeyProj {
chunks,
key_fn,
last_key,
pending_operations,
pending_returns,
mut signal,
} = self.project();
if let Some(op) = pending_returns.pop_front() {
log::trace!("running queued op {:?}", &op);
return wrap_poll_result(op);
}
loop ... | Rust | 0 |
HashMap;
use std::default::Default;
use std::io::extensions::u64_from_be_bytes;
use serialize::{Decoder, Decodable, Encoder, Encodable};
use secp256k1::key::PublicKey;
use blockdata::utxoset::UtxoSet;
use network::constants::Network;
use wallet::bip32::{mod, ChildNumber, ExtendedPrivKey, ExtendedPubKey, Normal, Harde... | Rust | 0 |
= self.company_regimenes_ganancias_ids
partner_regimen = (
self.partner_id.commercial_partner_id.default_regimen_ganancias_id)
if partner_regimen:
def_regimen = partner_regimen
elif cia_regs:
def_regimen = cia_regs[0]
else:... | Python | 1 |
type Properties = SemitoneNotationToolProps;
fn create(props: Self::Properties, _link: ComponentLink<Self>) -> Self {
Self { props }
}
fn update(&mut self, _msg: Self::Message) -> ShouldRender {
true
}
fn change(&mut self, props: Self::Properties) -> ShouldRender {
if se... | Rust | 0 |
# -*- coding: utf-8 -*-
"""
Task 22.1c
Copy the Topology class from task 22.1b and modify it.
Add a delete_node method that deletes all connections to the specified device.
If there is no such device, the message "There is no such device" is printed.
Topology creation:
In [1]: t = Topology(topology_example)
In [2... | Python | 1 |
use the variable defined previously
//! )
//! );
//!
//! let r = f(b"abcdabcdefghefghX");
//! assert_eq!(r, Ok((&b"X"[..], A{a: 1, b: 2})));
//!
//! let r2 = f(b"abcdefghefghX");
//! assert_eq!(r2, Ok((&b"X"[..], A{a: 1, b: 2})));
//! # }
//! ```
//!
//! The double right arrow `>>` is used as separator between every... | Rust | 0 |
Criterion::default().sample_size(10);
targets =
bench_solve_discrete_log,
}
criterion_main!(discrete_log);
<reponame>chancedrigor/ParakeetBot
mod bot;
mod commands;
mod config;
mod error;
mod youtube;
use color_eyre::Result;
use dotenv::dotenv;
use tracing_subscriber::{prelude::__tracing_subscriber_Subscriber... | Rust | 0 |
te_ss(update.from_user.id, False)
else:
await db.set_generate_ss(update.from_user.id, True)
await OpenSettings(update.message)
elif update.data == "triggerGenSample":
await update.answer()
generate_sample_video = await db.get_generate_sample_video(update.from_user.id)
... | Python | 1 |
/// Create a new Sentry layer that binds a new Sentry hub for each request made
pub fn new_from_top() -> Self {
Self {
provider: NewFromTopProvider,
_hub: PhantomData,
}
}
}
/// Tower service that binds a new Sentry hub for each request made.
pub type NewSentryService<S... | Rust | 0 |
import os
import toml
EXAMPLES_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "examples")
# List of all semantic roles to check (add/remove as needed)
ROLES = [
"ACCENT",
"HIGHLIGHT_BG",
"TEXT",
"DIM",
"WARNING",
"SUCCESS",
"ERROR",
"STATUS_BAR",
"BREADCRUMB_BAR",
... | Python | 1 |
(1, 0x00);
mcu.set_register(2, 0xF0);
let memory_data = vec![0x12, 0x20];
mcu.load_program_memory(&memory_data);
assert_eq!(mcu.get_program_counter(), 0x0);
mcu.step();
assert_eq!(mcu.get_program_counter(), 0x2);
assert_eq!(mcu.get_register(1), 0x00);
let flags = mcu.get_flags();
ass... | Rust | 0 |
yield f"data: {chunk.json()}\n\n"
yield f"data: [DONE]\n\n"
return StreamingResponse(wrapper_astream_search(), media_type="text/event-stream")
# API端点
@app.post("/api/chat_completions")
async def chat_completions(request: ChatCompletionRequest):
"""
模拟 webserver 的 /v1/chat/completions 端点
"""... | Python | 1 |
river;
let driver_port = manager.context.options.driver_port;
let browser = &manager.context.options.browser;
// Spawn the driver
span.add_event("Spawning process".to_string(), vec![]);
let child = subtasks::launch_driver(driver, browser).await?;
*manager.context.driver_reference.driver.lock().... | Rust | 0 |
_uint.from_param(20000)), r"^<cparam '[LI]' \(20000\)>$")
self.assertRegex(repr(c_long.from_param(20000)), r"^<cparam '[li]' \(20000\)>$")
self.assertRegex(repr(c_ulong.from_param(20000)), r"^<cparam '[LI]' \(20000\)>$")
self.assertRegex(repr(c_longlong.from_param(20000)), r"^<cparam '[liq]' \(2... | Python | 1 |
Ignored*/&mut gtk::TextIter, end: /*Ignored*/&mut gtk::TextIter, flags: SortFlags, column: i32) {
// unsafe { TODO: call ffi::gtk_source_buffer_sort_lines() }
//}
fn undo(&self) {
unsafe {
ffi::gtk_source_buffer_undo(self.to_glib_none().0);
}
}
fn get_property_can_re... | Rust | 0 |
def K(a=3,b=5):
print(a,b)
z = 0
y = 0
k = K()
print(k) | Python | 1 |
} else {
if has_room_left {
vec![
" ╝".into(),
"..".into(),
" ╗".into(),
]
} else {
vec![
" ║".into(),
" ║"... | Rust | 0 |
def get_mask_card_number(card_number: int) -> str:
"""
Принимает номер карты в виде числа и возвращает строку
в формате XXXX XX** **** XXXX
:param card_number: номер карты, например 2102123456789012
:return: Маска номера, например '2102 12** **** 9012'
"""
card_str = str(card_number)
# ... | Python | 1 |
per5.SetInputConnection(tex5.GetOutputPort())
byuActor5 = vtkActor()
byuActor5.SetMapper(byuMapper5)
byuActor5.SetTexture(texture)
byuActor5.GetProperty().SetColor(GetRGBColor('peach_puff'))
# Add the actors to the renderer, set the background and size
#
ren1.AddActor(byuActor)
ren1.AddActor(byuActor2)
ren1.AddActor(... | Python | 1 |
from server import PromptServer
from aiohttp import web
import os
import inspect
import json
import importlib
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
import pysssss
root_directory = os.path.dirname(inspect.getfile(PromptServer))
workflows_directory = os.path.join(root_directory, "pyss... | Python | 1 |
from __future__ import annotations
from typing import TYPE_CHECKING
from pandas.plotting._matplotlib.boxplot import (
BoxPlot,
boxplot,
boxplot_frame,
boxplot_frame_groupby,
)
from pandas.plotting._matplotlib.converter import (
deregister,
register,
)
from pandas.plotting._matplotlib.core impo... | Python | 1 |
eholders[1]
title2.text = "簡報大綱 (Presentation Outline)"
content2.text = """1. 研究背景與問題 (Background & Problem)
• LEO 衛星網路挑戰
• 傳統換手限制
2. MC-HO 演算法 (Core Algorithm)
• 雙重連線架構
• 條件式觸發機制
3. 演算法流程 (Algorithm Flow)
• 4-Phase 設計
• 時序圖分析
4. 數學模型 (Mathematical Model)
• 距離計算公式
• 路徑損耗模型
5. 實驗... | Python | 1 |
(batch_size, input_features, device=cuda_device)
h = torch.randn(batch_size, state_size, device=cuda_device)
C = torch.randn(batch_size, state_size, device=cuda_device)
rnn = LLTM(input_features, state_size).to(cuda_device)
forward = 0
backward = 0
for _ in range(100000):
start = time.... | Python | 1 |
from pymoo.core.crossover import Crossover
import numpy as np
import abc
class AbstractCrossover(Crossover, abc.ABC):
def __init__(self, cross_prob: float = 0.9):
# define the crossover: number of parents and number of offsprings
super().__init__(2, 2)
self.cross_prob = cross_pr... | Python | 1 |
take(attrs), ctx),
));
}
};
for scope in self.contents {
match scope {
CssScopeContent::Attribute(m) => attrs.push(m),
CssScopeContent::AtRule(m) => {
flush_attrs(&mut attrs, &mut contents, ctx);
... | Rust | 0 |
TEST_API_KEY, TEST_SECRET_KEY)
.and_then(move |_| ps.get_dataset(FIXTURE_DATASET_NAME)),
)
});
if ds.is_err() {
panic!("{}", ds.unwrap_err().to_string());
}
}
#[test]
fn fetching_dataset_generic_works_with_id() {
let ds = run(&ps(... | Rust | 0 |
dResults<T> {
pub items: Vec<T>,
pub count_extras: usize,
}
impl PlatformDetails {
pub fn new_using_rustc(target_triple: &str) -> CargoResult<Self> {
let attrs = fetch_attrs(target_triple)?;
Ok(Self::new(target_triple.to_owned(), attrs))
}
pub fn new(target_triple: String, attrs: Vec<Cfg>) -> Self {... | Rust | 0 |
import paramiko
# 远程服务器的连接信息
hostname = '1.u2936308.nyat.app' # 远程主机地址
port = 43180 # SSH端口
username = 'ubuntu' # 登录用户名
password = '123456abc' # 登录密码(或者使用密钥认证)
# 创建一个SSH客户端实例
ssh = paramiko.SSHClient()
# 自动加载系统的known_hosts
ssh.load_system_host_keys()
# 如果远程服务器没有提供密钥,接受它
ssh.set_missing_host_key_policy(paramiko.... | Python | 1 |
tSpace(comm, (L0, F1), coordinates=(psi, rv))
u_hat = Function(T, buffer=ue)
du = curl(grad(u_hat))
du.terms() == [[]]
r, theta, z = psi = sp.symbols('x,y,z', real=True, positive=True)
rv = (r*sp.cos(theta), r*sp.sin(theta), z)
# Manufactured solution
ue = (r*(1-r)*sp.cos(4*theta)-1*(r-1))... | Python | 1 |
();
for (i, _) in grid.iter().enumerate().rev() {
for (j, _) in grid[i].iter().enumerate().rev() {
if i == grid.len() - 1 && j != grid[0].len() - 1 {
dp[i][j] = dp[i][j] + dp[i][j + 1];
} else if j == grid[0].len() - 1 && i != grid.len() - 1 {
... | Rust | 0 |
let store = match &server.store.0 {
ObjectStoreIntegration::InMemory(in_mem) => in_mem.clone().await,
_ => panic!("wrong type"),
};
let store = Arc::new(ObjectStore::new_in_memory(store));
let mut recovered_server = Server::new(manager, store);
let server_c... | Rust | 0 |
let gpio = unsafe { &mut *GPIO0 };
let uart = unsafe { &mut *UART };
// Configure pin functions for UART
unsafe {
syscon.enable_clock(CLOCK_IOCON);
// Select RXD and TXD functions
iocon.write(PIO1_6, 1 | IOCON_MODE_PULL_UP);
iocon.write(PIO1_7, 1 | IOCON_MODE_PULL_UP);
... | Rust | 0 |
itting several fields, and only outputting what's
// necessary to pass the validation tool
vec![
input_lat1, input_lon1, azi1, input_lat2, input_lon2, azi2, s12, a12, m12,
]
} else {
vec![azi1, azi2, s12]
};
output_fields
... | Rust | 0 |
string::String>,
pub(crate) quantity: std::option::Option<i32>,
}
impl Builder {
/// <p>The ID of the catalog item.</p>
pub fn catalog_item_id(mut self, input: impl Into<std::string::String>) -> Self {
self.catalog_item_id = Some(input.into());
self
}
... | Rust | 0 |
0x30 => Instruction(Opcode::BMI, Addressing::Relative, 2),
0xD0 => Instruction(Opcode::BNE, Addressing::Relative, 2),
0x10 => Instruction(Opcode::BPL, Addressing::Relative, 2),
0x00 => Instruction(Opcode::BRK, Addressing::Implied, 7),
0x50 => Instruction(Opcode::... | Rust | 0 |
sum);
funcdef! ((vm) <sum_sig> sum VERSION sum_v1);
// entry
block! ((vm, sum_v1) blk_entry);
ssa! ((vm, sum_v1) <int64> blk_entry_n);
consta! ((vm, sum_v1) int64_0_local = int64_0);
consta! ((vm, sum_v1) int64_1_local = int64_1);
block! ((vm, sum_v1) blk_head)... | Rust | 0 |
from typing import Any, Generator, Callable, override
from Py4GWCoreLib import GLOBAL_CACHE, Routines, Range
from Widgets.CustomBehaviors.primitives.behavior_state import BehaviorState
from Widgets.CustomBehaviors.primitives.bus.event_bus import EventBus
from Widgets.CustomBehaviors.primitives.helpers import custom_be... | Python | 1 |
thor: Jiaqi Liu\n"
"Contact: liujiaqi@uec.ac.jp\n\n"
"Howtoplot is a versatile data plotting tool designed to handle "
"various data formats and generate customizable plots, including "
"line plots, boxplots, violin plots, and heatmaps. It supports drag-and-drop "
... | Python | 1 |
intln!("Key: {}; Value: {}", entry.key, entry.val);
/// }
/// }
/// ```
pub struct Ini {
/// All the sections of the file. The values can be modified at will.
pub sections: Vec<IniSection>,
}
/// A single section of an [`Ini`](crate::Ini).
pub struct IniSection {
/// The name of this section.
pub n... | Rust | 0 |
x8::new(1, 2, 3, 4, 5, 6, 7, 8);
let b = u16x8::new(0, 3, 2, 5, 4, 7, 6, 9);
let e = u16x8::new(2, 4, 6, 8, 3, 5, 7, 9);
let r: u16x8 = vpmaxq_u16(a.into_bits(), b.into_bits()).into_bits();
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vpmaxq_u32() {
... | Rust | 0 |
_u32`] mode where the blitter is automatically chosen.
pub const NCBLIT_DEFAULT: NcBlitter_u32 = ffi::ncblitter_e_NCBLIT_DEFAULT;
/// [`NcBlitter_u32`] mode using: space, compatible with ASCII.
pub const NCBLIT_1x1: NcBlitter_u32 = ffi::ncblitter_e_NCBLIT_1x1;
/// [`NcBlitter_u32`] mode using: halves + ... | Rust | 0 |
api_key=api_key,
stripe_version=stripe_version,
stripe_account=stripe_account,
params=params,
)
if not isinstance(result, ListObject):
raise TypeError(
"Expected list object from API, got %s"
% (type(result).__name__)
... | Python | 1 |
self,
file_offset,
vec: Some(vec),
pending_waker: None,
};
fut.await
.map(|(n, vec)| (n as usize, vec))
.map_err(AsyncError::Poll)
}
/// Reads to the given `mem` at the given offsets from the file starting at `file_offset`.
async ... | Rust | 0 |
ity::new(3384, "Estonia", "Kuressaare", 58.2480556, 22.5038891, 5.0),
City::new(3385, "Estonia", "Voru", 57.8338889, 27.0194435, 71.0),
City::new(3386, "Estonia", "Valga", 57.7778128, 26.0472965, 70.0),
City::new(3387, "Estonia", "Haapsalu", 58.9430556, 23.5413895, 8.0),
City::new(3388, "Estonia", "Johvi", 59.35916... | Rust | 0 |
f.name_len() + self.advertising_data.len()
}
fn name_len(&self) -> usize {
// The serialized name includes one byte indicating the type of name. That byte is not
// included if the name is empty.
match self.local_name {
Some(LocalName::Shortened(bytes)) | Some(LocalName::Com... | Rust | 0 |
fruit = input()
day = input()
quantity = float(input())
price = 0
if day == 'Monday' or day == 'Tuesday' or day == 'Wednesday' \
or day == 'Thursday' or day == 'Friday':
if fruit == 'banana':
price = 2.5
elif fruit == 'apple':
price = 1.2
elif fruit == 'orange':
price = 0.85
... | Python | 1 |
"How did your father make you feel?",
"How do you feel about your father?",
"Does your relationship with your father relate to your feelings today?",
"Do you have trouble showing affection with your family?"]],
[r'(.*) child(.*)',
[ "Did you have close friends as a child?",
"What is your favo... | Python | 1 |
psnr_val_rgb.append(utils.torchPSNR(res, tar))
psnr_val_rgb = torch.stack(psnr_val_rgb).mean().item()
if psnr_val_rgb > best_psnr:
best_psnr = psnr_val_rgb
best_epoch = epoch
torch.save({'epoch': epoch,
'state_dict': model_re... | Python | 1 |
age': page_num,
'_table': table_idx + 1,
'_row': row_idx + 1
}
for cell_idx, cell in enumerate(cells):
text = await cell.text_content()
if text:
text = text.strip().re... | Python | 1 |
.unbox::<f32>();
assert_eq!(out.unwrap(), -1.);
Ok(())
})
.unwrap();
});
}
#[test]
fn call2() {
JULIA.with(|j| {
let mut jlrs = j.borrow_mut();
let out = jlrs.scope_with_slots(3, |global, frame| unsafe {
let func = Module::bas... | Rust | 0 |
tag_ids_from_report_lines(xmlids),
table_references=query.from_clause,
search_condition=query.where_clause,
country_code='EE%',
groupby_clause=groupby_clause,
)
self.env.cr.execute(sql_query)
query_res_lines = self.env.cr.dictf... | Python | 1 |
from plots import *
from experiments import load_results
marker = ["o", "v", "D", "*", "1"]
d = load_results("swingup_gauss_offpolicy")
l = [7,6,8,9]
names = ["LSPE", "LSPE-TO", "LSTD-TO", "LSTD"]
for i in l:
m = d["methods"][i]
m.ls = "-"
m.name = names[0]
names = names[1:]
m.nobar = True
m.ma... | Python | 1 |
import undetected_chromedriver as uc
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
import time
import random
from parsing.modules.str_in... | Python | 1 |
();
while i < total {
let end = (i + Instance::MAX).min(total);
let amount = end - i;
let mut instances_buffer = staging_belt.write_buffer(
encoder,
&self.instances_buffer,
0,
wgpu::BufferSize::new(
... | Rust | 0 |
rved outcomes. Default is Green
color_e : str, optional
Color of the line/area for the treated group. Default is Blue
color_u : str, optional
Color of the line/area for the treated group. Default is Red
Returns
---------------
matplotlib axes
"""
... | Python | 1 |
task index is not used in this approach.
///
/// ```
/// use oqueue::Sequencer;
/// use std::sync::Mutex;
///
/// struct WorkItem(u8);
///
/// fn main() {
/// let oqueue = Sequencer::stderr();
/// let work = Mutex::new((b'A'..=b'Z').map(WorkItem));
///
/// // Launch 10 worker threads.
/// rayon::scope(|... | Rust | 0 |
bc\xa3lP\xae\x8c\x7f\xcf\xcb\xfc\xa3-\xed3\xd8\
\xbc;\x8d%u\x06\x9fb\xf8t\x81\x1a\x9e0\xf62\
23H\x18\xaan\xc4V\x0f\xc3d^\xe6\x98\xf1\xc3\
\x98\xc9\xc8SG\xd9\xbd\x82\x1e\xa9\xd3\xa5\x84\x8cl\xf5\
\x80x\xb4yd\xbc\x04\xf9\x00\x05bd\xeb\x0b\xbeV\
\xa7\xff\xdbp\xe9\xd7\x0c\xb7\x97\x15-^\x11:\x86b\
\x90\x91O}\xeaS\xb7\xfe\xe... | Python | 1 |
def falling(n, k):
"""Compute the falling factorial of n to depth k.
>>> falling(6, 3) # 6 * 5 * 4
120
>>> falling(4, 3) # 4 * 3 * 2
24
>>> falling(4, 1) # 4
4
>>> falling(4, 0)
1
"""
"*** YOUR CODE HERE ***"
i = 1
result = n
if k != 0:
while i < k:
... | Python | 1 |
e_options = {"Select ST Slope": -1, "Upsloping": 0, "Flat": 1, "Downsloping": 2}
slope_choice = st.selectbox(f'{label}', list(slope_options.keys()), help="0: Upsloping, 1: Flat, 2: Downsloping")
user_inputs[feature] = slope_options[slope_choice]
if slope_options[slope_choice] == -1:
... | Python | 1 |
ef err) if err.is_eof() => return Err(crate::ResponseError::NeedMoreData),
Err(err) => (Err(err), 0),
}
};
Ok((ListExternalAdmissionHookConfigurationResponse::Other(result), read))
},
}
}
}
// Generated from... | Rust | 0 |
sent for the rigid backed porous absorber device
// Firefox crashes if you attempt to draw a zero-width image, but Chrome and Brave are fine with this
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
let panel_width_px = panel_thickness_mm * ho... | Rust | 0 |
raceback.print_exc(50,sys.stderr)
sys.exit(1)
print("exit sever")
def exec_loop_cleanup(self):
pass
###################################################################
# spying stuff
def get_ps_stats(self):
ret=''
f=os.popen("echo ============ `hostname` u... | Python | 1 |
textbox,
// we make sure we will have at least the same height as the default textbox.
let min_height = 70.0;
let baseline = self.text.baseline_offset();
ctx.set_baseline_offset(baseline + padding_height);
bc.constrain(Size::new(
self.text_size.width + padding_width... | Rust | 0 |
];
Ok(Payout { amount, nullifier })
}
}
fn update_delta<G: AffineCurve>(
lagrange_commitments: &[G],
updates: &[SingleUpdate],
) -> G::Projective {
let bases: Vec<G> = updates
.iter()
.map(|u| {
// The first N lagrange commitments are reserved for public input
... | Rust | 0 |
Make a pretty string from an input shape
Example
--------
>>> X = np.random.rand(10, 4)
>>> X.shape
(10, 4)
>>> pretty_shape(X.shape)
'10 x 4'
"""
return " x ".join(map(str, shape))
def get_memory_usage():
# Get the current process
process = psutil.Process(os.getpid())
... | Python | 1 |
"""Module for the Bloom filter encoder."""
import hashlib
class BloomFilterEncoder:
"""Encoder of tokens and features via hashing and a Bloom filter.
The process for creating a cryptographically secure Bloom filter
encoding of a set of tokens is as follows:
1. Compute the hash digest for your token... | Python | 1 |
= n_vars - n_schemas;
for _ in 0..diff {
let schema = TypeSchema::Monotype(ctx.new_variable());
lex.0.write().expect("poisoned lexicon").vars.push(schema);
}
}
fn typed_context<'a>(
input: CompleteStr<'a>,
lex: &mut Lexicon,
ctx: &mut TypeContext,
) -> nom::IResult<CompleteStr<'a>, ... | Rust | 0 |
t("=", 1)
params[key.strip()] = value.strip()
# Parse data
data = None
if args.data:
try:
data = json.loads(args.data)
except json.JSONDecodeError:
print("Error: Invalid JSON in --data parameter")
sys.exit(1)
# Fetch data
result = fet... | Python | 1 |
#iteration_functions
from random import *
#create list
palitos =["-","--","---","----"]
#mix list
def mix(list):
shuffle(list)
return list
# select line
def select_line():
intento=''
while intento not in ['1','2','3','4']:
intento= input("elige un numero del 1 al 4: ")
return int(intento... | Python | 1 |
import re
txt = "The rain in Spain"
x = re.search("^The.*Spain$", txt)
print(x) # returns a match object | Python | 1 |
(s1: &mut String, s2: S2) {
add_end_slash_in_place(s1);
s1.push_str(delete_start_slash(s2.as_ref()));
delete_end_slash_in_place(s1);
}
/**
Concatenate multiple strings with slashes. It can also be used to get the literal `'/'`.
```
#[macro_use] extern crate slash_formatter;
assert_eq!("path/to/file", sla... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.