lang
stringclasses
10 values
seed
stringlengths
5
2.12k
rust
} #[derive(Debug)] pub enum UnitTypeError { /// if the value was outside the range `0` - `31`. ValueOutOfRange(u8) } #[derive(Copy,Clone)] pub struct NalHeader ( u8 );
rust
} debug::info!("Leaving get_user_debt_with_interest"); if let Some(user_debt) = Self::user_debt(asset_id, user) { (total_debt_index / user_debt.index).saturating_mul_int(user_debt.amount) } else { T::Balance::zero() } } pub fn get_user_supply_with_interest(asset_id: T::AssetId, user: T::AccountId) -> T::Balance {
rust
pub mod warparty; pub mod monstercard; pub mod monstercards; pub mod combat; pub mod stattype; pub mod monstertypes; pub mod eventtypes; use monstercard::MonsterCard; struct _Hand { cards: Vec<MonsterCard>, }
rust
current_state: &StateType, rng: &mut R, current_score: Option<f64>, ) -> (StateType, TransitionType, f64); fn evaluate_state(&self, state: &StateType) -> f64; } #[cfg(test)]
rust
} pub struct LocalDeps { docker: clients::Cli, } impl LocalDeps { pub fn new() -> Self { Self { docker: clients::Cli::default(), } } pub fn run_postgres(&self) -> PostgresHandle { let image = images::postgres::Postgres::default();
rust
process_post(&args, entry)?; } } Ok(()) }
rust
left: None, right: None, } } // --- fn boxer(node: Node) -> NodeBox { Some(Box::new(node)) } // --- fn set_left(&mut self, node: Node) { self.left = Self::boxer(node); }
rust
rows: 1, cols: 1, orientation: AxisPlaneOrientation::ZX, } .build(); grid.rotate([0.0, 1.0, 0.0], std::f64::consts::PI * 0.25); let bbox = grid.bounding_box(); let bound = 2.0_f64.sqrt(); let minb = bbox.min_corner();
rust
running -= 1; } } if running <= 0 { break; } self.do_step(); } steps[0].lcm(&steps[1].lcm(&steps[2])) } } fn main() { let mut sim = Simulation::from_stdin();
rust
} UnmutateVecToken::Replace(new_value, new_cache) => { // M::ValueConversion::replace(value, new_value); let _ = std::mem::replace(value, new_value); let _ = std::mem::replace(cache, new_cache); } UnmutateVecToken::InsertMany(idx, v, c) => { insert_many(value, idx, v.into_iter()); insert_many(&mut cache.inner, idx, c.inner.into_iter()); let added_cplx = c.sum_cplx; cache.sum_cplx += added_cplx; }
rust
/// } /// ``` fn into_cache<A>(self, upstream: &Addr<A>) -> QueryCache<A, Self> where A: Actor, Self: Message + Send + Sized, Self::Result: MessageResponse<A, Self> + Send + 'static, { QueryCache { upstream: upstream.clone(), message: self, }
rust
/// [winapi]: https://docs.rs/winapi/*/winapi/um/winbase/constant.PIPE_TYPE_MESSAGE.html pub type PIPE_TYPE_MESSAGE = crate::doc::NotDefinedHere; /// See [winapi::um::winbase::PIPE_TYPE_BYTE][winapi] /// /// [winapi]: https://docs.rs/winapi/*/winapi/um/winbase/constant.PIPE_TYPE_BYTE.html pub type PIPE_TYPE_BYTE = crate::doc::NotDefinedHere; /// See [winapi::um::winbase::PIPE_CLIENT_END][winapi]
rust
Mod(Reg(r), op) => { regs[r] %= get_val(&regs, op) }, Rcv(_) => { return freq }, Jgz(op1, op2) => { if get_val(&regs, op1) > 0 { new_pc = pc + get_val(&regs, op2); }; }, _ => panic!(), } pc = new_pc; } } struct Thread<'a> {
rust
val * 100 } #[cfg(test)] mod extra; #[cfg(test)]
rust
frame.render_widget(block, size); let mut banner = Text::from(BANNER); banner.patch_style(styling::banner_style()); let banner_widget = Paragraph::new(banner); frame.render_widget(banner_widget, rows[0]); let mut content = Text::from(CONTENT); content.patch_style(styling::normal_text_style()); let content_widget = Paragraph::new(content); frame.render_widget(content_widget, rows[1]); } fn my_tasks(frame: &mut Frame, size: Rect, state: &State) {
rust
#[test] fn distinct_simple_round_promotion() { test_distinct( vec![(8, 1), (9, -1), (5, 1), (6, -1), (8, -1), (9, 1)], vec![(5, 1), (6, -1)], ) } #[test] fn distinct_full_promotion() { test_distinct( vec![ (9, 1), (9, 1),
rust
return Instant::now(); } fn get_destination_reached_icmp_type(&self) -> Option<IcmpType> { Some(IcmpTypes::EchoReply) } fn get_rx(&mut self) -> &mut TransportReceiver { self.channels.rx_icmp.as_mut().unwrap() }
rust
use log::*; use std::time::Duration; #[cfg(feature = "hyper_client")] pub mod client { use super::*; use hyper::body::to_bytes; use hyper::Uri; use std::str::FromStr; pub type HttpClient = hyper::Client< hyper_timeout::TimeoutConnector< hyper::client::HttpConnector<hyper::client::connect::dns::GaiResolver>,
rust
#[path = "../../src/long_mode.rs"] mod long_mode; pub use long_mode::*; #[path = "../../src/protected_mode.rs"] mod protected_mode;
rust
} } pub struct Boxa { pub raw: leptonica_plumbing::Boxa, } impl Boxa { pub fn get_n(&self) -> usize { let lboxa: &leptonica_plumbing::leptonica_sys::Boxa = self.raw.as_ref(); lboxa.n as usize }
rust
continue; } } passed = false; let s = if turn == Square::Black { "o" } else { "x" }; print!("\n{}'s turn> ", s); io::stdout().flush();
rust
/// Module containing the channel logic for arcon pub mod channel; /// Module containing arcon nodes that drive the streaming execution pub mod node; /// Module containing all available arcon streaming operators pub mod operator; /// Module containing all available arcon sources pub mod source; /// Module containing time logic within Arcon pub mod time;
rust
use dotenv::dotenv; use std::env; use crate::api::router; fn main() { let addr = "0.0.0.0:8000"; dotenv().ok(); env_logger::init(); let db_url = env::var("DATABASE_URL").expect("DATABASE_URL must be specify"); gotham::start(addr, router(db::Repo::new(&db_url))); }
rust
pub type SYS_TIMER_TARGET2_TIMER_UNIT_SEL_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SYS_TIMER_TARGET2_TIMER_UNIT_SEL`"] pub struct SYS_TIMER_TARGET2_TIMER_UNIT_SEL_W<'a> { w: &'a mut W, } impl<'a> SYS_TIMER_TARGET2_TIMER_UNIT_SEL_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)]
rust
@center@ @mycanvas()@ @center@ Koliko učenika trenira košarku? @hspacept(5)@ @lib.check_number(basket,15)@ @center@ Koliko učenika trenira samo fudbal? @hspacept(5)@ @lib.check_number(res_f,15)@ @center@ Koliko učenika ne trenira košarku? @hspacept(5)@ @lib.check_number(vel,15)@
rust
impl FromStr for Code { type Err = ComputerError; fn from_str(input: &str) -> Result<Code, Self::Err> { Ok(input .split(",") .map(|s| s.trim().parse()) .collect::<Result<Vec<_>, _>>()? .into()) } }
rust
println!("foo: {}", transfer_if_odd("foo")); println!("foobar: {}", transfer_if_odd("foobar")); } fn transfer_if_odd(val: &'static str) -> bool { let dr = DynRef::new(); { let mut lifetime = Lifetime::empty(); let s = String::from(val); assert!(dr.is_none()); { stack_let!(inner_lifetime = dr.lock(&s)); assert!(dr.is_some());
rust
.map(|(i, target)| TargetEntry::new(target, TargetFlags::all(), i as u32)) .collect(); clipboard.set_with_data(&targets, move |_, selection, _| { selection.set(&selection.target(), 8i32, string.as_bytes()); }); } pub(crate) fn read_text(&self) -> Option<String> { let display = gdk::Display::default().unwrap(); let clipboard = gtk::Clipboard::default(&display).unwrap(); for target in &CLIPBOARD_TARGETS {
rust
) -> bool { let p0 = a * v0[1] - b * v0[2]; let p2 = a * v2[1] - b * v2[2]; let min: f32; let max: f32; if p0 < p2 { min = p0; max = p2; } else { min = p2; max = p0; }; let rad = (fa + fb) * half_box; !(min > rad || max < -rad)
rust
} } fn bad2() { for Some(Qux(_)) | None in [Some(""), None] { //~^ ERROR mismatched types todo!(); } }
rust
newstate } } pub enum MainState {
rust
assert_eq!(result, expected); } #[test] fn ok_single_with_comma() { let input = r#"a: u232,"#;
rust
impl AsRawFd for SignalFd { #[inline] fn as_raw_fd(&self) -> libc::c_int { self.fd } } impl Drop for SignalFd { #[inline] fn drop(&mut self) { unsafe { libc::close(self.fd); } } }
rust
#![crate_name="crateA"] // Base crate pub fn func<T>() {}
rust
} #[test] fn test_in_array_invalid_null() { let mut params = Map::new(); params.assign("in", Value::Null).ok(); params.assign("other", Value::Array(vec![Value::String("1".into()), Value::U64(2)])) .ok(); let mut rules = BTreeMap::new(); rules.insert("in", vec![Rule::InArray("other")]); let result = validate(&rules, params);
rust
Deltas::default() } } } /// Iterator over the set of per-region deltas for an item. #[derive(Copy, Clone, Default)] struct Deltas<'a> { store: ItemVariationStore<'a>, cursor: Cursor<'a>, region_indices: Slice<'a, u16>, num_word_deltas: u16, long_words: bool, len: u16,
rust
} impl Display for BlockRef { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.block) } } pub struct Block { label: String, idx: u64, instructions: RefCell<Vec<Instruction>>, func: FunctionWeakRef, }
rust
#[bench] pub fn teams(b: &mut test::Bencher) { let parser = liquid::ParserBuilder::with_liquid() .extra_filters() .build() .unwrap();
rust
for g in guilds { let guild = match g.to_guild_cached(&ctx).await { Some(guild) => guild, None => return, };
rust
Self { position, light_index: light_index as f32, light_position: Point4::new( light.position.x,
rust
let write_res = stream.write(&buffer[0..bytes_read]); if write_res.is_ok() { let bytes_written = write_res.unwrap(); assert!(bytes_written == bytes_read); if bytes_read < BUFFER_SIZE { break; } // buffer is extended each time read_to_end() is called, so we need this. // In theory, it should be very cheap, as it doesn't de-allocate the memory... buffer.clear();
rust
"Service trait must have only methods", ) .to_compile_error()) } }; let lit_method_name = syn::LitStr::new(&format!("{}", method.sig.ident), Span::call_site()); let encoder_module_name = quote::format_ident!(
rust
/// [getName](https://developer.android.com/reference/android/app/VoiceInteractor.Request.html#getName()) /// /// Required features: "java-lang-String" #[cfg(any(feature = "all", all(feature = "java-lang-String")))] pub fn getName<'env>(&'env self) -> __jni_bindgen::std::result::Result<__jni_bindgen::std::option::Option<__jni_bindgen::Local<'env, crate::java::lang::String>>, __jni_bindgen::Local<'env, crate::java::lang::Throwable>> { // class.path == "android/app/VoiceInteractor$Request", java.flags == PUBLIC, .name == "getName", .descriptor == "()Ljava/lang/String;" unsafe { let __jni_args = []; let __jni_env = __jni_bindgen::Env::from_ptr(self.0.env); let (__jni_class, __jni_method) = __jni_env.require_class_method("android/app/VoiceInteractor$Request\0", "getName\0", "()Ljava/lang/String;\0"); __jni_env.call_object_method_a(self.0.object, __jni_method, __jni_args.as_ptr()) } }
rust
pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w);
rust
} impl Actor for Answerer { fn receive(&self, message: Box<Any>, context: ActorCell) { if let Ok(message) = Box::<Any>::downcast::<Exchanges>(message) { if *message == Exchanges::Request { context.complete(context.sender(), Exchanges::Answer(self.secret)); } } } } impl Answerer {
rust
use std::error; use std::fmt; use syntex_pos::SpanSnippetError; #[derive(Debug, PartialEq)] pub enum Error { Snippet(SpanSnippetError), InvalidInput, Unsupported, } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
rust
pub mod bo; pub mod condition_behavior; pub mod ctr_behavior;
rust
.read(false) .write(true) .mode(nix::libc::S_IWUSR | nix::libc::S_IRUSR) .open("/dev/kmsg") .map_err(|io| { printable_error(PROGRAM_NAME, format!("unable to open /dev/kmsg: {}", io)) })?; Ok(Self(file))
rust
extern crate hygiene_example_codegen; pub use hygiene_example_codegen::hello; pub fn print(string: &str) { println!("{}", string); }
rust
let data = MyData { field1: "This is my string".to_owned(), field2: 4402, }; println!("Data: {:?}", data); } // ------------ #[derive(Eq)] struct DateNotes { day: u8,
rust
sql: sql, _marker: PhantomData, } } } impl<ST> Expression for SqlLiteral<ST> { type SqlType = ST;
rust
for (seg_a, seg_b) in self.segments().zip(other.segments()) { if seg_a.ends_with("..>") || seg_b.ends_with("..>") { return true; } if !seg_a.collides_with(seg_b) { return false; } }
rust
pub fn delete_limits(&self, namespace: &Namespace) -> Result<(), StorageErr> { if let Some(data) = self.limits.write().unwrap().remove(namespace) { let limits = data.iter().cloned().collect(); self.counters.delete_counters(limits)?; }
rust
} /// Find the guard + minute pairing that had the most sleep occurrences /// Return the product of the two as desired by the problem. fn part2(minute_counters: &[Counter<Guard>]) -> usize {
rust
let a_give_count = (&set_a - &set_b).len(); let b_give_count = (&set_b - &set_a).len(); writeln!(output, "{}", min(a_give_count, b_give_count))?; } } fn main() {
rust
// SPDX-License-Identifier: Apache-2.0 use sallyport::syscall::FileSyscallHandler; impl<'a> FileSyscallHandler for super::Handler<'a> {}
rust
let len = a.len(); let a = a.as_ptr(); let a_end = a.add(len); let mut node = a.add(i); loop {
rust
use serde::{Serialize, Deserialize}; use chrono::NaiveDateTime; use rocket_codegen::FromForm; use rocket::{Request, response::{self, Responder}, Response, http::{self, ContentType}}; use std::io::Cursor; #[derive(Serialize, Debug)] pub struct Paste { pub id: i64, pub filename: Option<String>, pub content: Option<String>,
rust
//! Interpreter-facing API to the Yorick meta-tracer. #![cfg_attr(test, feature(test))] mod location; pub(crate) mod mt; pub use self::location::Location; pub use self::mt::{HotThreshold, MT};
rust
prop_compose! { pub fn someip_header_any()( message_id in any::<u32>(), length in SOMEIP_LEN_OFFSET_TO_PAYLOAD..SOMEIP_MAX_PAYLOAD_LEN + 1, request_id in any::<u32>(),
rust
_ => '1', }) .collect::<String>() }) .map(|sit| u16::from_str_radix(&sit, 2).unwrap()) .collect::<Vec<_>>(); sits.sort(); let answer = sits .windows(2) .find(|neighbors| neighbors[1] - neighbors[0] == 2) .map(|neighbors| neighbors[0] + 1) .unwrap(); println!("{}", answer); }
rust
fn open_or_senior(data: Vec<(i32, i32)>) -> Vec<String> { let mut result = Vec::new(); for elem in data.into_iter() { if elem.0 >= 55 && elem.1 > 7 { result.push(String::from("Senior")); } else { result.push(String::from("Open"));
rust
use bee_signing_ext::binary::ed25519; const PBKDF2_ROUNDS: usize = 2048; const PBKDF2_BYTES: usize = 32; // 64 for secp256k1 , 32 for ed25 /// PBKDF2 helper, used to generate [`Seed`][Seed] from [`Mnemonic`][Mnemonic] /// /// [Mnemonic]: ../mnemonic/struct.Mnemonic.html /// [Seed]: ../seed/struct.Seed.html fn _pbkdf2(input: &[u8], salt: &str) -> Vec<u8> { let mut seed = vec![0u8; PBKDF2_BYTES]; pbkdf2::pbkdf2::<Hmac<sha2::Sha512>>(input, salt.as_bytes(), PBKDF2_ROUNDS, &mut seed);
rust
/// This combinator is conceptually equivalent to calling /// `.into_future().and_then()` on a stream and properly passing /// both the returned value and the stream through a stream /// transformation function. /// A stream that wraps and transforms another stream /// once it has produced a value #[derive(Debug)] #[must_use = "streams do nothing unless polled"] pub struct Sequence<S, F, U>
rust
use std::collections::HashMap; pub fn bbbbb() { println!("good fkdjslfsjdlfkasjflsdfsla"); }
rust
use sqlx::FromRow; use sqlx::*; pub struct Maine { pub db: db::DB, }
rust
); test_case!( getIsize, {-1isize} {0isize} {1isize} {::std::isize::MAX >> 1} ); test_case!( getOption, { None } { Some(1isize)}
rust
#[test] fn test_non_authorized() { let content = String::from(PASSWORD) + "\n" + NOTES; let session = Session::default(); let args = [RESOURCE.to_owned(), content]; let mut arg_iter = args.iter().cloned(); assert!(matches!( new_record(&session, &mut arg_iter), Err(Error::UnacceptableRequestAtThisState) ));
rust
use mmrbi::*; fn main() { warning!("this is a test warning"); error!(code: "EX0001", "this is a test error"); info!(at: "examples/macros.rs", "this is a test message"); }
rust
/// compiler pub const BLOCK_HAS_EXTENDED_LAYOUT: block_flags = 1 << 31; /// Flags used in the final argument to _Block_object_assign() and /// _Block_object_dispose(). These indicate the type of copy or dispose to /// perform. /// Values for _Block_object_assign() and _Block_object_dispose() parameters /// /// This is a helper type, in the sources this type does not have a name! #[allow(non_camel_case_types)] pub type block_assign_dispose_flags = i32; /// The value is of some id-like type, and should be copied as an Objective-C /// object: i.e. by sending -retain or via the GC assign functions in GC mode
rust
#[error("Amount is not available!")] AmountIsNotAvailable {}, #[error("Vesting schedule error on addr: {0}. Should satisfy: (start < end and at_start < total) or (start = end and at_start = total)")] VestingScheduleError(Addr), #[error("Vesting schedule amount error. Schedules total amount should be equal to cw20 receive amount.")] VestingScheduleAmountError, }
rust
source.split(split_by).map(|s| s.to_string()).collect() } // convert a string to a Rust file path pub fn push_file_path( path: &str,
rust
y: splits.next().unwrap().parse().unwrap(), } } fn abs_difference(&self, other: &Point) -> Coord { (self.x - other.x).abs() + (self.y - other.y).abs() } } impl Map { /// Make a new map that will fit all these points
rust
#![cfg_attr( all(not(debug_assertions), target_os = "windows"), windows_subsystem = "windows" )] mod app;
rust
<gh_stars>1000+ // compile-flags:-g #![crate_type = "rlib"] #[macro_export] macro_rules! new_scope { () => { let x = 1;
rust
flags: flags }; trace!("data: {:?}", data); unsafe { let ptr = buffer.ptr() as *mut RawSegment; *ptr.as_mut().unwrap() = data; buffer.into_box() } }
rust
&object_path, args.load_address, args.addresses, args.verbose, args.file_offset_type, ); match result {
rust
use crate::default_skin::button::DefaultButtonSkin; pub mod button; pub type Button = crate::button::Button<DefaultButtonSkin>; pub type ButtonId = crate::button::ButtonId; pub type ButtonBuilder = crate::button::ButtonBuilder<DefaultButtonSkin>; pub type RibbonBuilder = crate::ribbon::RibbonBuilder;
rust
} if balance == 0 { res += 1; } } res } // greedy string #[test] fn test1_1221() { assert_eq!(balanced_string_split("RLRRLLRLRL".to_string()), 4);
rust
use crate::Hitable; use crate::Ray; #[derive(PartialEq)] pub struct HitableList<T: Hitable + std::fmt::Debug> { l: Vec<Box<T>>, } impl<T: Hitable + std::fmt::Debug> HitableList<T> { pub fn new() -> HitableList<T> { HitableList::<T> { l: Vec::new() } }
rust
} fn main() { let filename = "input.txt"; let fd = File::open(filename).expect(&format!("Failure opening {}", filename)); let buf = BufReader::new(fd); let mut v_orig = Vec::new(); buf.lines().for_each(|line| { line.unwrap().split(',').for_each(|numstr| { let num = numstr.parse::<i64>().unwrap(); v_orig.push(num); });
rust
) } #[test] fn many_distribute_glow_to_voter() { let mut deps = mock_dependencies(&[]); mock_instantiate(deps.as_mut()); mock_register_contracts(deps.as_mut()); let mut env = mock_env_height(0, 1000000); let info = mock_info(VOTING_TOKEN, &[]); for i in 2..=101 {
rust
fn main() { let s: i32; let s1; {
rust
/// The height of the hex pillars is discretized. So instead of saving a `f32` /// to represent the height, we have fixed steps of heights and we will just /// save a `u16` to represent the height. pub const PILLAR_STEP_HEIGHT: f32 = 0.5; /// How many hex pillars a chunk is long. So the number of hex pillars in a /// chunk is `CHUNK_SIZE`². pub const CHUNK_SIZE: u16 = 16;
rust
append(&mut file, preamble); if verbose { println!("[Info] Created CONTRIBUTING.md"); } } fn append_rule(rule: &Rule) { let mut file: File = open(CONTRIBUTING); if rule.flag { append(&mut file, rule.rule);
rust
if child.file_type()?.is_dir() { remove_dir_all_recursive(&child.path())?; } else { fs::remove_file(&child.path())?; } } fs::remove_dir(path) }
rust
) }), |(arc_process, tuple)| { prop_assert_eq!(native(&arc_process, tuple), Err(badarg!().into())); Ok(()) }, ) .unwrap(); }
rust
#[derive(Debug, Copy, Clone)] pub struct RawVkSurfaceProtectedCapabilities { pub s_type: RawVkStructureType, pub next: *mut c_void, pub supports_protected: u32, }
rust
pub struct MerkleTree { pub root: [u8; 28], layers: Vec<Layer>, } impl MerkleTree { pub fn new<T>(leafs: &[T]) -> Self where Vec<u8>: From<T>, T: Clone,
rust
} pub fn add_resource_root(&mut self, root_path: &str) { self.resource_root.push(root_path.to_string()); } pub fn add_test_source_root(&mut self, root_path: &str) { self.test_source_root.push(root_path.to_string()); } pub fn add_test_resource_root(&mut self, root_path: &str) { self.test_resource_root.push(root_path.to_string()); } }
rust
use std::ffi::CString; pub unsafe fn to_c_str<T>(input: T) -> *const libc::c_char where T: std::convert::Into<std::vec::Vec<u8>>, { let c_str = CString::new(input).unwrap(); let ptr = c_str.as_ptr(); std::mem::forget(c_str); ptr }
rust
} } // JC (0xD, 0xA) => { let addr = self.fetch_word(io); debug_println!("JC ${:04X}", addr); if self.get_flag(Flag::C) {
rust
use std::{env, fs::File, io::{Read, Write}, path::Path}; const ATOMS: &'static [&'static str] = &[ "+", "-", "...", "head", "tail", "cons", "lambda", "let", "gensym" ];
rust
} impl Value for H256 { fn to_h256(&self) -> H256 { *self } fn zero() -> Self { H256::zero() } }
rust
) -> Result<(), ReplyError> { let req = self.request(request, ctx, MessageIdVs::DestroyVolume); let response = self.client().destroy_volume(req).await?.into_inner(); match response.error { None => Ok(()), Some(err) => Err(err.into()), } }
rust
/// Get the current key length (number of characters) fn key_len(&self) -> usize { if let Some(define) = self.define { let i = define.indent * self.indent_spaces.unwrap_or(0); let k = define.key.chars().count(); i + k } else { 0 }
rust
pub use self::{create::*, find::*, project::*}; mod create; mod find; mod project;
rust
+44 1234 45665 +49 (1234) 44444 +44 12344 55538"; let re = Regex::new(r"(\+[\d]{1,4})").unwrap(); let prefixes = re .captures_iter(&phone_numbers) .map(|match_| match_.get(1)) .filter(|m| m.is_some()) .fold(RefCell::new(counter), |c, prefix| {
rust
} } } #[derive(Switch, Clone, Debug)] pub enum AppRoute { #[to = "/posts/new"] NewPost, #[to = "/posts/update/{id}"]
rust
let mut flash = device.FLASH.constrain(); let mut rcc = device.RCC.constrain(); let mut _afio = device.AFIO.constrain(&mut rcc.apb2); let _clocks = rcc .cfgr .use_hse(8.mhz()) .sysclk(72.mhz()) .pclk1(36.mhz()) .freeze(&mut flash.acr); // Setup ADC (we're using ADC1 for this example since we're reding PB0) let adc1 = adc::Adc::adc1(device.ADC1, &mut rcc.apb2, _clocks); // Setup GPIOB (so we can access the ADC via PB0)