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
wasm_testsuite.rs
use cranelift_codegen::isa; use cranelift_codegen::print_errors::pretty_verifier_error; use cranelift_codegen::settings::{self, Flags}; use cranelift_codegen::verifier; use cranelift_wasm::{translate_module, DummyEnvironment, ReturnMode}; use std::fs; use std::fs::File; use std::io; use std::io::prelude::*; use std::pa...
#[test] fn use_fallthrough_return() { let flags = Flags::new(settings::builder()); handle_module( Path::new("../wasmtests/use_fallthrough_return.wat"), &flags, ReturnMode::FallthroughReturn, ); } fn read_file(path: &Path) -> io::Result<Vec<u8>> { let mut buf: Vec<u8> = Vec::new(...
random_line_split
build.rs
extern crate symbiosis; use std::path::Path; use std::fs::{File, create_dir_all}; use std::io::Read; use std::default::Default; use symbiosis::TemplateGroup; use symbiosis::rust::{self, Rust}; use symbiosis::javascript::{self, JavaScript}; fn
() { let out_dir = std::env::var("OUT_DIR").unwrap(); let rust_dest = Path::new(&out_dir).join("symbiosis/"); if let Err(e) = create_dir_all(&rust_dest) { panic!("failed to create Symbiosis output directory: {}", e); } let js_dest = Path::new("res"); let mut templates = TemplateGroup::n...
main
identifier_name
build.rs
extern crate symbiosis; use std::path::Path; use std::fs::{File, create_dir_all}; use std::io::Read; use std::default::Default; use symbiosis::TemplateGroup; use symbiosis::rust::{self, Rust}; use symbiosis::javascript::{self, JavaScript}; fn main() { let out_dir = std::env::var("OUT_DIR").unwrap(); let rust...
let js = JavaScript { namespace: Some("templates"), ..Default::default() }; let rust = Rust {..Default::default() }; if let Err(e) = File::create(js_dest.join("templates.js")).map_err(|e| javascript::Error::Io(e)).and_then(|mut file| templates.emit_code(&mut file, &js)) { pani...
{ panic!("failed to precompile templates/shared: {}", e); }
conditional_block
build.rs
extern crate symbiosis; use std::path::Path; use std::fs::{File, create_dir_all}; use std::io::Read; use std::default::Default; use symbiosis::TemplateGroup; use symbiosis::rust::{self, Rust}; use symbiosis::javascript::{self, JavaScript}; fn main() {
let rust_dest = Path::new(&out_dir).join("symbiosis/"); if let Err(e) = create_dir_all(&rust_dest) { panic!("failed to create Symbiosis output directory: {}", e); } let js_dest = Path::new("res"); let mut templates = TemplateGroup::new(); if let Err(e) = templates.parse_directory("temp...
let out_dir = std::env::var("OUT_DIR").unwrap();
random_line_split
build.rs
extern crate symbiosis; use std::path::Path; use std::fs::{File, create_dir_all}; use std::io::Read; use std::default::Default; use symbiosis::TemplateGroup; use symbiosis::rust::{self, Rust}; use symbiosis::javascript::{self, JavaScript}; fn main()
if let Err(e) = File::create(js_dest.join("templates.js")).map_err(|e| javascript::Error::Io(e)).and_then(|mut file| templates.emit_code(&mut file, &js)) { panic!("failed to create res/templates.js: {}", e); } let mut source = String::new(); if let Err(e) = File::open("templates/Document.html"...
{ let out_dir = std::env::var("OUT_DIR").unwrap(); let rust_dest = Path::new(&out_dir).join("symbiosis/"); if let Err(e) = create_dir_all(&rust_dest) { panic!("failed to create Symbiosis output directory: {}", e); } let js_dest = Path::new("res"); let mut templates = TemplateGroup::new(...
identifier_body
diagnostic.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 ...
(di: DiagnosticInfoRef) -> Diagnostic { let kind = super::LLVMGetDiagInfoKind(di); match kind { super::DK_InlineAsm => InlineAsm(InlineAsmDiagnostic::unpack(di)), super::DK_OptimizationRemark => Optimization(OptimizationDiagnostic::unpack(Optimiz...
unpack
identifier_name
diagnostic.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 ...
message: ptr::null_mut(), }; super::LLVMUnpackOptimizationDiagnostic(di, &mut opt.pass_name, &mut opt.function, &mut opt.debug_loc, &mut opt.message); opt } } pub struct InlineAsmDiagnostic { pub cookie: c_uint, pub messa...
kind: kind, pass_name: ptr::null(), function: ptr::null_mut(), debug_loc: ptr::null_mut(),
random_line_split
htmlvideoelement.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::document_loader::{LoadBlocker, LoadType}; use crate::dom::attr::Attr; use crate::dom::bindings::cell::...
pub fn set_video_width(&self, width: u32) { self.video_width.set(width); } pub fn get_video_height(&self) -> u32 { self.video_height.get() } pub fn set_video_height(&self, height: u32) { self.video_height.set(height); } pub fn allow_load_event(&self) { Lo...
{ self.video_width.get() }
identifier_body
htmlvideoelement.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::document_loader::{LoadBlocker, LoadType}; use crate::dom::attr::Attr; use crate::dom::bindings::cell::...
(&mut self, payload: Vec<u8>) { if self.cancelled { // An error was received previously, skip processing the payload. return; } self.image_cache .notify_pending_response(self.id, FetchResponseMsg::ProcessResponseChunk(payload)); } fn process_response_...
process_response_chunk
identifier_name
htmlvideoelement.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::document_loader::{LoadBlocker, LoadType}; use crate::dom::attr::Attr; use crate::dom::bindings::cell::...
if self.htmlmediaelement.get_ready_state() == ReadyState::HaveNothing { return 0; } self.video_width.get() } // https://html.spec.whatwg.org/multipage/#dom-video-videoheight fn VideoHeight(&self) -> u32 { if self.htmlmediaelement.get_ready_state() == ReadyState::...
random_line_split
cargo_output_metadata.rs
use crate::core::compiler::{CompileKind, CompileTarget, RustcTargetData}; use crate::core::dependency::DepKind; use crate::core::resolver::{HasDevUnits, Resolve, ResolveOpts}; use crate::core::{Dependency, InternedString, Package, PackageId, Workspace}; use crate::ops::{self, Packages}; use crate::util::CargoResult; us...
requested_kind, ); } }
package_map, target_data,
random_line_split
cargo_output_metadata.rs
use crate::core::compiler::{CompileKind, CompileTarget, RustcTargetData}; use crate::core::dependency::DepKind; use crate::core::resolver::{HasDevUnits, Resolve, ResolveOpts}; use crate::core::{Dependency, InternedString, Package, PackageId, Workspace}; use crate::ops::{self, Packages}; use crate::util::CargoResult; us...
{ nodes: Vec<MetadataResolveNode>, root: Option<PackageId>, } #[derive(Serialize)] struct MetadataResolveNode { id: PackageId, dependencies: Vec<PackageId>, deps: Vec<Dep>, features: Vec<InternedString>, } #[derive(Serialize)] struct Dep { name: String, pkg: PackageId, dep_kinds: ...
MetadataResolve
identifier_name
htmlcanvaselement.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 canvas_traits::{CanvasMsg, FromLayoutMsg}; use dom::attr::Attr; use dom::attr::AttrValue; use dom::bindings::c...
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); match attr.local_name() { &atom!(width) | &atom!(height) => self.recreate_contexts(), _ => (), }; } fn parse_plain_attribut...
{ Some(self.upcast::<HTMLElement>() as &VirtualMethods) }
identifier_body
htmlcanvaselement.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 canvas_traits::{CanvasMsg, FromLayoutMsg}; use dom::attr::Attr; use dom::attr::AttrValue; use dom::bindings::c...
{ pub renderer_id: Option<usize>, pub ipc_renderer: Option<IpcSender<CanvasMsg>>, pub width: u32, pub height: u32, } pub trait LayoutHTMLCanvasElementHelpers { fn data(&self) -> HTMLCanvasData; } impl LayoutHTMLCanvasElementHelpers for LayoutJS<HTMLCanvasElement> { #[allow(unsafe_code)] f...
HTMLCanvasData
identifier_name
htmlcanvaselement.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 canvas_traits::{CanvasMsg, FromLayoutMsg}; use dom::attr::Attr; use dom::attr::AttrValue; use dom::bindings::c...
use ipc_channel::ipc::{self, IpcSender}; use js::jsapi::{HandleValue, JSContext}; use offscreen_gl_context::GLContextAttributes; use rustc_serialize::base64::{STANDARD, ToBase64}; use std::iter::repeat; use string_cache::Atom; use util::str::DOMString; const DEFAULT_WIDTH: u32 = 300; const DEFAULT_HEIGHT: u32 = 150; ...
use image::png::PNGEncoder;
random_line_split
manifest.rs
// Copyright (c) 2017 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...
{ /// The identifier of the Habitat package pub pkg_ident: PackageIdent, /// Name of the Kubernetes resource. pub metadata_name: String, /// The docker image. pub image: String, /// The number of desired instances in the service group. pub count: u64, /// The relationship of a servi...
Manifest
identifier_name
manifest.rs
// Copyright (c) 2017 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...
} #[test] fn test_manifest_generation_binds() { let mut m = Manifest { pkg_ident: PackageIdent::from_str("core/nginx").unwrap(), metadata_name: "nginx-latest".to_owned(), image: "core/nginx:latest".to_owned(), count: 3, service_topology: D...
assert_eq!(out, expected);
random_line_split
manifest.rs
// Copyright (c) 2017 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...
}; let version_suffix = match pkg_ident.version { Some(ref v) => { pkg_ident .release .as_ref() .map(|r| format!("{}-{}", v, r)) .unwrap_or(v.to_string()) } None => "latest".t...
{ let count = matches.value_of("COUNT").unwrap_or("1").parse()?; let topology: Topology = matches .value_of("TOPOLOGY") .unwrap_or("standalone") .parse() .unwrap_or(Default::default()); let group = matches.value_of("GROUP").map(|s| s.to_string()); ...
identifier_body
struct.rs
// First attempt: No explicit lifetimes // Error! Compiler needs explicit lifetime //struct Singleton { //one: &mut i32, //} // TODO ^ Try uncommenting this struct // Second attempt: Add lifetimes to all the references struct
<'a, 'b> { one: &'a mut i32, two: &'b mut i32, } fn main() { // Let's say that `one` has lifetime `o` let mut one = 1; { // And that `two` has lifetime `t` // `two` has a shorter (and different) lifetime than `one` (`'t < 'o`) let mut two = 2; println!("Before: ({}...
Pair
identifier_name
struct.rs
// First attempt: No explicit lifetimes // Error! Compiler needs explicit lifetime //struct Singleton { //one: &mut i32, //} // TODO ^ Try uncommenting this struct // Second attempt: Add lifetimes to all the references struct Pair<'a, 'b> { one: &'a mut i32, two: &'b mut i32, } fn main() { // Let's sa...
}
random_line_split
render.rs
// Copyright: Ankitects Pty Ltd and contributors // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html use super::{CardTemplate, NoteType, NoteTypeKind}; use crate::{ card::{Card, CardID}, collection::Collection, err::{AnkiError, Result}, i18n::{I18n, TR}, notes::{Note, No...
fn render_card_inner( &mut self, note: &Note, card: &Card, nt: &NoteType, template: &CardTemplate, browser: bool, ) -> Result<RenderCardOutput> { let mut field_map = note.fields_map(&nt.fields); let card_num; self.add_special_fields(&mut...
{ // fetch existing card if let Some(ord) = template_ord { if let Some(card) = self.storage.get_card_by_ordinal(nid, ord as u16)? { return Ok(card); } } // no existing card; synthesize one Ok(Card { template_idx: card_ord, ...
identifier_body
render.rs
// Copyright: Ankitects Pty Ltd and contributors // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html use super::{CardTemplate, NoteType, NoteTypeKind}; use crate::{ card::{Card, CardID}, collection::Collection, err::{AnkiError, Result}, i18n::{I18n, TR}, notes::{Note, No...
} } } }
{ *val = format!("({})", field.name); }
conditional_block
render.rs
// Copyright: Ankitects Pty Ltd and contributors // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html use super::{CardTemplate, NoteType, NoteTypeKind}; use crate::{ card::{Card, CardID}, collection::Collection, err::{AnkiError, Result}, i18n::{I18n, TR}, notes::{Note, No...
if let Some(ord) = template_ord { if let Some(card) = self.storage.get_card_by_ordinal(nid, ord as u16)? { return Ok(card); } } // no existing card; synthesize one Ok(Card { template_idx: card_ord, ..Default::default() ...
template_ord: Option<u32>, card_ord: u16, ) -> Result<Card> { // fetch existing card
random_line_split
render.rs
// Copyright: Ankitects Pty Ltd and contributors // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html use super::{CardTemplate, NoteType, NoteTypeKind}; use crate::{ card::{Card, CardID}, collection::Collection, err::{AnkiError, Result}, i18n::{I18n, TR}, notes::{Note, No...
(n: u8) -> &'static str { match n { 1 => "flag1", 2 => "flag2", 3 => "flag3", 4 => "flag4", _ => "", } } fn fill_empty_fields(note: &mut Note, qfmt: &str, nt: &NoteType, i18n: &I18n) { if let Ok(tmpl) = ParsedTemplate::from_text(qfmt) { let cloze_fields = tmp...
flag_name
identifier_name
mod.rs
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
}
{ if iana::KeyParameter::from_i64(label).is_some() { panic!("param() method used to set KeyParameter"); // safe: invalid input } self.0.params.push((Label::Int(label), value)); self }
identifier_body
mod.rs
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
cbor::value::Value, common::AsCborValue, iana, iana::EnumI64, util::{to_cbor_array, ValueTryAs}, Algorithm, CoseError, Label, Result, }; use alloc::{collections::BTreeSet, vec, vec::Vec}; #[cfg(test)] mod tests; /// Key type. pub type KeyType = crate::RegisteredLabel<iana::KeyType>; impl Defa...
//! COSE_Key functionality. use crate::{
random_line_split
mod.rs
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
(self) -> Result<Value> { let mut map: Vec<(Value, Value)> = vec![(KTY.to_cbor_value()?, self.kty.to_cbor_value()?)]; if!self.key_id.is_empty() { map.push((KID.to_cbor_value()?, Value::Bytes(self.key_id))); } if let Some(alg) = self.alg { map.push((ALG.to_cbor_val...
to_cbor_value
identifier_name
keyframes.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/. */ //! Keyframes: https://drafts.csswg.org/css-animations/#keyframes #![deny(missing_docs)] use cssparser::{AtRuleP...
}, KeyframesStepValue::ComputedValues => { panic!("Shouldn't happen to set animation-timing-function in missing keyframes") }, } } } /// This structure represents a list of animation steps computed from the list /// of keyframes, in order. /// /// It only...
random_line_split
keyframes.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/. */ //! Keyframes: https://drafts.csswg.org/css-animations/#keyframes #![deny(missing_docs)] use cssparser::{AtRuleP...
panic!("Shouldn't happen to set animation-timing-function in missing keyframes") }, } } } /// This structure represents a list of animation steps computed from the list /// of keyframes, in order. /// /// It only takes into account animable properties. #[derive(Debug)] #[cfg_at...
{ if !self.declared_timing_function { return None; } match self.value { KeyframesStepValue::Declarations { ref block } => { let guard = block.read(); let &(ref declaration, _) = guard.get(PropertyDeclarationId::Longhand(...
identifier_body
keyframes.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/. */ //! Keyframes: https://drafts.csswg.org/css-animations/#keyframes #![deny(missing_docs)] use cssparser::{AtRuleP...
{} impl<'a> AtRuleParser for KeyframeListParser<'a> { type Prelude = Void; type AtRule = Arc<RwLock<Keyframe>>; } impl<'a> QualifiedRuleParser for KeyframeListParser<'a> { type Prelude = KeyframeSelector; type QualifiedRule = Arc<RwLock<Keyframe>>; fn parse_prelude(&mut self, input: &mut Parser) ...
Void
identifier_name
clear.rs
use fbo::{self, ValidatedAttachments}; use context::Context; use ContextExt; use Rect; use QueryExt; use draw_parameters::TimeElapsedQuery; use Api; use version::Version; use gl; pub fn clear(context: &Context, framebuffer: Option<&ValidatedAttachments>, rect: Option<&Rect>, color: Option<(f32, f32, f...
} } if let Some(stencil) = stencil { let stencil = stencil as gl::types::GLint; flags |= gl::STENCIL_BUFFER_BIT; if ctxt.state.clear_stencil!= stencil { ctxt.gl.ClearStencil(stencil); ctxt.state.clear_stencil = stencil; ...
{ let depth = depth as gl::types::GLclampf; flags |= gl::DEPTH_BUFFER_BIT; if ctxt.state.clear_depth != depth { if ctxt.version >= &Version(Api::Gl, 1, 0) { ctxt.gl.ClearDepth(depth as gl::types::GLclampd); } else if ctxt.version ...
conditional_block
clear.rs
use fbo::{self, ValidatedAttachments}; use context::Context; use ContextExt; use Rect; use QueryExt; use draw_parameters::TimeElapsedQuery; use Api; use version::Version; use gl; pub fn clear(context: &Context, framebuffer: Option<&ValidatedAttachments>, rect: Option<&Rect>, color: Option<(f32, f32, f...
flags |= gl::STENCIL_BUFFER_BIT; if ctxt.state.clear_stencil!= stencil { ctxt.gl.ClearStencil(stencil); ctxt.state.clear_stencil = stencil; } } ctxt.gl.Clear(flags); } }
if let Some(stencil) = stencil { let stencil = stencil as gl::types::GLint;
random_line_split
clear.rs
use fbo::{self, ValidatedAttachments}; use context::Context; use ContextExt; use Rect; use QueryExt; use draw_parameters::TimeElapsedQuery; use Api; use version::Version; use gl; pub fn
(context: &Context, framebuffer: Option<&ValidatedAttachments>, rect: Option<&Rect>, color: Option<(f32, f32, f32, f32)>, color_srgb: bool, depth: Option<f32>, stencil: Option<i32>) { unsafe { let mut ctxt = context.make_current(); let fbo_id = fbo::FramebuffersContainer::...
clear
identifier_name
clear.rs
use fbo::{self, ValidatedAttachments}; use context::Context; use ContextExt; use Rect; use QueryExt; use draw_parameters::TimeElapsedQuery; use Api; use version::Version; use gl; pub fn clear(context: &Context, framebuffer: Option<&ValidatedAttachments>, rect: Option<&Rect>, color: Option<(f32, f32, f...
if!color_srgb &&!ctxt.state.enabled_framebuffer_srgb { ctxt.gl.Enable(gl::FRAMEBUFFER_SRGB); ctxt.state.enabled_framebuffer_srgb = true; } else if color_srgb && ctxt.state.enabled_framebuffer_srgb { ctxt.gl.Disable(gl::FRAMEBUFFER_SRGB); ...
{ unsafe { let mut ctxt = context.make_current(); let fbo_id = fbo::FramebuffersContainer::get_framebuffer_for_drawing(&mut ctxt, framebuffer); fbo::bind_framebuffer(&mut ctxt, fbo_id, true, false); if ctxt.state.enabled_rasterizer_discard { ctxt.gl.Disable(gl::RASTERIZ...
identifier_body
account_db.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
(&self, key: &H256) -> Option<DBValue> { if key == &SHA3_NULL_RLP { return Some(DBValue::from_slice(&NULL_RLP_STATIC)); } self.0.get(key) } fn contains(&self, key: &H256) -> bool { if key == &SHA3_NULL_RLP { return true; } self.0.contains(key) } fn insert(&mut self, value: &[u8]) -> H256 { if ...
get
identifier_name
account_db.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
} impl Factory { /// Create a read-only accountdb. /// This will panic when write operations are called. pub fn readonly<'db>(&self, db: &'db HashDB, address_hash: H256) -> Box<HashDB + 'db> { match *self { Factory::Mangled => Box::new(AccountDB::from_hash(db, address_hash)), Factory::Plain => Box::new(Wrap...
impl Default for Factory { fn default() -> Self { Factory::Mangled }
random_line_split
account_db.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
} struct Wrapping<'db>(&'db HashDB); impl<'db> HashDB for Wrapping<'db> { fn keys(&self) -> HashMap<H256, i32> { unimplemented!() } fn get(&self, key: &H256) -> Option<DBValue> { if key == &SHA3_NULL_RLP { return Some(DBValue::from_slice(&NULL_RLP_STATIC)); } self.0.get(key) } fn contains(&self, ke...
{ if key == &SHA3_NULL_RLP { return; } let key = combine_key(&self.address_hash, key); self.db.remove(&key) }
identifier_body
account_db.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
let key = combine_key(&self.address_hash, &key); self.db.emplace(key, value) } fn remove(&mut self, key: &H256) { if key == &SHA3_NULL_RLP { return; } let key = combine_key(&self.address_hash, key); self.db.remove(&key) } } struct Wrapping<'db>(&'db HashDB); impl<'db> HashDB for Wrapping<'db> { f...
{ return; }
conditional_block
messages.rs
//! Update parsing for user messages and conversation updates. /// Specification on whether a message is incoming or outgoing. #[derive(serde::Deserialize, Copy, Clone, Eq, PartialEq, Hash, Debug)] pub enum MessageDirectionType { /// Incoming messages: messages sent by someone other than the subscribed user. #...
{ /// The unique identifier for this message. #[serde(rename = "_id")] pub message_id: String, /// Whether or not it is now unread. Most likely `false`: going from read to unread is not supported in screeps /// as of this writing. pub unread: bool, /// Phantom data in order to allow adding ...
MessageUnreadUpdate
identifier_name
messages.rs
//! Update parsing for user messages and conversation updates. /// Specification on whether a message is incoming or outgoing. #[derive(serde::Deserialize, Copy, Clone, Eq, PartialEq, Hash, Debug)] pub enum MessageDirectionType { /// Incoming messages: messages sent by someone other than the subscribed user. #...
/// [`ChannelUpdate::UserConversation`]:../enum.ChannelUpdate.html #[serde(rename = "type")] pub direction: MessageDirectionType, /// Whether or not the user who received this message has read it... Probably going to be false, as this is a /// message that was just sent. pub unread: bool, //...
/// [`ChannelUpdate::UserMessage`]: ../enum.ChannelUpdate.html
random_line_split
main.rs
#![feature(plugin, start, core_intrinsics)] #![no_std] #![plugin(macro_platformtree)] extern crate zinc; use zinc::drivers::chario::CharIO; use zinc::drivers::lcd::hd44780u::{Hd44780u, Font}; platformtree!( tiva_c@mcu { clock { source = "MOSC"; xtal = "X16_0MHz"; pll = false; } ...
lcd.custom_char_5x8(1, [0b00100, 0b01010, 0b00100, 0b11111, 0b00100, 0b01010, 0b10001, 0b00000]); // Enable blinking lcd.display_c...
{ let lcd = Hd44780u::new(args.timer, args.rs, args.en, [ args.d4, args.d5, args.d6, args.d7 ]); lcd.init(true, Font::Font5x8); // Create custom 'heart' character at index 0. lcd.custom_char_5x8(0, [0b00000, ...
identifier_body
main.rs
#![feature(plugin, start, core_intrinsics)] #![no_std] #![plugin(macro_platformtree)] extern crate zinc; use zinc::drivers::chario::CharIO; use zinc::drivers::lcd::hd44780u::{Hd44780u, Font}; platformtree!( tiva_c@mcu { clock { source = "MOSC"; xtal = "X16_0MHz"; pll = false; } ...
(args: &pt::run_args) { let lcd = Hd44780u::new(args.timer, args.rs, args.en, [ args.d4, args.d5, args.d6, args.d7 ]); lcd.init(true, Font::Font5x8); // Create custom 'heart' character at index 0. lcd.custom_char_5x8(0, ...
run
identifier_name
main.rs
#![feature(plugin, start, core_intrinsics)] #![no_std] #![plugin(macro_platformtree)] extern crate zinc;
use zinc::drivers::chario::CharIO; use zinc::drivers::lcd::hd44780u::{Hd44780u, Font}; platformtree!( tiva_c@mcu { clock { source = "MOSC"; xtal = "X16_0MHz"; pll = false; } gpio { a { d7@5 { direction = "out"; } } b { rs@0 { direction = "out"; } ...
random_line_split
check_static_recursion.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 ...
(&mut self, enum_definition: &'ast ast::EnumDef, generics: &'ast ast::Generics) { self.populate_enum_discriminants(enum_definition); visit::walk_enum_def(self, enum_definition, generics); } fn visit_variant(&mut self, variant: &'ast ast::Variant, _: &'...
visit_enum_def
identifier_name
check_static_recursion.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 ...
// Go through all the variants. let mut variant_stack: Vec<ast::NodeId> = Vec::new(); for variant in enum_definition.variants.iter().rev() { variant_stack.push(variant.node.id); // When we find an expression, every variant currently on the stack // is affecte...
}
random_line_split
check_static_recursion.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 ...
_ => () } }, _ => () } visit::walk_expr(self, e); } }
{ if let ast::ItemEnum(ref enum_def, ref generics) = self.ast_map.expect_item(enum_id.local_id()).node { self.populate_enum_discriminants(enum_def); let variant = self.ast_map.expect_variant(variant_id.local_i...
conditional_block
check_static_recursion.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 with_item_id_pushed<F>(&mut self, id: ast::NodeId, f: F) where F: Fn(&mut Self) { if self.idstack.iter().any(|&x| x == id) { let any_static = self.idstack.iter().any(|&x| { if let ast_map::NodeItem(item) = self.ast_map.get(x) { if let ast::ItemSt...
{ CheckItemRecursionVisitor { root_span: span, sess: v.sess, ast_map: v.ast_map, def_map: v.def_map, discriminant_map: &v.discriminant_map, idstack: Vec::new(), } }
identifier_body
constellation_msg.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/. */ //! The high-level interface from script to constellation. Using this abstract interface helps //! reduce coupling...
() -> PipelineId { PipelineId { namespace_id: PipelineNamespaceId(0), index: PipelineIndex(0), } } } impl fmt::Display for PipelineId { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let PipelineNamespaceId(namespace_id) = self.namespace_id; let...
fake_root_pipeline_id
identifier_name
constellation_msg.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/. */ //! The high-level interface from script to constellation. Using this abstract interface helps //! reduce coupling...
LeftControl, LeftAlt, LeftSuper, RightShift, RightControl, RightAlt, RightSuper, Menu, NavigateBackward, NavigateForward, } bitflags! { #[derive(Deserialize, Serialize)] flags KeyModifiers: u8 { const NONE = 0x00, const SHIFT = 0x01, const CONTRO...
random_line_split
websocket_session.rs
use async_trait::async_trait; use futures::{stream::SplitSink, FutureExt, SinkExt}; use serde::Serialize; use std::net::SocketAddr; use tokio::io::Result; use warp::ws::{Message, WebSocket}; use super::session::Session; use super::{SessionOutput, SessionPromptInfo, SessionState, SignInState}; #[derive(Serialize)] str...
} } SessionOutput::None => {} } } fn set_state(&mut self, state: SessionState) { self.state = state; } fn source(&self) -> String { format!("{}", self.addr.ip()) } fn state(&self) -> &SessionState { &self.state } } a...
self.send(output).await
random_line_split
websocket_session.rs
use async_trait::async_trait; use futures::{stream::SplitSink, FutureExt, SinkExt}; use serde::Serialize; use std::net::SocketAddr; use tokio::io::Result; use warp::ws::{Message, WebSocket}; use super::session::Session; use super::{SessionOutput, SessionPromptInfo, SessionState, SignInState}; #[derive(Serialize)] str...
(&mut self) -> Result<()> { self.tx.close().map(|_| Ok(())).await } async fn send(&mut self, output: SessionOutput) { match output { SessionOutput::Json(data) => { send_message(&mut self.tx, Message::text(data.to_string())).await } SessionOutp...
close
identifier_name
websocket_session.rs
use async_trait::async_trait; use futures::{stream::SplitSink, FutureExt, SinkExt}; use serde::Serialize; use std::net::SocketAddr; use tokio::io::Result; use warp::ws::{Message, WebSocket}; use super::session::Session; use super::{SessionOutput, SessionPromptInfo, SessionState, SignInState}; #[derive(Serialize)] str...
} #[async_trait] impl Session for WebSocketSession { async fn close(&mut self) -> Result<()> { self.tx.close().map(|_| Ok(())).await } async fn send(&mut self, output: SessionOutput) { match output { SessionOutput::Json(data) => { send_message(&mut self.tx, Mes...
{ Self { id, addr, tx, state: SessionState::SigningIn(Box::new(SignInState::new())), } }
identifier_body
websocket_session.rs
use async_trait::async_trait; use futures::{stream::SplitSink, FutureExt, SinkExt}; use serde::Serialize; use std::net::SocketAddr; use tokio::io::Result; use warp::ws::{Message, WebSocket}; use super::session::Session; use super::{SessionOutput, SessionPromptInfo, SessionState, SignInState}; #[derive(Serialize)] str...
SessionOutput::Aggregate(outputs) => { for output in outputs { self.send(output).await } } SessionOutput::None => {} } } fn set_state(&mut self, state: SessionState) { self.state = state; } fn sour...
{ let prompt = Prompt { player: info }; send_message( &mut self.tx, Message::text(serde_json::to_string(&prompt).unwrap()), ) .await }
conditional_block
freq_handler.rs
use compression::BlockDecoder; use common::VInt; use common::BinarySerializable; use compression::{CompositeDecoder, VIntDecoder}; use postings::SegmentPostingsOption; use compression::NUM_DOCS_PER_BLOCK; /// `FreqHandler` is in charge of decompressing /// frequencies and/or positions. pub struct FreqHandler { f...
} /// Decompresses an incomplete frequency block pub fn read_freq_vint(&mut self, data: &[u8], num_els: usize) { match self.option { SegmentPostingsOption::NoFreq => {} SegmentPostingsOption::Freq => { self.freq_decoder.uncompress_vint_unsorted(data, num_els)...
remaining } }
random_line_split
freq_handler.rs
use compression::BlockDecoder; use common::VInt; use common::BinarySerializable; use compression::{CompositeDecoder, VIntDecoder}; use postings::SegmentPostingsOption; use compression::NUM_DOCS_PER_BLOCK; /// `FreqHandler` is in charge of decompressing /// frequencies and/or positions. pub struct FreqHandler { f...
(position_data: &[u8]) -> FreqHandler { let positions = read_positions(position_data); FreqHandler { freq_decoder: BlockDecoder::new(), positions: positions, option: SegmentPostingsOption::FreqAndPositions, positions_offsets: [0; NUM_DOCS_PER_BLOCK + 1], ...
new_with_freq_and_position
identifier_name
freq_handler.rs
use compression::BlockDecoder; use common::VInt; use common::BinarySerializable; use compression::{CompositeDecoder, VIntDecoder}; use postings::SegmentPostingsOption; use compression::NUM_DOCS_PER_BLOCK; /// `FreqHandler` is in charge of decompressing /// frequencies and/or positions. pub struct FreqHandler { f...
} } }
{ self.freq_decoder.uncompress_vint_unsorted(data, num_els); self.fill_positions_offset(); }
conditional_block
freq_handler.rs
use compression::BlockDecoder; use common::VInt; use common::BinarySerializable; use compression::{CompositeDecoder, VIntDecoder}; use postings::SegmentPostingsOption; use compression::NUM_DOCS_PER_BLOCK; /// `FreqHandler` is in charge of decompressing /// frequencies and/or positions. pub struct FreqHandler { f...
fn fill_positions_offset(&mut self) { let mut cur_position: usize = self.positions_offsets[NUM_DOCS_PER_BLOCK]; let mut i: usize = 0; self.positions_offsets[i] = cur_position; let mut last_cur_position = cur_position; for &doc_freq in self.freq_decoder.output_array() { ...
{ let positions = read_positions(position_data); FreqHandler { freq_decoder: BlockDecoder::new(), positions: positions, option: SegmentPostingsOption::FreqAndPositions, positions_offsets: [0; NUM_DOCS_PER_BLOCK + 1], } }
identifier_body
partial.rs
// Copyright 2014 Pierre Talbot (IRCAM) // 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 map<U, F: FnOnce(T) -> U>(self, f: F) -> Partial<U> { match self { Value(x) => Value(f(x)), Fake(x) => Fake(f(x)), Nothing => Nothing } } pub fn and_then<U, F: FnOnce(T) -> Partial<U>>(self, f: F) -> Partial<U> { match self { Value(x) => f(x), Fake(x) => match f...
{ match self { Value(x) => x, Fake(_) => panic!("called `Partial::unwrap()` on a `Fake` value"), Nothing => panic!("called `Partial::unwrap()` on a `Nothing` value") } }
identifier_body
partial.rs
// Copyright 2014 Pierre Talbot (IRCAM)
// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed unde...
random_line_split
partial.rs
// Copyright 2014 Pierre Talbot (IRCAM) // 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...
<U, F: FnOnce(T) -> Partial<U>>(self, f: F) -> Partial<U> { match self { Value(x) => f(x), Fake(x) => match f(x) { Value(x) => Fake(x), x => x }, Nothing => Nothing } } } #[test] fn partial() { assert_eq!(Value(9i32).unwrap(), 9i32); assert_eq!(Value(9i32).map(|i|i...
and_then
identifier_name
mod.rs
use co_slog; pub fn
() { let log = co_slog::logger(); let server = log.new(o!("host" => "localhost", "port" => "8080")); let _log = co_slog::set_logger(server); info!("starting"); info!("listening"); let log = co_slog::logger(); join!( { let peer1 = log.clone().new( o!("p...
simulate_server
identifier_name
mod.rs
use co_slog; pub fn simulate_server()
debug!("disconnected"); }, { let peer2 = log.clone().new( o!("peer_addr" => "82.9.9.9", "port" => "42381"), ); let _log = co_slog::set_logger(peer2); debug!("connected"); debug!("message received"; "length" => 2); ...
{ let log = co_slog::logger(); let server = log.new(o!("host" => "localhost", "port" => "8080")); let _log = co_slog::set_logger(server); info!("starting"); info!("listening"); let log = co_slog::logger(); join!( { let peer1 = log.clone().new( o!("peer...
identifier_body
mod.rs
use co_slog; pub fn simulate_server() { let log = co_slog::logger(); let server = log.new(o!("host" => "localhost", "port" => "8080")); let _log = co_slog::set_logger(server); info!("starting"); info!("listening"); let log = co_slog::logger(); join!( { let peer1 = lo...
); crit!("internal error"); info!("exit"); }
random_line_split
mutability-inherits-through-fixed-length-vec.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let mut ints = [0; 32]; for i in &mut ints { *i += 22; } for i in &ints { assert_eq!(*i, 22); } } pub fn main() { test1(); test2(); }
test2
identifier_name
mutability-inherits-through-fixed-length-vec.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn test2() { let mut ints = [0; 32]; for i in &mut ints { *i += 22; } for i in &ints { assert_eq!(*i, 22); } } pub fn main() { test1(); test2(); }
{ let mut ints = [0; 32]; ints[0] += 1; assert_eq!(ints[0], 1); }
identifier_body
mutability-inherits-through-fixed-length-vec.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
test1(); test2(); }
pub fn main() {
random_line_split
unique-in-vec-copy.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let mut a = vec!(box 10i); let b = a.clone(); assert_eq!(**a.get(0), 10); assert_eq!(**b.get(0), 10); // This should only modify the value in a, not b **a.get_mut(0) = 20; assert_eq!(**a.get(0), 20); assert_eq!(**b.get(0), 10); }
main
identifier_name
unique-in-vec-copy.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let mut a = vec!(box 10i); let b = a.clone(); assert_eq!(**a.get(0), 10); assert_eq!(**b.get(0), 10); // This should only modify the value in a, not b **a.get_mut(0) = 20; assert_eq!(**a.get(0), 20); assert_eq!(**b.get(0), 10); }
identifier_body
unique-in-vec-copy.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
let mut a = vec!(box 10i); let b = a.clone(); assert_eq!(**a.get(0), 10); assert_eq!(**b.get(0), 10); // This should only modify the value in a, not b **a.get_mut(0) = 20; assert_eq!(**a.get(0), 20); assert_eq!(**b.get(0), 10); }
random_line_split
hyperbolictangent.rs
use std::f64; use activation::Activation; #[derive(Copy, Clone)] pub struct HyperbolicTangent; impl HyperbolicTangent { pub fn new() -> HyperbolicTangent { return HyperbolicTangent; } } impl Activation for HyperbolicTangent { /// Calculates the tanh of input `x` fn calc(&self, x: Vec<f64>) ->...
(&self, x: Vec<f64>) -> Vec<f64> { x.iter() .map(|n| { let tanh_factor = n.tanh(); 1f64 - (tanh_factor * tanh_factor) }) .collect::<Vec<_>>() } } #[cfg(test)] mod tests { use super::Activation; use super::HyperbolicTangent; #[t...
derivative
identifier_name
hyperbolictangent.rs
use std::f64; use activation::Activation; #[derive(Copy, Clone)] pub struct HyperbolicTangent; impl HyperbolicTangent { pub fn new() -> HyperbolicTangent
} impl Activation for HyperbolicTangent { /// Calculates the tanh of input `x` fn calc(&self, x: Vec<f64>) -> Vec<f64> { x.iter().map(|n| n.tanh()).collect::<Vec<_>>() } /// Calculates the Derivative tanh of input `x` fn derivative(&self, x: Vec<f64>) -> Vec<f64> { x.iter() ...
{ return HyperbolicTangent; }
identifier_body
hyperbolictangent.rs
use std::f64; use activation::Activation; #[derive(Copy, Clone)] pub struct HyperbolicTangent; impl HyperbolicTangent { pub fn new() -> HyperbolicTangent { return HyperbolicTangent; } } impl Activation for HyperbolicTangent { /// Calculates the tanh of input `x` fn calc(&self, x: Vec<f64>) ->...
#[test] fn tanh_derivative_test() { let activation = HyperbolicTangent::new(); assert_approx_eq!(activation.derivative(vec![3f64])[0], 0.0098660372f64); } }
let activation = HyperbolicTangent::new(); assert_approx_eq!(activation.calc(vec![3f64])[0], 0.995054754f64); }
random_line_split
stemmer.rs
use super::{Token, TokenFilter, TokenStream}; use crate::tokenizer::BoxTokenStream; use rust_stemmers::{self, Algorithm}; use serde::{Deserialize, Serialize}; /// Available stemmer languages. #[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Copy, Clone)] #[allow(missing_docs)] pub enum Language { Arabic, ...
fn token_mut(&mut self) -> &mut Token { self.tail.token_mut() } }
random_line_split
stemmer.rs
use super::{Token, TokenFilter, TokenStream}; use crate::tokenizer::BoxTokenStream; use rust_stemmers::{self, Algorithm}; use serde::{Deserialize, Serialize}; /// Available stemmer languages. #[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Copy, Clone)] #[allow(missing_docs)] pub enum Language { Arabic, ...
(&mut self) -> &mut Token { self.tail.token_mut() } }
token_mut
identifier_name
stemmer.rs
use super::{Token, TokenFilter, TokenStream}; use crate::tokenizer::BoxTokenStream; use rust_stemmers::{self, Algorithm}; use serde::{Deserialize, Serialize}; /// Available stemmer languages. #[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Copy, Clone)] #[allow(missing_docs)] pub enum Language { Arabic, ...
} impl TokenFilter for Stemmer { fn transform<'a>(&self, token_stream: BoxTokenStream<'a>) -> BoxTokenStream<'a> { let inner_stemmer = rust_stemmers::Stemmer::create(self.stemmer_algorithm); BoxTokenStream::from(StemmerTokenStream { tail: token_stream, stemmer: inner_stemme...
{ Stemmer::new(Language::English) }
identifier_body
windows.rs
//! A collection of window functions. //! //! All functions take a size `n` and return vectors with `n` elements. //! //! Window calculation can be costly depending on the size and type of window, //! so it is recommended to precompute windows whenever possible. use std::f32::consts::PI; use types::Sample; /// Retu...
} window } /// Returns a generalized cosine window of size `n`, with the provided /// coefficients. /// /// Hanning, hamming, and blackmann windows are all generalized cosine windows. pub fn generalized_cosine_window(alphas: &[Sample], n: usize) -> Vec<Sample> { let mut window = Vec::with_capacity(n); ...
{ window.push(2.0-z); }
conditional_block
windows.rs
//! A collection of window functions. //! //! All functions take a size `n` and return vectors with `n` elements. //! //! Window calculation can be costly depending on the size and type of window, //! so it is recommended to precompute windows whenever possible. use std::f32::consts::PI; use types::Sample; /// Retu...
#[test] fn test_hanning() { use super::hanning; check_window(&hanning(8), &[0.0, 0.1882551, 0.61126047, 0.95048443, 0.95048443, 0.61126047, 0.1882551, 0.0]); } #[test] fn test_hamming() { use super::hamming; check_window(...
{ use super::bartlett; check_window(&bartlett(8), &[0.0, 0.28571429, 0.57142857, 0.85714286, 0.85714286, 0.57142857, 0.28571429, 0.0]) }
identifier_body
windows.rs
//! A collection of window functions. //! //! All functions take a size `n` and return vectors with `n` elements. //! //! Window calculation can be costly depending on the size and type of window, //! so it is recommended to precompute windows whenever possible. use std::f32::consts::PI; use types::Sample; /// Retu...
(actual: &[Sample], expected: &[Sample]) { for (a, e) in actual.iter().zip(expected) { assert!(flt_eq(*a, *e)); } } #[test] fn test_bartlett() { use super::bartlett; check_window(&bartlett(8), &[0.0, 0.28571429, 0.57142857, 0.85714286, 0.8571...
check_window
identifier_name
windows.rs
//! A collection of window functions. //! //! All functions take a size `n` and return vectors with `n` elements. //! //! Window calculation can be costly depending on the size and type of window, //! so it is recommended to precompute windows whenever possible. use std::f32::consts::PI; use types::Sample; /// Retu...
let mut window = Vec::with_capacity(n); let f0 = 2.0*PI / ((n-1) as f32); for i in 0..n { let mut wi = 0.0; for (k, ak) in alphas.iter().enumerate() { wi += ak * (f0*k as f32*i as f32).cos(); } window.push(wi); } window } /// Returns a hanning window of s...
/// coefficients. /// /// Hanning, hamming, and blackmann windows are all generalized cosine windows. pub fn generalized_cosine_window(alphas: &[Sample], n: usize) -> Vec<Sample> {
random_line_split
coverage.rs
// Copyright 2020, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <https://opensource.org/licenses/MIT> use glib::translate::*; use pango_sys; use std::fmt; use std::mem; use std::ptr; use CoverageLeve...
pub fn set(&self, index_: i32, level: CoverageLevel) { unsafe { pango_sys::pango_coverage_set(self.to_glib_none().0, index_, level.to_glib()); } } #[cfg_attr(feature = "v1_44", deprecated)] pub fn to_bytes(&self) -> Vec<u8> { unsafe { let mut bytes = pt...
{ unsafe { pango_sys::pango_coverage_max(self.to_glib_none().0, other.to_glib_none().0); } }
identifier_body
coverage.rs
// Copyright 2020, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <https://opensource.org/licenses/MIT> use glib::translate::*; use pango_sys; use std::fmt; use std::mem; use std::ptr; use CoverageLeve...
(&self, other: &Coverage) { unsafe { pango_sys::pango_coverage_max(self.to_glib_none().0, other.to_glib_none().0); } } pub fn set(&self, index_: i32, level: CoverageLevel) { unsafe { pango_sys::pango_coverage_set(self.to_glib_none().0, index_, level.to_glib()); ...
max
identifier_name
coverage.rs
// Copyright 2020, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <https://opensource.org/licenses/MIT> use glib::translate::*; use pango_sys; use std::fmt; use std::mem; use std::ptr; use CoverageLeve...
let mut n_bytes = mem::MaybeUninit::uninit(); pango_sys::pango_coverage_to_bytes( self.to_glib_none().0, &mut bytes, n_bytes.as_mut_ptr(), ); FromGlibContainer::from_glib_full_num(bytes, n_bytes.assume_init() as usize) ...
let mut bytes = ptr::null_mut();
random_line_split
integration.rs
// Copyright 2017 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
let exit = rpc_looper.mainloop(|| r, &mut handler); match exit { Err(ReadError::Json(_)) => (), Err(err) => panic!("Incorrect error: {:?}", err), Ok(()) => panic!("Expected an error"), } }
let r = make_reader(r#"this is not valid json"#);
random_line_split
integration.rs
// Copyright 2017 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
#[test] fn test_recv_resp() { // we should reply to a well formed request let mut handler = EchoHandler; let (tx, mut rx) = test_channel(); let mut rpc_looper = RpcLoop::new(tx); let r = make_reader(r#"{"id": 1, "method": "hullo", "params": {"words": "plz"}}"#); assert!(rpc_looper.mainloop(|| ...
{ // we should not reply to a well formed notification let mut handler = EchoHandler; let (tx, mut rx) = test_channel(); let mut rpc_looper = RpcLoop::new(tx); let r = make_reader(r#"{"method": "hullo", "params": {"words": "plz"}}"#); assert!(rpc_looper.mainloop(|| r, &mut handler).is_ok()); ...
identifier_body
integration.rs
// Copyright 2017 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
; #[allow(unused)] impl Handler for EchoHandler { type Notification = RpcCall; type Request = RpcCall; fn handle_notification(&mut self, ctx: &RpcCtx, rpc: Self::Notification) {} fn handle_request(&mut self, ctx: &RpcCtx, rpc: Self::Request) -> Result<Value, RemoteError> { Ok(rpc.params) } ...
EchoHandler
identifier_name
date.rs
use std::fmt::{self, Show}; use std::str::FromStr; use time::Tm; use header::{Header, HeaderFormat}; use header::shared::util::from_one_raw_str; use header::shared::time::tm_from_str; // Egh, replace as soon as something better than time::Tm exists. /// The `Date` header field. #[derive(Copy, PartialEq, Clone)] pub st...
impl FromStr for Date { fn from_str(s: &str) -> Option<Date> { tm_from_str(s).map(Date) } } bench_header!(imf_fixdate, Date, { vec![b"Sun, 07 Nov 1994 08:48:37 GMT".to_vec()] }); bench_header!(rfc_850, Date, { vec![b"Sunday, 06-Nov-94 08:49:37 GMT".to_vec()] }); bench_header!(asctime, Date, { vec![b"Su...
random_line_split
date.rs
use std::fmt::{self, Show}; use std::str::FromStr; use time::Tm; use header::{Header, HeaderFormat}; use header::shared::util::from_one_raw_str; use header::shared::time::tm_from_str; // Egh, replace as soon as something better than time::Tm exists. /// The `Date` header field. #[derive(Copy, PartialEq, Clone)] pub st...
(_: Option<Date>) -> &'static str { "Date" } fn parse_header(raw: &[Vec<u8>]) -> Option<Date> { from_one_raw_str(raw) } } impl HeaderFormat for Date { fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let tm = **self; match tm.tm_utcoff { 0 =>...
header_name
identifier_name
date.rs
use std::fmt::{self, Show}; use std::str::FromStr; use time::Tm; use header::{Header, HeaderFormat}; use header::shared::util::from_one_raw_str; use header::shared::time::tm_from_str; // Egh, replace as soon as something better than time::Tm exists. /// The `Date` header field. #[derive(Copy, PartialEq, Clone)] pub st...
} impl FromStr for Date { fn from_str(s: &str) -> Option<Date> { tm_from_str(s).map(Date) } } bench_header!(imf_fixdate, Date, { vec![b"Sun, 07 Nov 1994 08:48:37 GMT".to_vec()] }); bench_header!(rfc_850, Date, { vec![b"Sunday, 06-Nov-94 08:49:37 GMT".to_vec()] }); bench_header!(asctime, Date, { vec![...
{ let tm = **self; match tm.tm_utcoff { 0 => tm.rfc822().fmt(fmt), _ => tm.to_utc().rfc822().fmt(fmt) } }
identifier_body
lifetime-elision-return-type-requires-explicit-lifetime.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> { x: &'a int, } // Lifetime annotation needed because we have two lifetimes: one as a parameter // and one on the reference. fn h(_x: &Foo) -> &int { //~ ERROR missing lifetime specifier //~^ HELP the signature does not say which one of `_x`'s 2 elided lifetimes it is borrowed from panic!() } fn i(_x: in...
Foo
identifier_name
lifetime-elision-return-type-requires-explicit-lifetime.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
// option. This file may not be copied, modified, or distributed // except according to those terms. // Lifetime annotation needed because we have no arguments. fn f() -> &int { //~ ERROR missing lifetime specifier //~^ HELP there is no value for it to be borrowed from panic!() } // Lifetime annotation needed ...
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
random_line_split
lifetime-elision-return-type-requires-explicit-lifetime.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 ...
// Lifetime annotation needed because we have two by-reference parameters. fn g(_x: &int, _y: &int) -> &int { //~ ERROR missing lifetime specifier //~^ HELP the signature does not say whether it is borrowed from `_x` or `_y` panic!() } struct Foo<'a> { x: &'a int, } // Lifetime annotation needed because ...
{ //~ ERROR missing lifetime specifier //~^ HELP there is no value for it to be borrowed from panic!() }
identifier_body
builder.rs
use std::collections::{HashMap, VecDeque}; use crate::level::{Background, Level}; use crate::position::*; use crate::util::*; /// Dynamic part of a cell. #[derive(Debug, Clone, Copy, PartialEq, Hash)] pub enum Foreground { None, Worker, Crate, } fn char_to_cell(chr: char) -> Option<(Background, Foregroun...
} // Try to figure out whether a given cell is inside the walls. if!inside && bg.is_wall() { inside = true; } if inside && bg == Background::Empty && index >= columns ...
if fg == Foreground::Crate { crates.push(Position::new(x, y));
random_line_split
builder.rs
use std::collections::{HashMap, VecDeque}; use crate::level::{Background, Level}; use crate::position::*; use crate::util::*; /// Dynamic part of a cell. #[derive(Debug, Clone, Copy, PartialEq, Hash)] pub enum Foreground { None, Worker, Crate, } fn char_to_cell(chr: char) -> Option<(Background, Foregroun...
{ columns: usize, rows: usize, background: Vec<Background>, crates: HashMap<Position, usize>, worker_position: Position, } fn is_empty_or_comment(s: &str) -> bool { s.is_empty() || s.trim().starts_with(';') } impl LevelBuilder { pub fn new(rank: usize, level_string: &str) -> Result<Self, ...
LevelBuilder
identifier_name
builder.rs
use std::collections::{HashMap, VecDeque}; use crate::level::{Background, Level}; use crate::position::*; use crate::util::*; /// Dynamic part of a cell. #[derive(Debug, Clone, Copy, PartialEq, Hash)] pub enum Foreground { None, Worker, Crate, } fn char_to_cell(chr: char) -> Option<(Background, Foregroun...
pub(crate) struct LevelBuilder { columns: usize, rows: usize, background: Vec<Background>, crates: HashMap<Position, usize>, worker_position: Position, } fn is_empty_or_comment(s: &str) -> bool { s.is_empty() || s.trim().starts_with(';') } impl LevelBuilder { pub fn new(rank: usize, leve...
{ match chr { '#' => Some((Background::Wall, Foreground::None)), ' ' => Some((Background::Empty, Foreground::None)), '$' => Some((Background::Floor, Foreground::Crate)), '@' => Some((Background::Floor, Foreground::Worker)), '.' => Some((Background::Goal, Foreground::None)), ...
identifier_body
hybridmulti.rs
// Copyright 2016 The Noise-rs Developers. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ...
() { debug::render_noise_module3("hybridmulti.png", &HybridMulti::new(), 1024, 1024, 200); }
main
identifier_name
hybridmulti.rs
// Copyright 2016 The Noise-rs Developers. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ...
extern crate noise; use noise::HybridMulti; mod debug; fn main() { debug::render_noise_module3("hybridmulti.png", &HybridMulti::new(), 1024, 1024, 200); }
//! An example of using the `HybridMulti` noise function
random_line_split
hybridmulti.rs
// Copyright 2016 The Noise-rs Developers. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ...
{ debug::render_noise_module3("hybridmulti.png", &HybridMulti::new(), 1024, 1024, 200); }
identifier_body
24_game_solve.rs
// http://rosettacode.org/wiki/24_game/Solve // modeled after the scala solution // http://rosettacode.org/wiki/24_game/Solve#Scala #![feature(collections)] #![feature(slice_patterns)] extern crate num; use num::rational::{Ratio, Rational}; use num::traits::Zero; // convenience macro to create a fixed-sized vector //...
() { assert_eq!( // without the rationals! macro [Ratio::from_integer(1), Ratio::from_integer(2), Ratio::from_integer(3), Ratio::from_integer(4)], // with the rationals! macro (rationals![1, 2, 3, 4])); } #[test] #[ignore] // printing of rationals changed but seems wrong... fn test_solv...
test_rationals_macro
identifier_name
24_game_solve.rs
// http://rosettacode.org/wiki/24_game/Solve // modeled after the scala solution // http://rosettacode.org/wiki/24_game/Solve#Scala #![feature(collections)] #![feature(slice_patterns)] extern crate num; use num::rational::{Ratio, Rational}; use num::traits::Zero; // convenience macro to create a fixed-sized vector //...
} rt } } } #[test] fn test_rationals_macro() { assert_eq!( // without the rationals! macro [Ratio::from_integer(1), Ratio::from_integer(2), Ratio::from_integer(3), Ratio::from_integer(4)], // with the rationals! macro (rationals![1, 2, 3, 4])); } #[te...
random_line_split
24_game_solve.rs
// http://rosettacode.org/wiki/24_game/Solve // modeled after the scala solution // http://rosettacode.org/wiki/24_game/Solve#Scala #![feature(collections)] #![feature(slice_patterns)] extern crate num; use num::rational::{Ratio, Rational}; use num::traits::Zero; // convenience macro to create a fixed-sized vector //...
{ let mut r = rationals![1, 3, 7, 9]; assert_eq!( solve(&mut r[..], 24), Some("(9 / (3 / (1 + 7)))".to_string())); }
identifier_body