text string | label_name string | labels int64 |
|---|---|---|
S r / SQrSrSrSrSr SSKJrJr S r
S
rSS jrSS jr
SS
jrSS jrS rS rS r\S:X a \" 5 gg! \ a SrSr N>f = f)HConversions to/from quoted-printable transport encoding as per RFC 1521.encodedecodeencodestring... | Python | 1 |
|o| {
o.clock_mode_colour
.as_ref()
.map(|v| format!("\"{}\"", v.to_string()))
},
CLOCK_MODE_COLOUR,
),
#[cfg(feature = "tmux_1_0")]
(
"clock-mode-style",
|o, _, s| o.clock_mode_style = s.parse().ok(),
|o| o.clock_mode... | Rust | 0 |
foo").await;
session.zadd(user_id, "3", "zzz").await;
// check result BEFORE incrementing
let redis_tags = read_redis_tags(user_id_1(), session.redis())
.await
.expect("failed to get tags");
assert_eq!(vec!["zzz", "xxx", "foo"], redis_tags);
for _ in 0..... | Rust | 0 |
t == c).float(), axes=axes)
tp_hard = tp_hard.sum(0, keepdim=False).detach().cpu().numpy()
fp_hard = fp_hard.sum(0, keepdim=False).detach().cpu().numpy()
fn_hard = fn_hard.sum(0, keepdim=False).detach().cpu().numpy()
self.online_eval_foreground_dc.append(
... | Python | 1 |
ta.to`` is
accepted.
Returns
-------
Bell_state : qobj
:math:`\lvert B_{11}\rangle` Bell state
"""
dtype = _data._parse_default_dtype(dtype, "dense")
return bell_state('11').to(dtype)
def triplet_states(*, dtype: LayerType = None) -> list[Qobj]:
r"""
Returns a list of ... | Python | 1 |
breach_count:i32::from_le_bytes(*breach_count),
breach_count_this_window:u32::from_le_bytes(*breach_count_this_window),
work_cached:u64::from_le_bytes(*work_cached),
token_mint_id:Pubkey::new_from_array(*token_mint_id),
token_doubles:u64::from_... | Rust | 0 |
.age_hours,
}
if w.latest_run
else None
),
}
for name, w in self.workflows.items()
},
}
output_path.write_text(json.dumps(report, indent=2))
print(f"✅ JSON rep... | Python | 1 |
import metrics
assert type(y_preds) == type(y_probas)
if not(isinstance(y_preds,dict)):
y_preds={'clf':y_preds}
y_probas={'clf':y_probas}
models_report=pd.DataFrame()
conf_matrix={}
fig1,ax1=plt.subplots()
fig2,ax2=plt.subplots()
fig3,ax3=plt.subplots()
for clf in y_preds... | Python | 1 |
rs: addrs })
}
}
// The reason why we need to implement the PartialOrd trait is that the datastore library (a
// key-value storage) which we use allows performing queries where the results can be ordered.
//
// Since the struct that implements PartialOrd is internal and since we never use this ordering
// feature,... | Rust | 0 |
use crate::error::{BoxError, Context};
use thiserror::Error;
/// `Object`-related errors
pub type Error = crate::Error<ErrorKind>;
/// Kinds of `Object`-related errors
#[derive(Copy, Clone, Debug, Eq, Error, PartialEq)]
pub enum ErrorKind {
/// Invalid label
#[error("invalid label")]
LabelInvalid,
//... | Rust | 0 |
mask_hard: 0-1 array.
"""
if len(Input.shape) > 2:
Input = Input.squeeze(0).to(self.device)
with torch.no_grad():
mask_probs = self._actor_out(Input)
mask_hard = torch.round(mask_probs).detach()
return mask_hard, 0
def explain(self,... | Python | 1 |
# Generated by Django 5.0.7 on 2024-08-06 15:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("website", "0123_tag_issue_tags"),
]
operations = [
migrations.AddField(
model_name="company",
name="tags",
... | Python | 1 |
_code, non_upper_case_globals)] pub const UNSIGNED_INT_VEC4: types::GLenum = 0x8DC8;
#[allow(dead_code, non_upper_case_globals)] pub const UNSIGNED_NORMALIZED: types::GLenum = 0x8C17;
#[allow(dead_code, non_upper_case_globals)] pub const UNSIGNED_SHORT: types::GLenum = 0x1403;
#[allow(dead_code, non_upper_case_globals)... | Rust | 0 |
to timestampConverter() but works for a different string format.
Requires: timestamp_string argument to be a string in the "HOURShMINUTES" ('%Hh%M') format.
Ensures: returnal of the same timestamp but in datetime type.
"""
timestamp_datetime = datetime.datetime.strptime(str(timestamp_string), '%Hh%M')... | Python | 1 |
"""
Code for downloading data from camara de leis
"""
# pylint: disable=invalid-name
import argparse
import csv
import json
import pathlib
def from_json_to_csv(filepath):
"""
Transform json file to csv file
"""
with open(filepath, "r", encoding="utf-8") as f:
laws = json.load(f)
with open(... | Python | 1 |
:
'''将 Chat 对象转成 prompt str, 合并 human/assitant 输出为 format 字符串.'''
return f'{self.prompt_inout["input"]}{self.prompt_inout["output"]}'
@classmethod
def _format_packs(cls, packs: Dict[str, List[str]]) -> Dict[str, List[str]]:
'''格式化 pack 样本, 输出相同 pack inputs, outputs 个数.'''
_packs... | Python | 1 |
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
#ex1
print(car.get("model"))
#ex2
car["year"]=2020
#ex3
car["color"]="red"
#ex4
car.pop("model")
#ex5
car.clear() | Python | 1 |
q_weight=q_weight.astype("uint8"),
scale=scale.astype(dtype),
zero_point=zp if scheme == "asym" else None,
accuracy_level=accuracy_level,
)
model.add_initializers(new_inits)
model.remove_node(nod... | Python | 1 |
# phi_t(j,1)
phi_1 = np.tensordot(phi, q[:,:,1:], axes=2)
phi[:,1:] = phi[:,:-1] * q[:,:-1,0]
phi[:,0] = phi_1
tau = phi.sum(1)
# online sequence estimate (could improve using a filter)
seq[t] = np.argmax(tau)
# sufficient statistics updates
s = st... | Python | 1 |
"bne loop",
chr_data_ptr = in(reg) VID_RAM.as_ptr().offset(vid_ram_idx),
pxl_data_ptr = inout(reg) SCANLINE_PIXELS.as_mut_ptr() => _,
pxl_count = in(reg) 40,
char_rom_base = in(reg) CHAR_ROM_RAM.as_ptr(),
scanline_mod = in... | Rust | 0 |
el_len = buf.get_u16() as usize;
let protocol_len = buf.get_u16() as usize;
let required_len = label_len + protocol_len;
if buf.remaining() < required_len {
return Err(Error::UnexpectedEndOfBuffer {
expected: required_len,
actual: buf.remaining(),
... | Rust | 0 |
0f64, noise).unwrap();
for _ in 0..points_per_centroid {
// Generate points from each centroid
for centroid in centroids.row_iter() {
// Generate a point randomly around the centroid
let mut point = Vec::with_capacity(centroids.cols());
for feature in centroid.it... | Rust | 0 |
let body = resp.take_body().as_str().to_string();
assert!(body.contains("\"a\": Integer(123)"));
assert!(!body.contains("\"b\": Float(52.3)"));
assert!(!body.contains("\"b\": Float(32.3)"));
assert!(body.contains(&uuid1.to_string()));
assert!(body.contains(&uuid2.to_string()));
assert!(body.co... | Rust | 0 |
et (entry_5, (tmp_3, tmp_1)) = tmp_3.add_unequal(cs, tmp_1)?;
let (entry_6, (tmp_3, _)) = tmp_3.sub_unequal(cs, tmp_1)?;
let (entry_7, _) = tmp_3.sub_unequal(cs, tmp_0)?;
let params = entry_0.x.representation_params;
let entries = vec![
entry_0, entry_1, entry_2, entry_3, ... | Rust | 0 |
to_vec();
let mut file = OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(&self.path)
.await?;
file.write_buf(&mut buf.as_ref()).await?;
file.sync_data().await?;
Ok(())
}
}
<filename>src/commands/rerun_com... | Rust | 0 |
t<Cert, PickyError> {
// validity
let now = chrono::offset::Utc::now();
let valid_from = UTCDate::from(now);
let valid_to = UTCDate::from(now + chrono::Duration::days(INTERMEDIATE_DURATION_DAYS));
let subject_name = DirectoryName::new_common_name(intermediate_name);
let... | Rust | 0 |
h)
temp_module_path = os.path.join(temp_dir, module_name)
shutil.copyfile(module_path, temp_module_path)
# Run the IDA Pro extractBasicBlocks script
env_vars = os.environ.copy()
env_vars['TVHEADLESS'] = '1'
# This is requi... | Python | 1 |
from pyconnectwise.endpoints.base.connectwise_endpoint import ConnectWiseEndpoint
from pyconnectwise.interfaces import (
IGettable,
IPaginateable,
)
from pyconnectwise.models.automate import LabTechScanFrequency
from pyconnectwise.responses.paginated_response import PaginatedResponse
from pyconnectwise.types im... | Python | 1 |
Info2) -> MemoryRequirements2 {
let mut memoryRequirements = MemoryRequirements2::new();
unsafe { vkGetImageMemoryRequirements2(self, pInfo, &mut memoryRequirements) };
memoryRequirements
}
pub fn get_buffer_memory_requirements_2(self, pInfo : &BufferMemoryRequirementsInfo2) -> MemoryRequirements2 {
let mut ... | Rust | 0 |
# 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 under the Apache License, Version 2.0 (the
# "License"); you may not u... | Python | 1 |
ruct G(
#[proptest(weight = 3)]
Vec<u8>
);
#[derive(Debug, Arbitrary)] //~ ERROR: [proptest_derive, E0009]
struct H {
#[proptest(weight = 3)]
field: Vec<u8>
}
#[derive(Debug, Arbitrary)] //~ ERROR: [proptest_derive, E0009]
enum I {
V0 {
#[proptest(weight = 3)]
field: Vec<u8>
}
... | Rust | 0 |
# -*- coding: utf-8 -*-
from io import StringIO
from urllib.parse import urlencode
import re
import scrapy
from image360.items import GoodsItem
class TaobaoSpider(scrapy.Spider):
name = 'taobao'
allowed_domains = ['www.taobao.com']
def start_requests(self):
base_url = 'https://s.taobao.com/sear... | Python | 1 |
,
create_params: &CreateStructW<
<Self as CanHandleWin32Messages>::CreateParamTy,
>,
) -> Win32Result<CreationFlow> {
if let Err(e) = register_raw_input_devices(&[RawInputDevice {
hwnd_target: hwnd,
usage: HidUsage::GENERIC_MOUSE,
usage_page: HidUsagePage::GENERIC,
flags: RID... | Rust | 0 |
import pandas as pd
import numpy as np
from sklearn import svm
import matplotlib.pyplot as plt
# Read data from CSV file
recipes = pd.read_csv('svm1.csv')
# Extract features and labels
features = recipes[['Flour', 'Sugar']].to_numpy()
label = np.where(recipes['Type'] == 'Muffin', 0, 1)
# Train SVM model
model = svm.... | Python | 1 |
owed_native: NATIVE_TOKEN.to_string(),
initial_balance: Uint128::new(10000000000000),
coefficient_up: Uint128::new(20),
coefficient_down: Uint128::new(5),
coefficient: Uint128::new(20),
};
let env = mock_env();
let info = mock_info(
"a... | Rust | 0 |
lename = "orm2010.profile"
cProfile.runctx('runit()', globals(), locals(), filename)
stats = pstats.Stats(filename)
counts_by_methname = dict((key[2], stats.stats[key][0]) for key in stats.stats)
print "SQLA Version: %s" % __version__
print "Total calls %d" % stats.total_calls
print "Total cpu seconds: %.2f" % stats.... | Python | 1 |
copy_from_slice(input_row);
input_index += y_input_stride;
output_index += y_output_stride;
}
}
Ok(())
}
}
impl ConvertPixelFormat<I420> for NV12 {
fn convert(&self,
_: &I420,
output_pixels: &mut [&mut [u8]],
... | Rust | 0 |
wisdom\": 75,\n\t\t\t\"leads\": [ \n\t\t\t\t{\n\t\t\t\t\t\"name\": \'orc1\'\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t\"name\": \'orc3\'\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t\"name\": \'orc4\'\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t\"name\": \'orc5\'\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t\"name\": \'orc6\'\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\... | Rust | 0 |
")
.as_u64(),
};
let mut from = genesis;
let mut res = vec![];
while from <= max_block {
let to = if from + batch_size > max_block {
max_block
} else {
from + batch_size - 1
};
res.push(BlockBatch { from, to });
from = from + ba... | Rust | 0 |
,
metric_families,
basic_auth,
) {
Ok(_) => {}
Err(e) => {
debug!("push metrics error: {:?}", e);
}
};
}
#![cfg(feature = "ndarray")]
use ndarray::{Array1, Array2};
use rand::SeedableRng;
use rand_chacha::ChaCha20Rng;
use smawk::online_column_minima;
mod ran... | Rust | 0 |
256) -> Self::Output {
Self(self.0 / rhs)
}
}
impl ops::DivAssign<Uint256> for Decimal256 {
fn div_assign(&mut self, rhs: Uint256) {
self.0 /= rhs;
}
}
/// Serializes as a decimal string
impl Serialize for Decimal256 {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
... | Rust | 0 |
result::rustls_error(7000, &mut buf as *mut _, buf.len(), &mut n);
let output: String = String::from_utf8(buf[0..n].iter().map(|b| *b as u8).collect()).unwrap();
assert_eq!(&output, "OK");
rustls_result::rustls_error(7101, &mut buf as *mut _, buf.len(), &mut n);
let output: String = String::from_utf8(b... | Rust | 0 |
self.graphql::<Option<MinimizeData>, _>(
MINIMIZE,
serde_json::json!({
"node_id": node_id,
"reason": reason,
}),
)?;
Ok(())
}
pub fn internal(&self) -> &reqwest::Client {
&self.internal
}
fn graphql<T... | Rust | 0 |
(Either8, Eight, eight),
(Either7, Seven, seven),
(Either6, Six, six),
(Either5, Five, five),
(Either4, Four, four),
(Either3, Three, three),
(Either2, Two, two),
(Either1, One, one),
);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let either7 = match ... | Rust | 0 |
#!/usr/bin/python3
'''
Package initializer
'''
| Python | 1 |
_n_keys(self.to_glib_none().0) }
}
#[doc(alias = "gdk_device_get_name")]
pub fn name(&self) -> Option<glib::GString> {
unsafe { from_glib_none(ffi::gdk_device_get_name(self.to_glib_none().0)) }
}
#[doc(alias = "gdk_device_get_position")]
pub fn position(&self) -> (Screen, i32, i32) {
... | Rust | 0 |
t_literal => Ok(Expr {
kind: ExprKind::Nat(parsed.as_str().parse::<BigUint>().unwrap()),
}),
Rule::atom => Ok(Expr {
kind: ExprKind::Atom(parsed.as_str()[1..].to_string()),
}),
_ => unreachable!(),
}
}
pub fn parse(source: &str) -> ParseResult<Vec<Toplevel>> ... | Rust | 0 |
#!/usr/bin/env python3
import asyncio
task_wait_random = __import__('3-tasks').task_wait_random
async def test(max_delay: int) -> float:
task = task_wait_random(max_delay)
await task
print(task.__class__)
asyncio.run(test(5)) | Python | 1 |
pub fn commit_index(&self) -> u64 {
self.commit_index
}
pub fn set_commit_index(&mut self, value: u64) {
if self.commit_index < value {
self.commit_index = value;
}
}
}
impl Default for PersistentServerState {
fn default() -> Self {
PersistentServerState... | Rust | 0 |
DWORD,
uTitleBitmap: ::UINT,
cch: ::UINT,
pszTitle: *mut ::WCHAR,
}}
pub type LPTTGETTITLE = *mut TTGETTITLE;
pub const TTM_SETWINDOWTHEME: ::UINT = CCM_SETWINDOWTHEME;
pub type LPHITTESTINFOW = LPTTHITTESTINFOW;
pub type LPHITTESTINFOA = LPTTHITTESTINFOA;
STRUCT!{struct TTHITTESTINFOA {
hwnd: ::HWND,
... | Rust | 0 |
layout = self.layout_for_lang.get(lang, None)
if layout is None:
return self.default_setting
return layout
def load_layout_suggestions(self, path=None):
if path is None:
path = resource_path("kbds") + "/keyboard-configuration.yaml"
with open(path) as... | Python | 1 |
.len(), 0);
let token = nft_contract
.call(&worker, "nft_token")
.args_json((TOKEN_ID,))?
.view()
.await?
.json::<Token>()?;
assert_eq!(token.owner_id.to_string(), token_receiver_contract.id().to_string());
Ok(())
}
#[tokio::test]
async fn simulate_transfer_call_sl... | Rust | 0 |
mask](irqmask) module"]
pub type IRQMASK = crate::Reg<u32, _IRQMASK>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _IRQMASK;
#[doc = "`read()` method returns [irqmask::R](irqmask::R) reader structure"]
impl crate::Readable for IRQMASK {}
#[doc = "`write(|w| ..)` method takes [irqmask::W](irqmask::W) writer structur... | Rust | 0 |
e pass the tree so that we can infer the type of `T`.
///
/// `fine` is a function that gives the true distance between the `point`
/// and the specified tree element.
///
/// `broad` is a function that gives the distance between the `point`
/// and the closest point of a axis aligned rectangle. This function
/// is us... | Rust | 0 |
riter - FIFO 8k Push/POP Data Register. In ringbuffer mode, \\[16\\]
is treated as SOP (start-of-packet) by autodrain logic"]
pub struct PF8K_DATA_REG_W<'a> {
w: &'a mut W,
}
impl<'a> PF8K_DATA_REG_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u32) ->... | Rust | 0 |
,
}
impl<TDocument> Pending<TDocument> {
fn new<F>(fut: F) -> Self
where
F: Future<Item = SearchResponse<TDocument>, Error = Error> + Send + 'static,
{
Pending {
inner: Box::new(fut),
}
}
}
impl<TDocument> Future for Pending<TDocument>
where
TDocument: Deseriali... | Rust | 0 |
ego_pose, ego_pose_clean = ego_cav_base['params']['lidar_pose'], ego_cav_base['params']['lidar_pose_clean']
# calculate the transformation matrix
transformation_matrix = \
x1_to_x2(selected_cav_base['params']['lidar_pose'],
ego_pose) # T_ego_cav
... | Python | 1 |
/// # Arguments
/// * title (&String): the title for the to item to be created
///
/// # Returns
/// None
fn create(&self, title: &String) {
println!("{} is being created", title);
}
}<filename>tests/ifelse.rs
extern crate piske;
use piske::parse::program;
use piske::visitor::{Stat... | Rust | 0 |
samples <= 0.5 * log_k (1 + 2 ^ 64 (FACTOR - 1))
fn fregression(data: &[(f64, Duration)]) -> (f64, f64) {
if data.len() < 2 {
return (f64::NAN, f64::NAN);
}
// Do all the arithmetic using f64, because it can happen that the
// squared numbers to overflow using integer arithmetic if the
// te... | Rust | 0 |
// The header encoded at the beginning of .text by the linker script. It is
/// accessed by rust_start() using its text_start parameter.
#[repr(C)]
struct LayoutHeader {
got_sym_start: usize,
got_start: usize,
got_size: usize,
data_sym_start: usize,
data_start: usize,
data_size: usize,
bss_s... | Rust | 0 |
sentation::CSharpLegacy)
.is_err());
assert!(bin
.to_uuid_with_representation(UuidRepresentation::PythonLegacy)
.is_err());
assert!(bin
.to_uuid_with_representation(UuidRepresentation::PythonLegacy)
.is_err());
}
#[test]
fn test_binary_to_uuid_explicitly_standard_rep() {... | Rust | 0 |
from pathlib import Path
import json
# Read data as a string and convert to a Python object.
path = Path('eq_data/eq_data_1_day_m1.geojson')
contents = path.read_text(encoding='utf-8')
all_eq_data = json.loads(contents)
# Examine all earthquakes in the dataset.
all_eq_dicts = all_eq_data['features']
mags = []
for e... | Python | 1 |
messagebox.showerror("Error", "Please enter a percentage between 0 and 100!")
return
except ValueError:
messagebox.showerror("Error", "Please enter a valid percentage!")
return
base_dir = os.path.dirname(os.path.abspath(__file__))
if n == 9... | Python | 1 |
AND n with register A, result stored in A.
/// Flags [Z 0 1 0]
pub fn and(mmu: &mut MMU, n: u8) {
mmu.a &= n;
mmu.set_flag_z(mmu.a == 0);
mmu.set_flag_n(false);
mmu.set_flag_h(true);
mmu.set_flag_c(false);
}
/// Increment register value. Set Z if zero, H if half carry (bit 3), N reset.
/// Not to ... | Rust | 0 |
\n"
else:
inputs += f"{k}: {v:.3f}\n"
prompts, victims, labels, choicess = [], [], [], []
for target in df.columns:
if target in ["Gender", "Age", "Readmission", "Mechanical Ventilation"]:
continue
if target in feature_... | Python | 1 |
cation of the [`tima`](#structfield.tima) register.
pub const TIMA: u16 = 0xFF05;
/// Memory mapped location of the [`tma`](#structfield.tma) register.
pub const TMA: u16 = 0xFF06;
/// Memory mapped location of the [`tac`](#structfield.tac) register.
pub const TAC: u16 = 0xFF07;
#[derive(Debug, Clone)]
pub struct Time... | Rust | 0 |
set_one: |src, dst| unsafe { *(dst as *mut T) = ptr::read(src as *mut T) },
}
}
}
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
char_set::CharSet,
failure::{format_... | Rust | 0 |
h(CompileError::FieldNotFound {
field_name: field.clone(),
available_fields: available_fields.join(", "),
struct_name: type_checked_buf.last().unwrap().name.clone(),
});
return err(warnings, errors);
}
}
... | Rust | 0 |
class SeatBookingSystem:
def __init__(self):
# Initialize the seating arrangement with each seat marked as 'F'(F is free)
self.seats = {f"{i}{chr(j)}": "F" for i in range(1, 81) for j in range(65, 71)}
def check_availability(self):
# Check and print all available seats
available... | Python | 1 |
# A una clave, un valor:
my_dictionary = {
"key1": "value1",
"key2": "value2"
}
#Si se desea acceder a un elemento del diccionario
#se puede referir su clave colocándola dentro de corchetes, o usando el método get()
pol_esp_dictionary = {
"kwiat": "flor",
"woda": "agua",
"gleba": "tierra"
}... | Python | 1 |
ntr.exec_code();
assert_eq!((0, 30), host.xycors());
}
#[test]
pub fn interpreter_forward_const_repeat_const_times() {
let code = r#"
REPEAT 3 [FORWARD 5]
"#;
setup_interpreter!(code, env, cfg, host, intr);
let _ = intr.exec_code();
assert_eq!((0, 15), host.xycors());
}
#[test]
pub ... | Rust | 0 |
current_user.password = hash_password(update_data["password"])
current_user.update_timestamp()
await current_user.save(session=s)
return BaseResponse(code=0, msg="User information updated successfully")
@router.delete("/delete/{username}", response_model=BaseResponse)
async def delet... | Python | 1 |
ger.dict()
if args.article:
if args.templates:
if os.path.exists(args.templates):
with open(args.templates) as file:
load_templates(file)
file = fileinput.FileInput(input_file, openhook=fileinput.hook_compressed)
for page_data in pages_from(f... | Python | 1 |
for bot in self.bots if bot.positions),
"exited_bots": sum(1 for bot in self.bots if not bot.positions and bot.trade_history),
"waiting_bots": sum(1 for bot in self.bots if not bot.positions and not bot.trade_history),
"total_spent": float(total_spent),
"total_received": ... | Python | 1 |
true => None,
false => Some(binds),
},
privileged: Some(true),
port_bindings: Some(port_bindings),
restart_policy: Some(RestartPolicy {
name: Some(RestartPolicyNameEnum::UNLESS_STOPPED),
maximum_retry_count:... | Rust | 0 |
-> FilterMap {
let map = self.enabled.get();
#[cfg(debug_assertions)]
if self.counters.in_filter_pass.get() == 0 {
debug_assert_eq!(map, FilterMap::default());
}
map
}
}
/// This is a horrible and bad abuse of the downcasting system to expose
/// *internally* wh... | Rust | 0 |
#!/usr/bin/env python
import asyncio
import faust
WORDS = ['the', 'quick', 'brown', 'fox']
app = faust.App(
'word-counts',
broker='kafka://localhost:9092',
store='rocksdb://',
version=1,
topic_partitions=8,
)
posts_topic = app.topic('posts', value_type=str)
word_counts = app.Table('word_counts',... | Python | 1 |
Ok(file) = File::open(dir_entry.path()) {
let reader = BufReader::new(file);
return serde_json::from_reader(reader).ok();
}
}
}
None
}
//Commented out because it will change from machine to machine
// #[cfg(test)]
// pub mod test{
// use super::guess_def... | Rust | 0 |
ts::default(),
val.schema,
vec![s.unwrap().clone()],
);
}
#[test]
fn test_get_splits() {
let c = setup();
let mut p = Planner::new(c.config.clone());
let mut val = dbg!(p.get_table(
"".to_owned(),
"/aws/lambda/cwtest".to_owned(),
"2019/11/16/[$latest]05346b61111b... | Rust | 0 |
f"Creating virtual environment ({self.venv_backend}) using"
f" {resolved_interpreter_name} in {self.location_name}"
)
nox.command.run(cmd, silent=True, log=nox.options.verbose or False)
return True
@property
def venv_backend(self) -> str:
return self._ve... | Python | 1 |
|| {
// let id = semaphores.next();
// (id, id)
// });
// trace!("Schedule: {:#?}", schedule);
// trace!("Build nodes");
// for family in schedule.iter() {
// trace!("For family {:#?}", family);
// for queue in family.iter() {
// ... | Rust | 0 |
# Copyright (c) ONNX Project Contributors
# SPDX-License-Identifier: Apache-2.0
import numpy as np
from onnx.reference.ops._op import OpRunBinaryNumpy
class Max(OpRunBinaryNumpy):
def __init__(self, onnx_node, run_params): # type: ignore
OpRunBinaryNumpy.__init__(self, np.maximum, onnx_node, run_para... | Python | 1 |
if let Some(res) = body() {
match res {
0 => {
println!("Game exit successfully!");
}
_ => {
println!("Game exit with error code: {}", res);
}
};
break 'game;
}
... | Rust | 0 |
l other callbacks.
Args:
callbacks: A list of callbacks.
Return:
A new list in which the first elements are tuner specific callbacks and last elements are ModelCheckpoints
if there were any present in the input.
"""
tuner_callbacks: List[Callback] =... | Python | 1 |
def test_steps_offset(self):
for steps_offset in [0, 1]:
self.check_over_configs(steps_offset=steps_offset)
scheduler_class = self.scheduler_classes[0]
scheduler_config = self.get_scheduler_config(steps_offset=1)
scheduler = scheduler_class(**scheduler_config)
scheduler.set_timesteps(5)
... | Python | 1 |
import numpy as np
import asyncio
import os
from copy import deepcopy
from openai import AsyncOpenAI
openAI_client = AsyncOpenAI(api_key=os.getenv('OPENAI_API_KEY'))
port = str(2776 + int(os.getenv('SLURM_ARRAY_TASK_ID', 0)))
local_client = AsyncOpenAI(
base_url=f"http://localhost:{port}/v1",
api_key="key1",
... | Python | 1 |
POT START {} {{pid: {:?}, seed: {}}} >>>",
pot_name,
Pid::this(),
cfg.rng_seed,
);
let man = M::start(pot_name, mancfg, self.env, &logger);
thread::spawn({
let logger = logger.clone();
let man = man.clone();
move || {
... | Rust | 0 |
sert_allclose(softmax([1, 1]), np.array([.5, .5]), rtol=1e-13)
assert_allclose(softmax([0, 1]), np.array([1, np.e])/(1 + np.e),
rtol=1e-13)
# Expected value computed using mpmath (with mpmath.mp.dps = 200) and then
# converted to float.
x = np.arange(4)
expected = np.array([0.03... | Python | 1 |
"""
Write a function to find the nth tetrahedral number.
assert tetrahedral_number(5) == 35
"""
def tetrahedral_number(n):
"""
:type n: int
:rtype: int
"""
n += 1
return n*(n-1)/2 + 1
assert tetrahedral_number(5) == 35 | Python | 1 |
sult {
if existed {
write!(f, "{}", name)
} else {
match vars.get(*&name) {
Some(e) => write!(
f,
"{}",
ReprExpr {
expr: e,
vars: vars,
display_mode: IdentReprMode::Eager,
... | Rust | 0 |
__all__ = [
"BaseExceptionGroup",
"ExceptionGroup",
"catch",
"format_exception",
"format_exception_only",
"print_exception",
"print_exc",
"suppress",
]
import os
import sys
from ._catch import catch
from ._version import version as __version__ # noqa: F401
if sys.version_info < (3, 1... | Python | 1 |
-87,
-87, -88, -88, -88, -88, -89, -89, -90, -90, -90, -90, -91, -91, -91,
-92, -92, -92, -93, -94, -95, -95, -95, -95, -95, -95, -96, -96, -97,
-98, -98, -98
] as &[_]);
sort_by_key(&mut c, |x: &i64| x.abs());
assert!(
c.iter()
.zip(&c[1..])
.all(|(... | Rust | 0 |
elf) -> Layout {
self.inner.layout()
}
#[inline(always)]
unsafe fn as_ref(&self, ptr: Self::Ptr) -> Self::Item {
self.inner.as_ref(ptr)
}
#[inline(always)]
unsafe fn uget_ptr(&self, i: &Self::Dim) -> Self::Ptr {
self.inner.uget_ptr(i)
}
#[inline(always)]
fn... | Rust | 0 |
use std::alloc;
use std::hash::{Hash, Hasher};
use std::mem::MaybeUninit;
use std::{fmt, mem};
use crate::boxed::refs::Gc;
use crate::boxed::types::field_value::FieldGcRefIter;
use crate::boxed::*;
/// Numeric ID indicating which class the record belongs to
///
/// This is used to distinguish record types before each... | Rust | 0 |
t', None)
reference_audio_bytes = None
if reference_audio:
if not reference_audio.filename.lower().endswith('.wav'):
raise HTTPException(400, "Invalid audio format (must be WAV)")
reference_audio_bytes = await reference_audio.read()
... | Python | 1 |
ou it's insane how similar we are especially the food the food is so similar for example Mexicans love tortillas Indian people love naan bread which is a fluffier form of a tortilla Mexicans love chicken Indians love chicken Mexicans love hot and spicy Indians invented hot and spicy most popular drink in Mexico is Fant... | Python | 1 |
.raw.set_cell_status(i, j, status)
}
/// The mutable statuses of all the cells of this heightfield.
pub fn cells_statuses_mut(&mut self) -> &mut [HeightFieldCellStatus] {
self.raw.cells_statuses_mut().as_mut_slice()
}
}
use crate::{
after_effects::{
conv::{FromMultiDimensional, From... | Rust | 0 |
let Some(var_230) = &input.metric_name {
scope_229.string(var_230);
}
#[allow(unused_mut)]
let mut scope_231 = writer.prefix("Dimensions");
if let Some(var_232) = &input.dimensions {
let mut list_234 = scope_231.start_list(false, None);
for item_233 in var_232 {
#[al... | Rust | 0 |
# Copyright 2016 The TensorFlow 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 applica... | Python | 1 |
, without re-extracting a new mesh for the block. Which means changing the resolution for one block can cascade through constraints to re-generating a few other blocks as well
# Basic usage
Either try calling one of the functions in [extraction], or follow the example below:
```rust
// The first thing you need is a de... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.