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 |
|---|---|---|---|---|
font.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 app_units::Au;
use euclid::{Point2D, Rect, Size2D};
use font_template::FontTemplateDescriptor;
use platform::f... | options.flags.contains(IS_WHITESPACE_SHAPING_FLAG),
options.flags.contains(RTL_FLAG));
if self.can_do_fast_shaping(text, options) {
debug!("shape_text: Using ASCII fast path.");
self.sh... | };
let result = self.shape_cache.borrow_mut().find_or_create(lookup_key, || {
let start_time = time::precise_time_ns();
let mut glyphs = GlyphStore::new(text.len(), | random_line_split |
font.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 app_units::Au;
use euclid::{Point2D, Rect, Size2D};
use font_template::FontTemplateDescriptor;
use platform::f... | (&self, text: &str, options: &ShapingOptions, glyphs: &mut GlyphStore) {
let mut prev_glyph_id = None;
for (i, byte) in text.bytes().enumerate() {
let character = byte as char;
let glyph_id = match self.glyph_index(character) {
Some(id) => id,
None... | shape_text_fast | identifier_name |
service.rs | use std::sync::atomic::*;
use futures::channel::mpsc;
use futures::{FutureExt, SinkExt, StreamExt, TryFutureExt};
use grpcio::{self, *};
use kvproto::backup::*;
use tikv_util::worker::*;
use super::Task;
/// Service handles the RPC messages for the `Backup` service.
#[derive(Clone)]
pub struct Service {
schedule... | () {
let (_server, client, mut rx) = new_rpc_suite();
let (tmp, endpoint) = new_endpoint();
let engine = endpoint.engine.clone();
endpoint.region_info.set_regions(vec![
(b"".to_vec(), b"2".to_vec(), 1),
(b"2".to_vec(), b"5".to_vec(), 2),
]);
let ... | test_client_stop | identifier_name |
service.rs | use std::sync::atomic::*;
use futures::channel::mpsc;
use futures::{FutureExt, SinkExt, StreamExt, TryFutureExt};
use grpcio::{self, *}; |
/// Service handles the RPC messages for the `Backup` service.
#[derive(Clone)]
pub struct Service {
scheduler: Scheduler<Task>,
}
impl Service {
/// Create a new backup service.
pub fn new(scheduler: Scheduler<Task>) -> Service {
Service { scheduler }
}
}
impl Backup for Service {
fn bac... | use kvproto::backup::*;
use tikv_util::worker::*;
use super::Task; | random_line_split |
service.rs | use std::sync::atomic::*;
use futures::channel::mpsc;
use futures::{FutureExt, SinkExt, StreamExt, TryFutureExt};
use grpcio::{self, *};
use kvproto::backup::*;
use tikv_util::worker::*;
use super::Task;
/// Service handles the RPC messages for the `Backup` service.
#[derive(Clone)]
pub struct Service {
schedule... |
#[test]
fn test_client_stop() {
let (_server, client, mut rx) = new_rpc_suite();
let (tmp, endpoint) = new_endpoint();
let engine = endpoint.engine.clone();
endpoint.region_info.set_regions(vec![
(b"".to_vec(), b"2".to_vec(), 1),
(b"2".to_vec(), b"5".to... | {
let env = Arc::new(EnvBuilder::new().build());
let (scheduler, rx) = dummy_scheduler();
let backup_service = super::Service::new(scheduler);
let builder =
ServerBuilder::new(env.clone()).register_service(create_backup(backup_service));
let mut server = builder.bind(... | identifier_body |
tests.rs | use tempdir;
use libxch;
mod util;
#[test]
fn test_success() |
#[test]
fn test_failure() {
let dir = tempdir::TempDir::new("test").expect("Could not create temporary directory");
let file1 = dir.path().join("file1");
util::create_file_with_content(&file1, b"content1").expect("Could not create file in tempdir");
assert!(libxch::xch_non_atomic(&file1, dir.path()).... | {
let dir = tempdir::TempDir::new("test").expect("Could not create temporary directory");
let file1 = dir.path().join("file1");
let file2 = dir.path().join("file2");
util::create_file_with_content(&file1, b"content1").expect("Could not create file in tempdir");
util::create_file_with_content(&file2,... | identifier_body |
tests.rs | use tempdir;
use libxch;
mod util;
#[test]
fn test_success() {
let dir = tempdir::TempDir::new("test").expect("Could not create temporary directory");
let file1 = dir.path().join("file1");
let file2 = dir.path().join("file2");
util::create_file_with_content(&file1, b"content1").expect("Could not create... | let dir = tempdir::TempDir::new("test").expect("Could not create temporary directory");
let file1 = dir.path().join("file1");
util::create_file_with_content(&file1, b"content1").expect("Could not create file in tempdir");
assert!(libxch::xch_non_atomic(&file1, dir.path()).is_err());
assert!(util::e... | #[test]
fn test_failure() { | random_line_split |
tests.rs | use tempdir;
use libxch;
mod util;
#[test]
fn | () {
let dir = tempdir::TempDir::new("test").expect("Could not create temporary directory");
let file1 = dir.path().join("file1");
let file2 = dir.path().join("file2");
util::create_file_with_content(&file1, b"content1").expect("Could not create file in tempdir");
util::create_file_with_content(&fil... | test_success | identifier_name |
mutation_utils.rs | use std::ops;
use cge::gene::GeneExtras;
use rand::{Rng, thread_rng};
use crate::utils::Individual;
use crate::cge_utils::Mutation;
use crate::NNFitnessFunction;
// A few convenience methods for helping with determining which mutation operators are valid
impl<T: NNFitnessFunction+ Clone> Individual<T> {
// Retur... | else {
if include_connections {
depths.push(depth);
}
while let Some(&1) = stack.last() {
stack.pop();
}
if let Some(last) = stack.last_mut() {
*last -= 1;
}
... | {
depths.push(depth);
stack.push(*inputs);
} | conditional_block |
mutation_utils.rs | use std::ops;
use cge::gene::GeneExtras;
use rand::{Rng, thread_rng};
use crate::utils::Individual;
use crate::cge_utils::Mutation;
use crate::NNFitnessFunction;
// A few convenience methods for helping with determining which mutation operators are valid
impl<T: NNFitnessFunction+ Clone> Individual<T> {
// Retur... | (&self, id: usize) -> usize {
self.network.genome.iter().fold(0, |acc, g| {
if let GeneExtras::Input(_) = (*g).variant {
acc + ((g.id == id) as usize)
} else {
acc
}
})
}
// Returns a vector with each element being the length o... | get_input_copies | identifier_name |
mutation_utils.rs | use std::ops;
use cge::gene::GeneExtras;
use rand::{Rng, thread_rng};
use crate::utils::Individual;
use crate::cge_utils::Mutation;
use crate::NNFitnessFunction;
// A few convenience methods for helping with determining which mutation operators are valid
impl<T: NNFitnessFunction+ Clone> Individual<T> {
// Retur... | // does not need to be implemented
fn previous_neuron_index(&self, _: usize) -> Option<usize> {
unimplemented!();
}
} | random_line_split | |
mutation_utils.rs | use std::ops;
use cge::gene::GeneExtras;
use rand::{Rng, thread_rng};
use crate::utils::Individual;
use crate::cge_utils::Mutation;
use crate::NNFitnessFunction;
// A few convenience methods for helping with determining which mutation operators are valid
impl<T: NNFitnessFunction+ Clone> Individual<T> {
// Retur... | }
}
depths
}
pub fn random_index(&self) -> usize {
let indices = (0..self.next_id).map(|i| {
self.network.get_neuron_index(i).unwrap()
}).collect::<Vec<usize>>();
*thread_rng().choose(&indices).unwrap()
}
pub fn subnetwork_index(&self,... | {
let mut depths = Vec::new();
let mut stack = Vec::new();
for gene in &self.network.genome {
let depth = stack.len();
if let GeneExtras::Neuron(_, ref inputs) = gene.variant {
depths.push(depth);
stack.push(*inputs);
} else {... | identifier_body |
mod.rs | use communication::Message;
pub use self::counter::Counter;
pub mod counter;
/// The pullable design may need to be upgraded: right now there is no obvious connection between
/// subsequent calls to pull; although multiple calls may produce the same time, they don't need to
/// and defensive implementations must con... |
}
| { (**self).pull() } | identifier_body |
mod.rs | use communication::Message;
pub use self::counter::Counter;
pub mod counter;
/// The pullable design may need to be upgraded: right now there is no obvious connection between
/// subsequent calls to pull; although multiple calls may produce the same time, they don't need to
/// and defensive implementations must con... | (&mut self) -> Option<(&T, &mut Message<D>)> { (**self).pull() }
}
| pull | identifier_name |
mod.rs | use communication::Message;
pub use self::counter::Counter;
| /// may conservatively over-flush, if the defensive implementation isn't well done (e.g. now).
/// An alternate design is for a Pullable<T, D> to return a (&T, Session<D>), where Session<D> is a
/// new type implementing Iterator<Item=Message<D>>, or Iterator<Item=D>, or PullableSession<D>, or
/// something like that.... | pub mod counter;
/// The pullable design may need to be upgraded: right now there is no obvious connection between
/// subsequent calls to pull; although multiple calls may produce the same time, they don't need to
/// and defensive implementations must constantly check this. This complicates data exchange, which | random_line_split |
movemant.rs | extern crate ggez;
extern crate rand;
use rand::Rng;
use ggez::graphics::{Point};
use ::MainState;
#[derive(Clone)]
pub struct Rabbit{
pub x:i32,
pub y:i32,
pub point:Point,
}
pub fn | (tself:&mut MainState){
let mut next_rabbits = Vec::new();
for obj in tself.rabbits_hash.iter(){
let cor_prev = obj.1;
let rab = rabbit_run(cor_prev);
let mut cor_next = rab.0;
cor_next.point = match tself.map_hash.get(&(cor_next.x, cor_next.y)) {
Some(n) => *n,
None => Point{x:150.0,y:150.0},
... | rabbits_run | identifier_name |
movemant.rs | extern crate ggez;
extern crate rand;
use rand::Rng;
use ggez::graphics::{Point};
use ::MainState;
#[derive(Clone)]
pub struct Rabbit{
pub x:i32,
pub y:i32,
pub point:Point,
}
pub fn rabbits_run (tself:&mut MainState){
let mut next_rabbits = Vec::new();
for obj in tself.rabbits_hash.iter(){
let cor_prev = obj.... | point: cor_prev.point,
};
let right = Rabbit{
x: (cor_prev.x + 1),
y: cor_prev.y,
point: cor_prev.point,
};
let up_left = Rabbit{
x: (cor_prev.x - 1),
y: (cor_prev.y - 1),
point: cor_prev.point,
};
let down_right = Rabbit{
x: (cor_prev.x + 1),
y: (cor_prev.y + 1),
point: cor_prev.point,
};
l... | random_line_split | |
perf_context.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum PerfLevel {
Uninitialized,
Disable,
EnableCount,
EnableTimeExceptForMutex,
EnableTimeAndCPUTimeExceptForMutex,
EnableTime,
OutOfBounds,
}
/// Extensions for measuring engine... | {
RaftstoreApply,
RaftstoreStore,
}
/// Reports metrics to prometheus
///
/// For alternate engines, it is reasonable to make `start_observe`
/// and `report_metrics` no-ops.
pub trait PerfContext: Send {
/// Reinitializes statistics and the perf level
fn start_observe(&mut self);
/// Reports the... | PerfContextKind | identifier_name |
perf_context.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum PerfLevel {
Uninitialized,
Disable,
EnableCount,
EnableTimeExceptForMutex,
EnableTimeAndCPUTimeExceptForMutex,
EnableTime,
OutOfBounds,
}
/// Extensions for measuring engine... | }
/// The raftstore subsystem the PerfContext is being created for.
///
/// This is a leaky abstraction that supports the encapsulation of metrics
/// reporting by the two raftstore subsystems that use `report_metrics`.
#[derive(Eq, PartialEq, Copy, Clone)]
pub enum PerfContextKind {
RaftstoreApply,
RaftstoreS... | fn get_perf_context(&self, level: PerfLevel, kind: PerfContextKind) -> Self::PerfContext; | random_line_split |
day3.rs | use std::io::{self, BufRead};
use std::fmt;
static DEFAULT: i32 = 0;
static MULTIPLE: i32 = -1;
pub struct Entry {
num: i32,
index_x: i32,
index_y: i32,
width: i32,
height: i32
}
impl fmt::Display for Entry {
fn fmt(&self,fmt: &mut fmt::Formatter) -> fmt::Result {
let str_num = "num... | if current_value == DEFAULT {
matrix[x as usize][y as usize] = entry.num;
//matrix[x as usize][y as usize] = "1";
} else {
if current_value!= MULTIPLE {
matrix[x as usize][y as usize] = MULTIPLE;
}
... |
fn fill_matrix(matrix: &mut [[i32; 10]; 10], entry: &mut Entry) {
for x in entry.index_x..entry.width{
for y in entry.index_y..entry.height {
let current_value = matrix[x as usize][y as usize]; | random_line_split |
day3.rs | use std::io::{self, BufRead};
use std::fmt;
static DEFAULT: i32 = 0;
static MULTIPLE: i32 = -1;
pub struct | {
num: i32,
index_x: i32,
index_y: i32,
width: i32,
height: i32
}
impl fmt::Display for Entry {
fn fmt(&self,fmt: &mut fmt::Formatter) -> fmt::Result {
let str_num = "num=".to_string()+&self.num.to_string();
let str_index_x = "index_x=".to_string() + &self.index_x.to_string();... | Entry | identifier_name |
day3.rs | use std::io::{self, BufRead};
use std::fmt;
static DEFAULT: i32 = 0;
static MULTIPLE: i32 = -1;
pub struct Entry {
num: i32,
index_x: i32,
index_y: i32,
width: i32,
height: i32
}
impl fmt::Display for Entry {
fn fmt(&self,fmt: &mut fmt::Formatter) -> fmt::Result {
let str_num = "num... | else if *col == -1 as i32 {
print!("X");
} else {
print!("{}", col);
}
}
println!();
}
}
fn fill_matrix(matrix: &mut [[i32; 10]; 10], entry: &mut Entry) {
for x in entry.index_x..entry.width{
for y in entry.index_y..entry.heig... | {
print!(".");
} | conditional_block |
day3.rs | use std::io::{self, BufRead};
use std::fmt;
static DEFAULT: i32 = 0;
static MULTIPLE: i32 = -1;
pub struct Entry {
num: i32,
index_x: i32,
index_y: i32,
width: i32,
height: i32
}
impl fmt::Display for Entry {
fn fmt(&self,fmt: &mut fmt::Formatter) -> fmt::Result |
}
fn paint_matrix(matrix: &mut [[i32; 10]; 10]) {
for (i, row) in matrix.iter_mut().enumerate() {
for (y, col) in row.iter_mut().enumerate() {
if *col == 0 as i32 {
print!(".");
} else if *col == -1 as i32 {
print!("X");
} else {
... | {
let str_num = "num=".to_string()+&self.num.to_string();
let str_index_x = "index_x=".to_string() + &self.index_x.to_string();
let str_index_y = "index_y=".to_string() + &self.index_y.to_string();
let str_w = "w=".to_string() + &self.width.to_string();
let str_h = "h=".to_strin... | identifier_body |
mqueue.rs | use {Error, Result, from_ffi};
use errno::Errno;
use libc::{c_int, c_long, c_char, size_t, mode_t, strlen};
use std::ffi::CString;
use sys::stat::Mode;
pub use self::consts::*;
pub type MQd = c_int;
#[cfg(target_os = "linux")]
mod consts {
use libc::c_int;
bitflags!(
flags MQ_OFlag: c_int {
... |
pub fn mq_getattr(mqd: MQd) -> Result<MqAttr> {
let mut attr = MqAttr::new(0, 0, 0, 0);
let res = unsafe { ffi::mq_getattr(mqd, &mut attr) };
if res < 0 {
return Err(Error::Sys(Errno::last()));
}
Ok(attr)
}
| {
let len = unsafe { strlen(message.as_ptr()) as size_t };
let res = unsafe { ffi::mq_send(mqdes, message.as_ptr(), len, msq_prio) };
if res < 0 {
return Err(Error::Sys(Errno::last()));
}
Ok(res as usize)
} | identifier_body |
mqueue.rs | use {Error, Result, from_ffi};
use errno::Errno;
use libc::{c_int, c_long, c_char, size_t, mode_t, strlen};
use std::ffi::CString;
use sys::stat::Mode;
pub use self::consts::*;
pub type MQd = c_int;
#[cfg(target_os = "linux")]
mod consts {
use libc::c_int;
bitflags!(
flags MQ_OFlag: c_int {
... | }
Ok(res)
}
pub fn mq_close(mqdes: MQd) -> Result<()> {
let res = unsafe { ffi::mq_close(mqdes) };
from_ffi(res)
}
pub fn mq_receive(mqdes: MQd, message: &mut [u8], msq_prio: u32) -> Result<usize> {
let len = message.len() as size_t;
let res = unsafe { ffi::mq_receive(mqdes, message.as_mut_... | return Err(Error::Sys(Errno::last())); | random_line_split |
mqueue.rs | use {Error, Result, from_ffi};
use errno::Errno;
use libc::{c_int, c_long, c_char, size_t, mode_t, strlen};
use std::ffi::CString;
use sys::stat::Mode;
pub use self::consts::*;
pub type MQd = c_int;
#[cfg(target_os = "linux")]
mod consts {
use libc::c_int;
bitflags!(
flags MQ_OFlag: c_int {
... | (mqdes: MQd, message: &CString, msq_prio: u32) -> Result<usize> {
let len = unsafe { strlen(message.as_ptr()) as size_t };
let res = unsafe { ffi::mq_send(mqdes, message.as_ptr(), len, msq_prio) };
if res < 0 {
return Err(Error::Sys(Errno::last()));
}
Ok(res as usize)
}
pub fn mq_getattr(... | mq_send | identifier_name |
mqueue.rs | use {Error, Result, from_ffi};
use errno::Errno;
use libc::{c_int, c_long, c_char, size_t, mode_t, strlen};
use std::ffi::CString;
use sys::stat::Mode;
pub use self::consts::*;
pub type MQd = c_int;
#[cfg(target_os = "linux")]
mod consts {
use libc::c_int;
bitflags!(
flags MQ_OFlag: c_int {
... |
Ok(res as usize)
}
pub fn mq_send(mqdes: MQd, message: &CString, msq_prio: u32) -> Result<usize> {
let len = unsafe { strlen(message.as_ptr()) as size_t };
let res = unsafe { ffi::mq_send(mqdes, message.as_ptr(), len, msq_prio) };
if res < 0 {
return Err(Error::Sys(Errno::last()));
}
... | {
return Err(Error::Sys(Errno::last()));
} | conditional_block |
log_entry.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | // You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Log entry type definition.
use std::ops::Deref;
use util::{H256, Address, Bytes, HeapSizeOf, Hashable};
use util::bloom::Bloomable;
use rlp::*;
use basic_types::LogBloom;
use he... | random_line_split | |
log_entry.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | () {
let bloom = H2048::from_str("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000... | test_empty_log_bloom | identifier_name |
log_entry.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... |
}
| {
let bloom = H2048::from_str("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000... | identifier_body |
main.rs | use std::thread;
use std::sync::{Mutex, Arc};
struct Table {
forks: Vec<Mutex<()>>
}
struct Philosopher {
name: String,
left_index: usize,
right_index: usize
}
impl Philosopher {
fn new(name: &str, left_index: usize, right_index: usize) -> Philosopher {
Philosopher {
name: nam... |
}
fn main() {
let table = Arc::new(Table {
forks: vec![
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
Mutex::new(())
]
});
let philosophers = vec![
Philosopher::new("Philosopher 1", 0, 1),
Philos... | {
let _left = table.forks[self.left_index].lock().unwrap();
let _right = table.forks[self.right_index].lock().unwrap();
println!("{} started eating", self.name);
thread::sleep_ms(1000);
println!("{} is done eating.", self.name);
} | identifier_body |
main.rs | use std::thread;
use std::sync::{Mutex, Arc};
struct Table {
forks: Vec<Mutex<()>>
}
struct | {
name: String,
left_index: usize,
right_index: usize
}
impl Philosopher {
fn new(name: &str, left_index: usize, right_index: usize) -> Philosopher {
Philosopher {
name: name.to_string(),
left_index: left_index,
right_index: right_index
}
}
... | Philosopher | identifier_name |
main.rs | use std::thread;
use std::sync::{Mutex, Arc};
struct Table {
forks: Vec<Mutex<()>>
}
struct Philosopher {
name: String,
left_index: usize,
right_index: usize
}
impl Philosopher {
fn new(name: &str, left_index: usize, right_index: usize) -> Philosopher {
Philosopher {
name: nam... | fn main() {
let table = Arc::new(Table {
forks: vec![
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
Mutex::new(())
]
});
let philosophers = vec![
Philosopher::new("Philosopher 1", 0, 1),
Philosophe... | }
| random_line_split |
promote.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless r... | return Err(Error::from(e));
}
}
ui.status(Status::Promoted, ident)?;
Ok(())
}
| {
let depot_client = Client::new(url, PRODUCT, VERSION, None)?;
ui.begin(format!("Promoting {} to channel '{}'", ident, channel))?;
if channel != "stable" && channel != "unstable" {
match depot_client.create_channel(&ident.origin, channel, token) {
Ok(_) => (),
Err(depot_cl... | identifier_body |
promote.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless r... | (
ui: &mut UI,
url: &str,
ident: &PackageIdent,
channel: &str,
token: &str,
) -> Result<()> {
let depot_client = Client::new(url, PRODUCT, VERSION, None)?;
ui.begin(format!("Promoting {} to channel '{}'", ident, channel))?;
if channel!= "stable" && channel!= "unstable" {
match ... | start | identifier_name |
promote.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless r... | //! ```
//!//! This will promote the acme package specified to the stable channel.
//!
//! Notes:
//! The package should already have been uploaded to Builder.
//! If the specified channel does not exist, it will be created.
//!
use common::ui::{Status, UIWriter, UI};
use depot_client::{self, Client};
use hcore:... | //!
//! ```bash
//! $ hab pkg promote acme/redis/2.0.7/2112010203120101 stable | random_line_split |
explicit-self.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 quux(&self) -> int { *self.x.a }
pub fn baz<'a>(&'a self) -> &'a A { &self.x }
pub fn spam(self) -> int { *self.x.a }
}
trait Nus { fn f(&self); }
impl Nus for thing { fn f(&self) {} }
pub fn main() {
let x = @thing(A {a: @10});
assert_eq!(x.foo(), 10);
assert_eq!(x.quux(), 10);
l... | pub fn foo(@self) -> int { *self.x.a }
pub fn bar(~self) -> int { *self.x.a } | random_line_split |
explicit-self.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 ... | (shape: &shape) -> f64 {
match *shape {
circle(_, radius) => 0.5 * tau * radius * radius,
rectangle(_, ref size) => size.w * size.h
}
}
impl shape {
// self is in the implicit self region
pub fn select<'r, T>(&self, threshold: f64, a: &'r T, b: &'r T)
-> &'r T {... | compute_area | identifier_name |
explicit-self.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 bar(~self) -> int { *self.x.a }
pub fn quux(&self) -> int { *self.x.a }
pub fn baz<'a>(&'a self) -> &'a A { &self.x }
pub fn spam(self) -> int { *self.x.a }
}
trait Nus { fn f(&self); }
impl Nus for thing { fn f(&self) {} }
pub fn main() {
let x = @thing(A {a: @10});
assert_eq!(x.foo(... | { *self.x.a } | identifier_body |
main.rs | extern crate getopts;
extern crate librespot;
extern crate rpassword;
use std::clone::Clone;
use std::fs::File;
use std::io::{stdout, Read, Write};
use std::path::Path;
use std::thread;
use std::path::PathBuf;
use getopts::Options;
use rpassword::read_password;
use librespot::session::{Config, Session};
use librespo... | () {
let args: Vec<String> = std::env::args().collect();
let program = args[0].clone();
let mut opts = Options::new();
opts.reqopt("a", "appkey", "Path to a spotify appkey", "APPKEY");
opts.reqopt("u", "username", "Username to sign in with", "USERNAME");
opts.optopt("p", "password", "Password (... | main | identifier_name |
main.rs | extern crate getopts;
extern crate librespot;
extern crate rpassword;
use std::clone::Clone;
use std::fs::File;
use std::io::{stdout, Read, Write};
use std::path::Path;
use std::thread;
use std::path::PathBuf;
use getopts::Options;
use rpassword::read_password;
use librespot::session::{Config, Session};
use librespo... |
};
let mut appkey_file = File::open(
Path::new(&*matches.opt_str("a").unwrap())
).expect("Could not open app key.");
let username = matches.opt_str("u").unwrap();
let cache_location = matches.opt_str("c").unwrap();
let name = mat... | {
print!("Error: {}\n{}", f.to_string(), usage(&*program, &opts));
return;
} | conditional_block |
main.rs | extern crate getopts;
extern crate librespot;
extern crate rpassword;
use std::clone::Clone;
use std::fs::File;
use std::io::{stdout, Read, Write};
use std::path::Path;
use std::thread;
use std::path::PathBuf;
use getopts::Options;
use rpassword::read_password;
use librespot::session::{Config, Session};
use librespo... |
let mut spirc_manager = SpircManager::new(&session, player, name);
spirc_manager.run();
} | });
let player = Player::new(&session); | random_line_split |
main.rs | extern crate getopts;
extern crate librespot;
extern crate rpassword;
use std::clone::Clone;
use std::fs::File;
use std::io::{stdout, Read, Write};
use std::path::Path;
use std::thread;
use std::path::PathBuf;
use getopts::Options;
use rpassword::read_password;
use librespot::session::{Config, Session};
use librespo... |
fn main() {
let args: Vec<String> = std::env::args().collect();
let program = args[0].clone();
let mut opts = Options::new();
opts.reqopt("a", "appkey", "Path to a spotify appkey", "APPKEY");
opts.reqopt("u", "username", "Username to sign in with", "USERNAME");
opts.optopt("p", "password", "P... | {
let brief = format!("Usage: {} [options]", program);
format!("{}", opts.usage(&brief))
} | identifier_body |
sys.rs | // Copyright 2020 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use std::ffi::c_void;
use std::fmt::{self, Debug};
use std::marker::PhantomData;
use std::slice;
use libc::iovec;
/// This type is essentialy `std::i... |
}
impl<'a> AsRef<libc::iovec> for IoBufMut<'a> {
fn as_ref(&self) -> &libc::iovec {
&self.iov
}
}
impl<'a> AsMut<libc::iovec> for IoBufMut<'a> {
fn as_mut(&mut self) -> &mut libc::iovec {
&mut self.iov
}
}
// It's safe to implement Send + Sync for this type for the same reason that `... | {
// Safe because `IoBufMut` is ABI-compatible with `iovec`.
unsafe { slice::from_raw_parts(iovs.as_ptr() as *const libc::iovec, iovs.len()) }
} | identifier_body |
sys.rs | // Copyright 2020 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use std::ffi::c_void;
use std::fmt::{self, Debug};
use std::marker::PhantomData;
use std::slice;
use libc::iovec;
/// This type is essentialy `std::i... |
}
#[inline]
pub fn len(&self) -> usize {
self.iov.iov_len as usize
}
#[inline]
pub fn is_empty(&self) -> bool {
self.iov.iov_len == 0
}
/// Gets a const pointer to this slice's memory.
#[inline]
pub fn as_ptr(&self) -> *const u8 {
self.iov.iov_base as ... | {
self.iov.iov_len = len;
} | conditional_block |
sys.rs | // Copyright 2020 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use std::ffi::c_void;
use std::fmt::{self, Debug};
use std::marker::PhantomData;
use std::slice;
use libc::iovec;
/// This type is essentialy `std::i... | }
/// Advance the internal position of the buffer.
///
/// Panics if `count > self.len()`.
pub fn advance(&mut self, count: usize) {
assert!(count <= self.len());
self.iov.iov_len -= count;
// Safe because we've checked that `count <= self.len()` so both the starting and re... | phantom: PhantomData,
} | random_line_split |
sys.rs | // Copyright 2020 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use std::ffi::c_void;
use std::fmt::{self, Debug};
use std::marker::PhantomData;
use std::slice;
use libc::iovec;
/// This type is essentialy `std::i... | <'a> {
iov: iovec,
phantom: PhantomData<&'a mut [u8]>,
}
impl<'a> IoBufMut<'a> {
pub fn new(buf: &mut [u8]) -> IoBufMut<'a> {
// Safe because buf's memory is of the supplied length, and
// guaranteed to exist for the lifetime of the returned value.
unsafe { Self::from_raw_parts(buf.... | IoBufMut | identifier_name |
person.rs | use super::Point;
use super::terrain::Terrain;
use std::fmt; // formatting for console display
use std::cmp;
use std::cmp::Ordering::Equal;
// ******
// PERSON
// ******
#[derive(Debug)]
pub struct Person {
pub id: usize,
pub position : Point,
pub has_escaped : bool,
}
impl Person {
pub fn new_plac... | else {
terrain.move_src_to_dst(&self.position, new_point);
self.position.x = new_point.x; // change internal position (copy of x and y)
self.position.y = new_point.y;
}
}
/// This function encapulates a complete move for a person :
/// from looking around to actually movin... | {
terrain.move_src_to_dst(&self.position, new_point); // should just increase exit counts
trace!("I escaped : {}", self.id);
self.has_escaped = true;
self.remove_from_terrain(terrain);
} | conditional_block |
person.rs | use super::Point;
use super::terrain::Terrain;
use std::fmt; // formatting for console display
use std::cmp;
use std::cmp::Ordering::Equal;
// ******
// PERSON
// ******
#[derive(Debug)]
pub struct Person {
pub id: usize,
pub position : Point,
pub has_escaped : bool,
}
impl Person {
pub fn new_plac... |
/// This function encapulates a complete move for a person :
/// from looking around to actually moving to another place
/// (and mutating the Person and the Terrain).
pub fn look_and_move(&mut self, terrain : &mut Terrain) {
//println!("Dealing with : {}", self);
// look around
... | {
if self.has_escaped == true {
} else if terrain.get_exit_points().contains(new_point) {
terrain.move_src_to_dst(&self.position, new_point); // should just increase exit counts
trace!("I escaped : {}", self.id);
self.has_escaped = true;
self.remove_from_t... | identifier_body |
person.rs | use super::Point;
use super::terrain::Terrain;
use std::fmt; // formatting for console display
use std::cmp;
use std::cmp::Ordering::Equal;
// ******
// PERSON
// ******
#[derive(Debug)]
pub struct Person {
pub id: usize,
pub position : Point,
pub has_escaped : bool,
}
impl Person {
pub fn new_plac... |
impl fmt::Display for Person {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Person : {{ id : {}, position : {} }}", self.id, self.position)
}
} | random_line_split | |
person.rs | use super::Point;
use super::terrain::Terrain;
use std::fmt; // formatting for console display
use std::cmp;
use std::cmp::Ordering::Equal;
// ******
// PERSON
// ******
#[derive(Debug)]
pub struct Person {
pub id: usize,
pub position : Point,
pub has_escaped : bool,
}
impl Person {
pub fn new_plac... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Person : {{ id : {}, position : {} }}", self.id, self.position)
}
}
| fmt | identifier_name |
backtrace.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/. */
//! Similar to `println!("{:?}", Backtrace::new())`, but doesn’t allocate.
//!
//! Seems to fix some deadlocks: h... | loop {
match std::str::from_utf8(bytes) {
Ok(s) => {
fmt.write_str(s)?;
break;
}
Err(err) => {
fmt.write_char(std::char::REPLACEMENT_CHARACTER)?;
... | fn print_path(fmt: &mut fmt::Formatter, path: BytesOrWideString) -> fmt::Result {
match path {
BytesOrWideString::Bytes(mut bytes) => { | random_line_split |
backtrace.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/. */
//! Similar to `println!("{:?}", Backtrace::new())`, but doesn’t allocate.
//!
//! Seems to fix some deadlocks: h... | fmt.write_char(c.unwrap_or(std::char::REPLACEMENT_CHARACTER))?
}
}
}
Ok(())
}
| match path {
BytesOrWideString::Bytes(mut bytes) => {
loop {
match std::str::from_utf8(bytes) {
Ok(s) => {
fmt.write_str(s)?;
break;
}
Err(err) => {
f... | identifier_body |
backtrace.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/. */
//! Similar to `println!("{:?}", Backtrace::new())`, but doesn’t allocate.
//!
//! Seems to fix some deadlocks: h... | : &mut fmt::Formatter, path: BytesOrWideString) -> fmt::Result {
match path {
BytesOrWideString::Bytes(mut bytes) => {
loop {
match std::str::from_utf8(bytes) {
Ok(s) => {
fmt.write_str(s)?;
break;
... | t_path(fmt | identifier_name |
perfect.rs | use super::lookups;
use cards::card::{Card};
use super::{HandRank};
use super::utils::{card_to_deck_number};
fn simulate_32bit_precision(u: usize) -> usize {
let mask = 0xffffffff;
u & mask
}
// don't use this.
pub fn find_fast(something: usize) -> usize {
let mut u = simulate_32bit_precision(something);... |
//TODO: FIXME
// version: perfect hash. Not working currently
let lookup = find_fast(
((c1 & 0xff) * (c2 & 0xff) * (c3 & 0xff) * (c4 & 0xff) * (c5 & 0xff)) as usize
);
HAND_RANK_COUNT - (lookups::HASH_VALUES[lookup] as HandRank)
}
// don't use this.
pub fn eval_7cards(cards: [&Card; 7... | {
return s;
} | conditional_block |
perfect.rs | use super::lookups;
use cards::card::{Card};
use super::{HandRank};
use super::utils::{card_to_deck_number};
fn simulate_32bit_precision(u: usize) -> usize {
let mask = 0xffffffff;
u & mask
}
// don't use this.
pub fn find_fast(something: usize) -> usize {
let mut u = simulate_32bit_precision(something);... | (cards: [&Card; 5]) -> HandRank {
let c1 = card_to_deck_number(cards[0]);
let c2 = card_to_deck_number(cards[1]);
let c3 = card_to_deck_number(cards[2]);
let c4 = card_to_deck_number(cards[3]);
let c5 = card_to_deck_number(cards[4]);
let q : usize = ((c1 | c2 | c3 | c4 | c5) as usize) >> 16;
... | eval_5cards | identifier_name |
perfect.rs | use super::lookups;
use cards::card::{Card};
use super::{HandRank};
use super::utils::{card_to_deck_number};
fn simulate_32bit_precision(u: usize) -> usize {
let mask = 0xffffffff;
u & mask
}
// don't use this.
pub fn find_fast(something: usize) -> usize {
let mut u = simulate_32bit_precision(something);... |
// these two guys only work by accident
/*
#[test]
fn get_rank_of_5_perfect() {
let c1 = Card(Value::Two, Suit::Spades);
let c2 = Card(Value::Two, Suit::Hearts);
let c3 = Card(Value::Two, Suit::Diamonds);
let c4 = Card(Value::Two, Suit::Clubs);
let c5 = Card(Value::Three, Suit::Hearts);
let c... | {
let mut tmp;
let mut best = 0;
for ids in lookups::PERM_7.iter() {
let subhand : [&Card; 5] = [
cards[ids[0] as usize],
cards[ids[1] as usize],
cards[ids[2] as usize],
cards[ids[3] as usize],
cards[ids[4] as usize]
... | identifier_body |
perfect.rs | use super::lookups;
use cards::card::{Card};
use super::{HandRank};
use super::utils::{card_to_deck_number};
fn simulate_32bit_precision(u: usize) -> usize {
let mask = 0xffffffff;
u & mask
}
// don't use this.
pub fn find_fast(something: usize) -> usize {
let mut u = simulate_32bit_precision(something);... | let c1 = Card(Value::Two, Suit::Spades);
let c2 = Card(Value::Two, Suit::Hearts);
let c3 = Card(Value::Two, Suit::Diamonds);
let c4 = Card(Value::Two, Suit::Clubs);
let c5 = Card(Value::Three, Suit::Hearts);
let c6 = Card(Value::Three, Suit::Diamonds);
let c7 = Card(Value::Three, Suit::Clubs... | #[test]
fn get_rank_of_7_perfect() { | random_line_split |
backtrace.rs | which in theory means that they're available for dynamic
/// linking and lookup. Other symbols end up only in the local symbol table of
/// the file. This loosely corresponds to pub and priv functions in Rust.
///
/// Armed with this knowledge, we know that our solution for address to symbol
/// translation will need ... | &mut cx as *mut Context as *mut libc::c_void)
} {
uw::_URC_NO_REASON => {
match cx.last_error {
Some(err) => Err(err),
None => Ok(())
}
}
_ => Ok(()),
};
extern fn trace_fn(ctx: *mut uw::_Unwind_Co... | {
struct Context<'a> {
idx: isize,
writer: &'a mut (Write+'a),
last_error: Option<io::Error>,
}
// When using libbacktrace, we use some necessary global state, so we
// need to prevent more than one thread from entering this block. This
// is semi-reasonable in terms of prin... | identifier_body |
backtrace.rs | which in theory means that they're available for dynamic
/// linking and lookup. Other symbols end up only in the local symbol table of
/// the file. This loosely corresponds to pub and priv functions in Rust.
///
/// Armed with this knowledge, we know that our solution for address to symbol
/// translation will need ... | (w: &mut Write, idx: isize, addr: *mut libc::c_void,
symaddr: *mut libc::c_void) -> io::Result<()> {
use env;
use os::unix::prelude::*;
use ptr;
////////////////////////////////////////////////////////////////////////
// libbacktrace.h API
//////////////////////////////////////////////... | print | identifier_name |
backtrace.rs | executable which in theory means that they're available for dynamic
/// linking and lookup. Other symbols end up only in the local symbol table of
/// the file. This loosely corresponds to pub and priv functions in Rust.
///
/// Armed with this knowledge, we know that our solution for address to symbol
/// translation... | ////////////////////////////////////////////////////////////////////////
// backtrace errors are currently swept under the rug, only I/O
// errors are reported
let state = unsafe { init_state() };
if state.is_null() {
return output(w, idx, addr, None)
}
let mut data = ptr::null();
... | ////////////////////////////////////////////////////////////////////////
// translation | random_line_split |
backtrace.rs | which in theory means that they're available for dynamic
/// linking and lookup. Other symbols end up only in the local symbol table of
/// the file. This loosely corresponds to pub and priv functions in Rust.
///
/// Armed with this knowledge, we know that our solution for address to symbol
/// translation will need ... |
// dladdr() on osx gets whiny when we use FindEnclosingFunction, and
// it appears to work fine without it, so we only use
// FindEnclosingFunction on non-osx platforms. In doing so, we get a
// slightly more accurate stack trace in the process.
//
// This is often beca... | {
// this is a non-signaling frame, so `ip` refers to the address
// after the calling instruction. account for that.
ip = (ip as usize - 1) as *mut _;
} | conditional_block |
mod.rs | //! Two sample Kolmogorov-Smirnov test.
/// Two sample test result.
pub struct TestResult {
pub is_rejected: bool,
pub statistic: f64,
pub reject_probability: f64,
pub critical_value: f64,
pub confidence: f64,
}
/// Perform a two sample Kolmogorov-Smirnov test on given samples.
///
/// The samples... | else {
// Maintain invariant that reject_probability(low) <= confidence.
low = mid;
}
}
panic!("No convergence in calculate_critical_value({}, {}, {}).",
n1,
n2,
confidence);
}
/// Calculate the Kolmogorov-Smirnov probability function.
fn proba... | {
// Maintain invariant that reject_probability(high) > confidence.
high = mid;
} | conditional_block |
mod.rs | //! Two sample Kolmogorov-Smirnov test.
/// Two sample test result.
pub struct TestResult {
pub is_rejected: bool,
pub statistic: f64,
pub reject_probability: f64,
pub critical_value: f64,
pub confidence: f64,
}
/// Perform a two sample Kolmogorov-Smirnov test on given samples.
///
/// The samples... | // Maintain invariant that reject_probability(high) > confidence.
high = mid;
} else {
// Maintain invariant that reject_probability(low) <= confidence.
low = mid;
}
}
panic!("No convergence in calculate_critical_value({}, {}, {}).",
n1... | {
assert!(0.0 < confidence && confidence < 1.0);
// Only supports samples of size > 7.
assert!(n1 > 7 && n2 > 7);
// The test statistic is between zero and one so can binary search quickly
// for the critical value.
let mut low = 0.0;
let mut high = 1.0;
for _ in 1..200 {
if l... | identifier_body |
mod.rs | //! Two sample Kolmogorov-Smirnov test.
/// Two sample test result.
pub struct TestResult {
pub is_rejected: bool,
pub statistic: f64,
pub reject_probability: f64,
pub critical_value: f64,
pub confidence: f64,
}
/// Perform a two sample Kolmogorov-Smirnov test on given samples.
///
/// The samples... | (statistic: f64, n1: usize, n2: usize) -> f64 {
// Only supports samples of size > 7.
assert!(n1 > 7 && n2 > 7);
let n1 = n1 as f64;
let n2 = n2 as f64;
let factor = ((n1 * n2) / (n1 + n2)).sqrt();
let term = (factor + 0.12 + 0.11 / factor) * statistic;
let reject_probability = 1.0 - prob... | calculate_reject_probability | identifier_name |
mod.rs | //! Two sample Kolmogorov-Smirnov test.
/// Two sample test result.
pub struct TestResult {
pub is_rejected: bool,
pub statistic: f64,
pub reject_probability: f64,
pub critical_value: f64,
pub confidence: f64,
}
/// Perform a two sample Kolmogorov-Smirnov test on given samples.
///
/// The samples... | assert!(n1 > 7 && n2 > 7);
// The test statistic is between zero and one so can binary search quickly
// for the critical value.
let mut low = 0.0;
let mut high = 1.0;
for _ in 1..200 {
if low + 1e-8 >= high {
return high;
}
let mid = low + (high - low) / 2... | /// ```
pub fn calculate_critical_value(n1: usize, n2: usize, confidence: f64) -> f64 {
assert!(0.0 < confidence && confidence < 1.0);
// Only supports samples of size > 7. | random_line_split |
types.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants;
use ca... | (&self) -> bool {
match *self {
TexImageTarget::Texture2D => false,
_ => true,
}
}
}
| is_cubic | identifier_name |
types.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants;
use ca... |
}
| {
match *self {
TexImageTarget::Texture2D => false,
_ => true,
}
} | identifier_body |
types.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants;
use ca... | TexImageTarget::Texture2D => false,
_ => true,
}
}
} | pub fn is_cubic(&self) -> bool {
match *self { | random_line_split |
fakes.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
//! Fakes for filling-in hardware functionality from `manticore::hardware`.
use std::collections::HashMap;
use std::convert::TryInto as _;
use std::time::Duration;
use ... | (&self) -> Duration {
self.startup_time.elapsed()
}
}
| uptime | identifier_name |
fakes.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
//! Fakes for filling-in hardware functionality from `manticore::hardware`.
use std::collections::HashMap;
use std::convert::TryInto as _;
use std::time::Duration;
use ... |
impl Reset {
/// Creates a new `Reset`.
pub fn new(resets_since_power_on: u32) -> Self {
Self {
startup_time: Instant::now(),
resets_since_power_on,
}
}
}
impl manticore::hardware::Reset for Reset {
fn resets_since_power_on(&self) -> u32 {
self.resets_si... | random_line_split | |
fakes.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
//! Fakes for filling-in hardware functionality from `manticore::hardware`.
use std::collections::HashMap;
use std::convert::TryInto as _;
use std::time::Duration;
use ... |
fn uptime(&self) -> Duration {
self.startup_time.elapsed()
}
}
| {
self.resets_since_power_on
} | identifier_body |
main.rs |
extern crate regex;
#[macro_use]
extern crate lazy_static;
use std::io;
use std::io::prelude::*;
use std::str::FromStr;
use regex::Regex;
lazy_static! {
static ref PARTICLE_RE: Regex = Regex::new(r"^p=<(?P<pos_x>-?[0-9]+),(?P<pos_y>-?[0-9]+),(?P<pos_z>-?[0-9]+)>, v=<(?P<vel_x>-?[0-9]+),(?P<vel_y>-?[0-9]+),(?... |
fn get_num_particles(&self) -> usize {
self.0.len()
}
}
fn dot_product(left: &(f64, f64, f64), right: &(f64, f64, f64)) -> f64 {
left.0 * right.0 + left.1 * right.1 + left.2 * right.2
}
fn get_norm(vec: &(f64, f64, f64)) -> f64 {
dot_product(&vec, &vec).sqrt()
}
fn main() {
let mut inp... | {
let (idx, part, _) = self.0
.iter()
.enumerate()
.map(|(idx, part)| {
let norm = get_norm(&part.acc);
(idx, part, norm)
})
.min_by(|&(_, _, l_norm), &(_, _, r_norm)| {
l_norm.partial_cmp(&r_norm).unwra... | identifier_body |
main.rs |
extern crate regex;
#[macro_use]
extern crate lazy_static;
use std::io;
use std::io::prelude::*;
use std::str::FromStr;
use regex::Regex;
lazy_static! {
static ref PARTICLE_RE: Regex = Regex::new(r"^p=<(?P<pos_x>-?[0-9]+),(?P<pos_y>-?[0-9]+),(?P<pos_z>-?[0-9]+)>, v=<(?P<vel_x>-?[0-9]+),(?P<vel_y>-?[0-9]+),(?... | else {
acc
},
);
occurrence_count <= 1
})
.cloned()
.collect();
}
fn get_longterm_closest_particle(&self) -> (usize, &Particle) {
let (idx, part, _) = self.0
.iter()
.en... | {
acc + 1
} | conditional_block |
main.rs | extern crate regex;
#[macro_use]
extern crate lazy_static;
use std::io;
use std::io::prelude::*;
use std::str::FromStr;
use regex::Regex;
lazy_static! {
static ref PARTICLE_RE: Regex = Regex::new(r"^p=<(?P<pos_x>-?[0-9]+),(?P<pos_y>-?[0-9]+),(?P<pos_z>-?[0-9]+)>, v=<(?P<vel_x>-?[0-9]+),(?P<vel_y>-?[0-9]+),(?P... | acc + 1
} else {
acc
},
);
occurrence_count <= 1
})
.cloned()
.collect();
}
fn get_longterm_closest_particle(&self) -> (usize, &Particle) {
let (idx... | let occurrence_count = self.0.iter().fold(
0,
|acc, particle_2| if particle_1.pos ==
particle_2.pos
{ | random_line_split |
main.rs |
extern crate regex;
#[macro_use]
extern crate lazy_static;
use std::io;
use std::io::prelude::*;
use std::str::FromStr;
use regex::Regex;
lazy_static! {
static ref PARTICLE_RE: Regex = Regex::new(r"^p=<(?P<pos_x>-?[0-9]+),(?P<pos_y>-?[0-9]+),(?P<pos_z>-?[0-9]+)>, v=<(?P<vel_x>-?[0-9]+),(?P<vel_y>-?[0-9]+),(?... | (s: &str) -> Result<Self, Self::Err> {
Ok(Simulation(s.lines()
.map(|line| line.parse())
.collect::<Result<Vec<Particle>, ()>>()?))
}
}
impl Simulation {
fn do_step(&mut self) {
for particle in self.0.iter_mut() {
particle.vel.0 += particle.acc.0;
... | from_str | identifier_name |
cef_process_message.rs | // Copyright (c) 2014 Marshall A. Greenblatt. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of ... |
}
impl CefProcessMessage {
pub unsafe fn from_c_object(c_object: *mut cef_process_message_t) -> CefProcessMessage {
CefProcessMessage {
c_object: c_object,
}
}
pub unsafe fn from_c_object_addref(c_object: *mut cef_process_message_t) -> CefProcessMessage {
if!c_object.is_null() {
((*c_ob... | {
unsafe {
if !self.c_object.is_null() {
((*self.c_object).base.release.unwrap())(&mut (*self.c_object).base);
}
}
} | identifier_body |
cef_process_message.rs | // Copyright (c) 2014 Marshall A. Greenblatt. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of ... |
CefProcessMessage {
c_object: c_object,
}
}
pub fn c_object(&self) -> *mut cef_process_message_t {
self.c_object
}
pub fn c_object_addrefed(&self) -> *mut cef_process_message_t {
unsafe {
if!self.c_object.is_null() {
eutil::add_ref(self.c_object as *mut types::cef_base_t);... | {
((*c_object).base.add_ref.unwrap())(&mut (*c_object).base);
} | conditional_block |
cef_process_message.rs | // Copyright (c) 2014 Marshall A. Greenblatt. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of ... | pub fn is_not_null_cef_object(&self) -> bool {
!self.c_object.is_null()
}
//
// Returns true (1) if this object is valid. Do not call any other functions
// if this function returns false (0).
//
pub fn is_valid(&self) -> libc::c_int {
if self.c_object.is_null() {
panic!("called a CEF method... | } | random_line_split |
cef_process_message.rs | // Copyright (c) 2014 Marshall A. Greenblatt. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of ... | (&self) -> libc::c_int {
if self.c_object.is_null() {
panic!("called a CEF method on a null object")
}
unsafe {
CefWrap::to_rust(
((*self.c_object).is_read_only.unwrap())(
self.c_object))
}
}
//
// Returns a writable copy of this object.
//
pub fn copy(&self) -> ... | is_read_only | identifier_name |
videotracklist.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::VideoTrackListBinding::{... |
}
track.add_track_list(self);
}
pub fn clear(&self) {
self.tracks
.borrow()
.iter()
.for_each(|t| t.remove_track_list());
self.tracks.borrow_mut().clear();
}
}
impl VideoTrackListMethods for VideoTrackList {
// https://html.spec.whatwg.... | {
self.set_selected(idx, false);
} | conditional_block |
videotracklist.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::VideoTrackListBinding::{... | let this = Trusted::new(self);
let (source, canceller) = global
.as_window()
.task_manager()
.media_element_task_source_with_canceller();
if let Some(current) = self.selected_index() {
self.tracks.borrow()[current].set_selected(false);
}
... | random_line_split | |
videotracklist.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::VideoTrackListBinding::{... |
pub fn find(&self, track: &VideoTrack) -> Option<usize> {
self.tracks.borrow().iter().position(|t| &**t == track)
}
pub fn item(&self, idx: usize) -> Option<DomRoot<VideoTrack>> {
self.tracks
.borrow()
.get(idx)
.map(|track| DomRoot::from_ref(&**track))
... | {
self.tracks.borrow().len()
} | identifier_body |
videotracklist.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::VideoTrackListBinding::{... | {
eventtarget: EventTarget,
tracks: DomRefCell<Vec<Dom<VideoTrack>>>,
media_element: Option<Dom<HTMLMediaElement>>,
}
impl VideoTrackList {
pub fn new_inherited(
tracks: &[&VideoTrack],
media_element: Option<&HTMLMediaElement>,
) -> VideoTrackList {
VideoTrackList {
... | VideoTrackList | identifier_name |
lib.rs | #![crate_name = "nfc"]
#![crate_type = "dylib"]
extern crate libc;
pub mod ffi;
pub mod initiator;
pub mod target;
pub mod device;
pub mod context;
pub mod error;
pub mod misc;
pub mod to_str;
use libc::size_t;
// Library initialization/deinitialization
// See http://www.libnfc.org/api/group__lib.html
/// Registe... |
/// Scan for discoverable supported devices
pub fn list_devices(context: *mut ffi::nfc_context, connstrings: *mut ffi::nfc_connstring, constrings_len: size_t) -> size_t {
unsafe { ffi::nfc_list_devices(context, connstrings, constrings_len) }
}
/// Switches the NFC device to idle mode
pub fn idle(pnd: *mut ffi::n... | {
unsafe { ffi::nfc_close(pnd); }
} | identifier_body |
lib.rs | #![crate_name = "nfc"]
#![crate_type = "dylib"]
extern crate libc; | pub mod target;
pub mod device;
pub mod context;
pub mod error;
pub mod misc;
pub mod to_str;
use libc::size_t;
// Library initialization/deinitialization
// See http://www.libnfc.org/api/group__lib.html
/// Registers an NFC device driver with libnfc
pub fn register_driver(ndr: *const ffi::nfc_driver) -> i32 {
u... |
pub mod ffi;
pub mod initiator; | random_line_split |
lib.rs | #![crate_name = "nfc"]
#![crate_type = "dylib"]
extern crate libc;
pub mod ffi;
pub mod initiator;
pub mod target;
pub mod device;
pub mod context;
pub mod error;
pub mod misc;
pub mod to_str;
use libc::size_t;
// Library initialization/deinitialization
// See http://www.libnfc.org/api/group__lib.html
/// Registe... | (ndr: *const ffi::nfc_driver) -> i32 {
unsafe { ffi::nfc_register_driver(ndr) }
}
/// Initializes libnfc. This function must be called before calling any other libnfc function
pub fn init(context: *mut *mut ffi::nfc_context) {
unsafe { ffi::nfc_init(context); }
}
/// Deinitializes libnfc. Should be called aft... | register_driver | identifier_name |
rastrigin.rs | // Copyright 2016 Martin Ankerl.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according... | println!("{:?} best position", pos);
} | {
// command line args: dimension, number of evaluations
let args: Vec<String> = env::args().collect();
let dim = args[1].parse::<usize>().unwrap();
// initial search space for each dimension
let initial_min_max = vec![(-5.12, 5.12); dim];
// initialize differential evolution
let mut de = ... | identifier_body |
rastrigin.rs | // Copyright 2016 Martin Ankerl.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according... | (pos: &[f32]) -> f32 {
pos.iter().fold(0.0, |sum, x|
sum + x * x - 10.0 * (2.0 * PI * x).cos() + 10.0)
}
fn main() {
// command line args: dimension, number of evaluations
let args: Vec<String> = env::args().collect();
let dim = args[1].parse::<usize>().unwrap();
// initial search space f... | rastrigin | identifier_name |
rastrigin.rs | // Copyright 2016 Martin Ankerl.
// | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern crate differ... | random_line_split | |
broken.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... | {
error: Error,
message: ::capnp::message::Builder<::capnp::message::HeapAllocator>,
}
impl Request {
pub fn new(error: Error, _size_hint: Option<::capnp::MessageSize>) -> Request {
Request {
error: error,
message: ::capnp::message::Builder::new_default(),
}
}
}... | Request | identifier_name |
broken.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... | }
}
}
impl RequestHook for Request {
fn get<'a>(&'a mut self) -> any_pointer::Builder<'a> {
self.message.get_root().unwrap()
}
fn get_brand(&self) -> usize {
0
}
fn send<'a>(self: Box<Self>) -> RemotePromise<any_pointer::Owned> {
let pipeline = Pipeline::new(self... | message: ::capnp::message::Builder::new_default(), | random_line_split |
autoderef-method-priority.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) -> uint { *self * 2u }
}
pub fn main() {
let x = box 3u;
assert_eq!(x.double(), 6u);
}
| double | identifier_name |
autoderef-method-priority.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 ... | } | random_line_split | |
autoderef-method-priority.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 main() {
let x = box 3u;
assert_eq!(x.double(), 6u);
}
| { *self * 2u } | identifier_body |
simd-binop.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-tidy-linelength
#![allow(experimental)]
use std::unstable::simd::f32x4;
fn ... | random_line_split | |
simd-binop.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 _ = f32x4(0.0, 0.0, 0.0, 0.0) == f32x4(0.0, 0.0, 0.0, 0.0);
//~^ ERROR binary comparison operation `==` not supported for floating point SIMD vector `std::unstable::simd::f32x4`
let _ = f32x4(0.0, 0.0, 0.0, 0.0)!= f32x4(0.0, 0.0, 0.0, 0.0);
//~^ ERROR binary comparison operation `!=` not supp... | main | identifier_name |
simd-binop.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 _ = f32x4(0.0, 0.0, 0.0, 0.0) == f32x4(0.0, 0.0, 0.0, 0.0);
//~^ ERROR binary comparison operation `==` not supported for floating point SIMD vector `std::unstable::simd::f32x4`
let _ = f32x4(0.0, 0.0, 0.0, 0.0) != f32x4(0.0, 0.0, 0.0, 0.0);
//~^ ERROR binary comparison operation `!=` not suppor... | identifier_body |
socks4.rs | //! Socks4a Protocol Definition
//!
//! <http://ftp.icm.edu.pl/packages/socks/socks4/SOCKS4.protocol>
#![allow(dead_code)]
use std::{
fmt,
io::{self, ErrorKind},
net::{Ipv4Addr, SocketAddr, SocketAddrV4},
};
use byteorder::{BigEndian, ByteOrder};
use bytes::{BufMut, BytesMut};
use thiserror::Error;
use t... | (&self) -> usize {
let mut s = 1 + 1 + 2 + 4 + self.user_id.len() + 1; // USERID.LEN + NULL
if let Address::DomainNameAddress(ref dname, _) = self.dst {
s += dname.len() + 1;
}
s
}
}
/// Handshake Response
///
/// ```plain
/// +----+----+----+----+----+----+-... | serialized_len | identifier_name |
socks4.rs | //! Socks4a Protocol Definition
//!
//! <http://ftp.icm.edu.pl/packages/socks/socks4/SOCKS4.protocol>
#![allow(dead_code)]
use std::{
fmt,
io::{self, ErrorKind},
net::{Ipv4Addr, SocketAddr, SocketAddrV4},
};
use byteorder::{BigEndian, ByteOrder};
use bytes::{BufMut, BytesMut};
use thiserror::Error;
use t... |
/// Length in bytes
#[inline]
pub fn serialized_len(&self) -> usize {
1 + 1 + 2 + 4
}
}
/// SOCKS 4/4a Error
#[derive(Error, Debug)]
pub enum Error {
// I/O Error
#[error("{0}")]
IoError(#[from] io::Error),
#[error("host must be UTF-8 encoding")]
AddressHostInvalidEncoding... | {
let HandshakeResponse { ref cd } = *self;
buf.put_slice(&[
// VN: Result Code's version, must be 0
0x00,
// CD: Result Code
cd.as_u8(),
// DSTPORT: Ignored
0x00,
0x00,
// DSTIP: Ignored
0x00,
... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.