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 |
|---|---|---|---|---|
htmlpictureelement.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 crate::dom::bindings::codegen::Bindings::HTMLPictureElementBinding;
use crate::dom::bindings::root::DomRoot;
u... | local_name: LocalName,
prefix: Option<Prefix>,
document: &Document,
) -> DomRoot<HTMLPictureElement> {
Node::reflect_node(
Box::new(HTMLPictureElement::new_inherited(
local_name, prefix, document,
)),
document,
HTMLPictu... | random_line_split | |
htmlpictureelement.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 crate::dom::bindings::codegen::Bindings::HTMLPictureElementBinding;
use crate::dom::bindings::root::DomRoot;
u... | (
local_name: LocalName,
prefix: Option<Prefix>,
document: &Document,
) -> DomRoot<HTMLPictureElement> {
Node::reflect_node(
Box::new(HTMLPictureElement::new_inherited(
local_name, prefix, document,
)),
document,
HTMLPic... | new | identifier_name |
vm.rs | -on-write approach for each slot within the save vector. The
// top `nsave` elements in `oldsave` represent the delta from the
// current machine state to the top of stack.
impl State {
fn new(n_saves: usize, max_stack: usize, options: u32) -> State {
State {
saves: vec![usize::MAX; n_saves],
... | arbitrary | identifier_name | |
vm.rs |
pub fn new(body: Vec<Insn>, n_saves: usize) -> Prog {
Prog {
body: body,
n_saves: n_saves,
}
}
pub fn debug_print(&self) {
for (i, insn) in self.body.iter().enumerate() {
println!("{:3}: {:?}", i, insn);
}
}
}
struct State {
pub ... |
// get the count of backtracks
fn backtrack_count(&self) -> usize {
self.stack.len()
}
// discard backtracks since the corresponding call to backtrack_count
fn backtrack_cut(&mut self, count: usize) {
if self.stack.len() == count {
return;
}
let mut old... | {
let explicit_sp = self.explicit_sp;
let sp = self.get(explicit_sp) - 1;
let result = self.get(sp);
self.save(explicit_sp, sp);
result
} | identifier_body |
vm.rs |
pub fn new(body: Vec<Insn>, n_saves: usize) -> Prog {
Prog {
body: body,
n_saves: n_saves,
}
}
pub fn debug_print(&self) {
for (i, insn) in self.body.iter().enumerate() {
println!("{:3}: {:?}", i, insn);
}
}
}
struct State {
pub ... |
state.save(repeat, repcount + 1);
if repcount >= lo {
state.save(check, ix);
state.push(next, ix)?;
}
}
Insn::RepeatEpsilonNg { lo, next, repeat, check } => {
... | {
// prevent zero-length match on repeat
break 'fail;
} | conditional_block |
vm.rs | {
pub fn new(body: Vec<Insn>, n_saves: usize) -> Prog {
Prog {
body: body,
n_saves: n_saves,
}
}
pub fn debug_print(&self) {
for (i, insn) in self.body.iter().enumerate() {
println!("{:3}: {:?}", i, insn);
}
}
}
struct State {
pu... | if repcount >= lo {
state.save(check, ix);
state.push(next, ix)?;
}
}
Insn::RepeatEpsilonNg { lo, next, repeat, check } => {
let repcount = state.get(repeat);
i... | break 'fail;
}
state.save(repeat, repcount + 1); | random_line_split |
crates_io.rs | use std::io::Read;
use std::result;
use serde::Deserialize;
use url::Url;
use crate::errors::*;
#[derive(Clone, Debug)]
pub enum Repository {
GitHub(String),
Other(String),
None,
}
#[derive(Deserialize, Debug)]
pub struct Metadata {
pub id: String,
#[serde(deserialize_with = "deserialize_url")]
pub reposi... | {
let mut buffer = String::new();
let _ = reqwest::Client::new()
.get(&format!("https://crates.io/api/v1/crates/{}", crate_id))
.send()?
.read_to_string(&mut buffer)?;
Ok(json::from_str(&buffer)?)
} | identifier_body | |
crates_io.rs | use std::io::Read;
use std::result;
use serde::Deserialize;
use url::Url;
use crate::errors::*;
#[derive(Clone, Debug)]
pub enum Repository {
GitHub(String),
Other(String),
None,
}
#[derive(Deserialize, Debug)]
pub struct Metadata {
pub id: String,
#[serde(deserialize_with = "deserialize_url")]
pub reposi... | (&self) -> Repository {
self.meta.repository.clone()
}
}
pub fn get(crate_id: &str) -> Result<Crate> {
let mut buffer = String::new();
let _ = reqwest::Client::new()
.get(&format!("https://crates.io/api/v1/crates/{}", crate_id))
.send()?
.read_to_string(&mut buffer)?;
Ok(json::from_str(&buffer)?)... | repository | identifier_name |
crates_io.rs | use std::io::Read;
use std::result;
use serde::Deserialize;
use url::Url;
use crate::errors::*;
#[derive(Clone, Debug)]
pub enum Repository {
GitHub(String),
Other(String),
None,
}
| pub struct Metadata {
pub id: String,
#[serde(deserialize_with = "deserialize_url")]
pub repository: Repository,
}
fn deserialize_url<'de, D: serde::Deserializer<'de>>(
deserializer: D,
) -> result::Result<Repository, D::Error> {
Option::<String>::deserialize(deserializer)
.map(|s| s.unwrap_or("".to_owned... | #[derive(Deserialize, Debug)] | random_line_split |
destructured-for-loop-variable.rs | // min-lldb-version: 310
// This fails on lldb 6.0.1 on x86-64 Fedora 28; so mark it macOS-only
// for now.
// only-macos
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// DESTRUCTURED STRUCT
// gdb-command:print x
// gdb-... | () {()}
| zzz | identifier_name |
destructured-for-loop-variable.rs | // min-lldb-version: 310
// This fails on lldb 6.0.1 on x86-64 Fedora 28; so mark it macOS-only
// for now.
// only-macos
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// DESTRUCTURED STRUCT
// gdb-command:print x
// gdb-... | // lldbg-check:[...]$16 = false
// lldbr-check:(bool) z1 = false
// lldb-command:print *x2
// lldbg-check:[...]$17 = -30000
// lldbr-check:(i16) *x2 = -30000
// lldb-command:print y2
// lldbg-check:[...]$18 = -300001.5
// lldbr-check:(f32) y2 = -300001.5
// lldb-command:print *z2
// lldbg-check:[...]$19 = true
// lldbr... | random_line_split | |
main.rs | use std::collections::HashMap;
use std::error::Error;
use mediawiki::{
api_sync::ApiSync,
};
const CATEGORY_NAMESPACE: &str = "14";
fn ends_in_four_digits(s: &str) -> bool {
s.chars().rev().take(4).all(|c: char| c.is_ascii_digit())
}
fn make_map(params: &[(&str, &str)]) -> HashMap<String, String> {
para... | config
.merge(config::File::with_name("settings"))?
.merge(config::Environment::with_prefix("APP"))?;
let username = config.get_str("username")?;
let password = config.get_str("password")?;
let api_url = config.get_str("api_url")?;
let mut api = ApiSync::new(&api_url)?;
api.login(u... | fn main() -> Result<(), Box<dyn Error>> {
let mut config = config::Config::default(); | random_line_split |
main.rs | use std::collections::HashMap;
use std::error::Error;
use mediawiki::{
api_sync::ApiSync,
};
const CATEGORY_NAMESPACE: &str = "14";
fn ends_in_four_digits(s: &str) -> bool {
s.chars().rev().take(4).all(|c: char| c.is_ascii_digit())
}
fn make_map(params: &[(&str, &str)]) -> HashMap<String, String> {
para... | ("prop", "categoryinfo"),
("formatversion", "2"),
("format", "json"),
]), /* limit */ None) {
let x = format!("{:?}", subcats_page);
for subcat in subcats_page?["query"]["pages"].as_array().ok_or(format!("subcats_page.query.pag... | {
// can't use u64 because sometimes the API returns negative numbers for these values (????)
let mut total =
make_nonnegative(categoryinfo["pages"].as_i64().ok_or(format!(
"categoryinfo.pages '{}' '{:?}' '{:?}'",
category_title, categoryinfo["pages"], categoryinfo
))?) +... | identifier_body |
main.rs | use std::collections::HashMap;
use std::error::Error;
use mediawiki::{
api_sync::ApiSync,
};
const CATEGORY_NAMESPACE: &str = "14";
fn ends_in_four_digits(s: &str) -> bool {
s.chars().rev().take(4).all(|c: char| c.is_ascii_digit())
}
fn make_map(params: &[(&str, &str)]) -> HashMap<String, String> {
para... | () -> Result<(), Box<dyn Error>> {
let mut config = config::Config::default();
config
.merge(config::File::with_name("settings"))?
.merge(config::Environment::with_prefix("APP"))?;
let username = config.get_str("username")?;
let password = config.get_str("password")?;
let api_url = con... | main | identifier_name |
main.rs | use std::collections::HashMap;
use std::error::Error;
use mediawiki::{
api_sync::ApiSync,
};
const CATEGORY_NAMESPACE: &str = "14";
fn ends_in_four_digits(s: &str) -> bool {
s.chars().rev().take(4).all(|c: char| c.is_ascii_digit())
}
fn make_map(params: &[(&str, &str)]) -> HashMap<String, String> {
para... |
}
/// recursively get total category size given title and categoryinfo
fn size(api: &ApiSync, category_title: &str, categoryinfo: &serde_json::Value, never_recurse: bool) -> Result<u64, Box<dyn Error>> {
// can't use u64 because sometimes the API returns negative numbers for these values (????)
let mut total ... | {
i as u64
} | conditional_block |
utils.rs | // Lumol, an extensible molecular simulation engine
// Copyright (C) Lumol's contributors — BSD license
//! Module for small utility structs
/// Helper struct that can wrap an algorithm to make
/// it run only a fraction of the times it is called.
///
/// # Example
///
/// ```
/// use lumol_core::sim::Alternator;
///... | mut self) -> &mut T {
&mut self.base
}
}
| _mut(& | identifier_name |
utils.rs | // Lumol, an extensible molecular simulation engine
// Copyright (C) Lumol's contributors — BSD license
//! Module for small utility structs
/// Helper struct that can wrap an algorithm to make
/// it run only a fraction of the times it is called.
///
/// # Example
///
/// ```
/// use lumol_core::sim::Alternator;
///... |
impl<T> AsRef<T> for Alternator<T> {
/// Access the base algorithm as a reference.
fn as_ref(&self) -> &T {
&self.base
}
}
impl<T> AsMut<T> for Alternator<T> {
/// Access the base algorithm as a mutable reference.
fn as_mut(&mut self) -> &mut T {
&mut self.base
}
}
| self.count += 1;
self.count % self.every == 0
}
} | identifier_body |
utils.rs | // Lumol, an extensible molecular simulation engine |
//! Module for small utility structs
/// Helper struct that can wrap an algorithm to make
/// it run only a fraction of the times it is called.
///
/// # Example
///
/// ```
/// use lumol_core::sim::Alternator;
///
/// struct HelloWorld;
///
/// trait SaySomething {
/// fn say_something(&mut self) -> &'static str... | // Copyright (C) Lumol's contributors — BSD license | random_line_split |
mod.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
//! SPDM protocol messages.
use crate::io::Read;
use crate::io::ReadInt as _;
use crate::io::Write;
use crate::protocol::wire;
pub mod get_version;
pub use get_versio... |
}
| {
let v1 = Version::MANTICORE;
let v2 = Version::new(0x1f, 0x1e);
let v3 = ExtendedVersion::new(v1, 5, 6);
assert_eq!(v1.major(), 1);
assert_eq!(v1.minor(), 2);
assert_eq!(v2.major(), 15);
assert_eq!(v2.minor(), 14);
assert_eq!(v3.version(), v1);
a... | identifier_body |
mod.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
//! SPDM protocol messages.
use crate::io::Read;
use crate::io::ReadInt as _;
use crate::io::Write;
use crate::protocol::wire;
pub mod get_version;
pub use get_versio... | Ok(())
}
fn write_zeros(w: &mut impl Write, count: usize) -> Result<(), wire::Error> {
for _ in 0..count {
w.write_le(0u8)?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use zerocopy::AsBytes as _;
#[test]
fn version_byte_values() {
let v1 = Version::MANTICORE;
... | }
} | random_line_split |
mod.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
//! SPDM protocol messages.
use crate::io::Read;
use crate::io::ReadInt as _;
use crate::io::Write;
use crate::protocol::wire;
pub mod get_version;
pub use get_versio... | (version: u8) -> Self {
Self { version }
}
}
/// An extended SPDM protocol version, consiting of a [`Version`] plus revision
/// and alpha nybbles.
#[derive(
Clone,
Copy,
PartialEq,
Eq,
PartialOrd,
Ord,
Hash,
Debug,
zerocopy::FromBytes,
zerocopy::AsBytes,
)]
#[cfg_at... | from | identifier_name |
mod.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
//! SPDM protocol messages.
use crate::io::Read;
use crate::io::ReadInt as _;
use crate::io::Write;
use crate::protocol::wire;
pub mod get_version;
pub use get_versio... |
}
Ok(())
}
fn write_zeros(w: &mut impl Write, count: usize) -> Result<(), wire::Error> {
for _ in 0..count {
w.write_le(0u8)?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use zerocopy::AsBytes as _;
#[test]
fn version_byte_values() {
let v1 = Version::MANTIC... | {
return Err(wire::Error::OutOfRange);
} | conditional_block |
test_region_info_accessor.rs | // Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0.
use keys::data_end_key;
use kvproto::metapb::Region;
use raft::StateRole;
use raftstore::coprocessor::{RegionInfo, RegionInfoAccessor};
use raftstore::store::util::{find_peer, new_peer};
use std::sync::mpsc::channel;
use std::sync::Arc;
use std::thread... |
fn test_region_info_accessor_impl(cluster: &mut Cluster<NodeCluster>, c: &RegionInfoAccessor) {
for i in 0..9 {
let k = format!("k{}", i).into_bytes();
let v = format!("v{}", i).into_bytes();
cluster.must_put(&k, &v);
}
let pd_client = Arc::clone(&cluster.pd_client);
let init... | {
assert_eq!(regions.len(), ranges.len());
regions
.iter()
.zip(ranges.iter())
.for_each(|((r, _), (start_key, end_key))| {
assert_eq!(r.get_start_key(), *start_key);
assert_eq!(r.get_end_key(), *end_key);
})
} | identifier_body |
test_region_info_accessor.rs | // Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0.
use keys::data_end_key;
use kvproto::metapb::Region;
use raft::StateRole;
use raftstore::coprocessor::{RegionInfo, RegionInfoAccessor};
use raftstore::store::util::{find_peer, new_peer};
use std::sync::mpsc::channel;
use std::sync::Arc;
use std::thread... | check_region_ranges(
&merge_regions,
&[
(&b""[..], &b"k1"[..]),
(b"k1", b"k3"),
(b"k3", b"k4"),
(b"k4", b""),
],
);
// Merge from right to left
pd_client.must_merge(merge_regions[2].0.get_id(), merge_regions[1].0.get_id());
let... | random_line_split | |
test_region_info_accessor.rs | // Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0.
use keys::data_end_key;
use kvproto::metapb::Region;
use raft::StateRole;
use raftstore::coprocessor::{RegionInfo, RegionInfoAccessor};
use raftstore::store::util::{find_peer, new_peer};
use std::sync::mpsc::channel;
use std::sync::Arc;
use std::thread... | () {
let mut cluster = new_node_cluster(1, 3);
configure_for_merge(&mut cluster);
let pd_client = Arc::clone(&cluster.pd_client);
pd_client.disable_default_operator();
// Create a RegionInfoAccessor on node 1
let (tx, rx) = channel();
cluster
.sim
.wl()
.post_create_co... | test_node_cluster_region_info_accessor | identifier_name |
test_region_info_accessor.rs | // Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0.
use keys::data_end_key;
use kvproto::metapb::Region;
use raft::StateRole;
use raftstore::coprocessor::{RegionInfo, RegionInfoAccessor};
use raftstore::store::util::{find_peer, new_peer};
use std::sync::mpsc::channel;
use std::sync::Arc;
use std::thread... |
}
// Merge from left to right
pd_client.must_merge(split_regions[1].0.get_id(), split_regions[2].0.get_id());
let merge_regions = dump(&c);
check_region_ranges(
&merge_regions,
&[
(&b""[..], &b"k1"[..]),
(b"k1", b"k3"),
(b"k3", b"k4"),
... | {
assert_ne!(
region.get_region_epoch(),
init_regions[0].0.get_region_epoch()
);
} | conditional_block |
proxyhandler.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/. */
//! Utilities for the implementation of JSAPI proxy handlers.
#![deny(missing_docs)]
use dom::bindings::conversi... | (obj: HandleObject) -> *mut JSObject {
unsafe {
assert!(is_dom_proxy(obj.get()));
let val = GetProxyExtra(obj.get(), JSPROXYSLOT_EXPANDO);
if val.is_undefined() {
ptr::null_mut()
} else {
val.to_object()
}
}
}
/// Get the expando object, or create... | get_expando_object | identifier_name |
proxyhandler.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/. */
//! Utilities for the implementation of JSAPI proxy handlers.
#![deny(missing_docs)]
use dom::bindings::conversi... |
/// Set the property descriptor's object to `obj` and set it to enumerable,
/// and writable if `readonly` is true.
pub fn fill_property_descriptor(desc: &mut PropertyDescriptor,
obj: *mut JSObject,
attrs: u32) {
desc.obj = obj;
desc.attrs = attr... | {
unsafe {
assert!(is_dom_proxy(obj.get()));
let mut expando = get_expando_object(obj);
if expando.is_null() {
expando = JS_NewObjectWithGivenProto(cx, ptr::null_mut(), HandleObject::null());
assert!(!expando.is_null());
SetProxyExtra(obj.get(), JSPROXYSL... | identifier_body |
proxyhandler.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/. */
//! Utilities for the implementation of JSAPI proxy handlers.
#![deny(missing_docs)]
use dom::bindings::conversi... | else {
val.to_object()
}
}
}
/// Get the expando object, or create it if it doesn't exist yet.
/// Fails on JSAPI failure.
pub fn ensure_expando_object(cx: *mut JSContext, obj: HandleObject) -> *mut JSObject {
unsafe {
assert!(is_dom_proxy(obj.get()));
let mut expando = get... | {
ptr::null_mut()
} | conditional_block |
proxyhandler.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/. */
//! Utilities for the implementation of JSAPI proxy handlers.
#![deny(missing_docs)]
use dom::bindings::conversi... | id: HandleId,
desc: MutableHandle<PropertyDescriptor>)
-> bool {
let handler = GetProxyHandler(proxy.get());
if!InvokeGetOwnPropertyDescriptor(handler, cx, proxy, id... | /// with argument `id` and return the result, if it is not `undefined`.
/// Otherwise, walk along the prototype chain to find a property with that
/// name.
pub unsafe extern "C" fn get_property_descriptor(cx: *mut JSContext,
proxy: HandleObject, | random_line_split |
pinned_events.rs | //! Types for the [`m.room.pinned_events`] event.
//!
//! [`m.room.pinned_events`]: https://spec.matrix.org/v1.2/client-server-api/#mroompinned_events
use ruma_macros::EventContent;
use serde::{Deserialize, Serialize};
use crate::EventId; | ///
/// Used to "pin" particular events in a room for other participants to review later.
#[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
#[ruma_event(type = "m.room.pinned_events", kind = State)]
pub struct RoomPinnedEventsEventConte... |
/// The content of an `m.room.pinned_events` event. | random_line_split |
pinned_events.rs | //! Types for the [`m.room.pinned_events`] event.
//!
//! [`m.room.pinned_events`]: https://spec.matrix.org/v1.2/client-server-api/#mroompinned_events
use ruma_macros::EventContent;
use serde::{Deserialize, Serialize};
use crate::EventId;
/// The content of an `m.room.pinned_events` event.
///
/// Used to "pin" part... | (pinned: Vec<Box<EventId>>) -> Self {
Self { pinned }
}
}
#[cfg(all(test, feature = "rand"))]
mod tests {
use std::convert::TryInto;
use crate::{server_name, EventId, MilliSecondsSinceUnixEpoch, RoomId, UserId};
use super::RoomPinnedEventsEventContent;
use crate::events::{StateEvent, Unsi... | new | identifier_name |
clients.rs | #![feature(proc_macro, plugin, custom_attribute, custom_derive, plugin)]
#![plugin(serde_derive)]
extern crate tin_can_telephone as tct;
use std::net::{TcpStream as StdTcpStream, SocketAddr};
use std::io::{
//Read,
Write};
#[test]
fn | () {
let addr = "127.0.0.1:3000".to_string().parse::<SocketAddr>().unwrap();
let mut tcp_a = match StdTcpStream::connect(&addr) {
Ok(stream) => stream,
Err(_) => panic!("Error, server not available, \
try running 'cargo run --example server'"),
};
let mut tcp_b... | login | identifier_name |
clients.rs | #![feature(proc_macro, plugin, custom_attribute, custom_derive, plugin)]
#![plugin(serde_derive)]
extern crate tin_can_telephone as tct;
use std::net::{TcpStream as StdTcpStream, SocketAddr};
use std::io::{
//Read,
Write};
#[test]
fn login() | tcp_b.write(login_b).unwrap();
tcp_b.flush().unwrap();
println!("Verify logins via server log, this point means succesful connection");
}
| {
let addr = "127.0.0.1:3000".to_string().parse::<SocketAddr>().unwrap();
let mut tcp_a = match StdTcpStream::connect(&addr) {
Ok(stream) => stream,
Err(_) => panic!("Error, server not available, \
try running 'cargo run --example server'"),
};
let mut tcp_b = ... | identifier_body |
clients.rs | #![feature(proc_macro, plugin, custom_attribute, custom_derive, plugin)]
#![plugin(serde_derive)]
extern crate tin_can_telephone as tct;
use std::net::{TcpStream as StdTcpStream, SocketAddr};
use std::io::{
//Read,
Write};
#[test]
fn login() {
let addr = "127.0.0.1:3000".to_string().parse::<SocketAddr>(... | tcp_b.write(login_b).unwrap();
tcp_b.flush().unwrap();
println!("Verify logins via server log, this point means succesful connection");
} | let login_a = "\"LoginCredentials\"{\"user\":\"login_a\"}\n".as_bytes();
let login_b = "\"LoginCredentials\"{\"user\":\"login_b\"}\n".as_bytes();
tcp_a.write(login_a).unwrap();
tcp_a.flush().unwrap(); | random_line_split |
swarm_config.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use anyhow::Result;
use diem_config::config::NodeConfig;
use diem_crypto::ed25519::Ed25519PrivateKey;
use diem_types::waypoint::Waypoint;
use std::{fs::File, io::Write, path::PathBuf};
pub trait BuildSwarm {
/// Generate the config... | <T: BuildSwarm>(config_builder: &T, output_dir: &PathBuf) -> Result<Self> {
let (mut configs, diem_root_key) = config_builder.build_swarm()?;
let mut config_files = vec![];
for (index, config) in configs.iter_mut().enumerate() {
let node_dir = output_dir.join(index.to_string());
... | build | identifier_name |
swarm_config.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use anyhow::Result;
use diem_config::config::NodeConfig;
use diem_crypto::ed25519::Ed25519PrivateKey;
use diem_types::waypoint::Waypoint;
use std::{fs::File, io::Write, path::PathBuf};
pub trait BuildSwarm {
/// Generate the config... | key_file.write_all(&serialized_keys)?;
Ok(SwarmConfig {
config_files,
diem_root_key_path,
waypoint: configs[0].base.waypoint.waypoint(),
})
}
} |
let diem_root_key_path = output_dir.join("mint.key");
let serialized_keys = bcs::to_bytes(&diem_root_key)?;
let mut key_file = File::create(&diem_root_key_path)?; | random_line_split |
thread_local.rs | // Copyright 2014-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-MI... | target_os = "freebsd",
target_os = "dragonfly",
target_os = "bitrig",
target_os = "netbsd",
target_os = "openbsd")))]
type pthread_key_t = ::libc::c_uint;
extern {
fn pthread_key_create(key: *mut pthread_key_t,
dtor: Op... | type pthread_key_t = ::libc::c_int;
#[cfg(not(any(target_os = "macos",
target_os = "ios", | random_line_split |
thread_local.rs | // Copyright 2014-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-MI... | (key: Key) -> *mut u8 {
pthread_getspecific(key)
}
#[inline]
pub unsafe fn destroy(key: Key) {
let r = pthread_key_delete(key);
debug_assert_eq!(r, 0);
}
#[cfg(any(target_os = "macos",
target_os = "ios"))]
type pthread_key_t = ::libc::c_ulong;
#[cfg(any(target_os = "freebsd",
target_o... | get | identifier_name |
thread_local.rs | // Copyright 2014-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-MI... |
#[inline]
pub unsafe fn set(key: Key, value: *mut u8) {
let r = pthread_setspecific(key, value);
debug_assert_eq!(r, 0);
}
#[inline]
pub unsafe fn get(key: Key) -> *mut u8 {
pthread_getspecific(key)
}
#[inline]
pub unsafe fn destroy(key: Key) {
let r = pthread_key_delete(key);
debug_assert_eq!(r... | {
let mut key = 0;
assert_eq!(pthread_key_create(&mut key, dtor), 0);
key
} | identifier_body |
cargo_generate_lockfile.rs | use core::PackageId;
use core::registry::PackageRegistry;
use core::{Source, Resolve};
use core::resolver::Method;
use ops;
use sources::{PathSource};
use util::config::{Config};
use util::{CargoResult, human};
pub struct UpdateOptions<'a, 'b: 'a> {
pub config: &'a Config<'b>,
pub to_update: Option<&'a str>,
... | use std::collections::HashSet;
use std::path::Path;
| random_line_split | |
cargo_generate_lockfile.rs | use std::collections::HashSet;
use std::path::Path;
use core::PackageId;
use core::registry::PackageRegistry;
use core::{Source, Resolve};
use core::resolver::Method;
use ops;
use sources::{PathSource};
use util::config::{Config};
use util::{CargoResult, human};
pub struct UpdateOptions<'a, 'b: 'a> {
pub config: ... |
pub fn update_lockfile(manifest_path: &Path,
opts: &UpdateOptions) -> CargoResult<()> {
let mut source = try!(PathSource::for_path(manifest_path.parent().unwrap(),
opts.config));
try!(source.update());
let package = try!(source.root_pac... | {
let mut source = try!(PathSource::for_path(manifest_path.parent().unwrap(),
config));
try!(source.update());
let package = try!(source.root_package());
let mut registry = PackageRegistry::new(config);
let resolve = try!(ops::resolve_with_previous(&mut... | identifier_body |
cargo_generate_lockfile.rs | use std::collections::HashSet;
use std::path::Path;
use core::PackageId;
use core::registry::PackageRegistry;
use core::{Source, Resolve};
use core::resolver::Method;
use ops;
use sources::{PathSource};
use util::config::{Config};
use util::{CargoResult, human};
pub struct UpdateOptions<'a, 'b: 'a> {
pub config: ... | }
None => {}
}
}
}
None => to_avoid.extend(previous_resolve.iter()),
}
let resolve = try!(ops::resolve_with_previous(&mut registry,
&package,
... | {
let dep = try!(previous_resolve.query(name));
if opts.aggressive {
fill_with_deps(&previous_resolve, dep, &mut to_avoid,
&mut HashSet::new());
} else {
to_avoid.insert(dep);
match opts.precise {
... | conditional_block |
cargo_generate_lockfile.rs | use std::collections::HashSet;
use std::path::Path;
use core::PackageId;
use core::registry::PackageRegistry;
use core::{Source, Resolve};
use core::resolver::Method;
use ops;
use sources::{PathSource};
use util::config::{Config};
use util::{CargoResult, human};
pub struct UpdateOptions<'a, 'b: 'a> {
pub config: ... | <'a>(resolve: &'a Resolve, dep: &'a PackageId,
set: &mut HashSet<&'a PackageId>,
visited: &mut HashSet<&'a PackageId>) {
if!visited.insert(dep) { return }
set.insert(dep);
match resolve.deps(dep) {
Some(deps) => {
fo... | fill_with_deps | identifier_name |
future.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 ... |
#[test]
pub fn test_sendable_future() {
let expected = ~"schlorf";
let f = do spawn { copy expected };
do task::spawn || {
let actual = f.get();
assert!(actual == expected);
}
}
} | #[ignore(cfg(target_os = "win32"))]
pub fn test_futurefail() {
let f = spawn(|| fail!());
let _x: ~str = f.get();
} | random_line_split |
future.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 ... |
pub fn from_fn<A>(f: ~fn() -> A) -> Future<A> {
/*!
* Create a future from a function.
*
* The first time that the value is requested it will be retreived by
* calling the function. Note that this function is a local
* function. It is not spawned into another task.
*/
Future {s... | {
/*!
* Create a future from a port
*
* The first time that the value is requested the task will block
* waiting for the result to be received on the port.
*/
let port = Cell(port);
do from_fn || {
let port = port.take();
match recv(port) {
oneshot::send... | identifier_body |
future.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 ... | (&self) -> &'self A {
/*!
* Executes the future's closure and then returns a borrowed
* pointer to the result. The borrowed pointer lasts as long as
* the future.
*/
unsafe {
match self.state {
Forced(ref mut v) => { return cast::transmute(v);... | get_ref | identifier_name |
data_loader.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/. */
extern crate hyper;
use ipc_channel::ipc; | use net_traits::{LoadData, LoadContext, NetworkError, LoadOrigin};
use self::hyper::header::ContentType;
use self::hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value};
use url::Url;
struct DataLoadTest;
impl LoadOrigin for DataLoadTest {
fn referrer_url(&self) -> Option<Url> {
None
}
fn referrer_... | use msg::constellation_msg::{PipelineId, ReferrerPolicy};
use net_traits::LoadConsumer::Channel;
use net_traits::ProgressMsg::{Payload, Done}; | random_line_split |
data_loader.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/. */
extern crate hyper;
use ipc_channel::ipc;
use msg::constellation_msg::{PipelineId, ReferrerPolicy};
use net_trait... |
#[test]
fn plain_charset() {
assert_parse("data:text/plain;charset=latin1,hello",
Some(ContentType(Mime(TopLevel::Text,
SubLevel::Plain,
vec!((Attr::Charset, Value::Ext("latin1".to_owned())))))),
Some("latin1".to_owned()), Some(b"hello".i... | {
assert_parse(
"data:text/plain,hello",
Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec!()))),
None,
Some(b"hello".iter().map(|&x| x).collect()));
} | identifier_body |
data_loader.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/. */
extern crate hyper;
use ipc_channel::ipc;
use msg::constellation_msg::{PipelineId, ReferrerPolicy};
use net_trait... |
}
}
#[test]
fn empty_invalid() {
assert_parse("data:", None, None, None);
}
#[test]
fn plain() {
assert_parse(
"data:,hello%20world",
Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain,
vec!((Attr::Charset, Value::Ext("us-ascii".to_owned())))))),
S... | {
assert_eq!(progress, Payload(dat));
assert_eq!(response.progress_port.recv().unwrap(), Done(Ok(())));
} | conditional_block |
data_loader.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/. */
extern crate hyper;
use ipc_channel::ipc;
use msg::constellation_msg::{PipelineId, ReferrerPolicy};
use net_trait... | () {
assert_parse("data:text/plain;charset=koi8-r;base64,8PLl9+XkIO3l5Pfl5A==",
Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain,
vec!((Attr::Charset, Value::Ext("koi8-r".to_owned())))))),
Some("koi8-r".to_owned()),
Some(vec!(0xF0, 0xF2, 0xE5, 0xF7, 0xE5, 0... | base64_charset | identifier_name |
list_box_row.rs | // This file was generated by gir (b7f5189) from gir-files (71d73f0)
// DO NOT EDIT
use Bin;
use Container;
use Widget;
use ffi;
use glib::object::Downcast;
use glib::object::IsA;
use glib::signal::connect;
use glib::translate::*;
use glib_ffi;
use std::boxed::Box as Box_;
use std::mem::transmute;
glib_wrapper! {
... |
#[cfg(feature = "v3_10")]
pub fn get_index(&self) -> i32 {
unsafe {
ffi::gtk_list_box_row_get_index(self.to_glib_none().0)
}
}
#[cfg(feature = "v3_14")]
pub fn get_selectable(&self) -> bool {
unsafe {
from_glib(ffi::gtk_list_box_row_get_selectable(s... | {
unsafe {
from_glib_none(ffi::gtk_list_box_row_get_header(self.to_glib_none().0))
}
} | identifier_body |
list_box_row.rs | // This file was generated by gir (b7f5189) from gir-files (71d73f0)
// DO NOT EDIT | use ffi;
use glib::object::Downcast;
use glib::object::IsA;
use glib::signal::connect;
use glib::translate::*;
use glib_ffi;
use std::boxed::Box as Box_;
use std::mem::transmute;
glib_wrapper! {
pub struct ListBoxRow(Object<ffi::GtkListBoxRow>): Bin, Container, Widget;
match fn {
get_type => || ffi::g... |
use Bin;
use Container;
use Widget; | random_line_split |
list_box_row.rs | // This file was generated by gir (b7f5189) from gir-files (71d73f0)
// DO NOT EDIT
use Bin;
use Container;
use Widget;
use ffi;
use glib::object::Downcast;
use glib::object::IsA;
use glib::signal::connect;
use glib::translate::*;
use glib_ffi;
use std::boxed::Box as Box_;
use std::mem::transmute;
glib_wrapper! {
... | (&self) {
unsafe {
ffi::gtk_list_box_row_changed(self.to_glib_none().0);
}
}
#[cfg(feature = "v3_14")]
pub fn get_activatable(&self) -> bool {
unsafe {
from_glib(ffi::gtk_list_box_row_get_activatable(self.to_glib_none().0))
}
}
#[cfg(feature ... | changed | identifier_name |
dependency_format.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 ... | (tcx: &ty::ctxt) {
let mut fmts = tcx.dependency_formats.borrow_mut();
for &ty in tcx.sess.crate_types.borrow().iter() {
fmts.insert(ty, calculate_type(&tcx.sess, ty));
}
tcx.sess.abort_if_errors();
}
fn calculate_type(sess: &session::Session,
ty: config::CrateType) -> Depende... | calculate | identifier_name |
dependency_format.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 ... | link: cstore::LinkagePreference,
m: &mut FnvHashMap<ast::CrateNum, cstore::LinkagePreference>) {
match m.get(&cnum) {
Some(&link2) => {
// If the linkages differ, then we'd have two copies of the library
// if we continued linking. If the linkages are bo... | }
fn add_library(sess: &session::Session,
cnum: ast::CrateNum, | random_line_split |
dependency_format.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 ... | None => {}
}
sess.cstore.iter_crate_data(|cnum, data| {
let src = sess.cstore.get_used_crate_source(cnum).unwrap();
if src.rlib.is_some() { return }
sess.err(&format!("dependency `{}` not found in rlib format",
... | {
match ty {
// If the global prefer_dynamic switch is turned off, first attempt
// static linkage (this can fail).
config::CrateTypeExecutable if !sess.opts.cg.prefer_dynamic => {
match attempt_static(sess) {
Some(v) => return v,
None => {}
... | identifier_body |
middleware.rs | /// Macro to reduce the boilerplate required for using unboxed
/// closures as `Middleware` due to current type inference behaviour.
///
/// In future, the macro should hopefully be able to be removed while
/// having minimal changes to the closure's code. | /// # #[macro_use] extern crate nickel;
/// # fn main() {
/// use nickel::{Nickel, HttpRouter};
/// use std::sync::atomic::{AtomicUsize, Ordering};
///
/// let mut server = Nickel::new();
///
/// // Some shared resource between requests, must be `Sync + Send`
/// let visits = AtomicUsize::new(0);
///
/// server.get("/"... | ///
/// # Examples
/// ```rust,no_run | random_line_split |
events.rs | // extern crate sdl2;
macro_rules! struct_events {
(
keyboard: { $( $k_alias:ident : $k_sdl:ident ),* },
// match against a pattern
else: { $( $e_alias:ident : $e_sdl:pat ),* }
) => {
use sdl2::EventPump;
pub struct ImmediateEvents {
// for every keyboard e... | // when initialized, nothing has happened yet, so all are
// set to None
$( $k_alias: None, )*
$( $e_alias: false ),*,
resize: None
}
}
}
pub struct Events {
pump:... | ImmediateEvents { | random_line_split |
iterator.rs | fn main() {
println!(">迭代器测试样例<");
let mut v = vec![1, 2, 3, 4, 5];
let v_len = v.len();
println!("v.len() = {}", v_len);
for i in &v {
println!("A reference to {}", i);
}
for i in &mut v {
println!("A mutable reference to {}", i);
}
for i in 0.. v_len {
... |
//let nums = vec![1, 2, 3];
let nums = (1..10).collect::<Vec<i32>>();;
for i in 0.. nums.len() {
println!("nums[{}] = {}", i, nums[i]);
}
for num in &nums {
println!("value: {}", num);
}
let items = [1, 2, 3];
for item in items.iter() {
println!("items->item: ... | for x in 10 .. 20 {
println!(" -> {}", x);
} | random_line_split |
iterator.rs | fn | () {
println!(">迭代器测试样例<");
let mut v = vec![1, 2, 3, 4, 5];
let v_len = v.len();
println!("v.len() = {}", v_len);
for i in &v {
println!("A reference to {}", i);
}
for i in &mut v {
println!("A mutable reference to {}", i);
}
for i in 0.. v_len {
println... | main | identifier_name |
iterator.rs | fn main() {
println!(">迭代器测试样例<");
let mut v = vec![1, 2, 3, 4, 5];
let v_len = v.len();
println!("v.len() = {}", v_len);
for i in &v {
println!("A reference to {}", i);
}
for i in &mut v {
println!("A mutable reference to {}", i);
}
for i in 0.. v_len {
... | > {}", x);
}
//let nums = vec![1, 2, 3];
let nums = (1..10).collect::<Vec<i32>>();;
for i in 0.. nums.len() {
println!("nums[{}] = {}", i, nums[i]);
}
for num in &nums {
println!("value: {}", num);
}
let items = [1, 2, 3];
for item in items.iter() {
printl... | ln!(" - | conditional_block |
iterator.rs | fn main() | // 以下代码会影响 v 的作用域,上面3行代码放到 i in v 块后,编译不过.
for i in v {
println!("Take ownership of the vector and its element {}", i);
}
let mut range = 0.. 10;
loop {
match range.next() {
Some(x) => {
println!("current is: {}", x);
},
None ... | {
println!(">迭代器测试样例<");
let mut v = vec![1, 2, 3, 4, 5];
let v_len = v.len();
println!("v.len() = {}", v_len);
for i in &v {
println!("A reference to {}", i);
}
for i in &mut v {
println!("A mutable reference to {}", i);
}
for i in 0 .. v_len {
println!(... | identifier_body |
mod.rs | // The MIT License (MIT)
//
// Copyright (c) 2015 Vladislav Orlov
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use,... |
}
| {
let val = context.get(&self.var_name);
let mut cur_val = match val {
Some(content) => Some(content.clone_box()),
None => None,
};
for filter in self.filters.iter() {
cur_val = filter.apply(cur_val);
}
cur_val
} | identifier_body |
mod.rs | // The MIT License (MIT)
//
// Copyright (c) 2015 Vladislav Orlov
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use,... | (expr: &str, storage: &HashMap<String, FilterFunction>) -> Result<FilterExpression> {
let mut expr_splitter = expr.trim().split('|');
let var_name = expr_splitter.next().unwrap().to_string();
let mut filters = Vec::new();
for filter_expr in expr_splitter {
let filter = try!(FilterNode::from_ex... | new | identifier_name |
mod.rs | // of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnis... | // The MIT License (MIT)
//
// Copyright (c) 2015 Vladislav Orlov
//
// Permission is hereby granted, free of charge, to any person obtaining a copy | random_line_split | |
project_json.rs | use rustc_serialize::json;
use fuse::{FileType, ReplyAttr, ReplyData, ReplyEntry, Request};
use fs::constants;
use fs::GoodDataFS;
use fs::helpers::create_inode_file_attributes;
use fs::inode;
use fs::item;
use helpers;
use object;
use super::project_from_inode;
use std::path::Path;
fn getattr(fs: &mut GoodDataFS,... | (fs: &mut GoodDataFS, _req: &Request, parent: u64, _name: &Path, reply: ReplyEntry) {
let inode_parent = inode::Inode::deserialize(parent);
let inode = inode::Inode::serialize(&inode::Inode {
project: inode_parent.project,
category: constants::Category::Internal as u8,
item: 0,
r... | lookup | identifier_name |
project_json.rs | use rustc_serialize::json;
use fuse::{FileType, ReplyAttr, ReplyData, ReplyEntry, Request};
use fs::constants;
use fs::GoodDataFS;
use fs::helpers::create_inode_file_attributes;
use fs::inode;
use fs::item;
use helpers;
use object;
use super::project_from_inode;
use std::path::Path;
fn getattr(fs: &mut GoodDataFS,... |
fn read(fs: &mut GoodDataFS, inode: inode::Inode, reply: ReplyData, offset: u64, size: u32) {
info!("read() - Reading {}", constants::PROJECT_JSON_FILENAME);
let project: &object::Project = &project_from_inode(fs, inode);
let json = json::as_pretty_json(project).to_string();
reply.data(helpers::read_... | {
let project: &object::Project = &project_from_inode(fs, ino);
let json = json::as_pretty_json(project).to_string();
let attr = create_inode_file_attributes(ino, json.len() as u64, constants::DEFAULT_CREATE_TIME);
reply.attr(&constants::DEFAULT_TTL, &attr);
} | identifier_body |
project_json.rs | use rustc_serialize::json;
use fuse::{FileType, ReplyAttr, ReplyData, ReplyEntry, Request};
use fs::constants;
use fs::GoodDataFS;
use fs::helpers::create_inode_file_attributes;
use fs::inode;
use fs::item;
use helpers;
use object;
use super::project_from_inode;
use std::path::Path;
fn getattr(fs: &mut GoodDataFS,... | reply.data(helpers::read_bytes(&json, offset, size));
}
fn lookup(fs: &mut GoodDataFS, _req: &Request, parent: u64, _name: &Path, reply: ReplyEntry) {
let inode_parent = inode::Inode::deserialize(parent);
let inode = inode::Inode::serialize(&inode::Inode {
project: inode_parent.project,
cat... |
let project: &object::Project = &project_from_inode(fs, inode);
let json = json::as_pretty_json(project).to_string(); | random_line_split |
border_none.rs | //! Bayer reader without any additional border logic.
use std::io::Read;
use ::BayerResult;
use bayer::*;
pub struct BorderNone8;
pub struct BorderNone16BE;
pub struct BorderNone16LE;
impl BorderNone8 {
pub fn new() -> Self {
BorderNone8
}
}
impl BayerRead8 for BorderNone8 {
fn read_line(&self,... |
}
impl BorderNone16LE {
pub fn new() -> Self {
BorderNone16LE
}
}
impl BayerRead16 for BorderNone16LE {
fn read_line(&self, r: &mut Read, dst: &mut [u16])
-> BayerResult<()> {
read_exact_u16le(r, dst)
}
}
| {
read_exact_u16be(r, dst)
} | identifier_body |
border_none.rs | //! Bayer reader without any additional border logic.
use std::io::Read;
use ::BayerResult;
use bayer::*;
pub struct BorderNone8;
pub struct BorderNone16BE;
pub struct BorderNone16LE;
impl BorderNone8 {
pub fn new() -> Self {
BorderNone8
}
}
impl BayerRead8 for BorderNone8 {
fn | (&self, r: &mut Read, dst: &mut [u8])
-> BayerResult<()> {
read_exact_u8(r, dst)
}
}
impl BorderNone16BE {
pub fn new() -> Self {
BorderNone16BE
}
}
impl BayerRead16 for BorderNone16BE {
fn read_line(&self, r: &mut Read, dst: &mut [u16])
-> BayerResult<()> {
... | read_line | identifier_name |
border_none.rs | //! Bayer reader without any additional border logic.
use std::io::Read;
use ::BayerResult;
use bayer::*;
pub struct BorderNone8;
pub struct BorderNone16BE;
pub struct BorderNone16LE;
impl BorderNone8 {
pub fn new() -> Self {
BorderNone8
}
}
impl BayerRead8 for BorderNone8 {
fn read_line(&self,... | -> BayerResult<()> {
read_exact_u16be(r, dst)
}
}
impl BorderNone16LE {
pub fn new() -> Self {
BorderNone16LE
}
}
impl BayerRead16 for BorderNone16LE {
fn read_line(&self, r: &mut Read, dst: &mut [u16])
-> BayerResult<()> {
read_exact_u16le(r, dst)
}... |
impl BayerRead16 for BorderNone16BE {
fn read_line(&self, r: &mut Read, dst: &mut [u16]) | random_line_split |
region.rs | use std::collections::HashSet;
use std::path::Path;
use mnemonic::Bound;
use layer::{Layer,OpaqueLayer,LayerIter};
use graph_algos::adjacency_list::{AdjacencyListEdgeDescriptor,AdjacencyListVertexDescriptor};
use graph_algos::{AdjacencyList,GraphTrait,VertexListGraphTrait,MutableGraphTrait,IncidenceGraphTrait};
#[deri... |
}
if last < reg.size() {
let free = Bound::new(last,reg.size());
ret.push((free,v));
}
}
if self.dependencies.num_vertices() > 0 {
step(self.root,&self.dependencies,&mut ret,&mut visited);
}
ret
}
}
#... | {
step(nx,regs,ret,visited);
} | conditional_block |
region.rs | use std::collections::HashSet;
use std::path::Path;
use mnemonic::Bound;
use layer::{Layer,OpaqueLayer,LayerIter};
use graph_algos::adjacency_list::{AdjacencyListEdgeDescriptor,AdjacencyListVertexDescriptor};
use graph_algos::{AdjacencyList,GraphTrait,VertexListGraphTrait,MutableGraphTrait,IncidenceGraphTrait};
#[deri... | <'a>(a: (Bound,&'a Layer),v: Vec<(Bound,&'a Layer)>) -> Vec<(Bound,&'a Layer)> {
let mut ret = v.iter().fold(Vec::new(),|mut acc,x| {
if x.0.start >= a.0.start && x.0.end <= a.0.end { // a covers x completly
acc
} else if x.0.start >= a.0.end || x.0.end <= a.0.start { // ... | add | identifier_name |
region.rs | use std::collections::HashSet;
use std::path::Path;
use mnemonic::Bound;
use layer::{Layer,OpaqueLayer,LayerIter};
use graph_algos::adjacency_list::{AdjacencyListEdgeDescriptor,AdjacencyListVertexDescriptor};
use graph_algos::{AdjacencyList,GraphTrait,VertexListGraphTrait,MutableGraphTrait,IncidenceGraphTrait};
#[deri... | let r1 = Region::undefined("test".to_string(),128);
let mut s1 = r1.iter();
assert_eq!(s1.clone().count(), 128);
assert!(s1.all(|x| x.is_none()));
}
#[test]
fn read_one_layer() {
if let Ok(ref tmpdir) = TempDir::new("test-panop") {
let p1 = tmpdir.path()... | fn read_undefined() { | random_line_split |
region.rs | use std::collections::HashSet;
use std::path::Path;
use mnemonic::Bound;
use layer::{Layer,OpaqueLayer,LayerIter};
use graph_algos::adjacency_list::{AdjacencyListEdgeDescriptor,AdjacencyListVertexDescriptor};
use graph_algos::{AdjacencyList,GraphTrait,VertexListGraphTrait,MutableGraphTrait,IncidenceGraphTrait};
#[deri... |
}
impl Regions {
pub fn new(r: Region) -> Regions {
let mut g = RegionGraph::new();
let b = g.add_vertex(r);
Regions{
dependencies: g,
root: b
}
}
pub fn projection(&self) -> Vec<(Bound,RegionRef)> {
let mut ret = Vec::<(Bound,RegionRef)>::... | {
&self.name
} | identifier_body |
utils.rs | // Copyright 2020, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <https://opensource.org/licenses/MIT>
use anyhow::{bail, Result};
use itertools::Itertools;
use proc_macro2::{Ident, Span};
use proc_ma... |
match parse_enum_attribute(&meta)? {
EnumAttribute::TypeName(n) => Ok(n),
}
}
#[derive(Debug)]
pub enum ItemAttribute {
Name(String),
Nick(String),
}
fn parse_item_attribute(meta: &NestedMeta) -> Result<ItemAttribute> {
let (ident, v) = parse_attribute(meta)?;
match ident.as_ref() {
... |
let meta = match find_nested_meta(&meta, "type_name") {
Some(meta) => meta,
_ => bail!("Missing meta 'type_name'"),
}; | random_line_split |
utils.rs | // Copyright 2020, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <https://opensource.org/licenses/MIT>
use anyhow::{bail, Result};
use itertools::Itertools;
use proc_macro2::{Ident, Span};
use proc_ma... | (meta: &NestedMeta) -> Result<(String, String)> {
let meta = match &meta {
NestedMeta::Meta(m) => m,
_ => bail!("wrong meta type"),
};
let meta = match meta {
Meta::NameValue(n) => n,
_ => bail!("wrong meta type"),
};
let value = match &meta.lit {
Lit::Str(s) ... | parse_attribute | identifier_name |
utils.rs | // Copyright 2020, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <https://opensource.org/licenses/MIT>
use anyhow::{bail, Result};
use itertools::Itertools;
use proc_macro2::{Ident, Span};
use proc_ma... |
// parse a single meta like: ident = "value"
fn parse_attribute(meta: &NestedMeta) -> Result<(String, String)> {
let meta = match &meta {
NestedMeta::Meta(m) => m,
_ => bail!("wrong meta type"),
};
let meta = match meta {
Meta::NameValue(n) => n,
_ => bail!("wrong meta type... | {
let meta = match attrs.iter().find(|a| a.path.is_ident(attr_name)) {
Some(a) => a.parse_meta(),
_ => return Ok(None),
};
match meta? {
Meta::List(n) => Ok(Some(n)),
_ => bail!("wrong meta type"),
}
} | identifier_body |
externs.rs | use libc;
use std::cell::RefCell;
use std::collections::HashMap;
use std::mem;
use std::string::FromUtf8Error;
use core::{Field, Id, Key, TypeConstraint, TypeId, Value};
// An opaque pointer to a context used by the extern functions.
pub type ExternContext = libc::c_void;
pub type SatisfiedByExtern =
extern "C" f... |
pub fn project_multi(&self, value: &Value, field: &Field) -> Vec<Value> {
let buf = (self.project_multi)(self.context, value, field);
with_vec(buf.values_ptr, buf.values_len as usize, |value_vec| value_vec.clone())
}
pub fn id_to_str(&self, digest: Id) -> String {
(self.id_to_str)(self.context, dig... | {
(self.project)(self.context, value, field, type_id)
} | identifier_body |
externs.rs | use libc;
use std::cell::RefCell;
use std::collections::HashMap;
use std::mem;
use std::string::FromUtf8Error;
use core::{Field, Id, Key, TypeConstraint, TypeId, Value};
// An opaque pointer to a context used by the extern functions.
pub type ExternContext = libc::c_void;
pub type SatisfiedByExtern =
extern "C" f... | (&self, values: Vec<&Value>, merge: bool) -> Value {
if merge && values.len() == 1 {
// We're merging, but there is only one input value: return it immediately.
if let Some(&first) = values.first() {
return first.clone();
}
}
// Execute extern.
let values_clone: Vec<Value> = v... | store_list | identifier_name |
externs.rs | use libc;
use std::cell::RefCell;
use std::collections::HashMap;
use std::mem;
use std::string::FromUtf8Error;
use core::{Field, Id, Key, TypeConstraint, TypeId, Value};
// An opaque pointer to a context used by the extern functions.
pub type ExternContext = libc::c_void;
pub type SatisfiedByExtern =
extern "C" f... |
// Execute extern.
let values_clone: Vec<Value> = values.into_iter().map(|&v| v).collect();
(self.store_list)(self.context, values_clone.as_ptr(), values_clone.len() as u64, merge)
}
pub fn project(&self, value: &Value, field: &Field, type_id: &TypeId) -> Value {
(self.project)(self.context, valu... | {
// We're merging, but there is only one input value: return it immediately.
if let Some(&first) = values.first() {
return first.clone();
}
} | conditional_block |
externs.rs | use libc;
use std::cell::RefCell;
use std::collections::HashMap;
use std::mem;
use std::string::FromUtf8Error;
use core::{Field, Id, Key, TypeConstraint, TypeId, Value};
// An opaque pointer to a context used by the extern functions.
pub type ExternContext = libc::c_void;
pub type SatisfiedByExtern =
extern "C" f... | create_exception: CreateExceptionExtern,
) -> Externs {
Externs {
context: ext_context,
key_for: key_for,
satisfied_by: satisfied_by,
satisfied_by_cache: RefCell::new(HashMap::new()),
store_list: store_list,
project: project,
project_multi: project_multi,
id_to_... | project_multi: ProjectMultiExtern, | random_line_split |
ui.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the F... | .multiple(false)
.help("Alternative path where to put the repository. Default: ~/.imag"))
}
| {
app
.arg(Arg::with_name("devel")
.long("dev")
.takes_value(false)
.required(false)
.multiple(false)
.help("Put dev configuration into the generated repo (with debugging enabled)"))
.arg(Arg::with_name("nogit")
.long("no... | identifier_body |
ui.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the F... | <'a>(app: App<'a, 'a>) -> App<'a, 'a> {
app
.arg(Arg::with_name("devel")
.long("dev")
.takes_value(false)
.required(false)
.multiple(false)
.help("Put dev configuration into the generated repo (with debugging enabled)"))
.arg(Arg::with_name(... | build_ui | identifier_name |
ui.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the F... | .long("dev")
.takes_value(false)
.required(false)
.multiple(false)
.help("Put dev configuration into the generated repo (with debugging enabled)"))
.arg(Arg::with_name("nogit")
.long("no-git")
.takes_value(false)
.re... |
pub fn build_ui<'a>(app: App<'a, 'a>) -> App<'a, 'a> {
app
.arg(Arg::with_name("devel") | random_line_split |
server.rs | // Copyright (c) 2013-2016 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, inc... | (
&mut self,
_params: http_session::PostParams,
_results: http_session::PostResults)
-> Promise<(), Error>
{
// TODO
Promise::err(Error::unimplemented(format!("post() is unimplemented")))
}
}
pub fn main() {
use std::net::ToSocketAddrs;
let args: Vec<Stri... | post | identifier_name |
server.rs | // Copyright (c) 2013-2016 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, inc... | }
}
fn from_curl_error(e: ::curl::Error) -> Error {
Error::failed(format!("curl error: {:?}", e))
}
fn from_perform_error(e: ::tokio_curl::PerformError) -> Error {
Error::failed(format!("curl perform error: {:?}", e))
}
impl http_session::Server for HttpSession {
fn get(
&mut self,
pa... | random_line_split | |
server.rs | // Copyright (c) 2013-2016 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, inc... |
let mut core = reactor::Core::new().unwrap();
let handle = core.handle();
let addr = args[2].to_socket_addrs().unwrap().next().expect("could not parse address");
let socket = ::tokio_core::net::TcpListener::bind(&addr, &handle).unwrap();
let proxy = outgoing_http::ToClient::new(
Outgoing... | {
println!("usage: {} server HOST:PORT", args[0]);
return;
} | conditional_block |
server.rs | // Copyright (c) 2013-2016 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, inc... |
}
pub fn main() {
use std::net::ToSocketAddrs;
let args: Vec<String> = ::std::env::args().collect();
if args.len()!= 3 {
println!("usage: {} server HOST:PORT", args[0]);
return;
}
let mut core = reactor::Core::new().unwrap();
let handle = core.handle();
let addr = args[2]... | {
// TODO
Promise::err(Error::unimplemented(format!("post() is unimplemented")))
} | identifier_body |
actor.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/// General actor system infrastructure.
use devtools_traits::PreciseTime;
use rustc_serialize::json;
use std::an... | <T: Reflect +'static>(&self) -> bool {
// Get TypeId of the type this function is instantiated with
let t = TypeId::of::<T>();
// Get TypeId of the type in the trait object
let boxed = self.get_type_id();
// Compare both TypeIds on equality
t == boxed
}
/// Ret... | is | identifier_name |
actor.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/// General actor system infrastructure.
use devtools_traits::PreciseTime;
use rustc_serialize::json;
use std::an... | #[allow(unsafe_code)]
pub fn downcast_ref<T: Reflect +'static>(&self) -> Option<&T> {
if self.is::<T>() {
unsafe {
// Get the raw representation of the trait object
let to: TraitObject = transmute(self);
// Extract the data pointer
... | /// `None` if it isn't.
#[inline] | random_line_split |
fft.rs | use num::complex::{Complex, Complex64};
use libc::c_double;
use std::f64::consts::PI;
///
/// Compute the Discrete Fast Fourier Transform
/// of an f64 Vec with the Cooley-Turkey FFT algorithm
/// (implementation taken from Wikipedia)
///
pub fn | (x: &Vec<Complex64>) -> Vec<Complex64> {
let mut res: Vec<Complex64> = Vec::<Complex64>::with_capacity(x.len());
if x.len() == 1 {
res.push(x[0]);
return res
}
else {
// Follow the Cooley-Tukey recursive implementation
let x_1: &Vec<Complex64> = &x.iter()
.enum... | fft | identifier_name |
fft.rs | use num::complex::{Complex, Complex64};
use libc::c_double;
use std::f64::consts::PI;
///
/// Compute the Discrete Fast Fourier Transform
/// of an f64 Vec with the Cooley-Turkey FFT algorithm
/// (implementation taken from Wikipedia)
///
pub fn fft(x: &Vec<Complex64>) -> Vec<Complex64> {
let mut res: Vec<Complex6... |
}
| {
let x: Vec<Complex64> = vec![1.0, 2.0, 3.0, 4.0, 5.0].iter()
.map(|x| Complex64::new(*x, 0.0)).collect();
println!("{:?}", fft(&x));
} | identifier_body |
fft.rs | use num::complex::{Complex, Complex64};
use libc::c_double;
use std::f64::consts::PI;
| ///
pub fn fft(x: &Vec<Complex64>) -> Vec<Complex64> {
let mut res: Vec<Complex64> = Vec::<Complex64>::with_capacity(x.len());
if x.len() == 1 {
res.push(x[0]);
return res
}
else {
// Follow the Cooley-Tukey recursive implementation
let x_1: &Vec<Complex64> = &x.iter()
... | ///
/// Compute the Discrete Fast Fourier Transform
/// of an f64 Vec with the Cooley-Turkey FFT algorithm
/// (implementation taken from Wikipedia) | random_line_split |
fft.rs | use num::complex::{Complex, Complex64};
use libc::c_double;
use std::f64::consts::PI;
///
/// Compute the Discrete Fast Fourier Transform
/// of an f64 Vec with the Cooley-Turkey FFT algorithm
/// (implementation taken from Wikipedia)
///
pub fn fft(x: &Vec<Complex64>) -> Vec<Complex64> {
let mut res: Vec<Complex6... | else {
res.push(fft_2[k/2]);
}
k += 1;
}
let mut k = 0;
let n = x.len();
while k < n/2 - 1 {
let t = res[k];
let modulus: Complex64 = Complex::i() * 2.0 * PI *
(((k as u32) / (n as u32)) as c_double);
... | {
res.push(fft_1[k/2]);
} | conditional_block |
heap.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 ... | #[inline]
pub unsafe fn zero_alloc(size: uint) -> *mut u8 {
if size == 0 {
0 as *mut u8
} else {
let ptr = calloc(1, size);
if ptr == 0 as *mut u8 {
out_of_memory()
}
ptr
}
}
#[inline]
pub unsafe fn realloc(ptr: *mut u8, size: uint) -> *mut u8 {
if si... | ptr
}
}
| random_line_split |
heap.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 ... |
ptr
}
}
#[inline]
pub unsafe fn zero_alloc(size: uint) -> *mut u8 {
if size == 0 {
0 as *mut u8
} else {
let ptr = calloc(1, size);
if ptr == 0 as *mut u8 {
out_of_memory()
}
ptr
}
}
#[inline]
pub unsafe fn realloc(ptr: *mut u8, size: uint) ... | {
out_of_memory()
} | conditional_block |
heap.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 ... | (ptr: *mut u8) {
detail::free(ptr)
}
#[inline]
#[lang = "exchange_malloc"]
pub unsafe fn alloc(size: uint) -> *mut u8 {
if size == 0 {
0 as *mut u8
} else {
let ptr = malloc(size);
if ptr == 0 as *mut u8 {
out_of_memory()
}
ptr
}
}
#[inline]
pub unsa... | free | identifier_name |
heap.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 ... |
#[inline]
#[lang = "exchange_malloc"]
pub unsafe fn alloc(size: uint) -> *mut u8 {
if size == 0 {
0 as *mut u8
} else {
let ptr = malloc(size);
if ptr == 0 as *mut u8 {
out_of_memory()
}
ptr
}
}
#[inline]
pub unsafe fn zero_alloc(size: uint) -> *mut u8 ... | {
detail::free(ptr)
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.