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 |
|---|---|---|---|---|
issue-42467.rs | // Copyright 2017 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 ... | {} | identifier_body | |
no_0079_word_search.rs | pub fn exist(board: Vec<Vec<char>>, word: String) -> bool {
let m = board.len();
if m == 0 {
return false;
}
let n = board[0].len();
let mut marked = vec![vec![false; n]; m];
let directions = vec![
(-1, 0), // 上
(0, 1), // 右
(1, 0), // 下
(0, -1), // 左
... | word_idx == word.len() - 1 {
// 匹配完了
return true;
}
marked[board_x][board_y] = true;
// 当前匹配上了,再匹配下一个,可选的是相邻的四个位置
for (dx, dy) in directions {
let (x, y) = (board_x as isize + *dx, board_y as isize + *dy);
if 0 <= x && x < m as isize && 0 <= y && y < n as isize {
... | return false;
}
if | conditional_block |
no_0079_word_search.rs | pub fn exist(board: Vec<Vec<char>>, word: String) -> bool {
let m = board.len();
if m == 0 {
return false;
}
let n = board[0].len();
let mut marked = vec![vec![false; n]; m];
let directions = vec![
(-1, 0), // 上
(0, 1), // 右
(1, 0), // 下
(0, -1), // 左
... | &board,
m,
n,
word.as_bytes(),
0,
i,
j,
&mut marked,
&directions,
) {
return true;
}
}
}
false
}
fn match_word(
bo... | if match_word( | random_line_split |
no_0079_word_search.rs | pub fn exist(board: Vec<Vec<char>>, word: String) -> bool {
let m = board.len();
if m == 0 {
return false;
}
let n = board[0].len();
let mut marked = vec![vec![false; n]; m];
let directions = vec![
(-1, 0), // 上
(0, 1), // 右
(1, 0), // 下
(0, -1), // 左
... | S'],
vec!['A', 'D', 'E', 'E'],
];
assert_eq!(exist(board.clone(), "ABCCED".to_owned()), true);
assert_eq!(exist(board.clone(), "SEE".to_owned()), true);
assert_eq!(exist(board.clone(), "ABCB".to_owned()), false);
}
}
| F', 'C', ' | identifier_name |
no_0079_word_search.rs | pub fn exist(board: Vec<Vec<char>>, word: String) -> bool | m,
n,
word.as_bytes(),
0,
i,
j,
&mut marked,
&directions,
) {
return true;
}
}
}
false
}
fn mat
ch_word(
board: &Vec<Vec<char>>,
... | {
let m = board.len();
if m == 0 {
return false;
}
let n = board[0].len();
let mut marked = vec![vec![false; n]; m];
let directions = vec![
(-1, 0), // 上
(0, 1), // 右
(1, 0), // 下
(0, -1), // 左
];
for i in 0..m {
for j in 0..n {
... | identifier_body |
task-comm-11.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | {
let (tx, rx) = channel();
let _child = Thread::spawn(move|| {
start(&tx)
});
let _tx = rx.recv().unwrap();
} | identifier_body | |
task-comm-11.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | // except according to those terms.
use std::sync::mpsc::{channel, Sender};
use std::thread::Thread;
fn start(tx: &Sender<Sender<int>>) {
let (tx2, _rx) = channel();
tx.send(tx2).unwrap();
}
pub fn main() {
let (tx, rx) = channel();
let _child = Thread::spawn(move|| {
start(&tx)
});
l... | // 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 | random_line_split |
task-comm-11.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (tx: &Sender<Sender<int>>) {
let (tx2, _rx) = channel();
tx.send(tx2).unwrap();
}
pub fn main() {
let (tx, rx) = channel();
let _child = Thread::spawn(move|| {
start(&tx)
});
let _tx = rx.recv().unwrap();
}
| start | identifier_name |
ili9341.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.o... |
fn do_pixel(&self, x: u32, y: u32, color: u16) {
self.set_col(x as u16, x as u16);
self.set_page(y as u16, y as u16);
self.send_cmd(0x2c);
self.send_data(color);
}
}
impl<'a, S: Spi, T: Timer, P: Gpio> LCD for ILI9341<'a, S, T, P> {
fn clear(&self) {
self.do_clear();
}
fn flush(&self) {... | {
self.set_col(0, 239);
self.set_page(0, 319);
self.send_cmd(0x2c);
self.dc.set_high();
self.cs.set_low();
for _ in range(0usize, 38400) {
self.spi.transfer(0);
self.spi.transfer(0);
self.spi.transfer(0);
self.spi.transfer(0);
}
self.cs.set_high();
} | identifier_body |
ili9341.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.o... |
}
true
}
fn set_power_control_a(&self) {
self.send_cmd(0xcb);
self.write_data(0x39);
self.write_data(0x2c);
self.write_data(0x00);
self.write_data(0x34); // REG_VD = 0b100 = Vcore 1.6V
self.write_data(0x02); // VBC = 0b010 = DDVDH 5.6V
}
fn set_power_control_b(&self) {
... | {
return false;
} | conditional_block |
ili9341.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.o... | (&self) {
self.do_clear();
}
fn flush(&self) {}
fn pixel(&self, x: u32, y: u32, color: u16) {
self.do_pixel(x, y, color);
}
}
impl<'a, S: Spi, T: Timer, P: Gpio> CharIO for ILI9341<'a, S, T, P> {
fn putc(&self, _: char) {
// TODO(farcaller): implement
}
}
| clear | identifier_name |
ili9341.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.o... | self.write_data(0x28); // VCOML = -1.5V
}
fn everything_else(&self) {
self.send_cmd(0xC7);
self.write_data(0x86);
self.send_cmd(0x36);
self.write_data(0x48);
self.send_cmd(0x3A);
self.write_data(0x55);
self.send_cmd(0xB1);
self.write_data(0x00);
self.write_data(0x18);
... | random_line_split | |
bayesian.rs | // Copyright 2016 Johannes Köster.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.
//! Utilities for Bayesian statistics.
use itertools::Itertools;
use ordered_float::OrderedFloat;
use stats::LogProb;
... | let peps = [
LogProb(0.1f64.ln()),
LogProb::ln_zero(),
LogProb(0.25f64.ln()),
];
let fdrs = expected_fdr(&peps);
println!("{:?}", fdrs);
assert_relative_eq!(*fdrs[1], *LogProb::ln_zero());
assert_relative_eq!(*fdrs[0], *LogProb(0.05f64... | identifier_body | |
bayesian.rs | // Copyright 2016 Johannes Köster.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.
//! Utilities for Bayesian statistics.
use itertools::Itertools;
use ordered_float::OrderedFloat;
use stats::LogProb;
... | eps: &[LogProb]) -> Vec<LogProb> {
// sort indices
let sorted_idx =
(0..peps.len()).sorted_by(|&i, &j| OrderedFloat(*peps[i]).cmp(&OrderedFloat(*peps[j])));
// estimate FDR
let mut expected_fdr = vec![LogProb::ln_zero(); peps.len()];
for (i, expected_fp) in LogProb::ln_cumsum_exp(sorted_idx.... | pected_fdr(p | identifier_name |
bayesian.rs | // Copyright 2016 Johannes Köster.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.
//! Utilities for Bayesian statistics.
use itertools::Itertools;
use ordered_float::OrderedFloat;
use stats::LogProb;
... |
assert_relative_eq!(*fdrs[1], *LogProb::ln_zero());
assert_relative_eq!(*fdrs[0], *LogProb(0.05f64.ln()));
assert_relative_eq!(*fdrs[2], *LogProb((0.35 / 3.0f64).ln()));
}
} | LogProb::ln_zero(),
LogProb(0.25f64.ln()),
];
let fdrs = expected_fdr(&peps);
println!("{:?}", fdrs); | random_line_split |
bayesian.rs | // Copyright 2016 Johannes Köster.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.
//! Utilities for Bayesian statistics.
use itertools::Itertools;
use ordered_float::OrderedFloat;
use stats::LogProb;
... | lse {
LogProb::ln_one()
};
}
expected_fdr
}
#[cfg(test)]
mod tests {
use super::*;
use stats::LogProb;
#[test]
fn test_expected_fdr() {
let peps = [
LogProb(0.1f64.ln()),
LogProb::ln_zero(),
LogProb(0.25f64.ln()),
];
... | fdr
} e | conditional_block |
decoder.rs | use std::io::{Error, ErrorKind, Read, Result};
use std::ptr;
use super::liblz4::*;
use libc::size_t;
const BUFFER_SIZE: usize = 32 * 1024;
struct DecoderContext {
c: LZ4FDecompressionContext,
}
pub struct Decoder<R> {
c: DecoderContext,
r: R,
buf: Box<[u8]>,
pos: usize,
len: usize,
next: ... | }
assert_eq!(expected, actual);
finish_decode(decoder);
}
}
| {
let mut encoder = EncoderBuilder::new().level(1).build(Vec::new()).unwrap();
let mut expected = Vec::new();
let mut rnd: u32 = 42;
for _ in 0..1027 * 1023 * 7 {
expected.push((rnd & 0xFF) as u8);
rnd = ((1664525 as u64) * (rnd as u64) + (1013904223 as u64)) as u... | identifier_body |
decoder.rs | use std::io::{Error, ErrorKind, Read, Result};
use std::ptr;
use super::liblz4::*;
use libc::size_t;
const BUFFER_SIZE: usize = 32 * 1024;
struct DecoderContext {
c: LZ4FDecompressionContext,
}
pub struct Decoder<R> {
c: DecoderContext,
r: R,
buf: Box<[u8]>,
pos: usize,
len: usize,
next: ... | finish_decode(decoder);
}
#[test]
fn test_decoder_smoke() {
let mut encoder = EncoderBuilder::new().level(1).build(Vec::new()).unwrap();
let mut expected = Vec::new();
expected.write(b"Some data").unwrap();
encoder.write(&expected[..4]).unwrap();
encoder.writ... | random_line_split | |
decoder.rs | use std::io::{Error, ErrorKind, Read, Result};
use std::ptr;
use super::liblz4::*;
use libc::size_t;
const BUFFER_SIZE: usize = 32 * 1024;
struct DecoderContext {
c: LZ4FDecompressionContext,
}
pub struct Decoder<R> {
c: DecoderContext,
r: R,
buf: Box<[u8]>,
pos: usize,
len: usize,
next: ... | () {
let mut encoder = EncoderBuilder::new().level(1).build(Vec::new()).unwrap();
let mut expected = Vec::new();
let mut rnd: u32 = 42;
for _ in 0..1027 * 1023 * 7 {
expected.push((rnd & 0xFF) as u8);
rnd = ((1664525 as u64) * (rnd as u64) + (1013904223 as u64)) a... | test_decoder_random | identifier_name |
show.rs | use actix_identity::Identity;
use actix_web::{error, get, web, Error, HttpResponse, Result};
use askama::Template;
use crate::DbPool;
use super::actions;
use crate::models::Like;
use crate::uri_helpers::*;
use crate::utils as filters;
#[derive(Template)]
#[template(path = "likes/show.html.jinja")]
struct Show<'a> {... |
Ok(HttpResponse::Ok().content_type("text/html; charset=utf-8").body(s))
}
| {
let like = web::block(move || {
let conn = pool.get()?;
actions::get_like(id.into_inner(), &conn)
})
.await?
.map_err(|e| error::ErrorInternalServerError(format!("Database error: {}", e)))?;
let s = Show {
title: Some(&format!("♥ {}", like.in_reply_to)),
page_type:... | identifier_body |
show.rs | use actix_identity::Identity;
use actix_web::{error, get, web, Error, HttpResponse, Result};
use askama::Template;
use crate::DbPool;
use super::actions;
use crate::models::Like;
use crate::uri_helpers::*;
use crate::utils as filters; |
#[derive(Template)]
#[template(path = "likes/show.html.jinja")]
struct Show<'a> {
title: Option<&'a str>,
page_type: Option<&'a str>,
page_image: Option<&'a str>,
body_id: Option<&'a str>,
logged_in: bool,
like: &'a Like,
index: bool,
atom: bool,
}
#[get("/{id}")]
pub async fn show(id... | random_line_split | |
show.rs | use actix_identity::Identity;
use actix_web::{error, get, web, Error, HttpResponse, Result};
use askama::Template;
use crate::DbPool;
use super::actions;
use crate::models::Like;
use crate::uri_helpers::*;
use crate::utils as filters;
#[derive(Template)]
#[template(path = "likes/show.html.jinja")]
struct | <'a> {
title: Option<&'a str>,
page_type: Option<&'a str>,
page_image: Option<&'a str>,
body_id: Option<&'a str>,
logged_in: bool,
like: &'a Like,
index: bool,
atom: bool,
}
#[get("/{id}")]
pub async fn show(ident: Identity, pool: web::Data<DbPool>, id: web::Path<i32>) -> Result<HttpRe... | Show | identifier_name |
error.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 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 ... | } | } | random_line_split |
helper_each.rs | use serialize::json::{Json, ToJson};
use helpers::{HelperDef};
use registry::{Registry};
use context::{Context};
use render::{Renderable, RenderContext, RenderError, render_error, Helper};
#[derive(Clone, Copy)]
pub struct EachHelper;
impl HelperDef for EachHelper{
fn | (&self, c: &Context, h: &Helper, r: &Registry, rc: &mut RenderContext) -> Result<(), RenderError> {
let param = h.param(0);
if param.is_none() {
return Err(render_error("Param not found for helper \"each\""));
}
let template = h.template();
match template {
... | call | identifier_name |
helper_each.rs | use serialize::json::{Json, ToJson};
use helpers::{HelperDef};
use registry::{Registry};
use context::{Context};
use render::{Renderable, RenderContext, RenderError, render_error, Helper};
#[derive(Clone, Copy)]
pub struct EachHelper;
impl HelperDef for EachHelper{
fn call(&self, c: &Context, h: &Helper, r: &Reg... | for i in 0..len {
rc.set_local_var("@first".to_string(), (i == 0usize).to_json());
rc.set_local_var("@last".to_string(), (i == len - 1).to_json());
rc.set_local_var("@index".to_string(), i.to_json());
... | let len = list.len(); | random_line_split |
helper_each.rs | use serialize::json::{Json, ToJson};
use helpers::{HelperDef};
use registry::{Registry};
use context::{Context};
use render::{Renderable, RenderContext, RenderError, render_error, Helper};
#[derive(Clone, Copy)]
pub struct EachHelper;
impl HelperDef for EachHelper{
fn call(&self, c: &Context, h: &Helper, r: &Reg... | ,
_ => {
Err(render_error("Param is not an iteratable."))
}
};
rc.set_path(path);
rc.demote_local_vars();
rendered
},
None => Ok(())
}
}
}
pub static EACH_... | {
let mut first:bool = true;
for k in obj.keys() {
rc.set_local_var("@first".to_string(), first.to_json());
if first {
first = false;
}
... | conditional_block |
context.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Data needed by the layout task.
#![allow(unsafe_code)]
use css::matching::{ApplicableDeclarationsCache, Styl... |
pub fn heap_size_of_local_context() -> usize {
LOCAL_CONTEXT_KEY.with(|r| {
r.borrow().clone().map_or(0, |context| context.heap_size_of_children())
})
}
fn create_or_get_local_context(shared_layout_context: &SharedLayoutContext)
-> Rc<LocalLayoutContext> {
LOCAL_CONT... | }
thread_local!(static LOCAL_CONTEXT_KEY: RefCell<Option<Rc<LocalLayoutContext>>> = RefCell::new(None)); | random_line_split |
context.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Data needed by the layout task.
#![allow(unsafe_code)]
use css::matching::{ApplicableDeclarationsCache, Styl... | (&self) -> usize {
self.font_context.heap_size_of_children()
}
}
thread_local!(static LOCAL_CONTEXT_KEY: RefCell<Option<Rc<LocalLayoutContext>>> = RefCell::new(None));
pub fn heap_size_of_local_context() -> usize {
LOCAL_CONTEXT_KEY.with(|r| {
r.borrow().clone().map_or(0, |context| context.hea... | heap_size_of_children | identifier_name |
mod.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/. */
//! The implementation of the DOM.
//!
//! The DOM is comprised of interfaces (defined by specifications using
//... | pub mod xrrigidtransform;
pub mod xrsession;
pub mod xrsessionevent;
pub mod xrspace;
pub mod xrtest;
pub mod xrview;
pub mod xrviewerpose;
pub mod xrviewport;
pub mod xrwebgllayer; | pub mod xrinputsourcearray;
pub mod xrinputsourceevent;
pub mod xrpose;
pub mod xrreferencespace;
pub mod xrrenderstate; | random_line_split |
mod.rs | #[allow(dead_code)] // FIXME
pub mod environment;
#[macro_use]
pub mod logger;
#[macro_use]
pub mod term;
#[cfg(test)]
pub mod test;
pub mod table;
#[macro_export] //TODO move to more relevant place
macro_rules! update_json_map_opt_key {
($map:expr, $key:expr, $val:expr) => (match $val {
Some(val) => { $ma... | self::execute,
Some(self::cleanup),
)
}
)
}
#[macro_export] //TODO move to more relevant place
macro_rules! unwrap_or_return {
($result:expr, $err:expr) => {
match $result {
Some(res) => res,
None => return $err
};
... | macro_rules! command_with_cleanup {
($meta:expr) => (
pub fn new() -> Command {
Command::new(
$meta, | random_line_split |
mod.rs | use std::cmp::Ordering;
use std::fmt;
use perlin_core::index::posting::{Posting, PostingIterator, PostingDecoder};
use perlin_core::utils::seeking_iterator::{PeekableSeekable, SeekingIterator};
use perlin_core::utils::progress::Progress;
pub use query::operators::{And, Funnel, Combinator};
#[macro_use]
pub mod query... | (&mut self, other: &Posting) -> Option<Posting> {
match *self {
Operand::Term(_, ref mut decoder, _, _) => decoder.next_seek(other),
}
}
}
impl<'a> Operand<'a> {
pub fn weight(&self) -> Weight {
match *self {
Operand::Term(w, _, _, _) => w,
}
}
p... | next_seek | identifier_name |
mod.rs | use std::cmp::Ordering;
use std::fmt;
use perlin_core::index::posting::{Posting, PostingIterator, PostingDecoder};
use perlin_core::utils::seeking_iterator::{PeekableSeekable, SeekingIterator};
use perlin_core::utils::progress::Progress;
pub use query::operators::{And, Funnel, Combinator};
#[macro_use]
pub mod query... | match *self {
Operand::Term(weight, _, ref term, ref field) => {
write!(f,
"Querying term {:?} on field {:?} with weight {:?}",
term,
field,
weight)
}
}
}
}
impl<'a> I... | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | random_line_split |
mod.rs | use std::cmp::Ordering;
use std::fmt;
use perlin_core::index::posting::{Posting, PostingIterator, PostingDecoder};
use perlin_core::utils::seeking_iterator::{PeekableSeekable, SeekingIterator};
use perlin_core::utils::progress::Progress;
pub use query::operators::{And, Funnel, Combinator};
#[macro_use]
pub mod query... |
if new_current_operands.is_empty() || (curr_weight.0 < (0.01 * self.max_weight.0)) {
return None;
}
// TODO: Sort current operands by length(!)
self.counter += 1;
self.cu... | {
loop {
// If we have steps left
if let Some(mut current_operands) = self.current_operands.take() {
// NOTE: This is filthy fix as soon as nonliteral borrowing lands
// Get next entry from step
let next = And::next(&mut current_operands);
... | identifier_body |
mod.rs | use std::cmp::Ordering;
use std::fmt;
use perlin_core::index::posting::{Posting, PostingIterator, PostingDecoder};
use perlin_core::utils::seeking_iterator::{PeekableSeekable, SeekingIterator};
use perlin_core::utils::progress::Progress;
pub use query::operators::{And, Funnel, Combinator};
#[macro_use]
pub mod query... |
}
if new_current_operands.is_empty() || (curr_weight.0 < (0.01 * self.max_weight.0)) {
return None;
}
// TODO: Sort current operands by length(!)
self.counter += 1;
... | {
curr_weight = Weight(curr_weight.0 + op.inner().weight().0);
new_current_operands.push(op.clone());
} | conditional_block |
arc-rw-read-mode-shouldnt-escape.rs | //
// 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 mod std;
... | // 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. | random_line_split | |
arc-rw-read-mode-shouldnt-escape.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let x = ~arc::RWARC(1);
let mut y = None;
do x.write_downgrade |write_mode| {
y = Some(x.downgrade(write_mode));
//~^ ERROR cannot infer an appropriate lifetime
}
// Adding this line causes a method unification failure instead
// do (&option::unwrap(y)).read |state| { assert!(*... | identifier_body | |
arc-rw-read-mode-shouldnt-escape.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let x = ~arc::RWARC(1);
let mut y = None;
do x.write_downgrade |write_mode| {
y = Some(x.downgrade(write_mode));
//~^ ERROR cannot infer an appropriate lifetime
}
// Adding this line causes a method unification failure instead
// do (&option::unwrap(y)).read |state| { assert... | main | identifier_name |
mioco_ws.rs | use serde_json;
use serde_json::Value;
use std::sync::atomic::{AtomicUsize, Ordering};
use mioco;
use ws;
const NULL_PAYLOAD: &'static Value = &Value::Null;
pub struct | <'a> {
ws: ws::Sender,
count: &'a AtomicUsize,
}
impl<'a> BenchHandler<'a> {
pub fn run(address: &str, port: &str, threads: usize) {
let address = String::from(address);
let port = String::from(port);
mioco::start_threads(threads, move|| {
let count = AtomicUsize::new(0... | BenchHandler | identifier_name |
mioco_ws.rs | use serde_json;
use serde_json::Value;
use std::sync::atomic::{AtomicUsize, Ordering};
use mioco;
use ws;
const NULL_PAYLOAD: &'static Value = &Value::Null;
pub struct BenchHandler<'a> {
ws: ws::Sender,
count: &'a AtomicUsize,
}
impl<'a> BenchHandler<'a> {
pub fn run(address: &str, port: &str, threads: u... |
});
Ok(())
}
fn on_open(&mut self, _: ws::Handshake) -> ws::Result<()> {
self.count.fetch_add(1, Ordering::SeqCst);
Ok(())
}
fn on_close(&mut self, _: ws::CloseCode, _: &str) {
self.count.fetch_sub(1, Ordering::SeqCst);
}
}
| {
if let Some(&Value::String(ref s)) = obj.get("type") {
if s == "echo" {
ws.send(msg).unwrap();
} else if s == "broadcast" {
ws.broadcast(msg).unwrap();
ws.send(format!(r#"{{"type":"broadcast... | conditional_block |
mioco_ws.rs | use serde_json;
use serde_json::Value;
use std::sync::atomic::{AtomicUsize, Ordering};
use mioco;
use ws;
const NULL_PAYLOAD: &'static Value = &Value::Null;
pub struct BenchHandler<'a> {
ws: ws::Sender,
count: &'a AtomicUsize,
}
impl<'a> BenchHandler<'a> {
pub fn run(address: &str, port: &str, threads: u... | Ok(())
}
fn on_open(&mut self, _: ws::Handshake) -> ws::Result<()> {
self.count.fetch_add(1, Ordering::SeqCst);
Ok(())
}
fn on_close(&mut self, _: ws::CloseCode, _: &str) {
self.count.fetch_sub(1, Ordering::SeqCst);
}
}
| {
// would love to not preload the atomic but the 'static bound
// on the execute function demands it :(
let ws = self.ws.clone();
let count = self.count.load(Ordering::SeqCst);
mioco::spawn(move|| {
if let Ok(Ok(Value::Object(obj))) = msg.as_text().map(serde_json::f... | identifier_body |
mioco_ws.rs | use serde_json;
use serde_json::Value;
use std::sync::atomic::{AtomicUsize, Ordering};
use mioco;
use ws;
const NULL_PAYLOAD: &'static Value = &Value::Null;
pub struct BenchHandler<'a> {
ws: ws::Sender,
count: &'a AtomicUsize,
}
impl<'a> BenchHandler<'a> {
pub fn run(address: &str, port: &str, threads: u... |
fn on_close(&mut self, _: ws::CloseCode, _: &str) {
self.count.fetch_sub(1, Ordering::SeqCst);
}
} | random_line_split | |
lib.rs | //! # Handlebars for Iron
//!
//! This library combines [Handlebars templating library](https://github.com/sunng87/handlebars-rust) and [Iron web framework](http://ironframework.io) together. It gives you a `HandlebarsEngine` as Iron `AfterMiddleware`, so you can render your data with specified handlebars template.
//!... | extern crate log;
pub use self::middleware::Template;
pub use self::middleware::HandlebarsEngine;
#[cfg(feature = "watch")]
pub use self::watch::Watchable;
mod middleware;
#[cfg(feature = "watch")]
mod watch; | extern crate plugin;
extern crate walker;
#[cfg(feature = "watch")]
extern crate notify;
#[macro_use] | random_line_split |
libseat.rs | //!
//! Implementation of the [`Session`](::backend::session::Session) trait through the libseat.
//!
//! This requires libseat to be available on the system.
use libseat::{Seat, SeatEvent};
use std::{
cell::RefCell,
collections::HashMap,
os::unix::io::RawFd,
path::Path,
rc::{Rc, Weak},
sync::{... | (&self) -> Signaler<SessionSignal> {
self.signaler.clone()
}
}
impl EventSource for LibSeatSessionNotifier {
type Event = ();
type Metadata = ();
type Ret = ();
fn process_events<F>(&mut self, readiness: Readiness, token: Token, _: F) -> std::io::Result<PostAction>
where
F: FnM... | signaler | identifier_name |
libseat.rs | //!
//! Implementation of the [`Session`](::backend::session::Session) trait through the libseat.
//!
//! This requires libseat to be available on the system.
use libseat::{Seat, SeatEvent};
use std::{
cell::RefCell,
collections::HashMap,
os::unix::io::RawFd,
path::Path,
rc::{Rc, Weak},
sync::{... | SessionLost,
}
impl AsErrno for Error {
fn as_errno(&self) -> Option<i32> {
match self {
&Self::FailedToOpenSession(errno)
| &Self::FailedToOpenDevice(errno)
| &Self::FailedToCloseDevice(errno)
| &Self::FailedToChangeVt(errno) => Some(errno as i32),
... | random_line_split | |
libseat.rs | //!
//! Implementation of the [`Session`](::backend::session::Session) trait through the libseat.
//!
//! This requires libseat to be available on the system.
use libseat::{Seat, SeatEvent};
use std::{
cell::RefCell,
collections::HashMap,
os::unix::io::RawFd,
path::Path,
rc::{Rc, Weak},
sync::{... | ;
close(fd).unwrap();
out
} else {
Err(Error::SessionLost)
}
}
fn change_vt(&mut self, vt: i32) -> Result<(), Self::Error> {
if let Some(session) = self.internal.upgrade() {
debug!(session.logger, "Session switch: {:?}", vt);
... | {
Ok(())
} | conditional_block |
libseat.rs | //!
//! Implementation of the [`Session`](::backend::session::Session) trait through the libseat.
//!
//! This requires libseat to be available on the system.
use libseat::{Seat, SeatEvent};
use std::{
cell::RefCell,
collections::HashMap,
os::unix::io::RawFd,
path::Path,
rc::{Rc, Weak},
sync::{... | channel::Event::Closed => {
// Tx is stored inside of Seat, and Rc<Seat> is stored in LibSeatSessionNotifier so this is unreachable
}
})
}
fn register(&mut self, poll: &mut Poll, factory: &mut TokenFactory) -> std::io::Result<()> {
self.rx.register(poll,... | {
if token == self.token {
self.internal.seat.borrow_mut().dispatch(0).unwrap();
}
let internal = &self.internal;
let signaler = &self.signaler;
self.rx.process_events(readiness, token, |event, _| match event {
channel::Event::Msg(event) => match event {... | identifier_body |
text.rs | "WAT: can't coalesce non-text nodes in flush_clump_to_list()!");
out_fragments.push(self.clump.pop_front().unwrap());
return false
}
}
// Concatenate all of the transformed strings together, saving the new character indices.
... | e_height_from_style(st | identifier_name | |
text.rs |
let selected = match selection {
Some(range) => range.contains(ByteIndex(byte_index as isize)),
None => false
};
// Now, if necessary, flush the mapping we were building up.
let flush_run =... | fn identifier(font: &Option<FontRef>) -> Option<Atom> {
font.as_ref().map(|f| f.borrow().identifier()) | random_line_split | |
text.rs | if run_info.bidi_level.is_rtl() {
options.flags.insert(ShapingFlags::RTL_FLAG);
}
// If no font is found (including fallbacks), there's no way we can render.
let font =
run_info.font
.or_else(||... | let original = string[first_character_position..].to_owned();
string.truncate(first_character_position);
let mut capitalize_next_letter = is_first_run || last_whitespace;
for character in original.chars() {
// FIXME(#4311, pcwalton): Should be the CSS/Unic... | conditional_block | |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Servo, the mighty web browser engine from the future.
//!
//! This is a very simple library that wires all of ... | (window: Rc<Window>) -> Browser<Window> {
// Global configuration options, parsed from the command line.
let opts = opts::get();
// Get both endpoints of a special channel for communication between
// the client window and the compositor. This channel is unique because
// messa... | new | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Servo, the mighty web browser engine from the future.
//!
//! This is a very simple library that wires all of ... | #[cfg(not(target_os = "windows"))]
use gaol::sandbox::{ChildSandbox, ChildSandboxMethods};
use gfx::font_cache_thread::FontCacheThread;
use ipc_channel::ipc::{self, IpcSender};
use log::{Log, LogMetadata, LogRecord};
use net::image_cache_thread::new_image_cache_thread;
use net::resource_thread::new_resource_threads;
us... | use env_logger::Logger as EnvLogger; | random_line_split |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Servo, the mighty web browser engine from the future.
//!
//! This is a very simple library that wires all of ... |
}
// The compositor coordinates with the client window to create the final
// rendered page and display it somewhere.
let compositor = IOCompositor::create(window, InitialCompositorState {
sender: compositor_proxy,
receiver: compositor_receiver,
cons... | {
webdriver(port, constellation_chan.clone());
} | conditional_block |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Servo, the mighty web browser engine from the future.
//!
//! This is a very simple library that wires all of ... |
pub fn repaint_synchronously(&mut self) {
self.compositor.repaint_synchronously()
}
pub fn pinch_zoom_level(&self) -> f32 {
self.compositor.pinch_zoom_level()
}
pub fn request_title_for_main_frame(&self) {
self.compositor.title_for_main_frame()
}
pub fn setup_log... | {
self.compositor.handle_events(events)
} | identifier_body |
transaction.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program is free software: you can redistribute it
// and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any
// later version.
// Th... |
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
use bytes::Bytes;
use libproto::blockchain::SignedTransaction as ProtoSignedTransaction;
use libproto::request::FullTransaction as PTransaction;
use protobuf::Message;
use util... | // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the GNU General Public License for more details. | random_line_split |
transaction.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program is free software: you can redistribute it
// and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any
// later version.
// Th... | {
pub hash: H256,
pub content: Bytes,
}
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct RpcTransaction {
pub hash: H256,
pub content: Bytes,
#[serde(rename = "blockNumber")]
pub block_number: U256,
#[serde(rename = "blockHash")]
pub block_hash: H256,
pub index: U256,... | FullTransaction | identifier_name |
transaction.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program is free software: you can redistribute it
// and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any
// later version.
// Th... |
}
impl From<ProtoSignedTransaction> for TransactionHash {
fn from(stx: ProtoSignedTransaction) -> Self {
TransactionHash { hash: H256::from_slice(stx.get_tx_hash()) }
}
}
| {
FullTransaction {
hash: H256::from_slice(stx.get_tx_hash()),
content: Bytes(stx.get_transaction_with_sig().get_transaction().write_to_bytes().unwrap()),
}
} | identifier_body |
app_chooser.rs | // Copyright 2013-2015, The Rust-GNOME Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use glib::translate::{from_glib_none};
use ffi;
use cast::GTK_APP_CHOOSER;
pub trait App... | (&self) -> () {
unsafe { ffi::gtk_app_chooser_refresh(GTK_APP_CHOOSER(self.unwrap_widget())) }
}
}
| refresh | identifier_name |
app_chooser.rs | // Copyright 2013-2015, The Rust-GNOME Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use glib::translate::{from_glib_none};
use ffi;
use cast::GTK_APP_CHOOSER;
pub trait App... |
}
| {
unsafe { ffi::gtk_app_chooser_refresh(GTK_APP_CHOOSER(self.unwrap_widget())) }
} | identifier_body |
app_chooser.rs | // Copyright 2013-2015, The Rust-GNOME Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
|
pub trait AppChooserTrait: ::WidgetTrait {
fn get_app_info(&self) -> Option<::AppInfo> {
let tmp_pointer = unsafe { ffi::gtk_app_chooser_get_app_info(GTK_APP_CHOOSER(self.unwrap_widget())) };
if tmp_pointer.is_null() {
None
} else {
Some(::FFIWidget::wrap_widget(tmp... | use glib::translate::{from_glib_none};
use ffi;
use cast::GTK_APP_CHOOSER; | random_line_split |
app_chooser.rs | // Copyright 2013-2015, The Rust-GNOME Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use glib::translate::{from_glib_none};
use ffi;
use cast::GTK_APP_CHOOSER;
pub trait App... | else {
Some(::FFIWidget::wrap_widget(tmp_pointer as *mut ffi::GtkWidget))
}
}
fn get_content_info(&self) -> Option<String> {
unsafe {
from_glib_none(
ffi::gtk_app_chooser_get_content_type(GTK_APP_CHOOSER(self.unwrap_widget())))
}
}
fn re... | {
None
} | conditional_block |
main.rs | use std::io;
fn stdinln_i32() -> i32 {
// 이 함수는 하나의 줄을 stdin으로 받아 단 하나의 integer를 리턴합니다.
let mut buffer = String::new();
std::io::stdin().read_line(&mut buffer).expect("Failed to read stdin.");
buffer.trim().parse::<i32>().unwrap()
}
fn stdinln_vec_i32() -> Vec<i32> {
// 이 함수는 하나의 줄을 stdin으로 받아 여러개의 integer 을 vec... | org/std/primitive.array.html
fn main() {
let nr_tel = stdinln_i32() as usize;
let mut tels: Vec<i32> = Vec::new();
for i in 0..nr_tel {
tels.push(stdinln_i32());
}
let mut problem = TelBox::new_from_vec_i32(tels, nr_tel);
// TelBox::get_most()를 완성해주세요!
println!("{:04}", problem.get_most());
} | i in 1..10000 {
if self.cntbox[i] > self.cntbox[biggest] {
biggest = i;
}else if self.cntbox[i] == self.cntbox[biggest] {
if i < biggest {
biggest = i;
}
}
}
biggest as u32
// End of TelBox::get_most()
}
}
// Rust에서는 array사용시 컴파일시간내에서만 결정되어야한다.
// 이 문제같은 경우 0~10000이라는 조건이 컴파일 시간이전에 결정... | identifier_body |
main.rs | use std::io;
fn stdinln_i32() -> i32 {
// 이 함수는 하나의 줄을 stdin으로 받아 단 하나의 integer를 리턴합니다.
let mut buffer = String::new();
std::io::stdin().read_line(&mut buffer).expect("Failed to read stdin.");
buffer.trim().parse::<i32>().unwrap()
}
fn stdinln_vec_i32() -> Vec<i32> {
// 이 함수는 하나의 줄을 stdin으로 받아 여러개의 integer 을 vec... | identifier_name | ||
main.rs | use std::io;
fn stdinln_i32() -> i32 {
// 이 함수는 하나의 줄을 stdin으로 받아 단 하나의 integer를 리턴합니다.
let mut buffer = String::new();
std::io::stdin().read_line(&mut buffer).expect("Failed to read stdin.");
buffer.trim().parse::<i32>().unwrap()
}
fn stdinln_vec_i32() -> Vec<i32> {
// 이 함수는 하나의 줄을 stdin으로 받아 여러개의 integer 을 vec... |
struct TelBox {
data: Vec<i32>,
nr_tel: usize,
cntbox: [u32; 10000], // 컴파일 시간내에 사이즈가 결정되는 어레이, Vector보다 빠르다
}
impl TelBox {
fn new_from_vec_i32(inputs: Vec<i32>, len: usize) -> TelBox {
TelBox{data:inputs, nr_tel:len, cntbox:[0; 10000]}
}
fn get_most(&mut self) -> u32 {
// TelBox::get_most() 를 완성해주세요!
f... | ret
} | random_line_split |
os.rs | use yaml_rust::{Yaml};
use yaml;
use regex::Regex;
///`OS` contains the operating system information from the user agent.
#[derive(Debug, PartialEq, Eq)]
pub struct OS {
pub family: String,
pub major: Option<String>,
pub minor: Option<String>,
pub patch: Option<String>,
pub patch_minor: Option<Stri... | {
pub regex: Regex,
pub family: Option<String>,
pub major: Option<String>,
pub minor: Option<String>,
pub patch: Option<String>,
pub patch_minor: Option<String>,
}
impl OSParser {
pub fn from_yaml(y: &Yaml) -> Option<OSParser> {
yaml::string_from_map(y, "regex")
.map... | OSParser | identifier_name |
os.rs | use yaml_rust::{Yaml};
use yaml;
use regex::Regex;
///`OS` contains the operating system information from the user agent.
#[derive(Debug, PartialEq, Eq)]
pub struct OS {
pub family: String,
pub major: Option<String>,
pub minor: Option<String>,
pub patch: Option<String>,
pub patch_minor: Option<Stri... | pub regex: Regex,
pub family: Option<String>,
pub major: Option<String>,
pub minor: Option<String>,
pub patch: Option<String>,
pub patch_minor: Option<String>,
}
impl OSParser {
pub fn from_yaml(y: &Yaml) -> Option<OSParser> {
yaml::string_from_map(y, "regex")
.map(|r... | }
#[derive(Debug)]
pub struct OSParser { | random_line_split |
fuse.rs | // Copyright 2021 lowRISC 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... |
}
impl Fuse for FuseController {
fn get_dev_id(&self) -> u64 {
((self.registers.dev_id0.get() as u64) << 32)
| (self.registers.dev_id1.get() as u64)
}
}
| {
FuseController {
registers: base_addr,
}
} | identifier_body |
fuse.rs | // Copyright 2021 lowRISC 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... |
const FUSE_BASE_ADDR: u32 = 0x4045_0000;
const FUSE_REGISTERS: StaticRef<Registers> =
unsafe { StaticRef::new(FUSE_BASE_ADDR as *const Registers) };
pub static mut FUSE: FuseController = FuseController::new(FUSE_REGISTERS);
/// Fuse Controller
pub struct FuseController {
registers: StaticRef<Registers>,
}
i... | (0x004c => _reserved004c),
(0x0448 => @END),
}
} | random_line_split |
fuse.rs | // Copyright 2021 lowRISC 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | (&self) -> u64 {
((self.registers.dev_id0.get() as u64) << 32)
| (self.registers.dev_id1.get() as u64)
}
}
| get_dev_id | identifier_name |
char_class.rs | /// Recognises an alphabetic character, `a-zA-Z`.
#[inline]
pub fn alpha(term: u8) -> bool {
term.is_ascii_alphabetic()
}
/// Recognises a decimal digit, `0-9`.
#[inline]
pub fn digit(term: u8) -> bool {
term.is_ascii_digit()
}
/// Recognises an alphanumeric character, `a-zA-Z0-9`.
#[inline]
pub fn alphanum(term: u... |
/// Recognises a hexadecimal digit, `0-9a-fA-F`.
#[inline]
pub fn hex_digit(term: u8) -> bool {
(0x30..=0x39).contains(&term) || (0x41..=0x46).contains(&term) || (0x61..=0x66).contains(&term)
}
/// Recognises an octal digit, `0-7`.
#[inline]
pub fn oct_digit(term: u8) -> bool {
(0x30..=0x37).contains(&term)
}
///... | {
term.is_ascii_alphanumeric()
} | identifier_body |
char_class.rs | /// Recognises an alphabetic character, `a-zA-Z`.
#[inline]
pub fn alpha(term: u8) -> bool {
term.is_ascii_alphabetic()
}
/// Recognises a decimal digit, `0-9`.
#[inline] | }
/// Recognises an alphanumeric character, `a-zA-Z0-9`.
#[inline]
pub fn alphanum(term: u8) -> bool {
term.is_ascii_alphanumeric()
}
/// Recognises a hexadecimal digit, `0-9a-fA-F`.
#[inline]
pub fn hex_digit(term: u8) -> bool {
(0x30..=0x39).contains(&term) || (0x41..=0x46).contains(&term) || (0x61..=0x66).contai... | pub fn digit(term: u8) -> bool {
term.is_ascii_digit() | random_line_split |
char_class.rs | /// Recognises an alphabetic character, `a-zA-Z`.
#[inline]
pub fn alpha(term: u8) -> bool {
term.is_ascii_alphabetic()
}
/// Recognises a decimal digit, `0-9`.
#[inline]
pub fn digit(term: u8) -> bool {
term.is_ascii_digit()
}
/// Recognises an alphanumeric character, `a-zA-Z0-9`.
#[inline]
pub fn alphanum(term: u... | (term: u8) -> bool {
(0x30..=0x39).contains(&term) || (0x41..=0x46).contains(&term) || (0x61..=0x66).contains(&term)
}
/// Recognises an octal digit, `0-7`.
#[inline]
pub fn oct_digit(term: u8) -> bool {
(0x30..=0x37).contains(&term)
}
/// Recognises a space or tab.
#[inline]
pub fn space(term: u8) -> bool {
term ... | hex_digit | identifier_name |
mod.rs | extern crate gtk;
mod glade;
mod handlers;
mod widgets;
use std::cell::{RefCell};
use gtk::prelude::*;
use gtk::{Window, WindowType};
use gtk::{Button, FileChooserDialog, Entry};
use std::sync::mpsc::{Sender, Receiver};
use std::sync::{Arc,Mutex};
use std::rc::Rc;
use std::clone::Clone;
use std::thread;
use castnow:... |
pub fn init(&self, self_rc: Rc<Self>, rx: Receiver<State>, tx: Sender<Command>) {
let mut channels = self_rc.channels.borrow_mut();
channels.rx = Some(rx);
channels.tx = Some(tx);
self.build_widgets();
self.attach_handlers(&self_rc);
self.start_rendering_timer(&sel... | {
Rc::new(AppState{
channels: RefCell::new(AppChannels::new()),
widgets: RefCell::new(AppWidgets::new()),
model: RefCell::new(AppModel::new())
})
} | identifier_body |
mod.rs | extern crate gtk;
mod glade;
mod handlers;
mod widgets;
use std::cell::{RefCell};
use gtk::prelude::*;
use gtk::{Window, WindowType};
use gtk::{Button, FileChooserDialog, Entry};
use std::sync::mpsc::{Sender, Receiver};
use std::sync::{Arc,Mutex};
use std::rc::Rc;
use std::clone::Clone;
use std::thread;
use castnow:... | {
state: State,
status: String,
playing: bool,
path: String,
is_dirty: bool
}
pub struct AppState {
channels: RefCell<AppChannels>,
widgets: RefCell<AppWidgets>,
model: RefCell<AppModel>
}
impl AppModel {
fn new() -> AppModel {
AppModel {
state: State::Initial,... | AppModel | identifier_name |
mod.rs | extern crate gtk;
mod glade;
mod handlers;
mod widgets;
use std::cell::{RefCell};
use gtk::prelude::*;
use gtk::{Window, WindowType};
use gtk::{Button, FileChooserDialog, Entry};
use std::sync::mpsc::{Sender, Receiver};
use std::sync::{Arc,Mutex};
use std::rc::Rc;
use std::clone::Clone;
use std::thread;
use castnow:... | model.state = state;
model.status = format!("{}", state);
}
}
//println!("Checking...");
//Update the UI to reflect any changes
if self_clone.model.borrow().is_dirty {
println!("Model dirty. Rendering... | //let's assume we also got some name/value pairs with enough info to locate our widget and render it
//Modifying the model and updating it must be separate scopes
let mut model = self_clone.model.borrow_mut(); | random_line_split |
mod.rs | extern crate gtk;
mod glade;
mod handlers;
mod widgets;
use std::cell::{RefCell};
use gtk::prelude::*;
use gtk::{Window, WindowType};
use gtk::{Button, FileChooserDialog, Entry};
use std::sync::mpsc::{Sender, Receiver};
use std::sync::{Arc,Mutex};
use std::rc::Rc;
use std::clone::Clone;
use std::thread;
use castnow:... |
//println!("Checking...");
//Update the UI to reflect any changes
if self_clone.model.borrow().is_dirty {
println!("Model dirty. Rendering...");
self_clone.render_dirty();
}
//So this will get invoked on every tim... | {
while let Ok(state) = rx.try_recv() {
println!("Received state in ui thread {:?}", state);
//let's assume we also got some name/value pairs with enough info to locate our widget and render it
//Modifying the model and upda... | conditional_block |
batch.rs | // #![feature(plugin)]
// #![plugin(clippy)]
extern crate cassandra_sys;
extern crate num;
|
struct Pair {
key: String,
value: String,
}
fn prepare_insert_into_batch<'a>(session: &mut CassSession) -> Result<&'a CassPrepared, CassError> {
unsafe {
let query = "INSERT INTO examples.pairs (key, value) VALUES (?,?)";
let future = &mut *cass_session_prepare(session, CString::new(query... | mod examples_util;
use examples_util::*;
use std::ffi::CString;
use cassandra_sys::*; | random_line_split |
batch.rs | // #![feature(plugin)]
// #![plugin(clippy)]
extern crate cassandra_sys;
extern crate num;
mod examples_util;
use examples_util::*;
use std::ffi::CString;
use cassandra_sys::*;
struct | {
key: String,
value: String,
}
fn prepare_insert_into_batch<'a>(session: &mut CassSession) -> Result<&'a CassPrepared, CassError> {
unsafe {
let query = "INSERT INTO examples.pairs (key, value) VALUES (?,?)";
let future = &mut *cass_session_prepare(session, CString::new(query).unwrap().a... | Pair | identifier_name |
batch.rs | // #![feature(plugin)]
// #![plugin(clippy)]
extern crate cassandra_sys;
extern crate num;
mod examples_util;
use examples_util::*;
use std::ffi::CString;
use cassandra_sys::*;
struct Pair {
key: String,
value: String,
}
fn prepare_insert_into_batch<'a>(session: &mut CassSession) -> Result<&'a CassPrepared,... | }
fn insert_into_batch_with_prepared(session: &mut CassSession, prepared: &CassPrepared, pairs: Vec<Pair>)
-> Result<(), CassError> {
unsafe {
let batch = cass_batch_new(CASS_BATCH_TYPE_LOGGED);
for pair in pairs {
let statement = cass_prepared_bind(... | {
unsafe {
let query = "INSERT INTO examples.pairs (key, value) VALUES (?, ?)";
let future = &mut *cass_session_prepare(session, CString::new(query).unwrap().as_ptr());
cass_future_wait(future);
let rc = cass_future_error_code(future);
let result = match rc {
CAS... | identifier_body |
batch.rs | // #![feature(plugin)]
// #![plugin(clippy)]
extern crate cassandra_sys;
extern crate num;
mod examples_util;
use examples_util::*;
use std::ffi::CString;
use cassandra_sys::*;
struct Pair {
key: String,
value: String,
}
fn prepare_insert_into_batch<'a>(session: &mut CassSession) -> Result<&'a CassPrepared,... |
_ => {
print_error(future);
Err(rc)
}
};
cass_future_free(future);
result
}
}
fn insert_into_batch_with_prepared(session: &mut CassSession, prepared: &CassPrepared, pairs: Vec<Pair>)
-> Result<(), Ca... | {
let prepared = &*cass_future_get_prepared(future);
Ok(prepared)
} | conditional_block |
arg_visitor.rs | use std::io::{Read, Take};
use std::vec;
use serde::de;
use serde::de::{DeserializeSeed, SeqAccess, Visitor};
use error::{Error, ResultE};
use super::osc_reader::OscReader;
use super::osc_type::OscType;
use super::maybe_skip_comma::MaybeSkipComma;
#[derive(Debug)]
pub struct ArgDeserializer<'a, R: Read + 'a> {
da... | <'a, R: Read + 'a> {
read: &'a mut Take<R>,
/// calling.next() on this returns the OSC char code of the next argument,
/// e.g. 'i' for i32, 'f' for f32, etc.
/// We store this as an iterator to avoid tracking the index of the current arg.
arg_types : MaybeSkipComma<vec::IntoIter<u8>>,
}
impl<'a, R... | ArgVisitor | identifier_name |
arg_visitor.rs | use std::io::{Read, Take};
use std::vec;
use serde::de;
use serde::de::{DeserializeSeed, SeqAccess, Visitor};
use error::{Error, ResultE};
use super::osc_reader::OscReader;
use super::osc_type::OscType;
use super::maybe_skip_comma::MaybeSkipComma;
#[derive(Debug)]
pub struct ArgDeserializer<'a, R: Read + 'a> {
da... | }
fn parse_arg(&mut self, typecode: u8) -> ResultE<OscType> {
match typecode {
b'i' => self.read.parse_i32().map(|i| { OscType::I32(i) }),
b'f' => self.read.parse_f32().map(|f| { OscType::F32(f) }),
b's' => self.read.parse_str().map(|s| { OscType::String(s) }),
... | fn parse_next(&mut self) -> ResultE<Option<OscType>> {
match self.arg_types.next() {
None => Ok(None),
Some(tag) => self.parse_arg(tag).map(|arg| Some(arg)),
} | random_line_split |
build.rs | #[cfg(not(feature = "unstable"))]
mod inner {
extern crate syntex;
extern crate diesel_codegen;
extern crate dotenv_codegen;
use std::env;
use std::path::Path;
pub fn main() {
let out_dir = env::var_os("OUT_DIR").unwrap();
let mut registry = syntex::Registry::new();
die... |
fn main() {
dotenv().ok();
let database_url = ::std::env::var("DATABASE_URL")
.expect("DATABASE_URL must be set to run tests");
let connection = Connection::establish(&database_url).unwrap();
migrations::run_pending_migrations(&connection).unwrap();
inner::main();
} | extern crate dotenv;
use diesel::*;
use dotenv::dotenv; | random_line_split |
build.rs | #[cfg(not(feature = "unstable"))]
mod inner {
extern crate syntex;
extern crate diesel_codegen;
extern crate dotenv_codegen;
use std::env;
use std::path::Path;
pub fn main() |
}
#[cfg(feature = "unstable")]
mod inner {
pub fn main() {}
}
extern crate diesel;
extern crate dotenv;
use diesel::*;
use dotenv::dotenv;
fn main() {
dotenv().ok();
let database_url = ::std::env::var("DATABASE_URL")
.expect("DATABASE_URL must be set to run tests");
let connection = Connectio... | {
let out_dir = env::var_os("OUT_DIR").unwrap();
let mut registry = syntex::Registry::new();
diesel_codegen::register(&mut registry);
dotenv_codegen::register(&mut registry);
let src = Path::new("tests/lib.in.rs");
let dst = Path::new(&out_dir).join("lib.rs");
r... | identifier_body |
build.rs | #[cfg(not(feature = "unstable"))]
mod inner {
extern crate syntex;
extern crate diesel_codegen;
extern crate dotenv_codegen;
use std::env;
use std::path::Path;
pub fn main() {
let out_dir = env::var_os("OUT_DIR").unwrap();
let mut registry = syntex::Registry::new();
die... | () {}
}
extern crate diesel;
extern crate dotenv;
use diesel::*;
use dotenv::dotenv;
fn main() {
dotenv().ok();
let database_url = ::std::env::var("DATABASE_URL")
.expect("DATABASE_URL must be set to run tests");
let connection = Connection::establish(&database_url).unwrap();
migrations::run_pe... | main | identifier_name |
type_.rs | // Copyright 2013 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 i32(ccx: &CrateContext) -> Type {
ty!(llvm::LLVMInt32TypeInContext(ccx.llcx()))
}
pub fn i64(ccx: &CrateContext) -> Type {
ty!(llvm::LLVMInt64TypeInContext(ccx.llcx()))
}
// Creates an integer type with the given number of bits, e.g. i24
pub fn ix(ccx: &CrateContext, nu... | } | random_line_split |
type_.rs | // Copyright 2013 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 ... |
// Creates an integer type with the given number of bits, e.g. i24
pub fn ix(ccx: &CrateContext, num_bits: u64) -> Type {
ty!(llvm::LLVMIntTypeInContext(ccx.llcx(), num_bits as c_uint))
}
pub fn f32(ccx: &CrateContext) -> Type {
ty!(llvm::LLVMFloatTypeInContext(ccx.llcx()))
}
... | {
ty!(llvm::LLVMInt64TypeInContext(ccx.llcx()))
} | identifier_body |
type_.rs | // Copyright 2013 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 ... | (ccx: &CrateContext, els: &[Type], packed: bool) -> Type {
let els : &[TypeRef] = unsafe { mem::transmute(els) };
ty!(llvm::LLVMStructTypeInContext(ccx.llcx(), els.as_ptr(),
els.len() as c_uint,
packed as Bool))
}
... | struct_ | identifier_name |
issue-8898.rs | // Copyright 2013 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 abc = [1, 2, 3];
let tf = [true, false];
let x = [(), ()];
let y = ~[(), ()];
let slice = x.slice(0,1);
let z = @x;
assert_repr_eq(abc, ~"[1, 2, 3]");
assert_repr_eq(tf, ~"[true, false]");
assert_repr_eq(x, ~"[(), ()]");
assert_repr_eq(y, ~"~[(), ()]");
assert_repr... | main | identifier_name |
issue-8898.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | let x = [(), ()];
let y = ~[(), ()];
let slice = x.slice(0,1);
let z = @x;
assert_repr_eq(abc, ~"[1, 2, 3]");
assert_repr_eq(tf, ~"[true, false]");
assert_repr_eq(x, ~"[(), ()]");
assert_repr_eq(y, ~"~[(), ()]");
assert_repr_eq(slice, ~"&[()]");
assert_repr_eq(&x, ~"&[(), ()]")... | let abc = [1, 2, 3];
let tf = [true, false]; | random_line_split |
issue-8898.rs | // Copyright 2013 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 abc = [1, 2, 3];
let tf = [true, false];
let x = [(), ()];
let y = ~[(), ()];
let slice = x.slice(0,1);
let z = @x;
assert_repr_eq(abc, ~"[1, 2, 3]");
assert_repr_eq(tf, ~"[true, false]");
assert_repr_eq(x, ~"[(), ()]");
assert_repr_eq(y, ~"~[(), ()]");
assert_repr_eq... | identifier_body | |
list-endpoints.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_mediapackage::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Reg... |
// Displays your endpoint descriptions and URLs.
// snippet-start:[mediapackage.rust.list-endpoints]
async fn show_endpoints(client: &Client) -> Result<(), Error> {
let or_endpoints = client.list_origin_endpoints().send().await?;
println!("Endpoints:");
for e in or_endpoints.origin_endpoints().unwrap_or_... |
/// Whether to display additional information.
#[structopt(short, long)]
verbose: bool,
} | random_line_split |
list-endpoints.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_mediapackage::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Reg... |
let shared_config = aws_config::from_env().region(region_provider).load().await;
let client = Client::new(&shared_config);
show_endpoints(&client).await
}
| {
println!("MediaPackage client version: {}", PKG_VERSION);
println!(
"Region: {}",
region_provider.region().await.unwrap().as_ref()
);
println!();
} | conditional_block |
list-endpoints.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_mediapackage::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Reg... |
// snippet-end:[mediapackage.rust.list-endpoints]
/// Lists your AWS Elemental MediaPackage endpoint descriptions and URLs in the Region.
/// # Arguments
///
/// * `[-r REGION]` - The Region in which the client is created.
/// If not supplied, uses the value of the **AWS_REGION** environment variable.
/// If th... | {
let or_endpoints = client.list_origin_endpoints().send().await?;
println!("Endpoints:");
for e in or_endpoints.origin_endpoints().unwrap_or_default() {
let endpoint_url = e.url().unwrap_or_default();
let endpoint_description = e.description().unwrap_or_default();
println!(" Desc... | identifier_body |
list-endpoints.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_mediapackage::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Reg... | () -> Result<(), Error> {
tracing_subscriber::fmt::init();
let Opt { region, verbose } = Opt::from_args();
let region_provider = RegionProviderChain::first_try(region.map(Region::new))
.or_default_provider()
.or_else(Region::new("us-west-2"));
println!();
if verbose {
printl... | main | identifier_name |
main_raw.rs | #[global_allocator]
static GLOBAL: snmalloc_rs::SnMalloc = snmalloc_rs::SnMalloc;
use std::{future::Future, io, pin::Pin, task::Context, task::Poll};
use ntex::{fn_service, http::h1, io::Io, util::ready, util::BufMut, util::PoolId};
mod utils;
#[cfg(target_os = "macos")]
use serde_json as simd_json;
const JSON: &[u8... | {
io: Io,
codec: h1::Codec,
}
impl Future for App {
type Output = Result<(), ()>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.as_mut().get_mut();
loop {
if let Some(Ok((req, _))) = ready!(this.io.poll_read_next(&this.code... | App | identifier_name |
main_raw.rs | #[global_allocator]
static GLOBAL: snmalloc_rs::SnMalloc = snmalloc_rs::SnMalloc;
use std::{future::Future, io, pin::Pin, task::Context, task::Poll};
use ntex::{fn_service, http::h1, io::Io, util::ready, util::BufMut, util::PoolId};
mod utils;
#[cfg(target_os = "macos")]
use serde_json as simd_json;
const JSON: &[u8... |
// start http server
ntex::server::build()
.backlog(1024)
.bind("techempower", "0.0.0.0:8080", |cfg| {
cfg.memory_pool(PoolId::P1);
PoolId::P1.set_read_params(65535, 8192);
PoolId::P1.set_write_params(65535, 8192);
fn_service(|io| App {
... |
#[ntex::main]
async fn main() -> io::Result<()> {
println!("Started http server: 127.0.0.1:8080"); | random_line_split |
main_raw.rs | #[global_allocator]
static GLOBAL: snmalloc_rs::SnMalloc = snmalloc_rs::SnMalloc;
use std::{future::Future, io, pin::Pin, task::Context, task::Poll};
use ntex::{fn_service, http::h1, io::Io, util::ready, util::BufMut, util::PoolId};
mod utils;
#[cfg(target_os = "macos")]
use serde_json as simd_json;
const JSON: &[u8... |
"/plaintext" => {
buf.extend_from_slice(PLAIN);
this.codec.set_date_header(buf);
buf.extend_from_slice(BODY);
}
_ => {
buf.extend_from_... | {
buf.extend_from_slice(JSON);
this.codec.set_date_header(buf);
let _ = simd_json::to_writer(
crate::utils::Writer(buf),
&Message {
mess... | conditional_block |
const-str-ptr.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. | // option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::{str, string};
const A: [u8; 2] = ['h' as u8, 'i' as u8];
const B: &'static [u8; 2] = &A;
const C: *const u8 = B as *const u8;
pub fn main() {
unsafe {
let foo = &A as *const u8;
assert_... | //
// 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 | random_line_split |
const-str-ptr.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 ... | {
unsafe {
let foo = &A as *const u8;
assert_eq!(str::from_utf8_unchecked(&A), "hi");
assert_eq!(*C, A[0]);
assert_eq!(*(&B[0] as *const u8), A[0]);
}
} | identifier_body | |
const-str-ptr.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 ... | () {
unsafe {
let foo = &A as *const u8;
assert_eq!(str::from_utf8_unchecked(&A), "hi");
assert_eq!(*C, A[0]);
assert_eq!(*(&B[0] as *const u8), A[0]);
}
}
| main | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.