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 |
|---|---|---|---|---|
lib.rs | This module re-exports everything and includes free functions for all traits methods doing
out-of-place modifications.
* You can import the whole prelude using:
```.ignore
use nalgebra::*;
```
The preferred way to use **nalgebra** is to import types and traits explicitly, and call
free-functions using the `na::` pre... | /// Returns the squared distance between two points.
#[inline(always)]
pub fn sqdist<N: BaseFloat, P: FloatPnt<N, V>, V: Norm<N>>(a: &P, b: &P) -> N {
a.sqdist(b)
}
/*
* Translation<V>
*/
/// Gets the translation applicable by `m`.
///
/// ```rust
/// extern crate nalgebra as na;
/// use na::{Vec3, Iso3};
///
/... | a.dist(b)
}
| identifier_body |
lib.rs |
This module re-exports everything and includes free functions for all traits methods doing
out-of-place modifications.
* You can import the whole prelude using:
```.ignore
use nalgebra::*;
```
The preferred way to use **nalgebra** is to import types and traits explicitly, and call
free-functions using the `na::` pr... | /// }
/// ```
#[inline(always)]
pub fn translate<P, M: Translate<P>>(m: &M, p: &P) -> P {
m.translate(p)
}
/// Applies an inverse translation to a point.
///
/// ```rust
/// extern crate nalgebra as na;
/// use na::{Pnt3, Vec3, Iso3};
///
/// fn main() {
/// let t = Iso3::new(Vec3::new(1.0f64, 1.0, 1.0), na::... | random_line_split | |
lib.rs | This module re-exports everything and includes free functions for all traits methods doing
out-of-place modifications.
* You can import the whole prelude using:
```.ignore
use nalgebra::*;
```
The preferred way to use **nalgebra** is to import types and traits explicitly, and call
free-functions using the `na::` pre... | else {
max
}
}
else {
min
}
}
/// Same as `cmp::max`.
#[inline(always)]
pub fn max<T: Ord>(a: T, b: T) -> T {
cmp::max(a, b)
}
/// Same as `cmp::min`.
#[inline(always)]
pub fn min<T: Ord>(a: T, b: T) -> T {
cmp::min(a, b)
}
/// Returns the infimum of `a` and `b`... | val
}
| conditional_block |
utils.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::collections::HashMap;
use std::collections::HashSet;
use std::sync::Mutex;
use futures::future::BoxFuture;
use futures::TryStream... | (name: impl ToString) -> Vertex {
Vertex::copy_from(name.to_string().as_bytes())
}
}
| v | identifier_name |
utils.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::collections::HashMap;
use std::collections::HashSet;
use std::sync::Mutex;
use futures::future::BoxFuture;
use futures::TryStream... |
to_visit.push(p);
}
}
}
false
}
}
let state: Mutex<State> = Default::default();
move |v: Vertex| -> Result<Vec<Vertex>> {
let mut state = state.lock().unwrap();
if let Some(parents) = state.known.ge... | {
return true;
} | conditional_block |
utils.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::collections::HashMap;
use std::collections::HashSet;
use std::sync::Mutex;
use futures::future::BoxFuture;
use futures::TryStream... | return true;
}
to_visit.push(p);
}
}
}
false
}
}
let state: Mutex<State> = Default::default();
move |v: Vertex| -> Result<Vec<Vertex>> {
let mut state = st... | if let Some(parents) = self.known.get(&v) {
for p in parents {
if p == ancestor { | random_line_split |
utils.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::collections::HashMap;
use std::collections::HashSet;
use std::sync::Mutex;
use futures::future::BoxFuture;
use futures::TryStream... |
#[test]
fn test_break_parent_func_cycle_linear() -> Result<()> {
let parent_func = |n: Vertex| -> Result<Vec<Vertex>> {
let list = "0123456789".chars().map(|c| v(c)).collect::<Vec<_>>();
let parents = match list.iter().position(|x| x == &n) {
Some(i) if i > 0 =>... | {
let parent_func = |n: Vertex| -> Result<Vec<Vertex>> { Ok(vec![n, v("1"), v("2")]) };
let parent_func_no_cycle = break_parent_func_cycle(parent_func);
assert_eq!(parent_func_no_cycle(v("A"))?, vec![v("1"), v("2")]);
assert_eq!(parent_func_no_cycle(v("1"))?, vec![v("2")]);
asser... | identifier_body |
object_header.rs | //! A generic header for every Git object.
use object_type::ObjectType;
use object_type;
use reader::Reader;
use std::str::FromStr;
use error::GitError;
use error::GitError::CorruptObject;
#[deriving(PartialEq, Show, Clone)]
pub struct ObjectHeader {
pub typ: ObjectType,
pub length: uint
}
imp... | {
let mut reader = Reader::from_data(bytes);
let typ = try!(object_type::from_text(reader.take_string_while(|c| *c != 32).unwrap_or("")));
reader.skip(1);
let length: uint = try!(
FromStr::from_str(reader.take_string_while(|c| *c != 0).unwrap_or(""))
.ok_or(CorruptObject(... | identifier_body | |
object_header.rs | //! A generic header for every Git object.
use object_type::ObjectType;
use object_type;
use reader::Reader;
use std::str::FromStr;
use error::GitError;
use error::GitError::CorruptObject;
#[deriving(PartialEq, Show, Clone)]
pub struct ObjectHeader {
pub typ: ObjectType,
pub length: uint
}
imp... |
reader.skip(1);
let length: uint = try!(
FromStr::from_str(reader.take_string_while(|c| *c!= 0).unwrap_or(""))
.ok_or(CorruptObject("invalid header length".into_cow()))
);
Ok(ObjectHeader {
typ: typ,
length: length
})
} | random_line_split | |
object_header.rs | //! A generic header for every Git object.
use object_type::ObjectType;
use object_type;
use reader::Reader;
use std::str::FromStr;
use error::GitError;
use error::GitError::CorruptObject;
#[deriving(PartialEq, Show, Clone)]
pub struct ObjectHeader {
pub typ: ObjectType,
pub length: uint
}
imp... | (&self) -> Vec<u8> {
let mut buff = Vec::new();
buff.push_all(format!("{} ", self.typ.to_text()).into_bytes().as_slice());
buff.push_all(format!("{}", self.length).into_bytes().as_slice());
buff.push(0x00);
buff
}
}
pub fn decode(bytes: &[u8]) -> Result<ObjectHe... | encode | identifier_name |
error.rs | /* Error type based on the error type from es-rs:
*
* Copyright 2015-2018 Ben Ashford
*
* 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.... |
}
impl From<BuildError> for Error {
fn from(err: BuildError) -> Error {
Error::Build(err)
}
}
impl error::Error for Error {
#[allow(warnings)]
fn description(&self) -> &str {
match *self {
Error::Build(ref err) => err.description(),
Error::Lib(ref err) => err,
... | {
Error::Lib(err.to_string())
} | identifier_body |
error.rs | /* Error type based on the error type from es-rs:
*
* Copyright 2015-2018 Ben Ashford
*
* 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.... | (err: reqwest::Error) -> Error {
Error::Http(err)
}
}
impl From<serde_json::error::Error> for Error {
fn from(err: serde_json::error::Error) -> Error {
Error::Json(err)
}
}
impl From<url::ParseError> for Error {
fn from(err: url::ParseError) -> Error {
Error::Lib(err.to_string(... | from | identifier_name |
error.rs | /* Error type based on the error type from es-rs:
*
* Copyright 2015-2018 Ben Ashford
*
* 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.... | Lib(String),
/// HTTP library error
Http(reqwest::Error),
/// IO error
Io(io::Error),
/// JSON error
Json(serde_json::error::Error),
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Error {
Error::Io(err)
}
}
impl From<reqwest::Error> for Error {
fn from... |
/// A general error from this library | random_line_split |
defs.rs | //! Various definitions of types, constants, traint,... related to network
use core::fmt::{
Binary,
Octal,
LowerHex,
UpperHex,
Debug,
Display,
Formatter,
Error
};
use core::str::FromStr;
use vec::Vec;
use num::PrimInt;
use net::Packet;
/// Type of the ether_type
pub type EtherType ... |
let mut ret = Self::empty();
for (i, b) in split.iter().enumerate() {
let bytes = b.as_bytes();
if bytes.len()!= 2 {
return Err(())
}
let d1 = try!(b.char_at(0).to_digit(16).ok_or(())) * 16;
let d2 = try!(b.char_at(1).to_di... | {
return Err(())
} | conditional_block |
defs.rs | //! Various definitions of types, constants, traint,... related to network
use core::fmt::{
Binary,
Octal,
LowerHex,
UpperHex,
Debug,
Display,
Formatter,
Error
};
use core::str::FromStr;
use vec::Vec;
use num::PrimInt;
use net::Packet;
/// Type of the ether_type
pub type EtherType ... | /// Construct from an integer represented using host's endianness
pub fn from_host(i: T) -> Self {
Int(i.to_be())
}
/// Returns the contained integer using host's endianness
pub fn as_host(&self) -> T {
T::from_be(self.0.clone())
}
/// Returns the contained integer using ne... | random_line_split | |
defs.rs | //! Various definitions of types, constants, traint,... related to network
use core::fmt::{
Binary,
Octal,
LowerHex,
UpperHex,
Debug,
Display,
Formatter,
Error
};
use core::str::FromStr;
use vec::Vec;
use num::PrimInt;
use net::Packet;
/// Type of the ether_type
pub type EtherType ... | (&self) -> bool {
*self == Self::broadcast()
}
/// Create an hardware address from bytes.
///
/// This method is unsafe because the slice *MUST* contain at least 6
/// elements.
pub unsafe fn from_bytes(bytes: &[u8]) -> Self {
let mut ret = Self::empty();
ret.bytes[0] =... | is_broadcast | identifier_name |
htmlselectelement.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 dom::attr::Attr;
use dom::attr::AttrHelpers;
use dom::bindings::codegen::Bindings::HTMLSelectElementBinding;
u... |
}
}
| {
node.check_disabled_attribute();
} | conditional_block |
htmlselectelement.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 dom::attr::Attr;
use dom::attr::AttrHelpers;
use dom::bindings::codegen::Bindings::HTMLSelectElementBinding;
u... | fn after_set_attr(&self, attr: JSRef<Attr>) {
if let Some(ref s) = self.super_type() {
s.after_set_attr(attr);
}
match attr.local_name() {
&atom!("disabled") => {
let node: JSRef<Node> = NodeCast::from_ref(*self);
node.set_disabled_sta... | random_line_split | |
htmlselectelement.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 dom::attr::Attr;
use dom::attr::AttrHelpers;
use dom::bindings::codegen::Bindings::HTMLSelectElementBinding;
u... | (localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLSelectElement> {
let element = HTMLSelectElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLSelectElementBinding::Wrap)
}
}
impl<'a> HTMLSelectElementMethods... | new | identifier_name |
build.rs | extern crate cc;
use std::path::{ PathBuf, Path };
use std::process::Command;
struct Perl {
bin: String,
}
impl Perl {
fn new() -> Perl {
Perl {
bin: std::env::var("PERL").unwrap_or("perl".to_owned()),
}
}
fn cfg(&self, key: &str) -> String {
let out = Command::ne... |
if perl.cfg("useshrplib") == "true" {
println!("cargo:rustc-cfg=perl_useshrplib");
// Make sure ld links to libperl that matches current perl interpreter, instead of whatever
// is libperl version exists in default linker search path. $archlibexp/CORE is hard-coded
// installation... | {
println!("cargo:rustc-cfg=perl_multiplicity");
} | conditional_block |
build.rs | extern crate cc;
use std::path::{ PathBuf, Path };
use std::process::Command;
struct Perl {
bin: String,
}
impl Perl {
fn new() -> Perl {
Perl {
bin: std::env::var("PERL").unwrap_or("perl".to_owned()),
}
}
fn cfg(&self, key: &str) -> String {
let out = Command::ne... | (&self) -> PathBuf {
let archlib = self.cfg("archlibexp");
Path::new(&archlib).join("CORE")
}
}
fn build(perl: &Perl) {
let mut cc = cc::Build::new();
let ccflags = std::env::var("LIBPERL_CCFLAGS").unwrap_or_else(|_e| { perl.cfg("ccflags") });
for flag in ccflags.split_whitespace() {
... | path_core | identifier_name |
build.rs | extern crate cc;
use std::path::{ PathBuf, Path };
use std::process::Command;
struct Perl {
bin: String,
}
impl Perl {
fn new() -> Perl {
Perl {
bin: std::env::var("PERL").unwrap_or("perl".to_owned()),
}
}
fn cfg(&self, key: &str) -> String {
let out = Command::ne... | // is libperl version exists in default linker search path. $archlibexp/CORE is hard-coded
// installation path for default perl so this ought to be enough in most cases.
println!("cargo:rustc-link-search=native={}", perl.path_core().to_str().unwrap());
}
} | random_line_split | |
build.rs | extern crate cc;
use std::path::{ PathBuf, Path };
use std::process::Command;
struct Perl {
bin: String,
}
impl Perl {
fn new() -> Perl {
Perl {
bin: std::env::var("PERL").unwrap_or("perl".to_owned()),
}
}
fn cfg(&self, key: &str) -> String {
let out = Command::ne... | {
let perl = Perl::new();
perl.run("build/regen.pl");
build(&perl);
if perl.cfg("usemultiplicity") == "define" {
println!("cargo:rustc-cfg=perl_multiplicity");
}
if perl.cfg("useshrplib") == "true" {
println!("cargo:rustc-cfg=perl_useshrplib");
// Make sure ld links ... | identifier_body | |
request_redraw_threaded.rs | use std::{thread, time};
use simple_logger::SimpleLogger;
use winit::{
event::{Event, WindowEvent},
event_loop::{ControlFlow, EventLoop},
window::WindowBuilder,
};
fn | () {
SimpleLogger::new().init().unwrap();
let event_loop = EventLoop::new();
let window = WindowBuilder::new()
.with_title("A fantastic window!")
.build(&event_loop)
.unwrap();
thread::spawn(move || loop {
thread::sleep(time::Duration::from_secs(1));
window.request... | main | identifier_name |
request_redraw_threaded.rs | use std::{thread, time};
use simple_logger::SimpleLogger;
use winit::{
event::{Event, WindowEvent},
event_loop::{ControlFlow, EventLoop},
window::WindowBuilder,
};
fn main() {
SimpleLogger::new().init().unwrap();
let event_loop = EventLoop::new();
let window = WindowBuilder::new()
.wit... | }
});
} | _ => (), | random_line_split |
request_redraw_threaded.rs | use std::{thread, time};
use simple_logger::SimpleLogger;
use winit::{
event::{Event, WindowEvent},
event_loop::{ControlFlow, EventLoop},
window::WindowBuilder,
};
fn main() | Event::WindowEvent { event,.. } => match event {
WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit,
_ => (),
},
Event::RedrawRequested(_) => {
println!("\nredrawing!\n");
}
_ => (),
}
}... | {
SimpleLogger::new().init().unwrap();
let event_loop = EventLoop::new();
let window = WindowBuilder::new()
.with_title("A fantastic window!")
.build(&event_loop)
.unwrap();
thread::spawn(move || loop {
thread::sleep(time::Duration::from_secs(1));
window.request... | identifier_body |
main.rs | extern crate hyper;
extern crate iron;
extern crate router;
extern crate handlebars_iron as hbsi;
extern crate rustc_serialize;
extern crate persistent;
extern crate urlencoded;
extern crate traitobject;
#[macro_use]
extern crate mime;
extern crate mysql;
extern crate crypto;
extern crate rand;
extern crate iron_login;... | mount.mount("/", chain);
mount.mount("/static/", Static::new(Path::new("static")));
let listen = config.get("listen").as_str().unwrap();
iron::Iron::new(mount).http(listen).unwrap();
}
| {
// init logging
log4rs::init_file("log4rs.yaml", Default::default()).unwrap();
let mut chain = Chain::new(route::gen_router());
let config = Config::new();
chain.link_before(Read::<Config>::one(config.clone()));
let my_pool = MyPool::new(&config);
chain.link_before(Read::<MyPool>::one(my... | identifier_body |
main.rs | extern crate hyper;
extern crate iron;
extern crate router;
extern crate handlebars_iron as hbsi;
extern crate rustc_serialize;
extern crate persistent;
extern crate urlencoded;
extern crate traitobject;
#[macro_use]
extern crate mime;
extern crate mysql;
extern crate crypto;
extern crate rand;
extern crate iron_login;... | () {
// init logging
log4rs::init_file("log4rs.yaml", Default::default()).unwrap();
let mut chain = Chain::new(route::gen_router());
let config = Config::new();
chain.link_before(Read::<Config>::one(config.clone()));
let my_pool = MyPool::new(&config);
chain.link_before(Read::<MyPool>::one... | main | identifier_name |
main.rs | extern crate hyper;
extern crate iron;
extern crate router;
extern crate handlebars_iron as hbsi;
extern crate rustc_serialize;
extern crate persistent;
extern crate urlencoded;
extern crate traitobject;
#[macro_use]
extern crate mime;
extern crate mysql;
extern crate crypto;
extern crate rand;
extern crate iron_login;... | extern crate pulldown_cmark;
extern crate regex;
extern crate ammonia;
extern crate rss;
extern crate cookie;
extern crate oven;
extern crate url;
extern crate mount;
extern crate staticfile;
extern crate form_checker;
mod base;
mod handlers;
mod route;
use iron::Chain;
use hbsi::{HandlebarsEngine, DirectorySource};
... | extern crate log4rs;
extern crate time;
extern crate chrono;
#[macro_use]
extern crate lazy_static; | random_line_split |
vrstageparameters.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 crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::VRStageParametersBinding... |
}
*self.parameters.borrow_mut() = parameters.clone();
}
}
impl VRStageParametersMethods for VRStageParameters {
#[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrstageparameters-sittingtostandingtransform
unsafe fn SittingToStandingTransform(&self, _cx: *mut JSContext) -> Non... | {
array.update(¶meters.sitting_to_standing_transform);
} | conditional_block |
vrstageparameters.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 crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::VRStageParametersBinding... | (&self, parameters: &WebVRStageParameters) {
unsafe {
let cx = self.global().get_cx();
typedarray!(in(cx) let array: Float32Array = self.transform.get());
if let Ok(mut array) = array {
array.update(¶meters.sitting_to_standing_transform);
}
... | update | identifier_name |
vrstageparameters.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 crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::VRStageParametersBinding... | pub struct VRStageParameters {
reflector_: Reflector,
#[ignore_malloc_size_of = "Defined in rust-webvr"]
parameters: DomRefCell<WebVRStageParameters>,
transform: Heap<*mut JSObject>,
}
unsafe_no_jsmanaged_fields!(WebVRStageParameters);
impl VRStageParameters {
fn new_inherited(parameters: WebVRSta... | #[dom_struct] | random_line_split |
vrstageparameters.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 crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::VRStageParametersBinding... | }
#[allow(unsafe_code)]
pub fn update(&self, parameters: &WebVRStageParameters) {
unsafe {
let cx = self.global().get_cx();
typedarray!(in(cx) let array: Float32Array = self.transform.get());
if let Ok(mut array) = array {
array.update(¶meter... | {
let cx = global.get_cx();
rooted!(in (cx) let mut array = ptr::null_mut::<JSObject>());
unsafe {
let _ = Float32Array::create(
cx,
CreateWith::Slice(¶meters.sitting_to_standing_transform),
array.handle_mut(),
);
... | identifier_body |
intersection_two.rs | use docset::DocSet;
use query::Scorer;
use DocId;
use Score;
use SkipResult;
/// Creates a `DocSet` that iterator through the intersection of two `DocSet`s.
pub struct IntersectionTwoTerms<TDocSet> {
left: TDocSet,
right: TDocSet
}
impl<TDocSet: DocSet> IntersectionTwoTerms<TDocSet> {
pub fn new(left: TD... | let mut candidate = left.doc();
loop {
match right.skip_next(candidate) {
SkipResult::Reached => {
return true;
}
SkipResult::End => {
return false;
}
SkipResult::OverStep ... | } | random_line_split |
intersection_two.rs | use docset::DocSet;
use query::Scorer;
use DocId;
use Score;
use SkipResult;
/// Creates a `DocSet` that iterator through the intersection of two `DocSet`s.
pub struct IntersectionTwoTerms<TDocSet> {
left: TDocSet,
right: TDocSet
}
impl<TDocSet: DocSet> IntersectionTwoTerms<TDocSet> {
pub fn new(left: TD... | (&mut self) -> bool {
let (left, right) = (&mut self.left, &mut self.right);
if!left.advance() {
return false;
}
let mut candidate = left.doc();
loop {
match right.skip_next(candidate) {
SkipResult::Reached => {
return t... | advance | identifier_name |
intersection_two.rs | use docset::DocSet;
use query::Scorer;
use DocId;
use Score;
use SkipResult;
/// Creates a `DocSet` that iterator through the intersection of two `DocSet`s.
pub struct IntersectionTwoTerms<TDocSet> {
left: TDocSet,
right: TDocSet
}
impl<TDocSet: DocSet> IntersectionTwoTerms<TDocSet> {
pub fn new(left: TD... |
SkipResult::End => {
return false;
}
SkipResult::OverStep => {
candidate = left.doc();
}
}
}
}
fn doc(&self) -> DocId {
self.left.doc()
}
fn size_hint(&self) -> u32 {
... | {
return true;
} | conditional_block |
intersection_two.rs | use docset::DocSet;
use query::Scorer;
use DocId;
use Score;
use SkipResult;
/// Creates a `DocSet` that iterator through the intersection of two `DocSet`s.
pub struct IntersectionTwoTerms<TDocSet> {
left: TDocSet,
right: TDocSet
}
impl<TDocSet: DocSet> IntersectionTwoTerms<TDocSet> {
pub fn new(left: TD... | return true;
}
SkipResult::End => {
return false;
}
SkipResult::OverStep => {
candidate = left.doc();
}
}
}
}
fn doc(&self) -> DocId {
self.le... | {
let (left, right) = (&mut self.left, &mut self.right);
if !left.advance() {
return false;
}
let mut candidate = left.doc();
loop {
match right.skip_next(candidate) {
SkipResult::Reached => {
return true;
... | identifier_body |
lib.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/. */
// Make |cargo bench| work.
#![cfg_attr(feature = "bench", feature(test))]
#[macro_use]
extern crate bitflags;
#... | extern crate smallvec;
extern crate to_shmem;
#[macro_use]
extern crate to_shmem_derive;
pub mod attr;
pub mod bloom;
mod builder;
pub mod context;
pub mod matching;
mod nth_index_cache;
pub mod parser;
pub mod sink;
mod tree;
pub mod visitor;
pub use crate::nth_index_cache::NthIndexCache;
pub use crate::parser::{Par... | extern crate phf;
extern crate precomputed_hash;
extern crate servo_arc; | random_line_split |
actor.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/. */
/// General actor system infrastructure.
use devtools_traits::PreciseTime;
use rustc_serialize::json;
use std::an... |
/// Find an actor by registered name
pub fn find_mut<'a, T: Any>(&'a mut self, name: &str) -> &'a mut T {
let actor = self.actors.get_mut(name).unwrap();
actor.actor_as_any_mut().downcast_mut::<T>().unwrap()
}
/// Attempt to process a message as directed by its `to` property. If the ac... | /// Find an actor by registered name
pub fn find<'a, T: Any>(&'a self, name: &str) -> &'a T {
let actor = self.actors.get(name).unwrap();
actor.actor_as_any().downcast_ref::<T>().unwrap()
} | random_line_split |
actor.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/. */
/// General actor system infrastructure.
use devtools_traits::PreciseTime;
use rustc_serialize::json;
use std::an... | {
actors: HashMap<String, Box<Actor + Send>>,
new_actors: RefCell<Vec<Box<Actor + Send>>>,
old_actors: RefCell<Vec<String>>,
script_actors: RefCell<HashMap<String, String>>,
shareable: Option<Arc<Mutex<ActorRegistry>>>,
next: Cell<u32>,
start_stamp: PreciseTime,
}
impl ActorRegistry {
... | ActorRegistry | identifier_name |
actor.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/. */
/// General actor system infrastructure.
use devtools_traits::PreciseTime;
use rustc_serialize::json;
use std::an... |
pub fn drop_actor_later(&self, name: String) {
let mut actors = self.old_actors.borrow_mut();
actors.push(name);
}
}
| {
self.actors.remove(&name);
} | identifier_body |
pow.rs | use libtww::std::ops::Mul;
use {One, CheckedMul};
/// Raises a value to the power of exp, using exponentiation by squaring.
///
/// # Example
///
/// ```rust
/// use num_traits::pow;
///
/// assert_eq!(pow(2i8, 4), 16);
/// assert_eq!(pow(6u8, 3), 216);
/// ```
#[inline]
pub fn pow<T: Clone + One + Mul<T, Output = T>>... | <T: Clone + One + CheckedMul>(mut base: T, mut exp: usize) -> Option<T> {
if exp == 0 {
return Some(T::one());
}
macro_rules! optry {
( $ expr : expr ) => {
if let Some(val) = $expr { val } else { return None }
}
}
while exp & 1 == 0 {
base = optry!(base... | checked_pow | identifier_name |
pow.rs | use libtww::std::ops::Mul;
use {One, CheckedMul};
/// Raises a value to the power of exp, using exponentiation by squaring.
///
/// # Example
///
/// ```rust
/// use num_traits::pow;
///
/// assert_eq!(pow(2i8, 4), 16);
/// assert_eq!(pow(6u8, 3), 216);
/// ```
#[inline]
pub fn pow<T: Clone + One + Mul<T, Output = T>>... |
let mut acc = base.clone();
while exp > 1 {
exp >>= 1;
base = optry!(base.checked_mul(&base));
if exp & 1 == 1 {
acc = optry!(acc.checked_mul(&base));
}
}
Some(acc)
}
| {
return Some(base);
} | conditional_block |
pow.rs | use libtww::std::ops::Mul;
use {One, CheckedMul};
/// Raises a value to the power of exp, using exponentiation by squaring.
///
/// # Example
///
/// ```rust
/// use num_traits::pow;
///
/// assert_eq!(pow(2i8, 4), 16);
/// assert_eq!(pow(6u8, 3), 216);
/// ```
#[inline]
pub fn pow<T: Clone + One + Mul<T, Output = T>>... | } | Some(acc) | random_line_split |
pow.rs | use libtww::std::ops::Mul;
use {One, CheckedMul};
/// Raises a value to the power of exp, using exponentiation by squaring.
///
/// # Example
///
/// ```rust
/// use num_traits::pow;
///
/// assert_eq!(pow(2i8, 4), 16);
/// assert_eq!(pow(6u8, 3), 216);
/// ```
#[inline]
pub fn pow<T: Clone + One + Mul<T, Output = T>>... | while exp > 1 {
exp >>= 1;
base = optry!(base.checked_mul(&base));
if exp & 1 == 1 {
acc = optry!(acc.checked_mul(&base));
}
}
Some(acc)
}
| {
if exp == 0 {
return Some(T::one());
}
macro_rules! optry {
( $ expr : expr ) => {
if let Some(val) = $expr { val } else { return None }
}
}
while exp & 1 == 0 {
base = optry!(base.checked_mul(&base));
exp >>= 1;
}
if exp == 1 {
... | identifier_body |
verify.rs | // Copyright 2014 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 ... |
fn main() {
fn next(r: &mut lexer::StringReader) -> TokenAndSpan {
use syntax::parse::lexer::Reader;
r.next_token()
}
let args = std::os::args();
let mut token_file = File::open(&Path::new(args.get(2).as_slice()));
let token_map = parse_token_list(token_file.read_to_string().unwr... | {
match a {
&IDENT(id, _) => match b {
&IDENT(id2, _) => id == id2,
_ => false
},
_ => a == b
}
} | identifier_body |
verify.rs | // Copyright 2014 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 ... |
debug!("What we got: content (`{}`), proto: {}", content, proto_tok);
let real_tok = match *proto_tok {
BINOP(..) => BINOP(str_to_binop(content)),
BINOPEQ(..) => BINOPEQ(str_to_binop(content.slice_to(content.len() - 1))),
LIT_STR(..) => LIT_STR(fix(content)),
LIT_STR_RAW(..) =>... |
let proto_tok = tokens.find_equiv(&toknum).expect(format!("didn't find token {} in the map",
toknum).as_slice());
let nm = parse::token::intern(content); | random_line_split |
verify.rs | // Copyright 2014 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 ... | (a: &Token, b: &Token) -> bool {
match a {
&IDENT(id, _) => match b {
&IDENT(id2, _) => id == id2,
_ => false
},
_ => a == b
}
}
fn main() {
fn next(r: &mut lexer::StringReader) -> TokenAndSpan {
use syntax::parse::lexer::Reader;
r.nex... | tok_cmp | identifier_name |
sparse.rs | use std::fmt;
use std::ops::Deref;
use std::slice;
/// A sparse set used for representing ordered NFA states.
///
/// This supports constant time addition and membership testing. Clearing an
/// entire set can also be done in constant time. Iteration yields elements
/// in the order in which they were inserted.
///
//... |
}
impl fmt::Debug for SparseSet {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "SparseSet({:?})", self.dense)
}
}
impl Deref for SparseSet {
type Target = [usize];
fn deref(&self) -> &Self::Target {
&self.dense
}
}
impl<'a> IntoIterator for &'a SparseSet {
... | {
self.dense.clear();
} | identifier_body |
sparse.rs | use std::fmt;
use std::ops::Deref;
use std::slice;
/// A sparse set used for representing ordered NFA states.
///
/// This supports constant time addition and membership testing. Clearing an
/// entire set can also be done in constant time. Iteration yields elements
/// in the order in which they were inserted.
///
//... | sparse: vec![0; size].into_boxed_slice(),
}
}
pub fn len(&self) -> usize {
self.dense.len()
}
pub fn is_empty(&self) -> bool {
self.dense.is_empty()
}
pub fn capacity(&self) -> usize {
self.dense.capacity()
}
pub fn insert(&mut self, value:... | SparseSet {
dense: Vec::with_capacity(size), | random_line_split |
sparse.rs | use std::fmt;
use std::ops::Deref;
use std::slice;
/// A sparse set used for representing ordered NFA states.
///
/// This supports constant time addition and membership testing. Clearing an
/// entire set can also be done in constant time. Iteration yields elements
/// in the order in which they were inserted.
///
//... | (&mut self, value: usize) {
let i = self.len();
assert!(i < self.capacity());
self.dense.push(value);
self.sparse[value] = i;
}
pub fn contains(&self, value: usize) -> bool {
let i = self.sparse[value];
self.dense.get(i) == Some(&value)
}
pub fn clear(&m... | insert | identifier_name |
is_power_of_2.rs | use malachite_base::num::arithmetic::traits::IsPowerOf2;
use Rational;
impl IsPowerOf2 for Rational {
/// Determines whether a `Rational` is an integer power of 2.
///
/// # Worst-case complexity
/// $T(n) = O(n)$
///
/// $M(n) = O(1)$
///
/// where $T$ is time, $M$ is additional memory... |
}
| {
self.sign
&& (self.denominator == 1u32 && self.numerator.is_power_of_2()
|| self.numerator == 1u32 && self.denominator.is_power_of_2())
} | identifier_body |
is_power_of_2.rs | use malachite_base::num::arithmetic::traits::IsPowerOf2;
use Rational;
impl IsPowerOf2 for Rational {
/// Determines whether a `Rational` is an integer power of 2.
///
/// # Worst-case complexity
/// $T(n) = O(n)$
///
/// $M(n) = O(1)$
///
/// where $T$ is time, $M$ is additional memory... | && (self.denominator == 1u32 && self.numerator.is_power_of_2()
|| self.numerator == 1u32 && self.denominator.is_power_of_2())
}
} | random_line_split | |
is_power_of_2.rs | use malachite_base::num::arithmetic::traits::IsPowerOf2;
use Rational;
impl IsPowerOf2 for Rational {
/// Determines whether a `Rational` is an integer power of 2.
///
/// # Worst-case complexity
/// $T(n) = O(n)$
///
/// $M(n) = O(1)$
///
/// where $T$ is time, $M$ is additional memory... | (&self) -> bool {
self.sign
&& (self.denominator == 1u32 && self.numerator.is_power_of_2()
|| self.numerator == 1u32 && self.denominator.is_power_of_2())
}
}
| is_power_of_2 | identifier_name |
mimetype.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 dom::bindings::codegen::Bindings::MimeTypeBinding::MimeTypeMethods;
use dom::bindings::js::Root;
use dom::bind... |
// https://html.spec.whatwg.org/multipage/#dom-mimetype-description
fn Description(&self) -> DOMString {
unreachable!()
}
// https://html.spec.whatwg.org/multipage/#dom-mimetype-suffixes
fn Suffixes(&self) -> DOMString {
unreachable!()
}
// https://html.spec.whatwg.org/mu... | {
unreachable!()
} | identifier_body |
mimetype.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 dom::bindings::codegen::Bindings::MimeTypeBinding::MimeTypeMethods;
use dom::bindings::js::Root;
use dom::bind... | fn Suffixes(&self) -> DOMString {
unreachable!()
}
// https://html.spec.whatwg.org/multipage/#dom-mimetype-enabledplugin
fn EnabledPlugin(&self) -> Root<Plugin> {
unreachable!()
}
} | }
// https://html.spec.whatwg.org/multipage/#dom-mimetype-suffixes | random_line_split |
mimetype.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 dom::bindings::codegen::Bindings::MimeTypeBinding::MimeTypeMethods;
use dom::bindings::js::Root;
use dom::bind... | {
reflector_: Reflector,
}
impl MimeTypeMethods for MimeType {
// https://html.spec.whatwg.org/multipage/#dom-mimetype-type
fn Type(&self) -> DOMString {
unreachable!()
}
// https://html.spec.whatwg.org/multipage/#dom-mimetype-description
fn Description(&self) -> DOMString {
u... | MimeType | identifier_name |
util.rs | // This file is part of rss.
//
// Copyright © 2015-2017 The rust-syndication Developers
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the MIT License and/or Apache 2.0 License.
use std::collections::HashMap;
use std::io::BufRead;
use std::str;
use quick_xml::even... | }
let items = match extension.children.get_mut(name) {
Some(items) => items,
None => unreachable!(),
};
items.push(ext);
}
Event::CData(element) => {
extension.value = Some(r... |
let mut extension = Extension::default();
let mut buf = Vec::new();
for attr in atts.with_checks(false) {
if let Ok(attr) = attr {
let key = str::from_utf8(attr.key)?;
let value = attr.unescape_and_decode_value(reader)?;
extension.attrs.insert(key.to_string(), v... | identifier_body |
util.rs | // This file is part of rss.
//
// Copyright © 2015-2017 The rust-syndication Developers
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the MIT License and/or Apache 2.0 License.
use std::collections::HashMap;
use std::io::BufRead;
use std::str;
use quick_xml::even... |
map: &mut HashMap<String, Vec<Extension>>,
key: &str,
) -> Option<String> {
map.remove(key)
.map(|mut v| v.remove(0))
.and_then(|ext| ext.value)
}
| emove_extension_value( | identifier_name |
util.rs | // This file is part of rss.
//
// Copyright © 2015-2017 The rust-syndication Developers
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the MIT License and/or Apache 2.0 License.
use std::collections::HashMap;
use std::io::BufRead;
use std::str;
use quick_xml::even... | }
loop {
match reader.read_event(&mut buf)? {
Event::Start(element) => {
let ext = parse_extension_element(reader, element.attributes())?;
let name = str::from_utf8(element.local_name())?;
if!extension.children.contains_key(name) {
... |
let key = str::from_utf8(attr.key)?;
let value = attr.unescape_and_decode_value(reader)?;
extension.attrs.insert(key.to_string(), value);
}
| conditional_block |
util.rs | // This file is part of rss.
//
// Copyright © 2015-2017 The rust-syndication Developers
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the MIT License and/or Apache 2.0 License.
use std::collections::HashMap;
use std::io::BufRead;
use std::str;
use quick_xml::even... | fn parse_extension_element<R: BufRead>(
reader: &mut Reader<R>,
mut atts: Attributes,
) -> Result<Extension, Error> {
let mut extension = Extension::default();
let mut buf = Vec::new();
for attr in atts.with_checks(false) {
if let Ok(attr) = attr {
let key = str::from_utf8(attr.... | }
| random_line_split |
enum-doc-bitfield.rs | /* automatically generated by rust-bindgen */
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals | /// Document field with three slashes
pub const VAR_A: B = B(0);
}
impl B {
/// Document field with preceeding star
pub const VAR_B: B = B(1);
}
impl B {
/// Document field with preceeding exclamation
pub const VAR_C: B = B(2);
}
impl B {
///< Document field with following star
pub const... | )]
impl B { | random_line_split |
enum-doc-bitfield.rs | /* automatically generated by rust-bindgen */
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
impl B {
/// Document field with three slashes
pub const VAR_A: B = B(0);
}
impl B {
/// Document field with preceeding star
pub const VAR_B: B = B(1);
}
i... | (self, other: Self) -> Self {
B(self.0 & other.0)
}
}
impl ::std::ops::BitAndAssign for B {
#[inline]
fn bitand_assign(&mut self, rhs: B) {
self.0 &= rhs.0;
}
}
#[repr(transparent)]
/// Document enum
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct B(pub u32);
| bitand | identifier_name |
enum-doc-bitfield.rs | /* automatically generated by rust-bindgen */
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
impl B {
/// Document field with three slashes
pub const VAR_A: B = B(0);
}
impl B {
/// Document field with preceeding star
pub const VAR_B: B = B(1);
}
i... |
}
impl ::std::ops::BitOrAssign for B {
#[inline]
fn bitor_assign(&mut self, rhs: B) {
self.0 |= rhs.0;
}
}
impl ::std::ops::BitAnd<B> for B {
type Output = Self;
#[inline]
fn bitand(self, other: Self) -> Self {
B(self.0 & other.0)
}
}
impl ::std::ops::BitAndAssign for B {
... | {
B(self.0 | other.0)
} | identifier_body |
main.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/. */
#![feature(env, os, start)]
#[cfg(target_os="android")]
extern crate libc;
extern crate servo;
extern crate time... | {
browser: Browser,
}
#[cfg(target_os="android")]
android_start!(main);
#[cfg(target_os="android")]
fn get_args() -> Vec<String> {
vec![
"servo".to_owned(),
"http://en.wikipedia.org/wiki/Rust".to_owned()
]
}
#[cfg(not(target_os="android"))]
fn get_args() -> Vec<String> {
use std::env... | BrowserWrapper | identifier_name |
main.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/. */
#![feature(env, os, start)]
#[cfg(target_os="android")]
extern crate libc;
extern crate servo;
extern crate time... | }
#[cfg(not(target_os="android"))]
fn setup_logging() {
}
fn main() {
if opts::from_cmdline_args(&*get_args()) {
setup_logging();
resource_task::global_init();
let window = if opts::get().headless {
None
} else {
Some(app::create_window())
};
... | random_line_split | |
main.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/. */
#![feature(env, os, start)]
#[cfg(target_os="android")]
extern crate libc;
extern crate servo;
extern crate time... |
}
| {
let is_resize = match event {
WindowEvent::Resize(..) => true,
_ => false,
};
if !self.browser.handle_event(event) {
return false
}
if is_resize {
self.browser.repaint_synchronously()
}
true
} | identifier_body |
regex_route.rs | use util::*;
use hyper::status::StatusCode;
use hyper::client::Response;
fn with_path<F>(path: &str, f: F) where F: FnOnce(&mut Response) {
run_example("regex_route", |port| {
let url = format!("http://localhost:{}{}", port, path);
let ref mut res = response_for(&url);
f(res)
})
}
#[t... |
#[test]
fn ignores_query() {
with_path("/hello/world?foo=bar", |res| {
let s = read_body_to_string(res);
assert_eq!(s, "Hello world");
})
}
#[test]
// FIXME?
// Rym: I would expect this to 404, but its behavior is somewhat
// expected when compared to the regex provided. To get my expected
//... | {
with_path("/hello/world", |res| {
let s = read_body_to_string(res);
assert_eq!(s, "Hello world");
})
} | identifier_body |
regex_route.rs | use util::*;
use hyper::status::StatusCode;
use hyper::client::Response;
fn with_path<F>(path: &str, f: F) where F: FnOnce(&mut Response) {
run_example("regex_route", |port| {
let url = format!("http://localhost:{}{}", port, path);
let ref mut res = response_for(&url);
f(res)
})
}
#[t... | // This seems like it might be a bit of a footgun.
fn fallthrough_too_many_params() {
with_path("/hello/beautiful/world", |res| {
let s = read_body_to_string(res);
assert_eq!(s, "Hello beautiful");
})
}
#[test]
fn fallthrough_with_no_match() {
with_path("/", |res| {
assert_eq!(res.s... | // Rym: I would expect this to 404, but its behavior is somewhat
// expected when compared to the regex provided. To get my expected
// behaviour, you'd need to append `$` to the regex in the example. | random_line_split |
regex_route.rs | use util::*;
use hyper::status::StatusCode;
use hyper::client::Response;
fn | <F>(path: &str, f: F) where F: FnOnce(&mut Response) {
run_example("regex_route", |port| {
let url = format!("http://localhost:{}{}", port, path);
let ref mut res = response_for(&url);
f(res)
})
}
#[test]
fn with_param() {
with_path("/hello/world", |res| {
let s = read_body_... | with_path | identifier_name |
routing_graph.rs | use crate::database::{Database, DeviceGlobalsData,};
use std::collections::{HashSet, HashMap};
use std::convert::TryInto;
use crate::bba::idstring::*;
use crate::bba::idxset::*;
use crate::bba::tiletype::{Neighbour, BranchSide, TileTypes};
use crate::sites::*;
use crate::wires::*;
use crate::pip_classes::classify_pip... | GraphBuilder {
g: IcGraph::new(ids, width, height),
ids: ids,
chip: chip,
glb: globals.clone(),
db: db,
tiletypes_by_xy: tiletypes_by_xy,
// the original tiletypes from the database
orig_tts: orig_tts,
}
... | let orig_tts = TileTypes::new(db, ids, &chip.family, &[&chip.device]);
let globals = db.device_globals(&chip.family, &chip.device);
| random_line_split |
routing_graph.rs | crate::database::{Database, DeviceGlobalsData,};
use std::collections::{HashSet, HashMap};
use std::convert::TryInto;
use crate::bba::idstring::*;
use crate::bba::idxset::*;
use crate::bba::tiletype::{Neighbour, BranchSide, TileTypes};
use crate::sites::*;
use crate::wires::*;
use crate::pip_classes::classify_pip;
... | (from_wire: &str, to_wire: &str) -> String {
let (src_rel, src_name) = Neighbour::parse_wire(from_wire);
let (dst_rel, dst_name) = Neighbour::parse_wire(to_wire);
let (src_x, src_y) = match src_rel {
Some(Neighbour::RelXY { rel_x: x, rel_y: y }) => (x, y),
_ => (0, 0)
... | get_pip_tmg_class | identifier_name |
routing_graph.rs | crate::database::{Database, DeviceGlobalsData,};
use std::collections::{HashSet, HashMap};
use std::convert::TryInto;
use crate::bba::idstring::*;
use crate::bba::idxset::*;
use crate::bba::tiletype::{Neighbour, BranchSide, TileTypes};
use crate::sites::*;
use crate::wires::*;
use crate::pip_classes::classify_pip;
... |
pub fn tile_at(&mut self, x: u32, y: u32) -> &mut IcTileInst {
let idx = self.tile_idx(x, y);
&mut self.tiles[idx]
}
pub fn type_at(&mut self, x: u32, y: u32) -> &mut IcTileType {
let idx = self.tile_at(x, y).type_idx;
self.tile_types.value_mut(idx)
}
pub fn map_node... | {
assert!(x < self.width);
assert!(y < self.height);
((y * self.width) + x) as usize
} | identifier_body |
dompoint.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 dom::bindings::codegen::Bindings::DOMPointBinding::{DOMPointInit, DOMPointMethods, Wrap};
use dom::bindings::c... | (&self, value: f64) {
self.point.SetY(value);
}
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-z
fn Z(&self) -> f64 {
self.point.Z()
}
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-z
fn SetZ(&self, value: f64) {
self.poin... | SetY | identifier_name |
dompoint.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 dom::bindings::codegen::Bindings::DOMPointBinding::{DOMPointInit, DOMPointMethods, Wrap};
use dom::bindings::c... |
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-w
fn SetW(&self, value: f64) {
self.point.SetW(value);
}
}
| {
self.point.W()
} | identifier_body |
dompoint.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 dom::bindings::codegen::Bindings::DOMPointBinding::{DOMPointInit, DOMPointMethods, Wrap};
use dom::bindings::c... | fn SetZ(&self, value: f64) {
self.point.SetZ(value);
}
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-w
fn W(&self) -> f64 {
self.point.W()
}
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-w
fn SetW(&self, value: f64) {
... | self.point.Z()
}
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-z | random_line_split |
session.rs | use std::future::Future;
use std::pin::Pin;
use std::sync::{atomic, Arc};
use std::task::{Context, Poll};
use crate::core;
use futures::channel::oneshot;
use futures::future;
use futures::FutureExt;
use parking_lot::Mutex;
use slab::Slab;
use crate::server_utils::cors::Origin;
use crate::server_utils::hosts::Host;
u... | if!header_is_allowed(&self.allowed_origins, origin) {
warn!(
"Blocked connection to WebSockets server from untrusted origin: {:?}",
origin.and_then(|s| std::str::from_utf8(s).ok()),
);
Some(forbidden("URL Blocked", "Connection Origin has been rejected."))
} else {
None
}
}
fn verify_host(&s... | req.header("origin").map(|x| &x[..])
}
fn verify_origin(&self, origin: Option<&[u8]>) -> Option<ws::Response> { | random_line_split |
session.rs | use std::future::Future;
use std::pin::Pin;
use std::sync::{atomic, Arc};
use std::task::{Context, Poll};
use crate::core;
use futures::channel::oneshot;
use futures::future;
use futures::FutureExt;
use parking_lot::Mutex;
use slab::Slab;
use crate::server_utils::cors::Origin;
use crate::server_utils::hosts::Host;
u... | (&self, req: &ws::Request) -> Option<ws::Response> {
let host = req.header("host").map(|x| &x[..]);
if!header_is_allowed(&self.allowed_hosts, host) {
warn!(
"Blocked connection to WebSockets server with untrusted host: {:?}",
host.and_then(|s| std::str::from_utf8(s).ok()),
);
Some(forbidden("URL Bl... | verify_host | identifier_name |
session.rs | use std::future::Future;
use std::pin::Pin;
use std::sync::{atomic, Arc};
use std::task::{Context, Poll};
use crate::core;
use futures::channel::oneshot;
use futures::future;
use futures::FutureExt;
use parking_lot::Mutex;
use slab::Slab;
use crate::server_utils::cors::Origin;
use crate::server_utils::hosts::Host;
u... |
// Disallow in other cases
_ => false,
}
}
fn forbidden(title: &str, message: &str) -> ws::Response {
let mut forbidden = ws::Response::new(403, "Forbidden", format!("{}\n{}\n", title, message).into_bytes());
{
let headers = forbidden.headers_mut();
headers.push(("Connection".to_owned(), b"close".to_vec())... | {
for v in values {
if v.matches(val) {
return true;
}
}
false
} | conditional_block |
session.rs | use std::future::Future;
use std::pin::Pin;
use std::sync::{atomic, Arc};
use std::task::{Context, Poll};
use crate::core;
use futures::channel::oneshot;
use futures::future;
use futures::FutureExt;
use parking_lot::Mutex;
use slab::Slab;
use crate::server_utils::cors::Origin;
use crate::server_utils::hosts::Host;
u... | {
let mut forbidden = ws::Response::new(403, "Forbidden", format!("{}\n{}\n", title, message).into_bytes());
{
let headers = forbidden.headers_mut();
headers.push(("Connection".to_owned(), b"close".to_vec()));
}
forbidden
} | identifier_body | |
mod.rs | use std::fs;
use std::path;
use std::io::Read;
use serialize::json;
use valico::json_schema;
fn visit_specs<F>(dir: &path::Path, cb: F) where F: Fn(&path::Path, json::Json) {
let contents = fs::read_dir(dir).ok().unwrap();
for entry in contents {
let path = entry.unwrap().path();
match fs::File... | let spec_set = spec_set.as_array().unwrap();
let exceptions: Vec<(String, String)> = vec![
("maxLength.json".to_string(), "two supplementary Unicode code points is long enough".to_string()),
("minLength.json".to_string(), "one supplementary Unicode code point is not long enough"... | let json_v4_schema: json::Json = content.parse().unwrap();
visit_specs(&path::Path::new("tests/schema/JSON-Schema-Test-Suite/tests/draft4"), |path, spec_set: json::Json| { | random_line_split |
mod.rs | use std::fs;
use std::path;
use std::io::Read;
use serialize::json;
use valico::json_schema;
fn visit_specs<F>(dir: &path::Path, cb: F) where F: Fn(&path::Path, json::Json) {
let contents = fs::read_dir(dir).ok().unwrap();
for entry in contents {
let path = entry.unwrap().path();
match fs::File... | () {
let mut content = String::new();
fs::File::open(&path::Path::new("tests/schema/schema.json")).ok().unwrap()
.read_to_string(&mut content).ok().unwrap();
let json_v4_schema: json::Json = content.parse().unwrap();
visit_specs(&path::Path::new("tests/schema/JSON-Schema-Test-Suite/tests/draft... | test_suite | identifier_name |
mod.rs | use std::fs;
use std::path;
use std::io::Read;
use serialize::json;
use valico::json_schema;
fn visit_specs<F>(dir: &path::Path, cb: F) where F: Fn(&path::Path, json::Json) |
#[test]
fn test_suite() {
let mut content = String::new();
fs::File::open(&path::Path::new("tests/schema/schema.json")).ok().unwrap()
.read_to_string(&mut content).ok().unwrap();
let json_v4_schema: json::Json = content.parse().unwrap();
visit_specs(&path::Path::new("tests/schema/JSON-Schema... | {
let contents = fs::read_dir(dir).ok().unwrap();
for entry in contents {
let path = entry.unwrap().path();
match fs::File::open(&path) {
Err(_) => continue,
Ok(mut file) => {
let metadata = file.metadata().unwrap();
if metadata.is_file() {... | identifier_body |
cliente.rs | use std::cmp::{Ordering, min};
use std::fs::File;
use std::io::{BufWriter, Write, Read};
use chrono::{DateTime, NaiveDateTime, Utc};
use serializable::Serializable;
use serializable::SerializeError;
use byteorder::{ReadBytesExt, WriteBytesExt, BigEndian};
#[derive(Debug, Clone)]
pub struct Cliente {
pub codigo:... | (&self, file: &mut File) -> Result<(), SerializeError> {
let mut file = BufWriter::new(file);
if self.codigo == 3763629520 {
println!("entra aqui arrombado");
}
file.write_u32::<BigEndian>(self.codigo)?;
let bytes = self.nome.as_bytes();
let bounda... | serialize | identifier_name |
cliente.rs | use std::cmp::{Ordering, min};
use std::fs::File;
use std::io::{BufWriter, Write, Read};
use chrono::{DateTime, NaiveDateTime, Utc};
use serializable::Serializable;
use serializable::SerializeError;
use byteorder::{ReadBytesExt, WriteBytesExt, BigEndian};
#[derive(Debug, Clone)]
pub struct Cliente {
pub codigo:... |
}
| {
let codigo = file.read_u32::<BigEndian>()?;
let mut nome = [0; 50];
file.read_exact(&mut nome)?;
let nul_pos = nome.iter().position(|&c| c == b'\0').unwrap_or(nome.len());
let nome = String::from_utf8(nome[..nul_pos].to_vec())?;
let data_nascimento = file.read_i64::<... | identifier_body |
cliente.rs | use std::cmp::{Ordering, min};
use std::fs::File;
use std::io::{BufWriter, Write, Read};
use chrono::{DateTime, NaiveDateTime, Utc};
use serializable::Serializable;
use serializable::SerializeError;
use byteorder::{ReadBytesExt, WriteBytesExt, BigEndian};
#[derive(Debug, Clone)]
pub struct Cliente {
pub codigo:... |
file.write_u32::<BigEndian>(self.codigo)?;
let bytes = self.nome.as_bytes();
let boundary = min(50, bytes.len());
let diff = 50 - boundary;
file.write_all(&bytes[..boundary])?;
for _ in 0..diff {
file.write_u8(0)?;
}
file.write_i6... | {
println!("entra aqui arrombado");
} | conditional_block |
cliente.rs | use std::cmp::{Ordering, min};
use std::fs::File;
use std::io::{BufWriter, Write, Read};
use chrono::{DateTime, NaiveDateTime, Utc};
use serializable::Serializable;
use serializable::SerializeError;
use byteorder::{ReadBytesExt, WriteBytesExt, BigEndian};
#[derive(Debug, Clone)]
pub struct Cliente {
pub codigo:... | let boundary = min(50, bytes.len());
let diff = 50 - boundary;
file.write_all(&bytes[..boundary])?;
for _ in 0..diff {
file.write_u8(0)?;
}
file.write_i64::<BigEndian>(self.data_nascimento.timestamp())?;
Ok(())
}
fn deserialize(file: &mut F... | random_line_split | |
main.rs | use binaryninja::architecture::Architecture;
use binaryninja::binaryview::{BinaryViewBase, BinaryViewExt};
// Standalone executables need to provide a main function for rustc
// Plugins should refer to `binaryninja::command::*` for the various registration callbacks.
fn main() {
// This loads all the core architec... | println!("Loading binary...");
let bv = binaryninja::open_view("/bin/cat").expect("Couldn't open `/bin/cat`");
println!("Filename: `{}`", bv.metadata().filename());
println!("File size: `{:#x}`", bv.len());
println!("Function count: {}", bv.functions().len());
for func in &bv.functions() {
... | binaryninja::headless::init();
// Your code here... | random_line_split |
main.rs | use binaryninja::architecture::Architecture;
use binaryninja::binaryview::{BinaryViewBase, BinaryViewExt};
// Standalone executables need to provide a main function for rustc
// Plugins should refer to `binaryninja::command::*` for the various registration callbacks.
fn main() | match func.arch().instruction_text(
bv.read_buffer(addr, func.arch().max_instr_len())
.unwrap()
.get_data(),
addr,
) {
Some((_, tokens)) => {
tokens
... | {
// This loads all the core architecture, platform, etc plugins
// Standalone executables probably need to call this, but plugins do not
println!("Loading plugins...");
binaryninja::headless::init();
// Your code here...
println!("Loading binary...");
let bv = binaryninja::open_view("/bin/... | identifier_body |
main.rs | use binaryninja::architecture::Architecture;
use binaryninja::binaryview::{BinaryViewBase, BinaryViewExt};
// Standalone executables need to provide a main function for rustc
// Plugins should refer to `binaryninja::command::*` for the various registration callbacks.
fn | () {
// This loads all the core architecture, platform, etc plugins
// Standalone executables probably need to call this, but plugins do not
println!("Loading plugins...");
binaryninja::headless::init();
// Your code here...
println!("Loading binary...");
let bv = binaryninja::open_view("/b... | main | identifier_name |
main.rs | use binaryninja::architecture::Architecture;
use binaryninja::binaryview::{BinaryViewBase, BinaryViewExt};
// Standalone executables need to provide a main function for rustc
// Plugins should refer to `binaryninja::command::*` for the various registration callbacks.
fn main() {
// This loads all the core architec... |
_ => (),
}
}
}
}
// Important! Standalone executables need to call shutdown or they will hang forever
binaryninja::headless::shutdown();
}
| {
tokens
.iter()
.for_each(|token| print!("{}", token.text().as_str()));
println!("")
} | conditional_block |
split.rs | // #![ warn( missing_docs ) ]
// #![ warn( missing_debug_implementations ) ]
use former::Former;
///
/// Either delimeter or delimeted with the slice on its string.
///
#[ derive( Debug ) ]
pub struct Split< 'a >
{
string : &'a str,
typ : SplitType,
}
impl< 'a > From< Split< 'a > > for String
{
fn from( src :... | }
//
impl< 'a > Iterator for SplitIterator< 'a >
{
type Item = Split< 'a >;
fn next( &mut self ) -> Option< Self::Item >
{
self.counter += 1;
if self.counter % 2 == 1
{
let next = self.iterator.next();
if let Some( next ) = next
{
Some( Split { string : next, typ : SplitTy... | delimeter,
counter,
}
} | random_line_split |
split.rs | // #![ warn( missing_docs ) ]
// #![ warn( missing_debug_implementations ) ]
use former::Former;
///
/// Either delimeter or delimeted with the slice on its string.
///
#[ derive( Debug ) ]
pub struct Split< 'a >
{
string : &'a str,
typ : SplitType,
}
impl< 'a > From< Split< 'a > > for String
{
fn from( src :... |
Some( Split { string : self.delimeter, typ : SplitType::Delimeter } )
// Some( Split::Delimeter( self.delimeter.clone() ) )
}
}
}
///
/// Options of function split.
///
#[ derive( Debug ) ]
#[ derive( Former ) ]
#[ form_after( fn split( self ) -> SplitIterator< 'a > ) ]
pub struct SplitOptions< 'a ... | {
self.iterator.next();
return None;
} | conditional_block |
split.rs | // #![ warn( missing_docs ) ]
// #![ warn( missing_debug_implementations ) ]
use former::Former;
///
/// Either delimeter or delimeted with the slice on its string.
///
#[ derive( Debug ) ]
pub struct Split< 'a >
{
string : &'a str,
typ : SplitType,
}
impl< 'a > From< Split< 'a > > for String
{
fn from( src :... |
}
///
/// Either delimeter or delimeted
///
#[ derive( Debug ) ]
pub enum SplitType
{
/// Substring of the original string with text inbetween delimeters.
Delimeted,
/// Delimeter.
Delimeter,
}
///
/// Split iterator.
///
#[ derive( Debug ) ]
pub struct SplitIterator< 'a >
{
iterator : std::iter::Peekabl... | {
src.string.into()
} | identifier_body |
split.rs | // #![ warn( missing_docs ) ]
// #![ warn( missing_debug_implementations ) ]
use former::Former;
///
/// Either delimeter or delimeted with the slice on its string.
///
#[ derive( Debug ) ]
pub struct Split< 'a >
{
string : &'a str,
typ : SplitType,
}
impl< 'a > From< Split< 'a > > for String
{
fn from( src :... | ( &self ) -> &'a str
{
self.delimeter
}
fn preserving_empty( &self ) -> bool
{
self.preserving_empty
}
fn preserving_delimeters( &self ) -> bool
{
self.preserving_delimeters
}
}
///
/// Function to split a string.
///
/// It produces former. To convert former into options and run algorithm ... | delimeter | identifier_name |
sha1nexte.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn sha1nexte_1() {
run_test(&Instruction { mnemonic: Mnemonic::SHA1NEXTE, operand1: Some(Direct(XMM1)), operand2: Some(Dir... |
fn sha1nexte_3() {
run_test(&Instruction { mnemonic: Mnemonic::SHA1NEXTE, operand1: Some(Direct(XMM4)), operand2: Some(Direct(XMM2)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 56, 200, 226], OperandSize::Qword)
}
fn sha1ne... | {
run_test(&Instruction { mnemonic: Mnemonic::SHA1NEXTE, operand1: Some(Direct(XMM2)), operand2: Some(IndirectScaledDisplaced(EDI, Two, 1878744270, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15,... | identifier_body |
sha1nexte.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn sha1nexte_1() {
run_test(&Instruction { mnemonic: Mnemonic::SHA1NEXTE, operand1: Some(Direct(XMM1)), operand2: Some(Dir... | () {
run_test(&Instruction { mnemonic: Mnemonic::SHA1NEXTE, operand1: Some(Direct(XMM2)), operand2: Some(IndirectScaledDisplaced(EDI, Two, 1878744270, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[... | sha1nexte_2 | identifier_name |
sha1nexte.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn sha1nexte_1() {
run_test(&Instruction { mnemonic: Mnemonic::SHA1NEXTE, operand1: Some(Direct(XMM1)), operand2: Some(Dir... | } | random_line_split | |
insertion.rs | // Copyright 2020 Johannes Köster.
// Licensed under the GNU GPLv3 license (https://opensource.org/licenses/GPL-3.0)
// This file may not be copied, modified, or distributed
// except according to those terms.
use std::cell::RefCell;
use std::cmp;
use std::rc::Rc;
use std::sync::Arc;
use anyhow::Result;
use bio::stat... | } {
Some(vec![0])
} else {
None
}
}
/// Return variant loci.
fn loci(&self) -> &Self::Loci {
&self.locus
}
/// Calculate probability for alt and reference allele.
fn allele_support(
&self,
evidence: &Self::Evidence,
... |
!self.locus().overlap(left, true).is_none()
|| !self.locus().overlap(right, true).is_none()
}
| conditional_block |
insertion.rs | // Copyright 2020 Johannes Köster.
// Licensed under the GNU GPLv3 license (https://opensource.org/licenses/GPL-3.0)
// This file may not be copied, modified, or distributed
// except according to those terms.
use std::cell::RefCell;
use std::cmp;
use std::rc::Rc;
use std::sync::Arc;
use anyhow::Result;
use bio::stat... | }
}
impl<R: Realigner> ReadSamplingBias for Insertion<R> {}
impl<R: Realigner> Variant for Insertion<R> {
type Evidence = PairedEndEvidence;
type Loci = MultiLocus;
fn is_valid_evidence(
&self,
evidence: &Self::Evidence,
_: &AlignmentProperties,
) -> Option<Vec<usize>> {
... | }
fn enclosable_len(&self) -> Option<u64> {
Some(self.ins_seq.len() as u64) | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.