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 |
|---|---|---|---|---|
01c_quick_example.rs | #[macro_use]
extern crate clap;
fn main() {
// This example shows how to create an application with several arguments using macro builder.
// It combines the simplicity of the from_usage methods and the performance of the Builder Pattern.
//
// The example below is functionally identical to the one in ... | (author: "Kevin K. <kbknapp@gmail.com>")
(about: "Does awesome things")
(@arg CONFIG: -c --config +takes_value "Sets a custom config file")
(@arg INPUT: +required "Sets the input file to use")
(@arg debug: -d... "Sets the level of debugging information")
(@subcommand test... | random_line_split | |
01c_quick_example.rs | #[macro_use]
extern crate clap;
fn main() {
// This example shows how to create an application with several arguments using macro builder.
// It combines the simplicity of the from_usage methods and the performance of the Builder Pattern.
//
// The example below is functionally identical to the one in ... |
}
// more program logic goes here...
}
| {
println!("Printing normally...");
} | conditional_block |
01c_quick_example.rs | #[macro_use]
extern crate clap;
fn | () {
// This example shows how to create an application with several arguments using macro builder.
// It combines the simplicity of the from_usage methods and the performance of the Builder Pattern.
//
// The example below is functionally identical to the one in 01a_quick_example.rs and 01b_quick_examp... | main | identifier_name |
dictionary.rs | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// 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 ... |
value.unwrap()
}
/// A convenience function to retrieve `CFType` instances.
#[inline]
pub unsafe fn get_CFType(&self, key: *const c_void) -> CFType {
let value: CFTypeRef = mem::transmute(self.get(key));
TCFType::wrap_under_get_rule(value)
}
}
#[link(name = "CoreFoundation... | {
panic!("No entry found for key {:p}", key);
} | conditional_block |
dictionary.rs | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// 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 ... | (&self, key: *const c_void) -> *const c_void {
let value = self.find(key);
if value.is_none() {
panic!("No entry found for key {:p}", key);
}
value.unwrap()
}
/// A convenience function to retrieve `CFType` instances.
#[inline]
pub unsafe fn get_CFType(&self,... | get | identifier_name |
dictionary.rs | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// 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 ... |
#[inline]
pub fn find(&self, key: *const c_void) -> Option<*const c_void> {
unsafe {
let mut value: *const c_void = ptr::null();
if CFDictionaryGetValueIfPresent(self.obj, key, &mut value)!= 0 {
Some(value)
} else {
None
}... | {
unsafe {
CFDictionaryContainsKey(self.obj, key) != 0
}
} | identifier_body |
dictionary.rs | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// 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 ... |
#[inline]
unsafe fn wrap_under_get_rule(reference: CFDictionaryRef) -> CFDictionary {
let reference: CFDictionaryRef = mem::transmute(CFRetain(mem::transmute(reference)));
TCFType::wrap_under_create_rule(reference)
}
#[inline]
fn as_CFTypeRef(&self) -> CFTypeRef {
unsafe {
... | } | random_line_split |
mod.rs | // Copyright (C) 2020 Markus Ebner <info@ebner-markus.de>
//
// 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 distrib... | {
gst::Element::register(
Some(plugin),
"gifenc",
gst::Rank::Primary,
GifEnc::static_type(),
)
} | identifier_body | |
mod.rs | // Copyright (C) 2020 Markus Ebner <info@ebner-markus.de>
// | // 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.
use glib::prelude::... | random_line_split | |
mod.rs | // Copyright (C) 2020 Markus Ebner <info@ebner-markus.de>
//
// 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 distrib... | (plugin: &gst::Plugin) -> Result<(), glib::BoolError> {
gst::Element::register(
Some(plugin),
"gifenc",
gst::Rank::Primary,
GifEnc::static_type(),
)
}
| register | identifier_name |
rule_args.rs | extern crate peg;
peg::parser!( grammar ra() for str {
use peg::ParseLiteral;
rule number() -> i64
= n:$(['0'..='9']+) { n.parse().unwrap() }
rule commasep<T>(x: rule<T>) -> Vec<T> = v:(x() ** ",") ","? {v}
rule bracketed<T>(x: rule<T>) -> T = "[" v:x() "]" {v}
pub rule list() -> Vec<i64... | rule ident() = ['a'..='z']+
rule _ = [' ']*
pub rule ifelse() = keyword("if") _ ident() _ keyword("then") _ ident() _ keyword("else") _ ident()
pub rule repeated_a(i: usize) = ['a']*<{i}>
rule i(literal: &'static str) = input:$([_]*<{literal.len()}>) {? if input.eq_ignore_ascii_case(literal) {... | rule keyword(id: &'static str) = ##parse_string_literal(id) !['0'..='9' | 'a'..='z' | 'A'..='Z' | '_'] | random_line_split |
rule_args.rs | extern crate peg;
peg::parser!( grammar ra() for str {
use peg::ParseLiteral;
rule number() -> i64
= n:$(['0'..='9']+) { n.parse().unwrap() }
rule commasep<T>(x: rule<T>) -> Vec<T> = v:(x() ** ",") ","? {v}
rule bracketed<T>(x: rule<T>) -> T = "[" v:x() "]" {v}
pub rule list() -> Vec<i64... | () {
assert_eq!(list("1,2,3,4"), Ok(vec![1,2,3,4]));
assert_eq!(array("[1,1,2,3,5,]"), Ok(vec![1,1,2,3,5]));
assert!(ifelse("if foo then x else y").is_ok());
assert!(ifelse("iffoothenxelsey").is_err());
assert!(repeated_a("aa", 2).is_ok());
assert!(repeated_a("aaa", 2).is_err());
assert!(r... | main | identifier_name |
rule_args.rs | extern crate peg;
peg::parser!( grammar ra() for str {
use peg::ParseLiteral;
rule number() -> i64
= n:$(['0'..='9']+) { n.parse().unwrap() }
rule commasep<T>(x: rule<T>) -> Vec<T> = v:(x() ** ",") ","? {v}
rule bracketed<T>(x: rule<T>) -> T = "[" v:x() "]" {v}
pub rule list() -> Vec<i64... | {
assert_eq!(list("1,2,3,4"), Ok(vec![1,2,3,4]));
assert_eq!(array("[1,1,2,3,5,]"), Ok(vec![1,1,2,3,5]));
assert!(ifelse("if foo then x else y").is_ok());
assert!(ifelse("iffoothenxelsey").is_err());
assert!(repeated_a("aa", 2).is_ok());
assert!(repeated_a("aaa", 2).is_err());
assert!(repe... | identifier_body | |
main.rs | // This file is part of oxideNews-gtk
//
// Copyright © 2017-2018 red-oxide Developers
//
// This program 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 optio... | {
let application =
gtk::Application::new(gtk3::APP_ID, gio::ApplicationFlags::empty()).expect("Could not create application");
gtk3::App::new(application).connect_events().then_execute();
} | pub mod common;
#[cfg(feature = "gtk3")]
fn main() | random_line_split |
main.rs | // This file is part of oxideNews-gtk
//
// Copyright © 2017-2018 red-oxide Developers
//
// This program 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 optio... |
let application =
gtk::Application::new(gtk3::APP_ID, gio::ApplicationFlags::empty()).expect("Could not create application");
gtk3::App::new(application).connect_events().then_execute();
}
| identifier_body | |
main.rs | // This file is part of oxideNews-gtk
//
// Copyright © 2017-2018 red-oxide Developers
//
// This program 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 optio... | )
{
let application =
gtk::Application::new(gtk3::APP_ID, gio::ApplicationFlags::empty()).expect("Could not create application");
gtk3::App::new(application).connect_events().then_execute();
}
| ain( | identifier_name |
xdisplay.rs | use std::{collections::HashMap, error::Error, fmt, os::raw::c_int, ptr};
use libc;
use parking_lot::Mutex;
use crate::window::CursorIcon;
use super::ffi;
/// A connection to an X server.
pub struct XConnection {
pub xlib: ffi::Xlib,
/// Exposes XRandR functions from version < 1.5
pub xrandr: ffi::Xrandr... | (&self) {
*self.latest_error.lock() = None;
}
}
impl fmt::Debug for XConnection {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.display.fmt(f)
}
}
impl Drop for XConnection {
#[inline]
fn drop(&mut self) {
unsafe { (self.xlib.XCloseDisplay)(self.display) }... | ignore_error | identifier_name |
xdisplay.rs | use std::{collections::HashMap, error::Error, fmt, os::raw::c_int, ptr};
use libc;
use parking_lot::Mutex;
use crate::window::CursorIcon;
use super::ffi;
/// A connection to an X server.
pub struct XConnection {
pub xlib: ffi::Xlib,
/// Exposes XRandR functions from version < 1.5
pub xrandr: ffi::Xrandr... | let xlib = ffi::Xlib::open()?;
let xcursor = ffi::Xcursor::open()?;
let xrandr = ffi::Xrandr_2_2_0::open()?;
let xrandr_1_5 = ffi::Xrandr::open().ok();
let xinput2 = ffi::XInput2::open()?;
let xlib_xcb = ffi::Xlib_xcb::open()?;
let xrender = ffi::Xrender::open()?;... | Option<unsafe extern "C" fn(*mut ffi::Display, *mut ffi::XErrorEvent) -> libc::c_int>;
impl XConnection {
pub fn new(error_handler: XErrorHandler) -> Result<XConnection, XNotSupported> {
// opening the libraries | random_line_split |
zstdelta.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::cmp;
use std::ffi::CStr;
use std::io;
use libc::c_void;
use zstd_sys::ZSTD_DCtx_setMaxWindowSize;
use zstd_sys::ZSTD_compressBoun... |
let outsize = ZSTD_decompress_usingDict(
dctx,
buf.as_mut_ptr() as *mut c_void,
size,
delta.as_ptr() as *const c_void,
delta.len(),
base.as_ptr() as *const c_void,
base.len(),
);
ZSTD_freeDCtx(dctx);
if... |
let mut buf: Vec<u8> = Vec::with_capacity(size);
buf.set_len(size); | random_line_split |
zstdelta.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::cmp;
use std::ffi::CStr;
use std::io;
use libc::c_void;
use zstd_sys::ZSTD_DCtx_setMaxWindowSize;
use zstd_sys::ZSTD_compressBoun... | else {
Ok(buf)
}
}
}
#[cfg(test)]
mod tests {
use quickcheck::quickcheck;
use rand::RngCore;
use rand::SeedableRng;
use rand_chacha::ChaChaRng;
use super::*;
fn check_round_trip(base: &[u8], data: &[u8]) -> bool {
let delta = diff(base, data).expect("delta");
... | {
let msg = format!(
"decompress size mismatch (expected {}, got {})",
size, outsize
);
Err(io::Error::new(io::ErrorKind::Other, msg))
} | conditional_block |
zstdelta.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::cmp;
use std::ffi::CStr;
use std::io;
use libc::c_void;
use zstd_sys::ZSTD_DCtx_setMaxWindowSize;
use zstd_sys::ZSTD_compressBoun... | (code: usize) -> &'static str {
unsafe {
// ZSTD_getErrorName returns a static string.
let name = ZSTD_getErrorName(code);
let cstr = CStr::from_ptr(name);
cstr.to_str().expect("zstd error is utf-8")
}
}
/// Create a "zstd delta". Compress `data` using dictionary `base`.
pub fn ... | explain_error | identifier_name |
zstdelta.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::cmp;
use std::ffi::CStr;
use std::io;
use libc::c_void;
use zstd_sys::ZSTD_DCtx_setMaxWindowSize;
use zstd_sys::ZSTD_compressBoun... |
/// Create a "zstd delta". Compress `data` using dictionary `base`.
pub fn diff(base: &[u8], data: &[u8]) -> io::Result<Vec<u8>> {
// Customized wlog, hlog to let zstd do better at delta-ing. Use "fast" strategy, which is
// good enough assuming the primary space saving is caused by "delta-ing".
let log =... | {
unsafe {
// ZSTD_getErrorName returns a static string.
let name = ZSTD_getErrorName(code);
let cstr = CStr::from_ptr(name);
cstr.to_str().expect("zstd error is utf-8")
}
} | identifier_body |
rfc-1014.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 ... | () {
const STD_OUTPUT_HANDLE: DWORD = -11i32 as DWORD;
unsafe { CloseHandle(GetStdHandle(STD_OUTPUT_HANDLE)); }
}
#[cfg(not(windows))]
fn close_stdout() {
unsafe { libc::close(1); }
}
fn main() {
close_stdout();
println!("hello world");
}
| close_stdout | identifier_name |
rfc-1014.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 ... |
#[cfg(not(windows))]
fn close_stdout() {
unsafe { libc::close(1); }
}
fn main() {
close_stdout();
println!("hello world");
}
| {
const STD_OUTPUT_HANDLE: DWORD = -11i32 as DWORD;
unsafe { CloseHandle(GetStdHandle(STD_OUTPUT_HANDLE)); }
} | identifier_body |
rfc-1014.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 ... | #![feature(rustc_private)]
extern crate libc;
type DWORD = u32;
type HANDLE = *mut u8;
#[cfg(windows)]
extern "system" {
fn GetStdHandle(which: DWORD) -> HANDLE;
fn CloseHandle(handle: HANDLE) -> i32;
}
#[cfg(windows)]
fn close_stdout() {
const STD_OUTPUT_HANDLE: DWORD = -11i32 as DWORD;
unsafe { Cl... | // ignore-cloudabi stdout does not map to file descriptor 1 by default
// ignore-wasm32-bare no libc
| random_line_split |
generics.rs | // generics.rs
//inline 1
// a function
// there's an error here!
fn fill_a_vector<T>(param: &T) -> Vec<T> {
let mut a_vec: Vec<T> = Vec::new();
let the_param = param.clone();
for _ in range(0,5) {
a_vec.push(the_param);
}
a_vec
}
// a type
type SingleTypeMap<T> = std::collections:HashMap<T, T>;
// a struct
... | }
// an enum
enum vec_or_map<T> {
Vec<T>,
std::collections::HashMap<T, T>
}
//end 1
// 2nd version
//inline 2
fn fill_a_vector<T: Clone>(param: &T) -> Vec<T> {
let mut a_vec: Vec<T> = Vec::new();
let the_param = param.clone();
for _ in range(0,5) {
a_vec.push(the_param);
}
a_vec
}
//end 2
// final version
... | next: Option<Node<T>> | random_line_split |
generics.rs | // generics.rs
//inline 1
// a function
// there's an error here!
fn fill_a_vector<T>(param: &T) -> Vec<T> {
let mut a_vec: Vec<T> = Vec::new();
let the_param = param.clone();
for _ in range(0,5) {
a_vec.push(the_param);
}
a_vec
}
// a type
type SingleTypeMap<T> = std::collections:HashMap<T, T>;
// a struct
... | <T: Clone>(param: &T) -> Vec<T> {
let mut a_vec: Vec<T> = Vec::new();
let the_param = param.clone();
for _ in range(0,5) {
a_vec.push(the_param);
}
a_vec
}
//end 2
// final version
//inline 3
fn fill_a_vector<T: Clone + Copy>(param: &T) -> Vec<T> {
let mut a_vec: Vec<T> = Vec::new();
let the_param = param.cl... | fill_a_vector | identifier_name |
http_headers.rs | header! {
(AmzDate, "X-Amz-Date") => [String]
// Annoyingly, the tm! macro isn't exported: https://github.com/hyperium/hyper/pull/515
// test_amz_date { | // }
}
header! {
(Authorization, "Authorization") => [String]
// test_auth_header {
// test_header!(test1, "AWS4-HMAC-SHA256 Credential=akid/20110909/us-east-1/iam/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature=ced6826de92d2bdeed8f846f0bf508e8559e98e4b0199114b84c54174deb456c")... | // test_header!(test1, "20110909T233600Z"); | random_line_split |
clone.rs | // A unit struct without resources
#[deriving(Show, Copy)]
struct | ;
// A tuple struct with resources that implements the `Clone` trait
#[deriving(Clone,Show)]
struct Pair(Box<int>, Box<int>);
fn main() {
// Instantiate `Nil`
let nil = Nil;
// Copy `Nil`, there are no resources to move
let copied_nil = nil;
// Both `Nil`s can be used independently
println!("... | Nil | identifier_name |
clone.rs | // A unit struct without resources
#[deriving(Show, Copy)]
struct Nil;
// A tuple struct with resources that implements the `Clone` trait
#[deriving(Clone,Show)]
struct Pair(Box<int>, Box<int>);
fn main() {
// Instantiate `Nil`
let nil = Nil;
// Copy `Nil`, there are no resources to move
let copied_ni... | println!("clone: {}", cloned_pair);
} | random_line_split | |
unique-unique-kind.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 ... | () {
// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
let i = Box::new(Rc::new(100));
f(i);
//~^ ERROR `core::marker::Send` is not implemented
}
| main | identifier_name |
unique-unique-kind.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 f<T:Send>(__isize: T) {
}
fn main() {
// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
let i = Box::new(Rc::new(100));
f(i);
//~^ ERROR `core::marker::Send` is not implemented
} | use std::rc::Rc; | random_line_split |
unique-unique-kind.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 main() {
// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
let i = Box::new(Rc::new(100));
f(i);
//~^ ERROR `core::marker::Send` is not implemented
}
| {
} | identifier_body |
database_setup.rs | use support::{database, project};
#[test]
fn | () {
let p = project("database_setup_creates_database")
.folder("migrations")
.build();
let db = database(&p.database_url());
// sanity check
assert!(!db.exists());
let result = p.command("database")
.arg("setup")
.run();
assert!(result.is_success(), "Result was u... | database_setup_creates_database | identifier_name |
database_setup.rs | use support::{database, project};
#[test]
fn database_setup_creates_database() {
let p = project("database_setup_creates_database")
.folder("migrations")
.build();
let db = database(&p.database_url());
// sanity check
assert!(!db.exists());
let result = p.command("database")
... | .arg("setup")
.run();
assert!(result.is_success(), "Result was unsuccessful {:?}", result);
assert!(result.stdout().contains("Running migration 12345"),
"Unexpected stdout {}", result.stdout());
assert!(db.table_exists("users"));
} |
// sanity check
assert!(!db.exists());
let result = p.command("database") | random_line_split |
database_setup.rs | use support::{database, project};
#[test]
fn database_setup_creates_database() |
#[test]
fn database_setup_creates_schema_table () {
let p = project("database_setup_creates_schema_table")
.folder("migrations")
.build();
let db = database(&p.database_url());
// sanity check
assert!(!db.exists());
let result = p.command("database")
.arg("setup")
.r... | {
let p = project("database_setup_creates_database")
.folder("migrations")
.build();
let db = database(&p.database_url());
// sanity check
assert!(!db.exists());
let result = p.command("database")
.arg("setup")
.run();
assert!(result.is_success(), "Result was ... | identifier_body |
condvar.rs | use crate::cell::UnsafeCell;
use crate::sys::mutex::{self, Mutex};
use crate::time::Duration;
pub struct Condvar {
inner: UnsafeCell<libc::pthread_cond_t>,
}
pub type MovableCondvar = Box<Condvar>;
unsafe impl Send for Condvar {}
unsafe impl Sync for Condvar {}
const TIMESPEC_MAX: libc::timespec =
libc::tim... | (value: u64) -> libc::time_t {
if value > <libc::time_t>::MAX as u64 { <libc::time_t>::MAX } else { value as libc::time_t }
}
impl Condvar {
pub const fn new() -> Condvar {
// Might be moved and address is changing it is better to avoid
// initialization of potentially opaque OS data before it ... | saturating_cast_to_time_t | identifier_name |
condvar.rs | use crate::cell::UnsafeCell;
use crate::sys::mutex::{self, Mutex};
use crate::time::Duration;
pub struct Condvar {
inner: UnsafeCell<libc::pthread_cond_t>,
}
pub type MovableCondvar = Box<Condvar>;
unsafe impl Send for Condvar {}
unsafe impl Sync for Condvar {}
const TIMESPEC_MAX: libc::timespec =
libc::tim... | sec.map(|s| libc::timespec { tv_sec: s, tv_nsec: nsec as _ }).unwrap_or(TIMESPEC_MAX);
let r = libc::pthread_cond_timedwait(self.inner.get(), mutex::raw(mutex), &timeout);
assert!(r == libc::ETIMEDOUT || r == 0);
r == 0
}
// This implementation is modeled after libcxx's con... | random_line_split | |
condvar.rs | use crate::cell::UnsafeCell;
use crate::sys::mutex::{self, Mutex};
use crate::time::Duration;
pub struct Condvar {
inner: UnsafeCell<libc::pthread_cond_t>,
}
pub type MovableCondvar = Box<Condvar>;
unsafe impl Send for Condvar {}
unsafe impl Sync for Condvar {}
const TIMESPEC_MAX: libc::timespec =
libc::tim... |
#[cfg(any(
target_os = "macos",
target_os = "ios",
target_os = "l4re",
target_os = "android",
target_os = "redox"
))]
pub unsafe fn init(&mut self) {}
// NOTE: ESP-IDF's PTHREAD_COND_INITIALIZER support is not released yet
// So on that platform, init() sho... | {
// Might be moved and address is changing it is better to avoid
// initialization of potentially opaque OS data before it landed
Condvar { inner: UnsafeCell::new(libc::PTHREAD_COND_INITIALIZER) }
} | identifier_body |
condvar.rs | use crate::cell::UnsafeCell;
use crate::sys::mutex::{self, Mutex};
use crate::time::Duration;
pub struct Condvar {
inner: UnsafeCell<libc::pthread_cond_t>,
}
pub type MovableCondvar = Box<Condvar>;
unsafe impl Send for Condvar {}
unsafe impl Sync for Condvar {}
const TIMESPEC_MAX: libc::timespec =
libc::tim... |
// First, figure out what time it currently is, in both system and
// stable time. pthread_cond_timedwait uses system time, but we want to
// report timeout based on stable time.
let mut sys_now = libc::timeval { tv_sec: 0, tv_usec: 0 };
let stable_now = Instant::now();
... | {
// OSX implementation of `pthread_cond_timedwait` is buggy
// with super long durations. When duration is greater than
// 0x100_0000_0000_0000 seconds, `pthread_cond_timedwait`
// in macOS Sierra return error 316.
//
// This program demonstrates ... | conditional_block |
meteo.rs | use crate::dispatcher::Module;
use crate::dispatcher::MsgSender;
use rand::distributions::Normal;
use rand::prelude::*;
use std::collections::HashMap;
#[derive(PartialEq, Eq, Debug, Copy, Clone, Hash)]
enum MeasurementType {
Temperature,
Humidity,
Pressure,
LightLevel,
}
#[derive(Debug)]
pub struct ... | (
&mut self,
msg_writer: &mut dyn MsgSender,
transaction_id: u32,
_node_id: u32,
msg_str: &str,
) -> Result<(), ()> {
debug!("Handling message: {} {}", transaction_id, msg_str);
let mut values = msg_str.split(',');
let msg_type = values.next().ok_or(... | handle_incoming_msg | identifier_name |
meteo.rs | use crate::dispatcher::Module;
use crate::dispatcher::MsgSender;
use rand::distributions::Normal;
use rand::prelude::*;
use std::collections::HashMap;
#[derive(PartialEq, Eq, Debug, Copy, Clone, Hash)]
enum MeasurementType {
Temperature,
Humidity,
Pressure,
LightLevel,
}
#[derive(Debug)]
pub struct ... | self.generate_new_value(MeasurementType::Humidity, ch_num)
),
"GET_PRESSURE" => format!(
"PRESSURE_REPLY,{},{}",
ch_num,
self.generate_new_value(MeasurementType::Pressure, ch_num)
),
"GET_LIGHT_LEVEL" => form... | "GET_HUMIDITY" => format!(
"HUMIDITY_REPLY,{},{}",
ch_num, | random_line_split |
udp.rs | use ffi::{AF_INET, AF_INET6, AF_UNSPEC, SOCK_DGRAM, IPPROTO_UDP, AI_PASSIVE, AI_NUMERICSERV};
use core::Protocol;
use handler::Handler;
use dgram_socket::DgramSocket;
use ip::{IpEndpoint, IpProtocol, Passive, Resolver, ResolverIter, ResolverQuery};
use std::io;
use std::fmt;
use std::mem;
/// The User Datagram Protoc... |
}
impl<'a> ResolverQuery<Udp> for (Passive, &'a str) {
fn iter(self) -> io::Result<ResolverIter<Udp>> {
ResolverIter::new(&Udp { family: AF_UNSPEC }, "", self.1, AI_PASSIVE)
}
}
impl<'a, 'b> ResolverQuery<Udp> for (&'a str, &'b str) {
fn iter(self) -> io::Result<ResolverIter<Udp>> {
Resol... | {
let port = self.1.to_string();
ResolverIter::new(
&Udp { family: AF_UNSPEC },
"",
&port,
AI_PASSIVE | AI_NUMERICSERV,
)
} | identifier_body |
udp.rs | use ffi::{AF_INET, AF_INET6, AF_UNSPEC, SOCK_DGRAM, IPPROTO_UDP, AI_PASSIVE, AI_NUMERICSERV};
use core::Protocol;
use handler::Handler;
use dgram_socket::DgramSocket;
use ip::{IpEndpoint, IpProtocol, Passive, Resolver, ResolverIter, ResolverQuery};
use std::io;
use std::fmt;
use std::mem;
/// The User Datagram Protoc... | &port,
AI_PASSIVE | AI_NUMERICSERV,
)
}
}
impl<'a> ResolverQuery<Udp> for (Passive, &'a str) {
fn iter(self) -> io::Result<ResolverIter<Udp>> {
ResolverIter::new(&Udp { family: AF_UNSPEC }, "", self.1, AI_PASSIVE)
}
}
impl<'a, 'b> ResolverQuery<Udp> for (&'a str, &'... | ResolverIter::new(
&Udp { family: AF_UNSPEC },
"", | random_line_split |
udp.rs | use ffi::{AF_INET, AF_INET6, AF_UNSPEC, SOCK_DGRAM, IPPROTO_UDP, AI_PASSIVE, AI_NUMERICSERV};
use core::Protocol;
use handler::Handler;
use dgram_socket::DgramSocket;
use ip::{IpEndpoint, IpProtocol, Passive, Resolver, ResolverIter, ResolverQuery};
use std::io;
use std::fmt;
use std::mem;
/// The User Datagram Protoc... | () {
use core::IoContext;
use ip::*;
let ctx = &IoContext::new().unwrap();
let re = UdpResolver::new(ctx);
for ep in re.resolve(("127.0.0.1", "80")).unwrap() {
assert_eq!(ep, UdpEndpoint::new(IpAddrV4::loopback(), 80));
}
for ep in re.resolve(("::1", "80")).unwrap() {
assert... | test_udp_resolve | identifier_name |
main.rs | #[macro_use]
extern crate clap;
extern crate rand;
use std::io::Write;
use clap::{App, AppSettings, Arg};
use rand::Rng;
const LOWERCASE: &'static [u8] = b"abcdefghijklmnopqrstuvwxyz";
const UPPERCASE: &'static [u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const DIGITS: &'static [u8] = b"0123456789";
const SYMBOL: &'static [... | (args: &Args, count: usize) {
let mut rng = rand::thread_rng();
for _ in 0.. args.num_pw {
let mut mtl: Vec<char> = Vec::new();
mtl.extend_from_slice(&each_choose(args.lower_c, &LOWERCASE));
mtl.extend_from_slice(&each_choose(args.upper_c, &UPPERCASE));
mtl.extend_from_slice(&eac... | generate_pw | identifier_name |
main.rs | #[macro_use]
extern crate clap;
extern crate rand;
use std::io::Write;
use clap::{App, AppSettings, Arg};
use rand::Rng;
const LOWERCASE: &'static [u8] = b"abcdefghijklmnopqrstuvwxyz";
const UPPERCASE: &'static [u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const DIGITS: &'static [u8] = b"0123456789";
const SYMBOL: &'static [... | .arg(Arg::from_usage("-U 'Don't include uppercase letters'"))
.arg(Arg::from_usage("-D 'Don't include digits'"))
.arg(Arg::from_usage("-S 'Don't include symbols'"))
.arg(Arg::from_usage("-l --length [length] 'Length of the password'").default_value("8"))
.arg(Arg::from_usage("-n --num... | let matches = App::new("rpwg")
.version(crate_version!())
.author(crate_authors!())
.about("Random password generator")
.setting(AppSettings::DeriveDisplayOrder) | random_line_split |
main.rs | #[macro_use]
extern crate clap;
extern crate rand;
use std::io::Write;
use clap::{App, AppSettings, Arg};
use rand::Rng;
const LOWERCASE: &'static [u8] = b"abcdefghijklmnopqrstuvwxyz";
const UPPERCASE: &'static [u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const DIGITS: &'static [u8] = b"0123456789";
const SYMBOL: &'static [... | {
let mut vec: Vec<_> = Vec::new();
vec.write(LOWERCASE).unwrap();
if args.upper == false {
vec.write(UPPERCASE).unwrap();
}
if args.digits == false {
vec.write(DIGITS).unwrap();
}
if args.symbol == false {
vec.write(SYMBOL).unwrap();
}
return vec;
} | identifier_body | |
htmlmetaelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::attr::Attr;
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindin... |
}
}
#[allow(unrooted_must_root)]
fn apply_viewport(&self) {
if!pref!(layout.viewport.enabled) {
return;
}
let element = self.upcast::<Element>();
if let Some(ref content) = element.get_attribute(&ns!(), &local_name!("content")) {
let content ... | {
self.apply_referrer();
} | conditional_block |
htmlmetaelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */ | use crate::dom::bindings::codegen::Bindings::HTMLMetaElementBinding;
use crate::dom::bindings::codegen::Bindings::HTMLMetaElementBinding::HTMLMetaElementMethods;
use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::root::{DomRo... |
use crate::dom::attr::Attr;
use crate::dom::bindings::cell::DomRefCell; | random_line_split |
htmlmetaelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::attr::Attr;
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindin... |
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
if let Some(s) = self.super_type() {
s.attribute_mutated(attr, mutation);
}
self.process_referrer_attribute();
}
fn unbind_from_tree(&self, context: &UnbindContext) {
if let Some(ref s) = ... | {
if let Some(ref s) = self.super_type() {
s.bind_to_tree(context);
}
if context.tree_connected {
self.process_attributes();
}
} | identifier_body |
htmlmetaelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::attr::Attr;
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindin... | (
local_name: LocalName,
prefix: Option<Prefix>,
document: &Document,
) -> DomRoot<HTMLMetaElement> {
Node::reflect_node(
Box::new(HTMLMetaElement::new_inherited(local_name, prefix, document)),
document,
HTMLMetaElementBinding::Wrap,
)
... | new | identifier_name |
wmove.rs | #[macro_use]
extern crate cli_util;
extern crate wlib;
use std::env;
use wlib::window;
#[derive(Copy, Clone)]
enum Mode {
Relative,
Absolute
}
fn main() |
fn run(mode: Mode, x: i32, y: i32, wid: window::ID) -> Result<(), &'static str> {
let disp = try!(wlib::Display::open());
let mut win = try!(
disp.window(wid).map_err(|_| "window does not exist")
);
match mode {
Mode::Relative => try!(win.reposition_relative(x, y)),
Mode::Absol... | {
let name = cli_util::name(&mut env::args());
parse_args!{
description: "move window",
flag mode: Mode = Mode::Relative,
(&["-r", "--relative"], Mode::Relative, "move relatively (default)"),
(&["-a", "--absolute"], Mode::Absolute, "move absolutely"),
arg x: i32,... | identifier_body |
wmove.rs | #[macro_use]
extern crate cli_util;
extern crate wlib;
| use std::env;
use wlib::window;
#[derive(Copy, Clone)]
enum Mode {
Relative,
Absolute
}
fn main() {
let name = cli_util::name(&mut env::args());
parse_args!{
description: "move window",
flag mode: Mode = Mode::Relative,
(&["-r", "--relative"], Mode::Relative, "move relativ... | random_line_split | |
wmove.rs | #[macro_use]
extern crate cli_util;
extern crate wlib;
use std::env;
use wlib::window;
#[derive(Copy, Clone)]
enum Mode {
Relative,
Absolute
}
fn | () {
let name = cli_util::name(&mut env::args());
parse_args!{
description: "move window",
flag mode: Mode = Mode::Relative,
(&["-r", "--relative"], Mode::Relative, "move relatively (default)"),
(&["-a", "--absolute"], Mode::Absolute, "move absolutely"),
arg x: i... | main | identifier_name |
http.rs | use hyper::{Client, Url};
use hyper::status::StatusCode;
use hyper::header::{ContentType, Headers, Authorization, Basic};
use std::io::Read;
use errors::Error;
fn get_headers(url: Url) -> Headers {
let mut headers = Headers::new();
headers.set(ContentType::json());
headers.set(Authorization(Basic {
... |
headers
}
#[doc(hidden)]
pub fn post(url: &Url, body: &str) -> Result<String, Error> {
let headers = get_headers(url.clone());
let client = Client::new();
let mut res = try!(client.post(url.clone())
.headers(headers)
.body(body)
.send());
let mut resp = String::new();
res... | None => None,
Some(password) => Some(password.to_string()),
},
})); | random_line_split |
http.rs | use hyper::{Client, Url};
use hyper::status::StatusCode;
use hyper::header::{ContentType, Headers, Authorization, Basic};
use std::io::Read;
use errors::Error;
fn get_headers(url: Url) -> Headers |
#[doc(hidden)]
pub fn post(url: &Url, body: &str) -> Result<String, Error> {
let headers = get_headers(url.clone());
let client = Client::new();
let mut res = try!(client.post(url.clone())
.headers(headers)
.body(body)
.send());
let mut resp = String::new();
res.read_to_strin... | {
let mut headers = Headers::new();
headers.set(ContentType::json());
headers.set(Authorization(Basic {
username: url.username().to_string(),
password: match url.password() {
None => None,
Some(password) => Some(password.to_string()),
},
}));
headers... | identifier_body |
http.rs | use hyper::{Client, Url};
use hyper::status::StatusCode;
use hyper::header::{ContentType, Headers, Authorization, Basic};
use std::io::Read;
use errors::Error;
fn get_headers(url: Url) -> Headers {
let mut headers = Headers::new();
headers.set(ContentType::json());
headers.set(Authorization(Basic {
... | (url: &Url) -> Result<String, Error> {
let headers = get_headers(url.clone());
let client = Client::new();
let mut res = try!(client.get(url.clone())
.headers(headers)
.send());
let mut resp = String::new();
try!(res.read_to_string(&mut resp));
println!("GET {}", resp);
print... | get | identifier_name |
http.rs | use hyper::{Client, Url};
use hyper::status::StatusCode;
use hyper::header::{ContentType, Headers, Authorization, Basic};
use std::io::Read;
use errors::Error;
fn get_headers(url: Url) -> Headers {
let mut headers = Headers::new();
headers.set(ContentType::json());
headers.set(Authorization(Basic {
... |
}
| {
Err(Error::from_couch(&resp))
} | conditional_block |
stylesheets.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/. */
//! A collection of invalidations due to changes in which stylesheets affect a
//! document.
#![deny(unsafe_code)... | (
component: &Component<SelectorImpl>,
invalidation: &mut Option<Invalidation>)
{
match *component {
Component::LocalName(LocalName { ref name, ref lower_name }) => {
if invalidation.as_ref().map_or(true, |s|!s.is_id_or_class()) {
*invalidation... | scan_component | identifier_name |
stylesheets.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/. */
//! A collection of invalidations due to changes in which stylesheets affect a
//! document.
#![deny(unsafe_code)... | fn collect_invalidations_for_rule(
&mut self,
rule: &CssRule,
guard: &SharedRwLockReadGuard)
{
use stylesheets::CssRule::*;
debug!("StylesheetInvalidationSet::collect_invalidations_for_rule");
debug_assert!(!self.fully_invalid, "Not worth to be here!");
m... | random_line_split | |
stylesheets.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/. */
//! A collection of invalidations due to changes in which stylesheets affect a
//! document.
#![deny(unsafe_code)... |
/// Mark the DOM tree styles' as fully invalid.
pub fn invalidate_fully(&mut self) {
debug!("StylesheetInvalidationSet::invalidate_fully");
self.invalid_scopes.clear();
self.invalid_elements.clear();
self.fully_invalid = true;
}
/// Analyze the given stylesheet, and co... | {
Self {
invalid_scopes: FnvHashSet::default(),
invalid_elements: FnvHashSet::default(),
fully_invalid: false,
}
} | identifier_body |
ui.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 cssparser::RGBA;
use parsing::parse;
use style::values::{Auto, Either};
use style::values::specified::Color;
u... |
#[test]
fn test_caret_color() {
use style::properties::longhands::caret_color;
let auto = parse_longhand!(caret_color, "auto");
assert_eq!(auto, Either::Second(Auto));
let blue_color = Color::Numeric {
parsed: RGBA {
red: 0,
green: 0,
blue: 255,
... | {
use style::properties::longhands::_moz_user_select;
assert_roundtrip_with_context!(_moz_user_select::parse, "auto");
assert_roundtrip_with_context!(_moz_user_select::parse, "text");
assert_roundtrip_with_context!(_moz_user_select::parse, "none");
assert_roundtrip_with_context!(_moz_user_select::p... | identifier_body |
ui.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 cssparser::RGBA;
use parsing::parse;
use style::values::{Auto, Either};
use style::values::specified::Color;
u... | assert_roundtrip_with_context!(_moz_user_select::parse, "text");
assert_roundtrip_with_context!(_moz_user_select::parse, "none");
assert_roundtrip_with_context!(_moz_user_select::parse, "element");
assert_roundtrip_with_context!(_moz_user_select::parse, "elements");
assert_roundtrip_with_context!(_m... |
assert_roundtrip_with_context!(_moz_user_select::parse, "auto"); | random_line_split |
ui.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 cssparser::RGBA;
use parsing::parse;
use style::values::{Auto, Either};
use style::values::specified::Color;
u... | () {
use style::properties::longhands::caret_color;
let auto = parse_longhand!(caret_color, "auto");
assert_eq!(auto, Either::Second(Auto));
let blue_color = Color::Numeric {
parsed: RGBA {
red: 0,
green: 0,
blue: 255,
alpha: 255,
},
... | test_caret_color | identifier_name |
day7.rs | use std::io::prelude::*;
use std::fs::File;
use std::collections::VecDeque;
fn get_aba_or_abba(s: &String, abba: bool) -> Vec<(char, char)>{
let mut aba_vec = Vec::new();
let mut char_vec = VecDeque::new();
let len = if abba {4} else {3};
for ch in s.chars() {
char_vec.push_back(ch);
// Only look at ... |
let mut f = File::open("day7.txt").unwrap();
let mut f_s = String::new();
f.read_to_string(&mut f_s).unwrap();
let mut tls_count = 0; // part 1
let mut ssl_count = 0; // part 2
for l in f_s.lines() {
let mut s: String = l.to_string();
let mut supernet_bits = String::new();
let mut hypernet_bi... |
fn main() { | random_line_split |
day7.rs | use std::io::prelude::*;
use std::fs::File;
use std::collections::VecDeque;
fn get_aba_or_abba(s: &String, abba: bool) -> Vec<(char, char)>{
let mut aba_vec = Vec::new();
let mut char_vec = VecDeque::new();
let len = if abba {4} else {3};
for ch in s.chars() {
char_vec.push_back(ch);
// Only look at ... | }
if get_aba_or_abba(&supernet_bits, true).len()!= 0 &&
get_aba_or_abba(&hypernet_bits, true).len() == 0 {
tls_count += 1;
}
let bab_list = get_aba_or_abba(&hypernet_bits, false);
for aba in get_aba_or_abba(&supernet_bits, false) {
if bab_list.contains(&(aba.1, aba.0)) {
... | {
let mut f = File::open("day7.txt").unwrap();
let mut f_s = String::new();
f.read_to_string(&mut f_s).unwrap();
let mut tls_count = 0; // part 1
let mut ssl_count = 0; // part 2
for l in f_s.lines() {
let mut s: String = l.to_string();
let mut supernet_bits = String::new();
let mut hypernet_... | identifier_body |
day7.rs | use std::io::prelude::*;
use std::fs::File;
use std::collections::VecDeque;
fn get_aba_or_abba(s: &String, abba: bool) -> Vec<(char, char)>{
let mut aba_vec = Vec::new();
let mut char_vec = VecDeque::new();
let len = if abba {4} else {3};
for ch in s.chars() {
char_vec.push_back(ch);
// Only look at ... |
}
}
}
return aba_vec;
}
fn main() {
let mut f = File::open("day7.txt").unwrap();
let mut f_s = String::new();
f.read_to_string(&mut f_s).unwrap();
let mut tls_count = 0; // part 1
let mut ssl_count = 0; // part 2
for l in f_s.lines() {
let mut s: String = l.to_string();
let mut s... | {
aba_vec.push((char_vec[0],char_vec[1]));
} | conditional_block |
day7.rs | use std::io::prelude::*;
use std::fs::File;
use std::collections::VecDeque;
fn | (s: &String, abba: bool) -> Vec<(char, char)>{
let mut aba_vec = Vec::new();
let mut char_vec = VecDeque::new();
let len = if abba {4} else {3};
for ch in s.chars() {
char_vec.push_back(ch);
// Only look at characters for the given pattern
if char_vec.len() > len {
char_vec.pop_front();
... | get_aba_or_abba | identifier_name |
core.rs | // Copyright (c) 2017-2019 Linaro LTD
// Copyright (c) 2017-2019 JUUL Labs
//
// SPDX-License-Identifier: Apache-2.0
//! Core tests
//!
//! Run the existing testsuite as a Rust unit test.
use bootsim::{
DepTest, DepType, UpgradeInfo,
ImagesBuilder,
Images,
NO_DEPS,
REV_DEPS,
testlog,
};
use st... | (image: &Images, name: &str) {
if let Ok(request) = env::var("MCUBOOT_DEBUG_DUMP") {
if request.split(',').any(|req| {
req == "all" || name.contains(req)
}) {
let count = IMAGE_NUMBER.fetch_add(1, Ordering::SeqCst);
let full_name = format!("{}-{:04}", name, count)... | dump_image | identifier_name |
core.rs | // Copyright (c) 2017-2019 Linaro LTD
// Copyright (c) 2017-2019 JUUL Labs
//
// SPDX-License-Identifier: Apache-2.0
//! Core tests
//!
//! Run the existing testsuite as a Rust unit test.
use bootsim::{
DepTest, DepType, UpgradeInfo,
ImagesBuilder,
Images,
NO_DEPS,
REV_DEPS,
testlog,
};
use st... | } | log::info!("Dump {:?}", full_name);
image.debug_dump(&full_name);
}
} | random_line_split |
core.rs | // Copyright (c) 2017-2019 Linaro LTD
// Copyright (c) 2017-2019 JUUL Labs
//
// SPDX-License-Identifier: Apache-2.0
//! Core tests
//!
//! Run the existing testsuite as a Rust unit test.
use bootsim::{
DepTest, DepType, UpgradeInfo,
ImagesBuilder,
Images,
NO_DEPS,
REV_DEPS,
testlog,
};
use st... |
}
| {
if request.split(',').any(|req| {
req == "all" || name.contains(req)
}) {
let count = IMAGE_NUMBER.fetch_add(1, Ordering::SeqCst);
let full_name = format!("{}-{:04}", name, count);
log::info!("Dump {:?}", full_name);
image.debug_dump(&full_na... | conditional_block |
core.rs | // Copyright (c) 2017-2019 Linaro LTD
// Copyright (c) 2017-2019 JUUL Labs
//
// SPDX-License-Identifier: Apache-2.0
//! Core tests
//!
//! Run the existing testsuite as a Rust unit test.
use bootsim::{
DepTest, DepType, UpgradeInfo,
ImagesBuilder,
Images,
NO_DEPS,
REV_DEPS,
testlog,
};
use st... | {
if let Ok(request) = env::var("MCUBOOT_DEBUG_DUMP") {
if request.split(',').any(|req| {
req == "all" || name.contains(req)
}) {
let count = IMAGE_NUMBER.fetch_add(1, Ordering::SeqCst);
let full_name = format!("{}-{:04}", name, count);
log::info!("Dum... | identifier_body | |
https.rs | // This requires running with:
//
// ```bash
// cargo run --example https --features native-tls-example
// ```
//
// Generate an identity like so:
//
// ```bash
// openssl req -x509 -newkey rsa:4096 -nodes -keyout localhost.key -out localhost.crt -days 3650
// openssl pkcs12 -export -out identity.p12 -inkey localhost.k... | extern crate hyper_native_tls;
#[cfg(feature = "native-tls-example")]
fn main() {
// Avoid unused errors due to conditional compilation ('native-tls-example' feature is not default)
use hyper_native_tls::NativeTlsServer;
use iron::{Iron, Request, Response};
use iron::status;
use std::result::Result... | // ```
extern crate iron;
#[cfg(feature = "native-tls-example")] | random_line_split |
https.rs | // This requires running with:
//
// ```bash
// cargo run --example https --features native-tls-example
// ```
//
// Generate an identity like so:
//
// ```bash
// openssl req -x509 -newkey rsa:4096 -nodes -keyout localhost.key -out localhost.crt -days 3650
// openssl pkcs12 -export -out identity.p12 -inkey localhost.k... | () {
// Avoid unused errors due to conditional compilation ('native-tls-example' feature is not default)
use hyper_native_tls::NativeTlsServer;
use iron::{Iron, Request, Response};
use iron::status;
use std::result::Result;
let ssl = NativeTlsServer::new("identity.p12", "mypass").unwrap();
... | main | identifier_name |
https.rs | // This requires running with:
//
// ```bash
// cargo run --example https --features native-tls-example
// ```
//
// Generate an identity like so:
//
// ```bash
// openssl req -x509 -newkey rsa:4096 -nodes -keyout localhost.key -out localhost.crt -days 3650
// openssl pkcs12 -export -out identity.p12 -inkey localhost.k... | {
// We need to do this to make sure `cargo test` passes.
} | identifier_body | |
htmlobjectelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::HTMLObjectElementB... |
_ => { }
}
}
}
impl HTMLObjectElementMethods for HTMLObjectElement {
// https://html.spec.whatwg.org/multipage/#dom-cva-validity
fn Validity(&self) -> DomRoot<ValidityState> {
let window = window_from_node(self);
ValidityState::new(&window, self.upcast())
}
// ... | {
// TODO(gw): Prefetch the image here.
} | conditional_block |
htmlobjectelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::HTMLObjectElementB... | (&self) -> Option<DomRoot<HTMLFormElement>> {
self.form_owner()
}
}
impl Validatable for HTMLObjectElement {
fn is_instance_validatable(&self) -> bool {
true
}
fn validate(&self, validate_flags: ValidationFlags) -> bool {
if validate_flags.is_empty() {}
// Need more flag... | GetForm | identifier_name |
htmlobjectelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::HTMLObjectElementB... | prefix: Option<Prefix>,
document: &Document) -> DomRoot<HTMLObjectElement> {
Node::reflect_node(Box::new(HTMLObjectElement::new_inherited(local_name, prefix, document)),
document,
HTMLObjectElementBinding::Wrap)
}
}
trait P... | random_line_split | |
htmlobjectelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::HTMLObjectElementB... |
}
impl VirtualMethods for HTMLObjectElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
... | {
if validate_flags.is_empty() {}
// Need more flag check for different validation types later
true
} | identifier_body |
pif.rs | use byteorder::{BigEndian, ByteOrder};
pub const PIF_ROM_START: u32 = 0x0000;
pub const PIF_ROM_END: u32 = 0x07bf;
pub const PIF_RAM_SIZE: usize = 0x40;
pub const PIF_RAM_START: u32 = 0x07c0;
pub const PIF_RAM_END: u32 = PIF_RAM_START + (PIF_RAM_SIZE as u32) - 1;
const TEST_SEED: u32 = 0x00023F3F;
fn fix_ram(ram: &m... |
_ => {
panic!("Address out of range");
}
}
}
}
| {
BigEndian::write_u32(&mut self.ram[(addr - PIF_RAM_START) as usize..], value);
} | conditional_block |
pif.rs | use byteorder::{BigEndian, ByteOrder};
pub const PIF_ROM_START: u32 = 0x0000;
pub const PIF_ROM_END: u32 = 0x07bf;
pub const PIF_RAM_SIZE: usize = 0x40;
pub const PIF_RAM_START: u32 = 0x07c0;
pub const PIF_RAM_END: u32 = PIF_RAM_START + (PIF_RAM_SIZE as u32) - 1;
const TEST_SEED: u32 = 0x00023F3F;
fn fix_ram(ram: &m... | (&mut self, addr: u32, value: u32) {
match addr {
PIF_ROM_START...PIF_ROM_END => {
panic!("Cannot write to PIF ROM");
}
PIF_RAM_START...PIF_RAM_END => {
BigEndian::write_u32(&mut self.ram[(addr - PIF_RAM_START) as usize..], value);
... | write | identifier_name |
pif.rs | use byteorder::{BigEndian, ByteOrder};
pub const PIF_ROM_START: u32 = 0x0000;
pub const PIF_ROM_END: u32 = 0x07bf;
pub const PIF_RAM_SIZE: usize = 0x40;
pub const PIF_RAM_START: u32 = 0x07c0;
pub const PIF_RAM_END: u32 = PIF_RAM_START + (PIF_RAM_SIZE as u32) - 1;
const TEST_SEED: u32 = 0x00023F3F;
fn fix_ram(ram: &m... | panic!("Cannot write to PIF ROM");
}
PIF_RAM_START...PIF_RAM_END => {
BigEndian::write_u32(&mut self.ram[(addr - PIF_RAM_START) as usize..], value);
}
_ => {
panic!("Address out of range");
}
}
}
} | }
pub fn write(&mut self, addr: u32, value: u32) {
match addr {
PIF_ROM_START...PIF_ROM_END => { | random_line_split |
pif.rs | use byteorder::{BigEndian, ByteOrder};
pub const PIF_ROM_START: u32 = 0x0000;
pub const PIF_ROM_END: u32 = 0x07bf;
pub const PIF_RAM_SIZE: usize = 0x40;
pub const PIF_RAM_START: u32 = 0x07c0;
pub const PIF_RAM_END: u32 = PIF_RAM_START + (PIF_RAM_SIZE as u32) - 1;
const TEST_SEED: u32 = 0x00023F3F;
fn fix_ram(ram: &m... |
}
| {
match addr {
PIF_ROM_START...PIF_ROM_END => {
panic!("Cannot write to PIF ROM");
}
PIF_RAM_START...PIF_RAM_END => {
BigEndian::write_u32(&mut self.ram[(addr - PIF_RAM_START) as usize..], value);
}
_ => {
... | identifier_body |
matching.rs | //!
//! The matching module defines how a request is matched
//! against a list of potential interactions.
//!
use pact_matching::models::{RequestResponseInteraction, Request, PactSpecification};
use pact_matching::Mismatch;
use pact_matching::s;
use serde_json::json;
use itertools::Itertools;
use std::fmt::{Display, ... | },
MatchResult::RequestMismatch(interaction, mismatches) => {
write!(f, "Request did not match - {}", interaction.request)?;
for (i, mismatch) in mismatches.iter().enumerate() {
write!(f, " {}) {}", i, mismatch)?;
}
Ok(())
},
MatchResult::RequestNotFo... | random_line_split | |
matching.rs | //!
//! The matching module defines how a request is matched
//! against a list of potential interactions.
//!
use pact_matching::models::{RequestResponseInteraction, Request, PactSpecification};
use pact_matching::Mismatch;
use pact_matching::s;
use serde_json::json;
use itertools::Itertools;
use std::fmt::{Display, ... |
/// Converts this match result to a `Value` struct
pub fn to_json(&self) -> serde_json::Value {
match self {
&MatchResult::RequestMatch(_) => json!({ s!("type") : s!("request-match")}),
&MatchResult::RequestMismatch(ref interaction, ref mismatches) => mismatches_to_json(&intera... | {
match self {
MatchResult::RequestNotFound(req) => req.method == "OPTIONS",
_ => false
}
} | identifier_body |
matching.rs | //!
//! The matching module defines how a request is matched
//! against a list of potential interactions.
//!
use pact_matching::models::{RequestResponseInteraction, Request, PactSpecification};
use pact_matching::Mismatch;
use pact_matching::s;
use serde_json::json;
use itertools::Itertools;
use std::fmt::{Display, ... | (req: &Request, interactions: &Vec<RequestResponseInteraction>) -> MatchResult {
let mut match_results = interactions
.into_iter()
.map(|i| (i.clone(), pact_matching::match_request(i.request.clone(), req.clone())))
.sorted_by(|(_, i1), (_, i2)| {
Ord::cmp(&i2.score(), &i1.score())
});
match match... | match_request | identifier_name |
mod.rs | mod shell;
mod syscall;
use self::syscall::*;
#[no_mangle]
pub extern "C" fn el0_other() ->! {
println!("I just exit.");
//loop {}
syscall_exit(127);
}
#[no_mangle]
pub extern "C" fn el0_shell() ->! {
println!("I sleep 50ms.");
syscall_sleep(50).unwrap();
println!("And then I just shell.");
... | unsafe { asm!("brk 1" :::: "volatile"); }
println!("fuck you shit: {}", 555);
unsafe { asm!("brk 2" :::: "volatile"); }
//loop {}
println!("test GPIO");
use pi::gpio::{Gpio, GPIO_BASE};
use pi::common::IO_BASE_RAW;
let mut r = unsafe { Gpio::new_from(IO_BASE_RAW + GPIO_BASE, 21).into... | }
#[no_mangle]
pub extern "C" fn el0_init() -> ! {
println!("im in a bear suite"); | random_line_split |
mod.rs | mod shell;
mod syscall;
use self::syscall::*;
#[no_mangle]
pub extern "C" fn el0_other() ->! |
#[no_mangle]
pub extern "C" fn el0_shell() ->! {
println!("I sleep 50ms.");
syscall_sleep(50).unwrap();
println!("And then I just shell.");
loop {
let code = shell::shell("usr> ");
println!("exit with code: {}", code);
}
}
#[no_mangle]
pub extern "C" fn el0_init() ->! {
print... | {
println!("I just exit.");
//loop {}
syscall_exit(127);
} | identifier_body |
mod.rs | mod shell;
mod syscall;
use self::syscall::*;
#[no_mangle]
pub extern "C" fn el0_other() ->! {
println!("I just exit.");
//loop {}
syscall_exit(127);
}
#[no_mangle]
pub extern "C" fn el0_shell() ->! {
println!("I sleep 50ms.");
syscall_sleep(50).unwrap();
println!("And then I just shell.");
... | else { g.clear() }
if led & 4!= 0 { b.set() } else { b.clear() }
if!btn.level() {
led += 1;
motor.set();
syscall_sleep(5).unwrap();
motor.clear();
syscall_sleep(100).unwrap();
}
}
}
| { g.set() } | conditional_block |
mod.rs | mod shell;
mod syscall;
use self::syscall::*;
#[no_mangle]
pub extern "C" fn el0_other() ->! {
println!("I just exit.");
//loop {}
syscall_exit(127);
}
#[no_mangle]
pub extern "C" fn el0_shell() ->! {
println!("I sleep 50ms.");
syscall_sleep(50).unwrap();
println!("And then I just shell.");
... | () ->! {
println!("im in a bear suite");
unsafe { asm!("brk 1" :::: "volatile"); }
println!("fuck you shit: {}", 555);
unsafe { asm!("brk 2" :::: "volatile"); }
//loop {}
println!("test GPIO");
use pi::gpio::{Gpio, GPIO_BASE};
use pi::common::IO_BASE_RAW;
let mut r = unsafe { Gpi... | el0_init | identifier_name |
cmp_utils.rs | use regex::Regex;
use std::cmp::Ordering;
use crate::types::*;
lazy_static! {
static ref MODIFICATION_RE: Regex = Regex::new(r"^(?P<aa>[A-Z])(?P<pos>\d+)$").unwrap();
}
pub fn cmp_residues(residue1: &Option<Residue>, residue2: &Option<Residue>) -> Ordering {
if let Some(ref res1) = *residue1 {
if let... | } else {
if residue2.is_some() {
Ordering::Greater
} else {
Ordering::Equal
}
}
} | random_line_split | |
cmp_utils.rs | use regex::Regex;
use std::cmp::Ordering;
use crate::types::*;
lazy_static! {
static ref MODIFICATION_RE: Regex = Regex::new(r"^(?P<aa>[A-Z])(?P<pos>\d+)$").unwrap();
}
pub fn cmp_residues(residue1: &Option<Residue>, residue2: &Option<Residue>) -> Ordering | }
} else {
Ordering::Less
}
} else {
if residue2.is_some() {
Ordering::Greater
} else {
Ordering::Equal
}
}
}
| {
if let Some(ref res1) = *residue1 {
if let Some(ref res2) = *residue2 {
if let (Some(res1_captures), Some(res2_captures)) =
(MODIFICATION_RE.captures(res1), MODIFICATION_RE.captures(res2))
{
let res1_aa = res1_captures.name("aa").unwrap().as_str();
... | identifier_body |
cmp_utils.rs | use regex::Regex;
use std::cmp::Ordering;
use crate::types::*;
lazy_static! {
static ref MODIFICATION_RE: Regex = Regex::new(r"^(?P<aa>[A-Z])(?P<pos>\d+)$").unwrap();
}
pub fn | (residue1: &Option<Residue>, residue2: &Option<Residue>) -> Ordering {
if let Some(ref res1) = *residue1 {
if let Some(ref res2) = *residue2 {
if let (Some(res1_captures), Some(res2_captures)) =
(MODIFICATION_RE.captures(res1), MODIFICATION_RE.captures(res2))
{
... | cmp_residues | identifier_name |
cmp_utils.rs | use regex::Regex;
use std::cmp::Ordering;
use crate::types::*;
lazy_static! {
static ref MODIFICATION_RE: Regex = Regex::new(r"^(?P<aa>[A-Z])(?P<pos>\d+)$").unwrap();
}
pub fn cmp_residues(residue1: &Option<Residue>, residue2: &Option<Residue>) -> Ordering {
if let Some(ref res1) = *residue1 | } else {
Ordering::Less
}
}
else {
if residue2.is_some() {
Ordering::Greater
} else {
Ordering::Equal
}
}
}
| {
if let Some(ref res2) = *residue2 {
if let (Some(res1_captures), Some(res2_captures)) =
(MODIFICATION_RE.captures(res1), MODIFICATION_RE.captures(res2))
{
let res1_aa = res1_captures.name("aa").unwrap().as_str();
let res2_aa = res2_captur... | conditional_block |
native.rs | use winapi::*;
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct Buffer(pub *mut ID3D11Buffer);
unsafe impl Send for Buffer {}
unsafe impl Sync for Buffer {}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub enum Texture {
D1(*mut ID3D11Texture1D),
D2(*mut ID3D11Texture2D),
D3(*mut ID3D11... | pub struct Rtv(pub *mut ID3D11RenderTargetView);
unsafe impl Send for Rtv {}
unsafe impl Sync for Rtv {}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct Dsv(pub *mut ID3D11DepthStencilView);
unsafe impl Send for Dsv {}
unsafe impl Sync for Dsv {}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub st... | unsafe impl Sync for Texture {}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] | random_line_split |
native.rs | use winapi::*;
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct Buffer(pub *mut ID3D11Buffer);
unsafe impl Send for Buffer {}
unsafe impl Sync for Buffer {}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub enum Texture {
D1(*mut ID3D11Texture1D),
D2(*mut ID3D11Texture2D),
D3(*mut ID3D11... | (pub *mut ID3D11RenderTargetView);
unsafe impl Send for Rtv {}
unsafe impl Sync for Rtv {}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct Dsv(pub *mut ID3D11DepthStencilView);
unsafe impl Send for Dsv {}
unsafe impl Sync for Dsv {}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct Srv(pub *... | Rtv | identifier_name |
sudoku.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... |
pub fn from_vec(vec: &[[u8;9];9]) -> Sudoku {
let g = (0..9u).map(|i| {
(0..9u).map(|j| { vec[i][j] }).collect()
}).collect();
return Sudoku::new(g)
}
pub fn read(mut reader: &mut BufferedReader<StdReader>) -> Sudoku {
/* assert first line is exactly "9,9" */
... | {
return Sudoku { grid: g }
} | identifier_body |
sudoku.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 next_color(&mut self, row: u8, col: u8, start_color: u8) -> bool {
if start_color < 10u8 {
// colors not yet used
let mut avail = box Colors::new(start_color);
// drop colors already in use in neighbourhood
self.drop_colors(&mut *avail, r... | {
// no: redo this field aft recoloring pred; unless there is none
if ptr == 0u { panic!("No solution found for this sudoku"); }
ptr = ptr - 1u;
} | conditional_block |
sudoku.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... | let mut work: Vec<(u8, u8)> = Vec::new(); /* queue of uncolored fields */
for row in 0u8..9u8 {
for col in 0u8..9u8 {
let color = self.grid[row as uint][col as uint];
if color == 0u8 {
work.push((row, col));
}
}
... |
// solve sudoku grid
pub fn solve(&mut self) { | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.