file_name
large_stringlengths
4
69
prefix
large_stringlengths
0
26.7k
suffix
large_stringlengths
0
24.8k
middle
large_stringlengths
0
2.12k
fim_type
large_stringclasses
4 values
script.rs
use std::fmt; use std::str::FromStr; use super::lang_mapping; use crate::error::Error; use crate::Lang; #[cfg(feature = "enum-map")] use enum_map::Enum; /// Represents a writing system (Latin, Cyrillic, Arabic, etc). #[cfg_attr(feature = "enum-map", derive(Enum))] #[derive(PartialEq, Eq, Debug, Clone, Copy)] pub enu...
(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.name()) } } impl FromStr for Script { type Err = Error; fn from_str(s: &str) -> Result<Self, Self::Err> { match s.to_lowercase().trim() { "latin" => Ok(Script::Latin), "cyrillic" => Ok(Script::Cyr...
fmt
identifier_name
script.rs
use std::fmt; use std::str::FromStr; use super::lang_mapping; use crate::error::Error; use crate::Lang; #[cfg(feature = "enum-map")] use enum_map::Enum; /// Represents a writing system (Latin, Cyrillic, Arabic, etc). #[cfg_attr(feature = "enum-map", derive(Enum))] #[derive(PartialEq, Eq, Debug, Clone, Copy)] pub enu...
"mandarin" => Ok(Script::Mandarin), "hangul" => Ok(Script::Hangul), "greek" => Ok(Script::Greek), "kannada" => Ok(Script::Kannada), "tamil" => Ok(Script::Tamil), "thai" => Ok(Script::Thai), "gujarati" => Ok(Script::Gujarati), ...
"katakana" => Ok(Script::Katakana), "ethiopic" => Ok(Script::Ethiopic), "hebrew" => Ok(Script::Hebrew), "bengali" => Ok(Script::Bengali), "georgian" => Ok(Script::Georgian),
random_line_split
contact_ball_ball.rs
use crate::math::{Point, Vector}; use crate::query::Contact; use crate::shape::Ball; use na::{self, RealField, Unit}; /// Contact between balls. #[inline] pub fn contact_ball_ball<N: RealField>( center1: &Point<N>, b1: &Ball<N>, center2: &Point<N>, b2: &Ball<N>, prediction: N, ) -> Option<Contact<N...
; Some(Contact::new( *center1 + *normal * r1, *center2 + *normal * (-r2), normal, sum_radius - distance_squared.sqrt(), )) } else { None } }
{ Vector::x_axis() }
conditional_block
contact_ball_ball.rs
use crate::math::{Point, Vector}; use crate::query::Contact; use crate::shape::Ball; use na::{self, RealField, Unit}; /// Contact between balls. #[inline] pub fn contact_ball_ball<N: RealField>( center1: &Point<N>, b1: &Ball<N>, center2: &Point<N>, b2: &Ball<N>, prediction: N, ) -> Option<Contact<N...
)) } else { None } }
{ let r1 = b1.radius; let r2 = b2.radius; let delta_pos = *center2 - *center1; let distance_squared = delta_pos.norm_squared(); let sum_radius = r1 + r2; let sum_radius_with_error = sum_radius + prediction; if distance_squared < sum_radius_with_error * sum_radius_with_error { let no...
identifier_body
contact_ball_ball.rs
use crate::math::{Point, Vector}; use crate::query::Contact; use crate::shape::Ball; use na::{self, RealField, Unit}; /// Contact between balls. #[inline] pub fn
<N: RealField>( center1: &Point<N>, b1: &Ball<N>, center2: &Point<N>, b2: &Ball<N>, prediction: N, ) -> Option<Contact<N>> { let r1 = b1.radius; let r2 = b2.radius; let delta_pos = *center2 - *center1; let distance_squared = delta_pos.norm_squared(); let sum_radius = r1 + r2; ...
contact_ball_ball
identifier_name
contact_ball_ball.rs
use crate::math::{Point, Vector}; use crate::query::Contact; use crate::shape::Ball; use na::{self, RealField, Unit}; /// Contact between balls. #[inline] pub fn contact_ball_ball<N: RealField>( center1: &Point<N>, b1: &Ball<N>, center2: &Point<N>, b2: &Ball<N>, prediction: N, ) -> Option<Contact<N...
let r2 = b2.radius; let delta_pos = *center2 - *center1; let distance_squared = delta_pos.norm_squared(); let sum_radius = r1 + r2; let sum_radius_with_error = sum_radius + prediction; if distance_squared < sum_radius_with_error * sum_radius_with_error { let normal = if!distance_squared...
let r1 = b1.radius;
random_line_split
tests.rs
extern crate rustsocks; use rustsocks::{Socks4, Socks4a, Socks5}; use std::io::net::ip::IpAddr; static SOCKS_HOST : &'static str = "127.0.0.1"; static SOCKS_PORT : u16 = 9150; static GET_REQUEST : &'static str = "GET /404 HTTP/1.1\nHost: www.google.com\nConnection: close\n\n"; #[test] fn socks4a() { let mu...
{ let mut socks = Socks5::new(SOCKS_HOST, SOCKS_PORT); let addr = from_str::<IpAddr>("74.125.230.65").unwrap(); let mut stream = socks.connect(addr, 80); let _ = stream.write_str(GET_REQUEST); println!("{}", stream.read_to_string().unwrap()); }
identifier_body
tests.rs
extern crate rustsocks; use rustsocks::{Socks4, Socks4a, Socks5}; use std::io::net::ip::IpAddr; static SOCKS_HOST : &'static str = "127.0.0.1"; static SOCKS_PORT : u16 = 9150; static GET_REQUEST : &'static str = "GET /404 HTTP/1.1\nHost: www.google.com\nConnection: close\n\n"; #[test] fn socks4a() { let mu...
() { let mut socks = Socks5::new(SOCKS_HOST, SOCKS_PORT); let mut stream = socks.connect("www.google.com", 80); let _ = stream.write_str(GET_REQUEST); println!("{}", stream.read_to_string().unwrap()); } #[test] fn socks5_ipv4() { let mut socks = Socks5::new(SOCKS_HOST, SOCKS_PORT); let addr = ...
socks5_domain
identifier_name
tests.rs
extern crate rustsocks; use rustsocks::{Socks4, Socks4a, Socks5}; use std::io::net::ip::IpAddr; static SOCKS_HOST : &'static str = "127.0.0.1"; static SOCKS_PORT : u16 = 9150; static GET_REQUEST : &'static str = "GET /404 HTTP/1.1\nHost: www.google.com\nConnection: close\n\n"; #[test] fn socks4a() { let mu...
println!("{}", stream.read_to_string().unwrap()); }
let _ = stream.write_str(GET_REQUEST);
random_line_split
main.rs
use { futures::{ future::{BoxFuture, FutureExt}, task::{waker_ref, ArcWake}, }, std::{ future::Future, sync::mpsc::{sync_channel, Receiver, SyncSender}, sync::{Arc, Mutex}, task::{Context, Poll}, time::Duration, }, }; struct Task { future: Mut...
}
{ let (sender, receiver) = std::sync::mpsc::channel::<i32>(); let s1 = sender.clone(); std::thread::spawn(move || { std::thread::sleep(std::time::Duration::from_millis(1000)); println!("sent!"); s1.send(1).unwrap(); }); let receiver = FutureReceiver(Arc::from(Mutex::from(re...
identifier_body
main.rs
use { futures::{ future::{BoxFuture, FutureExt}, task::{waker_ref, ArcWake}, }, std::{ future::Future, sync::mpsc::{sync_channel, Receiver, SyncSender}, sync::{Arc, Mutex}, task::{Context, Poll}, time::Duration, }, }; struct Task { future: Mut...
( self: std::pin::Pin<&mut Self>, ctx: &mut std::task::Context<'_>, ) -> std::task::Poll<T> { println!("FutureReceiver.poll.1"); let ch = self.0.lock().unwrap(); let mut iter = ch.try_iter(); match iter.next() { Some(v) => std::task::Poll::Ready(v), ...
poll
identifier_name
main.rs
use { futures::{ future::{BoxFuture, FutureExt}, task::{waker_ref, ArcWake}, }, std::{ future::Future, sync::mpsc::{sync_channel, Receiver, SyncSender}, sync::{Arc, Mutex}, task::{Context, Poll}, time::Duration, }, }; struct Task { future: Mut...
}; let exec = new_executor_and_spawner(); exec.spawn(f); exec.run(); }
receiver.await; println!("done!");
random_line_split
cg.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use darling::{FromDeriveInput, FromField, FromVariant}; use proc_macro2::{Span, TokenStream}; use quote::TokenStr...
<F>(ty: &Type, params: &[&TypeParam], f: &mut F) -> Type where F: FnMut(&Ident) -> Type, { match *ty { Type::Slice(ref inner) => Type::from(TypeSlice { elem: Box::new(map_type_params(&inner.elem, params, f)), ..inner.clone() }), Type::Array(ref inner) => { ...
map_type_params
identifier_name
cg.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use darling::{FromDeriveInput, FromField, FromVariant}; use proc_macro2::{Span, TokenStream}; use quote::TokenStr...
} Type::from(TypePath { qself: None, path: map_type_params_in_path(path, params, f), }) }, Type::Path(TypePath { ref qself, ref path, }) => Type::from(TypePath { qself: qself.as_ref().map(|qs...
{ return f(ident); }
conditional_block
cg.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use darling::{FromDeriveInput, FromField, FromVariant}; use proc_macro2::{Span, TokenStream}; use quote::TokenStr...
ty, ); let ident = match path_to_ident(path) { Some(i) => i, None => panic!("Unhanded complex where type path: {:?}", path), }; if generics.type_params().any(|param| param.ident == *ident) { extra_bounds.push(ty.clone()); } } ...
assert!( ty.lifetimes.is_none(), "Unhanded complex lifetime bound: {:?}",
random_line_split
cg.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use darling::{FromDeriveInput, FromField, FromVariant}; use proc_macro2::{Span, TokenStream}; use quote::TokenStr...
pub fn parse_variant_attrs<A>(variant: &Variant) -> A where A: FromVariant, { match A::from_variant(variant) { Ok(attrs) => attrs, Err(e) => panic!("failed to parse variant attributes: {}", e), } } pub fn ref_pattern<'a>( variant: &'a VariantInfo, prefix: &str, ) -> (TokenStream, ...
{ let v = Variant { ident: variant.ident.clone(), attrs: variant.attrs.to_vec(), fields: variant.fields.clone(), discriminant: variant.discriminant.clone(), }; parse_variant_attrs(&v) }
identifier_body
traits.rs
use image::{imageops, DynamicImage, GenericImageView, GrayImage, ImageBuffer, Pixel}; use std::borrow::Cow; use std::ops; /// Interface for types used for storing hash data. /// /// This is implemented for `Vec<u8>`, `Box<[u8]>` and arrays that are multiples/combinations of /// useful x86 bytewise SIMD register width...
default fn foreach_pixel8<F>(&self, mut foreach: F) where F: FnMut(u32, u32, &[u8]) { self.enumerate_pixels().for_each(|(x, y, px)| foreach(x, y, px.channels())) } } impl<P:'static> DiffImage for ImageBuffer<P, Vec<u8>> where P: Pixel<Subpixel = u8> { fn diff_inplace(&mut self, other: &Self) { ...
{ imageops::blur(self, sigma) }
identifier_body
traits.rs
use image::{imageops, DynamicImage, GenericImageView, GrayImage, ImageBuffer, Pixel}; use std::borrow::Cow; use std::ops; /// Interface for types used for storing hash data. /// /// This is implemented for `Vec<u8>`, `Box<[u8]>` and arrays that are multiples/combinations of /// useful x86 bytewise SIMD register width...
else { upper / 8 + 1}) ) } } pub(crate) trait BitSet: HashBytes { fn from_bools<I: Iterator<Item = bool>>(iter: I) -> Self where Self: Sized { Self::from_iter(BoolsToBytes { iter }) } fn hamming(&self, other: &Self) -> u32 { self.as_slice().iter().zip(other.as_slice()).map(|(l...
{ upper / 8 }
conditional_block
traits.rs
use image::{imageops, DynamicImage, GenericImageView, GrayImage, ImageBuffer, Pixel}; use std::borrow::Cow; use std::ops; /// Interface for types used for storing hash data. /// /// This is implemented for `Vec<u8>`, `Box<[u8]>` and arrays that are multiples/combinations of /// useful x86 bytewise SIMD register width...
impl HashBytes for [u8; $n] { fn from_iter<I: Iterator<Item=u8>>(mut iter: I) -> Self { // optimizer should eliminate this zeroing let mut out = [0; $n]; for (src, dest) in iter.by_ref().zip(out.as_mut()) { *dest = src; ...
fn as_slice(&self) -> &[u8] { self } } macro_rules! hash_bytes_array { ($($n:expr),*) => {$(
random_line_split
traits.rs
use image::{imageops, DynamicImage, GenericImageView, GrayImage, ImageBuffer, Pixel}; use std::borrow::Cow; use std::ops; /// Interface for types used for storing hash data. /// /// This is implemented for `Vec<u8>`, `Box<[u8]>` and arrays that are multiples/combinations of /// useful x86 bytewise SIMD register width...
(&self, sigma: f32) -> Self::Buf { imageops::blur(self, sigma) } fn foreach_pixel8<F>(&self, mut foreach: F) where F: FnMut(u32, u32, &[u8]) { self.pixels().for_each(|(x, y, px)| foreach(x, y, px.channels())) } } #[cfg(feature = "nightly")] impl Image for GrayImage { // type Buf = GrayImage; ...
blur
identifier_name
time.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Specified time values. use cssparser::{Parser, Token}; use parser::{Parse, ParserContext}; use std::fmt::{sel...
{ seconds: CSSFloat, unit: TimeUnit, was_calc: bool, } /// A time unit. #[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq)] pub enum TimeUnit { /// `s` Second, /// `ms` Millisecond, } impl Time { /// Returns a time value that represents `seconds` seconds. pub fn from_seconds...
ime
identifier_name
time.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Specified time values. use cssparser::{Parser, Token}; use parser::{Parse, ParserContext}; use std::fmt::{sel...
unit: TimeUnit::Second, was_calc: false, } } /// Returns `0s`. pub fn zero() -> Self { Self::from_seconds(0.0) } /// Returns the time in fractional seconds. pub fn seconds(self) -> CSSFloat { self.seconds } /// Parses a time according to...
/// Returns a time value that represents `seconds` seconds. pub fn from_seconds(seconds: CSSFloat) -> Self { Time { seconds,
random_line_split
time.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Specified time values. use cssparser::{Parser, Token}; use parser::{Parse, ParserContext}; use std::fmt::{sel...
/// Returns a `Time` value from a CSS `calc()` expression. pub fn from_calc(seconds: CSSFloat) -> Self { Time { seconds: seconds, unit: TimeUnit::Second, was_calc: true, } } fn parse_with_clamping_mode<'i, 't>( context: &ParserContext, ...
let (seconds, unit) = match_ignore_ascii_case! { unit, "s" => (value, TimeUnit::Second), "ms" => (value / 1000.0, TimeUnit::Millisecond), _ => return Err(()) }; Ok(Time { seconds, unit, was_calc, }) }
identifier_body
time.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Specified time values. use cssparser::{Parser, Token}; use parser::{Parse, ParserContext}; use std::fmt::{sel...
match self.unit { TimeUnit::Second => { self.seconds.to_css(dest)?; dest.write_str("s")?; }, TimeUnit::Millisecond => { (self.seconds * 1000.).to_css(dest)?; dest.write_str("ms")?; }, } ...
dest.write_str("calc(")?; }
conditional_block
main.rs
use std::fs; use std::io::prelude::*; use std::net::TcpListener; use std::net::TcpStream; // ANCHOR: here use std::thread; use std::time::Duration; // --snip-- // ANCHOR_END: here fn main() { let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); for stream in listener.incoming() { let stream = ...
else { ("HTTP/1.1 404 NOT FOUND", "404.html") }; // --snip-- // ANCHOR_END: here let contents = fs::read_to_string(filename).unwrap(); let response = format!( "{}\r\nContent-Length: {}\r\n\r\n{}", status_line, contents.len(), contents ); stream.wr...
{ thread::sleep(Duration::from_secs(5)); ("HTTP/1.1 200 OK", "hello.html") }
conditional_block
main.rs
use std::fs; use std::io::prelude::*; use std::net::TcpListener; use std::net::TcpStream; // ANCHOR: here use std::thread; use std::time::Duration; // --snip-- // ANCHOR_END: here fn main() { let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); for stream in listener.incoming() { let stream = ...
// ANCHOR_END: here let contents = fs::read_to_string(filename).unwrap(); let response = format!( "{}\r\nContent-Length: {}\r\n\r\n{}", status_line, contents.len(), contents ); stream.write(response.as_bytes()).unwrap(); stream.flush().unwrap(); // ANCHOR: ...
random_line_split
main.rs
use std::fs; use std::io::prelude::*; use std::net::TcpListener; use std::net::TcpStream; // ANCHOR: here use std::thread; use std::time::Duration; // --snip-- // ANCHOR_END: here fn main() { let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); for stream in listener.incoming() { let stream = ...
// --snip-- // ANCHOR_END: here let contents = fs::read_to_string(filename).unwrap(); let response = format!( "{}\r\nContent-Length: {}\r\n\r\n{}", status_line, contents.len(), contents ); stream.write(response.as_bytes()).unwrap(); stream.flush().unwrap();...
{ // --snip-- // ANCHOR_END: here let mut buffer = [0; 1024]; stream.read(&mut buffer).unwrap(); // ANCHOR: here let get = b"GET / HTTP/1.1\r\n"; let sleep = b"GET /sleep HTTP/1.1\r\n"; let (status_line, filename) = if buffer.starts_with(get) { ("HTTP/1.1 200 OK", "hello.html"...
identifier_body
main.rs
use std::fs; use std::io::prelude::*; use std::net::TcpListener; use std::net::TcpStream; // ANCHOR: here use std::thread; use std::time::Duration; // --snip-- // ANCHOR_END: here fn main() { let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); for stream in listener.incoming() { let stream = ...
(mut stream: TcpStream) { // --snip-- // ANCHOR_END: here let mut buffer = [0; 1024]; stream.read(&mut buffer).unwrap(); // ANCHOR: here let get = b"GET / HTTP/1.1\r\n"; let sleep = b"GET /sleep HTTP/1.1\r\n"; let (status_line, filename) = if buffer.starts_with(get) { ("HTTP/1...
handle_connection
identifier_name
command.rs
// Copyright 2014 The Gfx-rs Developers. // // 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 ag...
} /// Returns the mapped buffers that The GPU will read from pub fn mapped_reads(&self) -> AccessInfoBuffers<R> { self.mapped_reads.iter() } /// Returns the mapped buffers that The GPU will write to pub fn mapped_writes(&self) -> AccessInfoBuffers<R> { self.mapped_writes.iter(...
{ self.mapped_writes.insert(buffer.clone()); }
conditional_block
command.rs
// Copyright 2014 The Gfx-rs Developers. // // 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 ag...
fn generate_mipmap(&mut self, R::ShaderResourceView); /// Clear color target fn clear_color(&mut self, R::RenderTargetView, ClearColor); fn clear_depth_stencil(&mut self, R::DepthStencilView, Option<target::Depth>, Option<target::Stencil>); /// Draw a primitive fn call...
random_line_split
command.rs
// Copyright 2014 The Gfx-rs Developers. // // 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 ag...
/// Returns the mapped buffers that The GPU will write to pub fn mapped_writes(&self) -> AccessInfoBuffers<R> { self.mapped_writes.iter() } /// Is there any mapped buffer reads? pub fn has_mapped_reads(&self) -> bool { !self.mapped_reads.is_empty() } /// Is there any mappe...
{ self.mapped_reads.iter() }
identifier_body
command.rs
// Copyright 2014 The Gfx-rs Developers. // // 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 ag...
(&self) -> bool { !self.mapped_writes.is_empty() } /// Takes all the accesses necessary for submission pub fn take_accesses(&self) -> SubmissionResult<AccessGuard<R>> { for buffer in self.mapped_reads().chain(self.mapped_writes()) { unsafe { if!buffer.mapping().un...
has_mapped_writes
identifier_name
transmission.rs
//! A minimal implementation of rpc client for Tranmission. use reqwest::header::HeaderValue; use reqwest::{self, Client, IntoUrl, StatusCode, Url}; use serde_json::Value; use std::{fmt, result}; pub type Result<T> = result::Result<T, failure::Error>;
#[fail(display = "failed to get SessionId from header")] SessionIdNotFound, #[fail(display = "unexpected status code: {}", status)] UnexpectedStatus { status: reqwest::StatusCode }, #[fail(display = "the transmission server responded with an error: {}", error)] ResponseError { error: String }, }...
#[derive(Debug, Fail)] enum TransmissionError {
random_line_split
transmission.rs
//! A minimal implementation of rpc client for Tranmission. use reqwest::header::HeaderValue; use reqwest::{self, Client, IntoUrl, StatusCode, Url}; use serde_json::Value; use std::{fmt, result}; pub type Result<T> = result::Result<T, failure::Error>; #[derive(Debug, Fail)] enum TransmissionError { #[fail(display...
; let url = url.into_url()?; let http_client = Client::new(); let sid = http_client .get(url.clone()) .send()? .headers() .get("X-Transmission-Session-Id") .ok_or(TransmissionError::SessionIdNotFound)? .clone(); Ok(Self { ...
{ None }
conditional_block
transmission.rs
//! A minimal implementation of rpc client for Tranmission. use reqwest::header::HeaderValue; use reqwest::{self, Client, IntoUrl, StatusCode, Url}; use serde_json::Value; use std::{fmt, result}; pub type Result<T> = result::Result<T, failure::Error>; #[derive(Debug, Fail)] enum TransmissionError { #[fail(display...
<U>(url: U, user: Option<(String, String)>) -> Result<Self> where U: IntoUrl, { let user = if let Some((n, p)) = user { Some(User { name: n, password: p, }) } else { None }; let url = url.into_url()?; ...
new
identifier_name
main.rs
// Author: Alex Chernyakhovsky (achernya@mit.edu) // TODO(achernya): Per the documentation on doc.rust-lang.org, std::io // is not yet ready, so use old_io until 1.0-final. #![feature(old_io)] // std::env contains a lot of nice functions that otherwise would // require std::os to use; std::os has lots of deprecated f...
let directory = dir.unwrap(); let result = env::set_current_dir(&directory); match result { Err(err) => { println_stderr!("cd: {}: {}", directory.display(), err); }, _ => {}, } } fn pwd() { let p = env::current_dir().unwrap_or(Path::new("/")); println!("{}", ...
}; if dir.is_none() { println_stderr!("cd: no directory to change to"); return; }
random_line_split
main.rs
// Author: Alex Chernyakhovsky (achernya@mit.edu) // TODO(achernya): Per the documentation on doc.rust-lang.org, std::io // is not yet ready, so use old_io until 1.0-final. #![feature(old_io)] // std::env contains a lot of nice functions that otherwise would // require std::os to use; std::os has lots of deprecated f...
(command: &Vec<&str>) -> bool { match command[0] { "cd" => cd(command), "pwd" => pwd(), _ => return false, } true } fn cd(command: &Vec<&str>) { // cd is the "change directory" command. It can take either 0 or 1 // arguments. If given no arguments, then the $HOME directory i...
builtins
identifier_name
main.rs
// Author: Alex Chernyakhovsky (achernya@mit.edu) // TODO(achernya): Per the documentation on doc.rust-lang.org, std::io // is not yet ready, so use old_io until 1.0-final. #![feature(old_io)] // std::env contains a lot of nice functions that otherwise would // require std::os to use; std::os has lots of deprecated f...
fn builtins(command: &Vec<&str>) -> bool { match command[0] { "cd" => cd(command), "pwd" => pwd(), _ => return false, } true } fn cd(command: &Vec<&str>) { // cd is the "change directory" command. It can take either 0 or 1 // arguments. If given no arguments, then the $HOM...
{ // Clean up the string by removing the newline at the end let expr = user_expr.trim_matches('\n'); let components: Vec<&str> = expr.split(' ').collect(); if builtins(&components) { return; } }
identifier_body
file_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use about_loader; use mime_classifier::MIMEClassifier; use mime_guess::guess_mime_type; use net_traits::ProgressMs...
cancel_listener: CancellationListener) { assert!(&*load_data.url.scheme == "file"); spawn_named("file_loader".to_owned(), move || { let file_path: Result<PathBuf, ()> = load_data.url.to_file_path(); match file_path { Ok(file_path) => { match File::open(...
random_line_split
file_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use about_loader; use mime_classifier::MIMEClassifier; use mime_guess::guess_mime_type; use net_traits::ProgressMs...
pub fn factory(load_data: LoadData, senders: LoadConsumer, classifier: Arc<MIMEClassifier>, cancel_listener: CancellationListener) { assert!(&*load_data.url.scheme == "file"); spawn_named("file_loader".to_owned(), move || { let file_path: Result<PathBuf, ()...
{ let mut metadata = Metadata::default(load_data.url); let mime_type = guess_mime_type(file_path.as_path()); metadata.set_content_type(Some(&mime_type)); return start_sending_sniffed_opt(senders, metadata, classifier, buf, load_data.context); }
identifier_body
file_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use about_loader; use mime_classifier::MIMEClassifier; use mime_guess::guess_mime_type; use net_traits::ProgressMs...
(reader: &mut File, progress_chan: &ProgressSender, cancel_listener: &CancellationListener) -> Result<LoadResult, String> { loop { if cancel_listener.is_cancelled() { let _ = progress_chan.send(Done(Err("load cancelled".to_owned()))); return Ok(LoadResult::Cancelled); ...
read_all
identifier_name
gpio.rs
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 use anyhow::Result; use erased_serde::Serialize; use std::any::Any; use structopt::StructOpt; use opentitanlib::app::command::CommandDispatch; use opentitanlib::app::Tr...
Read(GpioRead), Write(GpioWrite), SetMode(GpioSetMode), SetPullMode(GpioSetPullMode), }
} /// Commands for manipulating GPIO pins. #[derive(Debug, StructOpt, CommandDispatch)] pub enum GpioCommand {
random_line_split
gpio.rs
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 use anyhow::Result; use erased_serde::Serialize; use std::any::Any; use structopt::StructOpt; use opentitanlib::app::command::CommandDispatch; use opentitanlib::app::Tr...
{ #[structopt(name = "PIN", help = "The GPIO pin to modify")] pub pin: String, #[structopt( name = "PULLMODE", possible_values = &PullMode::variants(), case_insensitive=true, help = "The weak pull mode of the pin" )] pub pull_mode: PullMode, } impl CommandDispatch f...
GpioSetPullMode
identifier_name
mod.rs
pub use self::stack::Stack; pub use self::word::Word; use memory; use memory::MemoryMap; use self::opcode::{Opcode, PartialAddr, IWord}; mod alu; mod opcode; mod stack; mod word; pub struct CPU { p: Word, i: IWord, a: Word, b: Word, dat: Stack, ret: Stack, mem: MemoryMap } impl CPU { ...
(&mut self, op: u8, increment: bool) { let (reg, reg_op) = match (op, increment) { (3, true) => (&mut self.p, 1), // @p (7, true) => (&mut self.p, 2), //!p (0...3, _) => (&mut self.a, op & 3), // a @! a! (4...7, _) => (&mut self.b, op & 3), // b @b!b b...
exec_register
identifier_name
mod.rs
pub use self::stack::Stack; pub use self::word::Word; use memory; use memory::MemoryMap; use self::opcode::{Opcode, PartialAddr, IWord}; mod alu; mod opcode; mod stack; mod word; pub struct CPU { p: Word, i: IWord, a: Word, b: Word, dat: Stack, ret: Stack, mem: MemoryMap } impl CPU { ...
fn exec_register(&mut self, op: u8, increment: bool) { let (reg, reg_op) = match (op, increment) { (3, true) => (&mut self.p, 1), // @p (7, true) => (&mut self.p, 2), //!p (0...3, _) => (&mut self.a, op & 3), // a @! a! (4...7, _) => (&mut self.b...
{ use self::opcode::Opcode::*; match opcode { Unary(op) => alu::unary(op, &mut self.dat), Binary(op) => alu::binary(op, &mut self.dat, &mut self.ret), Stack(op) => alu::stack(op, &mut self.dat, &mut self.ret), Register(op, inc) => self.exec_register(op...
identifier_body
mod.rs
pub use self::stack::Stack; pub use self::word::Word; use memory; use memory::MemoryMap; use self::opcode::{Opcode, PartialAddr, IWord}; mod alu; mod opcode; mod stack; mod word; pub struct CPU { p: Word, i: IWord, a: Word, b: Word, dat: Stack, ret: Stack, mem: MemoryMap } impl CPU { ...
} } fn exec_register(&mut self, op: u8, increment: bool) { let (reg, reg_op) = match (op, increment) { (3, true) => (&mut self.p, 1), // @p (7, true) => (&mut self.p, 2), //!p (0...3, _) => (&mut self.a, op & 3), // a @! a! (4...7, _) ...
Stack(op) => alu::stack(op, &mut self.dat, &mut self.ret), Register(op, inc) => self.exec_register(op, inc), Control(op, addr) => self.exec_control(op, addr)
random_line_split
fake_browser.rs
extern crate cookie; use self::cookie::CookieJar; extern crate regex; use self::regex::Regex; extern crate hyper; use self::hyper::client::{Client, RedirectPolicy}; use self::hyper::Url; use std::io::prelude::*; use std::error::Error; use std::fmt::{Display, Formatter}; use api::CallError; /// Function that return...
/// The function implement login process for user without browser /// _Warning: use the thing careful to privacy and privacy policy of vk.com_ pub fn fake_browser(login: String, password: String, url: String) -> Result<(String, u64, u64),CallError> { use std::thread::sleep_ms; use self::hyper::header::{Cookie,L...
random_line_split
fake_browser.rs
extern crate cookie; use self::cookie::CookieJar; extern crate regex; use self::regex::Regex; extern crate hyper; use self::hyper::client::{Client, RedirectPolicy}; use self::hyper::Url; use std::io::prelude::*; use std::error::Error; use std::fmt::{Display, Formatter}; use api::CallError; /// Function that return...
(client_id: u64, scope: String, version: String, redirect: String) -> String { format!("https://oauth.vk.com/authorize?client_id={}&scope={}&redirect_uri={}&display=mobile&v={}&response_type=token", client_id, scope, redirect, version) } use std::collections::HashMap; // Get params send by hidden fields on auth pa...
authorization_client_uri
identifier_name
fake_browser.rs
extern crate cookie; use self::cookie::CookieJar; extern crate regex; use self::regex::Regex; extern crate hyper; use self::hyper::client::{Client, RedirectPolicy}; use self::hyper::Url; use std::io::prelude::*; use std::error::Error; use std::fmt::{Display, Formatter}; use api::CallError; /// Function that return...
// Get access token and other data from response URL fn get_token(u: &Url) -> (String, u64, u64) { let reg = Regex::new("access_token=([a-f0-9]+)&expires_in=([0-9]+)&user_id=([0-9]+)").unwrap(); let mut token: String = String::new(); let mut expires: u64 = 0u64; let mut user_id: u64 = 0u64; for cap...
{ let reg = Regex::new("action=\"([a-z:/?=&.0-9]*)\"").unwrap(); match reg.captures_iter(&*s).next() { Some(x) => x.at(1).unwrap_or(""), None => "" }.into() }
identifier_body
gen.rs
use std::rand::Rng; use std::rand; fn main()
println!("{}", v.as_slice()); // `shuffle` shuffles a mutable slice in place rng.shuffle(v.as_mut_slice()); println!("shuffle previous slice"); println!("{}", v.as_slice()); // `choose` will sample an slice *with* replacement // i.e. the same element can be chosen more than one time pr...
{ // create a task-local Random Number Generator let mut rng = rand::task_rng(); // the `gen` methods generates values in the full range of each type using // a uniform distribution println!("randomly generate some values for different primitive types"); println!("u8: {}", rng.gen::<u8>()); ...
identifier_body
gen.rs
use std::rand::Rng; use std::rand; fn
() { // create a task-local Random Number Generator let mut rng = rand::task_rng(); // the `gen` methods generates values in the full range of each type using // a uniform distribution println!("randomly generate some values for different primitive types"); println!("u8: {}", rng.gen::<u8>()); ...
main
identifier_name
gen.rs
use std::rand::Rng; use std::rand; fn main() { // create a task-local Random Number Generator let mut rng = rand::task_rng(); // the `gen` methods generates values in the full range of each type using // a uniform distribution println!("randomly generate some values for different primitive types")...
println!("f32: {}", rng.gen::<f32>()); println!("f64: {}", rng.gen::<f64>()); // `gen_iter` returns an iterator that yields a infinite number of randomly // generated numbers let mut v: Vec<u8> = rng.gen_iter::<u8>().take(10).collect(); println!("10 randomly generated u8 values"); println!...
println!("u16: {}", rng.gen::<u16>()); println!("i16: {}", rng.gen::<i16>()); // except for floats which get generated in the range [0, 1>
random_line_split
q_box.rs
use crate::{QObject, QPtr}; use cpp_core::{ CastFrom, CastInto, CppBox, CppDeletable, DynamicCast, Ptr, Ref, StaticDowncast, StaticUpcast, }; use std::ops::Deref; use std::{fmt, mem}; /// An owning pointer for `QObject`-based objects. /// /// `QBox` will delete its object on drop if it has no parent. If the object...
/// Returns the content as a const `Ptr`. /// /// ### Safety /// /// See type level documentation. pub unsafe fn as_ptr(&self) -> Ptr<T> { self.0.as_ptr() } /// Returns the content as a raw const pointer. /// /// ### Safety /// /// See type level documentation....
{ self.0.is_null() }
identifier_body
q_box.rs
use crate::{QObject, QPtr}; use cpp_core::{ CastFrom, CastInto, CppBox, CppDeletable, DynamicCast, Ptr, Ref, StaticDowncast, StaticUpcast, }; use std::ops::Deref; use std::{fmt, mem}; /// An owning pointer for `QObject`-based objects. /// /// `QBox` will delete its object on drop if it has no parent. If the object...
} } }
{ T::delete(&*ptr.as_raw_ptr()); }
conditional_block
q_box.rs
use crate::{QObject, QPtr}; use cpp_core::{ CastFrom, CastInto, CppBox, CppDeletable, DynamicCast, Ptr, Ref, StaticDowncast, StaticUpcast, }; use std::ops::Deref; use std::{fmt, mem}; /// An owning pointer for `QObject`-based objects. /// /// `QBox` will delete its object on drop if it has no parent. If the object...
(&mut self) { unsafe { let ptr = self.as_ptr(); if!ptr.is_null() && ptr.static_upcast().parent().is_null() { T::delete(&*ptr.as_raw_ptr()); } } } }
drop
identifier_name
q_box.rs
use crate::{QObject, QPtr}; use cpp_core::{ CastFrom, CastInto, CppBox, CppDeletable, DynamicCast, Ptr, Ref, StaticDowncast, StaticUpcast, }; use std::ops::Deref; use std::{fmt, mem}; /// An owning pointer for `QObject`-based objects. /// /// `QBox` will delete its object on drop if it has no parent. If the object...
/// Returns the content as a raw const pointer. /// /// ### Safety /// /// See type level documentation. pub unsafe fn as_raw_ptr(&self) -> *const T { self.0.as_raw_ptr() } /// Returns the content as a raw mutable pointer. /// /// ### Safety /// /// See type leve...
pub unsafe fn as_ptr(&self) -> Ptr<T> { self.0.as_ptr() }
random_line_split
platform.rs
/* * Copyright 2017 Sreejith Krishnan R * * 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...
pub fn new_canvas(&self, width: f32, height: f32) -> Canvas { Canvas::new(width.max(1.), height.max(1.), self.ruler.get_sk_typeface()) } } impl ::platform::Platform for Platform { fn get_text_ruler(&self, size: f32) -> &TextRuler { self.ruler.set_size(size); &s...
{ Platform { ruler: SnapshotRuler::new(typeface, 0) } }
identifier_body
platform.rs
/* * Copyright 2017 Sreejith Krishnan R * * 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...
(&self, size: f32) -> &TextRuler { self.ruler.set_size(size); &self.ruler } fn get_math_ruler(&self, size: f32) -> &MathRuler { self.ruler.set_size(size); &self.ruler } fn px_to_du(&self, px: f32) -> f32 { px } fn sp_to_du(&self, sp: f32) -> f32 { ...
get_text_ruler
identifier_name
platform.rs
/* * Copyright 2017 Sreejith Krishnan R * * 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 *
* See the License for the specific language governing permissions and * limitations under the License. */ use std::any::Any; use ::paint::{TextRuler, MathRuler}; use super::ruler::Ruler as SnapshotRuler; use super::canvas::Canvas; pub struct Platform { ruler: SnapshotRuler, } impl Platform { pub fn new(ty...
* 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.
random_line_split
lib.rs
/// ""abc"", ""abc" Str { terminated: bool }, /// "b"abc"", "b"abc" ByteStr { terminated: bool }, /// "r"abc"", "r#"abc"#", "r####"ab"###"c"####", "r#"a" RawStr { n_hashes: u16, err: Option<RawStrError> }, /// "br"abc"", "br#"abc"#", "br####"ab"###"c"####", "br#"a" RawByteStr { n_hashes...
mut self, first_digit: char) -> LiteralKind { debug_assert!('0' <= self.prev() && self.prev() <= '9'); let mut base = Base::Decimal; if first_digit == '0' { // Attempt to parse encoding base. let has_digits = match self.first() { 'b' => { ...
mber(&
identifier_name
lib.rs
Whitespace | TokenKind::LineComment { doc_style: None } | TokenKind::BlockComment { doc_style: None,.. } ) }); if next_non_whitespace_token!= Some(TokenKind::OpenBracket) { // No other choice than to consider this a shebang. ret...
// Bump again to skip escaped character.
random_line_split
portal.rs
use crate::compat::Mutex; use crate::screen::{Screen, ScreenBuffer}; use alloc::sync::Arc; use core::mem; use graphics_base::frame_buffer::{AsSurfaceMut, FrameBuffer}; use graphics_base::system::{DeletedIndex, System}; use graphics_base::types::Rect; use graphics_base::Result; use hecs::World; #[cfg(target_os = "rust_...
<S> { screen: Arc<Mutex<Screen<S>>>, input_state: Arc<Mutex<Option<PortalRef>>>, deleted_index: DeletedIndex<()>, } impl<S> ServerPortalSystem<S> { pub fn new(screen: Arc<Mutex<Screen<S>>>, input_state: Arc<Mutex<Option<PortalRef>>>) -> Self { ServerPortalSystem { screen, ...
ServerPortalSystem
identifier_name
portal.rs
use crate::compat::Mutex; use crate::screen::{Screen, ScreenBuffer}; use alloc::sync::Arc; use core::mem; use graphics_base::frame_buffer::{AsSurfaceMut, FrameBuffer}; use graphics_base::system::{DeletedIndex, System}; use graphics_base::types::Rect; use graphics_base::Result; use hecs::World; #[cfg(target_os = "rust_...
} *self.input_state.lock() = portals.last().map(|p| p.portal_ref.clone()); let deleted_entities = self .deleted_index .update(world.query::<()>().with::<ServerPortal>().iter()); if!deleted_entities.is_empty() || portals.iter().any(|p| p.needs_paint) { ...
{ portal.prev_pos = portal.pos; portal.needs_paint = true; }
conditional_block
portal.rs
use crate::compat::Mutex; use crate::screen::{Screen, ScreenBuffer}; use alloc::sync::Arc; use core::mem; use graphics_base::frame_buffer::{AsSurfaceMut, FrameBuffer}; use graphics_base::system::{DeletedIndex, System}; use graphics_base::types::Rect; use graphics_base::Result; use hecs::World; #[cfg(target_os = "rust_...
pub events: Rc<RefCell<VecDeque<Event>>>, } impl PartialEq for PortalRef { fn eq(&self, other: &Self) -> bool { self.portal_id == other.portal_id && Rc::ptr_eq(&self.events, &other.events) } } impl PortalRef { pub fn send_input(&self, input: EventInput) -> R...
#[derive(Clone)] pub struct PortalRef { pub portal_id: usize,
random_line_split
memory.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
(&mut self, offset: U256, slice: &[u8]) { let off = offset.low_u64() as usize; // TODO [todr] Optimize? for pos in off..off + slice.len() { self[pos] = slice[pos - off]; } } fn write(&mut self, offset: U256, value: U256) { let off = offset.low_u64() as usize...
write_slice
identifier_name
memory.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
fn read_slice(&self, init_off_u: U256, init_size_u: U256) -> &[u8] { let off = init_off_u.low_u64() as usize; let size = init_size_u.low_u64() as usize; if!is_valid_range(off, size) { &self[0..0] } else { &self[off..off + size] } } fn read(&self, offset: U256) -> U256 { le...
{ self.len() }
identifier_body
memory.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
} fn write_slice(&mut self, offset: U256, slice: &[u8]) { let off = offset.low_u64() as usize; // TODO [todr] Optimize? for pos in off..off + slice.len() { self[pos] = slice[pos - off]; } } fn write(&mut self, offset: U256, value: U256) { let off =...
{ &mut self[off..off + s] }
conditional_block
memory.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITH...
random_line_split
hibernate_state.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use kvproto::metapb::Region; use pd_client::{Feature, FeatureGate}; use serde_derive::{Deserialize, Serialize}; /// Because negotiation protocol can't be recognized by old version of binaries, /// so enabling it directly can cause a lot of connection ...
pub fn should_bcast(&self, gate: &FeatureGate) -> bool { gate.can_enable(NEGOTIATION_HIBERNATE) } pub fn maybe_hibernate(&mut self, my_id: u64, region: &Region) -> bool { let peers = region.get_peers(); let v = match &mut self.leader { LeaderState::Awaken => { ...
{ if let LeaderState::Poll(v) = &mut self.leader { if !v.contains(&from) { v.push(from); } } }
identifier_body
hibernate_state.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use kvproto::metapb::Region; use pd_client::{Feature, FeatureGate}; use serde_derive::{Deserialize, Serialize}; /// Because negotiation protocol can't be recognized by old version of binaries, /// so enabling it directly can cause a lot of connection ...
} } }
} else { false
random_line_split
hibernate_state.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use kvproto::metapb::Region; use pd_client::{Feature, FeatureGate}; use serde_derive::{Deserialize, Serialize}; /// Because negotiation protocol can't be recognized by old version of binaries, /// so enabling it directly can cause a lot of connection ...
{ group: GroupState, leader: LeaderState, } impl HibernateState { pub fn ordered() -> HibernateState { HibernateState { group: GroupState::Ordered, leader: LeaderState::Awaken, } } pub fn group_state(&self) -> GroupState { self.group } pub ...
HibernateState
identifier_name
hibernate_state.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use kvproto::metapb::Region; use pd_client::{Feature, FeatureGate}; use serde_derive::{Deserialize, Serialize}; /// Because negotiation protocol can't be recognized by old version of binaries, /// so enabling it directly can cause a lot of connection ...
else { false } } }
{ self.leader = LeaderState::Hibernated; true }
conditional_block
shootout-chameneos-redux.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2012-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted...
( name: uint, mut color: Color, from_rendezvous: Receiver<CreatureInfo>, to_rendezvous: Sender<CreatureInfo>, to_rendezvous_log: Sender<String> ) { let mut creatures_met = 0i32; let mut evil_clones_met = 0; let mut rendezvous = from_rendezvous.iter(); loop { // ask for a pai...
creature
identifier_name
shootout-chameneos-redux.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2012-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted...
7 => {" seven"} 8 => {" eight"} 9 => {" nine"} _ => {panic!("expected digits from 0 to 9...")} } } struct Number(uint); impl fmt::Show for Number { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut out = vec![]; let Number(mut num) = *self; ...
{" six"}
conditional_block
shootout-chameneos-redux.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2012-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted...
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. // n...
random_line_split
shootout-chameneos-redux.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2012-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted...
{ let nn = if std::os::getenv("RUST_BENCH").is_some() { 200000 } else { std::os::args().as_slice() .get(1) .and_then(|arg| arg.parse()) .unwrap_or(600u) }; print_complements(); println!(""); rendezvous(nn, vec...
identifier_body
ws_impl.rs
use flate2::read::ZlibDecoder; use serde_json; use websocket::message::OwnedMessage; use websocket::sync::stream::{TcpStream, TlsStream}; use websocket::sync::Client as WsClient; use gateway::GatewayError; use internal::prelude::*; pub trait ReceiverExt { fn recv_json<F, T>(&mut self, decode: F) -> Result<T> where...
OwnedMessage::Text(payload) => { let value = serde_json::from_str(&payload)?; Some(decode(value).map_err(|why| { warn!("(╯°□°)╯︵ ┻━┻ Error decoding: {}", payload); why })) }, OwnedMessage::Ping(...
why })) }, OwnedMessage::Close(data) => Some(Err(Error::Gateway(GatewayError::Closed(data)))),
random_line_split
ws_impl.rs
use flate2::read::ZlibDecoder; use serde_json; use websocket::message::OwnedMessage; use websocket::sync::stream::{TcpStream, TlsStream}; use websocket::sync::Client as WsClient; use gateway::GatewayError; use internal::prelude::*; pub trait ReceiverExt { fn recv_json<F, T>(&mut self, decode: F) -> Result<T> where...
warn!("(╯°□°)╯︵ ┻━┻ Error decoding: {}", payload); why })) }, OwnedMessage::Ping(x) => { self.send_message(&OwnedMessage::Pong(x)).map_err( Error::from, )?; None ...
{ let message = self.recv_message()?; let res = match message { OwnedMessage::Binary(bytes) => { let value = serde_json::from_reader(ZlibDecoder::new(&bytes[..]))?; Some(decode(value).map_err(|why| { let s = String::from_utf8_lossy(&bytes...
identifier_body
ws_impl.rs
use flate2::read::ZlibDecoder; use serde_json; use websocket::message::OwnedMessage; use websocket::sync::stream::{TcpStream, TlsStream}; use websocket::sync::Client as WsClient; use gateway::GatewayError; use internal::prelude::*; pub trait ReceiverExt { fn recv_json<F, T>(&mut self, decode: F) -> Result<T> where...
<()> { serde_json::to_string(value) .map(OwnedMessage::Text) .map_err(Error::from) .and_then(|m| self.send_message(&m).map_err(Error::from)) } }
-> Result
identifier_name
service.rs
use crate::protocol; #[cfg(windows)] use core::os::process::windows_child::{ChildStderr, ChildStdout, ExitStatus}; use core::util::BufReadLossy; use habitat_common::output::{self, StructuredOutput}; #[cfg(unix)] u...
(&self) -> u32 { self.process.id() } /// Attempt to gracefully terminate a proccess and then forcefully kill it after /// 8 seconds if it has not terminated. pub fn kill(&mut self) -> protocol::ShutdownMethod { self.process.kill() } pub fn name(&self) -> &str { &self.args.id } pub fn take_args(se...
id
identifier_name
service.rs
use crate::protocol; #[cfg(windows)] use core::os::process::windows_child::{ChildStderr, ChildStdout, ExitStatus}; use core::util::BufReadLossy; use habitat_common::output::{self, StructuredOutput}; #[cfg(unix)] u...
/// Consume standard error from a child process until EOF, then finish fn pipe_stderr<T>(err: T, id: &str) where T: Read { for line in BufReader::new(err).lines_lossy() { match line { Ok(line) => { let so = StructuredOutput::succinct(id, "E", output::get_format(), &line); ...
{ for line in BufReader::new(out).lines_lossy() { match line { Ok(line) => { let so = StructuredOutput::succinct(id, "O", output::get_format(), &line); if let Err(e) = so.println() { println!("printing output: '{}' to stdout resulted in error: ...
identifier_body
service.rs
use crate::protocol; #[cfg(windows)] use core::os::process::windows_child::{ChildStderr, ChildStdout, ExitStatus}; use core::util::BufReadLossy; use habitat_common::output::{self, StructuredOutput}; #[cfg(unix)] u...
impl Service { pub fn new(spawn: protocol::Spawn, process: Process, stdout: Option<ChildStdout>, stderr: Option<ChildStderr>) -> Self { if let Some(stdout) = stdout { let id = spawn.id.to_string(); thread::Builder::new().nam...
random_line_split
bind-by-move-neither-can-live-while-the-other-survives-4.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ x: (), } impl Drop for X { fn drop(&mut self) { println!("destructor runs"); } } fn main() { let x = Some((X { x: () }, X { x: () })); match x { Some((_y, ref _z)) => { }, //~ ERROR cannot bind by-move and by-ref in the same pattern None => fail!() } }
X
identifier_name
bind-by-move-neither-can-live-while-the-other-survives-4.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let x = Some((X { x: () }, X { x: () })); match x { Some((_y, ref _z)) => { }, //~ ERROR cannot bind by-move and by-ref in the same pattern None => fail!() } }
identifier_body
bind-by-move-neither-can-live-while-the-other-survives-4.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
impl Drop for X { fn drop(&mut self) { println!("destructor runs"); } } fn main() { let x = Some((X { x: () }, X { x: () })); match x { Some((_y, ref _z)) => { }, //~ ERROR cannot bind by-move and by-ref in the same pattern None => fail!() } }
// option. This file may not be copied, modified, or distributed // except according to those terms. struct X { x: (), }
random_line_split
p011.rs
//! [Problem 11](https://projecteuler.net/problem=11) solver. #![warn(bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #![feature(iter_arith)] #[macro_use(problem)] extern crate common; const INPUT: &'static str = " 08 02 22 97 38 15 00 40 00 75 ...
let h = grid.len(); let mut lines: Vec<Vec<_>> = vec![]; // rows lines.extend((0.. h).map(|y| (0.. w).map(|x| (x, y)).collect())); // cols lines.extend((0.. w).map(|x| (0.. h).map(|y| (x, y)).collect())); // top 2 right diagonal lines.extend((0.. w).map(|i| { let (x0, y0) = (i, ...
let w = grid[0].len();
random_line_split
p011.rs
//! [Problem 11](https://projecteuler.net/problem=11) solver. #![warn(bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #![feature(iter_arith)] #[macro_use(problem)] extern crate common; const INPUT: &'static str = " 08 02 22 97 38 15 00 40 00 75 ...
() -> String { compute(4).to_string() } problem!("70600674", solve);
solve
identifier_name
p011.rs
//! [Problem 11](https://projecteuler.net/problem=11) solver. #![warn(bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #![feature(iter_arith)] #[macro_use(problem)] extern crate common; const INPUT: &'static str = " 08 02 22 97 38 15 00 40 00 75 ...
(0.. w - x0).map(|j| (x0 + j, y0 + j)).collect() })); // left 2 bottom diagonal lines.extend((0.. h - 1).map(|i| { let (x0, y0) = (0, i + 1); (0.. h - y0).map(|j| (x0 + j, y0 + j)).collect() })); // top 2 left diagonal lines.extend((0.. w).map(|i| { let (x0, y0) =...
{ let grid: Vec<Vec<u32>> = INPUT .trim() .lines() .map(|line| { line.split_whitespace().filter_map(|s| s.parse().ok()).collect() }) .collect(); let w = grid[0].len(); let h = grid.len(); let mut lines: Vec<Vec<_>> = vec![]; // rows lines.ext...
identifier_body
lib.rs
// Copyright 2017 Kam Y. Tse // // 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 w...
pub use self::client::Client; /// The Errors that may occur when communicating with Pomotodo server. pub mod errors { error_chain! { types { Error, ErrorKind, ResultExt; } foreign_links { ReqError(::reqwest::Error); } } }
pub use self::pomo::{Pomo, PomoBuilder, PomoParameter}; pub use self::todo::{Todo, SubTodo, TodoBuilder, SubTodoBuilder, TodoParameter};
random_line_split
main.rs
// Copyright 2016 Gomez Guillaume // // 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 ...
} Err(e) => { println!("\x1b[31;1mProblem with directory '{}': {}\x1b[0m", entry_name, e); } } } } else { match entry.file_name() { Some(s) => { match ...
{ println!("\x1b[34;1m<- Leaving {}\x1b[0m", entry_name); }
conditional_block
main.rs
// Copyright 2016 Gomez Guillaume // // 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 ...
if files.len() == 0 { files.push(Path::new(".")); } if options.verbose { println!("\x1b[33;1m=== VERBOSE MODE ===\x1b[0m"); } for tmp in files.iter() { start_clean(&options, tmp, 0); } if options.verbose { println!("\x1b[33;1mEnd of execution\x1b[0m"); } }
} }
random_line_split
main.rs
// Copyright 2016 Gomez Guillaume // // 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 ...
match fs::read_dir(entry) { Ok(res) => { if options.verbose { println!("\x1b[36;1m-> Entering {}\x1b[0m", entry_name); } for tmp in res { match tmp { ...
{ let m = match ::std::fs::metadata(&entry) { Ok(e) => e, Err(e) => { println!("An error occured on '{:?}': {}", entry, e); return } }; let entry_name = match entry.to_str() { Some(n) => n, None => { println!("Invalid entry '{:?}'",...
identifier_body
main.rs
// Copyright 2016 Gomez Guillaume // // 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 ...
() { let mut args = Vec::new(); for argument in std::env::args() { args.push(argument); } let mut options = CleanOptions{recursive: false, verbose: false, confirmation: false, level: 0}; let mut files = Vec::new(); args.remove(0); for tmp in args.iter() { if tmp.clone().int...
main
identifier_name
sha3.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
// when let hash = sha3(&mut file).unwrap(); // then assert_eq!(format!("{:?}", hash), "68371d7e884c168ae2022c82bd837d51837718a7f7dfb7aa3f753074a35e1d87"); } }
random_line_split
sha3.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
() { // given use devtools::RandomTempPath; let path = RandomTempPath::new(); // Prepare file { let mut file = fs::File::create(&path).unwrap(); file.write_all(b"something").unwrap(); } let mut file = BufReader::new(fs::File::open(&path).unwrap()); // when let hash = sha3(&mut file).unwrap(); ...
should_sha3_a_file
identifier_name
sha3.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
sha3.update(&input[0..some]); } sha3.finalize(&mut output); Ok(output.into()) } #[cfg(test)] mod tests { use std::fs; use std::io::{Write, BufReader}; use super::*; #[test] fn sha3_empty() { assert_eq!([0u8; 0].sha3(), SHA3_EMPTY); } #[test] fn sha3_as() { assert_eq!([0x41u8; 32].sha3(), From::from...
{ break; }
conditional_block
sha3.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
fn sha3_into(&self, dest: &mut [u8]) { let input: &[u8] = self.as_ref(); unsafe { sha3_256(dest.as_mut_ptr(), dest.len(), input.as_ptr(), input.len()); } } } /// Calculate SHA3 of given stream. pub fn sha3(r: &mut io::BufRead) -> Result<H256, io::Error> { let mut output = [0u8; 32]; let mut input = [0u8...
{ let mut ret: H256 = H256::zero(); self.sha3_into(&mut *ret); ret }
identifier_body
mod.rs
#[cfg(test)] use game; use ai; use ai::run_match; use constants::LINES; use std::sync::Arc;
fn match_mc() { let structure = Arc::new(game::Structure::new(&LINES)); let mut white_player = ai::mc::MonteCarloAI::new(1000); let mut black_player = ai::mc::MonteCarloAI::new(1000); run_match(structure, &mut white_player, &mut black_player); } #[test] fn match_mc_tree() { let structure = Arc::new...
#[test]
random_line_split
mod.rs
#[cfg(test)] use game; use ai; use ai::run_match; use constants::LINES; use std::sync::Arc; #[test] fn match_mc() { let structure = Arc::new(game::Structure::new(&LINES)); let mut white_player = ai::mc::MonteCarloAI::new(1000); let mut black_player = ai::mc::MonteCarloAI::new(1000); run_match(structure...
#[test] fn subset_coherence() { // This is a property based test, see QuickCheck for more information. use rand::{thread_rng, Rng}; let mut rng = thread_rng(); for _ in 0..10000 { // Ensure that all positions returned by the Subset iterator are // contained in the Subset. let...
{ let structure = Arc::new(game::Structure::new(&LINES)); let mut white_player = ai::tree::TreeJudgementAI::new(structure.clone(), 2, ai::value::Simple::Subsets); let mut black_player = ai::tree::TreeJudgementAI::new(structure.clone(), 2, ai::value::Simple::Subsets); run_match(structure,...
identifier_body
mod.rs
#[cfg(test)] use game; use ai; use ai::run_match; use constants::LINES; use std::sync::Arc; #[test] fn match_mc() { let structure = Arc::new(game::Structure::new(&LINES)); let mut white_player = ai::mc::MonteCarloAI::new(1000); let mut black_player = ai::mc::MonteCarloAI::new(1000); run_match(structure...
() { let structure = Arc::new(game::Structure::new(&LINES)); let mut white_player = ai::tree::TreeJudgementAI::new(structure.clone(), 2, ai::value::Simple::Subsets); let mut black_player = ai::tree::TreeJudgementAI::new(structure.clone(), 2, ai::value::Simple::Subsets); run_match(structu...
match_tree
identifier_name