text stringlengths 8 4.13M |
|---|
/// Declares task-local values.
///
/// The macro wraps any number of static declarations and makes them task-local. Attributes and
/// visibility modifiers are allowed.
///
/// Each declared value is of the accessor type [`LocalKey`].
///
/// [`LocalKey`]: task/struct.LocalKey.html
///
/// # Examples
///
/// ```
/// #... |
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from ../gir-files
// DO NOT EDIT
use std::ffi::CStr;
#[doc(alias = "SOUP_ADDRESS_FAMILY")]
pub static ADDRESS_FAMILY: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_ADDRESS_FAMILY).to_str().unwrap... |
use sigmoid::Sigmoid;
use error::*;
use csv::{Reader, Writer};
use rand::thread_rng;
use rand::distributions::{IndependentSample, Range};
// 过早扩展是万恶之源
pub struct Data {
header: Option<Vec<String>>,
records: Vec<Iris>,
}
impl Data {
// 从文件读取
pub fn serialize(string: &str, has_header: bool) -> Result<Da... |
use std::path::{Path, PathBuf};
use std::collections::HashMap;
use std::fs::DirEntry;
use vec1::Vec1;
use mail::context::Source;
use mail::{Resource, IRI};
use ::error::{CreatingSpecError, CreatingSpecErrorVariant};
use ::utils::{new_string_path, new_str_path};
use ::{TemplateSpec, SubTemplateSpec};
use ::settings::... |
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// 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 ... |
//! Context extensions for tracing
use crate::{
global,
trace::{Span, SpanContext},
Context, ContextGuard, KeyValue,
};
use pin_project::pin_project;
use std::error::Error;
use std::sync::Mutex;
use std::{
borrow::Cow,
pin::Pin,
task::{Context as TaskContext, Poll},
};
lazy_static::lazy_static!... |
use std::io;
use std::io::Read;
fn main() {
let mut input = String::new();
io::stdin().read_to_string(&mut input).unwrap();
let mut joltages: Vec<u8> = input.lines().map(|x| x.parse().unwrap()).collect();
joltages.push(0); // Outlet
joltages.sort_unstable();
joltages.push(joltages[joltages.len... |
//! Sending and receiving slices of bytes.
//!
//! ## Example usage from a std crate
//!
//! See the `decode_*` and `encode_*` functions for simple uses with
//! various input and output types.
//!
//! The `Sender` struct writes encoded payloads to an
//! inner `std::io::Write` instance, and the `Receiver` struct reads... |
use super::Part;
use crate::codec::{Decode, Encode};
use crate::{remote_type, RemoteObject};
remote_type!(
/// A launch clamp. Obtained by calling `Part::launch_clamp().`
object SpaceCenter.LaunchClamp {
properties: {
{
Part {
/// Returns the part object for this launch clamp.
... |
use super::group_indices;
use petgraph::graph::{Graph, IndexType, NodeIndex};
use petgraph::EdgeType;
use petgraph_layout_force_simulation::{Force, Point, MIN_DISTANCE};
use std::collections::HashMap;
#[derive(Copy, Clone)]
pub struct GroupManyBodyForceArgument {
pub group: usize,
pub strength: Option<f32>,
}
... |
use core::{cell::RefCell, usize};
use cortex_m::interrupt::{CriticalSection, Mutex};
#[derive(Debug, Clone, Copy, defmt::Format)]
pub enum InterruptEvent {
Tick,
Encoder(i8),
ShortPress,
LongPress,
Alarm,
}
/// Inner implementation for EventQueue protected by a Mutex for inner mutability
#[derive(... |
use super::helpers::subtract_reuse_lhs;
use crate::{integer::Integer, rational::Rational};
use core::ops::Sub;
// Sub The subtraction operator -.
// ['Rational', 'Rational', 'Rational', 'Rational::subtract_assign', 'lhs',
// ['ref_mut'], ['ref']]
impl Sub<Rational> for Rational {
type Output = Rational;
... |
use crate::event::*;
use crate::types::*;
use chrono::Local;
use std::collections::hash_map::HashMap;
use std::collections::BTreeMap;
// Really, a resting order on the book.
#[allow(dead_code)]
#[derive(Clone, PartialEq)]
pub struct Order {
pub side: Side,
pub price: Price,
pub qty: Qty,
pub order_id: ... |
use crate::{
abi_stability::{GetStaticEquivalent, GetStaticEquivalent_, PrefixStableAbi, StableAbi},
pointer_trait::{GetPointerKind, PK_Reference},
prefix_type::{FieldAccessibility, PTStructLayout, PrefixRefTrait, WithMetadata_},
reexports::True,
reflection::ModReflMode,
sabi_types::StaticRef,
... |
extern crate olin;
use log::info;
use olin::random;
pub extern "C" fn test() -> Result<(), i32> {
info!("running ns::random tests");
info!("i31: {}, i63: {}", random::i31(), random::i63());
info!("ns::random tests passed");
Ok(())
}
|
use crate::{Error, mock::*};
use frame_support::{assert_ok, assert_noop};
#[test]
fn it_works_for_default_value() {
new_test_ext().execute_with(|| {
// Dispatch a signed extrinsic.
assert_ok!(TemplateModule::do_something(Origin::signed(1), 42));
// Read pallet storage and assert an expected result.
assert_eq!... |
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distri... |
use std::{collections::VecDeque, sync::Arc};
use sourcerenderer_core::graphics::{BindingFrequency, Buffer, BufferInfo, BufferUsage, CommandBuffer, LoadOp, MemoryUsage, PipelineBinding, Queue, Scissor, ShaderType, Viewport, IndexFormat, WHOLE_BUFFER, Texture, RenderpassRecordingMode, TextureView, Format};
use wasm_bind... |
use bellman::groth16::*;
use pairing::*;
use pairing::bls12_381::{Fr, FrRepr, Bls12};
use bellman::*;
use rand::thread_rng;
use jubjub::*;
use base::*;
use convert::*;
use std::fs::File;
struct P2Ccircuit<'a> {
generators: &'a [(Vec<Fr>, Vec<Fr>)],
j: &'a JubJub,
//r_h
rh: Assignment<Fr>,
//r_c... |
// generated by `sqlx migrate build-script`
fn main() {
// trigger recompilation when a new migration is added
println!("cargo:rerun-if-changed=migrations");
}
|
use crate::flat;
use crate::raw;
use crate::typeshape;
use crate::typeshape::{desugar, typeshape, FieldShape, TypeShape, WireFormat};
// use crate::raw::Spanned;
// use serde::ser::SerializeMap;
use serde::{Serialize, Serializer};
use std::collections::HashMap;
// impl Serialize for flat::Libraries {
// fn seriali... |
#[derive(Copy, Clone, Debug, PartialEq, Hash, Eq)]
pub enum Player {
White,
Black,
}
impl Player {
pub fn other(&self) -> Player {
match *self {
Player::White => Player::Black,
Player::Black => Player::White,
}
}
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Coordinate {
pub x: u... |
mod types;
use super::type_test::TypeTest;
use crate::{connector::Queryable, single::Quaint};
use names::Generator;
use once_cell::sync::Lazy;
use std::env;
static CONN_STR: Lazy<String> = Lazy::new(|| env::var("TEST_MYSQL").expect("TEST_MYSQL env var"));
pub struct MySql<'a> {
names: Generator<'a>,
conn: Qu... |
extern crate carillon;
use std::path::Path;
use std::process::exit;
use clap::{App, Arg, SubCommand};
use log;
use log4rs;
use carillon::tools;
/// # Carillon CLI
///
/// Carillon ノードの初期化、起動、停止、状態参照を行うための CLI です。
///
fn main() {
let matches = App::new("Carillon CIL")
.version("1.0")
.author("TAKAMI Torao ... |
use super::*;
#[derive(Debug, PartialEq)]
pub struct BinaryOp {
pub op: BinaryOpKind,
pub lhs: Box<Node>,
pub rhs: Box<Node>,
}
#[derive(Debug, PartialEq)]
pub enum BinaryOpKind {
/// <=>
Compare,
/// ==
Equal,
/// ===
CaseEqual,
/// !=
NotEqual,
/// =~
RegexMatch,
... |
extern crate collections;
use std::char::is_alphanumeric;
use std::io::{IoResult, IoError, Buffer};
use std::string::String;
pub enum Node {
Atom(String),
ParseError(String)
}
pub fn parse(source: &mut Buffer) -> IoResult<Node> {
match source.read_char() {
Ok(c) => {
i... |
use config::Config;
use errors::*;
use clap::{App, Arg, ArgMatches, SubCommand};
pub fn setup<'a, 'b>() -> App<'a, 'b> {
SubCommand::with_name("rm")
.about("Removes a user")
.arg(
Arg::with_name("USER")
.help("Specifies the user")
.required(true)
... |
use super::VarResult;
use crate::ast::syntax_type::{FunctionType, FunctionTypes, SimpleSyntaxType, SyntaxType};
use crate::helper::{pine_ref_to_f64, pine_ref_to_i64};
use crate::runtime::context::{downcast_ctx, Ctx};
use crate::types::{Callable, Float, Int, PineFrom, PineRef, RuntimeErr, Series, SeriesCall, NA};
use st... |
#[doc = r"Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r"Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::BOOTCFG {
#[doc = r"Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, ... |
#[macro_use]
extern crate criterion;
extern crate threads_pool;
use criterion::{black_box, Criterion};
use std::sync::atomic;
use threads_pool::prelude::*;
fn pool_base(size: usize, bound: usize) {
let mut pool = ThreadPool::new(size);
for num in 1..bound {
pool.exec(
move || {
... |
//! Independent traits
//!
//! This implements `Rng` for any `CryptoRng` implicitly.
//!
//! Note: this *only* considers the next_u32 member function
//!
//! Thoughts: this is basically equivalent to extends_Rng2.
// ——— traits ———
#[derive(Debug)]
struct CryptoError;
trait CryptoRng {
fn try_next_u32(&mut se... |
fn naive(s: &mut Vec<char>) {
s.sort();
if s.iter().collect::<String>().parse::<i32>().unwrap() % 8 == 0 {
println!("Yes");
return;
}
while s.next_permutation() {
if s.iter().collect::<String>().parse::<i32>().unwrap() % 8 == 0 {
println!("Yes");
return;
... |
//! Checks that fields on interface fragment spreads resolve okay.
//! See [#922](https://github.com/graphql-rust/juniper/issues/922) for details.
use juniper::{
graphql_interface, graphql_object, graphql_value, graphql_vars, EmptyMutation,
EmptySubscription, GraphQLObject,
};
struct Query;
#[graphql_object]... |
// https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero/submissions/
impl Solution {
pub fn sum_zero(n: i32) -> Vec<i32> {
let mut unique_array = Vec::with_capacity(n as usize);
for i in 1..n {
unique_array.push(i);
}
unique_array.push(-(n * (n - ... |
/* origin: FreeBSD /usr/src/lib/msun/src/s_sin.c */
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely ... |
use dirs::data_dir;
use std::path::PathBuf;
pub fn get_assets_path() -> PathBuf {
PathBuf::from(std::env::var("ASSET_PATH").unwrap_or("assets/".to_string()))
}
pub fn get_save_path() -> PathBuf {
if let Some(mut save_dir) = data_dir() {
save_dir.push("everfight");
if let Err(err) = std::fs::cr... |
use std::error;
use std::error::Error;
use std::io;
use std::fmt;
use std::num;
#[derive(Debug)]
pub enum WalletError {
WalletUnknownType(String),
WalletTypeAlreadyRegistered(String),
WalletNotFound(String),
WalletInvalidDataFormat(String),
WalletIncorrectPool(String),
WalletInvalidConfig(Strin... |
// Builds prefix-suffix array.
// query_vec: a string of query
// pfxsfx: the output
pub fn build_pfxsfx(query_vec: &Vec<u16>, pfxsfx: &mut Vec<usize>) {
// pfxsfx:The length of longest prefix-suffix match
assert!(
pfxsfx.len() == query_vec.len(),
"pfxsfx.len() == query_vec.len()"
);
pfx... |
fn main() {
let mut old = 1;
let mut curr = 1;
let mut sum = 0;
while curr < 4000000 {
let tmp = old + curr;
old = curr;
curr = tmp;
sum += if curr % 2 == 0 { curr } else { 0 }
}
print!("{}", sum)
}
|
use errors::crypto::CryptoError;
extern crate openssl;
use self::openssl::bn::{BigNum, BigNumRef, BigNumContext, MSB_MAYBE_ZERO};
use self::openssl::error::ErrorStack;
use self::openssl::hash::{hash, MessageDigest};
use std::error::Error;
pub struct BigNumberContext {
openssl_bn_context: BigNumContext
}
#[deri... |
use crate::{
activity::events as activity_events,
lobby::{events as lobby_events, Lobby, LobbyId},
overlay::events as overlay_events,
relations::events as relation_events,
types::ErrorPayload,
user::events as user_events,
};
use serde::{Deserialize, Serialize};
/// Events sent from Discord when... |
use crate::{DocBase, VarType};
const DESCRIPTION: &'static str = r#"
The sin function returns the trigonometric sine of an angle.
"#;
pub fn gen_doc() -> Vec<DocBase> {
let fn_doc = DocBase {
var_type: VarType::Function,
name: "sin",
signatures: vec![],
description: DESCRIPTION,
... |
use image;
use memory;
/// Image creation error.
#[derive(Clone, Copy, Debug, Fail)]
pub enum ImageCreationError {
/// An unsupported format was attempted to be used.
#[fail(display = "Unsupported format")]
UnsupportedFormat(image::Format),
/// Multi-sampled array textures or cubes are not supported.
... |
#[macro_use]
extern crate nickel;
extern crate regex;
extern crate json;
mod api;
use nickel::{Nickel, StaticFilesHandler, HttpRouter};
fn main() {
let mut server = Nickel::new();
server.get("/get_raw_data", middleware!(api::get_raw_data()));
server.utilize(StaticFilesHandler::new("static/"));
serv... |
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// 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 ... |
use crate::cell::Cell;
use crate::grid::Grid;
use crate::row::Row;
use crate::automaton::Automaton;
use crate::renderer::Renderer;
pub struct Lant {
n_cols: usize,
n_rows: usize,
grid: Grid,
current_direction: i32,
current_position_x: usize,
current_position_y: usize,
}
impl Lant {
pub fn... |
use math::primes;
pub fn demo(n: u64) {
println!("{:?}", primes::primes(n));
}
|
use vector::Vector;
use std::process::exit;
use vector::unit;
const GRAV_CONST: f64 = 0.00000000006674;
pub struct Point {
mass: f64,
pub cur_pos: Vector,
pub prev_pos: Vector,
pub accel: Vector,
grav_accel: Vector,
}
impl Point {
pub fn new(mass: f64, cur_pos: Vector, prev_pos: Vector, init_... |
use crate::archival::libarchive::bb_archive::archive_handle_t;
pub unsafe fn data_skip(mut archive_handle: *mut archive_handle_t) {
(*archive_handle).seek.expect("non-null function pointer")(
(*archive_handle).src_fd,
(*(*archive_handle).file_header).size,
);
}
|
use scheme::LispResult;
use scheme::error::LispError::*;
use scheme::value::Sexp;
use scheme::value::Sexp::*;
// 标准中只要求对两个操作数进行比较
// 大写字符是有序的
// 小写字符是有序的
// 数码字符是有序的
// 所有的数码字符大于或小于大写字符
// 所有的数码字符大于或小于小写字符
pub fn compare<F>(name: &str, op: F, args: &[Sexp]) -> LispResult<Sexp> where
F: Fn(char, char) -> bool {
... |
use super::UserInput;
use async_trait::async_trait;
use std::io::Result;
pub struct CLIBackend<'a> {
shell_trust: &'a super::ShellTrust,
}
impl<'a> CLIBackend<'a> {
pub fn new(shell_trust: &'a super::ShellTrust) -> Self {
Self { shell_trust }
}
}
#[async_trait]
impl<'a> UserInput for CLIBackend<'... |
/*
The following is an in-progress adaptation of the Beginner's Guide to PID
Controllers algorithm from Brett Beauregard, in a straight-line conversion to Rust.
As of 4-20-19 it is not complete.
references:
https://github.com/japaric/zen/ -- embedded TWIP with PID on stm32 board
https://github.com/johsnick/rust_pi... |
#![doc = include_str!("notes/mod.md")]
#[doc = include_str!("notes/thrun.md")]
pub mod thrun {}
#[doc = include_str!("notes/ndtmcl.md")]
pub mod ndtmcl {}
#[doc = include_str!("notes/kld.md")]
pub mod kld {}
#[doc = include_str!("notes/cddt.md")]
pub mod cddt {}
#[doc = include_str!("notes/rao.md")]
pub mod rao {}
|
fn tsub_ok(x: i32, y: i32) -> bool {
tadd_ok(x, -y)
}
|
extern crate compt;
use compt::*;
fn main() {
// Example that performs dfs in order traversal on the left side,
// and bfs order traversal on the right side of a tree.
// This demonstrates the composability of the different visitor functions.
//
// 0
// 1 2
// 3 4 5 6
... |
extern crate rand;
use std::env;
use std::io::{self, Write};
use std::ops::AddAssign;
use std::fmt;
use rand::Rng;
#[derive(Copy, Clone)]
struct Score {
correct: i32,
incorrect: i32,
}
impl Score {
fn new() -> Score {
Score { correct: 0, incorrect: 0 }
}
}
impl AddAssign for Score {
fn ... |
use bindings::{
Windows::Win32::Graphics::Direct3D11::*, Windows::Win32::Graphics::Direct3D12::*,
Windows::Win32::Graphics::DirectComposition::*, Windows::Win32::Graphics::Dxgi::*,
Windows::Win32::Graphics::Gdi::*, Windows::Win32::Graphics::Hlsl::*,
Windows::Win32::System::SystemServices::*, Windows::Wi... |
use crate::{
math::{Size, Vector2},
widgets::TypedWidget,
Backend,
};
pub struct EventStep<E, R> {
pub size: Size,
event_queue: Vec<E>,
reaction_queue: Vec<R>,
}
impl<E, R> Default for EventStep<E, R> {
fn default() -> Self {
EventStep {
size: Size::default(),
... |
//! A nul-terminated string,which is just a pointer to the string data,
//! it doesn't know the length of the string.
#[cfg(test)]
mod tests;
use crate::std_types::RStr;
use const_panic::{concat_assert, concat_panic};
use std::{
cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd},
fmt::{self, Debug, Display},
... |
use proconio::input;
#[allow(unused_imports)]
use proconio::marker::*;
#[allow(unused_imports)]
use std::cmp::{max, min};
#[allow(unused_imports)]
use std::collections::*;
#[allow(unused_imports)]
use std::f64::consts::*;
#[allow(unused)]
const INF: usize = std::usize::MAX / 4;
#[allow(unused)]
const M: usize = 100000... |
extern crate pretty_env_logger;
#[macro_use] extern crate log;
extern crate config;
extern crate dirs;
use std::env;
//use std::path::PathBuf;
use structopt::StructOpt;
use log::{info, warn, error};
use config::*;
#[derive(StructOpt, Debug)]
struct Params {
/// Verbose mode (-v, -vv, -vvv are possible)
#[stru... |
use crate::*;
/// Open a sqlite3 connection and insert or replace a meeting
/// We use the SQL commands `INSERT OR REPLACE` in order to overwrite any existing values.
pub fn insert_meeting(meeting: Meeting) -> rusqlite::Result<()> {
let conn = Connection::open("meetings.sql3")?;
conn.execute(
"CREATE T... |
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from ../gir-files
// DO NOT EDIT
use crate::CacheType;
use crate::SessionFeature;
use glib::object::IsA;
use glib::translate::*;
use glib::StaticType;
use std::fmt;
glib::wrapper! {
#[doc(alias = "SoupCache")]
pub struct Cache(Object<ffi::So... |
# ! [ doc = "General-purpose I/Os" ]
# [ doc = r" Register block" ]
# [ repr ( C ) ]
pub struct Gpio {
# [ doc = "0x00 - GPIO port mode register" ]
pub moder: Moder,
# [ doc = "0x04 - GPIO port output type register" ]
pub otyper: Otyper,
# [ doc = "0x08 - GPIO port output speed register" ]
pub o... |
use crate::token_type::TokenType;
#[derive(Debug, Eq, PartialEq, Default, Clone)]
pub struct Token {
pub token_type: TokenType,
pub literal: String,
}
impl Token {
pub fn new(token_type: TokenType, literal: String) -> Self {
Self {
token_type,
literal,
}
}
}
im... |
use proconio::input;
fn cross(x: i64, y: i64, xx: i64, yy: i64) -> i64 {
x * yy - y * xx
}
fn ok(x1: i64, y1: i64, x2: i64, y2: i64, x3: i64, y3: i64) -> bool {
cross(x3 - x2, y3 - y2, x1 - x2, y1 - y2) > 0
}
fn main() {
input! {
ax: i64,
ay: i64,
bx: i64,
by: i64,
... |
use rustviz_lib::data::{ExternalEvent, LifetimeTrait, ResourceAccessPoint, Owner, MutRef, StaticRef, Function, VisualizationData, Visualizable};
use rustviz_lib::svg_frontend::svg_generation;
use std::collections::BTreeMap;
fn main() {
let s1 = ResourceAccessPoint::Owner(Owner {
hash: 1,
name: Strin... |
use byteorder::LittleEndian;
use crate::io::Buf;
use crate::mysql::protocol::{AuthPlugin, Capabilities, Status};
// https://dev.mysql.com/doc/dev/mysql-server/8.0.12/page_protocol_connection_phase_packets_protocol_handshake_v10.html
// https://mariadb.com/kb/en/connection/#initial-handshake-packet
#[derive(Debug)]
pu... |
extern crate svmon_parser;
extern crate regex;
use svmon_parser::svmon::Svmon;
use regex::Regex;
use std::fs::File;
use std::io::{self, BufReader};
use std::io::prelude::*;
use std::env;
use std::process;
use std::error::Error;
fn main() {
let stdin = io::stdin();
let args: Vec<String> = env::args().collect()... |
use std::collections::BTreeMap;
use super::crt_objects::CrtObjectsFallback;
use super::{LinkerFlavor, LldFlavor, PanicStrategy, RelocModel, TargetOptions, TlsModel};
pub fn options() -> TargetOptions {
let mut lld_args = Vec::new();
let mut clang_args = Vec::new();
let mut arg = |arg: &'static str| {
... |
type Card = u32;
type Deck = Vec<Card>;
enum Players {
Player1(Deck),
Player2(Deck),
}
pub fn run() {
let mut iter = include_str!("../day22.txt").split("\n\n");
let mut player1 = iter
.next()
.unwrap()
.split("\n")
.skip(1)
.map(|str| str.parse::<Card>().unwra... |
#[allow(dead_code)]
pub static ANSI_RESET : &'static str = "\u{1B}[0m";
#[allow(dead_code)]
pub static ANSI_YELLOW : &'static str = "\u{1B}[33m";
#[allow(dead_code)]
pub static ANSI_GREEN : &'static str = "\u{1B}[32m";
|
#[cfg(test)]
mod test {
use std::cell::RefCell;
use std::rc::{Rc, Weak};
#[derive(Debug)]
struct Node {
value: i32,
parent: RefCell<Weak<Node>>,
children: Vec<Rc<Node>>,
}
#[test]
fn work() {
let leaf = Rc::new(Node {
value: 3,
... |
#[doc = "Reader of register PP"]
pub type R = crate::R<u32, super::PP>;
#[doc = "Flash Size\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u16)]
pub enum SIZE_A {
#[doc = "511: 1024 KB of Flash"]
_1MB = 511,
}
impl From<SIZE_A> for u16 {
#[inline(always)]
fn from(variant: SIZE_A)... |
#[cfg(not(feature = "const_generics"))]
use crate::Array;
use crate::SmallVec;
use core::ptr;
macro_rules! create_with_parts {
(
<$($({$s_impl_ty_prefix:ident})? $s_impl_ty:ident$(: $s_impl_ty_bound:ident)?),*>,
<$s_decl_ty:ident$(, {$s_decl_const_ty:ident})?>,
$array_item:ty
) => {
/// An iterator that c... |
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
//
use gltf::{mesh::Primitive, Buffer};
use spectral::prelude::*;
use crate::{Fingerprint, Result};
/// Computes a `Fingerprint` from a `Primitive`.
///
/// A fingerprint needs to be independent of triangle order and vertex order, and obviously... |
// Menggunakan while untuk meng-iterasi data vector
//
fn main() {
let num = vec![1,2,3,4,5];
let mut iter = (&num).into_iter();
while let Some(v) = iter.next() {
println!("{}", v);
}
} |
mod error;
mod play_flag;
use gstreamer::prelude::*;
use gstreamer::*;
use std::io::Write;
use std::iter::Iterator;
use std::sync::atomic::{AtomicI32, Ordering};
use std::sync::Arc;
const GRAPH_LENGTH: usize = 78;
fn got_location(prop_object: &Object) {
let location: String = prop_object.property("temp-location"... |
use std::fmt;
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub struct PlayerControlled {
pub id: PlayerId,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub struct PlayerId(pub u32);
impl fmt::Display for PlayerControlled {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write... |
use super::super::{Model, Var, LtXY, GtXY, LeXY, GeXY, LtXYC, GtXYC, LeXYC, GeXYC, LtXC, GtXC, LeXC, GeXC};
use super::{LtXYCx, LtXYCy};
#[test]
fn propagator_does_propagate() {
let m = Model::new();
let x = Var::new(m.clone(), -2, 255, "x");
let y = Var::new(m.clone(), -2, 255, "y");
LtXYCx::new(m.clo... |
// 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 failure::{bail, err_msg, Error, ResultExt};
use fidl_fuchsia_ui_text as txt;
use fuchsia_async::TimeoutExt;
use futures::prelude::*;
use std::collectio... |
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! Auto derive CryptoHash implement.
extern crate proc_macro;
use proc_macro::TokenStream;
use quote::quote;
use syn::DeriveInput;
#[proc_macro_derive(CryptoHash)]
pub fn crypto_hash(input: TokenStream) -> TokenStream {
let a... |
fn main() {
let c: f32 = convert_f_to_c(37.0);
println!("The temp in C is {}", c);
let n = 9;
let fibs: i32 = fib(n);
println!("The {}th term is {}", n, fibs);
xmas();
}
fn convert_f_to_c(f: f32) -> f32 {
let c: f32 = (f - 32.0) * (5.0 / 9.0);
c
}
fn fib(n: i32) -> i32 {
let mut ... |
use curses;
use {Error, Event, Key};
use super::Window;
pub struct Input<'a> {
window: &'a mut Window<'a>,
}
impl<'a> Input<'a> {
#[inline]
pub unsafe fn wrap<'b>(window: &'b mut Window<'b>) -> Input<'b> {
Input { window: window }
}
}
impl<'a> Input<'a> {
#[inline]
pub fn event(&mut self) -> Option<Event> {... |
//! Internals for the `@michael-f-bryan/gcode` package. Not intended for public
//! use.
mod callbacks;
mod parser;
mod simple_wrappers;
pub use callbacks::JavaScriptCallbacks;
pub use parser::Parser;
pub use simple_wrappers::{Comment, GCode, Line, Span, Word};
use gcode::Mnemonic;
pub(crate) fn mnemonic_letter(m: ... |
struct Data {
value: i32
}
#[no_mangle]
extern fn new_data(value: i32) -> *mut Data {
let d = Box::new(Data { value });
Box::into_raw(d)
}
#[no_mangle]
extern fn drop_data(ptr: *mut Data) {
unsafe {
drop(Box::from_raw(ptr));
}
}
#[no_mangle]
extern fn take_value(ptr: *mut Data) -> i32 {
... |
use std::net::SocketAddr;
use std::sync::Arc;
use failure::Error;
use tokio;
use tokio::prelude::*;
use trust_dns_resolver::AsyncResolver;
use crate::relay::forwarding::handle_incoming_tcp;
use tokio::net::TcpStream;
use asocks5::socks::Address;
use asocks5::socks::SocksError;
use asocks5::socks::TcpRequestHeader;
use... |
use crate::store::Store;
use crate::structures::Structure;
use retriever::traits::record::Record;
use retriever::types::entry::Entry;
use retriever::types::id::Id;
use retriever::types::storage::Storage;
use serde::{Deserialize, Serialize};
use std::marker::PhantomData;
#[derive(Debug, Deserialize, Serialize, Clone, H... |
use iron::prelude::*;
use iron::status;
use router::*;
use bodyparser;
use persistent::{Read, Write};
use hyper::header::*;
use hyper::mime::*;
use dal;
use std::ops::Deref;
use chrono::prelude::*;
use serde_json;
use std::str;
use uuid;
use bcrypt;
use slog;
use std;
use multipart::server::Multipart;
use multipart::se... |
use std::cmp::PartialOrd;
pub mod bubble_sort;
pub mod quick_sort;
pub mod selection_sort;
pub mod insertion_sort;
pub fn swap<T>(list: &mut [T], l_index: usize, r_index: usize)
where
T: PartialOrd + Copy,
{
let temp = list[r_index];
list[r_index] = list[l_index];
list[l_index] = temp
}
pub f... |
#![deny(warnings)]
use hyper::client::conn::Builder;
use hyper::client::connect::HttpConnector;
use hyper::client::service::Connect;
use hyper::service::Service;
use hyper::{Body, Request};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
pretty_env_logger::init();
let mut mk_svc = ... |
use ndarray::prelude::*;
use petgraph_drawing::{Drawing, DrawingIndex};
pub fn stress<N>(drawing: &Drawing<N, f32>, d: &Array2<f32>) -> f32
where
N: DrawingIndex,
{
let n = drawing.len();
let mut s = 0.;
for j in 1..n {
for i in 0..j {
let dx = drawing.coordinates[[i, 0]] - drawing.... |
use std::str;
pub struct IncomingResult<'a> {
pub data: &'a [u8],
}
impl<'a> IncomingResult<'a> {
pub fn begins_with(&self, name: &str) -> Option<&[u8]> {
let len = name.len();
// Make sure name fits with the data
if len > self.data.len() {
return None;
}
... |
use rocket_contrib::databases::diesel;
#[database("pg")]
pub struct DbConnection(diesel::PgConnection);
|
use crate::structures::structure::*;
use std::fs::File;
use crate::structures::basic::*;
#[derive(Debug, Default)]
pub struct Module {
types: Vec<FuncType>,
funcs: Vec<String>, // FIXME
tables: Vec<TableType>,
mems: Vec<MemType>,
globals: Vec<GlobalType>,
elem: Vec<String>, // FIXME
data: V... |
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distri... |
// Copyright 2022 Datafuse Labs.
//
// 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 applicable law or agreed to ... |
// Find the Most Competitive Subsequence
// https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/581/week-3-january-15th-january-21st/3611/
pub struct Solution;
impl Solution {
// Causes timeout
#[cfg(disable)]
pub fn most_competitive(mut nums: Vec<i32>, k: i32) -> Vec<i32> {
... |
#[cfg(feature = "serde")]
mod serde;
/// Handle to a value inside the BeachMap.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct ID<V = super::DefaultVersion> {
pub(crate) index: usize,
pub(crate) version: V,
}
impl<V: Default> ID<V> {
/// Returns an [`ID`] that can be used as a dummy value.
... |
//==============================================================================
// Notes
//==============================================================================
// config.rs
//==============================================================================
// Crates and Mods
//=================================... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.