text string | label_name string | labels int64 |
|---|---|---|
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
class IDGenerator:
"""
Tensor / Operator manager. To guarantee that each IRTensor / IROperator id
is unique and progressively increases.
This class is designed in singleton pattern.
"""
class __IDGenerator:
... | Python | 1 |
buf).await {
Ok(_) => {
let elapsed = tokio::time::Instant::now().duration_since(start);
println!(
"received response from outbound {} in {}ms",
&handler.tag(),
elapsed.as_millis()
... | Rust | 0 |
ut_selfies_validity(args)
evaluate(args.input_file, args.morgan_r, True)
"""
# retrosynthesis
python -m llava.eval.molecule_metrics.fingerprint_metrics \
--input_file=eval_result/moleculestm-retrosynthesis-5ep.jsonl
# reagent_pred
python -m llava.eval.molecule_metrics.fingerprint_metrics \
--inp... | Python | 1 |
8A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"></path>
</svg>
""",
"class": "",
},
],
}
autodoc_typehints = "description"
autodoc_typehints_description_target = "documented"
autodoc_class_signature = "separated"
pygments_style = "zenburn"
# -- Options for HTMLHelp o... | Python | 1 |
ypred: array![
1.73398006, 1.6375258, 1.56424946, 1.86392134, 0.88813238, 1.12646493, 0.85124713,
2.11783437, 2.13526103, 1.64689519
],
expected: array![
1.43146513e+01,
7.60592435e+00,
6.80199725e+00,
... | Rust | 0 |
"""
Utility code for manipulating AsciiDoc, in general, without regard to what the
AsciiDoc is being used for (whether it's journaling, manuscript writing,
whatever).
"""
import re
from .prose_utils import collapse_whitespace
ADOC_LINK = r"<<[-_A-Za-z0-9]+,([^>]*)>>"
ADOC_HEADING = r"^(={1,5})\s+(.*)$"
ADOC_BULLET = r... | Python | 1 |
tweets = t.user_timeline()
for tweet in tweets:
printf('----' * 10)
printf('Status: %s' % tweet.text)
printf('Posted at: %s' % tweet.created_at)
printf('----' * 10)
def _demo_update_status():
for api in APIs:
t = Twitter(api)
res = t.update... | Python | 1 |
xAlbertModel,
FlaxAlbertForPreTraining,
FlaxAlbertForMaskedLM,
FlaxAlbertForMultipleChoice,
FlaxAlbertForQuestionAnswering,
FlaxAlbertForSequenceClassification,
FlaxAlbertForTokenClassification,
FlaxAlbertForQuestionAnswering,
)... | Python | 1 |
# Generated by Django 5.0.4 on 2024-04-07 06:53
import django.utils.timezone
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app_users', '0001_initial'),
('auth', '0012_alter_user_first_name_max_length'),
]
operations = [
migrat... | Python | 1 |
annot use `allocate()` function
/// due to a borrow conflict of the page allocator:
/// - it borrows the page allocator to get the contents of a page.
/// - `allocate()` requires a mutable borrow of the page allocator.
/// This is solved by splitting `allocate()` into two functions:
/// `ensure_init... | Rust | 0 |
`∃(xor) => true1`
Red(app(Ex, Xor), True1.into()),
// `∃(eqb) => true1`
Red(app(Ex, Eqb), True1.into()),
// `∃(exc) => true1`
Red(app(Ex, Exc), True1.into()),
// `∃(imply) => true1`
Red(app(Ex, Imply), True1.into()),
// `∃(fstb) => true1`
Red(app(... | Rust | 0 |
else:
widgets.frame_brightness_content_ofDataset.setVisible(False)
# 清除算法
if "brightness" in SI.imageAugmentAlgorithm_ofDataset:
SI.imageAugmentAlgorithm_ofDataset.remove("brightness")
if "亮度" in SI.current_imageAugment_ofDat... | Python | 1 |
print(f'El resultado de la divion {numero_1}/{numero_2} es {float(numero_1)/float(numero_2)}')
except ValueError:
print('Error de valor')
except ZeroDivisionError:
print('Error division por cero')
else:
print('Impresion correcta')
finally:
print('Fin del programa de control')
'''/*
* DIFICULTAD ... | Python | 1 |
# 실전 문제 1 - 1로 만들기
# 1 <= X <= 30,000
X = int(input())
# 모든 경우의 수에 대해서, 완전 탐색을 해봐야 한다
# 근데.. 그걸 모든 X에 대해서 다 해보겠다고? 미친 짓이다
# 이 때 나오는 친구, DP
# 각각에서의 1로 만드는 최소 갯수를 재활용, 더 큰 문제에 쓴다는 마인드로다가
memo = [0] * (X+1)
# DP 진행 (Bottom-Up)
for i in range(2, X+1):
# 현재의 수에서 1을 빼는 경우
memo[i] = memo[i-1] + 1
# 현재의 수가 2로 나누어 떨어지는... | Python | 1 |
from fastapi import FastAPI
import logging
from app.kafka.UserCreatedComsumer import start_user_created_consumer, stop_user_created_consumer, get_user_created_consumer_status
from app.kafka.WallpaperCreatedComsumer import start_wallpaper_scraped_consumer, stop_wallpaper_scraped_consumer, get_wallpaper_scraped_consumer_... | Python | 1 |
on)
os.makedirs(output_dir, exist_ok=True)
print(f"Output directory is {output_dir}")
model_path = os.path.join(output_dir, "learned_ensemble_model.pkl")
if not os.path.exists(model_path):
# The model is just a simple average and does not require training
# Always default to the pickle file in case some of the ... | Python | 1 |
let move_to_target = hole.y + (width - hole.x);
// follow a 5-move pattern to shift the target data one to the left (minus 1 since it already moved once)
let top_row_pattern = 5 * (width - 1);
// the target data is now in the top left
navigate_wall + move_to_target + top_row_pattern
}
#[cfg(test)]
mo... | Rust | 0 |
rie.contains(input));
}
#[test]
fn it_can_return_previously_inserted_value() {
let mut trie: Trie<char, usize> = Trie::new();
let input = "abcdef".chars();
trie.insert_with_value(input.clone(), Some(666));
assert_eq!(trie.insert_with_value(input.clone(), Some(667)), Some(666... | Rust | 0 |
from robot_inteface.robot_interface import RobotInterfaceWithGripper
import time
from motion_planning.motion_planner import MotionPlanner
from motion_planning.geometry_and_transforms import GeometryAndTransforms
from robot_inteface.robots_metadata import ur5e_1, ur5e_2
target_position_world_rob1 = [-0.3, -0.5, 0.25]
t... | Python | 1 |
pr::Rel(_) => {
e.set_tag(Tag::Relation);
Ok(())
}
Expr::Uri(_) => {
e.set_tag(Tag::Uri);
Ok(())
}
Expr::Property(_) => {
e.set_tag(Tag::Property);
Ok(())
}
... | Rust | 0 |
print(f'found {len(chunk_offsets)} chunks to process')
random.shuffle(chunk_offsets)
burn_in_start = time.time()
n_burn_in_chunks = 10000
burn_in_chunk_offsets = chunk_offsets[:n_burn_in_chunks]
chunk_offsets = chunk_offsets[n_burn_in_chunks:]
for start_offset... | Python | 1 |
);
// Determine which border of the tile located at `Position` `pos` is in `compass_dir`.
let border_in_direction = self.get_border_for_pos(pos, compass_dir);
// Determine if `tile_matches` contains a match for the tile at `pos` and its border in
// `compass_dir`. If ... | Rust | 0 |
proto.MESSAGE,
number=4,
message=field_mask_pb2.FieldMask,
)
create: gagr_label.Label = proto.Field(
proto.MESSAGE,
number=1,
oneof="operation",
message=gagr_label.Label,
)
update: gagr_label.Label = proto.Field(
proto.MESSAGE,
numbe... | Python | 1 |
import requests
import json
dev_model = "qwen2.5-coder:7b-base-q3_K_M"
def print_msg(msg:dict, header:str, text: str = None):
print("-" * 50)
print(header)
print("-" * 50)
if text is not None:
print(text)
if msg is not None:
print(json.dumps(msg, indent=2))
print("=" * 50)
def... | Python | 1 |
import collections
def solve():
filename = "inputs/day01.input"
with open(filename) as f:
content = f.readlines()
left_list = []
right_list = []
for line in content:
left,right = line.split(' ', 1)
left_list.append(int(left.strip()))
right_list.append(int(right.s... | Python | 1 |
}
}
#[export_name = "hal_zero_frame_paddr"]
pub fn zero_frame_addr() -> PhysAddr {
#[repr(align(0x1000))]
struct Page([u8; PAGE_SIZE]);
static ZERO_PAGE: Page = Page([0u8; PAGE_SIZE]);
unsafe { ZERO_PAGE.0.as_ptr() as usize - PMEM_BASE }
}
}
pub fn phys_to_virt(paddr: ... | Rust | 0 |
_mnist_with_validation_and_dropout(0.3).unwrap();
println!("\nBatched Gradient Descent with Dropout\n");
batched_gradient_descent_with_dropout(0.5).unwrap();
}
fn three_layer_mnist() -> Result<(), Box<dyn Error>> {
let dataset_size = 100; // 1000 in notebook with numpy
let test_dataset_size = 10000;
... | Rust | 0 |
(invalid_data)
def test_gh_21286():
generators = np.array([[0, 0], [0, 1.1], [1, 0], [1, 1]])
tri = qhull.Delaunay(generators)
# verify absence of segfault reported in ticket:
with pytest.raises(IndexError):
tri.find_simplex(1)
with pytest.raises(IndexError):
# strikingly, Delaunay... | Python | 1 |
).short("V").multiple(true))
.arg(
Arg::with_name(EXECUTE)
.short("x")
.long(EXECUTE)
.takes_value(true)
.multiple(true),
)
.arg(Arg::with_name(QUIET).short("q").long(QUIET))
.... | Rust | 0 |
#[doc = "0: Pin is configured as general-purpose input, for the GPIO function. The pin will be high-Z if the port input is disabled in FPIOx_PIDR register."]
_0 = 0,
#[doc = "1: Pin is configured as general-purpose output, for the GPIO function."]
_1 = 1,
}
impl From<PDD_A> for u32 {
#[inline(always)]
... | 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 |
res["error"] != json!(null) {
let report = format!(
"Failed to sign_price from {}: Error: {}, Message: {}",
wallet_listener_url, res["error"]["code"], res["error"]["message"]
);
error!("{}", report);
return Err(Error::WalletComm(report));
}
let cb_data = res["result"]["Ok"].clone();
trace!("cb_data: ... | Rust | 0 |
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
import jax.numpy as jnp
def plot_distributions(initial_particles, transported_particles, density_params):
fig = plt.figure(figsize=(10, 6))
# Plot histogram of initial particles
plt.hist(initial_particles, bins=30, density=Tru... | Python | 1 |
print(f"{original_key}-> {key} : \nshape {val.shape} and { value.shape}, do not match")
key = original_key
mapping[key] = original_key
new_dict[key] = value
return new_dict
@torch.no_grad()
def convert_openai_checkpoint(model_name=None, pytorch_dump_folder_path=None):
"""
... | Python | 1 |
ctx.http, text).await?;
Ok(())
}
async fn build_status_message_short() -> String {
let raffles = api_helper::get_raffle("0".to_owned()).await.unwrap();
let tickets = api_helper::get_ticket("0".to_owned()).await.unwrap();
let mut text = String::new();
text.push_str(format!("**:tickets: Raffle Sta... | Rust | 0 |
stall_path, symlinks=True)
zippattern = None
if os.path.exists(signed_install_path):
apps = [d for d in os.listdir(signed_install_path) if d.endswith('.app')]
if apps:
zippattern = apps[0]
if not zippattern:
os.maked... | Python | 1 |
s_from_dividers(&[0.75]), &[0.75, 0.25], f32::EPSILON);
}
#[test]
fn test_weights_from_dividers_multiple() {
assert_slice_approx_eq!(
&weights_from_dividers(&[2.0 / 3.0, 0.75]),
&[0.5, 0.25, 0.25],
f32::EPSILON
);
assert_slice_approx_eq!(
... | Rust | 0 |
collections::HashMap;
use std::thread;
use std::time;
type VehiclePositionMap = HashMap<String, (String, String)>;
pub fn run(db: &Connection) {
let two_sec = time::Duration::from_millis(2000);
let mut positions = HashMap::new();
loop {
positions = do_run(&db, positions);
thread::sleep(tw... | Rust | 0 |
import re
from inference import GrpcClient
model_id = "flan-t5-small"
grpc_port = 433
infer_endpoint = "https://localhost/"
hostname = re.sub("https://|http://", "", infer_endpoint)
if hostname[-1] == "/":
hostname = hostname[:-1]
print(f"Querying host {hostname} with grpc port {grpc_port}")
client = GrpcClient... | Python | 1 |
(C)]
#[derive(Debug, Copy, Clone)]
pub struct cudaResourceDesc__bindgen_ty_1__bindgen_ty_3 {
#[doc = "< Device pointer"]
pub devPtr: *mut ::libc::c_void,
#[doc = "< Channel descriptor"]
pub desc: cudaChannelFormatDesc,
#[doc = "< Size in bytes"]
pub sizeInBytes: usize,
}
#[test]
fn bindgen_test_... | Rust | 0 |
#!/usr/bin/env python3
# Copyright 2021 Evan Flynn, Lucas Walter
#
# 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 retain the above copyright
# notice, this list of condi... | Python | 1 |
grpc: Code::NotFound,
reason: Reason::NotFound,
}
}
pub fn gateway_loop() -> Self {
Self {
message: "gateway loop detected",
http: http::StatusCode::LOOP_DETECTED,
grpc: Code::Aborted,
reason: Reason::GatewayLoop,
}
... | Rust | 0 |
#!/usr/bin/env python
'Test for psfmakewoffmetadata'
__url__ = 'https://github.com/silnrsi/pysilfont'
__copyright__ = 'Copyright (c) 2018 SIL Global (https://www.sil.org)'
__license__ = 'Released under the MIT License (https://opensource.org/licenses/MIT)'
__author__ = 'David Raymond'
import silfont.util
# Next 5 lin... | Python | 1 |
return port;
}
}
impl Iterator for PingPortPicker {
type Item = u16;
fn next(&mut self) -> Option<Self::Item> {
return self.fetch_next_available_port();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ping_port_picker_should_work_with_port_range_1() {
assert... | Rust | 0 |
n_max_bits: bits::BitLength,
e_min_value: u64,
) -> Result<Self, error::KeyRejected> {
// This is an incomplete implementation of NIST SP800-56Br1 Section
// 6.4.2.2, "Partial Public-Key Validation for RSA." That spec defers
// to NIST SP800-89 Section 5.3.3, "(Explicit) Partial Publ... | Rust | 0 |
: We may copy more files than necessary, if new files are added while we are
// performing the dump. We need a way to filter them out.
let temp_dump_file = tempfile::NamedTempFile::new_in(&dump_path)?;
to_tar_gz(temp_dump_path, temp_dump_file.path())
... | Rust | 0 |
"""
跟随指令管理器 - 智能识别和处理跟随请求
"""
import time
import re
from typing import Dict, List, Any, Optional, Tuple
from dataclasses import dataclass
import logging
logger = logging.getLogger(__name__)
@dataclass
class FollowCommand:
"""跟随指令数据"""
requester: str
command_text: str
timestamp: float
status: str ... | Python | 1 |
();
let limit = args[0].coerce_to_fixnum("Limit")?;
let step = if args.len() == 2 {
let step = args[1].coerce_to_fixnum("Step")?;
if step == 0 {
return Err(RubyError::argument("Step can not be 0."));
}
step
} else {
1
};
let iter = Step {
... | Rust | 0 |
),
Destroy(usize),
None,
}
// TODO: remove me in favor of adding classes representing state
pub fn destroy_other_windows(windows: &mut HashMap<usize, Window>, selected_id: &usize) {
let keys: Vec<usize> = windows.keys().cloned().collect();
keys.iter()
.filter(|&key| selected_id != key)
... | Rust | 0 |
in &elected_stashes {
let pref = Self::validators(stash);
<ErasValidatorPrefs<T>>::insert(&new_planned_era, stash, pref);
}
if new_planned_era > 0 {
log!(
info,
"new validator set of size {:?} has been processed for era {:?}",
elected_stashes.len(),
new_planned_era,
);
}
elected_s... | Rust | 0 |
ed=True,
help="Path to the JSON file containing the preprocessed dataset",
)
parser.add_argument(
"--dataset-name",
type=str,
required=True,
help="Name for the dataset (used for repository name if not specified)",
)
parser.add_argument(
"--repository-id",
... | Python | 1 |
import sys
import cProfile
import pickle as pkl
sys.path.insert(0, './')
sys.path.insert(0, './unity/')
sys.path.insert(0, './stable-baselines/')
from packing.packing_evalute import evaluate
from packing.packing_heuristic import *
list_pack_file_name = [["pack_ab/{}_tr_{}_ab".format(i, j) for i in range(0, 17)] for j... | Python | 1 |
ition (pixels)')
axes[1, 0].set_title('Y Position vs Time')
axes[1, 0].legend()
axes[1, 0].grid(True, alpha=0.3)
# Velocity plot
axes[1, 1].plot(df['t'], df['vy'], 'b.', alpha=0.6, label='Noisy Vy')
axes[1, 1].plot(df['t'], ideal_data['vy_ideal'], 'r-', linewidth=2, label='Ideal Vy')
ax... | Python | 1 |
import os
import sys
import vtk
import zarr
from vtk.util import numpy_support as np_s
class vtkContourGeneratorFromZarr(object):
def __init__(self, basepath):
self.zarrPath = os.path.normpath(basepath)
if not os.path.exists(self.zarrPath):
print(f"Path ({self.zarrPath}) is not valid"... | Python | 1 |
ataCell<'d>)>,
}
#[cfg(feature = "with-loader-impl")]
impl<'d> PvpShaderModules<'d>
{
pub fn new(device: &br::Device, container: PvpContainer) -> br::Result<Self>
{
let fragment = container.fragment_shader.map(|b| br::ShaderModule::from_memory(device, &b)).transpose()?;
Ok(PvpShaderMod... | Rust | 0 |
# Copyright 2015 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 |
# -*- encoding:utf-8 -*-
"""Autogenerated file, do not edit. Submit translations on Transifex."""
MESSAGES = {
"%d min remaining to read": "quedan %d minutos de lectura",
"(active)": "(activo)",
"Also available in:": "También disponible en:",
"Archive": "Archivo",
"Atom feed": "Canal Atom",
"Au... | Python | 1 |
.iter().map(|a| a.z3_ast).collect();
match unsafe {
Z3_optimize_check(
self.ctx.z3_ctx,
self.z3_opt,
assumptions.len().try_into().unwrap(),
assumptions.as_ptr(),
)
} {
Z3_L_FALSE => SatResult::Unsat,
... | Rust | 0 |
("The file created by this checkexec execution.")
.required(true)
)
.arg(Arg::new("verbose")
.long("verbose")
.short('v')
.takes_value(false)
)
.arg(Arg::new("infer")
.long("infer")
.takes_value(false)
.c... | Rust | 0 |
eContentType {
part: "/docProps/app.xml".into(),
ty: CONTENT_TYPE_EXTENDED.into(),
},
OverrideContentType {
part: "/docProps/core.xml".into(),
ty: CONTENT_TYPE_CORE.into(),
},
... | Rust | 0 |
atch self.0 {
c => {
write!(f, "{}", c).map_err(|_| fmt::Error)?;
}
}
Ok(())
}
}
#[derive(Clone, Copy)]
pub enum Modifier {
None,
Ctrl,
Alt,
Shift,
CtrlAlt,
CtrlShift,
... | Rust | 0 |
"""Utils for networks."""
import torch
def int_preprocess_onehot(int_lvls: torch.Tensor, nc: int) -> torch.Tensor:
"""
Preprocess int levels for networks.
Args:
int_lvls: Input int levels (batch_size, lvl_height, lvl_width)
nc: Number of objects
Returns:
One-hot encoded and pa... | Python | 1 |
distributions::range::Range;
pub use rand::distributions::Sample;
pub use expectest::prelude::be_equal_to;
describe! array {
before_each {
let mut between = Range::new(0, 1000);
let mut rng = rand::thread_rng();
let mut data = Vec::with_capacity(10);
let mut ret = Vec::with_capac... | Rust | 0 |
convert(&self, s: &str) -> String {
use Case::*;
match self {
CamelCase => heck::CamelCase::to_camel_case(s),
SnakeCase => heck::SnakeCase::to_snake_case(s),
KebabCase => heck::KebabCase::to_kebab_case(s),
ShoutySnakeCase => heck::ShoutySnakeCase::to_sho... | Rust | 0 |
wtr.write_record(&headers)?;
}
let mut record = csv::ByteRecord::new();
let mut counter: u64 = 0;
while rdr.read_byte_record(&mut record)? {
if let Some(constant_value) = &args.flag_constant {
record.push_field(constant_value.as_bytes());
} else if copy_operation {
... | Rust | 0 |
<usize> = parser.parallel_each(nthreads, |record_sets| {
//! // we can initialize thread local variables here.
//! let adapter = b"AATGATACGGCGACCACCGAGATCTACACTCTTTCCCTACACGACGCTCTTCCGATCT";
//! let matrix = align::Matrix::new(align::MatrixType::Identity);
//! let profil... | Rust | 0 |
let EnumKind {
// base: _,
ty,
// constraint: _,
interface,
} = match self.enum_kind(inner_ty, ancestors) {
None => return,
Some(kind) => kind,
};
// Don't rewrite enum classes.
if interface.is_some() {
... | Rust | 0 |
from django.urls import path
from . import views
app_name = 'students'
urlpatterns = [
path('list/', views.student_list, name='student_list'),
path('add/', views.add_student, name='add_student'),
path('detail/<int:pk>/', views.student_detail, name='student_detail'),
path('delete/<int:pk>/', views.s... | Python | 1 |
self
.w()
.iter()
.zip(x)
.map(|(w, x)| w * x)
.reduce(|a, b| a + b)
.unwrap()
+ self.b();
if self.relu {
ModelOutput::Scalar(act.relu())
} else {
ModelOutput::Scalar(act)
}
}
f... | Rust | 0 |
Stage) -> Self::Type {
(<A as Resource>::resource(stage),
<B as Resource>::resource(stage),
<C as Resource>::resource(stage),
<D as Resource>::resource(stage),
<E as Resource>::resource(stage))
}
}
use super::{Expression, Visitor};
use crate::Tuple;
use std::marker::Phan... | Rust | 0 |
# Requirements:
# A kinect for xbox 360
# Install kinect_ros2 package (use this fork: https://github.com/matlabbe/kinect_ros2)
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument, SetEnvironmentVariable
from launch.substitutions import LaunchConfiguration
from launch_ros.actions i... | Python | 1 |
power_networks(
structures: &StructureDynIter,
power_wires: &[PowerWire],
) -> Vec<PowerNetwork> {
let mut left_wires = power_wires.iter().collect::<HashSet<_>>();
let mut ret = vec![];
for (id, s) in structures.dyn_iter_id() {
if !s.power_sink() && !s.power_source() {
continue;... | Rust | 0 |
e use self::run::Run;
crate trait Subcommand {
fn subcommand<'a, 'b>() -> App<'a, 'b>;
fn execute(&self, config: &Config, matches: &ArgMatches<'_>) -> MusshResult<()>;
}
<reponame>macdonaldo/monkey
pub struct Defers {
stack: Vec<Box<dyn Fn()>>,
}
impl Defers {
pub fn defer(&mut self, f: Box<dyn Fn(... | Rust | 0 |
from dataclasses import dataclass
from typing import List, Tuple
@dataclass
class Box:
id: str
text: str
size: Tuple[int, int]
color: Tuple[int, int, int]
description: str
@dataclass
class Arrow:
start: str
end: str
color: Tuple[int, int, int]
description: str
@dataclass
class Di... | Python | 1 |
// Optimizing with max_inputs=2 should select 100, 2000
{
let mut utxos = generate_utxos(6);
utxos[0].value = 100 * MILLIMOB_TO_PICOMOB;
utxos[1].value = 200 * MILLIMOB_TO_PICOMOB;
utxos[2].value = 150 * MILLIMOB_TO_PICOMOB;
utxos[3].value = 3... | Rust | 0 |
as_udp_socket().recv() {
println!("{}", String::from_utf8_lossy(buf));
}
env::tick(&mut interface, &mut socket_set);
}
}
<gh_stars>1-10
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org... | Rust | 0 |
val: vec![1],
}
}
/// Check if the number is positive
///
/// # Examples
///
/// ```
/// use hyeong::big_number::BigNum;
///
/// let a = BigNum::new(1234);
/// let b = BigNum::new(-4321);
///
/// assert_eq!(true, a.is_pos());
/// assert_eq!(false, b.is_... | Rust | 0 |
# Copyright Amazon.com, Inc. or its affiliates. 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 ... | Python | 1 |
println!("Main Menu");
println!("---------");
println!("1.\tValidate an IPv4 address");
println!("2.\tIPv4 to IPv6");
println!("3.\tIPv4 to Binary");
println!("4.\tValidate an IPv6 address");
println!("5.\tIPv6 to IPv4");
println!("6.\tIPv6 to Binary");
pr... | Rust | 0 |
import numpy as np
import imageio
import tensorflow as tf
import os
import termcolor
def imread(fname):
return imageio.imread(fname)/255.0
def imsave(fname,array):
imageio.imsave(fname,(array*255).astype(np.uint8))
# convert to colored strings
def toRed(content): return termcolor.colored(content,"red",attrs=["bold"... | Python | 1 |
_price;
pub mod health;
pub mod light_client_proof;
pub mod network_info;
pub mod next_light_client_block;
pub mod query;
pub mod status;
pub mod tx;
pub mod validators;
// ======== experimental ========
mod experimental;
pub use experimental::EXPERIMENTAL_changes;
pub use experimental::EXPERIMENTAL_changes_in_block;
... | Rust | 0 |
&dyn SymDB) -> fmt::Result {
use ValueKind::*;
match &val.kind {
Bool(true) => write!(f, "t"),
Bool(false) => write!(f, "f"),
Int(n) => write!(f, "{}", n),
Real(a) => write!(f, "{}", a),
String(x) => write!(f, "{:?}", x),
Symbol(id) => write!(f, "{}", db.name(*id... | Rust | 0 |
ntinue
if name and name not in seen:
arr.append(name)
seen.add(name)
out[key] = arr
return out
async def save_map(self, payload: Dict[str, List[str]]) -> None:
normalized: Dict[str, List[str]] = {}
for k, v ... | Python | 1 |
3 views at strings from Rust: (grapheme clusters, the closest thing
to what we would call letters):
“नमस्ते” in Vec<u8> -> [224, 164, 168, 224, 164, 174, 224, 164, 184, 224,
165, 141, 224, 164, 164, 224, 165, 135]
18-byte in memory;
Unicode-scalar: -> `char` in Rust: ['न', ... | Rust | 0 |
)),
/*2..3*/
None,
/*3..3*/
Some((Bidder::New(NewBidder{who: 5, sub: 0}), 1)),
];
let winners = vec![
(Some(NewBidder{who: 2,sub: 0}), 0.into(), 2, SlotRange::ZeroZero),
(Some(NewBidder{who: 3,sub: 0}), 1.into(), 1, SlotRange::OneOne),
(Some(NewBidder{who: 1,sub: 0}), 2.into(), 53, SlotRange::T... | Rust | 0 |
ius_at(z).T*scale*m
y = np.array([
[wx, wx, z], [wy, wy, z],
[-wx, -wx, z], [-wy, -wy, z],
]).transpose(2, 0, 1)
y = self.from_axis(y)
for i, ci in zip((axis, 0 if axis else 1), ("-", "--")):
ax.plot(y[:, i::2, 2], y[:, i::2, axis], ci, **kwargs)
... | Python | 1 |
har('#');
easy.move_xy(draw_x + 2, draw_y);
easy.print(s);
easy.move_xy(draw_x * 2 - 1, draw_y);
easy.print_char('#');
draw_y -= 1;
easy.move_xy(draw_x, draw_y);
easy.print_char('#');
easy.move_xy(draw_x * 2 - 5, draw_y);
... | Rust | 0 |
= Schema::new(vec![Field::new("a", $A_TYPE, false)]);
let a = $A_ARRAY::from($A_VEC);
let batch =
RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
// verify that we can construct the expression
let expression =
cast_wit... | Rust | 0 |
�"),
keywords: &["ካርታ", "የጃፓን ካርታ", "ጃፓን"],
},
#[cfg(feature = "ar")]
crate::Annotation {
lang: "ar",
tts: Some("خريطة اليابان"),
keywords: &["اليابان", "خريطة"],
},
#[cfg(feature = "as")]
crate::Annotation {
lan... | Rust | 0 |
def reverse_pair(arr):
count = 0
n = len(arr)
for i in range(n):
cnt = 0
for j in range(i+1,n):
if arr[i] > (2 * arr[j]):
cnt+=1
count+=cnt
return count
arr = [40, 25, 19,12,9, 6, 2]
print(reverse_pair(arr))
# TC - O(n**2)
# SC - O(1)
# optimal... | Python | 1 |
connection = &*guard;
inner_connection.is_connected()
}
pub fn incoming_messages(&self) -> Iter<IdscpEvent> {
self.incoming_message_rx.iter()
}
pub fn recv_incoming_msg_with_timeout(
&self,
timeout: Duration,
) -> Result<IdscpEvent, RecvTimeoutError> {
self.... | Rust | 0 |
return Err(anyhow!("{}", error)).with_context(|| fl!("error-fetch-failed"));
}
}
}
Ok(())
}
/// Removes the installed font from the system.
pub fn remove<W>(&self, writer: &mut W, family: &str) -> anyhow::Result<()>
where
W: Write,
{
/... | Rust | 0 |
| j vrtdtdd S )Nznot a legal actionzHaven't written this yet...)_legal_actions
ValueErrorNotImplementedError)r& |