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 |
|---|---|---|---|---|
cache.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 std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::ha... |
}
}
pub fn evict_all(&mut self) {
self.entries.clear();
}
}
pub struct LRUCache<K, V> {
entries: Vec<(K, V)>,
cache_size: usize,
}
impl<K: Clone + PartialEq, V: Clone> LRUCache<K,V> {
pub fn new(size: usize) -> LRUCache<K, V> {
LRUCache {
entries: vec!(),
... | {
(*vacant.insert(blk(key))).clone()
} | conditional_block |
cache.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 std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::ha... | impl<K, V> HashCache<K,V>
where K: Clone + PartialEq + Eq + Hash,
V: Clone,
{
pub fn new() -> HashCache<K,V> {
HashCache {
entries: HashMap::with_hash_state(<DefaultState<SipHasher> as Default>::default()),
}
}
pub fn insert(&mut self, key: K, value: V) {
sel... | pub struct HashCache<K, V> {
entries: HashMap<K, V, DefaultState<SipHasher>>,
}
| random_line_split |
cache.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 std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::ha... |
pub fn iter<'a>(&'a self) -> Iter<'a,(K,V)> {
self.entries.iter()
}
pub fn insert(&mut self, key: K, val: V) {
if self.entries.len() == self.cache_size {
self.entries.remove(0);
}
self.entries.push((key, val));
}
pub fn find(&mut self, key: &K) -> Opti... | {
let last_index = self.entries.len() - 1;
if pos != last_index {
let entry = self.entries.remove(pos);
self.entries.push(entry);
}
self.entries[last_index].1.clone()
} | identifier_body |
lib.rs | //
//
//
#![crate_type="rlib"]
#![crate_name="alloc"]
#![feature(no_std)]
#![feature(lang_items)] // Allow definition of lang_items
#![feature(const_fn,unsize,coerce_unsized)]
#![feature(unique,nonzero)]
#![feature(box_syntax)]
#![feature(core_intrinsics,raw)]
#![feature(core_slice_ext)]
#![feature(optin_builtin_traits... |
}
pub fn into_box(self) -> ::boxed::Box<[T]> {
todo!("into_box");
}
pub fn unsafe_no_drop_flag_needs_drop(&self) -> bool {
self.cap()!= ::core::mem::POST_DROP_USIZE
}
}
}
| {
let newcap = self.cap() * 2;
self.0.resize(newcap);
} | conditional_block |
lib.rs | //
//
//
#![crate_type="rlib"]
#![crate_name="alloc"]
#![feature(no_std)]
#![feature(lang_items)] // Allow definition of lang_items
#![feature(const_fn,unsize,coerce_unsized)]
#![feature(unique,nonzero)]
#![feature(box_syntax)]
#![feature(core_intrinsics,raw)]
#![feature(core_slice_ext)]
#![feature(optin_builtin_traits... | (&mut self, used: usize) {
self.0.resize(used);
}
pub fn reserve(&mut self, cur_used: usize, extra: usize) {
let newcap = cur_used + extra;
if newcap < self.cap() {
}
else {
self.0.resize(newcap);
}
}
pub fn reserve_exact(&mut self, cur_used: usize, extra: usize) {
let newcap = cur... | shrink_to_fit | identifier_name |
lib.rs | //
//
//
#![crate_type="rlib"]
#![crate_name="alloc"]
#![feature(no_std)]
#![feature(lang_items)] // Allow definition of lang_items
#![feature(const_fn,unsize,coerce_unsized)]
#![feature(unique,nonzero)]
#![feature(box_syntax)]
#![feature(core_intrinsics,raw)]
#![feature(core_slice_ext)]
#![feature(optin_builtin_traits... |
pub fn ptr(&self) -> *mut T {
self.0.get_base() as *mut T
}
pub fn shrink_to_fit(&mut self, used: usize) {
self.0.resize(used);
}
pub fn reserve(&mut self, cur_used: usize, extra: usize) {
let newcap = cur_used + extra;
if newcap < self.cap() {
}
else {
self.0.resize(newcap);
}
... | {
self.0.count()
} | identifier_body |
lib.rs | // | #![crate_name="alloc"]
#![feature(no_std)]
#![feature(lang_items)] // Allow definition of lang_items
#![feature(const_fn,unsize,coerce_unsized)]
#![feature(unique,nonzero)]
#![feature(box_syntax)]
#![feature(core_intrinsics,raw)]
#![feature(core_slice_ext)]
#![feature(optin_builtin_traits)] // For!Send
#![feature(filli... | //
//
#![crate_type="rlib"] | random_line_split |
edit_server.rs | // Copyright 2016 Matthew Collins
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... | elements: None,
entry_info: entry_info,
}
}
fn save_servers(index: Option<usize>, name: &str, address: &str) {
let mut servers_info = match fs::File::open("servers.json") {
Ok(val) => serde_json::from_reader(val).unwrap(),
Err(_) => {
... | pub fn new(entry_info: Option<(usize, String, String)>) -> EditServerEntry {
EditServerEntry { | random_line_split |
edit_server.rs | // Copyright 2016 Matthew Collins
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... | {
logo: ui::logo::Logo,
elements: ui::Collection,
}
impl EditServerEntry {
pub fn new(entry_info: Option<(usize, String, String)>) -> EditServerEntry {
EditServerEntry {
elements: None,
entry_info: entry_info,
}
}
fn save_servers(index: Option<usize>, name:... | UIElements | identifier_name |
edit_server.rs | // Copyright 2016 Matthew Collins
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... |
}
| {
true
} | identifier_body |
util.rs | use std::collections::HashMap;
use std::sync::mpsc::{self, Receiver};
use std::thread;
use failure::format_err;
use octobot_lib::errors::*;
fn escape_for_slack(str: &str) -> String {
str.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
}
pub fn make_link(url: &str, text: &str) -> ... | (query_params: Option<&str>) -> HashMap<String, String> {
if query_params.is_none() {
return HashMap::new();
}
query_params
.unwrap()
.split('&')
.filter_map(|v| {
let parts = v.splitn(2, '=').collect::<Vec<_>>();
if parts.len()!= 2 {
None... | parse_query | identifier_name |
util.rs | use std::collections::HashMap;
use std::sync::mpsc::{self, Receiver};
use std::thread;
use failure::format_err;
use octobot_lib::errors::*;
fn escape_for_slack(str: &str) -> String {
str.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
}
pub fn make_link(url: &str, text: &str) -> ... | "Hey @mentioned-user, let me know what @other-mentioned-user thinks"
)
);
assert_eq!(
Vec::<&str>::new(),
get_mentioned_usernames("This won't count as a mention@notamention")
);
}
#[test]
fn test_check_unique_event() {
let ... | random_line_split | |
util.rs | use std::collections::HashMap;
use std::sync::mpsc::{self, Receiver};
use std::thread;
use failure::format_err;
use octobot_lib::errors::*;
fn escape_for_slack(str: &str) -> String {
str.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
}
pub fn make_link(url: &str, text: &str) -> ... |
#[test]
fn test_parse_query_none() {
assert_eq!(HashMap::new(), parse_query(None));
}
}
| {
let map = hashmap! {
"A".to_string() => "1".to_string(),
"B".to_string() => "Hello%20There".to_string(),
};
assert_eq!(map, parse_query(Some("A=1&B=Hello%20There")));
} | identifier_body |
util.rs | use std::collections::HashMap;
use std::sync::mpsc::{self, Receiver};
use std::thread;
use failure::format_err;
use octobot_lib::errors::*;
fn escape_for_slack(str: &str) -> String {
str.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
}
pub fn make_link(url: &str, text: &str) -> ... |
None => {
return Err(format_err!("Timed out waiting"));
}
},
Err(mpsc::TryRecvError::Disconnected) => {
return Err(format_err!("Channel disconnected!"));
}
};
}
}
#[cfg(test)]
mod tests {
use super:... | {
time_left = sub;
thread::sleep(sleep_time);
} | conditional_block |
mod.rs | use command_prelude::*;
pub fn | () -> Vec<App> {
vec![
bench::cli(),
build::cli(),
check::cli(),
clean::cli(),
doc::cli(),
fetch::cli(),
generate_lockfile::cli(),
git_checkout::cli(),
init::cli(),
install::cli(),
locate_project::cli(),
login::cli(),
... | builtin | identifier_name |
mod.rs | use command_prelude::*;
pub fn builtin() -> Vec<App> {
vec![
bench::cli(),
build::cli(),
check::cli(),
clean::cli(),
doc::cli(),
fetch::cli(),
generate_lockfile::cli(),
git_checkout::cli(),
init::cli(),
install::cli(),
locate_p... | "doc" => doc::exec,
"fetch" => fetch::exec,
"generate-lockfile" => generate_lockfile::exec,
"git-checkout" => git_checkout::exec,
"init" => init::exec,
"install" => install::exec,
"locate-project" => locate_project::exec,
"login" => login::exec,
"m... | "build" => build::exec,
"check" => check::exec,
"clean" => clean::exec, | random_line_split |
mod.rs | use command_prelude::*;
pub fn builtin() -> Vec<App> | read_manifest::cli(),
run::cli(),
rustc::cli(),
rustdoc::cli(),
search::cli(),
test::cli(),
uninstall::cli(),
update::cli(),
verify_project::cli(),
version::cli(),
yank::cli(),
]
}
pub fn builtin_exec(cmd: &str) -> Option<fn(&... | {
vec![
bench::cli(),
build::cli(),
check::cli(),
clean::cli(),
doc::cli(),
fetch::cli(),
generate_lockfile::cli(),
git_checkout::cli(),
init::cli(),
install::cli(),
locate_project::cli(),
login::cli(),
metadata:... | identifier_body |
_build.rs | use std::env;
use std::path::PathBuf;
fn | () {
let target = env::var("TARGET").unwrap();
if target.contains("pc-windows") {
let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
let mut lib_dir = manifest_dir.clone();
let mut dll_dir = manifest_dir.clone();
if target.contains("msvc") {
... | main | identifier_name |
_build.rs | use std::env;
use std::path::PathBuf;
fn main() | dll_dir.push("64");
} else {
lib_dir.push("32");
dll_dir.push("32");
}
println!("cargo:rustc-link-serach=all={}", lib_dir.display());
for entry in std::fs::read_dir(dll_dir).expect("Can't read DLL dir") {
let entry_path = entry.exp... | {
let target = env::var("TARGET").unwrap();
if target.contains("pc-windows") {
let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
let mut lib_dir = manifest_dir.clone();
let mut dll_dir = manifest_dir.clone();
if target.contains("msvc") {
... | identifier_body |
_build.rs | use std::env;
use std::path::PathBuf;
fn main() {
let target = env::var("TARGET").unwrap();
if target.contains("pc-windows") | lib_dir.push("32");
dll_dir.push("32");
}
println!("cargo:rustc-link-serach=all={}", lib_dir.display());
for entry in std::fs::read_dir(dll_dir).expect("Can't read DLL dir") {
let entry_path = entry.expect("invalid fs entry").path();
let fi... | {
let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
let mut lib_dir = manifest_dir.clone();
let mut dll_dir = manifest_dir.clone();
if target.contains("msvc") {
lib_dir.push("msvc");
dll_dir.push("msvc");
} else {
... | conditional_block |
_build.rs | use std::env;
use std::path::PathBuf;
fn main() {
let target = env::var("TARGET").unwrap();
if target.contains("pc-windows") {
let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
let mut lib_dir = manifest_dir.clone();
let mut dll_dir = manifest_dir.clone(... | println!("cargo:rustc-link-serach=all={}", lib_dir.display());
for entry in std::fs::read_dir(dll_dir).expect("Can't read DLL dir") {
let entry_path = entry.expect("invalid fs entry").path();
let file_name_result = entry_path.file_name();
let mut new_file_path = m... | random_line_split | |
no_effect.rs | #![feature(box_syntax)]
#![warn(clippy::no_effect)]
#![allow(dead_code)]
#![allow(path_statements)]
#![allow(clippy::deref_addrof)]
#![allow(clippy::redundant_field_names)]
#![feature(untagged_unions)]
struct Unit;
struct Tuple(i32);
struct Struct {
field: i32,
}
enum Enum {
Tuple(i32),
Struct { field: i32... | (&mut self) {}
}
struct FooString {
s: String,
}
union Union {
a: u8,
b: f64,
}
fn get_number() -> i32 {
0
}
fn get_struct() -> Struct {
Struct { field: 0 }
}
fn get_drop_struct() -> DropStruct {
DropStruct { field: 0 }
}
unsafe fn unsafe_fn() -> i32 {
0
}
fn main() {
let s = get_stru... | drop | identifier_name |
no_effect.rs | #![feature(box_syntax)]
#![warn(clippy::no_effect)]
#![allow(dead_code)]
#![allow(path_statements)]
#![allow(clippy::deref_addrof)]
#![allow(clippy::redundant_field_names)]
#![feature(untagged_unions)]
struct Unit;
struct Tuple(i32);
struct Struct {
field: i32,
}
enum Enum {
Tuple(i32),
Struct { field: i32... |
fn main() {
let s = get_struct();
let s2 = get_struct();
0;
s2;
Unit;
Tuple(0);
Struct { field: 0 };
Struct {..s };
Union { a: 0 };
Enum::Tuple(0);
Enum::Struct { field: 0 };
5 + 6;
*&42;
&6;
(5, 6, 7);
box 42;
..;
5..;
..5;
5..6;
5..=... | {
0
} | identifier_body |
no_effect.rs | #![feature(box_syntax)]
#![warn(clippy::no_effect)]
#![allow(dead_code)]
#![allow(path_statements)]
#![allow(clippy::deref_addrof)]
#![allow(clippy::redundant_field_names)]
#![feature(untagged_unions)]
struct Unit;
struct Tuple(i32);
struct Struct {
field: i32,
}
enum Enum {
Tuple(i32),
Struct { field: i32... | Union { a: 0 };
Enum::Tuple(0);
Enum::Struct { field: 0 };
5 + 6;
*&42;
&6;
(5, 6, 7);
box 42;
..;
5..;
..5;
5..6;
5..=6;
[42, 55];
[42, 55][1];
(42, 55).1;
[42; 55];
[42; 55][13];
let mut x = 0;
|| x += 5;
let s: String = "foo".into();
... | Struct { ..s }; | random_line_split |
lib.rs | #![feature(proc_macro)]
#![recursion_limit = "128"]
#[macro_use]
extern crate lazy_static;
extern crate proc_macro;
#[macro_use]
extern crate quote;
extern crate regex;
extern crate remacs_util;
extern crate syn;
use proc_macro::TokenStream;
use regex::Regex;
mod function;
#[proc_macro_attribute]
pub fn | (attr_ts: TokenStream, fn_ts: TokenStream) -> TokenStream {
let fn_item = syn::parse_item(&fn_ts.to_string()).unwrap();
let function = function::parse(&fn_item).unwrap();
let lisp_fn_args = match remacs_util::parse_lisp_fn(
&attr_ts.to_string(),
&function.name,
function.fntype.def_mi... | lisp_fn | identifier_name |
lib.rs | #![feature(proc_macro)]
#![recursion_limit = "128"]
#[macro_use]
extern crate lazy_static;
extern crate proc_macro;
#[macro_use]
extern crate quote;
extern crate regex;
extern crate remacs_util;
extern crate syn;
use proc_macro::TokenStream;
use regex::Regex;
mod function;
#[proc_macro_attribute]
pub fn lisp_fn(att... | {
syn::Ident::new(format!("{}{}", lhs, rhs))
} | identifier_body | |
lib.rs | #![feature(proc_macro)]
#![recursion_limit = "128"]
#[macro_use]
extern crate lazy_static;
extern crate proc_macro;
#[macro_use]
extern crate quote;
extern crate regex;
extern crate remacs_util;
extern crate syn;
use proc_macro::TokenStream;
use regex::Regex;
mod function;
#[proc_macro_attribute]
pub fn lisp_fn(att... |
let tokens = quote! {
#[no_mangle]
pub extern "C" fn #fname(#cargs) -> ::remacs_sys::Lisp_Object {
#body
let ret = #rname(#rargs);
::lisp::LispObject::from(ret).to_raw()
}
lazy_static! {
pub static ref #sname: ::lisp::LispSubrRef = ... | {
windows_header = quote!{
| (::std::mem::size_of::<::remacs_sys::Lisp_Subr>()
/ ::std::mem::size_of::<::remacs_sys::EmacsInt>()) as ::libc::ptrdiff_t
};
} | conditional_block |
lib.rs | #![feature(proc_macro)]
#![recursion_limit = "128"]
#[macro_use]
extern crate lazy_static;
extern crate proc_macro;
#[macro_use]
extern crate quote;
extern crate regex;
extern crate remacs_util;
extern crate syn;
use proc_macro::TokenStream;
use regex::Regex;
mod function;
#[proc_macro_attribute]
pub fn lisp_fn(att... |
// we could put #fn_item into the quoted code above, but doing so
// drops all of the line numbers on the floor and causes the
// compiler to attribute any errors in the function to the macro
// invocation instead.
// Note: TokenStream has a FromIterator trait impl that converts
// an iterator ... | ::lisp::ExternalPtr::new(ptr)
}
};
}
}; | random_line_split |
messageevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::MessageEve... | (&self) -> bool {
self.event.IsTrusted()
}
}
| IsTrusted | identifier_name |
messageevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::MessageEve... | bubbles: bool, cancelable: bool,
data: HandleValue, origin: DOMString, lastEventId: DOMString)
-> Root<MessageEvent> {
let ev = MessageEvent::new_initialized(global, data, origin, lastEventId);
{
let event = ev.upcast::<Event>();
event... |
pub fn new(global: GlobalRef, type_: Atom, | random_line_split |
messageevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::MessageEve... |
pub fn new_initialized(global: GlobalRef,
data: HandleValue,
origin: DOMString,
lastEventId: DOMString) -> Root<MessageEvent> {
let mut ev = box MessageEvent {
event: Event::new_inherited(),
data: Heap... | {
MessageEvent::new_initialized(global,
HandleValue::undefined(),
DOMString::new(),
DOMString::new())
} | identifier_body |
bvh_base.rs | #![allow(dead_code)]
use crate::{algorithm::merge_slices_append, bbox::BBox, lerp::lerp_slice, math::log2_64};
use super::objects_split::{median_split, sah_split};
pub const BVH_MAX_DEPTH: usize = 42;
// Amount bigger the union of all time samples can be
// and still use the union rather than preserve the
// indivi... | (&self) -> usize {
0
}
fn acc_bounds<'a, T, F>(&mut self, objects: &mut [T], bounder: &F)
where
F: 'a + Fn(&T) -> &'a [BBox],
{
// TODO: do all of this without the temporary cache
let max_len = objects.iter().map(|obj| bounder(obj).len()).max().unwrap();
self.bo... | root_node_index | identifier_name |
bvh_base.rs | #![allow(dead_code)]
use crate::{algorithm::merge_slices_append, bbox::BBox, lerp::lerp_slice, math::log2_64};
use super::objects_split::{median_split, sah_split};
pub const BVH_MAX_DEPTH: usize = 42;
// Amount bigger the union of all time samples can be
// and still use the union rather than preserve the
// indivi... | self.bounds_cache[i] |= bounds[i];
}
} else {
let s = (max_len - 1) as f32;
for (i, bbc) in self.bounds_cache.iter_mut().enumerate() {
*bbc |= lerp_slice(bounds, i as f32 / s);
}
}
}
... | random_line_split | |
bvh_base.rs | #![allow(dead_code)]
use crate::{algorithm::merge_slices_append, bbox::BBox, lerp::lerp_slice, math::log2_64};
use super::objects_split::{median_split, sah_split};
pub const BVH_MAX_DEPTH: usize = 42;
// Amount bigger the union of all time samples can be
// and still use the union rather than preserve the
// indivi... |
}
}
fn recursive_build<'a, T, F>(
&mut self,
offset: usize,
depth: usize,
objects_per_leaf: usize,
objects: &mut [T],
bounder: &F,
) -> (usize, (usize, usize))
where
F: 'a + Fn(&T) -> &'a [BBox],
{
let me = self.nodes.len();
... | {
let s = (max_len - 1) as f32;
for (i, bbc) in self.bounds_cache.iter_mut().enumerate() {
*bbc |= lerp_slice(bounds, i as f32 / s);
}
} | conditional_block |
deriving-rand.rs | // Copyright 2013-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... | {
D0,
D1(usize),
D2 { x: (), y: () }
}
pub fn main() {
// check there's no segfaults
for _ in 0..20 {
rand::random::<A>();
rand::random::<B>();
rand::random::<C>();
rand::random::<D>();
}
}
| D | identifier_name |
deriving-rand.rs | // Copyright 2013-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... | } | } | random_line_split |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![crate_name = "devtools"]
#![crate_type = "rlib"]
#![comment = "The Servo Parallel Browser Project"]
#![license... | (port: Receiver<DevtoolsControlMsg>) {
let listener = TcpListener::bind("127.0.0.1", 6000);
// bind the listener to the specified address
let mut acceptor = listener.listen().unwrap();
acceptor.set_timeout(Some(POLL_TIMEOUT));
let mut registry = ActorRegistry::new();
let root = box RootActor ... | run_server | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![crate_name = "devtools"]
#![crate_type = "rlib"]
#![comment = "The Servo Parallel Browser Project"]
#![license... | let packet_len = num::from_str_radix(packet_len_str.as_slice(), 10).unwrap();
let packet_buf = stream.read_exact(packet_len).unwrap();
let packet = String::from_utf8(packet_buf).unwrap();
println!("{:s}", packet);
... | {
println!("connection established to {:?}", stream.peer_name().unwrap());
{
let mut actors = actors.lock();
let msg = actors.find::<RootActor>("root").encodable();
stream.write_json_packet(&msg);
}
// https://wiki.mozilla.org/Remote_Debugging_Protoc... | identifier_body |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![crate_name = "devtools"]
#![crate_type = "rlib"]
#![comment = "The Servo Parallel Browser Project"]
#![license... | acceptor.set_timeout(Some(POLL_TIMEOUT));
let mut registry = ActorRegistry::new();
let root = box RootActor {
tabs: vec!(),
};
registry.register(root);
registry.find::<RootActor>("root");
let actors = Arc::new(Mutex::new(registry));
/// Process the input from a single devtoo... | fn run_server(port: Receiver<DevtoolsControlMsg>) {
let listener = TcpListener::bind("127.0.0.1", 6000);
// bind the listener to the specified address
let mut acceptor = listener.listen().unwrap(); | random_line_split |
message.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::rpc::LayoutRPC;
use crate::{OpaqueStyleAndLayoutData, PendingImage, TrustedNodeAddress};
use app_units... | ReflowGoal::Full | ReflowGoal::TickAnimations => true,
ReflowGoal::LayoutQuery(ref querymsg, _) => match *querymsg {
QueryMsg::NodesFromPointQuery(..) |
QueryMsg::TextIndexQuery(..) |
QueryMsg::InnerWindowDimensionsQuery(_) |
QueryM... | pub fn needs_display_list(&self) -> bool {
match *self { | random_line_split |
message.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::rpc::LayoutRPC;
use crate::{OpaqueStyleAndLayoutData, PendingImage, TrustedNodeAddress};
use app_units... | {
Full,
TickAnimations,
LayoutQuery(QueryMsg, u64),
}
impl ReflowGoal {
/// Returns true if the given ReflowQuery needs a full, up-to-date display list to
/// be present or false if it only needs stacking-relative positions.
pub fn needs_display_list(&self) -> bool {
match *self {
... | ReflowGoal | identifier_name |
authentication.rs | // Authentication
use hyper::client::{Client};
use hyper::server::{Server, Request, Response, Listening};
use hyper::uri::RequestUri::AbsolutePath;
use regex::Regex;
use rustc_serialize::json::Json;
use std::fs;
use std::io::prelude::*;
use std::process::Command;
use std::sync::Mutex;
use std::sync::mpsc::channel;
pub... |
// TODO Needs test
fn format_access_uri(temp_code: &TempCode) -> String {
let base = "https://slack.com/api/oauth.access";
let query = format!("?client_id={}&client_secret={}&code={}", SLACK_CLIENT_ID, SLACK_CLIENT_SECRET, temp_code);
format!("{}{}", base, query)
}
fn extract_temp_code(path: &str) -> Opt... | {
let mut client = Client::new();
// I thought & is sufficient to make it a slice
let mut res = client.get(format_access_uri(temp_code).as_str()).send().unwrap();
let mut body = String::new();
res.read_to_string(&mut body).unwrap();
match Json::from_str(&body) {
Ok(json) => {
... | identifier_body |
authentication.rs | // Authentication
use hyper::client::{Client};
use hyper::server::{Server, Request, Response, Listening};
use hyper::uri::RequestUri::AbsolutePath;
use regex::Regex;
use rustc_serialize::json::Json;
use std::fs;
use std::io::prelude::*;
use std::process::Command;
use std::sync::Mutex;
use std::sync::mpsc::channel;
pub... |
// TODO Test
fn store_token(token: &AuthToken) {
let mut f = fs::File::create(AUTH_TOKEN_FILE).unwrap();
f.write_all(token.as_bytes()).unwrap();
}
#[allow(dead_code)] // Hard to test
fn request_temp_code() -> (TempCode, Listening) {
Command::new("xdg-open").arg(format!("https://slack.com/oauth/authorize?s... | fn arrange_new_token() -> (AuthToken, Listening) {
let (temp_code, listener) = request_temp_code();
let token = request_token(&temp_code);
(token, listener)
} | random_line_split |
authentication.rs | // Authentication
use hyper::client::{Client};
use hyper::server::{Server, Request, Response, Listening};
use hyper::uri::RequestUri::AbsolutePath;
use regex::Regex;
use rustc_serialize::json::Json;
use std::fs;
use std::io::prelude::*;
use std::process::Command;
use std::sync::Mutex;
use std::sync::mpsc::channel;
pub... | () -> (TempCode, Listening) {
Command::new("xdg-open").arg(format!("https://slack.com/oauth/authorize?scope=client&client_id={}", SLACK_CLIENT_ID)).output().unwrap();
let (tx, rx) = channel();
let mtx = Mutex::new(tx);
let mut guard = Server::http("127.0.0.1:9999").unwrap().handle(move |req: Request, ... | request_temp_code | identifier_name |
timeline_demo.rs | use nannou::prelude::*;
use nannou::ui::prelude::*;
use nannou_timeline as timeline;
use pitch_calc as pitch;
use std::iter::once;
use time_calc as time;
use timeline::track::automation::{BangValue as Bang, Envelope, Point, ToggleValue as Toggle};
use timeline::track::piano_roll;
use timeline::{bars, track};
const BPM... | } | } | random_line_split |
timeline_demo.rs | use nannou::prelude::*;
use nannou::ui::prelude::*;
use nannou_timeline as timeline;
use pitch_calc as pitch;
use std::iter::once;
use time_calc as time;
use timeline::track::automation::{BangValue as Bang, Envelope, Point, ToggleValue as Toggle};
use timeline::track::piano_roll;
use timeline::{bars, track};
const BPM... | (app: &App, model: &Model, frame: Frame) {
model.ui.draw_to_frame(app, &frame).unwrap();
}
// Update / draw the Ui.
fn set_widgets(ui: &mut UiCell, ids: &Ids, data: &mut TimelineData) {
use timeline::Timeline;
// Main window canvas.
widget::Canvas::new()
.border(0.0)
.color(ui::color::DA... | view | identifier_name |
timeline_demo.rs | use nannou::prelude::*;
use nannou::ui::prelude::*;
use nannou_timeline as timeline;
use pitch_calc as pitch;
use std::iter::once;
use time_calc as time;
use timeline::track::automation::{BangValue as Bang, Envelope, Point, ToggleValue as Toggle};
use timeline::track::piano_roll;
use timeline::{bars, track};
const BPM... | ;
let delta_ticks = time::Ms(delta_secs * ONE_SECOND_MS).to_ticks(current_bpm, PPQN);
let total_duration_ticks =
timeline::bars_duration_ticks(timeline_data.bars.iter().cloned(), PPQN);
let previous_playhead_ticks = timeline_data.playhead_ticks.clone();
timeline_data.playhead_ticks =
(ti... | {
0.0
} | conditional_block |
canvas.rs | // +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> |
// | |
// | This file is part of Tuna. |
... |
}
pub fn draw_image(
&mut self,
image: &ahi::Image,
palette: &ahi::Palette,
left: i32,
top: i32,
scale: u32,
) {
for row in 0..image.height() {
for col in 0..image.width() {
let pixel = image[(col, row)];
l... | {
self.renderer.clear();
} | conditional_block |
canvas.rs | // +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> |
// | |
// | This file is part of Tuna. |
... | Resources {
arrows: load_sprites_from_file(creator, "data/arrows.ahi"),
font: load_font_from_file(creator, "data/medfont.ahf"),
tool_icons: load_sprites_from_file(creator, "data/tool_icons.ahi"),
unsaved_icon: load_sprite_from_file(creator, "data/unsaved.ahi"),
... |
impl<'a> Resources<'a> {
pub fn new(creator: &'a TextureCreator<WindowContext>) -> Resources<'a> { | random_line_split |
canvas.rs | // +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> |
// | |
// | This file is part of Tuna. |
... | <'a> {
glyphs: HashMap<char, Glyph<'a>>,
default_glyph: Glyph<'a>,
_baseline: i32,
}
impl<'a> Font<'a> {
pub fn text_width(&self, text: &str) -> i32 {
let mut width = 0;
for chr in text.chars() {
let glyph = self.glyph(chr);
width += glyph.right_edge - glyph.left... | Font | identifier_name |
points.rs | use std::io;
const MAX: i32 = 99999999;
const MIN: i32 = -99999999;
struct Point {x: i32, y: i32,}
struct Line {h: Point, i: Point,}
impl Line {
fn length(&self, a: i32, b: i32) -> f64 {
let c = (a * a) + (b * b);
if c > MAX || c < MIN {panic!("overload.");}
(c as f64).sqrt()
}
fn midpoint(&self, a: i... | else {l1.i.x - l1.h.x};
if s1 > MAX || s1 < MIN {panic!("overload");}
let s2: i32 = if l1.h.y > l1.i.y {l1.h.y - l1.i.y} else {l1.i.y - l1.h.y};
if s2 > MAX || s2 < MIN {panic!("overload");}
let len = l1.length (s1, s2);
println!("length: {}", len);
let mid = l1.midpoint(l1.h.x, l1.i.x, l1.h.y, l1.i.y);
... | {l1.h.x - l1.i.x} | conditional_block |
points.rs | use std::io;
const MAX: i32 = 99999999;
const MIN: i32 = -99999999;
struct Point {x: i32, y: i32,}
struct Line {h: Point, i: Point,}
impl Line {
fn length(&self, a: i32, b: i32) -> f64 {
let c = (a * a) + (b * b);
if c > MAX || c < MIN {panic!("overload.");}
(c as f64).sqrt()
}
fn midpoint(&self, a: i... | () {
let mut numbox = vec![0, 0, 0, 0];
for i in 0..4 {
match i {
0 => println!("point 1 x-value: "),
1 => println!("point 1 y-value: "),
2 => println!("point 2 x-value: "),
3 => println!("point 2 y-value: "),
_ => panic!("error"),
}
let mut osin = io::stdin();
let mut ... | main | identifier_name |
points.rs | use std::io;
const MAX: i32 = 99999999;
const MIN: i32 = -99999999;
struct Point {x: i32, y: i32,}
struct Line {h: Point, i: Point,}
impl Line {
fn length(&self, a: i32, b: i32) -> f64 {
let c = (a * a) + (b * b);
if c > MAX || c < MIN {panic!("overload.");}
(c as f64).sqrt()
}
fn midpoint(&self, a: i... | osin.read_line(&mut entry).ok().expect("error.");
let gen: Option<i32> = entry.trim().parse::<i32>().ok();
let num = match gen {Some(num) => num, None => {return;}};
if num > MAX || num < MIN {panic!("overload");}
numbox[i] = num;
}
let p1: Point = Point {x: numbox[0], y: numbox[1]};
let p2: P... | _ => panic!("error"),
}
let mut osin = io::stdin();
let mut entry = String::new(); | random_line_split |
tutorial-10.rs | #[macro_use]
extern crate glium;
#[path = "../book/tuto-07-teapot.rs"]
mod teapot;
fn | () {
#[allow(unused_imports)]
use glium::{glutin, Surface};
let event_loop = glutin::event_loop::EventLoop::new();
let wb = glutin::window::WindowBuilder::new();
let cb = glutin::ContextBuilder::new().with_depth_buffer(24);
let display = glium::Display::new(wb, cb, &event_loop).unwrap();
l... | main | identifier_name |
tutorial-10.rs | #[macro_use]
extern crate glium;
#[path = "../book/tuto-07-teapot.rs"]
mod teapot;
fn main() | out vec3 v_normal;
uniform mat4 perspective;
uniform mat4 matrix;
void main() {
v_normal = transpose(inverse(mat3(matrix))) * normal;
gl_Position = perspective * matrix * vec4(position, 1.0);
}
"#;
let fragment_shader_src = r#"
#version ... | {
#[allow(unused_imports)]
use glium::{glutin, Surface};
let event_loop = glutin::event_loop::EventLoop::new();
let wb = glutin::window::WindowBuilder::new();
let cb = glutin::ContextBuilder::new().with_depth_buffer(24);
let display = glium::Display::new(wb, cb, &event_loop).unwrap();
let ... | identifier_body |
tutorial-10.rs | #[macro_use]
extern crate glium;
#[path = "../book/tuto-07-teapot.rs"]
mod teapot;
fn main() {
#[allow(unused_imports)]
use glium::{glutin, Surface};
let event_loop = glutin::event_loop::EventLoop::new();
let wb = glutin::window::WindowBuilder::new();
let cb = glutin::ContextBuilder::new().with_d... | let znear = 0.1;
let f = 1.0 / (fov / 2.0).tan();
[
[f * aspect_ratio , 0.0, 0.0 , 0.0],
[ 0.0 , f, 0.0 , 0.0],
[ 0.0 , 0.0, (zfar+znear... |
let fov: f32 = 3.141592 / 3.0;
let zfar = 1024.0; | random_line_split |
get-flavor.rs | // Copyright 2018 Dmitry Tantsur <divius.inside@gmail.com>
//
// 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 ap... | } | fn main() {
panic!("This example cannot run with 'compute' feature disabled"); | random_line_split |
get-flavor.rs | // Copyright 2018 Dmitry Tantsur <divius.inside@gmail.com>
//
// 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 ap... | () {
panic!("This example cannot run with 'compute' feature disabled");
}
| main | identifier_name |
get-flavor.rs | // Copyright 2018 Dmitry Tantsur <divius.inside@gmail.com>
//
// 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 ap... |
#[cfg(not(feature = "compute"))]
fn main() {
panic!("This example cannot run with 'compute' feature disabled");
}
| {
env_logger::init();
let os = openstack::Cloud::from_env()
.expect("Failed to create an identity provider from the environment");
let id = env::args().nth(1).expect("Provide a flavor ID");
let flavor = os.get_flavor(id).expect("Cannot get a flavor");
println!(
"ID = {}, Name = {}... | identifier_body |
htmlframeelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLFrameElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLFrame... | {
htmlelement: HTMLElement
}
impl HTMLFrameElementDerived for EventTarget {
fn is_htmlframeelement(&self) -> bool {
*self.type_id() ==
EventTargetTypeId::Node(
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLFrameElement)))
}
}
impl HTMLFrameEleme... | HTMLFrameElement | identifier_name |
htmlframeelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLFrameElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLFrame... |
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: JSRef<Document>) -> Temporary<HTMLFrameElement> {
let element = HTMLFrameElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, documen... | {
HTMLFrameElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLFrameElement, localName, prefix, document)
}
} | identifier_body |
htmlframeelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLFrameElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLFrame... |
impl HTMLFrameElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLFrameElement {
HTMLFrameElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLFrameElement, localName, prefix, document)
}
}
#[allow(un... | *self.type_id() ==
EventTargetTypeId::Node(
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLFrameElement)))
}
} | random_line_split |
mediaquerylist.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::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNul... | (&self) -> DOMString {
let mut s = String::new();
self.media_query_list.to_css(&mut s).unwrap();
DOMString::from_string(s)
}
// https://drafts.csswg.org/cssom-view/#dom-mediaquerylist-matches
fn Matches(&self) -> bool {
match self.last_match_state.get() {
None =>... | Media | identifier_name |
mediaquerylist.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::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNul... | fn evaluate_changes(&self) -> MediaQueryListMatchState {
let matches = self.evaluate();
let result = if let Some(old_matches) = self.last_match_state.get() {
if old_matches == matches {
MediaQueryListMatchState::Same(matches)
} else {
MediaQue... | }
}
impl MediaQueryList { | random_line_split |
lib.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 dirs = [
LogDirective { name: None, level: 3 },
LogDirective { name: Some("crate1::mod1".to_string()), level: 2 }
];
assert!(enabled(2, "crate1::mod1", dirs.iter()));
assert!(enabled(3, "crate2::mod2", dirs.iter()));
}
#[test]
fn zero_level()... | match_default | identifier_name |
lib.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 ... |
}
}
}
/// This function is called directly by the compiler when using the logging
/// macros. This function does not take into account whether the log level
/// specified is active or not, it will always log something if this method is
/// called.
///
/// It is not recommended to call this function direct... | {} | conditional_block |
lib.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 mut logger: Box<Logger + Send> = LOCAL_LOGGER.with(|s| {
s.borrow_mut().take()
}).unwrap_or_else(|| {
box DefaultLogger { handle: io::stderr() }
});
logger.log(&LogRecord {
level: LogLevel(level),
args: args,
file: loc.file,
module_path: loc.module_pat... | {
// Test the literal string from args against the current filter, if there
// is one.
unsafe {
let _g = LOCK.lock();
match FILTER as usize {
0 => {}
1 => panic!("cannot log after main thread has exited"),
n => {
let filter = mem::transmute... | identifier_body |
lib.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 ... | pub fn set_logger(logger: Box<Logger + Send>) -> Option<Box<Logger + Send>> {
let mut l = Some(logger);
LOCAL_LOGGER.with(|slot| {
mem::replace(&mut *slot.borrow_mut(), l.take())
})
}
/// A LogRecord is created by the logging macros, and passed as the only
/// argument to Loggers.
#[derive(Debug)]
... | random_line_split | |
merge_sort.rs | fn merge(a: Vec<i32>, b: Vec<i32>) -> Vec<i32> {
let mut merged: Vec<i32> = Vec::with_capacity(a.len() + b.len());
let mut ai: usize = 0;
let mut bi: usize = 0;
while ai < a.len() && bi < b.len() {
if a[ai] <= b[bi] {
merged.push(a[ai]);
ai += 1;
}
else |
}
for i in ai..a.len() {
merged.push(a[i]);
}
for i in bi..b.len() {
merged.push(b[i]);
}
merged
}
fn merge_sort(v: Vec<i32>) -> Vec<i32> {
if v.len() <= 1 {
v
}
else {
let mid = v.len() / 2;
let parts = v.split_at(mid);
let a = merge... | {
merged.push(b[bi]);
bi += 1;
} | conditional_block |
merge_sort.rs | fn merge(a: Vec<i32>, b: Vec<i32>) -> Vec<i32> | merged
}
fn merge_sort(v: Vec<i32>) -> Vec<i32> {
if v.len() <= 1 {
v
}
else {
let mid = v.len() / 2;
let parts = v.split_at(mid);
let a = merge_sort(parts.0.to_vec());
let b = merge_sort(parts.1.to_vec());
merge(a, b)
}
}
fn main() {
let a = ve... | {
let mut merged: Vec<i32> = Vec::with_capacity(a.len() + b.len());
let mut ai: usize = 0;
let mut bi: usize = 0;
while ai < a.len() && bi < b.len() {
if a[ai] <= b[bi] {
merged.push(a[ai]);
ai += 1;
}
else {
merged.push(b[bi]);
bi ... | identifier_body |
merge_sort.rs | fn merge(a: Vec<i32>, b: Vec<i32>) -> Vec<i32> {
let mut merged: Vec<i32> = Vec::with_capacity(a.len() + b.len());
let mut ai: usize = 0;
let mut bi: usize = 0;
while ai < a.len() && bi < b.len() {
if a[ai] <= b[bi] {
merged.push(a[ai]);
ai += 1;
}
else {
... | merge_sort(vec![1, 5, 65, 23, 57, 1232, -1, -5, -2, 242, 100, 4, 423, 2, 564, 9, 0, 10, 43, 64, 32, 1, 999]),
vec![-5, -2, -1, 0, 1, 1, 2, 4, 5, 9, 10, 23, 32, 43, 57, 64, 65, 100, 242, 423, 564, 999, 1232]
);
} | random_line_split | |
merge_sort.rs | fn merge(a: Vec<i32>, b: Vec<i32>) -> Vec<i32> {
let mut merged: Vec<i32> = Vec::with_capacity(a.len() + b.len());
let mut ai: usize = 0;
let mut bi: usize = 0;
while ai < a.len() && bi < b.len() {
if a[ai] <= b[bi] {
merged.push(a[ai]);
ai += 1;
}
else {
... | (v: Vec<i32>) -> Vec<i32> {
if v.len() <= 1 {
v
}
else {
let mid = v.len() / 2;
let parts = v.split_at(mid);
let a = merge_sort(parts.0.to_vec());
let b = merge_sort(parts.1.to_vec());
merge(a, b)
}
}
fn main() {
let a = vec![1, 5, 7, 4, 3, 2, 1, 9, 0... | merge_sort | identifier_name |
intrinsic-alignment.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... | () {
unsafe {
assert_eq!(::rusti::pref_align_of::<u64>(), 8u);
assert_eq!(::rusti::min_align_of::<u64>(), 8u);
}
}
}
| main | identifier_name |
intrinsic-alignment.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... | assert_eq!(::rusti::min_align_of::<u64>(), 8u);
}
}
}
#[cfg(target_os = "android")]
mod m {
#[main]
#[cfg(target_arch = "arm")]
pub fn main() {
unsafe {
assert_eq!(::rusti::pref_align_of::<u64>(), 8u);
assert_eq!(::rusti::min_align_of::<u64>(), 8u);
... | pub fn main() {
unsafe {
assert_eq!(::rusti::pref_align_of::<u64>(), 8u); | random_line_split |
intrinsic-alignment.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... |
#[main]
#[cfg(target_arch = "x86_64")]
pub fn main() {
unsafe {
assert_eq!(::rusti::pref_align_of::<u64>(), 8u);
assert_eq!(::rusti::min_align_of::<u64>(), 8u);
}
}
}
#[cfg(target_os = "android")]
mod m {
#[main]
#[cfg(target_arch = "arm")]
pub fn m... | {
unsafe {
assert_eq!(::rusti::pref_align_of::<u64>(), 8u);
assert_eq!(::rusti::min_align_of::<u64>(), 8u);
}
} | identifier_body |
rmm.rs | //! The RMM map files have the following layout
//!
//! [HEADER]
//! String (first byte indicates how long the string is)
//! int map size x
//! int map size y
//! String (first byte indicates how long the string is)
//! int map number
//! int number of events
//!
//! [Event list (Number of events)] = Event clickable l... | let b_7: u32 = cursor.read_u8()? as u32;
assert_eq!(b_0 & 0x2, 0);
let obj_file_num = (b_0 / 4) + (b_1 % 32) * 64;
let tle_file_idx = ((b_2 % 128) * 8) + (b_1 / 32);
let tle_file_num = (b_3 * 2) + (b_2 / 128);
let warp = b_4;
let collision = b_6;
let obj_file_idx = if collision % 24 ==... | let b_4: u32 = cursor.read_u8()? as u32;
let b_5: u32 = cursor.read_u8()? as u32;
let b_6: u32 = cursor.read_u8()? as u32; | random_line_split |
rmm.rs | //! The RMM map files have the following layout
//!
//! [HEADER]
//! String (first byte indicates how long the string is)
//! int map size x
//! int map size y
//! String (first byte indicates how long the string is)
//! int map number
//! int number of events
//!
//! [Event list (Number of events)] = Event clickable l... |
// map size (x, y) in number of tiles
map.set_size_x(cursor.read_u32::<LE>()?);
map.set_size_y(cursor.read_u32::<LE>()?);
// Map name?
map.set_id_count(cursor.read_u8()?);
for idx in 0..(map.id_count()) {
map.add_id_list_val(cursor.read_u8()?);
}
map.name = cp949::cp949_to_utf... | {
// println!("{:?}", file_type);
return Err(Error::MissingMapIdentifier);
} | conditional_block |
rmm.rs | //! The RMM map files have the following layout
//!
//! [HEADER]
//! String (first byte indicates how long the string is)
//! int map size x
//! int map size y
//! String (first byte indicates how long the string is)
//! int map number
//! int number of events
//!
//! [Event list (Number of events)] = Event clickable l... | (b_7 << 1) + 1
};
let tile = MapTile {
obj_rmd_entry: Entry::new(obj_file_num, obj_file_idx),
tle_rmd_entry: Entry::new(tle_file_num, tle_file_idx),
warp,
collision,
};
Ok(tile)
}
// NOTE: This was a test to see if pulling out the bit fields could be made a li... | {
let b_0: u32 = cursor.read_u8()? as u32;
let b_1: u32 = cursor.read_u8()? as u32;
let b_2: u32 = cursor.read_u8()? as u32;
let b_3: u32 = cursor.read_u8()? as u32;
let b_4: u32 = cursor.read_u8()? as u32;
let b_5: u32 = cursor.read_u8()? as u32;
let b_6: u32 = cursor.read_u8()? as u32;
... | identifier_body |
rmm.rs | //! The RMM map files have the following layout
//!
//! [HEADER]
//! String (first byte indicates how long the string is)
//! int map size x
//! int map size y
//! String (first byte indicates how long the string is)
//! int map number
//! int number of events
//!
//! [Event list (Number of events)] = Event clickable l... | (data: &[u8]) -> Result<Map, Error> {
let mut cursor = Cursor::new(data);
let mut map = Map::new();
// filetype string: needs to equal "Redmoon MapData 1.0"
let string_length = cursor.read_u8()?;
let mut string = Vec::<u8>::new();
for _ in 0..string_length {
let chr = cursor.read_u8()?;... | parse_rmm | identifier_name |
insults.rs | ! version = 2.0
// Handling abusive users.
+ int random comeback{weight=100}
- You sound reasonable... time to up the medication.
- I see you've set aside this special time to humiliate yourself in public.
- Ahhh... I see the screw-up fairy has visited us again.
- I don't know what your problem is, but I'll bet it's ... | - I can see your point, but I still think you're full of it.
- What am I? Flypaper for freaks!?
- Any connection between your reality and mine is purely coincidental.
- I'm already visualizing the duct tape over your mouth.
- Your teeth are brighter than you are.
- We're all refreshed and challenged by your unique poin... | - I'm really easy to get along with once you people learn to worship me.
- It sounds like English, but I can't understand a word you're saying. | random_line_split |
insults.rs | ! version = 2.0
// Handling abusive users.
+ int random comeback{weight=100}
- You sound reasonable... time to up the medication.
- I see you've set aside this special time to humiliate yourself in public.
- Ahhh... I see the screw-up fairy has visited us again.
- I don't know what your problem is, but I'll bet it's ... |
- =-O How mean! :-({topic=apology}
- Omg what a jerk!!{topic=apology}
> topic apology
+ *
- <noreply>{weight=10}
- We're fighting.
- Say you're sorry.
- Say you're sorry. Now.
+ sorry
- Okay.. I'll forgive you. :-){topic=random}
- Good, you should be.{topic=random}
- Okay. :-){topic=random}
+ (* sorry|sor... | {weight=100} | conditional_block |
redirect-rename.rs | // Copyright 2016 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 ... | }
// @has foo/struct.FooBar.html
pub use hidden::Foo as FooBar;
// @has foo/baz/index.html
// @has foo/baz/struct.Thing.html
pub use hidden::bar as baz; | pub mod bar {
// @has foo/hidden/bar/struct.Thing.html
// @has - '//p/a' '../../foo/baz/struct.Thing.html'
pub struct Thing {}
} | random_line_split |
redirect-rename.rs | // Copyright 2016 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 ... | {}
}
}
// @has foo/struct.FooBar.html
pub use hidden::Foo as FooBar;
// @has foo/baz/index.html
// @has foo/baz/struct.Thing.html
pub use hidden::bar as baz;
| Thing | identifier_name |
main.rs | use std::fs;
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
use std::thread;
use std::time::Duration;
use web_server::ThreadPool;
fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
let pool = ThreadPool::new(4);
for stream in listener.incoming().take(2... | let (status_line, filename) = if buffer.starts_with(get) {
("HTTP/1.1 200 OK\r\n\r\n", "hello.html")
} else if buffer.starts_with(sleep) {
thread::sleep(Duration::from_secs(5));
("HTTP/1.1 200 OK\r\n\r\n", "hello.html")
} else {
("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html")
... | random_line_split | |
main.rs | use std::fs;
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
use std::thread;
use std::time::Duration;
use web_server::ThreadPool;
fn main() |
fn handle_connection(mut stream: TcpStream) {
let mut buffer = [0; 1024];
stream.read(&mut buffer).unwrap();
let get = b"GET / HTTP/1.1\r\n";
let sleep = b"GET /sleep HTTP/1.1\r\n";
let (status_line, filename) = if buffer.starts_with(get) {
("HTTP/1.1 200 OK\r\n\r\n", "hello.html")
} ... | {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
let pool = ThreadPool::new(4);
for stream in listener.incoming().take(2) {
let stream = stream.unwrap();
pool.execute(|| {
handle_connection(stream);
});
}
println!("Shutting down.")
} | identifier_body |
main.rs | use std::fs;
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
use std::thread;
use std::time::Duration;
use web_server::ThreadPool;
fn | () {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
let pool = ThreadPool::new(4);
for stream in listener.incoming().take(2) {
let stream = stream.unwrap();
pool.execute(|| {
handle_connection(stream);
});
}
println!("Shutting down.")
}
fn handle... | main | identifier_name |
main.rs | use std::fs;
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
use std::thread;
use std::time::Duration;
use web_server::ThreadPool;
fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
let pool = ThreadPool::new(4);
for stream in listener.incoming().take(2... | else {
("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html")
};
let contents = fs::read_to_string(filename).unwrap();
let response = format!("{}{}", status_line, contents);
stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
}
| {
thread::sleep(Duration::from_secs(5));
("HTTP/1.1 200 OK\r\n\r\n", "hello.html")
} | conditional_block |
main.rs | #![deny(warnings)]
#[cfg(feature = "bin")]
extern crate difference;
#[cfg(feature = "bin")]
extern crate getopts;
#[cfg(feature = "bin")]
use getopts::Options;
#[cfg(feature = "bin")]
use std::env;
#[cfg(not(feature = "bin"))]
fn main() {
panic!("Needs to be compiled with --features=bin");
}
#[cfg(feature = "bi... | else {
print!("{}", opts.usage(&format!("Usage: {} [options]", program)));
return;
};
}
| {
let ch = difference::Changeset::new(&matches.free[0], &matches.free[1], split);
println!("{}", ch);
} | conditional_block |
main.rs | #![deny(warnings)]
#[cfg(feature = "bin")]
extern crate difference;
#[cfg(feature = "bin")]
extern crate getopts;
#[cfg(feature = "bin")]
use getopts::Options;
#[cfg(feature = "bin")]
use std::env;
#[cfg(not(feature = "bin"))]
fn | () {
panic!("Needs to be compiled with --features=bin");
}
#[cfg(feature = "bin")]
fn main() {
let args: Vec<String> = env::args().collect();
let program = args[0].clone();
let mut opts = Options::new();
opts.optopt("s", "split", "", "char|word|line");
let matches = match opts.parse(&args[1..]... | main | identifier_name |
main.rs | #![deny(warnings)]
#[cfg(feature = "bin")]
extern crate difference;
#[cfg(feature = "bin")]
extern crate getopts;
#[cfg(feature = "bin")]
use getopts::Options;
#[cfg(feature = "bin")]
use std::env;
#[cfg(not(feature = "bin"))]
fn main() {
panic!("Needs to be compiled with --features=bin");
}
#[cfg(feature = "bi... | opts.optopt("s", "split", "", "char|word|line");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => panic!(f.to_string()),
};
let split = match matches.opt_str("s") {
Some(ref x) if x == "char" => "",
Some(ref x) if x == "word" => " ",
Some(ref x)... |
let mut opts = Options::new(); | random_line_split |
main.rs | #![deny(warnings)]
#[cfg(feature = "bin")]
extern crate difference;
#[cfg(feature = "bin")]
extern crate getopts;
#[cfg(feature = "bin")]
use getopts::Options;
#[cfg(feature = "bin")]
use std::env;
#[cfg(not(feature = "bin"))]
fn main() |
#[cfg(feature = "bin")]
fn main() {
let args: Vec<String> = env::args().collect();
let program = args[0].clone();
let mut opts = Options::new();
opts.optopt("s", "split", "", "char|word|line");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => panic!(f.to_string()... | {
panic!("Needs to be compiled with --features=bin");
} | identifier_body |
mod.rs | //! Platform abstraction
//!
//! This module aims to provide a platform abstraction and interface for
//! the rest of the kernel code. The idea is that an architecture may not
//! assume a specific platform, but platforms may assume a specific
//! architecture if they desire
//!
//! As there can only be one actual plat... |
}
/// Returns the concrete platform implenetation
/// We use this wrapper instead of directly re-exporting `plat_get_platform`
/// to ensure that the return type of `plat_get_platform` adheres to the
/// `PlatInterface` trait
///
/// # Safety
///
/// This function should be called no more than once as the underlying
... | {
for byte in s.bytes() {
self.putchar(byte);
}
Ok(())
} | identifier_body |
mod.rs | //! Platform abstraction
//!
//! This module aims to provide a platform abstraction and interface for
//! the rest of the kernel code. The idea is that an architecture may not
//! assume a specific platform, but platforms may assume a specific
//! architecture if they desire
//!
//! As there can only be one actual plat... | unsafe fn early_init(&mut self) -> Result<(), ()>;
/// Perform device discovery. Takes a window that can provide access
/// to any hardware structures to walk
fn early_device_discovery<'a, W: VSpaceWindow<'a>>(&mut self, window: &'a W) -> Result<(), ()>;
}
impl fmt::Write for PlatInterfaceType {
fn... | /// # Safety
///
/// This function should only be called once, and only during the
/// early bootup phase of the system | random_line_split |
mod.rs | //! Platform abstraction
//!
//! This module aims to provide a platform abstraction and interface for
//! the rest of the kernel code. The idea is that an architecture may not
//! assume a specific platform, but platforms may assume a specific
//! architecture if they desire
//!
//! As there can only be one actual plat... | (config: &BootConfig) -> PlatInterfaceType where PlatInterfaceType: PlatInterface {
plat_get_platform(config)
}
| get_platform | identifier_name |
font_context.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 font::UsedFontStyle;
use platform::font::FontHandle;
use font_context::FontContextHandleMethods;
use platform:... | {
ctx: FT_Library,
}
impl Drop for FreeTypeLibraryHandle {
fn drop(&self) {
assert!(self.ctx.is_not_null());
unsafe {
FT_Done_FreeType(self.ctx);
}
}
}
pub struct FontContextHandle {
ctx: @FreeTypeLibraryHandle,
}
impl FontContextHandle {
pub fn new() -> FontC... | FreeTypeLibraryHandle | identifier_name |
font_context.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 font::UsedFontStyle;
use platform::font::FontHandle;
use font_context::FontContextHandleMethods;
use platform:... |
}
| {
debug!("Creating font handle for %s", name);
do path_from_identifier(name, &style).chain |file_name| {
debug!("Opening font face %s", file_name);
FontHandle::new_from_file(self, file_name, &style)
}
} | identifier_body |
font_context.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 font::UsedFontStyle;
use platform::font::FontHandle;
use font_context::FontContextHandleMethods;
use platform:... |
FontContextHandle {
ctx: @FreeTypeLibraryHandle { ctx: ctx },
}
}
}
}
impl FontContextHandleMethods for FontContextHandle {
fn clone(&self) -> FontContextHandle {
FontContextHandle { ctx: self.ctx }
}
fn create_font_from_identifier(&self, name... | { fail!(); } | conditional_block |
font_context.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 font::UsedFontStyle;
use platform::font::FontHandle;
use font_context::FontContextHandleMethods;
use platform:... | ctx: @FreeTypeLibraryHandle,
}
impl FontContextHandle {
pub fn new() -> FontContextHandle {
unsafe {
let ctx: FT_Library = ptr::null();
let result = FT_Init_FreeType(ptr::to_unsafe_ptr(&ctx));
if!result.succeeded() { fail!(); }
FontContextHandle {
... | pub struct FontContextHandle { | random_line_split |
build.rs | use std::path::Path;
use std::path::PathBuf;
use std::env;
use std::process::Command;
fn | () {
let out_dir = env::var("OUT_DIR").unwrap();
let target = env::var("TARGET").unwrap();
// http://doc.crates.io/build-script.html#inputs-to-the-build-script
// "the build script’s current directory is the source directory of the build script’s package."
let current_dir = env::current_dir().unwra... | main | identifier_name |
build.rs | use std::path::Path;
use std::path::PathBuf;
use std::env;
use std::process::Command;
fn main() | };
println!(" QT_VER: {}", default_qt_ver);
println!(" QT_COMP: {}", default_qt_comp);
let qt_dir_default = home_dir.join("Qt")
.join(env::var("QT_VER").unwrap_or(default_qt_ver))
.join(env::var("QT_COMP").unwrap_or... | {
let out_dir = env::var("OUT_DIR").unwrap();
let target = env::var("TARGET").unwrap();
// http://doc.crates.io/build-script.html#inputs-to-the-build-script
// "the build script’s current directory is the source directory of the build script’s package."
let current_dir = env::current_dir().unwrap()... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.