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 |
|---|---|---|---|---|
runner.rs | use graph::Graph;
use modules;
use num_cpus;
use runtime::{Environment, Runtime};
use std::cmp;
use std::collections::{HashMap, HashSet};
use std::error::Error;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::mpsc;
use std::thread;
use task::Task;
use term;
#[derive(Clone)]
pub struct EnvironmentSpec ... |
/// Run all tasks even if they throw errors.
pub fn keep_going(&mut self) {
self.spec.keep_going = true;
}
/// Sets the number of threads to use to run tasks.
pub fn jobs(&mut self, jobs: usize) {
self.jobs = jobs;
}
/// Adds a path to Lua's require path for modules.
... | {
self.spec.always_run = true;
} | identifier_body |
runner.rs | use graph::Graph;
use modules;
use num_cpus;
use runtime::{Environment, Runtime};
use std::cmp;
use std::collections::{HashMap, HashSet};
use std::error::Error;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::mpsc;
use std::thread;
use task::Task;
use term;
#[derive(Clone)]
pub struct EnvironmentSpec ... | // Scheduling was successful, so remove the task frome the queue.
queue.pop_front().unwrap();
} else {
trace!("failed to send channel to thread {}", thread_id);
}
} else {
... | current_tasks.insert(thread_id, task.name().to_string());
free_threads.remove(&thread_id);
| random_line_split |
backtrace.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 ... | {
Offset: u64,
Segment: u16,
Mode: ADDRESS_MODE,
}
pub struct STACKFRAME64 {
AddrPC: ADDRESS64,
AddrReturn: ADDRESS64,
AddrFrame: ADDRESS64,
AddrStack: ADDRESS64,
AddrBStore: ADDRESS64,
FuncTableEntry: *mut libc::c_void,
Params: [u64; 4],
Far: libc::BOOL,
Virtual: libc:... | ADDRESS64 | identifier_name |
backtrace.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 ... | type SymInitializeFn =
extern "system" fn(libc::HANDLE, *mut libc::c_void,
libc::BOOL) -> libc::BOOL;
type SymCleanupFn =
extern "system" fn(libc::HANDLE) -> libc::BOOL;
type StackWalk64Fn =
extern "system" fn(libc::DWORD, libc::HANDLE, libc::HANDLE,
*mut STACK... | *mut SYMBOL_INFO) -> libc::BOOL; | random_line_split |
backtrace.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 ... |
i += 1;
try!(write!(w, " {:2}: {:#2$x}", i, addr, HEX_WIDTH));
let mut info: SYMBOL_INFO = unsafe { intrinsics::init() };
info.MaxNameLen = MAX_SYM_NAME as libc::c_ulong;
// the struct size in C. the value is different to
// `size_of::<SYMBOL_INFO>() - MAX_SYM_NAME + ... | { break } | conditional_block |
platform_types.rs |
Paste(Option<String>),
InsertNumbersAtCursors,
AddOrSelectBuffer(BufferName, String),
AddOrSelectBufferThenGoTo(BufferName, String, Position),
NewScratchBuffer(Option<String>),
TabIn,
TabOut,
StripTrailingWhitespace,
AdjustBufferSelection(SelectionAdjustment),
NextLanguage,
... | },
GoToPosition => match &self.menu {
MenuView::GoToPosition(ref gtp) => Some(>p.go_to_position),
_ => Option::None,
},
}.map(|d| &d.cursors[..])
}
#[must_use]
/// returns the currently visible editor buffer path if it has one.
... | MenuView::FileSwitcher(ref fs) => Some(&fs.search),
_ => Option::None, | random_line_split |
platform_types.rs | Paste(Option<String>),
InsertNumbersAtCursors,
AddOrSelectBuffer(BufferName, String),
AddOrSelectBufferThenGoTo(BufferName, String, Position),
NewScratchBuffer(Option<String>),
TabIn,
TabOut,
StripTrailingWhitespace,
AdjustBufferSelection(SelectionAdjustment),
NextLanguage,
P... | (&self) -> MenuMode {
match self {
Self::None => MenuMode::Hidden,
Self::FileSwitcher(_) => MenuMode::FileSwitcher,
Self::FindReplace(v) => MenuMode::FindReplace(v.mode),
Self::GoToPosition(_) => MenuMode::GoToPosition,
}
}
}
#[must_use]
pub fn kind_e... | get_mode | identifier_name |
platform_types.rs | Paste(Option<String>),
InsertNumbersAtCursors,
AddOrSelectBuffer(BufferName, String),
AddOrSelectBufferThenGoTo(BufferName, String, Position),
NewScratchBuffer(Option<String>),
TabIn,
TabOut,
StripTrailingWhitespace,
AdjustBufferSelection(SelectionAdjustment),
NextLanguage,
P... | GoToPosition => match &self.menu {
MenuView::GoToPosition(ref gtp) => Some(>p.go_to_position),
_ => Option::None,
},
}.map(|d| &d.cursors[..])
}
#[must_use]
/// returns the currently visible editor buffer path if it has one.
pub fn curr... | {
use BufferIdKind::*;
match self.current_buffer_kind {
// Seems like we never actually need to access the Text buffer
// cursors here. If we want to later, then some additional restructuring
// will be needed, at least according to the comment this comment
... | identifier_body |
eval.rs | use error::*;
use ast::*;
use engine::*;
use types::*;
use eval_static::*;
use std::fmt;
use std::rc::Rc;
use std::collections::HashMap;
#[derive(Clone)]
pub struct Macro(pub Ident, pub Rc<dyn Fn(&Exp, &Context) -> Ret<RunVal>>);
impl fmt::Debug for Macro {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
w... | (&mut self, id: String, variants: Vec<Ident>) -> Ret {
let rc = Rc::new(DataType {id: id.clone(), variants: variants.clone()});
for (i, variant) in variants.iter().enumerate() {
self.add_var(variant.clone(), RunVal::Data(rc.clone(), i), Type::Data(rc.clone()))?;
}
self.add_type(id, Type::Data(rc))
}
pub ... | add_datatype | identifier_name |
eval.rs | use error::*;
use ast::*;
use engine::*;
use types::*;
use eval_static::*;
use std::fmt;
use std::rc::Rc;
use std::collections::HashMap;
#[derive(Clone)]
pub struct Macro(pub Ident, pub Rc<dyn Fn(&Exp, &Context) -> Ret<RunVal>>);
impl fmt::Debug for Macro {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
w... | }
eval_exp(exp, ctx)
},
_ => eval_exp(exp, ctx),
}
}
pub fn eval_exp_seq(seq: &Vec<Exp>, ctx: &Context) -> Vec<RunVal> {
seq.iter().flat_map(|e| {
if let Exp::Expand(ref e) = e {
let val = eval_exp(e, ctx);
let err = Error(format!("Cannot expand value: {}", val));
iter... | for decl in decls {
eval_decl(decl, ctx).unwrap(); | random_line_split |
eval.rs | use error::*;
use ast::*;
use engine::*;
use types::*;
use eval_static::*;
use std::fmt;
use std::rc::Rc;
use std::collections::HashMap;
#[derive(Clone)]
pub struct Macro(pub Ident, pub Rc<dyn Fn(&Exp, &Context) -> Ret<RunVal>>);
impl fmt::Debug for Macro {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
w... | ,
RunVal::Tuple(vals) => Some(vals),
_ => None,
}
}
pub fn create_extract_gate_typed(cases: &Vec<Case>, min_input_size: usize, ctx: &Context) -> (Gate, Type) {
fn reduce_type(output_type: Option<Type>, t: Type) -> Option<Type> {
Some(match output_type {
None => t,
Some(ot) => if ot == t {t} else {Type::A... | {
Some((0..i).map(RunVal::Index).collect())
} | conditional_block |
eval.rs | use error::*;
use ast::*;
use engine::*;
use types::*;
use eval_static::*;
use std::fmt;
use std::rc::Rc;
use std::collections::HashMap;
#[derive(Clone)]
pub struct Macro(pub Ident, pub Rc<dyn Fn(&Exp, &Context) -> Ret<RunVal>>);
impl fmt::Debug for Macro {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
w... |
}
#[derive(Clone,Debug,PartialEq)]
pub struct Context {
path: String,
vars: HashMap<Ident, RunVal>,
types: TypeContext,
}
impl Context {
pub fn new(path: String) -> Context {
Context {
path,
vars: HashMap::new(),
types: TypeContext::new(),
}
}
pub fn path(&self) -> &String {
&self.path
}
p... | {
match self {
&RunVal::Index(ref n) => write!(f, "{}", n),
&RunVal::String(ref s) => write!(f, "{:?}", s),
&RunVal::Data(ref dt, ref index) => write!(f, "{}", dt.variants[*index]),
&RunVal::Tuple(ref vals) => write!(f, "({})", vals.iter().map(|val| format!("{}", val)).collect::<Vec<_>>().join(", ")),
... | identifier_body |
avx.rs | /*
* Copyright (c) 2023.
*
* This software is free software;
*
* You can redistribute it or modify it under terms of the MIT, Apache License or Zlib license
*/
//! AVX color conversion routines
//!
//! Okay these codes are cool
//!
//! Herein lies super optimized codes to do color conversions.
//!
//!
//! 1. The... | return min_v;
}
#[inline]
const fn shuffle(z: i32, y: i32, x: i32, w: i32) -> i32 {
(z << 6) | (y << 4) | (x << 2) | w
} | let max_v = _mm256_max_epi16(reg, min_s); //max(a,0)
let min_v = _mm256_min_epi16(max_v, max_s); //min(max(a,0),255) | random_line_split |
avx.rs | /*
* Copyright (c) 2023.
*
* This software is free software;
*
* You can redistribute it or modify it under terms of the MIT, Apache License or Zlib license
*/
//! AVX color conversion routines
//!
//! Okay these codes are cool
//!
//! Herein lies super optimized codes to do color conversions.
//!
//!
//! 1. The... |
#[inline]
#[target_feature(enable = "avx2")]
#[rustfmt::skip]
unsafe fn ycbcr_to_rgba_unsafe(
y: &[i16; 16], cb: &[i16; 16], cr: &[i16; 16],
out: &mut [u8],
offset: &mut usize,
)
{
// check if we have enough space to write.
let tmp:& mut [u8; 64] = out.get_mut(*offset..*offset + 64).expect("Slice ... | {
unsafe {
ycbcr_to_rgba_unsafe(y, cb, cr, out, offset);
}
} | identifier_body |
avx.rs | /*
* Copyright (c) 2023.
*
* This software is free software;
*
* You can redistribute it or modify it under terms of the MIT, Apache License or Zlib license
*/
//! AVX color conversion routines
//!
//! Okay these codes are cool
//!
//! Herein lies super optimized codes to do color conversions.
//!
//!
//! 1. The... | (
y: &[i16; 16], cb: &[i16; 16], cr: &[i16; 16],
out: &mut [u8],
offset: &mut usize,
)
{
// check if we have enough space to write.
let tmp:& mut [u8; 64] = out.get_mut(*offset..*offset + 64).expect("Slice to small cannot write").try_into().unwrap();
let (r, g, b) = ycbcr_to_rgb_baseline_no_cla... | ycbcr_to_rgba_unsafe | identifier_name |
day_06.rs | /// --- Day 6: Chronal Coordinates ---
///
/// The device on your wrist beeps several times, and once again you feel like
/// you're falling.
///
/// "Situation critical," the device announces. "Destination indeterminate.
/// Chronal interference detected. Please specify new target coordinates."
///
/// The device then... | .unwrap();
println!("The biggest non-infinite area size is: {}", biggest_area_size);
let concentrated_area = count_points_below(&points, &bounds, 10_000);
println!("The size of the area that have a total distance less than \
10.000 is: {}", concentrated_area);
}
fn create_grid(points:... | {
let points = parse_input(include_str!("../input/day_06.txt"));
let bounds = create_bounds(&points);
let grid = create_grid(&points, &bounds);
let mut areas = HashMap::new();
let mut infinite_areas = HashSet::new();
for (point, area_number) in grid.iter() {
if on_bounds(point,&bounds)... | identifier_body |
day_06.rs | /// --- Day 6: Chronal Coordinates ---
///
/// The device on your wrist beeps several times, and once again you feel like
/// you're falling.
///
/// "Situation critical," the device announces. "Destination indeterminate.
/// Chronal interference detected. Please specify new target coordinates."
///
/// The device then... | let bounds = Bounds {x:x_range, y:y_range};
assert!(on_bounds(&(0, 4), &bounds));
assert!(on_bounds(&(3, 2), &bounds));
assert!(on_bounds(&(2, 6), &bounds));
assert!(!on_bounds(&(2, 7), &bounds));
assert!(!on_bounds(&(2, 5), &bounds));
assert!(!on_bounds(&(1, 1)... | fn test_on_bounds() {
let x_range = Range {min:0, max:3};
let y_range = Range {min:2, max:6}; | random_line_split |
day_06.rs | /// --- Day 6: Chronal Coordinates ---
///
/// The device on your wrist beeps several times, and once again you feel like
/// you're falling.
///
/// "Situation critical," the device announces. "Destination indeterminate.
/// Chronal interference detected. Please specify new target coordinates."
///
/// The device then... | (reference_point: &Point, points: &Vec<Point>) -> i32 {
points.iter()
.map(|point| distance(reference_point, point))
.sum()
}
fn closest_point(reference_point: &Point, points: &Vec<Point>) -> Option<usize> {
let (index, _) = points.iter()
.map(|point| distance(reference_point, point))
... | total_distance | identifier_name |
lib.rs | // Copyright 2018 Mozilla
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software... | (&self, record: &log::Record) {
let message = format!("{}:{} -- {}", record.level(), record.target(), record.args());
println!("{}", message);
#[cfg(target_os = "android")]
{
unsafe {
let message = ::std::ffi::CString::new(message).unwrap();
le... | log | identifier_name |
lib.rs | // Copyright 2018 Mozilla
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software... | // We take the "low road" here when returning the structs - we expose the
// items (and arrays of items) as strings, which are JSON. The rust side of
// the world gets serialization and deserialization for free and it makes
// memory management that little bit simpler.
extern crate failure;
extern crate serde_json;
ex... | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
| random_line_split |
lib.rs | // Copyright 2018 Mozilla
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software... |
#[no_mangle]
pub unsafe extern "C" fn sync15_passwords_sync(
state: *mut PasswordState,
key_id: *const c_char,
access_token: *const c_char,
sync_key: *const c_char,
tokenserver_url: *const c_char,
error: *mut ExternError
) {
with_translated_void_result(error, || {
assert_pointer_not... |
Ok(url::Url::parse(url)?)
}
| identifier_body |
console.rs | // Copyright (c) 2019 - 2020 ESRLabs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law ... | .unwrap_or_else(|| "No".to_string()),
if app.container().is_resource_container() {
"resource"
} else {
"app"
}
.to_owned(),
... | {
to_table(
vec![vec![
"Name".to_string(),
"Version".to_string(),
"Running".to_string(),
"Type".to_string(),
]]
.iter()
.cloned()
.chain(
state
.applications()
.sorted_by_key(|app| app... | identifier_body |
console.rs | // Copyright (c) 2019 - 2020 ESRLabs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law ... | (tx: &EventTx) -> Result<()> {
let rx = serve().await?;
let tx = tx.clone();
// Spawn a task that handles lines received on the debug port.
task::spawn(async move {
while let Ok((line, tx_reply)) = rx.recv().await {
tx.send(Event::Console(line, tx_reply)).await;
}
});
... | init | identifier_name |
console.rs | // Copyright (c) 2019 - 2020 ESRLabs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law ... | /// Start applications. If `args` is empty *all* known applications that
/// are not in a running state are started. If a argument is supplied it
/// is used to construct a Regex and all container (names) matching that
/// Regex are attempted to be started.
async fn start(state: &mut State, args: &[&str]) -> Result<Str... | }
| random_line_split |
basic.rs | let array_slice = &array[1..3];
assert_eq!([2, 3, 4], array_slice);
// passing function arguments
let string = String::new();
take_reference(&string);
take_mut_ref(&mut string);
string = take_and_give_back_ownership(string);
take_ownership(string);
}
// function arguments
fn take_ownersh... | }
}
#[test]
fn using_other_iterator_trait_methods() {
let sum: u32 = Counter::new()
.zip(Counter::new().skip(1))
.map(|(a, b)| a * b)
.filter(|x| x % 3 == 0)
.sum();
assert_eq!(18, sum);
}
}
// cargo and creates
// //! Another documen... | None
} | random_line_split |
basic.rs | let array_slice = &array[1..3];
assert_eq!([2, 3, 4], array_slice);
// passing function arguments
let string = String::new();
take_reference(&string);
take_mut_ref(&mut string);
string = take_and_give_back_ownership(string);
take_ownership(string);
}
// function arguments
fn take_ownersh... | {
Int(i32),
Float(f64),
Text(String),
}
let row = vec![
SpreadsheetCell::Int(3),
SpreadsheetCell::Text(String::from("blue")),
SpreadsheetCell::Float(10.12),
];
}
// strings
// str is implemented in the core language and String is in the standard library
f... | SpreadsheetCell | identifier_name |
completion.rs | use std::{borrow::Cow, path::PathBuf, str::FromStr, sync::Arc};
use floem::{
peniko::kurbo::Rect,
reactive::{ReadSignal, RwSignal, Scope},
};
use lapce_core::{buffer::rope_text::RopeText, movement::Movement};
use lapce_rpc::{plugin::PluginId, proxy::ProxyRpcHandler};
use lsp_types::{
CompletionItem, Comple... | (&mut self) {
let count = self.display_count();
let active = self.active.get_untracked();
let new = Movement::Up.update_index(
active,
self.filtered_items.len(),
count,
false,
);
self.active.set(new);
}
/// The currently se... | previous_page | identifier_name |
completion.rs | use std::{borrow::Cow, path::PathBuf, str::FromStr, sync::Arc};
use floem::{
peniko::kurbo::Rect,
reactive::{ReadSignal, RwSignal, Scope},
};
use lapce_core::{buffer::rope_text::RopeText, movement::Movement};
use lapce_rpc::{plugin::PluginId, proxy::ProxyRpcHandler};
use lsp_types::{
CompletionItem, Comple... | // TODO: Possibly handle the 'is_incomplete' field on List.
CompletionResponse::List(list) => &list.items,
};
let items: im::Vector<ScoredCompletionItem> = items
.iter()
.map(|i| ScoredCompletionItem {
item: i.to_owned(),
plug... | random_line_split | |
completion.rs | use std::{borrow::Cow, path::PathBuf, str::FromStr, sync::Arc};
use floem::{
peniko::kurbo::Rect,
reactive::{ReadSignal, RwSignal, Scope},
};
use lapce_core::{buffer::rope_text::RopeText, movement::Movement};
use lapce_rpc::{plugin::PluginId, proxy::ProxyRpcHandler};
use lsp_types::{
CompletionItem, Comple... |
fn all_items(&self) -> im::Vector<ScoredCompletionItem> {
self.input_items
.get(&self.input)
.cloned()
.filter(|items|!items.is_empty())
.unwrap_or_else(move || {
self.input_items.get("").cloned().unwrap_or_default()
})
}
pub... | {
if self.status == CompletionStatus::Inactive {
return;
}
self.input = input;
// TODO: If the user types a letter that continues the current active item, we should
// try keeping that item active. Possibly give this a setting.
// ex: `p` has `print!` and `pri... | identifier_body |
lib.rs | // lib.rs -- RUST wasm interface for Conways game of life
mod utils;
use quad_rand;
use js_sys;
use wasm_bindgen::prelude::*;
// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeA... | {
width: u32, // width of each row
height: u32, // number of rows
cells: Vec<Cell>, // width*height cells, each one byte
prevcells: Vec<Cell>, // cells from previous tick
mousedown: bool // set when shift-click event, so that associated click ignored
}
// methods for Universe, but not exposed... | Universe | identifier_name |
lib.rs | // lib.rs -- RUST wasm interface for Conways game of life
mod utils;
use quad_rand;
use js_sys;
use wasm_bindgen::prelude::*;
// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeA... |
}
// impl Universe block w/o wasm_bindgen attribute
// Needed for testing -- don't expose to our JS.
// Rust-generated WebAsm functions cannot return borrowed references.
// NOTE/SUGGEST: Try compiling the Rust-generated WebAsm with
// the wasm_bindgen attribute and examine errors.
// NOTE: get_cells returns b... | {
log!("reset_board() : {:?}", pattern);
let width = self.width();
let height = self.height();
self.prevcells = self.cells.clone(); // current grid, needed for correct redraw
self.cells = generate_cells(width, height, pattern);
} | identifier_body |
lib.rs | // lib.rs -- RUST wasm interface for Conways game of life
mod utils;
use quad_rand;
use js_sys;
use wasm_bindgen::prelude::*;
// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeA... |
+ if self.cells[self.get_index(down,right)] == Cell::Alive { 1 } else { 0 };
neighbors
}
}
// standalone method, not part of Universe directly
fn generate_cells(width: u32, height: u32, _pattern: InitialPattern) -> Vec<Cell> {
// expression generating Vec<Cell>
let cells = (0..width... | { 0 } | conditional_block |
lib.rs | // lib.rs -- RUST wasm interface for Conways game of life
mod utils;
use quad_rand;
use js_sys;
use wasm_bindgen::prelude::*;
// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeA... | }).collect();
inverted_cells
}
// Public methods, exposed to JS
#[wasm_bindgen]
impl Universe
{
pub fn width(&self) -> u32 {
self.width
}
pub fn height(&self) -> u32 {
self.height
}
// set_width -- set width of Universe, set all cells to Dead state
pub fn set_width(&m... | let inverted_cells = (0..count).map(|i|
{
if cells[i] == Cell::Alive { Cell::Dead } else { Cell::Alive } | random_line_split |
mod.rs | //! Drop range analysis finds the portions of the tree where a value is guaranteed to be dropped
//! (i.e. moved, uninitialized, etc.). This is used to exclude the types of those values from the
//! generator type. See `InteriorVisitor::record` for where the results of this analysis are used.
//!
//! There are three ph... | use crate::FnCtxt;
use hir::def_id::DefId;
use hir::{Body, HirId, HirIdMap, Node};
use rustc_data_structures::unord::{UnordMap, UnordSet};
use rustc_hir as hir;
use rustc_index::bit_set::BitSet;
use rustc_index::IndexVec;
use rustc_middle::hir::map::Map;
use rustc_middle::hir::place::{PlaceBase, PlaceWithHirId};
use ru... |
use self::cfg_build::build_control_flow_graph;
use self::record_consumed_borrow::find_consumed_and_borrowed; | random_line_split |
mod.rs | //! Drop range analysis finds the portions of the tree where a value is guaranteed to be dropped
//! (i.e. moved, uninitialized, etc.). This is used to exclude the types of those values from the
//! generator type. See `InteriorVisitor::record` for where the results of this analysis are used.
//!
//! There are three ph... | (&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DropRanges")
.field("hir_id_map", &self.tracked_value_map)
.field("post_order_maps", &self.post_order_map)
.field("nodes", &self.nodes.iter_enumerated().collect::<BTreeMap<_, _>>())
.finish... | fmt | identifier_name |
mod.rs | //! Drop range analysis finds the portions of the tree where a value is guaranteed to be dropped
//! (i.e. moved, uninitialized, etc.). This is used to exclude the types of those values from the
//! generator type. See `InteriorVisitor::record` for where the results of this analysis are used.
//!
//! There are three ph... | else {
match self {
Self::Variable(hir_id) => write!(f, "Variable({hir_id:?})"),
Self::Temporary(hir_id) => write!(f, "Temporary({hir_id:?})"),
}
}
})
}
}
impl TrackedValue {
fn hir_id(&self) -> HirId {
match s... | {
write!(f, "{}", tcx.hir().node_to_string(self.hir_id()))
} | conditional_block |
mod.rs | //! Drop range analysis finds the portions of the tree where a value is guaranteed to be dropped
//! (i.e. moved, uninitialized, etc.). This is used to exclude the types of those values from the
//! generator type. See `InteriorVisitor::record` for where the results of this analysis are used.
//!
//! There are three ph... |
fn node_mut(&mut self, id: PostOrderId) -> &mut NodeInfo {
let size = self.num_values();
self.nodes.ensure_contains_elem(id, || NodeInfo::new(size))
}
fn add_control_edge(&mut self, from: PostOrderId, to: PostOrderId) {
trace!("adding control edge from {:?} to {:?}", from, to);
... | {
self.tracked_value_map.len()
} | identifier_body |
mod.rs | //! Code to compute example inputs given a backtrace.
use crate::grammar::repr::*;
use crate::message::builder::InlineBuilder;
use crate::message::Content;
use crate::style::Style;
use crate::tls::Tls;
use ascii_canvas::AsciiView;
use std::{
cmp::Ordering,
fmt::{Debug, Error, Formatter},
};
#[cfg(test)]
mod t... |
fn starting_positions(&self, lengths: &[usize]) -> Vec<usize> {
lengths
.iter()
.scan(0, |counter, &len| {
let start = *counter;
// Leave space for "NT " (if "NT" is the name
// of the nonterminal).
*counter = start + l... | {
let lengths = self.lengths();
let positions = self.positions(&lengths);
InlineBuilder::new()
.push(Box::new(ExamplePicture {
example: self,
positions,
styles,
}))
.indented()
.end()
} | identifier_body |
mod.rs | //! Code to compute example inputs given a backtrace.
use crate::grammar::repr::*;
use crate::message::builder::InlineBuilder;
use crate::message::Content;
use crate::style::Style;
use crate::tls::Tls;
use ascii_canvas::AsciiView;
use std::{
cmp::Ordering,
fmt::{Debug, Error, Formatter},
};
#[cfg(test)]
mod t... | (&self) -> Vec<::ascii_canvas::Row> {
let this = self.clone();
let content = this.into_picture(ExampleStyles::default());
let min_width = content.min_width();
let canvas = content.emit_to_canvas(min_width);
canvas.to_strings()
}
fn paint_on(&self, styles: &ExampleStyles,... | paint_unstyled | identifier_name |
mod.rs | //! Code to compute example inputs given a backtrace.
use crate::grammar::repr::*;
use crate::message::builder::InlineBuilder;
use crate::message::Content;
use crate::style::Style;
use crate::tls::Tls;
use ascii_canvas::AsciiView;
use std::{
cmp::Ordering,
fmt::{Debug, Error, Formatter},
};
#[cfg(test)]
mod t... | ///
/// The top-line is the `symbols` vector. The groupings below are
/// stored in the `reductions` vector, in order from smallest to
/// largest (they are always properly nested). The `cursor` field
/// indicates the current lookahead token.
///
/// The `symbols` vector is actually `Option<Symbol>` to account
/// for... | /// ``` | random_line_split |
mod.rs | /* File_config_functionalities_pmz */
// conditions:
/*
exec trait: [alias:(file/any)] [operations] [path/name] [parameters/--options]
Read:Content _ none
Write:Content _ String : if use multi line content ->
check len()::Enum -> i32|&str
Update:Content _ String
... | println!(
"test {:?} ",
(match_inside_brac.is_match(test), test.trim_matches(x))
);
} | println!("t {}", test);
let x: &[_] = &['[', ']']; | random_line_split |
mod.rs | /* File_config_functionalities_pmz */
// conditions:
/*
exec trait: [alias:(file/any)] [operations] [path/name] [parameters/--options]
Read:Content _ none
Write:Content _ String : if use multi line content ->
check len()::Enum -> i32|&str
Update:Content _ String
... | {
let match_inside_brac = regex::Regex::new(r"^\[(.*)\]$").unwrap();
let test = "[Apple sauce bananan ba;;;a]";
println!("t {}", test);
let x: &[_] = &['[', ']'];
println!(
"test {:?} ",
(match_inside_brac.is_match(test), test.trim_matches(x))
);
} | identifier_body | |
mod.rs | /* File_config_functionalities_pmz */
// conditions:
/*
exec trait: [alias:(file/any)] [operations] [path/name] [parameters/--options]
Read:Content _ none
Write:Content _ String : if use multi line content ->
check len()::Enum -> i32|&str
Update:Content _ String
... | (result: &str) -> OriResult<String> {
if result.is_empty() {
let empty_err = FileError::new().set_message("The Folder is Empty inside");
Err(empty_err)
} else {
Ok(result.trim().to_string())
}
}
impl Operation for Fileconfig {
fn read(&self) -> OriResult<String> {
let fil... | checkempty | identifier_name |
main.rs | use crossterm::{
cursor,
event::{self, DisableMouseCapture, EnableMouseCapture, Event},
queue,
style::{self, Color::Rgb, Colors, Print, SetColors},
terminal,
};
use serde::{Deserialize, Serialize};
use std::{
cmp::min,
collections::HashMap,
env, fs,
io::{self, Write},
iter,
p... |
dir: Direction,
skip: bool,
}
#[derive(Clone)]
enum Direction {
Next,
Prev,
}
pub struct Bk<'a> {
quit: bool,
chapters: Vec<epub::Chapter>,
// position in the book
chapter: usize,
line: usize,
mark: HashMap<char, (usize, usize)>,
links: HashMap<String, (usize, usize)>,
... | archArgs { | identifier_name |
main.rs | use crossterm::{
cursor,
event::{self, DisableMouseCapture, EnableMouseCapture, Event},
queue,
style::{self, Color::Rgb, Colors, Print, SetColors},
terminal,
};
use serde::{Deserialize, Serialize};
use std::{
cmp::min,
collections::HashMap,
env, fs,
io::{self, Write},
iter,
p... | }
false
}
}
}
}
#[derive(argh::FromArgs)]
/// read a book
struct Args {
#[argh(positional)]
path: Option<String>,
/// background color (eg 282a36)
#[argh(option)]
bg: Option<String>,
/// foreground color (eg f8f8f2)
#[argh(option)]
... | self.jump_byte(c, index);
return true;
}
| conditional_block |
main.rs | use crossterm::{
cursor,
event::{self, DisableMouseCapture, EnableMouseCapture, Event},
queue,
style::{self, Color::Rgb, Colors, Print, SetColors},
terminal,
};
use serde::{Deserialize, Serialize};
use std::{
cmp::min,
collections::HashMap,
env, fs,
io::{self, Write},
iter,
p... |
let byte = bk.chapters[bk.chapter].lines[bk.line].0;
state
.save
.files
.insert(state.path.clone(), (bk.chapter, byte));
state.save.last = state.path;
let serialized = ron::to_string(&state.save).unwrap();
fs::write(state.save_path, serialized).unwrap_or_else(|e| {
prin... | random_line_split | |
colors.rs | use std::io;
use std::mem;
use std::os::windows::io::AsRawHandle;
use std::str::Bytes;
use windows_sys::Win32::Foundation::HANDLE;
use windows_sys::Win32::System::Console::{
GetConsoleScreenBufferInfo, SetConsoleTextAttribute, CONSOLE_SCREEN_BUFFER_INFO,
FOREGROUND_BLUE as FG_BLUE, FOREGROUND_GREEN as FG_GREEN... | cur_attr: TextAttributes,
}
#[derive(Clone, Copy, Debug)]
enum HandleKind {
Stdout,
Stderr,
}
impl HandleKind {
fn handle(&self) -> HANDLE {
match *self {
HandleKind::Stdout => io::stdout().as_raw_handle() as HANDLE,
HandleKind::Stderr => io::stderr().as_raw_handle() as... | #[derive(Debug)]
pub struct Console {
kind: HandleKind,
start_attr: TextAttributes, | random_line_split |
colors.rs | use std::io;
use std::mem;
use std::os::windows::io::AsRawHandle;
use std::str::Bytes;
use windows_sys::Win32::Foundation::HANDLE;
use windows_sys::Win32::System::Console::{
GetConsoleScreenBufferInfo, SetConsoleTextAttribute, CONSOLE_SCREEN_BUFFER_INFO,
FOREGROUND_BLUE as FG_BLUE, FOREGROUND_GREEN as FG_GREEN... |
}
| {
let attr = "leading bytes \x1b[1m trailing bytes";
let parsed = driver(parse_attr, attr).unwrap();
assert_eq!(parsed, b'1');
} | identifier_body |
colors.rs | use std::io;
use std::mem;
use std::os::windows::io::AsRawHandle;
use std::str::Bytes;
use windows_sys::Win32::Foundation::HANDLE;
use windows_sys::Win32::System::Console::{
GetConsoleScreenBufferInfo, SetConsoleTextAttribute, CONSOLE_SCREEN_BUFFER_INFO,
FOREGROUND_BLUE as FG_BLUE, FOREGROUND_GREEN as FG_GREEN... | () -> io::Result<Console> {
Self::create_for_stream(HandleKind::Stdout)
}
/// Create a new Console to stderr.
///
/// If there was a problem creating the console, then an error is returned.
pub fn stderr() -> io::Result<Console> {
Self::create_for_stream(HandleKind::Stderr)
}
... | stdout | identifier_name |
appendlist.rs | use std::cell::{Cell, UnsafeCell};
use std::fmt::{self, Debug};
use std::iter::FromIterator;
use std::ops::Index;
use crate::common::{chunk_size, chunk_start, index_chunk};
/// A list that can be appended to while elements are borrowed
///
/// This looks like a fairly bare-bones list API, except that it has a `push`
... | self.len.get() - chunk_start(self.chunks().len() - 1)
);
} else {
// No chunks
assert_eq!(0, self.chunks().len());
}
}
}
/// Create a new `AppendList`
pub fn new() -> Self {
Self {
chunk... | {
#[cfg(test)]
{
if self.len.get() > 0 {
// Correct number of chunks
assert_eq!(index_chunk(self.len.get() - 1), self.chunks().len() - 1);
// Every chunk holds enough items
for chunk_id in 0..self.chunks().len() {
... | identifier_body |
appendlist.rs | use std::cell::{Cell, UnsafeCell};
use std::fmt::{self, Debug};
use std::iter::FromIterator;
use std::ops::Index;
use crate::common::{chunk_size, chunk_start, index_chunk};
/// A list that can be appended to while elements are borrowed
///
/// This looks like a fairly bare-bones list API, except that it has a `push`
... | (&self) -> usize {
self.check_invariants();
self.len.get()
}
/// Get an item from the list, if it is in bounds
///
/// Returns `None` if the `index` is out-of-bounds. Note that you can also
/// index with `[]`, which will panic on out-of-bounds.
pub fn get(&self, index: usize) ... | len | identifier_name |
appendlist.rs | use std::cell::{Cell, UnsafeCell};
use std::fmt::{self, Debug};
use std::iter::FromIterator;
use std::ops::Index;
use crate::common::{chunk_size, chunk_start, index_chunk};
/// A list that can be appended to while elements are borrowed
///
/// This looks like a fairly bare-bones list API, except that it has a `push`
... | impl<'l, T> Iterator for Iter<'l, T> {
type Item = &'l T;
fn next(&mut self) -> Option<Self::Item> {
let item = self.list.get(self.index);
self.index += 1;
item
}
fn size_hint(&self) -> (usize, Option<usize>) {
let remaining = self.list.len() - self.index;
(r... | index: usize,
}
| random_line_split |
unified.rs | (Self::Sapling, Self::Sapling)
| (Self::P2sh, Self::P2sh)
| (Self::P2pkh, Self::P2pkh) => cmp::Ordering::Equal,
// We don't know for certain the preference order of unknown receivers, but it
// is likely that the higher typecode has higher preference. The exact order
... | else {
typecodes.insert(t);
}
}
if typecodes.iter().all(|t| t.is_transparent()) {
Err(ParseError::OnlyTransparent)
} else {
// All checks pass!
Ok(Address(receivers))
}
}
}
impl Address {
/// Returns the raw encod... | {
return Err(ParseError::BothP2phkAndP2sh);
} | conditional_block |
unified.rs | (Self::Sapling, Self::Sapling)
| (Self::P2sh, Self::P2sh)
| (Self::P2pkh, Self::P2pkh) => cmp::Ordering::Equal,
// We don't know for certain the preference order of unknown receivers, but it
// is likely that the higher typecode has higher preference. The exact order
... | {
/// The unified address contains both P2PKH and P2SH receivers.
BothP2phkAndP2sh,
/// The unified address contains a duplicated typecode.
DuplicateTypecode(Typecode),
/// The parsed typecode exceeds the maximum allowed CompactSize value.
InvalidTypecodeValue(u64),
/// The string is an inv... | ParseError | identifier_name |
unified.rs | | (Self::Sapling, Self::Sapling)
| (Self::P2sh, Self::P2sh)
| (Self::P2pkh, Self::P2pkh) => cmp::Ordering::Equal,
// We don't know for certain the preference order of unknown receivers, but it
// is likely that the higher typecode has higher preference. The exact order
... | // Unknown typecodes are treated as not transparent for the purpose of disallowing
// only-transparent UAs, which can be represented with existing address encodings.
matches!(self, Typecode::P2pkh | Typecode::P2sh)
}
}
/// An error while attempting to parse a string as a Zcash address.
#[de... | impl Typecode {
fn is_transparent(&self) -> bool { | random_line_split |
game.rs | use std::ops::Add;
use super::rand::{thread_rng, Rng};
use super::direction::Direction;
/// A mask with a single section of 16 bits set to 0.
/// Used to extract a "horizontal slice" out of a 64 bit integer.
pub static ROW_MASK: u64 = 0xFFFF;
/// A `u64` mask with 4 sections each starting after the n * 16th bit.
/// ... | ///
/// // | F | E | D | C | | F | B | 7 | 3 |
/// // | B | A | 9 | 8 | => | E | A | 6 | 2 |
/// // | 7 | 6 | 5 | 4 | | D | 9 | 5 | 1 |
/// // | 3 | 2 | 1 | 0 | | C | 8 | 4 | 0 |
///
/// assert_eq!(Game::transpose(0xFEDC_BA98_7654_3210), 0xFB73_EA62_D951_C840);
/// `... | random_line_split | |
game.rs | use std::ops::Add;
use super::rand::{thread_rng, Rng};
use super::direction::Direction;
/// A mask with a single section of 16 bits set to 0.
/// Used to extract a "horizontal slice" out of a 64 bit integer.
pub static ROW_MASK: u64 = 0xFFFF;
/// A `u64` mask with 4 sections each starting after the n * 16th bit.
/// ... | { pub board: u64 }
impl Game {
/// Constructs a new `tfe::Game`.
///
/// `Game` stores a board internally as a `u64`.
///
/// # Examples
///
/// Simple example:
///
/// ```
/// use tfe::Game;
///
/// let mut game = Game::new();
/// # println!("{:016x}", game.board);
... | Game | identifier_name |
git.rs | //---------------------------------------------------------------------------//
// Copyright (c) 2017-2023 Ismael Gutiérrez González. All rights reserved.
//
// This file is part of the Rusted PackFile Manager (RPFM) project,
// which can be found here: https://github.com/Frodo45127/rpfm.
//
// This file is licensed un... | let _ = std::fs::remove_dir_all(&self.local_path);
self.update_repo()
}
else {
// Reset the repo to his original state after the check
if current_branch_name!= master_refname {
self.checkout_branch(&repo, ¤t_branch_name)?;
... | let path = self.local_path.to_string_lossy().to_string() + "\\*.*";
let _ = SystemCommand::new("attrib").arg("-r").arg(path).arg("/s").output();
}
| conditional_block |
git.rs | //---------------------------------------------------------------------------//
// Copyright (c) 2017-2023 Ismael Gutiérrez González. All rights reserved.
//
// This file is part of the Rusted PackFile Manager (RPFM) project,
// which can be found here: https://github.com/Frodo45127/rpfm.
//
// This file is licensed un... | self, contents: &str) -> Result<()> {
let mut file = BufWriter::new(File::create(self.local_path.join(".gitignore"))?);
file.write_all(contents.as_bytes()).map_err(From::from)
}
/// This function switches the branch of a `GitIntegration` to the provided refspec.
pub fn checkout_branch(&self... | d_gitignore(& | identifier_name |
git.rs | //---------------------------------------------------------------------------//
// Copyright (c) 2017-2023 Ismael Gutiérrez González. All rights reserved.
//
// This file is part of the Rusted PackFile Manager (RPFM) project,
// which can be found here: https://github.com/Frodo45127/rpfm.
//
// This file is licensed un... | Err(_) => return Ok(GitResponse::NoLocalFiles),
};
// Just in case there are loose changes, stash them.
// Ignore a fail on this, as it's possible we don't have contents to stash.
let current_branch_name = Reference::normalize_name(repo.head()?.name().unwrap(), ReferenceForm... | let mut repo = match Repository::open(&self.local_path) {
Ok(repo) => repo,
// If this fails, it means we either we don´t have the repo downloaded, or we have a folder without the .git folder. | random_line_split |
main.rs | extern crate bible_reference_rs;
extern crate chrono;
extern crate futures;
extern crate hyper;
extern crate postgres;
extern crate serde;
extern crate url;
#[macro_use]
extern crate serde_json;
mod models;
use bible_reference_rs::*;
use futures::future::{Future, FutureResult};
use hyper::service::{NewService, Service... |
struct SearchService;
impl NewService for SearchService {
type ReqBody = Body;
type ResBody = Body;
type Error = ServiceError;
type Service = SearchService;
type Future = Box<Future<Item = Self::Service, Error = Self::Error> + Send>;
type InitError = ServiceError;
fn new_service(&self) -... | {
futures::future::ok(
Response::builder()
.header(header::CONTENT_TYPE, "application/json")
.header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
.header(header::ACCESS_CONTROL_ALLOW_METHODS, "GET")
.header(header::ACCESS_CONTROL_ALLOW_HEADERS, "Content-Type")
... | identifier_body |
main.rs | extern crate bible_reference_rs;
extern crate chrono;
extern crate futures;
extern crate hyper;
extern crate postgres;
extern crate serde;
extern crate url;
#[macro_use]
extern crate serde_json;
mod models;
use bible_reference_rs::*;
use futures::future::{Future, FutureResult};
use hyper::service::{NewService, Service... | (query: SearchPaginate, db: &Connection) -> FutureResult<Body, ServiceError> {
let text = &query.text;
let results = fetch_search_results(text.to_string(), query.page, db);
futures::future::ok(Body::from(
json!({
"meta": { "text": text, "page": query.page, "total": results.1 },
... | search_text | identifier_name |
main.rs | extern crate bible_reference_rs;
extern crate chrono;
extern crate futures;
extern crate hyper;
extern crate postgres;
extern crate serde;
extern crate url;
#[macro_use]
extern crate serde_json;
mod models;
use bible_reference_rs::*;
use futures::future::{Future, FutureResult};
use hyper::service::{NewService, Service... | .unwrap(),
)
}
struct SearchService;
impl NewService for SearchService {
type ReqBody = Body;
type ResBody = Body;
type Error = ServiceError;
type Service = SearchService;
type Future = Box<Future<Item = Self::Service, Error = Self::Error> + Send>;
type InitError = ServiceError;... | .header(header::ACCESS_CONTROL_ALLOW_METHODS, "GET")
.header(header::ACCESS_CONTROL_ALLOW_HEADERS, "Content-Type")
.body(body) | random_line_split |
borrow_set.rs | use crate::borrow_check::place_ext::PlaceExt;
use crate::borrow_check::nll::ToRegionVid;
use crate::borrow_check::path_utils::allow_two_phase_borrow;
use crate::dataflow::indexes::BorrowIndex;
use crate::dataflow::move_paths::MoveData;
use rustc::mir::traversal;
use rustc::mir::visit::{PlaceContext, Visitor, NonUseCont... | (
locals_are_invalidated_at_exit: bool,
body: &Body<'tcx>,
move_data: &MoveData<'tcx>
) -> Self {
struct HasStorageDead(BitSet<Local>);
impl<'tcx> Visitor<'tcx> for HasStorageDead {
fn visit_local(&mut self, local: &Local, ctx: PlaceContext, _: Location) {
... | build | identifier_name |
borrow_set.rs | use crate::borrow_check::place_ext::PlaceExt;
use crate::borrow_check::nll::ToRegionVid;
use crate::borrow_check::path_utils::allow_two_phase_borrow;
use crate::dataflow::indexes::BorrowIndex;
use crate::dataflow::move_paths::MoveData;
use rustc::mir::traversal;
use rustc::mir::visit::{PlaceContext, Visitor, NonUseCont... |
}
}
if locals_are_invalidated_at_exit {
LocalsStateAtExit::AllAreInvalidated
} else {
let mut has_storage_dead = HasStorageDead(BitSet::new_empty(body.local_decls.len()));
has_storage_dead.visit_body(body);
let mut has_storage_dead_or... | {
self.0.insert(*local);
} | conditional_block |
borrow_set.rs | use crate::borrow_check::place_ext::PlaceExt;
use crate::borrow_check::nll::ToRegionVid;
use crate::borrow_check::path_utils::allow_two_phase_borrow;
use crate::dataflow::indexes::BorrowIndex;
use crate::dataflow::move_paths::MoveData;
use rustc::mir::traversal;
use rustc::mir::visit::{PlaceContext, Visitor, NonUseCont... | }
}
impl<'tcx> BorrowSet<'tcx> {
pub fn build(
tcx: TyCtxt<'tcx>,
body: &Body<'tcx>,
locals_are_invalidated_at_exit: bool,
move_data: &MoveData<'tcx>,
) -> Self {
let mut visitor = GatherBorrows {
tcx,
body,
idx_vec: IndexVec::new(... | LocalsStateAtExit::SomeAreInvalidated{ has_storage_dead_or_moved }
} | random_line_split |
zigzag_graph.rs | forward: vec![None; cache_entries as usize],
reverse: vec![None; cache_entries as usize],
cache_entries,
}
}
pub fn contains_forward(&self, node: u32) -> bool {
assert!(node < self.cache_entries);
self.forward[node as usize].is_some()
}
pub f... |
}
#[inline]
fn real_index(&self, i: usize) -> usize {
if self.reversed {
(self.size() - 1) - i
} else {
i
}
}
}
impl<H, G> PartialEq for ZigZagGraph<H, G>
where
H: Hasher,
G: Graph<H>,
{
fn eq(&self, other: &ZigZagGraph<H, G>) -> bool {
... | {
cache.read_reverse(node as u32, |parents| cb(parents.unwrap()))
} | conditional_block |
zigzag_graph.rs | forward: vec![None; cache_entries as usize],
reverse: vec![None; cache_entries as usize],
cache_entries,
}
}
pub fn contains_forward(&self, node: u32) -> bool {
assert!(node < self.cache_entries);
self.forward[node as usize].is_some()
}
pub f... | (&self) -> usize {
self.expansion_degree
}
fn reversed(&self) -> bool {
self.reversed
}
// TODO: Optimization: Evaluate providing an `all_parents` (and hence
// `all_expanded_parents`) method that would return the entire cache
// in a single lock operation, or at least (if the ... | expansion_degree | identifier_name |
zigzag_graph.rs | forward: vec![None; cache_entries as usize],
reverse: vec![None; cache_entries as usize],
cache_entries,
}
}
pub fn contains_forward(&self, node: u32) -> bool {
assert!(node < self.cache_entries);
self.forward[node as usize].is_some()
}
pub f... |
/// To zigzag a graph, we just toggle its reversed field.
/// All the real work happens when we calculate node parents on-demand.
// We always share the two caches (forward/reversed) between
// ZigZag graphs even if each graph will use only one of those
// caches (depending of its direction). This... | {
Self::new(None, nodes, base_degree, expansion_degree, seed)
} | identifier_body |
zigzag_graph.rs |
forward: vec![None; cache_entries as usize],
reverse: vec![None; cache_entries as usize],
cache_entries,
}
}
pub fn contains_forward(&self, node: u32) -> bool {
assert!(node < self.cache_entries);
self.forward[node as usize].is_some()
}
pub ... | F: FnMut(&Vec<u32>) -> T,
{
if!self.use_cache {
// No cache usage, generate on demand.
return cb(&self.generate_expanded_parents(node));
}
// Check if we need to fill the cache.
if!self.contains_parents_cache(node) {
// Cache is empty so w... | random_line_split | |
diagnostic_server.rs | //! A small TCP server to handle collection of diagnostics information in a
//! cross-platform way for the `cargo fix` command.
use std::collections::HashSet;
use std::io::{BufReader, Read, Write};
use std::net::{Shutdown, SocketAddr, TcpListener, TcpStream};
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool,... | {
listener: TcpListener,
addr: SocketAddr,
}
pub struct StartedServer {
addr: SocketAddr,
done: Arc<AtomicBool>,
thread: Option<JoinHandle<()>>,
}
impl RustfixDiagnosticServer {
pub fn new() -> Result<Self, Error> {
let listener = TcpListener::bind("127.0.0.1:0")
.with_cont... | RustfixDiagnosticServer | identifier_name |
diagnostic_server.rs | //! A small TCP server to handle collection of diagnostics information in a
//! cross-platform way for the `cargo fix` command.
use std::collections::HashSet;
use std::io::{BufReader, Read, Write};
use std::net::{Shutdown, SocketAddr, TcpListener, TcpStream};
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool,... |
if!files.is_empty() {
writeln!(
self.config.shell().err(),
"\nafter fixes were automatically applied the compiler \
reported errors within these files:\n"
)?;
for file in... | {
self.config
.shell()
.warn("failed to automatically apply fixes suggested by rustc")?;
} | conditional_block |
diagnostic_server.rs | //! A small TCP server to handle collection of diagnostics information in a
//! cross-platform way for the `cargo fix` command.
use std::collections::HashSet;
use std::io::{BufReader, Read, Write};
use std::net::{Shutdown, SocketAddr, TcpListener, TcpStream};
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool,... | self.config.shell().warn(&format!("\
{}
If you are trying to migrate from the previous edition ({prev_edition}), the
process requires following these steps:
1. Start with `edition = \"{prev_edition}\"` in `Cargo.toml`
2. Run `cargo fix --edition`
3. Modify `Cargo.toml` to set `edition = \"{this_ed... | message: "".to_string(), // Dummy, so that this only long-warns once.
edition: *edition,
}) { | random_line_split |
asset.rs | 0} contains confidential data
EpochSealConfidential(NodeId),
/// nurn & replace seal definition for node {0} contains confidential data
BurnSealConfidential(NodeId),
/// inflation assignment (seal or state) for node {0} contains confidential
/// data
InflationAssignmentConfidential(NodeId),
... | let supply = *genesis_meta
.u64(FieldType::IssuedSupply)
.first()
.ok_or(Error::UnsatisfiedSchemaRequirement)?;
let mut issue_limit = 0;
// Check if issue limit can be known
for assignment in
genesis.owned_rights_by_type(OwnedRightType::Infla... | random_line_split | |
asset.rs | contains confidential data
EpochSealConfidential(NodeId),
/// nurn & replace seal definition for node {0} contains confidential data
BurnSealConfidential(NodeId),
/// inflation assignment (seal or state) for node {0} contains confidential
/// data
InflationAssignmentConfidential(NodeId),
... | lf) -> &str {
&self.active_nomination().ticker()
}
/// Current version of the asset contract, represented in Ricardian form
///
/// Current value determined by the last known renomination operation –
/// or, by the genesis nomination, if no renomination are known
///
/// NB: the ret... | (&se | identifier_name |
asset.rs | } contains confidential data
EpochSealConfidential(NodeId),
/// nurn & replace seal definition for node {0} contains confidential data
BurnSealConfidential(NodeId),
/// inflation assignment (seal or state) for node {0} contains confidential
/// data
InflationAssignmentConfidential(NodeId),
... | / Returns sum of all known allocations, in atomic value units
#[inline]
pub fn known_value(&self) -> AtomicValue {
self.known_allocations.iter().map(Allocation::value).sum()
}
/// Returns sum of known allocation after applying `filter` function. Useful
/// for filtering UTXOs owned by the c... | self.last_nomination().unwrap_or(&self.genesis_nomination)
}
// | identifier_body |
csv_import_accts_txns.rs | // Copyright (c) 2017-2020, scoobybejesus
// Redistributions must include the license: https://github.com/scoobybejesus/cryptools/blob/master/LEGAL.txt
use std::error::Error;
use std::process;
use std::fs::File;
use std::cell::{RefCell};
use std::collections::{HashMap};
use std::path::PathBuf;
use chrono::NaiveDate;
... | // A StringRecord doesn't accept the same range indexing needed below, so a Vec of Strings will be used
let headerstrings: Vec<String> = header1.into_iter().map(|field| field.to_string()).collect();
let acct_num_warn = "Transactions will not import correctly if account numbers in th... | random_line_split | |
csv_import_accts_txns.rs | // Copyright (c) 2017-2020, scoobybejesus
// Redistributions must include the license: https://github.com/scoobybejesus/cryptools/blob/master/LEGAL.txt
use std::error::Error;
use std::process;
use std::fs::File;
use std::cell::{RefCell};
use std::collections::{HashMap};
use std::path::PathBuf;
use chrono::NaiveDate;
... | (field: &str) -> String {
// First, remove commas.
let no_comma_string = field.replace(",", "");
let almost_done = no_comma_string.replace(" ", "");
// Next, if ASCII (better be), check for accounting formatting
if almost_done.is_ascii() {
if... | sanitize_string_for_d128_parsing_basic | identifier_name |
csv_import_accts_txns.rs | // Copyright (c) 2017-2020, scoobybejesus
// Redistributions must include the license: https://github.com/scoobybejesus/cryptools/blob/master/LEGAL.txt
use std::error::Error;
use std::process;
use std::fs::File;
use std::cell::{RefCell};
use std::collections::{HashMap};
use std::path::PathBuf;
use chrono::NaiveDate;
... | // Strip non-numeric and non-period characters
let all_done: String = near_done.chars()
.filter(|x|
x.is_numeric() |
(x == &(".".as_bytes()[0] as char)) |
(x == &("-".as_bytes()[0] as char)))
.collect()... | {
let mut near_done = "".to_string();
// First, remove commas.
let no_comma_string = field.replace(",", "");
let almost_done = no_comma_string.replace(" ", "");
// Next, if ASCII (better be), check for accounting formating
if almost_done.is_ascii... | identifier_body |
csv_import_accts_txns.rs | // Copyright (c) 2017-2020, scoobybejesus
// Redistributions must include the license: https://github.com/scoobybejesus/cryptools/blob/master/LEGAL.txt
use std::error::Error;
use std::process;
use std::fs::File;
use std::cell::{RefCell};
use std::collections::{HashMap};
use std::path::PathBuf;
use chrono::NaiveDate;
... | ;
if amount.is_nan() {
println!("FATAL: Couldn't convert amount to d128 for transaction:\n{:#?}", record);
std::process::exit(1);
}
let amount_rounded = round_d128_1e8(&amount);
if amount!= amount_rounded { changed_... | {
let c = sanitize_string_for_d128_parsing_full(field).parse::<d128>().unwrap();
amount = c;
} | conditional_block |
spline.rs | //! Spline curves and operations.
#[cfg(feature = "serialization")] use serde_derive::{Deserialize, Serialize};
#[cfg(not(feature = "std"))] use alloc::vec::Vec;
#[cfg(feature = "std")] use std::cmp::Ordering;
#[cfg(feature = "std")] use std::ops::{Div, Mul};
#[cfg(not(feature = "std"))] use core::ops::{Div, Mul};
#[c... | key and return the key already present.
///
/// The key is updated — if present — with the provided function.
///
/// # Notes
///
/// That function makes sense only if you want to change the interpolator (i.e. [`Key::t`]) of
/// your key. If you just want to change the interpolation mode or the carried v... | = self.0.len() {
None
} else {
Some(self.0.remove(index))
}
}
/// Update a | identifier_body |
spline.rs | //! Spline curves and operations.
#[cfg(feature = "serialization")] use serde_derive::{Deserialize, Serialize};
#[cfg(not(feature = "std"))] use alloc::vec::Vec;
#[cfg(feature = "std")] use std::cmp::Ordering;
#[cfg(feature = "std")] use std::ops::{Div, Mul};
#[cfg(not(feature = "std"))] use core::ops::{Div, Mul};
#[c... | ried value.
pub value: &'a mut V,
/// Interpolation mode to use for that key.
pub interpolation: &'a mut Interpolation<T, V>,
}
// Normalize a time ([0;1]) given two control points.
#[inline(always)]
pub(crate) fn normalize_time<T, V>(
t: T,
cp: &Key<T, V>,
cp1: &Key<T, V>
) -> T where T: Additive + Div<T,... | // Car | identifier_name |
spline.rs | //! Spline curves and operations.
#[cfg(feature = "serialization")] use serde_derive::{Deserialize, Serialize};
#[cfg(not(feature = "std"))] use alloc::vec::Vec;
#[cfg(feature = "std")] use std::cmp::Ordering;
#[cfg(feature = "std")] use std::ops::{Div, Mul};
#[cfg(not(feature = "std"))] use core::ops::{Div, Mul};
#[c... | Interpolation::Linear => {
let cp1 = &keys[i + 1];
let nt = normalize_time(t, cp0, cp1);
let value = Interpolate::lerp(cp0.value, cp1.value, nt);
Some((value, cp0, Some(cp1)))
}
Interpolation::Cosine => {
let two_t = T::one() + T::one();
let cp1 = &key... | random_line_split | |
spline.rs | //! Spline curves and operations.
#[cfg(feature = "serialization")] use serde_derive::{Deserialize, Serialize};
#[cfg(not(feature = "std"))] use alloc::vec::Vec;
#[cfg(feature = "std")] use std::cmp::Ordering;
#[cfg(feature = "std")] use std::ops::{Div, Mul};
#[cfg(not(feature = "std"))] use core::ops::{Div, Mul};
#[c... | None
}
}
})
}
/// Sample a spline at a given time with clamping.
pub fn clamped_sample(&self, t: T) -> Option<V>
where T: Additive + One + Trigo + Mul<T, Output = T> + Div<T, Output = T> + PartialOrd,
V: Interpolate<T> {
self.clamped_sample_with_key(t).map(|(v, _, _)| v)
}
... | ((last.value, &last, None))
} else {
| conditional_block |
ourairports.rs | use serde::de::{self, Unexpected};
use serde::{Deserialize, Deserializer, Serialize};
/// Contains a record of a single airport.
#[derive(Deserialize, Serialize)]
pub struct Airport {
/// Internal OurAirports integer identifier for the airport.
/// This will stay persistent, even if the airport code changes.
... | <'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
where
D: Deserializer<'de>,
{
let keywords = String::deserialize(deserializer)?;
match keywords.len() {
0 => Ok(vec![]),
_ => Ok(keywords.split(',').map(|s| s.trim().to_string()).collect()),
}
}
| vec_string_from_string | identifier_name |
ourairports.rs | use serde::de::{self, Unexpected};
use serde::{Deserialize, Deserializer, Serialize};
/// Contains a record of a single airport.
#[derive(Deserialize, Serialize)]
pub struct Airport {
/// Internal OurAirports integer identifier for the airport.
/// This will stay persistent, even if the airport code changes.
... | /// for voice communication (radio navigation aids appear in struct Navaids)
#[derive(Deserialize, Serialize)]
pub struct AirportFrequency {
/// Internal OurAirports integer identifier for the frequency.
/// This will stay persistent, even if the radio frequency or description changes.
id: String,
/// I... | keywords: Vec<String>,
}
/// Contains information about a single airport radio frequency | random_line_split |
num_format.rs | // This file is part of the uutils coreutils package.
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
// spell-checker:ignore (vars) charf cninetyninehexfloatf decf floatf intf scif strf Cninety
//! handles creating printed output for nu... | (field: &FormatField, in_str_opt: Option<&String>) -> Option<String> {
let field_char = field.field_char;
// num format mainly operates by further delegating to one of
// several Formatter structs depending on the field
// see formatter.rs for more details
// to do switch to static dispatch
le... | num_format | identifier_name |
num_format.rs | // This file is part of the uutils coreutils package.
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
// spell-checker:ignore (vars) charf cninetyninehexfloatf decf floatf intf scif strf Cninety
//! handles creating printed output for nu... |
// when character constant arguments have excess characters
// issue a warning when POSIXLY_CORRECT is not set
fn warn_char_constant_ign(remaining_bytes: &[u8]) {
match env::var("POSIXLY_CORRECT") {
Ok(_) => {}
Err(e) => {
if let env::VarError::NotPresent = e {
show_war... | {
// important: keep println here not print
show_error!("{}: expected a numeric value", pf_arg.maybe_quote());
} | identifier_body |
num_format.rs | // This file is part of the uutils coreutils package.
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
// spell-checker:ignore (vars) charf cninetyninehexfloatf decf floatf intf scif strf Cninety
//! handles creating printed output for nu... | ret.offset += 1;
top_char = str_it.next();
}
_ => {}
}
// we want to exit with offset being
// the index of the first non-zero
// digit before the decimal point or
// if there is none, the zero before the
// decimal point, or, if there is none,
// the ... | random_line_split | |
publish.rs | //!
//! The Zargo package manager `publish` subcommand.
//!
use std::convert::TryFrom;
use std::path::PathBuf;
use std::str::FromStr;
use colored::Colorize;
use structopt::StructOpt;
use zksync::web3::types::H256;
use zksync_eth_signer::PrivateKeySigner;
use zksync_types::tx::PackedEthSignature;
use crate::error::E... |
let verifying_key = VerifyingKeyFile::try_from(&verifying_key_path)?;
if!self.quiet {
eprintln!(
" {} the instance `{}` of `{} v{}` to network `{}`",
"Uploading".bright_green(),
self.instance,
manifest.project.name,
... | {
VirtualMachine::setup_contract(
self.verbosity,
self.quiet,
&binary_path,
zinc_const::contract::CONSTRUCTOR_IDENTIFIER,
&proving_key_path,
&verifying_key_path,
)?;
} | conditional_block |
publish.rs | //!
//! The Zargo package manager `publish` subcommand.
//!
use std::convert::TryFrom;
use std::path::PathBuf;
use std::str::FromStr;
use colored::Colorize;
use structopt::StructOpt;
use zksync::web3::types::H256;
use zksync_eth_signer::PrivateKeySigner;
use zksync_types::tx::PackedEthSignature;
use crate::error::E... | let initial_transfer = crate::transaction::new_initial(
&wallet,
response.address,
self.change_pubkey_fee_token,
response.change_pubkey_fee,
)
.await?;
let address = response.address;
let response = http_client
.initializ... | let wallet =
zksync::Wallet::new(zksync::RpcProvider::new(network.into()), wallet_credentials)
.await?;
| random_line_split |
publish.rs | //!
//! The Zargo package manager `publish` subcommand.
//!
use std::convert::TryFrom;
use std::path::PathBuf;
use std::str::FromStr;
use colored::Colorize;
use structopt::StructOpt;
use zksync::web3::types::H256;
use zksync_eth_signer::PrivateKeySigner;
use zksync_types::tx::PackedEthSignature;
use crate::error::E... |
}
impl Command {
///
/// A shortcut constructor.
///
pub fn new(
verbosity: usize,
quiet: bool,
manifest_path: PathBuf,
instance: String,
network: Option<String>,
change_pubkey_fee_token: Option<String>,
) -> Self {
Self {
verbosi... | {
Self {
address,
account_id,
}
} | identifier_body |
publish.rs | //!
//! The Zargo package manager `publish` subcommand.
//!
use std::convert::TryFrom;
use std::path::PathBuf;
use std::str::FromStr;
use colored::Colorize;
use structopt::StructOpt;
use zksync::web3::types::H256;
use zksync_eth_signer::PrivateKeySigner;
use zksync_types::tx::PackedEthSignature;
use crate::error::E... | {
/// The address of the published contract instance.
pub address: zksync_types::Address,
/// The account ID of the published contract instance.
pub account_id: zksync_types::AccountId,
}
impl Data {
///
/// A shortcut constructor.
///
pub fn new(address: zksync_types::Address, account... | Data | identifier_name |
manager.rs | use std::rc::Rc;
use std::cell::RefCell;
use std::path::{Path,PathBuf};
use std::fs;
use std::collections::HashMap;
use std::io::Write;
use Realm;
use Result;
use Systemd;
use RealmSymlinks;
use NetworkConfig;
use util::*;
const REALMS_BASE_PATH: &str = "/realms";
pub struct RealmManager {
/// Map from realm na... |
fn create_network_config() -> Result<Rc<RefCell<NetworkConfig>>> {
let mut network = NetworkConfig::new();
network.add_bridge("clear", "172.17.0.0/24")?;
Ok(Rc::new(RefCell::new(network)))
}
pub fn load() -> Result<RealmManager> {
let mut manager = RealmManager::new()?;
... | {
let network = RealmManager::create_network_config()?;
Ok(RealmManager {
realm_map: HashMap::new(),
realm_list: Vec::new(),
symlinks: Rc::new(RefCell::new(RealmSymlinks::new())),
network: network.clone(),
systemd: Systemd::new(network),
... | identifier_body |
manager.rs | use std::rc::Rc;
use std::cell::RefCell;
use std::path::{Path,PathBuf};
use std::fs;
use std::collections::HashMap;
use std::io::Write;
use Realm;
use Result;
use Systemd;
use RealmSymlinks;
use NetworkConfig;
use util::*;
const REALMS_BASE_PATH: &str = "/realms";
pub struct RealmManager {
/// Map from realm na... |
pub fn set_default_by_name(&self, realm_name: &str) -> Result<()> {
self.with_named_realm(realm_name, false, |realm| realm.set_default())
}
pub fn realm_name_exists(&self, name: &str) -> bool {
self.realm_map.contains_key(name)
}
pub fn realm(&self, name: &str) -> Option<&Realm> {
... | random_line_split | |
manager.rs | use std::rc::Rc;
use std::cell::RefCell;
use std::path::{Path,PathBuf};
use std::fs;
use std::collections::HashMap;
use std::io::Write;
use Realm;
use Result;
use Systemd;
use RealmSymlinks;
use NetworkConfig;
use util::*;
const REALMS_BASE_PATH: &str = "/realms";
pub struct RealmManager {
/// Map from realm na... | (&mut self, realm: Realm) -> &Realm {
self.realm_map.insert(realm.name().to_owned(), realm.clone());
self.realm_list.push(realm.clone());
self.realm_map.get(realm.name()).expect("cannot find realm we just added to map")
}
fn remove_realm_entry(&mut self, name: &str) -> Result<()> {
... | add_realm_entry | identifier_name |
http.rs | //! This example uses [hyper][] to create a http server which handles requests asynchronously in
//! gluon. To do this we define a few types and functions in Rust with which we register in gluon
//! so that we can communicate with `hyper`. The rest of the implementation is done in gluon,
//! routing the requests and co... | stream.poll().map(|async| async.map(IO::Value))
})))
}
// A http body that is being written
pub struct ResponseBody(Arc<Mutex<Option<Sender<Result<Chunk, hyper::Error>>>>>);
impl fmt::Debug for ResponseBody {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "hyper::Response")
... | // polled until completion. After `poll` returns `Ready` the value is then returned to the
// gluon function which called `read_chunk`
FutureResult(Box::new(poll_fn(move || {
let mut stream = body.lock().unwrap(); | random_line_split |
http.rs | //! This example uses [hyper][] to create a http server which handles requests asynchronously in
//! gluon. To do this we define a few types and functions in Rust with which we register in gluon
//! so that we can communicate with `hyper`. The rest of the implementation is done in gluon,
//! routing the requests and co... |
}
define_vmtype! { StatusCode }
impl<'vm> Getable<'vm> for Wrap<StatusCode> {
fn from_value(_: &'vm Thread, value: Variants) -> Self {
use hyper::StatusCode::*;
match value.as_ref() {
ValueRef::Data(data) => Wrap(match data.tag() {
0 => Ok,
1 => NotFoun... | {
use hyper::Method::*;
context.stack.push(Value::tag(match self.0 {
Get => 0,
Post => 1,
Delete => 2,
_ => {
return Err(VmError::Message(format!(
"Method `{:?}` does not exist in gluon",
self.0
... | identifier_body |
http.rs | //! This example uses [hyper][] to create a http server which handles requests asynchronously in
//! gluon. To do this we define a few types and functions in Rust with which we register in gluon
//! so that we can communicate with `hyper`. The rest of the implementation is done in gluon,
//! routing the requests and co... | }
}
Err(err) => {
let _ = stderr().write(format!("{}", err).as_bytes());
Ok(HyperResponse::new().with_status(StatusCode::InternalServerError))
}
... |
let _ = stderr().write(err.as_bytes());
Ok(
HyperResponse::new()
.with_status(StatusCode::InternalServerError),
)
... | conditional_block |
http.rs | //! This example uses [hyper][] to create a http server which handles requests asynchronously in
//! gluon. To do this we define a few types and functions in Rust with which we register in gluon
//! so that we can communicate with `hyper`. The rest of the implementation is done in gluon,
//! routing the requests and co... | (
response: &ResponseBody,
bytes: &[u8],
) -> FutureResult<Box<Future<Item = IO<()>, Error = VmError> + Send +'static>> {
use futures::future::poll_fn;
use futures::AsyncSink;
// Turn `bytes´ into a `Chunk` which can be sent to the http body
let mut unsent_chunk = Some(Ok(bytes.to_owned().into(... | write_response | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.