lang
stringclasses
10 values
seed
stringlengths
5
2.12k
rust
let blocked_by = &robot_flow.get(&key_item.loc.clone()).unwrap().3; //println!("{} blocked by {:?}", key_name, blocked_by); for b in blocked_by { // don't walk through keys if b.is_ascii_lowercase() && !used.contains(&b) {
rust
anon_arg_info.is_first, region_info.def_id, region_info.is_impl_item, ); match br { ty::BrAnon(_) => {} _ => {
rust
indicador_ie: dest.indicador_ie, } } } impl FromStr for Destinatario { type Err = Error; fn from_str(s: &str) -> Result<Self, Self::Err> { let base = s.parse::<DestinatarioBase>()?; base.try_into()
rust
use super::fetch; use crate::connection::Conn; use crate::schema::{actors, followings}; /// A model for storing an actor in a database. #[derive(Debug, Identifiable, Insertable, Queryable, Serialize, Deserialize)] #[table_name = "actors"] pub struct Actor { /// The id of the actor as the URL to the ActivityPub Actor document. pub id: String, } /// A model for storing an actor who follows the user in a database. #[derive(Debug, Insertable, Queryable, AsChangeset, Serialize, Deserialize)] #[table_name = "followings"]
rust
use super::*; #[test] #[should_panic] fn test_code_new_reserved_success() { ErrorCode::new(0); } #[test] #[should_panic]
rust
.save(self) .and_then(move |_| { (*parent).lock().unwrap().state = ChunkState::Unloaded; Ok(()) }) .or_else(|err| { // TODO: error handling Ok(()) })); } } }
rust
mod temporary_ffi_project; mod generic_ffi_generator; mod build_type; pub use generic_ffi_generator::*; pub use temporary_ffi_project::*; pub use build_type::*; use crate::generator::{File, ProjectVisitor};
rust
fn main() { println!("running build.rs"); let target = env::var("TARGET").unwrap(); println!("target {}", target); let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap(); println!("target_os {}", target_os);
rust
Constructor(@ast::RecordDeclaration), // f(a, b, ...) = ... Function(@[Fun<Interp>]), // a.{...} Module(@mut linear::LinearMap<ast::Sym, @mut Val<Interp>>), // <routine> Routine(@fn (@mut Interp, @mut env::Env<Interp>) -> @mut Val<Interp>),
rust
color: Cell::default(), border: Cell::new(false), text_cache: RefCell::new(None), }); } pub fn set_text(&self, text: String) { *self.text.borrow_mut() = text;
rust
#[inline(always)] fn bitand_assign(&mut self, rhs: $signed_size) { self.0 &= rhs } }
rust
use super::utils::PipeGraph; pub struct ValidationErrorDetailsDisplay { details: HashMap<String, String>, } impl ValidationErrorDetailsDisplay { pub fn new(details: HashMap<String, String>) -> Self { ValidationErrorDetailsDisplay { details } } } impl Display for ValidationErrorDetailsDisplay { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
rust
let base = Path::new(env!("CARGO_MANIFEST_DIR")); hbs.register_template_file("Dockerfile", base.join("./templates/Dockerfile.hbs")).expect("Could not read ./template/Dockerfile.hbs file."); hbs.register_template_file(".dockerignore", base.join("./templates/.dockerignore.hbs")).expect("Could not read ./template/.dockerignore.hbs file."); hbs.register_helper("choose", Box::new(choose_helper)); hbs } pub fn dockerfile<T>(hbs: &Handlebars<'static>, data: &T) -> String where T: Serialize { hbs.render("Dockerfile", data).expect("Could not render docker tempalte") }
rust
} #[test] fn basic_tests() { assert_eq!(row_weights(vec![13, 27, 49]), (62, 27)); assert_eq!(row_weights(vec![50, 60, 70, 80]), (120, 140)); assert_eq!(row_weights(vec![80]), (80,0)); }
rust
// 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 in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and
rust
use rlua::{Error as LuaError, Lua}; use checksumdir; pub fn checksum(_lua: &Lua, path: String) -> Result<String, LuaError> { checksumdir::checksumdir(&path[..]) .map_err(LuaError::external) }
rust
Rust には null はありませんが、値がないことを表現することの重要性を無視しているわけではありません。 既に知っているツールを使った素朴な表現を考えてみましょう。 1つ以上の値を None によって代替するパターンは、null がない Rust ではとても一般的です。 ジェネリック型はこの問題を解決するのに役立ちます。 Rustには Option と呼ばれるジェネリックな列挙型が組み込まれており、 null を使わずに null 許容な値を表現できます。
rust
assert_eq!(client1.get(b"1".to_vec()), Ok(b"10".to_vec())); assert_eq!(client2.get(b"1".to_vec()), Ok(b"10".to_vec())); assert_eq!(client2.get(b"2".to_vec()), Ok(b"20".to_vec())); client2.set(b"1".to_vec(), b"12".to_vec());
rust
use std::io::{stdin, BufRead}; use std::str::FromStr; fn re_get<'a>(m: &'a regex::Captures, name: &str) -> Result<&'a str> { Ok(m.name(name)
rust
#[derive(Deserialize)] struct Request { name: String, } #[derive(Serialize)] struct Response { message: String, }
rust
<gh_stars>1-10 // Copyright 2020 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 { anyhow::{Context, Error}, fdio::{SpawnAction, SpawnOptions}, fidl::endpoints::ClientEnd, fidl_fuchsia_io as fio, fuchsia_runtime::{HandleInfo, HandleType}, fuchsia_zircon as zx, scoped_task::{self, Scoped}, std::ffi::CString,
rust
let response = surf::get(url("/atcoder-api/v3/user/ac_rank?user=U3", port)) .recv_json::<Value>() .await .unwrap(); assert_eq!(response, json!({"count": 1, "rank": 1})); let response = surf::get(url(
rust
let env = EnvironmentBuilder::new(Arc::new(storage_factory)) .fidl_interfaces(&[Interface::DoNotDisturb]) .spawn_and_get_nested_environment(ENV_NAME) .await .unwrap(); let dnd_proxy = env.connect_to_protocol::<DoNotDisturbMarker>().unwrap(); verify(dnd_proxy.watch().await, DoNotDisturbInfo::new(true, false)); // The following calls should succeed but not return as no value is available. let second_watch = dnd_proxy.watch(); let third_watch = dnd_proxy.watch(); set_dnd(env, None, Some(true)).await;
rust
#[derive(Deserialize)] pub struct ServiceConfig { pub core_settings: CoreSettings, pub listener: ListenerConfig,
rust
arg.into() }; let file = File::open(&path).unwrap_or_else(|e| { panic!("Unable to open {:?}: {}", path, e); }); let file = BufReader::new(file); // Verify that the struct looks like `[pub] struct name;` let input = parse_macro_input!(input as syn::DeriveInput); let name = input.ident; let is_unit_struct = match input.data { syn::Data::Struct(s) => match s.fields {
rust
//! * [An Efficient Memory-Mapped Key-Value Store for `FlashStorage`](http://www.exanest.eu/pub/SoCC18_efficient_kv_store.pdf) //! * [Generalized File System Dependencies](http://featherstitch.cs.ucla.edu/publications/featherstitch-sosp07.pdf) //! //! ### Replication //!
rust
// 浅蓝色 LightBlue = 9, // 浅绿色 LightGreen = 10, // 浅青色 LightCyan = 11, // 亮红色 LightRed = 12, // 粉色 Pink = 13, // 黄色 Yellow = 14,
rust
_ => token.can_begin_type(), }, NonterminalKind::Block => match token.kind { token::OpenDelim(token::Brace) => true, token::Interpolated(ref nt) => !matches!( **nt, token::NtItem(_)
rust
#[test] fn test_path_components() { let path = p!("foo/bar/baz"); let mut components = path.components(); assert_eq!(components.next().unwrap(), "foo"); assert_eq!(components.next().unwrap(), "bar"); assert_eq!(components.next().unwrap(), "baz"); } #[test] fn test_path_accumulative_components() { let path = p!("foo/bar/baz"); let mut components = path.cumulative_components(); assert_eq!(components.next().unwrap(), "foo");
rust
pub const LC_ALL: libc::c_int = 0; pub const SIGWINCH: libc::c_int = 28; extern "C" { pub fn setlocale(category: libc::c_int, locale: *const libc::c_char); }
rust
} #[allow(clippy::unnecessary_wraps)] pub fn parse_evaluate_session_response( response: &http::Response<bytes::Bytes>, ) -> std::result::Result<crate::output::EvaluateSessionOutput, crate::error::EvaluateSessionError> { Ok({ #[allow(unused_mut)] let mut output = crate::output::evaluate_session_output::Builder::default(); let _ = response; output = crate::json_deser::deser_operation_crate_operation_evaluate_session( response.body().as_ref(), output, ) .map_err(crate::error::EvaluateSessionError::unhandled)?;
rust
// distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // FIXME: we should remove this line after we add safe doc to all the unsafe functions // see: https://rust-lang.github.io/rust-clippy/master/index.html#missing_safety_doc #![allow(clippy::missing_safety_doc)] extern crate core; extern crate libc; #[macro_use] pub extern crate librocksdb_sys;
rust
impl<$($T),+> Store for ($($T,)+) where $($T: Store),+ { #[inline] fn store(&self, q: &mut ByteQue) { $(self.$n.store(q);)+ } #[inline] fn restore(q: &mut ByteQue) -> Self { ($($T::restore(q),)+) } } }; }
rust
if line.chars().nth(idx).unwrap() == tree { tree_count += 1; } idx = get_next_idx(idx, line.len(), slope_right); if slope_down > 1 { i += slope_down - 1; }
rust
<gh_stars>0 use std::io::{Read, Write}; use rbx_dom_weak::RbxValue; use crate::{ deserializer::{DecodeError, XmlEventReader}, serializer::{EncodeError, XmlEventWriter}, }; pub trait XmlType<T: ?Sized> {
rust
let ps = PoolService::new(); assert_match!(Err(PoolError::InvalidHandle(_)), ps.send_tx(-1, "txn")); } #[test] fn pool_close_works_for_invalid_handle() { TestUtils::cleanup_storage(); let ps = PoolService::new(); assert_match!(Err(PoolError::InvalidHandle(_)), ps.close(-1)); }
rust
let error_count = error_count.load(Ordering::SeqCst); if error_count > 0 { eprintln!("Found {} problems", error_count); std::process::exit(1); } Ok(()) } pub fn print_rules_list() { let lint_rules = rules::get_recommended_rules();
rust
fidl_fuchsia_net::Ipv6SocketAddress { address: #addr, port: #port, zone_index: #scope_id } } } } declare_macro!(fidl_ip, FidlGen, IpAddr); declare_macro!(fidl_ip_v4, FidlGen, Ipv4Addr); declare_macro!(fidl_ip_v6, FidlGen, Ipv6Addr);
rust
//! let highway_field = feature.field("highway").unwrap(); //! let geometry = feature.geometry(); //! println!("{} {}", highway_field.into_string().unwrap(), geometry.wkt().unwrap()); //! } //! ``` pub use vector::driver::Driver; pub use vector::dataset::Dataset;
rust
} } if result.is_empty() { None } else { Some((result, count)) } } }
rust
let regnum: u8 = 14; let max_regval: u16 = 0xFF; let num_adds = (rest_of_addr / max_regval) as u8; // Remainder value for the last ADD let remainder = (rest_of_addr % max_regval) as u8;
rust
use parser::read_eval_print_loop; fn main() { if let Err(err) = read_eval_print_loop() { match err { rpn::Error::Quit => process::exit(0), _ => println!("Error: {:?}", err) }
rust
// Separation character for an ACTS command pub const COMMAND_DELIMITER: &str = "."; // Number of clauses for an ACTS command pub const COMMAND_SIZE: usize = 2; // Maximum number of requests to handle concurrently // TODO(CONN-6) figure out a good parallel value for this
rust
pub const fn new_standard(len: u8) -> Option<Self> { if len > Self::MAX_STD { None } else { Some(PayloadLength::Standard(len)) } } pub const fn new_extended(len: u16) -> Option<Self> {
rust
($w:ident, $fmt:expr, $($arg:tt)+) => { $w.push_msg(&format!($fmt, $($arg)+)); }; }
rust
let d = ParameterSplineCurveFit::<3,2> ::new(u.clone(), xy.clone())? .smoothing_spline(1E-5)?; let json = serde_json::to_string_pretty(&d)?; println!("{}", json); d.plot("fit.png", (2000,1000))?;
rust
pub struct EcommerceServer { addr: SocketAddr } impl EcommerceServer { pub fn new(addr: String) -> Self { let parsed_addr = addr.parse::<SocketAddr>().unwrap(); EcommerceServer { addr: parsed_addr } } pub async fn run_server(self) -> Result<(), Box<dyn std::error::Error>> { println!("Listening to address: {}\r\n", self.addr);
rust
dotenv::dotenv().ok(); // Initialize logging Logging::from_env().init()?; // Create DigitalOcean instance let digitalocean = DigitalOcean::from_env().init().await?; // Create DataBase instance let database = Database::from_env().init().await?; // Create Telegram instance let telegram = Telegram::from_env().init().await?; // Create Worker instance
rust
Ok(x) => x, Err(err) => { eprintln!("{}", err); panic!() } };
rust
pub use version::VersionInfo; pub use version::FullVersion; pub use version::OriginFile; mod scan; pub use scan::Scan; mod process;
rust
use serde::{Deserialize, Serialize}; #[derive(Deserialize, Serialize, Debug, Clone)] pub struct PerpetualData { pub interest: f64, }
rust
fn main() { let mem = 361527; println!("Memory {} takes {} steps.", mem, day3::memory_distance(mem)); println!( "First value above {} is {}", mem, day3::first_large_value(mem).unwrap() ); }
rust
#[doc(alias = "gtk_accelerator_valid")] pub fn accelerator_valid(keyval: gdk::keys::Key, modifiers: gdk::ModifierType) -> bool { assert_initialized_main_thread!(); unsafe { from_glib(ffi::gtk_accelerator_valid( keyval.to_glib(), modifiers.to_glib(),
rust
use core::fmt::Write; if let Some(mut writer) = $crate::vga_buffer::WRITER.try_lock() { writer.write_fmt(format_args!($($arg)*)).unwrap(); } }); }
rust
#[cfg(not(feature = "unicode-xid-ident"))] assert!(result.is_err()); let result = engine.eval::<INT>( " fn _1() { 1 } _1() ", ); assert!(result.is_err());
rust
self.bytes.push_str(block); self.bytes.push_str(" {\n"); } self.section_pending = false; } else if self.section_pending { if !self.bytes.is_empty() { self.bytes.push('\n');
rust
use lib3h_protocol::{ data_types::*, error::Lib3hProtocolResult, network_engine::NetworkEngine, protocol_client::Lib3hClientProtocol, protocol_server::Lib3hServerProtocol, Address, DidWork, }; use rmp_serde::{Deserializer, Serializer}; use serde::{Deserialize, Serialize}; impl TransportKeys { pub fn new(crypto: &dyn CryptoSystem) -> Lib3hResult<Self> { let hcm0 = hcid::HcidEncoding::with_kind("hcm0")?; let mut public_key: Box<dyn Buffer> = Box::new(vec![0; crypto.sign_public_key_bytes()]); let mut secret_key = crypto.buf_new_secure(crypto.sign_secret_key_bytes());
rust
//! Document crate #[macro_use] extern crate log; pub mod classic; pub mod sequenceops;
rust
enum Class { // Unknown is special and doesn't need a discriminant Unknown(isize), #[disunity(discriminant = 1)] GameObject { field: i32, }, #[disunity(discriminant = 2)] Transform, #[disunity(discriminant = 3)] Magic(i32), }
rust
pub struct Factory { ptr: ComPtr<IDWriteFactory>, } impl Factory { pub fn new() -> Result<Factory, DWriteError> { unsafe { let mut ptr: *mut IDWriteFactory = ptr::null_mut();
rust
#[allow(unused)] mod common; use common::{destroy_ds3234, new_ds3234, BitFlags, Register}; call_test!( can_en_temp_conv_bat, enable_temperature_conversions_on_battery, new_ds3234, destroy_ds3234, [SpiTrans::write(vec![Register::TEMP_CONV + 0x80, 0])] ); call_test!( can_dis_temp_conv_bat, disable_temperature_conversions_on_battery,
rust
fn sse(ct: u8) -> impl Stream<Item = Result<Event, Infallible>> { futures::stream::iter((0..=ct).into_iter().map({ |i| { let mut gen = Generator::new(r"[^\r\n]*", rand::thread_rng(), DEFAULT_MAX_REPEAT).unwrap(); let mut data = Vec::new(); gen.generate(&mut data).unwrap(); Ok(Event::default() .id(i.to_string()) .data(String::from_utf8_lossy(&data))) } })) }
rust
d -= 2 * dx; } d += 2 * dy; } } /// Get a pixel given its x,y position. /// /// `S`: pixel stride (`4` -> 4 bytes per pixel) fn get_pixel<const S: usize>(&self, x: i16, y: i16) -> [u8; S] { let idx = ((x + y * WIDTH as i16) as usize) * S; let mut pixel = [0u8; S]; pixel.copy_from_slice(&self.buffer[idx..idx + S]);
rust
//! Implementation of `CommandModel` and `CreateCommand` macros for enums (subcommands). mod command_model; mod create_command; mod parse; pub use command_model::impl_command_model; pub use create_command::impl_create_command;
rust
use ::{NbitsVec, N2}; type NV = NbitsVec<N2, usize>; #[test] fn into_iter() { let vec = NV::new(); for val in vec.into_iter() { let _ = val; }
rust
let id = self.get_next_id(); let state = self.create_state(); let printed = self.id_lookup.add_file(filename.clone().into_iter(), (self.site_id, id), self.site_id); let filename:Vec<_> = filename.iter().map(|c| c.to_str().unwrap().to_string()).collect(); self.files.insert((self.site_id, id), FileMetadata { filename: (state.time_stamp, filename.clone()), printed_filename: printed, attributes: HashMap::new() }); self.save().unwrap(); FileSetOperation::Create(CreateOperation { state: state,
rust
#[derive(Debug, Clone, Serialize, Deserialize, Queryable, Insertable)] #[table_name = "users"] pub struct User { pub id: i64, pub name: String, pub username: String, pub email: String, #[serde(skip_serializing)] pub password: String,
rust
use std::time::Duration; fn main() { let mut xplane = XPlane::new("127.0.0.1", 1).unwrap(); loop { if let Some(position) = xplane.position().unwrap() { println!("{:#?}", position); } else { thread::sleep(Duration::new(0, 1000000000/1000)); } } }
rust
// CHECK: #APP // CHECK: r{{[0-9]+}} = r{{[0-9]+}} // CHECK: #NO_APP check!(reg_i64 i64 reg); // CHECK-LABEL: wreg_i8: // CHECK: #APP // CHECK: w{{[0-9]+}} = w{{[0-9]+}} // CHECK: #NO_APP check!(wreg_i8 i8 wreg); // CHECK-LABEL: wreg_i16: // CHECK: #APP // CHECK: w{{[0-9]+}} = w{{[0-9]+}}
rust
Self { endian } } } impl DataOps for ReadDouble { type Out = f64; fn read(&self, start: usize, bytes: &[u8]) -> Option<Self::Out> { bytes.get(start..(start + 8))
rust
impl Plugin for LoadingPlugin { fn build(&self, app: &mut App) { AssetLoader::new(GameState::Loading) .with_collection::<FontAssets>() .with_collection::<TextureAssets>() .continue_to_state(GameState::Menu) .build(app);
rust
ColumnDef::new(entity::user::Column::Password) .string() .not_null(), ) .col( ColumnDef::new(entity::user::Column::PgpKey) .binary() .not_null(), ) .if_not_exists() .to_owned(), ) .await?; manager
rust
impl<'de> serde::Deserialize<'de> for Pos { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let s: String = String::deserialize(deserializer)?; Pos::parse(&s).ok_or_else(|| <D::Error as serde::de::Error>::custom("bad position")) } }
rust
.blocklist_function("sqrtl") .blocklist_function("strtold") .blocklist_function("tanhl") .blocklist_function("tanl") .blocklist_function("tgammal") .blocklist_function("truncl")
rust
Ok(repo) } #[tracing::instrument(level = "debug")] pub(crate) fn prepare_submodules(
rust
} } } /// Push up to an usize worth of bits pub fn push_bits(&mut self, bits: usize, count: usize) { if count == 0 { return;
rust
fn trigger_wol(&self, server_number: u32) -> Result<WakeOnLan, Error> { self.post::<WakeOnLanResponse, ()>(&format!("/wol/{}", server_number), ()) .map(WakeOnLan::from) } } #[cfg(test)] mod tests { use super::WakeOnLanRobot;
rust
compressed_data.len(), data.len() - compressed_data.len() ); conn.execute( "INSERT INTO hogan (key, data) VALUES (?1, ?2)",
rust
net.sf.jasperreports.engine.util.ResourceBundleMessageProviderFactory
rust
mod forced_exit; mod mint_nft; mod priority_ops; mod swap; mod transfer; mod withdraw; mod withdraw_nft;
rust
// ## WebView API // webview.eval(&format!("updateTicks({}, {})", counter, user_data)) // exit() : Window exit pub fn make_gui<'a>(cfg: AppConfig, html: &'a str, title: &'a str) -> WebView<'a, ()>{ let db_path = cfg.db_path.clone(); let mut webview = web_view::builder() .title(title) .content(Content::Html(html)) .size(cfg.window_width, cfg.window_height) .frameless(cfg.window_frameless)
rust
} } pub fn midi_in(&mut self, midi_message: MidiMessage) { let stack = match self.channels[0].as_mut() { Some(stack) => stack, None => return, }; match midi_message { MidiMessage::NoteOn(_channel, note, _velocity) => { self.pitch = note.to_freq_f64();
rust
/// Returns `true` if `HttpHeaders` contains no headers at all. pub fn is_empty(&self) -> bool { unimplemented!() } /// Adds a HTTP header. This will not overwrite an existing header of the same name.
rust
impl core::ops::Deref for S0ROM_R { type Target = crate::FieldReader<bool, S0ROM_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Sector 1 Locked Forever by User 2\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum S1ROM_A { #[doc = "0: No ROM functionality configured for sector n."] VALUE1 = 0, #[doc = "1: ROM functionality is configured for sector n. Re-programming of this sector is no longer possible."]
rust
/// Optional command to run. pub command: Option<PathBuf>, /// Optional arguments to pass to the command. pub args: Vec<OsString>, }
rust
// This looks stupid but we can only evaluate based on types. Both 1 and 2 are `Int`. assert_type_for_expr("Bool", "(= 1 2)"); } }
rust
self.0.load(Ordering::Relaxed) } } impl Clone for CountsClones { fn clone(&self) -> Self { self.0.fetch_add(1, Ordering::Relaxed); Self(self.0.clone())
rust
Ok(Self { float_length, length_invert, divider, s_x,
rust
recipient: env.contract.address.clone().into(), amount: config.amount, }; let exec_cw20_transfer = WasmMsg::Execute { contract_addr: config.token_address.addr().into(),
rust
pub static ACTOR_INKS: &[Ink] = &[ Ink::EraseActor, Ink::Actor(ActorKind::Lapin), Ink::Actor(ActorKind::Knight), Ink::Actor(ActorKind::Wolf), Ink::Actor(ActorKind::Fox), Ink::Actor(ActorKind::Hunter), Ink::Actor(ActorKind::Sheep), Ink::Actor(ActorKind::Dragon), ]; impl fmt::Display for Ink { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self {
rust
context ) } let toml_end = advisory_data.find("\n```").ok_or_else(|| { format_err!(
rust
table! { Transactions (id) { id -> Nullable<Integer>, sequence -> Nullable<Integer>, tranType -> Nullable<Integer>, dateTime -> Nullable<Double>, amount -> Nullable<Double>, } }
rust
fn refract(v: &Vec3, n: &Vec3, ni_over_nt: f32) -> Option<Vec3> { let uv = v.unit(); let dt = uv.dot(n); let discriminant = 1.0 - ni_over_nt * ni_over_nt * (1. - dt * dt); if discriminant > 0. { Some(ni_over_nt * (uv - n * dt) - n * discriminant.sqrt()) } else { None } }
rust
.service .clone() .get_events_by_txn_info_id(txn_info_id) .map_ok(|d| d.unwrap_or_default()) .map_err(map_err); Box::new(fut.compat()) } fn branches(&self) -> FutureResult<Vec<ChainInfo>> { let fut = self .service .clone() .master_startup_info() .map(|result| Ok(Into::<Vec<ChainInfo>>::into(result?))) .map_err(map_err); Box::new(fut.compat())
rust
"rotate" => { let amount = match parts[1] { "left" => parts[2].parse().unwrap(), "right" => self.password.len() - parts[2].parse::<usize>().unwrap(), "based" => { let pos = self.find(parts[6]); 2 * self.password.len() - if pos >= 4 { pos + 2 } else { pos + 1 } }, _ => panic!("Cannot rotate by {}", parts[2]), } % self.password.len();
rust
//! the `round` function, which supports three modes: //! * [Half Up](https://en.wikipedia.org/wiki/Rounding#Round_half_up) //! * [Half Down](https://en.wikipedia.org/wiki/Rounding#Round_half_down) //! * [Half Even](https://en.wikipedia.org/wiki/Rounding#Round_half_even) (default) //! //! ```edition2018 //! use rusty_money::{money, Money, Currency, Round};
rust
//! https://docs.gitlab.com/ce/api/projects.html#list-branches //! //! # List branches //! //! Lists all branches of a project. //! //! ```text //! GET /projects/ID/repository/branches //! ``` //! //! Parameters: //! //! | Attribute | Type | Required | Description | //! | --------- | ---- | -------- | ----------- | //! | `id` | integer/string | yes | The ID of the project or `NAMESPACE/PROJECT_NAME` |
rust
<gh_stars>1-10 use virtual_modular_core_nodes::std_nodes; use virtual_modular_definition_language::{code_generation::to_rust, parse}; fn main() { let input_path = std::env::args().nth(1).expect("Must supply input path"); let output_path = std::env::args().nth(2).expect("Must supply output path"); let parsed = parse(&std::fs::read_to_string(&input_path).expect("Couldn't read inputs")).unwrap();
rust
ui.collapsing("Test box rendering", |ui| self.box_painting.ui(ui)); CollapsingHeader::new("Scroll area") .default_open(false) .show(ui, |ui| { ScrollArea::from_max_height(200.0).show(ui, |ui| { ui.label(LOREM_IPSUM_LONG); }); }); CollapsingHeader::new("Painting")
rust
pub fn add_idle_token(&self, token: window::IdleToken) { tracing::trace!("add_idle_token initiated {:?}", token); let mut queue = self.queue.lock().unwrap(); queue.push(Kind::Token(token));