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 |
|---|---|---|---|---|
declare.rs | /*!
Functionality for declaring Objective-C classes.
Classes can be declared using the `ClassDecl` struct. Instance variables and
methods can then be added before the class is ultimately registered.
# Example
The following example demonstrates declaring a class named `MyNumber` that has
one ivar, a `u32` named `_num... | else {
Some(ClassDecl { cls })
}
}
/// Constructs a `ClassDecl` with the given name and superclass.
/// Returns `None` if the class couldn't be allocated.
pub fn new(name: &str, superclass: &Class) -> Option<ClassDecl> {
ClassDecl::with_superclass(name, Some(superclass))
... | {
None
} | conditional_block |
declare.rs | /*!
Functionality for declaring Objective-C classes.
Classes can be declared using the `ClassDecl` struct. Instance variables and
methods can then be added before the class is ultimately registered.
# Example
The following example demonstrates declaring a class named `MyNumber` that has
one ivar, a `u32` named `_num... | let size = mem::size_of::<T>();
let align = log2_align_of::<T>();
let success = unsafe {
runtime::class_addIvar(self.cls, c_name.as_ptr(), size, align,
encoding.as_ptr())
};
assert!(success!= NO, "Failed to add ivar {}", name);
}
/// Adds a pr... | let encoding = CString::new(T::encode().as_str()).unwrap(); | random_line_split |
declare.rs | /*!
Functionality for declaring Objective-C classes.
Classes can be declared using the `ClassDecl` struct. Instance variables and
methods can then be added before the class is ultimately registered.
# Example
The following example demonstrates declaring a class named `MyNumber` that has
one ivar, a `u32` named `_num... | <F>(&mut self, sel: Sel, func: F)
where F: MethodImplementation<Callee=Object> {
let encs = F::Args::encodings();
let encs = encs.as_ref();
let sel_args = count_args(sel);
assert!(sel_args == encs.len(),
"Selector accepts {} arguments, but function accepts {}",
... | add_method | identifier_name |
annealing3.rs | use crate::common::*;
use geo::algorithm::coords_iter::CoordsIter;
use rand::prelude::*;
use rand::seq::SliceRandom;
use std::collections::VecDeque;
use std::time::{Duration, Instant};
static SEED: [u8; 32] = [
0xfd, 0x00, 0xf1, 0x5c, 0xde, 0x01, 0x11, 0xc6, 0xc3, 0xea, 0xfb, 0xbf, 0xf3, 0xca, 0xd8, 0x32,
0x6a... |
(
dislike / (input.hole.exterior().coords_count() as f64),
-(vx + vy),
)
}
fn ascore(value: (f64, f64), progress: f64) -> f64 {
value.0 * progress + (1.0 - progress) * value.1
}
pub fn solve(
input: &Input,
mut solution: Vec<Point>,
time_limit: Duration,
fix_seed: bool,
... | {
let dislike = calculate_dislike(&solution, &input.hole);
let mut gx: f64 = 0.0;
let mut gy: f64 = 0.0;
for p in solution.iter() {
gx += p.x();
gy += p.y();
}
gx /= solution.len() as f64;
gy /= solution.len() as f64;
let mut vx: f64 = 0.0;
let mut vy: f64 = 0.0;
... | identifier_body |
annealing3.rs | use crate::common::*;
use geo::algorithm::coords_iter::CoordsIter;
use rand::prelude::*;
use rand::seq::SliceRandom;
use std::collections::VecDeque;
use std::time::{Duration, Instant};
static SEED: [u8; 32] = [
0xfd, 0x00, 0xf1, 0x5c, 0xde, 0x01, 0x11, 0xc6, 0xc3, 0xea, 0xfb, 0xbf, 0xf3, 0xca, 0xd8, 0x32,
0x6a... | temperature = initial_temperature * (1.0 - progress) * (-progress).exp2();
}
// move to neighbor
let r = rng.gen::<f64>();
if r > progress {
let mut i = 0;
{
let r = rng.gen::<usize>() % distance_total;
let mut sum = 0;... | // tweak temperature
progress = elapsed.as_secs_f64() / time_limit.as_secs_f64(); | random_line_split |
annealing3.rs | use crate::common::*;
use geo::algorithm::coords_iter::CoordsIter;
use rand::prelude::*;
use rand::seq::SliceRandom;
use std::collections::VecDeque;
use std::time::{Duration, Instant};
static SEED: [u8; 32] = [
0xfd, 0x00, 0xf1, 0x5c, 0xde, 0x01, 0x11, 0xc6, 0xc3, 0xea, 0xfb, 0xbf, 0xf3, 0xca, 0xd8, 0x32,
0x6a... |
return p;
}
return solution[i];
}
unreachable!()
}
fn is_valid_point_move(
index: usize,
p: &Point,
solution: &[Point],
original_vertices: &[Point],
out_edges: &[Vec<usize>],
hole: &Polygon,
epsilon: i64,
) -> bool {
let ok1 = out_edges[index].iter()... | {
continue;
} | conditional_block |
annealing3.rs | use crate::common::*;
use geo::algorithm::coords_iter::CoordsIter;
use rand::prelude::*;
use rand::seq::SliceRandom;
use std::collections::VecDeque;
use std::time::{Duration, Instant};
static SEED: [u8; 32] = [
0xfd, 0x00, 0xf1, 0x5c, 0xde, 0x01, 0x11, 0xc6, 0xc3, 0xea, 0xfb, 0xbf, 0xf3, 0xca, 0xd8, 0x32,
0x6a... | (
from: usize,
w: usize,
solution: &Vec<Point>,
input: &Input,
rng: &mut SmallRng,
out_edges: &Vec<Vec<usize>>,
orders: &Vec<Vec<usize>>,
) -> Option<Vec<Point>> {
let mut gx: f64 = 0.0;
let mut gy: f64 = 0.0;
for p in solution.iter() {
gx += p.x();
gy += p.y();
... | random_move_one_point | identifier_name |
mod.rs | use futures::prelude::*;
use http::Uri;
use slog::Logger;
use std::{
iter::FromIterator,
path::{Path, PathBuf},
str::FromStr,
};
use crate::{
cache::{self, Cacheable, Cache as _},
download,
error::prelude::*,
};
use tokio::io::AsyncReadExt;
mod hash_writer;
use hash_writer::HashWriter;
mod erro... | (&self, repo_uri: Uri) -> ResolvedArtifact {
ResolvedArtifact {
artifact: self.clone(),
repo: repo_uri,
}
}
pub fn download_from(
&self,
location: &Path,
repo_uri: Uri,
manager: download::Manager,
log: Logger,
) -> impl Future<... | resolve | identifier_name |
mod.rs | use futures::prelude::*;
use http::Uri;
use slog::Logger;
use std::{
iter::FromIterator,
path::{Path, PathBuf},
str::FromStr,
};
use crate::{
cache::{self, Cacheable, Cache as _},
download,
error::prelude::*,
};
use tokio::io::AsyncReadExt;
mod hash_writer;
use hash_writer::HashWriter;
mod erro... |
if let Some(ref ext) = self.extension {
strn.push('@');
strn.push_str(ext);
}
strn
}
}
impl FromStr for Artifact {
type Err = ArtifactParseError;
fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> {
let parts: Vec<&str> = s.split('@').col... | {
strn.push(':');
strn.push_str(classifier);
} | conditional_block |
mod.rs | use futures::prelude::*;
use http::Uri;
use slog::Logger;
use std::{
iter::FromIterator,
path::{Path, PathBuf},
str::FromStr,
};
use crate::{
cache::{self, Cacheable, Cache as _},
download,
error::prelude::*,
};
use tokio::io::AsyncReadExt;
mod hash_writer;
use hash_writer::HashWriter;
mod erro... | classifier = classifier_fmt,
extension = extension_fmt
)
}
pub fn resolve(&self, repo_uri: Uri) -> ResolvedArtifact {
ResolvedArtifact {
artifact: self.clone(),
repo: repo_uri,
}
}
pub fn download_from(
&self,
loca... | random_line_split | |
mod.rs | use futures::prelude::*;
use http::Uri;
use slog::Logger;
use std::{
iter::FromIterator,
path::{Path, PathBuf},
str::FromStr,
};
use crate::{
cache::{self, Cacheable, Cache as _},
download,
error::prelude::*,
};
use tokio::io::AsyncReadExt;
mod hash_writer;
use hash_writer::HashWriter;
mod erro... |
pub fn get_uri_on(&self, base: &Uri) -> Result<Uri,error::Error> {
let base = crate::util::uri_to_url(base).context(error::BadUrl)?;
let path = self.to_path();
let url = base.join(path.to_str().expect("non unicode path encountered")).context(error::BadUrl)?;
crate::util::url_to_uri... | {
let mut p = PathBuf::new();
p.push(&self.group_path());
p.push(&self.artifact);
p.push(&self.version);
p.push(&self.artifact_filename());
p
} | identifier_body |
main.rs |
Err(e) => e.to_string()
};
assert_eq!("5", end);
}
fn _result_match() {
let result: Result<i32, &str> = Ok(5);
let number = match result {
Ok(x) => x,
Err(_e) => 0,
};
assert_eq!(5, number)
}
fn _threads() {
let handles: Vec<_> = (0..10).map(|x| {
thread::... | let x = 2;
let num = match x {
1 | 2 => "1, 2",
3 => "3",
_ => "...",
};
assert_eq!("1, 2", num);
}
fn _match_rangos() {
let x = 3;
let resultado = match x {
1..= 5 => "uno al cinco",
_ => "cualquier cosa",
};
assert_eq!("uno al cinco", resultado)... | };
}
}
fn _multiples_patrones() { | random_line_split |
main.rs | Err(e) => e.to_string()
};
assert_eq!("5", end);
}
fn _result_match() {
let result: Result<i32, &str> = Ok(5);
let number = match result {
Ok(x) => x,
Err(_e) => 0,
};
assert_eq!(5, number)
}
fn _threads() {
let handles: Vec<_> = (0..10).map(|x| {
thread::s... | let origen = Punto { x: 1, y: 2 };
let suma = foo(&origen);
assert_eq!(3, suma);
assert_eq!(1, origen.x);
}
fn _tupla_estructuras() {
struct Color(i32, i32, i32);
let azul = Color(0, 0, 255);
assert_eq!(255, azul.2);
}
fn _estructuras_tipo_unitario() {
struct Electron;
let _e = Electr... | punto.x + punto.y
}
| identifier_body |
main.rs | Err(e) => e.to_string()
};
assert_eq!("5", end);
}
fn _result_match() {
let result: Result<i32, &str> = Ok(5);
let number = match result {
Ok(x) => x,
Err(_e) => 0,
};
assert_eq!(5, number)
}
fn _threads() {
let handles: Vec<_> = (0..10).map(|x| {
thread::sp... |
let x = 2;
let num = match x {
1 | 2 => "1, 2",
3 => "3",
_ => "...",
};
assert_eq!("1, 2", num);
}
fn _match_rangos() {
let x = 3;
let resultado = match x {
1..= 5 => "uno al cinco",
_ => "cualquier cosa",
};
assert_eq!("uno al cinco", resultado... | tiples_patrones() { | identifier_name |
main.rs | Err(e) => e.to_string()
};
assert_eq!("5", end);
}
fn _result_match() {
let result: Result<i32, &str> = Ok(5);
let number = match result {
Ok(x) => x,
Err(_e) => 0,
};
assert_eq!(5, number)
}
fn _threads() {
let handles: Vec<_> = (0..10).map(|x| {
thread::sp... | continua el ciclo por encima de y
println!("x: {}, y: {}", x, y);
}
}
}
fn _enumerate() {
for (i,j) in (5..10).enumerate() {
println!("i = {} y j = {}", i, j);
}
let lineas = "hola\nmundo".lines();
for (numero_linea, linea) in lineas.enumerate() {
println!("{}: ... | ntinue 'interior; } // | conditional_block |
fixed.rs | //! Groups all the static pages together.
use maud::Markup;
use rocket::Route;
mod contacts;
mod links;
mod projects;
mod resume;
/// Returns the "index" page, aka the home page of the website.
///
/// This simply calls [`page_client::home::index()`] from [`page_client`].
#[get("/")]
fn get_index() -> Markup {
h... | () -> Vec<Route> {
routes![
get_index,
resume::get,
links::get,
contacts::get,
projects::get,
projects::project::get,
]
}
/// Functions generating my home page.
pub mod htmlgen {
use maud::{html, Markup, Render};
use page_client::{data, partials};
//... | routes | identifier_name |
fixed.rs | //! Groups all the static pages together.
use maud::Markup;
use rocket::Route;
mod contacts;
mod links;
mod projects;
mod resume;
/// Returns the "index" page, aka the home page of the website.
///
/// This simply calls [`page_client::home::index()`] from [`page_client`].
#[get("/")]
fn get_index() -> Markup {
h... |
/// Returns the first slide as [`Markup`].
fn my_intro() -> Markup {
slide(
"Nice to meet you",
html! {
p { "My name is Ben. I am a developer, but I am also:" }
ul {
li {
"a reader; I love to read. But t... | {
html! {
div id = { "slide-marker-"(idx) } class={"slide-marker" @if idx == 0 { (" active-slide-marker") }} {}
}
} | identifier_body |
fixed.rs | //! Groups all the static pages together.
use maud::Markup;
use rocket::Route;
mod contacts;
mod links;
mod projects;
mod resume;
/// Returns the "index" page, aka the home page of the website.
///
/// This simply calls [`page_client::home::index()`] from [`page_client`].
#[get("/")]
fn get_index() -> Markup {
h... | @for i in 0..slide_cnt {
(slide_marker(i))
}
}
}
/// Returns the slide_marker as [`Markup`].
fn slide_marker(idx: u8) -> Markup {
html! {
div id = { "slide-marker-"(idx) } class={"slide-marker" @if idx == 0 { (" active-slide-marker") }} {}... | /// Returns the slide_markers as [`Markup`].
fn slide_markers(slide_cnt: u8) -> Markup {
html! { | random_line_split |
routes.rs | use rocket::State;
use rocket::response::{Flash, Redirect};
use rocket::request::{Form, FormItems, FromForm};
use option_filter::OptionFilterExt;
use super::{html, StudentPreferences, TimeSlotRating};
use config;
use db::Db;
use dict::{self, Locale};
use errors::*;
use state::PreparationState;
use template::{NavItem, ... | (locale: Locale) -> Vec<NavItem> {
// TODO: pass `Dict` once possible
let dict = dict::new(locale).prep;
vec![
NavItem::new(dict.nav_overview_title(), "/prep"),
NavItem::new(dict.nav_timeslots_title(), "/prep/timeslots"),
]
}
#[get("/prep")]
pub fn overview(
auth_user: AuthUser,
... | nav_items | identifier_name |
routes.rs | use rocket::State;
use rocket::response::{Flash, Redirect};
use rocket::request::{Form, FormItems, FromForm};
use option_filter::OptionFilterExt;
use super::{html, StudentPreferences, TimeSlotRating};
use config;
use db::Db;
use dict::{self, Locale};
use errors::*;
use state::PreparationState;
use template::{NavItem, ... | ").get_result::<f64>(conn)?;
let avg_ok_rating_per_student = sql("
select cast(avg(count) as float) from (
select count(*) as count, user_id
from timeslot_ratings
inner join users
... | where rating = 'good' and role = 'student'
group by user_id
) as counts | random_line_split |
ui.rs | //! Implements how the user interfaces with the application.
pub(crate) use crate::num::{Length, NonNegativeI32};
use crate::{fmt, Debug, Display, Formatter, Mrc, TryFrom, TryFromIntError};
use pancurses::Input;
use std::cell::RefCell;
use std::error;
use std::rc::Rc;
/// The [`Result`] returned by functions of this... | Change::Clear => write!(f, "Clear"),
Change::Format(n, color) => write!(f, "Format {} cells to {}", n, color),
Change::Insert(input) => write!(f, "Insert '{}'", input),
Change::Nothing => write!(f, "Nothing"),
Change::Row(row_str) => write!(f, "Write row '{}'"... | #[inline]
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Change::Backspace => write!(f, "Backspace"), | random_line_split |
ui.rs | //! Implements how the user interfaces with the application.
pub(crate) use crate::num::{Length, NonNegativeI32};
use crate::{fmt, Debug, Display, Formatter, Mrc, TryFrom, TryFromIntError};
use pancurses::Input;
use std::cell::RefCell;
use std::error;
use std::rc::Rc;
/// The [`Result`] returned by functions of this... |
}
/// Signifies a [`Change`] to make to an [`Address`].
///
/// [`Change`]: enum.Change.html
/// [`Address`]: struct.Address.html
#[derive(Clone, Debug, Default, Eq, Hash, PartialEq)]
pub struct Edit {
/// The [`Change`] to be made.
change: Change,
/// The [`Address`] on which the [`Change`] is intended.
... | {
match self {
Color::Default => write!(f, "Default"),
Color::Red => write!(f, "Red"),
Color::Green => write!(f, "Green"),
Color::Yellow => write!(f, "Yellow"),
Color::Blue => write!(f, "Blue"),
}
} | identifier_body |
ui.rs | //! Implements how the user interfaces with the application.
pub(crate) use crate::num::{Length, NonNegativeI32};
use crate::{fmt, Debug, Display, Formatter, Mrc, TryFrom, TryFromIntError};
use pancurses::Input;
use std::cell::RefCell;
use std::error;
use std::rc::Rc;
/// The [`Result`] returned by functions of this... | (&self) -> Outcome {
Self::process(self.window.delch(), Error::Wdelch)
}
/// Disables echoing received characters on the screen.
fn disable_echo(&self) -> Outcome {
Self::process(pancurses::noecho(), Error::Noecho)
}
/// Sets user interface to not wait for an input.
fn enable_n... | delete_char | identifier_name |
response.rs | use hyper::header::{self, CookiePair as Cookie, ContentType, Header, SetCookie};
use hyper::status::StatusCode as Status;
use hyper::Headers;
use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value};
use serde_json::value as json;
use serde_json::value::ToJson;
use std::any::Any;
use std::boxed::Box;
use std::borrow... | (&self) -> Option<&error::Error> {
None
}
}
impl From<Status> for Error {
fn from(status: Status) -> Error {
Error::new(status, None)
}
}
impl From<(Status, &'static str)> for Error {
fn from(pair: (Status, &'static str)) -> Error {
Error::new(pair.0, Some(Cow::Borrowed(pair.1)... | cause | identifier_name |
response.rs | use hyper::header::{self, CookiePair as Cookie, ContentType, Header, SetCookie};
use hyper::status::StatusCode as Status;
use hyper::Headers;
use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value};
use serde_json::value as json;
use serde_json::value::ToJson;
use std::any::Any;
use std::boxed::Box;
use std::borrow... | {
response.streaming
} | identifier_body | |
response.rs | use hyper::header::{self, CookiePair as Cookie, ContentType, Header, SetCookie};
use hyper::status::StatusCode as Status;
use hyper::Headers;
use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value};
use serde_json::value as json;
use serde_json::value::ToJson;
use std::any::Any;
use std::boxed::Box;
use std::borrow... | self.status(Status::InternalServerError).content_type("text/plain");
Some(format!("{}", err).into())
} else {
Some(buf)
}
},
Err(ref err) if err.kind() == ErrorKind::NotFound => {
self.sta... | // probably not the best idea for big files, we should use stream instead in that case
match File::open(path) {
Ok(mut file) => {
let mut buf = Vec::with_capacity(file.metadata().ok().map_or(1024, |meta| meta.len() as usize));
if let Err(err) = file.read_to_en... | random_line_split |
lib.rs | //! An element-tree style XML library
//!
//! # Examples
//!
//! ## Reading
//!
//! ```
//! use treexml::Document;
//!
//! let doc_raw = r#"
//! <?xml version="1.1" encoding="UTF-8"?>
//! <table>
//! <fruit type="apple">worm</fruit>
//! <vegetable />
//! </table>
//! "#;
//!
//! let doc = Document::parse(doc_ra... |
use indexmap::IndexMap;
use xml::common::XmlVersion as BaseXmlVersion;
/// Enumeration of XML versions
///
/// This exists solely because `xml-rs`'s `XmlVersion` doesn't implement Debug
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum XmlVersion {
/// XML Version 1.0
Version10,
/// XML Version 1.1
... |
pub use errors::*;
pub use builder::*; | random_line_split |
lib.rs | //! An element-tree style XML library
//!
//! # Examples
//!
//! ## Reading
//!
//! ```
//! use treexml::Document;
//!
//! let doc_raw = r#"
//! <?xml version="1.1" encoding="UTF-8"?>
//! <table>
//! <fruit type="apple">worm</fruit>
//! <vegetable />
//! </table>
//! "#;
//!
//! let doc = Document::parse(doc_ra... | (value: XmlVersion) -> BaseXmlVersion {
match value {
XmlVersion::Version10 => BaseXmlVersion::Version10,
XmlVersion::Version11 => BaseXmlVersion::Version11,
}
}
}
/// An XML element
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Element {
/// Tag prefix, used for nam... | from | identifier_name |
component.rs | };
use wasmtime_jit::{CodeMemory, CompiledModuleInfo};
use wasmtime_runtime::{MmapVec, VMFunctionBody, VMTrampoline};
/// A compiled WebAssembly Component.
//
// FIXME: need to write more docs here.
#[derive(Clone)]
pub struct Component {
inner: Arc<ComponentInner>,
}
struct ComponentInner {
/// Core wasm mod... |
pub(crate) fn signatures(&self) -> &SignatureCollection {
self.inner.code.signatures()
}
pub(crate) fn text(&self) -> &[u8] {
self.inner.code.code_memory().text()
}
pub(crate) fn lowering_ptr(&self, index: LoweredIndex) -> NonNull<VMFunctionBody> {
let info = &self.inner.... | {
match self.inner.code.types() {
crate::code::Types::Component(types) => types,
// The only creator of a `Component` is itself which uses the other
// variant, so this shouldn't be possible.
crate::code::Types::Module(_) => unreachable!(),
}
} | identifier_body |
component.rs | Index};
use wasmtime_jit::{CodeMemory, CompiledModuleInfo};
use wasmtime_runtime::{MmapVec, VMFunctionBody, VMTrampoline};
/// A compiled WebAssembly Component.
//
// FIXME: need to write more docs here.
#[derive(Clone)]
pub struct Component {
inner: Arc<ComponentInner>,
}
struct ComponentInner {
/// Core was... | let loc = &self.inner.info.always_trap[index];
self.func(loc)
| let info = &self.inner.info.lowerings[index];
self.func(info)
}
pub(crate) fn always_trap_ptr(&self, index: RuntimeAlwaysTrapIndex) -> NonNull<VMFunctionBody> { | random_line_split |
component.rs | };
use wasmtime_jit::{CodeMemory, CompiledModuleInfo};
use wasmtime_runtime::{MmapVec, VMFunctionBody, VMTrampoline};
/// A compiled WebAssembly Component.
//
// FIXME: need to write more docs here.
#[derive(Clone)]
pub struct Component {
inner: Arc<ComponentInner>,
}
struct ComponentInner {
/// Core wasm mod... | (&self) -> &[u8] {
self.inner.code.code_memory().text()
}
pub(crate) fn lowering_ptr(&self, index: LoweredIndex) -> NonNull<VMFunctionBody> {
let info = &self.inner.info.lowerings[index];
self.func(info)
}
pub(crate) fn always_trap_ptr(&self, index: RuntimeAlwaysTrapIndex) -> N... | text | identifier_name |
lib.rs | //! # L2
//!# What is L2?
//!
//!> L2 is named after the L2 or Euclidean distance, a popular distance function in deep learning
//!
//!L2 is a Pytorch-style Tensor+Autograd library written in the Rust programming language. It contains a multidimensional array class, `Tensor`, with support for strided arrays, numpy-styl... | () {
let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap();
let c = sum(&a, 0).unwrap();
assert!((c.data == vec![5.0]) && (c.shape == vec![1]))
}
#[test]
fn test_mean() {
let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap();
let c = mean(&a, 0).unwrap();
asser... | test_sum | identifier_name |
lib.rs | //! # L2
//!# What is L2?
//!
//!> L2 is named after the L2 or Euclidean distance, a popular distance function in deep learning
//!
//!L2 is a Pytorch-style Tensor+Autograd library written in the Rust programming language. It contains a multidimensional array class, `Tensor`, with support for strided arrays, numpy-styl... |
pub fn matmul<'a>(lhs: &'a Tensor, rhs: &'a Tensor) -> Result<Tensor<'a>, TensorError> {
lhs.matmul(rhs)
}
pub fn concat<'a>(lhs: &'a Tensor, rhs: &'a Tensor, dim: isize) -> Result<Tensor<'a>, TensorError> {
lhs.concat(&rhs, dim)
}
#[cfg(test)]
mod tests {
use super::tensor::*;
use super::*;
#[t... | } | random_line_split |
lib.rs | //! # L2
//!# What is L2?
//!
//!> L2 is named after the L2 or Euclidean distance, a popular distance function in deep learning
//!
//!L2 is a Pytorch-style Tensor+Autograd library written in the Rust programming language. It contains a multidimensional array class, `Tensor`, with support for strided arrays, numpy-styl... |
#[test]
fn test_mean() {
let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap();
let c = mean(&a, 0).unwrap();
assert!((c.data == vec![2.5]) && (c.shape == vec![1]))
}
#[test]
fn test_max() {
let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap();
let c = max(&a,... | {
let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap();
let c = sum(&a, 0).unwrap();
assert!((c.data == vec![5.0]) && (c.shape == vec![1]))
} | identifier_body |
lib.rs | use ndarray::{concatenate, s, Array1, Array2, Axis};
#[macro_use]
extern crate lazy_static;
peg::parser!(grammar parse_tile() for str {
pub rule parse_tile_id() -> usize
= "Tile " id:$(['0'..='9']+) ":" { id.parse().unwrap() }
pub rule parse_border() -> (u32, u32)
= line:$(['#' | '.']+) {
... | <'a>(
&'a self,
row: usize,
col: usize,
prev_images: &[(&'a Tile, usize)],
) -> Vec<(&'a Tile, usize)> {
let mut result: Vec<(&Tile, usize)> = vec![];
result.extend_from_slice(prev_images);
for tile in self.tiles.iter() {
if result.iter().any(|(t, ... | fits | identifier_name |
lib.rs | use ndarray::{concatenate, s, Array1, Array2, Axis};
#[macro_use]
extern crate lazy_static;
peg::parser!(grammar parse_tile() for str {
pub rule parse_tile_id() -> usize
= "Tile " id:$(['0'..='9']+) ":" { id.parse().unwrap() }
pub rule parse_border() -> (u32, u32)
= line:$(['#' | '.']+) {
... | }
} | let testcase = read_input("../testcase1.txt");
let test_image = BigImage::new(testcase);
let result = vec![];
let result = test_image.fits(0, 0, &result);
assert_eq!(part2_solution(&test_image, &result), 273); | random_line_split |
lib.rs | use ndarray::{concatenate, s, Array1, Array2, Axis};
#[macro_use]
extern crate lazy_static;
peg::parser!(grammar parse_tile() for str {
pub rule parse_tile_id() -> usize
= "Tile " id:$(['0'..='9']+) ":" { id.parse().unwrap() }
pub rule parse_border() -> (u32, u32)
= line:$(['#' | '.']+) {
... | let (bottom, bottom_rev) = parse_tile::parse_border(&lines[lines.len() - 1]).unwrap();
let mut sub_image = unsafe { Array2::<u8>::uninitialized((shape, shape)) };
for (i, row) in lines.iter().enumerate().skip(2).take(shape) {
let row_pixels = parse_tile::parse_sub_image(&row[1..row.l... | {
let lines = data
.split('\n')
.map(|s| s.trim_end().to_string())
.collect::<Vec<_>>();
let shape = lines[1].len() - 2;
let tile_id = parse_tile::parse_tile_id(&lines[0]).unwrap();
let (top, top_rev) = parse_tile::parse_border(&lines[1]).unwrap();
... | identifier_body |
linebreak.rs | slen sstart tabwidth tlen underlen winfo wlen wordlen
use std::cmp;
use std::i64;
use std::io::{BufWriter, Stdout, Write};
use std::mem;
use uucore::crash;
use crate::parasplit::{ParaWords, Paragraph, WordInfo};
use crate::FmtOptions;
struct BreakArgs<'a> {
opts: &'a FmtOptions,
init_len: usize,
indent... | <'a>(paths: &[LineBreak<'a>], active: &[usize]) -> Vec<(&'a WordInfo<'a>, bool)> {
let mut breakwords = vec![];
// of the active paths, we select the one with the fewest demerits
let mut best_idx = match active.iter().min_by_key(|&&a| paths[a].demerits) {
None => crash!(
1,
"... | build_best_path | identifier_name |
linebreak.rs | slen sstart tabwidth tlen underlen winfo wlen wordlen
use std::cmp;
use std::i64;
use std::io::{BufWriter, Stdout, Write};
use std::mem;
use uucore::crash;
use crate::parasplit::{ParaWords, Paragraph, WordInfo};
use crate::FmtOptions;
struct BreakArgs<'a> {
opts: &'a FmtOptions,
init_len: usize,
indent... |
}
// break_simple implements a "greedy" breaking algorithm: print words until
// maxlength would be exceeded, then print a linebreak and indent and continue.
fn break_simple<'a, T: Iterator<Item = &'a WordInfo<'a>>>(
mut iter: T,
args: &mut BreakArgs<'a>,
) -> std::io::Result<()> {
iter.try_fold((args.ini... | {
break_knuth_plass(p_words_words, &mut break_args)
} | conditional_block |
linebreak.rs | signum slen sstart tabwidth tlen underlen winfo wlen wordlen
use std::cmp;
use std::i64;
use std::io::{BufWriter, Stdout, Write};
use std::mem;
use uucore::crash;
use crate::parasplit::{ParaWords, Paragraph, WordInfo};
use crate::FmtOptions;
struct BreakArgs<'a> {
opts: &'a FmtOptions,
init_len: usize,
... | 1
}
} else {
0
}
}
// If we're on a fresh line, slen=0 and we slice off leading whitespace.
// Otherwise, compute slen and leave whitespace alone.
fn slice_if_fresh(
fresh: bool,
word: &str,
start: usize,
uniform: bool,
newline: bool,
sstart: bool,
punct:... | if uniform || newline {
if start || (newline && punct) {
2
} else { | random_line_split |
ioapic.rs | use core::{fmt, ptr};
use alloc::vec::Vec;
use spin::Mutex;
#[cfg(feature = "acpi")]
use crate::acpi::madt::{self, Madt, MadtEntry, MadtIoApic, MadtIntSrcOverride};
use crate::arch::interrupt::irq;
use crate::memory::Frame;
use crate::paging::{KernelMapper, Page, PageFlags, PhysicalAddress, RmmA, RmmArch, VirtualAdd... | }
impl fmt::Debug for IoApic {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
struct RedirTable<'a>(&'a Mutex<IoApicRegs>);
impl<'a> fmt::Debug for RedirTable<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut guard = self.0.lock();
... | random_line_split | |
ioapic.rs | use core::{fmt, ptr};
use alloc::vec::Vec;
use spin::Mutex;
#[cfg(feature = "acpi")]
use crate::acpi::madt::{self, Madt, MadtEntry, MadtIoApic, MadtIntSrcOverride};
use crate::arch::interrupt::irq;
use crate::memory::Frame;
use crate::paging::{KernelMapper, Page, PageFlags, PhysicalAddress, RmmA, RmmArch, VirtualAdd... |
fn resolve(irq: u8) -> u32 {
get_override(irq).map_or(u32::from(irq), |over| over.gsi)
}
fn find_ioapic(gsi: u32) -> Option<&'static IoApic> {
ioapics().iter().find(|apic| gsi >= apic.gsi_start && gsi < apic.gsi_start + u32::from(apic.count))
}
pub unsafe fn mask(irq: u8) {
let gsi = resolve(irq);
let... | {
src_overrides().iter().find(|over| over.bus_irq == irq)
} | identifier_body |
ioapic.rs | use core::{fmt, ptr};
use alloc::vec::Vec;
use spin::Mutex;
#[cfg(feature = "acpi")]
use crate::acpi::madt::{self, Madt, MadtEntry, MadtIoApic, MadtIntSrcOverride};
use crate::arch::interrupt::irq;
use crate::memory::Frame;
use crate::paging::{KernelMapper, Page, PageFlags, PhysicalAddress, RmmA, RmmArch, VirtualAdd... | <'a>(&'a Mutex<IoApicRegs>);
impl<'a> fmt::Debug for RedirTable<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut guard = self.0.lock();
let count = guard.max_redirection_table_entries();
f.debug_list().entries((0..count).map(|i| g... | RedirTable | identifier_name |
binomial.rs | // Copyright 2018 Developers of the Rand project.
// Copyright 2016-2017 The Rust Project Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. Thi... | for i in results.iter_mut() {
*i = binomial.sample(rng) as f64;
}
let mean = results.iter().sum::<f64>() / results.len() as f64;
assert!(
(mean as f64 - expected_mean).abs() < expected_mean / 50.0,
"mean: {}, expected_mean: {}",
mean,
... | let mut results = [0.0; 1000]; | random_line_split |
binomial.rs | // Copyright 2018 Developers of the Rand project.
// Copyright 2016-2017 The Rust Project Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. Thi... | else {
result
}
}
}
#[cfg(test)]
mod test {
use super::Binomial;
use crate::distributions::Distribution;
use crate::Rng;
fn test_binomial_mean_and_variance<R: Rng>(n: u64, p: f64, rng: &mut R) {
let binomial = Binomial::new(n, p);
let expected_mean = n as f64 ... | {
self.n - result
} | conditional_block |
binomial.rs | // Copyright 2018 Developers of the Rand project.
// Copyright 2016-2017 The Rust Project Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. Thi... | () {
let mut rng = crate::test::rng(351);
test_binomial_mean_and_variance(150, 0.1, &mut rng);
test_binomial_mean_and_variance(70, 0.6, &mut rng);
test_binomial_mean_and_variance(40, 0.5, &mut rng);
test_binomial_mean_and_variance(20, 0.7, &mut rng);
test_binomial_mean_an... | test_binomial | identifier_name |
binomial.rs | // Copyright 2018 Developers of the Rand project.
// Copyright 2016-2017 The Rust Project Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. Thi... |
let lambda_l = lambda((f_m - x_l) / (f_m - x_l * p));
let lambda_r = lambda((x_r - f_m) / (x_r * q));
// p1 + area of left tail
let p3 = p2 + c / lambda_l;
// p1 + area of right tail
let p4 = p3 + c / lambda_r;
// return value
... | {
a * (1. + 0.5 * a)
} | identifier_body |
main.rs | use anyhow::{Result, bail};
use futures::{FutureExt, StreamExt};
use warp::Filter;
use warp::ws::{Message, WebSocket};
use tokio::sync::{mpsc, RwLock};
use std::collections::{HashMap, hash_map};
use std::sync::{
Arc,
atomic::{AtomicUsize, Ordering},
};
use rand::seq::IteratorRandom;
use std::convert::Infallible;
use... | <Card: DeserializeOwned>(filename: &str) -> Result<Vec<Card>, Box<dyn std::error::Error>> {
let file = File::open(filename)?;
Ok(ron::de::from_reader(file)?)
}
fn load_prompts(filename: &str) -> Result<impl Iterator<Item=Prompt>, Box<dyn std::error::Error>> {
Ok(load_deck::<Prompt>(filename)?
.into_iter()
.map(... | load_deck | identifier_name |
main.rs | use anyhow::{Result, bail};
use futures::{FutureExt, StreamExt};
use warp::Filter;
use warp::ws::{Message, WebSocket};
use tokio::sync::{mpsc, RwLock};
use std::collections::{HashMap, hash_map};
use std::sync::{
Arc,
atomic::{AtomicUsize, Ordering},
};
use rand::seq::IteratorRandom;
use std::convert::Infallible;
use... |
// If player is Czar, return submitted answers to owners and restart round
if user_is_czar {
let mut round = game.round.take().unwrap();
game.prompts.discard(&[round.prompt]);
for (id, player) in game.players.iter_mut() {
player.hand.extend(round.answers.remove(id).into_iter().flatten());
}
if g... | {
let game = &mut *game.write().await;
game.clients.remove(&user_id);
if let Some(player) = game.players.remove(&user_id) {
// Discard player's answers
game.answers.discard(&player.hand);
// Discard player's submitted answers, if any
let mut user_is_czar = false;
if let Game {
answers,
round: Some(... | identifier_body |
main.rs | use anyhow::{Result, bail};
use futures::{FutureExt, StreamExt};
use warp::Filter;
use warp::ws::{Message, WebSocket};
use tokio::sync::{mpsc, RwLock};
use std::collections::{HashMap, hash_map};
use std::sync::{
Arc,
atomic::{AtomicUsize, Ordering},
};
use rand::seq::IteratorRandom;
use std::convert::Infallible;
use... | },
}
// Check whether all players have answered
if round.answers.len() == players.len() - 1 {
round.state = RoundState::Judging;
// If so, notify them that JUDGEMENT HAS BEGUN
// TODO maybe obfuscate the player IDs before sending
for id in players.keys() {
clients[id].send(Ws... | random_line_split | |
combat.rs | use crate::components::*;
use crate::map::*;
use crate::NewState;
use bracket_lib::prelude::*;
use legion::systems::CommandBuffer;
use legion::*;
use std::collections::HashSet;
pub fn player_open_fire_at_target(ecs: &mut World, map: &mut Map) -> NewState {
let mut player_entity = None;
let mut target = None;
... | (
ecs: &mut World,
commands: &mut CommandBuffer,
dead_entities: Vec<Entity>,
splatter: &mut Option<RGB>,
) {
dead_entities.iter().for_each(|entity| {
crate::stats::record_death();
let mut was_decor = false;
let mut was_player = false;
if let Ok(mut er) = ecs.entry_mut... | kill_things | identifier_name |
combat.rs | use crate::components::*;
use crate::map::*;
use crate::NewState;
use bracket_lib::prelude::*;
use legion::systems::CommandBuffer;
use legion::*;
use std::collections::HashSet;
pub fn player_open_fire_at_target(ecs: &mut World, map: &mut Map) -> NewState {
let mut player_entity = None;
let mut target = None;
... |
// Set state for the projectile path
let mut power = ranged_power;
let mut range = 0;
let mut projectile_path = Vec::new();
let mut splatter = None;
let mut commands = CommandBuffer::new(ecs);
let current_layer = attacker_pos.layer;
// Map of entity locations. Rebuilt every time becaus... | {
let mut attacker_pos = None;
let mut victim_pos = None;
// Find positions for the start and end
if let Ok(ae) = ecs.entry_ref(attacker) {
if let Ok(pos) = ae.get_component::<Position>() {
attacker_pos = Some(pos.clone());
}
}
if let Ok(ae) = ecs.entry_ref(victim) {... | identifier_body |
combat.rs | use crate::components::*;
use crate::map::*;
use crate::NewState;
use bracket_lib::prelude::*;
use legion::systems::CommandBuffer;
use legion::*;
use std::collections::HashSet;
pub fn player_open_fire_at_target(ecs: &mut World, map: &mut Map) -> NewState {
let mut player_entity = None;
let mut target = None;
... |
// If necessary, kill them.
let mut commands = CommandBuffer::new(ecs);
let mut splatter = None;
kill_things(ecs, &mut commands, dead_entities, &mut splatter);
// Splatter blood. It's good for you.
}
fn kill_things(
ecs: &mut World,
commands: &mut CommandBuffer,
dead_entities: Vec<En... | {
if let Ok(hp) = v.get_component_mut::<Health>() {
hp.current = i32::max(0, hp.current - melee_power);
if hp.current == 0 {
dead_entities.push(victim);
}
}
if let Ok(blood) = v.get_component::<Blood>() {
let idx = map.get_layer(dpo... | conditional_block |
combat.rs | use crate::components::*;
use crate::map::*;
use crate::NewState;
use bracket_lib::prelude::*;
use legion::systems::CommandBuffer;
use legion::*;
use std::collections::HashSet;
pub fn player_open_fire_at_target(ecs: &mut World, map: &mut Map) -> NewState {
let mut player_entity = None;
let mut target = None;
... | },
Glyph {
glyph: to_cp437('*'),
color: ColorPair::new(RED, BLACK),
},
));
commands.flush(ecs);
}
pub fn hit_tile_contents(
ecs: &mut World,
pt: Point,
layer: u32,
commands: &mut CommandBuffer,
splatter: &mut Option<RGB>,
power: i32,
) ->... | layer: current_layer as usize, | random_line_split |
idempotent.rs | //! mut_aliasing -- several links, AT_LEAST one of them is MUTABLE
//! BTW: bunch_of_closures_with_mut_refs is like obj which alias through its params, which is
//! mut_aliased refs on some another obj, or shared data
//! that_is: CLOSURE_CAPUTRING == OBJ.MUT_ALIASED_REFS
|
0
// fns with side-effs: --==... | }
fn fetchOrders(userId) {
ajax( "http://some.api/orders/" + userId, fn onOrders(orders) {
for (let i = 0; i < orders.length; i++) {
// keep a reference to latest order for each user
users[userId].latestOrder = orders[i];
userOrders[orders[i].o... | users[userId] = userData;
}); | random_line_split |
idempotent.rs | //! mut_aliasing -- several links, AT_LEAST one of them is MUTABLE
//! BTW: bunch_of_closures_with_mut_refs is like obj which alias through its params, which is
//! mut_aliased refs on some another obj, or shared data
//! that_is: CLOSURE_CAPUTRING == OBJ.MUT_ALIASED_REFS
|
0
// fns with side-effs: --==... |
// not IDEMPOTENT because: *WRONG: we update, and/but not completly rewrite `x`,
// *RIGHT: mut_aliasing (our computed value for `x` rely on mut_aliased `x`)
// (BUT)
// BTW(p.s.)--v: `some_fn` break rule:
/// "mutate only TREE_in_the_WOOD, emit "own_copied/immutabl" value"
// ... | { x += n*x } | identifier_body |
idempotent.rs | //! mut_aliasing -- several links, AT_LEAST one of them is MUTABLE
//! BTW: bunch_of_closures_with_mut_refs is like obj which alias through its params, which is
//! mut_aliased refs on some another obj, or shared data
//! that_is: CLOSURE_CAPUTRING == OBJ.MUT_ALIASED_REFS
|
0
// fns with side-effs: --==... | (a = [], n) { a.push(n) }
// ^-- here was: "ADD value, not just change."
// BUT actually.. it's also can be considered as MUT_alising.. since result of `push`
// depends of `a`,.. and if we call 2 times `some_fn` of course it's gives different sideeff,
// since its computation based on MUTated value, ("... | some_fn | identifier_name |
routing.rs | //! Functions for adding ingress/egress nodes.
//!
//! In particular:
//!
//! - New nodes that are children of nodes in a different domain must be preceeded by an ingress
//! - Egress nodes must be added to nodes that now have children in a different domain
//! - Egress nodes that gain new children must gain channel... | node::Type::Source => continue,
_ => unreachable!("ingress parent is not egress"),
}
}
}
}
| {
// ensure all egress nodes contain the tx channel of the domains of their child ingress nodes
for &node in new {
let n = &graph[node];
if let node::Type::Ingress = **n {
// check the egress connected to this ingress
} else {
continue;
}
for egr... | identifier_body |
routing.rs | //! Functions for adding ingress/egress nodes.
//!
//! In particular:
//!
//! - New nodes that are children of nodes in a different domain must be preceeded by an ingress
//! - Egress nodes must be added to nodes that now have children in a different domain
//! - Egress nodes that gain new children must gain channel... | (log: &Logger,
graph: &mut Graph,
main_txs: &HashMap<domain::Index, mpsc::SyncSender<Packet>>,
new: &HashSet<NodeIndex>) {
// ensure all egress nodes contain the tx channel of the domains of their child ingress nodes
for &node in new {
let n = &graph[node];
... | connect | identifier_name |
routing.rs | //! Functions for adding ingress/egress nodes.
//!
//! In particular:
//!
//! - New nodes that are children of nodes in a different domain must be preceeded by an ingress
//! - Egress nodes must be added to nodes that now have children in a different domain
//! - Egress nodes that gain new children must gain channel... | // of `node` with the ids of the egress nodes. thus, we actually need to do swaps on
// the values in `swaps`, not insert new entries (that, or we'd need to change the
// resolution process to be recursive, which is painful and unnecessary). note that we
// *also* need to... | let was_materialized = graph.remove_edge(old).unwrap();
graph.add_edge(ingress, node, was_materialized);
// tracking swaps here is a bit tricky because we've already swapped the "true" parents | random_line_split |
main.rs | .danger_accept_invalid_certs(true)
.build()
.unwrap()
.get("https://www.google.de/")
.send()
.unwrap()
.text()
.unwrap();*/
println!("body = {}", body.lines().take(3).collect::<String>()... | {
/* extern crate openssl;
println!("===== testOpenSSL =====");
use openssl::ssl::{SslConnector, SslMethod};
use std::io::{Read, Write};
use std::net::TcpStream;
let connector = SslConnector::builder(SslMethod::tls()).unwrap().build();
let stream = TcpStream::connect("google.com:443").... | identifier_body | |
main.rs | (uri: &Uri) -> String {
//let in_addr: SocketAddr = get_in_addr();
let uri_string = uri.path_and_query().map(|x| x.as_str()).unwrap_or("");
//let uri: String = uri_string.parse().unwrap();
//let in_uri_string = format!("http://{}/{}", in_addr, req.uri());
let in_remove_string = "/fwd/";
debug!(... | reduce_forwarded_uri | identifier_name | |
main.rs | u00a1-\uffff_-]{0,62})?[a-z0-9\u00a1-\uffff]\.)+(?:[a-z\u00a1-\uffff]{2,}\.?))(?::\d{2,5})?(?:[/?#]\S*)?$/i"
//r"(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[... | if len > 0 {
//Ok(Some(buf.iter().take(32).freeze().into()))
Ok(Some(buf.iter().take(32).into()))
} else {
Ok(None)
}
}
let akjsd = decode(chunks);*/
use bytes::{BigEndian, B... | random_line_split | |
mod.rs | memory::ByteValued;
use crate::abi::linux_abi as fuse;
use crate::api::filesystem::Entry;
use crate::api::{BackendFileSystem, VFS_MAX_INO};
#[cfg(feature = "async-io")]
mod async_io;
mod sync_io;
mod multikey;
use multikey::MultikeyBTreeMap;
use crate::async_util::AsyncDrive;
const CURRENT_DIR_CSTR: &[u8] = b".\0"... | if fd < 0 {
return Err(io::Error::last_os_error());
}
// Safe because we just opened this fd.
Ok(unsafe { File::from_raw_fd(fd) })
}
fn do_lookup(&self, parent: Inode, name: &CStr) -> io::Result<Entry> {
let p = self.inode_map.get(parent)?;
let f = Se... | unsafe { libc::openat(dfd, pathname.as_ptr(), flags) }
};
| conditional_block |
mod.rs | use std::mem::MaybeUninit;
use std::os::unix::io::{AsRawFd, FromRawFd, RawFd};
use std::str::FromStr;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, RwLock, RwLockWriteGuard};
use std::time::Duration;
use vm_memory::ByteValued;
use crate::abi::linux_abi as fuse;
use ... | use std::ffi::{CStr, CString};
use std::fs::File;
use std::io;
use std::marker::PhantomData; | random_line_split | |
mod.rs | {
inode,
file,
refcount: AtomicU64::new(refcount),
}
}
// When making use of the underlying RawFd, the caller must ensure that the Arc<InodeData>
// object is within scope. Otherwise it may cause race window to access wrong target fd.
// By introducing this ... | elease(&se | identifier_name | |
mod.rs | memory::ByteValued;
use crate::abi::linux_abi as fuse;
use crate::api::filesystem::Entry;
use crate::api::{BackendFileSystem, VFS_MAX_INO};
#[cfg(feature = "async-io")]
mod async_io;
mod sync_io;
mod multikey;
use multikey::MultikeyBTreeMap;
use crate::async_util::AsyncDrive;
const CURRENT_DIR_CSTR: &[u8] = b".\0"... | impl Default for CachePolicy {
fn default() -> Self {
CachePolicy::Auto
}
}
/// Options that configure the behavior of the passthrough fuse file system.
#[derive(Debug, Clone, PartialEq)]
pub struct Config {
/// How long the FUSE client should consider directory entries to be valid. If the contents... | match s {
"never" | "Never" | "NEVER" | "none" | "None" | "NONE" => Ok(CachePolicy::Never),
"auto" | "Auto" | "AUTO" => Ok(CachePolicy::Auto),
"always" | "Always" | "ALWAYS" => Ok(CachePolicy::Always),
_ => Err("invalid cache policy"),
}
}
}
| identifier_body |
mod.rs | //! A builder for a Fletcher-like algorithm.
//!
//! The basic functionality of this algorithm is:
//! * there is a sum which is just the bytes summed modulo some number
//! * there is also a second sum which the sum of all of the normal sums (modulo the same number)
//!
//! Note that text word sizes are currently only... |
/// The endian of the words of the input file
pub fn inendian(&mut self, e: Endian) -> &mut Self {
self.input_endian = Some(e);
self
}
/// The number of bits in a word of the input file
pub fn wordsize(&mut self, n: usize) -> &mut Self {
self.wordsize = Some(n);
self... | {
self.swap = Some(s);
self
} | identifier_body |
mod.rs | //! A builder for a Fletcher-like algorithm.
//!
//! The basic functionality of this algorithm is:
//! * there is a sum which is just the bytes summed modulo some number
//! * there is also a second sum which the sum of all of the normal sums (modulo the same number)
//!
//! Note that text word sizes are currently only... | (&mut self, e: Endian) -> &mut Self {
self.input_endian = Some(e);
self
}
/// The number of bits in a word of the input file
pub fn wordsize(&mut self, n: usize) -> &mut Self {
self.wordsize = Some(n);
self
}
/// The endian of the checksum
pub fn outendian(&mut se... | inendian | identifier_name |
mod.rs | //! A builder for a Fletcher-like algorithm.
//!
//! The basic functionality of this algorithm is:
//! * there is a sum which is just the bytes summed modulo some number
//! * there is also a second sum which the sum of all of the normal sums (modulo the same number)
//!
//! Note that text word sizes are currently only... | }
} | random_line_split | |
mod.rs | //! A builder for a Fletcher-like algorithm.
//!
//! The basic functionality of this algorithm is:
//! * there is a sum which is just the bytes summed modulo some number
//! * there is also a second sum which the sum of all of the normal sums (modulo the same number)
//!
//! Note that text word sizes are currently only... | ;
fletch.addout = fletch.to_compact((s, c));
match self.check {
Some(chk) => {
if fletch.digest(&b"123456789"[..]).unwrap()!= chk {
println!("{:x?}", fletch.digest(&b"123456789"[..]).unwrap());
Err(CheckBuilderErr::CheckFail)
... | {
fletch.init = init;
} | conditional_block |
rainstorm.rs | #![feature(macro_rules, intrinsics, lang_items, globs)]
#![no_std]
extern crate libc;
extern crate core;
extern crate alloc;
extern crate collections;
extern crate rand;
pub use core::prelude::*;
pub use cheats::{Cheat, CheatManager};
pub use alloc::owned::Box;
pub use collections::Vec;
use core::raw::Repr;
mod log... | #[no_mangle]
pub unsafe extern "C" fn rainstorm_extramousesample(input_sample_frametime: libc::c_float, active: bool) {
if cheats::CHEAT_MANAGER.is_not_null() {
(*cheats::CHEAT_MANAGER).extramousesample(input_sample_frametime, active);
} else {
quit!("Cheat manager not found!\n");
};
}
#[no_mangle]
pub extern "... | }
| random_line_split |
rainstorm.rs | #![feature(macro_rules, intrinsics, lang_items, globs)]
#![no_std]
extern crate libc;
extern crate core;
extern crate alloc;
extern crate collections;
extern crate rand;
pub use core::prelude::*;
pub use cheats::{Cheat, CheatManager};
pub use alloc::owned::Box;
pub use collections::Vec;
use core::raw::Repr;
mod log... |
#[allow(non_snake_case_functions)]
#[no_mangle]
pub extern "C" fn _imp___onexit() {
}
#[no_mangle]
pub extern "C" fn __dllonexit() {
}
#[no_mangle]
pub extern "C" fn __setusermatherr() {
} | {
log!("Failed at line {} of {}!\n", line, file);
let _ = logging::log_fmt(fmt).ok(); // if we fail here, god help us
unsafe { libc::exit(42); }
} | identifier_body |
rainstorm.rs | #![feature(macro_rules, intrinsics, lang_items, globs)]
#![no_std]
extern crate libc;
extern crate core;
extern crate alloc;
extern crate collections;
extern crate rand;
pub use core::prelude::*;
pub use cheats::{Cheat, CheatManager};
pub use alloc::owned::Box;
pub use collections::Vec;
use core::raw::Repr;
mod log... | (c_arguments: *const libc::c_char) {
let arguments_str = unsafe { core::str::raw::c_str_to_static_slice(c_arguments) };
log!("Command callback: {}\n", arguments_str);
let mut parts_iter = arguments_str.split(' ');
let command = parts_iter.next().expect("No command type specified!");
let parts: collections::Vec<&... | rainstorm_command_cb | identifier_name |
rainstorm.rs | #![feature(macro_rules, intrinsics, lang_items, globs)]
#![no_std]
extern crate libc;
extern crate core;
extern crate alloc;
extern crate collections;
extern crate rand;
pub use core::prelude::*;
pub use cheats::{Cheat, CheatManager};
pub use alloc::owned::Box;
pub use collections::Vec;
use core::raw::Repr;
mod log... | else {
quit!("Cheat manager not found!\n");
};
}
#[no_mangle]
pub unsafe extern "C" fn rainstorm_process_usercmd(cmd: &mut sdk::CUserCmd) {
if cheats::CHEAT_MANAGER.is_not_null() {
maybe_hook_inetchannel((*cheats::CHEAT_MANAGER).get_gamepointers());
(*cheats::CHEAT_MANAGER).process_usercmd(cmd);
} else {
q... | {
(*cheats::CHEAT_MANAGER).pre_createmove(sequence_number, input_sample_frametime, active);
} | conditional_block |
cli.rs | // Copyright (c) 2016 Chef Software Inc. and/or applicable contributors
//
// 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 r... | else {
para(&format!("You might want to create an origin key later with: `hab \
origin key generate {}'",
&origin));
}
}
} else {
para("Okay, maybe another time.");
}
... | {
try!(create_origin(&origin, cache_path));
generated_origin = true;
} | conditional_block |
cli.rs | // Copyright (c) 2016 Chef Software Inc. and/or applicable contributors
//
// 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 r... | (origin: &str, cache_path: &Path) -> bool {
match SigKeyPair::get_latest_pair_for(origin, cache_path) {
Ok(pair) => {
match pair.secret() {
Ok(_) => true,
_ => false,
}
}
_ => false,
}
}
... | is_origin_in_cache | identifier_name |
cli.rs | // Copyright (c) 2016 Chef Software Inc. and/or applicable contributors
//
// 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 r... | try!(io::stdin().read_line(&mut response));
match response.trim().chars().next().unwrap_or('\n') {
'y' | 'Y' => return Ok(true),
'n' | 'N' => return Ok(false),
'q' | 'Q' => process::exit(0),
'\n' => {
match defau... | let mut response = String::new(); | random_line_split |
cli.rs | // Copyright (c) 2016 Chef Software Inc. and/or applicable contributors
//
// 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 r... |
fn opt_in_analytics(analytics_path: &Path, generated_origin: bool) -> Result<()> {
let result = analytics::opt_in(analytics_path, generated_origin);
println!("");
result
}
fn opt_out_analytics(analytics_path: &Path) -> Result<()> {
let result = analytics::opt_out(analytics... | {
let default = match analytics::is_opted_in(analytics_path) {
Some(val) => Some(val),
None => Some(true),
};
prompt_yes_no("Enable analytics?", default)
} | identifier_body |
main.rs | #![allow(dead_code)]
extern crate libc;
extern crate time;
extern crate rand;
extern crate toml;
extern crate serde_json;
#[macro_use] extern crate serde_derive;
extern crate colored;
#[macro_use] extern crate prettytable;
extern crate ctrlc;
extern crate clap;
use clap::{Arg, App};
use std::sync::atomic::{AtomicBool... | s >= max_children { break; }
}
q.return_test(active_test.id, history);
q.save_latest(statistics.take_snapshot());
if canceled.load(Ordering::SeqCst) {
println!("User interrupted fuzzing. Going to shut down....");
break;
}
}
server.sync();
while let Some(feedback) = server.pop_coverage() {
let rr =... | { println!("invalid input...."); }
let (info, interesting_input) = server.get_info(feedback.id);
let now = get_time();
statistics.update_new_discovery(info.mutator.id, now, analysis.get_bitmap());
q.add_new_test(interesting_input, info, rr.new_cov,
!rr.is_invalid, now,
... | conditional_block |
main.rs | #![allow(dead_code)]
extern crate libc;
extern crate time;
extern crate rand;
extern crate toml;
extern crate serde_json;
#[macro_use] extern crate serde_derive;
extern crate colored;
#[macro_use] extern crate prettytable;
extern crate ctrlc;
extern crate clap;
use clap::{Arg, App};
use std::sync::atomic::{AtomicBool... | me();
std::time::Duration::new(raw.sec as u64, raw.nsec as u32)
} | identifier_body | |
main.rs | #![allow(dead_code)]
extern crate libc;
extern crate time;
extern crate rand;
extern crate toml;
extern crate serde_json;
#[macro_use] extern crate serde_derive;
extern crate colored;
#[macro_use] extern crate prettytable;
extern crate ctrlc;
extern crate clap;
use clap::{Arg, App};
use std::sync::atomic::{AtomicBool... | {
toml_config: String,
print_queue: bool,
print_total_cov: bool,
skip_deterministic: bool,
skip_non_deterministic: bool,
random: bool,
input_directory: Option<String>,
output_directory: String,
test_mode: bool,
jqf: analysis::JQFLevel,
fuzz_server_id: String,
seed_cycles: usize,
}
fn main() {
let matches... | Args | identifier_name |
main.rs | #![allow(dead_code)]
extern crate libc;
extern crate time;
extern crate rand;
extern crate toml;
extern crate serde_json;
#[macro_use] extern crate serde_derive;
extern crate colored;
#[macro_use] extern crate prettytable;
extern crate ctrlc;
extern crate clap;
use clap::{Arg, App};
use std::sync::atomic::{AtomicBool... | } else {
fuzzer(args, canceled, config, test_size, &mut server);
}
}
fn test_mode(server: &mut FuzzServer, config: &config::Config) {
println!("⚠️ Test mode selected! ⚠️");
test::test_fuzz_server(server, config);
}
fn fuzzer(args: Args, canceled: Arc<AtomicBool>, config: config::Config,
test_size: run... | let server_dir = format!("{}/{}", FPGA_DIR, args.fuzz_server_id);
let mut server = find_one_fuzz_server(&server_dir, srv_config).expect("failed to find a fuzz server");
if args.test_mode {
test_mode(&mut server, &config); | random_line_split |
http_remote.rs | stripped should still be valid");
Ok(HttpRegistry {
index_path: config.registry_index_path().join(name),
cache_path: config.registry_cache_path().join(name),
source_id,
config,
url,
multi: Multi::new(),
multiplexing: false,
... | (buf: &[u8]) -> Option<(&str, &str)> {
if buf.is_empty() {
return None;
}
let buf = std::str::from_utf8(buf).ok()?.trim_end();
// Don't let server sneak extra lines anywhere.
if buf.contains('\n') {
return None;
}
let (tag, value) = buf.spl... | handle_http_header | identifier_name |
http_remote.rs | + stripped should still be valid");
Ok(HttpRegistry {
index_path: config.registry_index_path().join(name),
cache_path: config.registry_cache_path().join(name),
source_id,
config,
url,
multi: Multi::new(),
multiplexing: false,
... | } else {
UNKNOWN.to_string()
};
trace!("index file version: {}", response_index_version);
return Poll::Ready(Ok(LoadResponse::Data {
raw_data: result.data,
index_versio... | format!("{}: {}", ETAG, etag)
} else if let Some(lm) = result.header_map.last_modified {
format!("{}: {}", LAST_MODIFIED, lm) | random_line_split |
http_remote.rs | stripped should still be valid");
Ok(HttpRegistry {
index_path: config.registry_index_path().join(name),
cache_path: config.registry_cache_path().join(name),
source_id,
config,
url,
multi: Multi::new(),
multiplexing: false,
... | let (mut download, handle) = self.downloads.pending.remove(&token).unwrap();
let was_present = self.downloads.pending_paths.remove(&download.path);
assert!(
was_present,
"expected pending_paths to contain {:?}",
download.path
... | {
assert_eq!(
self.downloads.pending.len(),
self.downloads.pending_paths.len()
);
// Collect the results from the Multi handle.
let results = {
let mut results = Vec::new();
let pending = &mut self.downloads.pending;
self.multi... | identifier_body |
lexer.rs | //! Lexer implementation
use std::borrow::Cow::Borrowed;
use std::borrow::{Borrow, Cow};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use crate::char_stream::{CharStream, InputData};
use crate::error_listener::{ConsoleErrorListener, ErrorListener};
use crate::errors::ANTLRError;
use crate::int_stream::IntStream;
... |
}
impl<'input, T, Input, TF> DerefMut for BaseLexer<'input, T, Input, TF>
where
T: LexerRecog<'input, Self> +'static,
Input: CharStream<TF::From>,
TF: TokenFactory<'input>,
{
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.recog
}
}
impl<'input, T, Input, TF> Recognizer<'input> f... | {
&self.recog
} | identifier_body |
lexer.rs | //! Lexer implementation
use std::borrow::Cow::Borrowed;
use std::borrow::{Borrow, Cow};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use crate::char_stream::{CharStream, InputData};
use crate::error_listener::{ConsoleErrorListener, ErrorListener};
use crate::errors::ANTLRError;
use crate::int_stream::IntStream;
... |
if self.token_type == TOKEN_INVALID_TYPE {
self.token_type = ttype;
}
if self.token_type == LEXER_SKIP {
continue 'outer;
}
if self.token_type!= LEXER_MORE {
break;
... | {
self.hit_eof = true;
} | conditional_block |
lexer.rs | //! Lexer implementation
use std::borrow::Cow::Borrowed;
use std::borrow::{Borrow, Cow};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use crate::char_stream::{CharStream, InputData};
use crate::error_listener::{ConsoleErrorListener, ErrorListener};
use crate::errors::ANTLRError;
use crate::int_stream::IntStream;
... | lexer.token_start_column,
&text,
Some(e),
)
}
}
impl<'input, T, Input, TF> Lexer<'input> for BaseLexer<'input, T, Input, TF>
where
T: LexerRecog<'input, Self> +'static,
Input: CharStream<TF::From>,
TF: TokenFactory<'input>,
{
type Input = Input;
fn i... | listener.syntax_error(
lexer,
None,
lexer.token_start_line, | random_line_split |
lexer.rs | //! Lexer implementation
use std::borrow::Cow::Borrowed;
use std::borrow::{Borrow, Cow};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use crate::char_stream::{CharStream, InputData};
use crate::error_listener::{ConsoleErrorListener, ErrorListener};
use crate::errors::ANTLRError;
use crate::int_stream::IntStream;
... | (&mut self, _text: <TF::Data as ToOwned>::Owned) {
self.text = Some(_text);
}
// fn get_all_tokens(&mut self) -> Vec<TF::Tok> { unimplemented!() }
// fn get_char_error_display(&self, _c: char) -> String { unimplemented!() }
/// Add error listener
pub fn add_error_listener(&mut self, liste... | set_text | identifier_name |
dwarfdebuginfo.rs | // Copyright 2021-2023 Vector 35 Inc.
//
// 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... |
Some((name, uid)) => Some(FunctionParameter::new(
self.get_type(*uid).unwrap().1,
name.clone(),
None,
)),
_ => None,
})
.collect();
// TODO : H... | {
Some(FunctionParameter::new(Type::void(), name.clone(), None))
} | conditional_block |
dwarfdebuginfo.rs | // Copyright 2021-2023 Vector 35 Inc.
//
// 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... |
pub fn set_name(&mut self, die_uid: TypeUID, name: CString) {
assert!(self.names.insert(die_uid, name).is_none());
}
pub fn get_name<R: Reader<Offset = usize>>(
&self,
dwarf: &Dwarf<R>,
unit: &Unit<R>,
entry: &DebuggingInformationEntry<R>,
) -> Option<CString> ... | {
if let Some((_existing_name, existing_type_uid)) =
self.data_variables.insert(address, (name, type_uid))
{
let existing_type = self.get_type(existing_type_uid).unwrap().1;
let new_type = self.get_type(type_uid).unwrap().1;
if existing_type_uid != type_u... | identifier_body |
dwarfdebuginfo.rs | // Copyright 2021-2023 Vector 35 Inc.
//
// 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... | (view: &BinaryView) -> Self {
DebugInfoBuilder {
functions: vec![],
types: HashMap::new(),
data_variables: HashMap::new(),
names: HashMap::new(),
default_address_size: view.address_size(),
}
}
pub fn default_address_size(&self) -> usiz... | new | identifier_name |
dwarfdebuginfo.rs | // Copyright 2021-2023 Vector 35 Inc.
//
// 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... | raw_name: Option<CString>,
return_type: Option<TypeUID>,
address: Option<u64>,
parameters: Vec<Option<(CString, TypeUID)>>,
) {
if let Some(function) = self.functions.iter_mut().find(|func| {
(func.raw_name.is_some() && func.raw_name == raw_name)
|... | &mut self,
full_name: Option<CString>, | random_line_split |
intcode.rs | //! # Day 2 1202 Program Alarm
//!
//! ## Part 1
//!
//! On the way to your gravity assist around the Moon, your ship computer beeps
//! angrily about a "1202 program alarm". On the radio, an Elf is already
//! explaining how to handle the situation: "Don't worry, that's perfectly norma--"
//!
//! The ship computer bur... | //! other words, don't reuse memory from a previous attempt.
//!
//! Find the input noun and verb that cause the program to produce the output
//! 19690720. What is 100 * noun + verb? (For example, if noun=12 and verb=2,
//! the answer would be 1202.)
//!
//! # Day 5: Sunny with a Chance of Asteroids
//!
//! ## Part 1
... | //! like before. Each time you try a pair of inputs, make sure you first reset
//! the computer's memory to the values in the program (your puzzle input) - in | random_line_split |
intcode.rs | //! # Day 2 1202 Program Alarm
//!
//! ## Part 1
//!
//! On the way to your gravity assist around the Moon, your ship computer beeps
//! angrily about a "1202 program alarm". On the radio, an Elf is already
//! explaining how to handle the situation: "Don't worry, that's perfectly norma--"
//!
//! The ship computer bur... | ((mode, value): (usize, i32)) -> Self {
match mode {
0 => Param::Position(value as usize),
1 => Param::Immediate(value),
_ => unreachable!(),
}
}
}
#[derive(Debug)]
enum Op {
Add { a: Param, b: Param, out: usize },
Multiply { a: Param, b: Param, out: usiz... | from_pair | identifier_name |
intcode.rs | //! # Day 2 1202 Program Alarm
//!
//! ## Part 1
//!
//! On the way to your gravity assist around the Moon, your ship computer beeps
//! angrily about a "1202 program alarm". On the radio, an Elf is already
//! explaining how to handle the situation: "Don't worry, that's perfectly norma--"
//!
//! The ship computer bur... | i += 2;
}
Op::Output { value } => {
let value = read_value(value, data).unwrap();
println!("offset={}, value={}", i, value);
i += 2;
}
Op::Halt => break,
_ => unreachable!(),
}
}
}
/... | {
let mut i = 0;
loop {
// FIXME: make read_instruction an iterator so it can manage the increment internally
match read_instruction(i, &data) {
Op::Add { a, b, out } => {
let a = read_value(a, data).unwrap();
let b = read_value(b, data).unwrap();
... | identifier_body |
com.rs | //! Common utilities
//!
//! A standard vocabulary used throughout the code.
use std::{self, cmp, convert, fmt, hash, iter, marker, num, ops, sync};
use crate::basic::sea::TableIndex;
/// A fragment of source code.
#[derive(Clone)]
pub struct CodeFragment(sync::Arc<Vec<u8>>);
impl CodeFragment {
/// Creates a n... | }
/// Skips n from the left.
pub fn skip_left(self, n: usize) -> Range {
Range {
offset: self.offset + (n as u32),
length: self.length - (n as u32),
}
}
/// Skips n from the right.
pub fn skip_right(self, n: usize) -> Range {
Range {
... | /// Shifts range to specified offset.
pub fn shift_to(self, offset: usize) -> Range {
Range { offset: offset as u32, ..self } | random_line_split |
com.rs | //! Common utilities
//!
//! A standard vocabulary used throughout the code.
use std::{self, cmp, convert, fmt, hash, iter, marker, num, ops, sync};
use crate::basic::sea::TableIndex;
/// A fragment of source code.
#[derive(Clone)]
pub struct CodeFragment(sync::Arc<Vec<u8>>);
impl CodeFragment {
/// Creates a n... | (&self) -> u32 { self.0.get() - 1 }
}
impl fmt::Debug for CoreId {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "{}", self.raw())
}
}
impl Default for CoreId {
fn default() -> CoreId {
unsafe { CoreId(num::NonZeroU32::new_unchecked(std::u32::MAX)) }
}
}
... | raw | identifier_name |
com.rs | //! Common utilities
//!
//! A standard vocabulary used throughout the code.
use std::{self, cmp, convert, fmt, hash, iter, marker, num, ops, sync};
use crate::basic::sea::TableIndex;
/// A fragment of source code.
#[derive(Clone)]
pub struct CodeFragment(sync::Arc<Vec<u8>>);
impl CodeFragment {
/// Creates a n... |
#[test]
fn range_extend_reversed() {
let result = Range::new(5, 3).extend(Range::new(3, 4));
assert_eq!(result, Range::new(3, 5));
}
}
| {
let result = Range::new(3, 4).extend(Range::new(5, 2));
assert_eq!(result, Range::new(3, 4));
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.