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 |
|---|---|---|---|---|
css_provider.rs | // Copyright 2013-2015, 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 <http://opensource.org/licenses/MIT>
use std::fmt::{self, Display, Formatter};
use ffi::{self, GtkCssProvider};
use glib::translat... | else {
Err(glib::Error::wrap(error))
}
}
}
}
impl Display for CssProvider {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let tmp: String = unsafe { from_glib_full(ffi::gtk_css_provider_to_string(self.pointer)) };
write!(f, "{}", tmp)
}
}
impl_GObj... | {
Ok(CssProvider { pointer: pointer })
} | conditional_block |
generic-tup.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 ... | info!("{:?}", get_third((1, 2, 3)));
assert_eq!(get_third((1, 2, 3)), 3);
assert_eq!(get_third((5u8, 6u8, 7u8)), 7u8);
} |
fn get_third<T>(t: (T, T, T)) -> T { let (_, _, x) = t; return x; }
pub fn main() { | random_line_split |
generic-tup.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 ... | {
info!("{:?}", get_third((1, 2, 3)));
assert_eq!(get_third((1, 2, 3)), 3);
assert_eq!(get_third((5u8, 6u8, 7u8)), 7u8);
} | identifier_body | |
generic-tup.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 ... | () {
info!("{:?}", get_third((1, 2, 3)));
assert_eq!(get_third((1, 2, 3)), 3);
assert_eq!(get_third((5u8, 6u8, 7u8)), 7u8);
}
| main | identifier_name |
incremental.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 flow::{self, AFFECTS_COUNTERS, Flow, HAS_COUNTER_AFFECTING_CHILDREN, IS_ABSOLUTELY_POSITIONED};
use std::fmt;
... |
}
| {
let self_base = flow::mut_base(self);
self_base.restyle_damage.insert(RestyleDamage::rebuild_and_reflow());
self_base.restyle_damage.remove(RECONSTRUCT_FLOW);
for kid in self_base.children.iter_mut() {
kid.reflow_entire_document();
}
} | identifier_body |
incremental.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 flow::{self, AFFECTS_COUNTERS, Flow, HAS_COUNTER_AFFECTING_CHILDREN, IS_ABSOLUTELY_POSITIONED};
use std::fmt;
... |
let self_base = flow::mut_base(self);
if self_base.flags.float_kind()!= float::T::none &&
self_base.restyle_damage.intersects(REFLOW) {
special_damage.insert(REFLOW_ENTIRE_DOCUMENT);
}
if has_counter_affecting_children {
self_base.flags.insert(HA... | } | random_line_split |
incremental.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 flow::{self, AFFECTS_COUNTERS, Flow, HAS_COUNTER_AFFECTING_CHILDREN, IS_ABSOLUTELY_POSITIONED};
use std::fmt;
... | else {
self_base.flags.remove(HAS_COUNTER_AFFECTING_CHILDREN)
}
special_damage
}
fn reflow_entire_document(self) {
let self_base = flow::mut_base(self);
self_base.restyle_damage.insert(RestyleDamage::rebuild_and_reflow());
self_base.restyle_damage.remove(RE... | {
self_base.flags.insert(HAS_COUNTER_AFFECTING_CHILDREN)
} | conditional_block |
incremental.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 flow::{self, AFFECTS_COUNTERS, Flow, HAS_COUNTER_AFFECTING_CHILDREN, IS_ABSOLUTELY_POSITIONED};
use std::fmt;
... | (self) -> SpecialRestyleDamage {
let mut special_damage = SpecialRestyleDamage::empty();
let is_absolutely_positioned = flow::base(self).flags.contains(IS_ABSOLUTELY_POSITIONED);
// In addition to damage, we use this phase to compute whether nodes affect CSS counters.
let mut has_counte... | compute_layout_damage | identifier_name |
make_current_guard.rs | use std::marker::PhantomData;
use std::os::raw::c_void;
use std::io;
use winapi::shared::windef::{HDC, HGLRC};
use CreationError;
use super::gl;
/// A guard for when you want to make the context current. Destroying the guard restores the
/// previously-current context.
pub struct CurrentContextGuard<'a, 'b> {
pre... |
}
impl<'a, 'b> Drop for CurrentContextGuard<'a, 'b> {
fn drop(&mut self) {
unsafe {
gl::wgl::MakeCurrent(self.previous_hdc as *const c_void,
self.previous_hglrc as *const c_void);
}
}
}
| {
let previous_hdc = gl::wgl::GetCurrentDC() as HDC;
let previous_hglrc = gl::wgl::GetCurrentContext() as HGLRC;
let result = gl::wgl::MakeCurrent(hdc as *const _, context as *const _);
if result == 0 {
return Err(CreationError::OsError(format!("wglMakeCurrent function faile... | identifier_body |
make_current_guard.rs | use std::marker::PhantomData;
use std::os::raw::c_void;
use std::io;
use winapi::shared::windef::{HDC, HGLRC};
use CreationError;
| previous_hglrc: HGLRC,
marker1: PhantomData<&'a ()>,
marker2: PhantomData<&'b ()>,
}
impl<'a, 'b> CurrentContextGuard<'a, 'b> {
pub unsafe fn make_current(hdc: HDC, context: HGLRC)
-> Result<CurrentContextGuard<'a, 'b>, CreationError>
{
let previous_hdc = gl::... | use super::gl;
/// A guard for when you want to make the context current. Destroying the guard restores the
/// previously-current context.
pub struct CurrentContextGuard<'a, 'b> {
previous_hdc: HDC, | random_line_split |
make_current_guard.rs | use std::marker::PhantomData;
use std::os::raw::c_void;
use std::io;
use winapi::shared::windef::{HDC, HGLRC};
use CreationError;
use super::gl;
/// A guard for when you want to make the context current. Destroying the guard restores the
/// previously-current context.
pub struct CurrentContextGuard<'a, 'b> {
pre... |
Ok(CurrentContextGuard {
previous_hdc: previous_hdc,
previous_hglrc: previous_hglrc,
marker1: PhantomData,
marker2: PhantomData,
})
}
}
impl<'a, 'b> Drop for CurrentContextGuard<'a, 'b> {
fn drop(&mut self) {
unsafe {
gl::wgl... | {
return Err(CreationError::OsError(format!("wglMakeCurrent function failed: {}",
format!("{}", io::Error::last_os_error()))));
} | conditional_block |
make_current_guard.rs | use std::marker::PhantomData;
use std::os::raw::c_void;
use std::io;
use winapi::shared::windef::{HDC, HGLRC};
use CreationError;
use super::gl;
/// A guard for when you want to make the context current. Destroying the guard restores the
/// previously-current context.
pub struct | <'a, 'b> {
previous_hdc: HDC,
previous_hglrc: HGLRC,
marker1: PhantomData<&'a ()>,
marker2: PhantomData<&'b ()>,
}
impl<'a, 'b> CurrentContextGuard<'a, 'b> {
pub unsafe fn make_current(hdc: HDC, context: HGLRC)
-> Result<CurrentContextGuard<'a, 'b>, CreationError>
... | CurrentContextGuard | identifier_name |
menu_button.rs | // Copyright 2013-2015, 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 <http://opensource.org/licenses/MIT>
//! A widget that shows a menu when clicked on
use ffi;
use cast::GTK_MENUBUTTON;
use ArrowT... | pub fn set_align_widget<T: ::WidgetTrait>(&self, align_widget: &T) -> () {
unsafe {
ffi::gtk_menu_button_set_align_widget(GTK_MENUBUTTON(self.pointer), align_widget.unwrap_widget())
}
}
}
impl_drop!(MenuButton);
impl_TraitWidget!(MenuButton);
impl ::ContainerTrait for MenuButton {}... | unsafe {
ffi::gtk_menu_button_get_direction(GTK_MENUBUTTON(self.pointer))
}
}
| identifier_body |
menu_button.rs | // Copyright 2013-2015, 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 <http://opensource.org/licenses/MIT>
//! A widget that shows a menu when clicked on
use ffi;
use cast::GTK_MENUBUTTON;
use ArrowT... | self) -> ArrowType {
unsafe {
ffi::gtk_menu_button_get_direction(GTK_MENUBUTTON(self.pointer))
}
}
pub fn set_align_widget<T: ::WidgetTrait>(&self, align_widget: &T) -> () {
unsafe {
ffi::gtk_menu_button_set_align_widget(GTK_MENUBUTTON(self.pointer), align_widget... | t_direction(& | identifier_name |
menu_button.rs | // Copyright 2013-2015, 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 <http://opensource.org/licenses/MIT>
//! A widget that shows a menu when clicked on
use ffi;
use cast::GTK_MENUBUTTON;
use ArrowT... |
pub fn set_direction(&self, direction: ArrowType) -> () {
unsafe {
ffi::gtk_menu_button_set_direction(GTK_MENUBUTTON(self.pointer), direction);
}
}
pub fn get_direction(&self) -> ArrowType {
unsafe {
ffi::gtk_menu_button_get_direction(GTK_MENUBUTTON(self.poi... | random_line_split | |
htmlfieldsetelement.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::utils::{DOMString, ErrorResult};
use dom::htmlcollection::HTMLCollection;
use dom::htmlelement:... |
}
| {
} | identifier_body |
htmlfieldsetelement.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::utils::{DOMString, ErrorResult};
use dom::htmlcollection::HTMLCollection;
use dom::htmlelement:... | }
pub fn Name(&self) -> DOMString {
None
}
pub fn SetName(&mut self, _name: &DOMString) -> ErrorResult {
Ok(())
}
pub fn Type(&self) -> DOMString {
None
}
pub fn Elements(&self) -> @mut HTMLCollection {
let window = self.htmlelement.element.node.owner_... | None | random_line_split |
htmlfieldsetelement.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::utils::{DOMString, ErrorResult};
use dom::htmlcollection::HTMLCollection;
use dom::htmlelement:... | (&self) -> @mut ValidityState {
let global = self.htmlelement.element.node.owner_doc().document().window;
ValidityState::new(global)
}
pub fn ValidationMessage(&self) -> DOMString {
None
}
pub fn CheckValidity(&self) -> bool {
false
}
pub fn SetCustomValidity(&... | Validity | identifier_name |
enum-non-c-like-repr-c-and-int.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 ... | 4 => MyEnumTag::E,
_ => return Err(()),
};
match dest.tag {
MyEnumTag::A => {
dest.payload.A.0 = read_u32_le(buf)?;
}
MyEnumTag::B => {
dest.payload.B.x = read_u8(buf)?;
dest.payload.B.y = read_u... | dest.tag = match tag {
0 => MyEnumTag::A,
1 => MyEnumTag::B,
2 => MyEnumTag::C,
3 => MyEnumTag::D, | random_line_split |
enum-non-c-like-repr-c-and-int.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 ... | (Duration);
fn main() {
let result: Vec<Result<MyEnum, ()>> = vec![
Ok(MyEnum::A(17)),
Ok(MyEnum::B { x: 206, y: 1145 }),
Ok(MyEnum::C),
Err(()),
Ok(MyEnum::D(Some(407))),
Ok(MyEnum::D(None)),
Ok(MyEnum::E(Duration::from_secs(100))),
Err(()),
];
... | MyEnumVariantE | identifier_name |
enum-non-c-like-repr-c-and-int.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 val = buf[0];
*buf = &buf[1..];
Ok(val)
}
| { return Err(()) } | conditional_block |
enum-non-c-like-repr-c-and-int.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 ... | dest.payload.B.x = read_u8(buf)?;
dest.payload.B.y = read_u16_le(buf)? as i16;
}
MyEnumTag::C => {
/* do nothing */
}
MyEnumTag::D => {
let is_some = read_u8(buf)? == 0;
if is_some {
... | {
unsafe {
// Should be correct to do this transmute.
let dest: &'a mut MyEnumRepr = mem::transmute(dest);
let tag = read_u8(buf)?;
dest.tag = match tag {
0 => MyEnumTag::A,
1 => MyEnumTag::B,
2 => MyEnumTag::C,
3 => MyEnumTag::D,
... | identifier_body |
move-into-dead-array-2.rs | // Copyright 2015 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 ... | () {
foo([d(), d(), d(), d()], 1);
foo([d(), d(), d(), d()], 3);
}
fn foo(mut a: [D; 4], i: usize) {
drop(a);
a[i] = d(); //~ ERROR use of moved value: `a`
}
| main | identifier_name |
move-into-dead-array-2.rs | // Copyright 2015 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Ensure that w... | random_line_split | |
net.rs | // Copyright 2015 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 fd = try!(cvt(libc::socket(fam, ty, 0)));
Ok(Socket(FileDesc::new(fd)))
}
}
pub fn accept(&self, storage: *mut libc::sockaddr,
len: *mut libc::socklen_t) -> io::Result<Socket> {
let fd = try!(cvt_r(|| unsafe {
libc::accept(self.0.raw(), ... | };
unsafe { | random_line_split |
net.rs | // Copyright 2015 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 ... |
pub fn cvt_gai(err: c_int) -> io::Result<()> {
if err == 0 { return Ok(()) }
let detail = unsafe {
str::from_utf8(CStr::from_ptr(c::gai_strerror(err)).to_bytes()).unwrap()
.to_string()
};
Err(io::Error::new(io::ErrorKind::Other,
&format!("failed to lookup add... | {} | identifier_body |
net.rs | // Copyright 2015 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 ... | (fd: c_int) -> Socket { Socket(FileDesc::new(fd)) }
}
| from_inner | identifier_name |
webglvertexarrayobjectoes.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::webgl::WebGLVertexArrayId;
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bin... |
pub fn borrow_bound_attrib_buffers(&self) -> Ref<HashMap<u32, Dom<WebGLBuffer>>> {
self.bound_attrib_buffers.borrow()
}
pub fn bound_attrib_buffers(&self) -> Vec<DomRoot<WebGLBuffer>> {
self.bound_attrib_buffers.borrow().iter().map(|(_, b)| DomRoot::from_ref(&**b)).collect()
}
pub... |
pub fn set_ever_bound(&self) {
self.ever_bound.set(true);
} | random_line_split |
webglvertexarrayobjectoes.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::webgl::WebGLVertexArrayId;
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bin... | (global: &GlobalScope, id: WebGLVertexArrayId) -> DomRoot<WebGLVertexArrayObjectOES> {
reflect_dom_object(Box::new(WebGLVertexArrayObjectOES::new_inherited(id)),
global,
WebGLVertexArrayObjectOESBinding::Wrap)
}
pub fn id(&self) -> WebGLVertexArrayI... | new | identifier_name |
webglvertexarrayobjectoes.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::webgl::WebGLVertexArrayId;
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bin... |
pub fn set_deleted(&self) {
self.is_deleted.set(true)
}
pub fn ever_bound(&self) -> bool {
return self.ever_bound.get()
}
pub fn set_ever_bound(&self) {
self.ever_bound.set(true);
}
pub fn borrow_bound_attrib_buffers(&self) -> Ref<HashMap<u32, Dom<WebGLBuffer>>> ... | {
self.is_deleted.get()
} | identifier_body |
config.rs | use actix_web::web;
/// Run custom configuration as part of the application building
/// process.
///
/// This function should contain all custom configuration for your function application.
///
/// ```rust
/// fn configure(cfg: &mut web::ServiceConfig) {
/// let db_driver = my_db();
/// cfg.data(db_driver.clo... |
/// An example of the function configuration structure.
pub struct HandlerConfig {
pub name: String,
}
impl Default for HandlerConfig {
fn default() -> HandlerConfig {
HandlerConfig {
name: String::from("world"),
}
}
}
| {
log::info!("Configuring service");
cfg.data(HandlerConfig::default());
} | identifier_body |
config.rs | use actix_web::web;
/// Run custom configuration as part of the application building
/// process.
///
/// This function should contain all custom configuration for your function application.
///
/// ```rust
/// fn configure(cfg: &mut web::ServiceConfig) {
/// let db_driver = my_db();
/// cfg.data(db_driver.clo... | (cfg: &mut web::ServiceConfig) {
log::info!("Configuring service");
cfg.data(HandlerConfig::default());
}
/// An example of the function configuration structure.
pub struct HandlerConfig {
pub name: String,
}
impl Default for HandlerConfig {
fn default() -> HandlerConfig {
HandlerConfig {
... | configure | identifier_name |
config.rs | use actix_web::web;
/// Run custom configuration as part of the application building
/// process.
///
/// This function should contain all custom configuration for your function application.
///
/// ```rust
/// fn configure(cfg: &mut web::ServiceConfig) {
/// let db_driver = my_db();
/// cfg.data(db_driver.clo... | }
} | name: String::from("world"),
} | random_line_split |
helpers.rs | extern crate diesel;
extern crate chrono;
extern crate dotenv;
extern crate serde;
extern crate wiko;
use std::path; | use wiko::models::*;
fn load_test_env() {
let mut path = path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
path.push("test.env");
dotenv::from_path(&path).expect("Invalid dotenv");
}
pub struct TestHelper;
impl TestHelper {
pub fn get_test_connection() -> WikoConnection {
load_test_env();
... | use self::diesel::*;
use wiko::{Wiko,WikoConnection}; | random_line_split |
helpers.rs | extern crate diesel;
extern crate chrono;
extern crate dotenv;
extern crate serde;
extern crate wiko;
use std::path;
use self::diesel::*;
use wiko::{Wiko,WikoConnection};
use wiko::models::*;
fn load_test_env() {
let mut path = path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
path.push("test.env");
dote... | () -> Wiko {
let conn = Self::get_test_connection();
Wiko::new(conn)
}
pub fn insert_post() -> Post {
let new_post = NewPost::default();
Self::new_wiko().create_post(&new_post).expect("Error creating new post")
}
pub fn get_post() -> Post {
let inserted = Self::... | new_wiko | identifier_name |
helpers.rs | extern crate diesel;
extern crate chrono;
extern crate dotenv;
extern crate serde;
extern crate wiko;
use std::path;
use self::diesel::*;
use wiko::{Wiko,WikoConnection};
use wiko::models::*;
fn load_test_env() {
let mut path = path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
path.push("test.env");
dote... |
pub fn get_post() -> Post {
let inserted = Self::insert_post();
Self::new_wiko().get_post(inserted.id).expect("Error getting post")
}
pub fn insert_post_revision() -> PostRevision {
let post = Self::get_post();
let new_post_revision = NewPostRevision::from_post(&post);
... | {
let new_post = NewPost::default();
Self::new_wiko().create_post(&new_post).expect("Error creating new post")
} | identifier_body |
properties.rs | use regex;
use serde_json::Value;
use std::collections;
use url;
use super::super::errors;
use super::super::scope;
#[derive(Debug)]
pub enum AdditionalKind {
Boolean(bool),
Schema(url::Url),
}
#[allow(missing_copy_implementations)]
pub struct Properties {
pub properties: collections::HashMap<String, url... | (&self, val: &Value, path: &str, scope: &scope::Scope) -> super::ValidationState {
let object = nonstrict_process!(val.as_object(), path);
let mut state = super::ValidationState::new();
'main: for (key, value) in object.iter() {
let is_property_passed = if self.properties.contains_ke... | validate | identifier_name |
properties.rs | use regex;
use serde_json::Value;
use std::collections;
use url;
use super::super::errors;
use super::super::scope;
#[derive(Debug)]
pub enum AdditionalKind {
Boolean(bool),
Schema(url::Url),
}
#[allow(missing_copy_implementations)]
pub struct Properties {
pub properties: collections::HashMap<String, url... | }
AdditionalKind::Schema(ref url) => {
let schema = scope.resolve(url);
if schema.is_some() {
let value_path = [path, key.as_ref()].join("/");
state.append(schema.unwrap().validate_in(value, value_pa... | AdditionalKind::Boolean(allowed) if !allowed => {
state.errors.push(Box::new(errors::Properties {
path: path.to_string(),
detail: format!("Additional property '{}' is not allowed", key)
})) | random_line_split |
cargo_generate_lockfile.rs | use std::collections::{BTreeMap, HashSet};
use core::PackageId;
use core::registry::PackageRegistry;
use core::{Resolve, SourceId, Workspace};
use core::resolver::Method;
use ops;
use util::config::Config;
use util::CargoResult;
pub struct UpdateOptions<'a> {
pub config: &'a Config,
pub to_update: &'a [String... | fill_with_deps(&previous_resolve, dep, &mut to_avoid,
&mut HashSet::new());
} else {
to_avoid.insert(dep);
sources.push(match opts.precise {
Some(precise) => {
// TODO: see comment in `... | {
if opts.aggressive && opts.precise.is_some() {
bail!("cannot specify both aggressive and precise simultaneously")
}
let previous_resolve = match try!(ops::load_pkg_lockfile(ws)) {
Some(resolve) => resolve,
None => return generate_lockfile(ws),
};
let mut registry = Packag... | identifier_body |
cargo_generate_lockfile.rs | use std::collections::{BTreeMap, HashSet};
use core::PackageId;
use core::registry::PackageRegistry;
use core::{Resolve, SourceId, Workspace};
use core::resolver::Method;
use ops;
use util::config::Config;
use util::CargoResult;
pub struct UpdateOptions<'a> {
pub config: &'a Config,
pub to_update: &'a [String... | <'a>(resolve: &'a Resolve, dep: &'a PackageId,
set: &mut HashSet<&'a PackageId>,
visited: &mut HashSet<&'a PackageId>) {
if!visited.insert(dep) {
return
}
set.insert(dep);
for dep in resolve.deps(dep) {
fill_with... | fill_with_deps | identifier_name |
cargo_generate_lockfile.rs | use std::collections::{BTreeMap, HashSet};
use core::PackageId;
use core::registry::PackageRegistry;
use core::{Resolve, SourceId, Workspace};
use core::resolver::Method;
use ops;
use util::config::Config;
use util::CargoResult;
pub struct UpdateOptions<'a> {
pub config: &'a Config,
pub to_update: &'a [String... | None => {
dep.source_id().clone().with_precise(None)
}
});
}
}
try!(registry.add_sources(&sources));
}
let resolve = try!(ops::resolve_with_previous(&mut registry,
... | random_line_split | |
lib.rs | //! Serving contents of static directory.
//!
//! ```no_run
//! extern crate staticdir;
//! extern crate iron; | //! Iron::new(StaticDir::new(".", AsJson)).http("localhost:3000").unwrap();
//! }
//! ```
//!
//! This will provide JSON similar to this:
//!
//!```ignore
//! [
//! {
//! "file_type": "File", // "File", "Dir" or "Symlink"
//! "file_name": ".gitignore",
//! "size": 7,
//! "creation_time": null, // ... | //!
//! use iron::prelude::*;
//! use staticdir::{ StaticDir, AsJson };
//!
//! fn main() { | random_line_split |
assertions_on_constants.rs | //FIXME: suggestions are wrongly expanded, this should be fixed along with #7843
#![allow(non_fmt_panics)]
macro_rules! assert_const {
($len:expr) => {
assert!($len > 0);
debug_assert!($len < 0);
};
}
fn | () {
assert!(true);
assert!(false);
assert!(true, "true message");
assert!(false, "false message");
let msg = "panic message";
assert!(false, "{}", msg.to_uppercase());
const B: bool = true;
assert!(B);
const C: bool = false;
assert!(C);
assert!(C, "C message");
debug... | main | identifier_name |
assertions_on_constants.rs | //FIXME: suggestions are wrongly expanded, this should be fixed along with #7843
#![allow(non_fmt_panics)]
macro_rules! assert_const {
($len:expr) => {
assert!($len > 0);
debug_assert!($len < 0);
};
}
fn main() {
assert!(true);
assert!(false);
assert!(true, "true message");
asse... | assert_const!(-1);
// Don't lint on this:
assert!(cfg!(feature = "hey") || cfg!(not(feature = "asdf")));
} |
debug_assert!(true);
// Don't lint this, since there is no better way for expressing "Only panic in debug mode".
debug_assert!(false); // #3948
assert_const!(3); | random_line_split |
assertions_on_constants.rs | //FIXME: suggestions are wrongly expanded, this should be fixed along with #7843
#![allow(non_fmt_panics)]
macro_rules! assert_const {
($len:expr) => {
assert!($len > 0);
debug_assert!($len < 0);
};
}
fn main() | assert_const!(-1);
// Don't lint on this:
assert!(cfg!(feature = "hey") || cfg!(not(feature = "asdf")));
}
| {
assert!(true);
assert!(false);
assert!(true, "true message");
assert!(false, "false message");
let msg = "panic message";
assert!(false, "{}", msg.to_uppercase());
const B: bool = true;
assert!(B);
const C: bool = false;
assert!(C);
assert!(C, "C message");
debug_as... | identifier_body |
slice-2.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 ... | x[mut]; //~ ERROR cannot take a mutable slice of a value with type `Foo`
x[mut Foo..]; //~ ERROR cannot take a mutable slice of a value with type `Foo`
x[mut..Foo]; //~ ERROR cannot take a mutable slice of a value with type `Foo`
x[mut Foo..Foo]; //~ ERROR cannot take a mutable slice of a value with typ... | x[]; //~ ERROR cannot take a slice of a value with type `Foo`
x[Foo..]; //~ ERROR cannot take a slice of a value with type `Foo`
x[..Foo]; //~ ERROR cannot take a slice of a value with type `Foo`
x[Foo..Foo]; //~ ERROR cannot take a slice of a value with type `Foo` | random_line_split |
slice-2.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 ... | () {
let x = Foo;
x[]; //~ ERROR cannot take a slice of a value with type `Foo`
x[Foo..]; //~ ERROR cannot take a slice of a value with type `Foo`
x[..Foo]; //~ ERROR cannot take a slice of a value with type `Foo`
x[Foo..Foo]; //~ ERROR cannot take a slice of a value with type `Foo`
x[mut]; //~ ... | main | identifier_name |
mod.rs | //
// 0 1 0 Mnemosyne: a functional systems programming language.
// 0 0 1 (c) 2015 Hawk Weisman
// 1 1 1 hi@hawkweisman.me
//
// Mnemosyne is released under the MIT License. Please refer to
// the LICENSE file at the top-level directory of this distribution
// or at https://github.com/hawkw/mnemosyne/.
//
//!... | .take($to)
.collect::<String>() )
}
pub mod ast;
pub mod types;
pub mod annotations;
impl<'a> AnnotateTypes<'a> for Unscoped<'a, Form<'a, UnscopedState>> {
#[allow(unused_variables)]
fn annotate_types(self, scope: SymbolTable) -> Scoped<'a, Self> {
unimple... | #[macro_use]
macro_rules! indent {
($to:expr) => ( iter::repeat('\t') | random_line_split |
mod.rs | //
// 0 1 0 Mnemosyne: a functional systems programming language.
// 0 0 1 (c) 2015 Hawk Weisman
// 1 1 1 hi@hawkweisman.me
//
// Mnemosyne is released under the MIT License. Please refer to
// the LICENSE file at the top-level directory of this distribution
// or at https://github.com/hawkw/mnemosyne/.
//
//!... |
}
| {
match *self {
SymbolAnnotation::TypeDef(ref ty) =>
match *ty { Type::Prim(_) => true
, _ => false
}
, _ => false
}
} | identifier_body |
mod.rs | //
// 0 1 0 Mnemosyne: a functional systems programming language.
// 0 0 1 (c) 2015 Hawk Weisman
// 1 1 1 hi@hawkweisman.me
//
// Mnemosyne is released under the MIT License. Please refer to
// the LICENSE file at the top-level directory of this distribution
// or at https://github.com/hawkw/mnemosyne/.
//
//!... | (&self) -> bool {
match *self {
SymbolAnnotation::TypeDef(ref ty) =>
match *ty { Type::Prim(_) => true
, _ => false
}
, _ => false
}
}
}
| is_prim_type | identifier_name |
issue-30018-nopanic.rs | // run-pass
#![allow(unreachable_code)]
// More thorough regression test for Issues #30018 and #30822. This
// attempts to explore different ways that array element construction
// (for both scratch arrays and non-scratch ones) interacts with
// breaks in the control-flow, in terms of the order of evaluation of
// the ... | assert_eq!(&log.borrow()[..], &[20, 21, 22]);
log.borrow_mut().clear();
// CASE 3: (Borrow of) slice-index of array is stored in _r slot.
loop {
let _r = &[D(log, 30),
D(log, 31),
D(log, 32)][..];
break;
}
assert_eq!(&log.borrow()[..], &[30,... | {
let log = &RefCell::new(Vec::new());
// CASE 1: Fixed-size array itself is stored in _r slot.
loop {
let _r = [D(log, 10),
D(log, 11),
D(log, 12)];
break;
}
assert_eq!(&log.borrow()[..], &[10, 11, 12]);
log.borrow_mut().clear();
// CASE... | identifier_body |
issue-30018-nopanic.rs | // run-pass
#![allow(unreachable_code)]
// More thorough regression test for Issues #30018 and #30822. This
// attempts to explore different ways that array element construction
// (for both scratch arrays and non-scratch ones) interacts with
// breaks in the control-flow, in terms of the order of evaluation of
// the ... | break;
}
assert_eq!(&log.borrow()[..], &[30, 31, 32]);
log.borrow_mut().clear();
} | loop {
let _r = &[D(log, 30),
D(log, 31),
D(log, 32)][..]; | random_line_split |
issue-30018-nopanic.rs | // run-pass
#![allow(unreachable_code)]
// More thorough regression test for Issues #30018 and #30822. This
// attempts to explore different ways that array element construction
// (for both scratch arrays and non-scratch ones) interacts with
// breaks in the control-flow, in terms of the order of evaluation of
// the ... | <'a>(&'a RefCell<Vec<i32>>, i32);
impl<'a> Drop for D<'a> {
fn drop(&mut self) {
println!("Dropping D({})", self.1);
(self.0).borrow_mut().push(self.1);
}
}
fn main() {
println!("Start");
break_during_elem();
break_after_whole();
println!("Finis");
}
fn break_during_elem() {
... | D | identifier_name |
fillable.rs | use errors::*;
use std::cmp;
/// Fillable is a range from [0,size) that can be filled by subranges.
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct Fillable {
size: u64,
contents: Vec<Interval>,
}
impl Fillable {
pub fn new(size: u64) -> Self {
Fillable {
size: size,
... | if start >= self.size {
bail!("first_unfilled_starting_at start:{} >= size:{}",
start,
self.size);
}
if self.contents.is_empty() {
return Ok(Some(start));
}
for interval in self.contents.iter() {
if interval.... |
/// Get the index of the first unfilled byte starting at offset.
/// Returns some offset in [start, self.size)
/// Returns None if everything from then on is filled.
pub fn first_unfilled_starting_at(&self, start: u64) -> Result<Option<u64>> { | random_line_split |
fillable.rs | use errors::*;
use std::cmp;
/// Fillable is a range from [0,size) that can be filled by subranges.
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct Fillable {
size: u64,
contents: Vec<Interval>,
}
impl Fillable {
pub fn new(size: u64) -> Self {
Fillable {
size: size,
... | (&self) -> u64 {
return self.size;
}
pub fn has(&self, n: u64) -> bool {
for i in self.contents.iter() {
if n < i.end {
return i.start <= n;
}
}
return false;
}
/// Fill the range [a, b)
/// Returns whether this piece is _newl... | size | identifier_name |
fillable.rs | use errors::*;
use std::cmp;
/// Fillable is a range from [0,size) that can be filled by subranges.
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct Fillable {
size: u64,
contents: Vec<Interval>,
}
impl Fillable {
pub fn new(size: u64) -> Self {
Fillable {
size: size,
... |
pub fn is_empty(&self) -> bool {
self.contents.len() == 0
}
pub fn size(&self) -> u64 {
return self.size;
}
pub fn has(&self, n: u64) -> bool {
for i in self.contents.iter() {
if n < i.end {
return i.start <= n;
}
}
... | {
let r = self.contents.len() == 1 && self.contents[0].start == 0 && self.contents[0].end == self.size;
// println!("is_full {:?} = {}", self, r);
return r;
} | identifier_body |
issue-2804.rs | // Copyright 2012-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-MI... | }
fn lookup(table: json::JsonObject, key: String, default: String) -> String
{
match table.find(&key.to_string()) {
option::Some(&json::String(ref s)) => {
s.to_string()
}
option::Some(value) => {
println!("{} was expected to be a string but is a {:?}", key, value);
... |
enum object {
bool_value(bool),
int_value(i64), | random_line_split |
issue-2804.rs |
// Copyright 2012-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-M... | {
bool_value(bool),
int_value(i64),
}
fn lookup(table: json::JsonObject, key: String, default: String) -> String
{
match table.find(&key.to_string()) {
option::Some(&json::String(ref s)) => {
s.to_string()
}
option::Some(value) => {
println!("{} was expected... | object | identifier_name |
issue-2804.rs |
// Copyright 2012-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-M... |
fn add_interface(_store: int, managed_ip: String, data: json::Json) -> (String, object)
{
match &data {
&json::Object(ref interface) => {
let name = lookup(interface.clone(),
"ifDescr".to_string(),
"".to_string());
let lab... | {
match table.find(&key.to_string()) {
option::Some(&json::String(ref s)) => {
s.to_string()
}
option::Some(value) => {
println!("{} was expected to be a string but is a {:?}", key, value);
default
}
option::None => {
default
... | identifier_body |
mutex.rs | use futures::channel::mpsc;
use futures::executor::block_on;
use futures::future::{ready, FutureExt};
use futures::lock::Mutex;
use futures::stream::StreamExt;
use futures::task::{Context, SpawnExt};
use futures_test::future::FutureTestExt;
use futures_test::task::{new_count_waker, panic_context};
use std::sync::Arc;
... | () {
let mutex = Mutex::new(());
for _ in 0..10 {
assert!(mutex.lock().poll_unpin(&mut panic_context()).is_ready());
}
}
#[test]
fn mutex_wakes_waiters() {
let mutex = Mutex::new(());
let (waker, counter) = new_count_waker();
let lock = mutex.lock().poll_unpin(&mut panic_context());
... | mutex_acquire_uncontested | identifier_name |
mutex.rs | use futures::channel::mpsc;
use futures::executor::block_on;
use futures::future::{ready, FutureExt};
use futures::lock::Mutex;
use futures::stream::StreamExt;
use futures::task::{Context, SpawnExt};
use futures_test::future::FutureTestExt;
use futures_test::task::{new_count_waker, panic_context};
use std::sync::Arc;
... | assert_eq!(num_tasks, *lock);
})
} | let lock = mutex.lock().await; | random_line_split |
mutex.rs | use futures::channel::mpsc;
use futures::executor::block_on;
use futures::future::{ready, FutureExt};
use futures::lock::Mutex;
use futures::stream::StreamExt;
use futures::task::{Context, SpawnExt};
use futures_test::future::FutureTestExt;
use futures_test::task::{new_count_waker, panic_context};
use std::sync::Arc;
... |
#[test]
fn mutex_contested() {
let (tx, mut rx) = mpsc::unbounded();
let pool = futures::executor::ThreadPool::builder()
.pool_size(16)
.create()
.unwrap();
let tx = Arc::new(tx);
let mutex = Arc::new(Mutex::new(0));
let num_tasks = 1000;
for _ in 0..num_tasks {
... | {
let mutex = Mutex::new(());
let (waker, counter) = new_count_waker();
let lock = mutex.lock().poll_unpin(&mut panic_context());
assert!(lock.is_ready());
let mut cx = Context::from_waker(&waker);
let mut waiter = mutex.lock();
assert!(waiter.poll_unpin(&mut cx).is_pending());
assert_e... | identifier_body |
enc_dec.rs | // Encoding and decoding routines.
//
// Copyright (c) 2016 Ivan Nejgebauer <inejge@gmail.com>
//
// Licensed under the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>. This file may not be copied,
// modified, or distributed except according to the terms of this
// license.
use std::char;
use std::... |
s >>= 6;
s |= (dec as u32) << 26;
processed += 1;
if processed == len {
break;
}
}
if processed < len {
return Err(Error::InsufficientLength);
}
Ok(s >> (32 - 6 * len))
}
pub fn encode_val(mut val: u32, mut nhex: usize) -> String {
let mut val_arr = [0u8; 4];
if nhex > 4 {
nhex = 4... | {
return Err(Error::EncodingError);
} | conditional_block |
enc_dec.rs | // Encoding and decoding routines.
//
// Copyright (c) 2016 Ivan Nejgebauer <inejge@gmail.com>
//
// Licensed under the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>. This file may not be copied,
// modified, or distributed except according to the terms of this
// license.
use std::char;
use std::... | if dec_idx == decbuf.len() {
break;
}
cbuild = dec & (0x3F >> cpos);
}
cpos += 2;
if cpos > 6 {
cpos = 0;
}
}
Ok(())
}
pub fn bcrypt_hash64_encode(bs: &[u8]) -> String {
b_c_hash64_encode(bs, &BCRYPT_HASH64)
}
pub fn crypt_hash64_encode(bs: &[u8]) -> String {
b_c_hash64_enco... | {
let mut cbuild = 0u8;
let mut cpos = 0;
let mut dec_idx = 0;
for b in enc.chars() {
let b = b as u32 - 0x20;
if b > 0x60 {
return Err(Error::EncodingError);
}
let dec = BCRYPT_HASH64_ENC_MAP[b as usize];
if dec == 64 {
return Err(Error::EncodingError);
}
if cpos == 0 {
cbuild = d... | identifier_body |
enc_dec.rs | // Encoding and decoding routines.
//
// Copyright (c) 2016 Ivan Nejgebauer <inejge@gmail.com>
//
// Licensed under the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>. This file may not be copied,
// modified, or distributed except according to the terms of this
// license.
use std::char;
use std::... | (enc: &str, decbuf: &mut [u8]) -> Result<()> {
let mut cbuild = 0u8;
let mut cpos = 0;
let mut dec_idx = 0;
for b in enc.chars() {
let b = b as u32 - 0x20;
if b > 0x60 {
return Err(Error::EncodingError);
}
let dec = BCRYPT_HASH64_ENC_MAP[b as usize];
if dec == 64 {
return Err(Error::Encod... | bcrypt_hash64_decode | identifier_name |
enc_dec.rs | // Encoding and decoding routines.
//
// Copyright (c) 2016 Ivan Nejgebauer <inejge@gmail.com>
//
// Licensed under the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>. This file may not be copied,
// modified, or distributed except according to the terms of this
// license.
use std::char;
use std::... | if dec_idx == decbuf.len() {
break;
}
cbuild = dec & (0x3F >> cpos);
}
cpos += 2;
if cpos > 6 {
cpos = 0;
}
}
Ok(())
}
pub fn bcrypt_hash64_encode(bs: &[u8]) -> String {
b_c_hash64_encode(bs, &BCRYPT_HASH64)
}
pub fn crypt_hash64_encode(bs: &[u8]) -> String {
b_c_hash64_encod... | decbuf[dec_idx] = cbuild;
dec_idx += 1; | random_line_split |
disallow_typename_on_root_test.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @generated SignedSource<<2ea6403534fde8fe5781de95bd4059c7>>
*/
mod disallow_typename_on_root;
use disallow_typename_on_root::... | {
let input = include_str!("disallow_typename_on_root/fixtures/valid.graphql");
let expected = include_str!("disallow_typename_on_root/fixtures/valid.expected");
test_fixture(transform_fixture, "valid.graphql", "disallow_typename_on_root/fixtures/valid.expected", input, expected);
} | identifier_body | |
disallow_typename_on_root_test.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @generated SignedSource<<2ea6403534fde8fe5781de95bd4059c7>>
*/
mod disallow_typename_on_root;
use disallow_typename_on_root::... | #[test]
fn typename_on_query_invalid() {
let input = include_str!("disallow_typename_on_root/fixtures/typename-on-query.invalid.graphql");
let expected = include_str!("disallow_typename_on_root/fixtures/typename-on-query.invalid.expected");
test_fixture(transform_fixture, "typename-on-query.invalid.graphql"... | let expected = include_str!("disallow_typename_on_root/fixtures/typename-on-mutation.invalid.expected");
test_fixture(transform_fixture, "typename-on-mutation.invalid.graphql", "disallow_typename_on_root/fixtures/typename-on-mutation.invalid.expected", input, expected);
}
| random_line_split |
disallow_typename_on_root_test.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @generated SignedSource<<2ea6403534fde8fe5781de95bd4059c7>>
*/
mod disallow_typename_on_root;
use disallow_typename_on_root::... | () {
let input = include_str!("disallow_typename_on_root/fixtures/typename-on-mutation.invalid.graphql");
let expected = include_str!("disallow_typename_on_root/fixtures/typename-on-mutation.invalid.expected");
test_fixture(transform_fixture, "typename-on-mutation.invalid.graphql", "disallow_typename_on_roo... | typename_on_mutation_invalid | identifier_name |
array_builder.rs | use serde_json::{Value, to_value};
use serde::{Serialize, Serializer};
pub type JsonArray = Vec<Value>;
use object_builder;
pub struct ArrayBuilder {
pub array: JsonArray,
pub null: bool,
pub skip: bool,
pub root: Option<String>
}
/// Use ArrayBuilder to produce JSON arrays
impl ArrayBuilder {
... | array: array,
null: false,
skip: false,
root: None
}),
_ => None
}
}
/// Create new ArrayBuilder, pass it to closure as mutable ref and return.
pub fn build<F>(builder: F) -> ArrayBuilder where F: FnOnce(&mut Ar... | random_line_split | |
array_builder.rs | use serde_json::{Value, to_value};
use serde::{Serialize, Serializer};
pub type JsonArray = Vec<Value>;
use object_builder;
pub struct ArrayBuilder {
pub array: JsonArray,
pub null: bool,
pub skip: bool,
pub root: Option<String>
}
/// Use ArrayBuilder to produce JSON arrays
impl ArrayBuilder {
... |
/// Create new array and push it.
pub fn array<F>(&mut self, builder: F) where F: FnOnce(&mut ArrayBuilder) {
self.push(ArrayBuilder::build(builder).unwrap());
}
/// Create new object and push it
pub fn object<F>(&mut self, builder: F) where F: FnOnce(&mut object_builder::ObjectBuilder) {... | {
self.array.push(value);
} | identifier_body |
array_builder.rs | use serde_json::{Value, to_value};
use serde::{Serialize, Serializer};
pub type JsonArray = Vec<Value>;
use object_builder;
pub struct ArrayBuilder {
pub array: JsonArray,
pub null: bool,
pub skip: bool,
pub root: Option<String>
}
/// Use ArrayBuilder to produce JSON arrays
impl ArrayBuilder {
... | (&mut self) {
self.skip = true;
}
// Set custom root for result Value object
pub fn root(&mut self, root: &str) {
self.root = Some(root.to_string());
}
pub fn has_root(&mut self) -> bool {
self.root.is_some()
}
/// Move out internal JSON value.
pub fn unwrap(se... | skip | identifier_name |
main.rs | /*
Copyright 2013 Jesse 'Jeaye' Wilkerson
See licensing in LICENSE file, or at:
http://www.opensource.org/licenses/BSD-3-Clause
File: server/main.rs
Author: Jesse 'Jeaye' Wilkerson
Description:
Main engine controller and entry point
for the server.
*/
#[feature(globs)];
#[featu... |
{
log::Log::initialize();
let mut server = Server::new();
server.initialize();
}
| in() | identifier_name |
main.rs | /*
Copyright 2013 Jesse 'Jeaye' Wilkerson
See licensing in LICENSE file, or at:
http://www.opensource.org/licenses/BSD-3-Clause
File: server/main.rs
Author: Jesse 'Jeaye' Wilkerson
Description:
Main engine controller and entry point
for the server.
*/
#[feature(globs)];
#[featu... |
else
{ ui::term::initialize() };
log_assert!(driver.is_some(), "Unable to initialize UI");
self.ui_driver = driver;
}
fn show_version()
{
println!("Q³ Server {}.{}", env!("VERSION"), env!("COMMIT"));
fail!("Exiting");
}
fn show_help()
{
let args = os::args();
println!("Q³... | { log_fail!("GUI mode is not yet implemented"); } | conditional_block |
main.rs | /*
Copyright 2013 Jesse 'Jeaye' Wilkerson
See licensing in LICENSE file, or at:
http://www.opensource.org/licenses/BSD-3-Clause
File: server/main.rs
Author: Jesse 'Jeaye' Wilkerson
Description:
Main engine controller and entry point
for the server.
*/
#[feature(globs)];
#[featu... |
fn main()
{
log::Log::initialize();
let mut server = Server::new();
server.initialize();
}
|
let args = os::args();
println!("Q³ Server {}.{}", env!("VERSION"), env!("COMMIT"));
println!("Usage:");
println!("\t{} [options...]", args[0]);
println!("");
println!("Options:");
println!("\t--help\tShows this help menu and exits");
println!("\t--tui\tEnable textual user interface mo... | identifier_body |
main.rs | /*
Copyright 2013 Jesse 'Jeaye' Wilkerson
See licensing in LICENSE file, or at:
http://www.opensource.org/licenses/BSD-3-Clause
File: server/main.rs
Author: Jesse 'Jeaye' Wilkerson
Description:
Main engine controller and entry point
for the server.
*/
#[feature(globs)];
#[featu... | { log_fail!("GUI mode is not yet implemented"); }
else
{ ui::term::initialize() };
log_assert!(driver.is_some(), "Unable to initialize UI");
self.ui_driver = driver;
}
fn show_version()
{
println!("Q³ Server {}.{}", env!("VERSION"), env!("COMMIT"));
fail!("Exiting");
}
fn show_he... |
/* Determine the UI driver. */
let driver =
if args.contains(&~"--gui") | random_line_split |
secure_message_sign_verify_rsa.rs | // Copyright 2020 Cossack Labs Limited
//
// 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 agre... | themis_secure_message_sign(
private.as_ptr(),
private.len(),
message.as_ptr(),
message.len(),
std::ptr::null_mut(),
&mut signatu... | {
let (private, _) = gen_rsa_key_pair().split();
let private = private.as_ref();
// Allocate buffer large enough for maximum test
let mut signature = vec![0; 10 * MB];
let mut group = c.benchmark_group("Secure Message signing - RSA");
for message_size in MESSAGE_SIZES {
group.throughpu... | identifier_body |
secure_message_sign_verify_rsa.rs | // Copyright 2020 Cossack Labs Limited
//
// 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 agre... | criterion_main!(benches); | random_line_split | |
secure_message_sign_verify_rsa.rs | // Copyright 2020 Cossack Labs Limited
//
// 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 agre... | else {
format!("{}", size)
}
}
criterion_group!(benches, signing, verification);
criterion_main!(benches);
| {
format!("{} KB", size / KB)
} | conditional_block |
secure_message_sign_verify_rsa.rs | // Copyright 2020 Cossack Labs Limited
//
// 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 agre... | (size: usize) -> String {
if size >= MB {
format!("{} MB", size / MB)
} else if size >= KB {
format!("{} KB", size / KB)
} else {
format!("{}", size)
}
}
criterion_group!(benches, signing, verification);
criterion_main!(benches);
| pretty | identifier_name |
characterdata.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/. */
//! DOM bindings for `CharacterData`.
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::... | (&self) -> u32 {
self.data.borrow().encode_utf16().count() as u32
}
// https://dom.spec.whatwg.org/#dom-characterdata-substringdata
fn SubstringData(&self, offset: u32, count: u32) -> Fallible<DOMString> {
let data = self.data.borrow();
// Step 1.
let data_from_offset = matc... | Length | identifier_name |
characterdata.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/. */
//! DOM bindings for `CharacterData`.
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::... | }
// https://dom.spec.whatwg.org/#dom-childnode-remove
fn Remove(&self) {
let node = self.upcast::<Node>();
node.remove_self();
}
// https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-previouselementsibling
fn GetPreviousElementSibling(&self) -> Option<Root<Element>> {
... | fn ReplaceWith(&self, nodes: Vec<NodeOrString>) -> ErrorResult {
self.upcast::<Node>().replace_with(nodes) | random_line_split |
characterdata.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/. */
//! DOM bindings for `CharacterData`.
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::... |
// https://dom.spec.whatwg.org/#dom-childnode-after
fn After(&self, nodes: Vec<NodeOrString>) -> ErrorResult {
self.upcast::<Node>().after(nodes)
}
// https://dom.spec.whatwg.org/#dom-childnode-replacewith
fn ReplaceWith(&self, nodes: Vec<NodeOrString>) -> ErrorResult {
self.upcas... | {
self.upcast::<Node>().before(nodes)
} | identifier_body |
characterdata.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/. */
//! DOM bindings for `CharacterData`.
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::... | else {
None
}
}
| {
Some(s.len())
} | conditional_block |
chiptune-sample.rs | extern crate chiptune;
extern crate sdl2;
use std::thread;
use std::time::Duration;
use std::io;
use std::io::prelude::*;
use std::fs::File;
fn play_sound(player: &mut chiptune::Chiptune, path: String) -> Result<chiptune::ChiptuneSound, chiptune::ChiptuneError> {
let sound = player.load_sound(path);
match so... |
Err(e) => println!("ERROR {:?}", e),
}
sound
}
fn play_sound_from_memory(player: &mut chiptune::Chiptune, path: String) -> Result<chiptune::ChiptuneSound, chiptune::ChiptuneError> {
let mut data = Vec::new();
let mut f = File::open(path.as_str()).unwrap();
f.read_to_end(&mut data).unwrap()... | {
println!("Playing sound");
player.play_sound(&mut chip_sound, -1, 13312, chiptune::CYD_PAN_CENTER, 50);
} | conditional_block |
chiptune-sample.rs | extern crate chiptune;
extern crate sdl2;
use std::thread;
use std::time::Duration;
use std::io;
use std::io::prelude::*;
use std::fs::File;
fn | (player: &mut chiptune::Chiptune, path: String) -> Result<chiptune::ChiptuneSound, chiptune::ChiptuneError> {
let sound = player.load_sound(path);
match sound {
Ok(mut chip_sound) => {
println!("Playing sound");
player.play_sound(&mut chip_sound, -1, 13312, chiptune::CYD_PAN_CENT... | play_sound | identifier_name |
chiptune-sample.rs | extern crate chiptune;
extern crate sdl2;
use std::thread;
use std::time::Duration;
use std::io;
use std::io::prelude::*;
use std::fs::File;
fn play_sound(player: &mut chiptune::Chiptune, path: String) -> Result<chiptune::ChiptuneSound, chiptune::ChiptuneError> {
let sound = player.load_sound(path);
match so... | sound
}
fn play_sound_from_memory(player: &mut chiptune::Chiptune, path: String) -> Result<chiptune::ChiptuneSound, chiptune::ChiptuneError> {
let mut data = Vec::new();
let mut f = File::open(path.as_str()).unwrap();
f.read_to_end(&mut data).unwrap();
println!("DATA = {:?}", data.len());
... | Err(e) => println!("ERROR {:?}", e),
} | random_line_split |
chiptune-sample.rs | extern crate chiptune;
extern crate sdl2;
use std::thread;
use std::time::Duration;
use std::io;
use std::io::prelude::*;
use std::fs::File;
fn play_sound(player: &mut chiptune::Chiptune, path: String) -> Result<chiptune::ChiptuneSound, chiptune::ChiptuneError> {
let sound = player.load_sound(path);
match so... |
println!("SOUND POSITION = {:?}", player.get_sound_position(0));
println!("Play sound");
/*let sound = play_sound(&mut player, "./src/chiptune/libksnd-source/src/assets/sounds/major.ki".to_string());
match sound {
Ok(mut chip_sound) => {
let program = player.get_sound_program(c... | {
sdl2::init();
let mut player = chiptune::Chiptune::new();
println!("Play music");
let song = player.load_music("./src/chiptune/libksnd-source/src/assets/ringmod.kt".to_string());
match song {
Ok(mut chip_song) => {
player.play_music(&mut chip_song, 0);
///println!... | identifier_body |
dottoxedit.rs | extern crate clap;
extern crate tox;
extern crate ttyaskpass;
extern crate secstr;
use std::fs::File;
use std::path::Path;
use std::collections::HashSet;
use std::io::{ stdout, Read, Write };
use clap::{ App, Arg, SubCommand };
use secstr::SecStr;
use ttyaskpass::askpass;
use tox::core::{ Tox, ToxOptions, Status, Frie... | <P: AsRef<Path>>(path: P, data: &[u8], passphrase: Option<SecStr>) {
File::create(path).unwrap().write(&match passphrase {
Some(pass) => ToxPassKey::new(pass).unwrap()
.encrypt(data).unwrap(),
None => data.into()
}).unwrap();
}
fn main() {
let app = App::new("Edit.TOX")
.... | write | identifier_name |
dottoxedit.rs | extern crate clap;
extern crate tox;
extern crate ttyaskpass;
extern crate secstr;
use std::fs::File;
use std::path::Path;
use std::collections::HashSet;
use std::io::{ stdout, Read, Write };
use clap::{ App, Arg, SubCommand };
use secstr::SecStr;
use ttyaskpass::askpass;
use tox::core::{ Tox, ToxOptions, Status, Frie... | let data = ToxPassKey::from(passphrase.clone(), &data).unwrap()
.decrypt(&data).unwrap();
(ToxOptions::default().from(&data).generate().unwrap(), Some(passphrase))
} else {
(ToxOptions::default().from(&data).generate().unwrap(), None)
}
}
fn write<P: AsRef<Path>>(path: P, dat... | None => askpass(b"~")
}; | random_line_split |
dottoxedit.rs | extern crate clap;
extern crate tox;
extern crate ttyaskpass;
extern crate secstr;
use std::fs::File;
use std::path::Path;
use std::collections::HashSet;
use std::io::{ stdout, Read, Write };
use clap::{ App, Arg, SubCommand };
use secstr::SecStr;
use ttyaskpass::askpass;
use tox::core::{ Tox, ToxOptions, Status, Frie... |
fn write<P: AsRef<Path>>(path: P, data: &[u8], passphrase: Option<SecStr>) {
File::create(path).unwrap().write(&match passphrase {
Some(pass) => ToxPassKey::new(pass).unwrap()
.encrypt(data).unwrap(),
None => data.into()
}).unwrap();
}
fn main() {
let app = App::new("Edit.TOX"... | {
let mut data = Vec::new();
File::open(path).unwrap().read_to_end(&mut data).unwrap();
if is_encrypted(&data) {
let passphrase = match passphrase {
Some(pass) => pass.into(),
None => askpass(b"~")
};
let data = ToxPassKey::from(passphrase.clone(), &data).unwr... | identifier_body |
dottoxedit.rs | extern crate clap;
extern crate tox;
extern crate ttyaskpass;
extern crate secstr;
use std::fs::File;
use std::path::Path;
use std::collections::HashSet;
use std::io::{ stdout, Read, Write };
use clap::{ App, Arg, SubCommand };
use secstr::SecStr;
use ttyaskpass::askpass;
use tox::core::{ Tox, ToxOptions, Status, Frie... | ,
Some("diff") => println!("{}", pk),
_ => unreachable!()
}
}
},
_ => unreachable!()
};
write(path, &tox.save(), passphrase);
},
_ => { stdout().wr... | { tox.add_friend(pk).unwrap(); } | conditional_block |
alg_misc.rs | use crate::seeded_rng;
use euclid::{point2, rect, Point2D, Rect};
use num::{Float, One, Zero};
use rand::distributions::{Distribution, Standard, Uniform};
use rand::Rng;
use std::error::Error;
use std::fmt;
use std::hash::Hash;
use std::ops::{Add, AddAssign, Div, Mul, Range, RangeInclusive, Sub, SubAssign};
/// A type... |
}
impl AddAssign for Deciban {
fn add_assign(&mut self, rhs: Deciban) { self.0 += rhs.0; }
}
impl Sub for Deciban {
type Output = Deciban;
fn sub(self, rhs: Deciban) -> Deciban { Deciban(self.0 - rhs.0) }
}
impl SubAssign for Deciban {
fn sub_assign(&mut self, rhs: Deciban) { self.0 -= rhs.0; }
}
/... | { Deciban(self.0 + rhs.0) } | identifier_body |
alg_misc.rs | use crate::seeded_rng;
use euclid::{point2, rect, Point2D, Rect};
use num::{Float, One, Zero};
use rand::distributions::{Distribution, Standard, Uniform};
use rand::Rng;
use std::error::Error;
use std::fmt;
use std::hash::Hash;
use std::ops::{Add, AddAssign, Div, Mul, Range, RangeInclusive, Sub, SubAssign};
/// A type... | (pub f32);
impl Deciban {
/// Build a deciban value from a probability in [0, 1).
pub fn new(p: f32) -> Deciban {
debug_assert!(p >= 0.0 && p < 1.0);
Deciban(10.0 * (p / (1.0 - p)).log(10.0))
}
/// Convert a deciban value to the corresponding probability in [0, 1).
pub fn to_p(self... | Deciban | identifier_name |
alg_misc.rs | use crate::seeded_rng;
use euclid::{point2, rect, Point2D, Rect};
use num::{Float, One, Zero};
use rand::distributions::{Distribution, Standard, Uniform};
use rand::Rng;
use std::error::Error;
use std::fmt;
use std::hash::Hash;
use std::ops::{Add, AddAssign, Div, Mul, Range, RangeInclusive, Sub, SubAssign};
/// A type... | .fold((0.0, None), |(weight_sum, prev_item), item| {
let item_weight = weight_fn(&item);
debug_assert!(item_weight >= 0.0);
let p = item_weight / (weight_sum + item_weight);
let next_item = if dist.sample(rng) < p {
Some(item... | {
let dist = Uniform::new(0.0, 1.0);
let (_, ret) = self
.into_iter() | random_line_split |
banning_queue.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... |
fn gas_required(_tx: &SignedTransaction) -> U256 {
0.into()
}
fn transaction(action: Action) -> SignedTransaction {
let keypair = Random.generate().unwrap();
Transaction {
action: action,
value: U256::from(100),
data: "3331600055".from_hex().unwrap(),
gas: U256::from(100_000),
gas_price: U256... | {
AccountDetails {
nonce: U256::zero(),
balance: !U256::zero(),
}
} | identifier_body |
banning_queue.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | assert!(!banlist1, "Threshold not reached yet.");
// Insert once
let import1 = txq.add_with_banlist(tx.clone(), &default_account_details, &gas_required).unwrap();
assert_eq!(import1, TransactionImportResult::Current);
// when
let banlist2 = txq.ban_codehash(codehash);
let import2 = txq.add_with_banlist(t... | random_line_split | |
banning_queue.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | ,
None => false,
}
}
/// Ban given sender.
/// If bans threshold is reached all subsequent transactions from this sender will be rejected.
/// Reaching bans threshold also removes all existsing transaction from this sender that are already in the
/// queue.
fn ban_sender(&mut self, address: Address) -> bool... | {
let sender = transaction.sender().expect("Transaction is in queue, so the sender is already validated; qed");
// Ban sender
let sender_banned = self.ban_sender(sender);
// Ban recipient and codehash
let recipient_or_code_banned = match transaction.action {
Action::Call(recipient) => {
s... | conditional_block |
banning_queue.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | (&self) -> &Self::Target {
&self.queue
}
}
impl DerefMut for BanningTransactionQueue {
fn deref_mut(&mut self) -> &mut Self::Target {
self.queue()
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use super::{BanningTransactionQueue, Threshold};
use ethkey::{Random, Generator};
use transaction::{Transac... | deref | identifier_name |
main.rs | pub fn sort_disjoint(values: &mut [i32], indices: &[usize]) {
let mut sublist_indices = indices.to_owned();
sublist_indices.sort_unstable();
let mut sublist: Vec<i32> = sublist_indices.iter().map(|&i| values[i]).collect();
sublist.sort_unstable();
for i in 0..sublist.len() {
values[sublist_i... | use super::sort_disjoint;
#[test]
fn test_example() {
let mut values = [7, 6, 5, 4, 3, 2, 1, 0];
let indices = [6, 1, 7];
sort_disjoint(&mut values, &indices);
assert_eq!(values, [7, 0, 5, 4, 3, 2, 1, 6]);
}
#[test]
fn test_sort_one() {
let mut values = [0... | mod tests { | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.