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 |
|---|---|---|---|---|
tensor.rs | use std::collections::HashSet;
use std::io::{Read, Seek};
use std::ops::Range;
use std::str::FromStr;
use std::sync::Mutex;
use crate::model::Model;
use tract_hir::internal::*;
#[derive(Debug, Default, Clone)]
pub struct TensorsValues(pub Vec<TensorValues>);
impl TensorsValues {
pub fn by_name(&self, name: &str)... |
self.by_input_ix_mut(ix).unwrap()
}
pub fn add(&mut self, other: TensorValues) {
let mut tensor = other.input_index.and_then(|ix| self.by_input_ix_mut(ix));
if tensor.is_none() {
tensor = other.name.as_deref().and_then(|ix| self.by_name_mut(ix))
}
if let S... | {
self.add(TensorValues { input_index: Some(ix), ..TensorValues::default() });
} | conditional_block |
tensor.rs | use std::collections::HashSet;
use std::io::{Read, Seek};
use std::ops::Range;
use std::str::FromStr;
use std::sync::Mutex;
use crate::model::Model;
use tract_hir::internal::*;
#[derive(Debug, Default, Clone)]
pub struct TensorsValues(pub Vec<TensorValues>);
impl TensorsValues {
pub fn by_name(&self, name: &str)... | (&mut self, name: &str) -> Option<&mut TensorValues> {
self.0.iter_mut().find(|t| t.name.as_deref() == Some(name))
}
pub fn by_name_mut_with_default(&mut self, name: &str) -> &mut TensorValues {
if self.by_name_mut(name).is_none() {
self.add(TensorValues { name: Some(name.to_string()... | by_name_mut | identifier_name |
tensor.rs | use std::collections::HashSet;
use std::io::{Read, Seek};
use std::ops::Range;
use std::str::FromStr;
use std::sync::Mutex;
use crate::model::Model;
use tract_hir::internal::*;
#[derive(Debug, Default, Clone)]
pub struct TensorsValues(pub Vec<TensorValues>);
impl TensorsValues {
pub fn by_name(&self, name: &str)... | values.iter().map(|v| tensor_for_fact(v.borrow(), None, None).map(|t| t.into())).collect()
}
pub fn make_inputs_for_model(model: &dyn Model) -> TractResult<TVec<TValue>> {
make_inputs(
&model
.input_outlets()
.iter()
.map(|&t| model.outlet_typedfact(t))
.coll... | }
Ok((0..tmp[0].len()).map(|turn| tmp.iter().map(|t| t[turn].clone()).collect()).collect())
}
fn make_inputs(values: &[impl std::borrow::Borrow<TypedFact>]) -> TractResult<TVec<TValue>> { | random_line_split |
tensor.rs | use std::collections::HashSet;
use std::io::{Read, Seek};
use std::ops::Range;
use std::str::FromStr;
use std::sync::Mutex;
use crate::model::Model;
use tract_hir::internal::*;
#[derive(Debug, Default, Clone)]
pub struct TensorsValues(pub Vec<TensorValues>);
impl TensorsValues {
pub fn by_name(&self, name: &str)... |
#[allow(unused_variables)]
pub fn tensor_for_fact(
fact: &TypedFact,
streaming_dim: Option<usize>,
tv: Option<&TensorValues>,
) -> TractResult<Tensor> {
if let Some(value) = &fact.konst {
return Ok(value.clone().into_tensor());
}
#[cfg(pulse)]
{
if fact.shape.stream_info().... | {
make_inputs(
&model
.input_outlets()
.iter()
.map(|&t| model.outlet_typedfact(t))
.collect::<TractResult<Vec<TypedFact>>>()?,
)
} | identifier_body |
rtic-i2s-audio-in-out.rs | //! # I2S example with rtic
//!
//! This application show how to use I2sDriver with interruption. Be careful to you ear, wrong
//! operation can trigger loud noise on the DAC output.
//!
//! # Hardware required
//!
//! * a STM32F411 based board
//! * I2S ADC and DAC, eg PCM1808 and PCM5102 from TI
//! * Audio signal at... |
// processing audio
#[task(binds = SPI5, local = [count: u32 = 0,process_c,process_p])]
fn process(cx: process::Context) {
let count = cx.local.count;
let process_c = cx.local.process_c;
let process_p = cx.local.process_p;
while let Some(mut smpl) = process_c.dequeue() {
... | {
writeln!(cx.local.logs_chan, "{}", message).unwrap();
} | identifier_body |
rtic-i2s-audio-in-out.rs | //! # I2S example with rtic
//!
//! This application show how to use I2sDriver with interruption. Be careful to you ear, wrong
//! operation can trigger loud noise on the DAC output.
//!
//! # Hardware required
//!
//! * a STM32F411 based board
//! * I2S ADC and DAC, eg PCM1808 and PCM5102 from TI
//! * Audio signal at... | (cx: i2s2::Context) {
let frame_state = cx.local.frame_state;
let frame = cx.local.frame;
let adc_p = cx.local.adc_p;
let i2s2_driver = cx.shared.i2s2_driver;
let status = i2s2_driver.status();
// It's better to read first to avoid triggering ovr flag
if status.rx... | i2s2 | identifier_name |
rtic-i2s-audio-in-out.rs | //! # I2S example with rtic
//!
//! This application show how to use I2sDriver with interruption. Be careful to you ear, wrong
//! operation can trigger loud noise on the DAC output.
//!
//! # Hardware required
//!
//! * a STM32F411 based board
//! * I2S ADC and DAC, eg PCM1808 and PCM5102 from TI
//! * Audio signal at... | let gpiob = device.GPIOB.split();
let gpioc = device.GPIOC.split();
let rcc = device.RCC.constrain();
let clocks = rcc
.cfgr
.use_hse(8u32.MHz())
.sysclk(96.MHz())
.hclk(96.MHz())
.pclk1(50.MHz())
.pclk2(100.MHz())
... | let gpioa = device.GPIOA.split(); | random_line_split |
crypto_box.rs | use crate::internal::rayon::rayon_exec;
use crate::internal::x25519;
use block_padding::Padding;
use crypto_box as lib_crypto_box;
use std::sync::Arc;
/// Length of the crypto box aead nonce.
/// Ideally this would be exposed from upstream but I didn't see a good way to get at it directly.
pub const NONCE_BYTES: usize... |
Err(_) => Ok(None),
}
})
.await
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test(flavor = "multi_thread")]
async fn it_can_encrypt_and_decrypt() {
for input in [
// Empty vec.
vec![],
// Small vec.
vec![0],
... | {
match block_padding::Iso7816::unpad(&decrypted_data) {
// @todo do we want associated data to enforce the originating DHT space?
Ok(unpadded) => Ok(Some(CryptoBoxData {
data: Arc::new(unpadded.to_vec()),
})),
... | conditional_block |
crypto_box.rs | use crate::internal::rayon::rayon_exec;
use crate::internal::x25519;
use block_padding::Padding;
use crypto_box as lib_crypto_box;
use std::sync::Arc;
/// Length of the crypto box aead nonce.
/// Ideally this would be exposed from upstream but I didn't see a good way to get at it directly.
pub const NONCE_BYTES: usize... | ];
to_encrypt.extend(padding_delimiter);
to_encrypt.extend(padding);
let encrypted_data = Arc::new(sender_box.encrypt(
AsRef::<[u8; NONCE_BYTES]>::as_ref(&nonce).into(),
to_encrypt.as_slice(),
)?);
// @todo do we want associated data to enforce t... | BLOCK_PADDING_SIZE
- (data.data.len() + 1) % BLOCK_PADDING_SIZE | random_line_split |
crypto_box.rs | use crate::internal::rayon::rayon_exec;
use crate::internal::x25519;
use block_padding::Padding;
use crypto_box as lib_crypto_box;
use std::sync::Arc;
/// Length of the crypto box aead nonce.
/// Ideally this would be exposed from upstream but I didn't see a good way to get at it directly.
pub const NONCE_BYTES: usize... | (slice: &[u8]) -> Result<Self, Self::Error> {
if slice.len() == NONCE_BYTES {
let mut inner = [0; NONCE_BYTES];
inner.copy_from_slice(slice);
Ok(Self(inner))
} else {
Err(crate::error::LairError::CryptoBoxNonceLength)
}
}
}
impl CryptoBoxNonce... | try_from | identifier_name |
crypto_box.rs | use crate::internal::rayon::rayon_exec;
use crate::internal::x25519;
use block_padding::Padding;
use crypto_box as lib_crypto_box;
use std::sync::Arc;
/// Length of the crypto box aead nonce.
/// Ideally this would be exposed from upstream but I didn't see a good way to get at it directly.
pub const NONCE_BYTES: usize... |
}
impl CryptoBoxData {
/// Length of newtype is length of inner.
pub fn len(&self) -> usize {
AsRef::<[u8]>::as_ref(self).len()
}
/// For clippy.
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl From<Vec<u8>> for CryptoBoxData {
fn from(v: Vec<u8>) -> Self {
... | {
self.data.as_ref()
} | identifier_body |
scoped_signal_handler.rs | // Copyright 2021 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Provides a struct for registering signal handlers that get cleared on drop.
use std::convert::TryFrom;
use std::fmt;
use std::io::{Cursor, Write};... | let mut buffer = [0u8; 64];
let mut cursor = Cursor::new(buffer.as_mut());
if writeln!(cursor, "signal handler got error for: {:?}", signal_debug).is_ok() {
let len = cursor.position() as usize;
// Safe in the sense that buffer is owned and the length is checked. This may... | {
// Make an effort to surface an error.
if catch_unwind(|| H::handle_signal(Signal::try_from(signum).unwrap())).is_err() {
// Note the following cannot be used:
// eprintln! - uses std::io which has locks that may be held.
// format! - uses the allocator which enforces mutual exclusion.... | identifier_body |
scoped_signal_handler.rs | // Copyright 2021 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Provides a struct for registering signal handlers that get cleared on drop.
use std::convert::TryFrom;
use std::fmt;
use std::io::{Cursor, Write};... |
line.clear();
}
}
/// Wait for a process to block either in a sleeping or disk sleep state.
fn wait_for_thread_to_sleep(tid: Pid, timeout: Duration) -> result::Result<(), errno::Error> {
let start = Instant::now();
loop {
if thread_is_sleeping(tid)? {
... | {
return Ok(matches!(
stripped.trim_start().chars().next(),
Some('S') | Some('D')
));
} | conditional_block |
scoped_signal_handler.rs | // Copyright 2021 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Provides a struct for registering signal handlers that get cleared on drop.
use std::convert::TryFrom;
use std::fmt;
use std::io::{Cursor, Write};... | // format! - uses the allocator which enforces mutual exclusion.
// Get the debug representation of signum.
let signal: Signal;
let signal_debug: &dyn fmt::Debug = match Signal::try_from(signum) {
Ok(s) => {
signal = s;
&signal as &dyn fmt::De... | // eprintln! - uses std::io which has locks that may be held. | random_line_split |
scoped_signal_handler.rs | // Copyright 2021 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Provides a struct for registering signal handlers that get cleared on drop.
use std::convert::TryFrom;
use std::fmt;
use std::io::{Cursor, Write};... | ;
/// # Safety
/// Safe because handle_signal is async-signal safe.
unsafe impl SignalHandler for EmptySignalHandler {
fn handle_signal(_: Signal) {}
}
/// Blocks until SIGINT is received, which often happens because Ctrl-C was pressed in an
/// interactive terminal.
///
/// Note: if you are using a multi-threaded... | EmptySignalHandler | identifier_name |
wavelet_tree_pointer.rs | use bio::data_structures::rank_select::RankSelect;
use bv::BitVec;
use bv::BitsMut;
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use snafu::{ensure, Snafu};
use std::fmt::Debug;
use std::hash::Hash;
use std::ops::Index;
///custom errors for the tree with pointer
#[derive(Debug, Snafu)]
pub enum Error... | + Clone + Ord + Debug>(alphabet: &[E], sequence: Vec<E>) -> BinNode {
let count = sequence.len();
if alphabet.len() <= 1 {
let value = BitVec::new_fill(true, count as u64);
BinNode {
value: RankSelect::new(value, 1),
left: None,
rig... | de<E: Hash | identifier_name |
wavelet_tree_pointer.rs | use bio::data_structures::rank_select::RankSelect;
use bv::BitVec;
use bv::BitsMut;
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use snafu::{ensure, Snafu};
use std::fmt::Debug;
use std::hash::Hash;
use std::ops::Index;
///custom errors for the tree with pointer
#[derive(Debug, Snafu)]
pub enum Error... | nts a non-consuming Iterator for the WaveletTree
impl<'de, T> IntoIterator for &'de WaveletTree<T>
where
T: Hash + Clone + Ord + Debug + Copy + Serialize + Deserialize<'de>,
{
type Item = T;
type IntoIter = Iterhelper<'de, T>;
fn into_iter(self) -> Self::IntoIter {
Iterhelper {
posit... | f.value.bits().len()
}
}
///Impleme | identifier_body |
wavelet_tree_pointer.rs | use bio::data_structures::rank_select::RankSelect;
use bv::BitVec;
use bv::BitsMut;
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use snafu::{ensure, Snafu};
use std::fmt::Debug;
use std::hash::Hash;
use std::ops::Index;
///custom errors for the tree with pointer
#[derive(Debug, Snafu)]
pub enum Error... | Iterhelper {
position: 0,
tree: self,
}
}
}
impl<'de, T> Iterator for Iterhelper<'de, T>
where
T: Hash + Clone + Ord + Debug + Copy + Serialize + Deserialize<'de>,
{
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
self.position += 1;
let... | type Item = T;
type IntoIter = Iterhelper<'de, T>;
fn into_iter(self) -> Self::IntoIter { | random_line_split |
wavelet_tree_pointer.rs | use bio::data_structures::rank_select::RankSelect;
use bv::BitVec;
use bv::BitsMut;
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use snafu::{ensure, Snafu};
use std::fmt::Debug;
use std::hash::Hash;
use std::ops::Index;
///custom errors for the tree with pointer
#[derive(Debug, Snafu)]
pub enum Error... | None
}
}
}
| conditional_block | |
mod.rs | // Import the rendering contract
use crate::traits::RendererBase;
use crate::traits::UIElement;
use crate::traits::UIEvent;
// We make use of the arguments of the event loop
use piston::input::{UpdateArgs, RenderArgs, Key};
// Used to send events to the application
use std::sync::mpsc;
// Use the GlGraphics backend
... |
if sample > self.max_amp {
self.max_amp = sample
}
}
// Min/max frequency
// Buffer size
text::Text::new_color(fg_color, self.base_font_size as u32).draw(
format!(
"Analyzed frequencies: {} Hz to {} Hz (channels: {})",
format_number(audio.bin_frequency.round()... | {
self.min_amp = sample
} | conditional_block |
mod.rs | // Import the rendering contract
use crate::traits::RendererBase;
use crate::traits::UIElement;
use crate::traits::UIEvent;
// We make use of the arguments of the event loop
use piston::input::{UpdateArgs, RenderArgs, Key};
// Used to send events to the application
use std::sync::mpsc;
// Use the GlGraphics backend
... |
}
| {
// ...
} | identifier_body |
mod.rs | // Import the rendering contract
use crate::traits::RendererBase;
use crate::traits::UIElement;
use crate::traits::UIEvent;
// We make use of the arguments of the event loop
use piston::input::{UpdateArgs, RenderArgs, Key};
// Used to send events to the application
use std::sync::mpsc;
// Use the GlGraphics backend
... |
// Font size relative to UI overlay (always three lines high)
self.base_font_size = (overlay_height / 3.0 * 0.95).floor();
if self.base_font_size > 14.0 {
self.base_font_size = 14.0; // Don't overdo it
}
// Colors
let bg_color = [0.0, 0.0, 0.0, self.ui_opacity as f32];
// Overlay ar... | let overlay_top = self.height as f64 * 0.8;
let overlay_height = self.height as f64 * 0.2; | random_line_split |
mod.rs | // Import the rendering contract
use crate::traits::RendererBase;
use crate::traits::UIElement;
use crate::traits::UIEvent;
// We make use of the arguments of the event loop
use piston::input::{UpdateArgs, RenderArgs, Key};
// Used to send events to the application
use std::sync::mpsc;
// Use the GlGraphics backend
... | (&mut self, begin_point: [f64; 2], text: String, gl: &mut GlGraphics, context: Context) -> [f64; 4] {
// Draws a text button with the UIs style
let padding = 5.0;
let real_width = self.ui_font.width(self.base_font_size as u32, text.as_str()).unwrap() + 2.0 * padding;
let real_height = self.base_font_si... | draw_text_button | identifier_name |
mod.rs | #![allow(dead_code)]
pub mod hypotheses;
use std::collections::HashMap;
use std::hash::Hash;
use std::cmp::{Eq, Ordering};
use std::iter::FromIterator;
use ansi_term::Style;
use triangles::Study;
use inference::triangle::hypotheses::BasicHypothesis;
use inference::triangle::hypotheses::JoinedHypothesis;
pub use inf... | nch]
fn concerning_the_expense_of_prediction(bencher: &mut Bencher) {
let distribution = complexity_prior(standard_basic_hypotheses());
bencher.iter(|| {
distribution.predict(&Study::sample(), true);
});
}
#[bench]
fn concerning_the_expense_of_the_value(bencher: &mut... | let distribution = complexity_prior(standard_basic_hypotheses());
bencher.iter(|| {
distribution.entropy()
});
}
#[be | identifier_body |
mod.rs | #![allow(dead_code)]
pub mod hypotheses;
use std::collections::HashMap;
use std::hash::Hash;
use std::cmp::{Eq, Ordering};
use std::iter::FromIterator;
use ansi_term::Style;
use triangles::Study;
use inference::triangle::hypotheses::BasicHypothesis;
use inference::triangle::hypotheses::JoinedHypothesis;
pub use inf... | // that I ran into when I was first sketching out the number game, as
// accounted in the README: if the true meaning of the complexity
// penalty is that the hypothesis "A" gets to sum over the unspecified
// details borne by the more complicated hypotheses "A ∧ B" and "A ∧
// C... | // ⎳ i=1 1/2^i = 1
//
// So ... I want to give conjunctions and disjunctions a lower prior
// probability, but I'm running into the same philosophical difficulty | random_line_split |
mod.rs | #![allow(dead_code)]
pub mod hypotheses;
use std::collections::HashMap;
use std::hash::Hash;
use std::cmp::{Eq, Ordering};
use std::iter::FromIterator;
use ansi_term::Style;
use triangles::Study;
use inference::triangle::hypotheses::BasicHypothesis;
use inference::triangle::hypotheses::JoinedHypothesis;
pub use inf... | (&self, desired_bits: f64, sample_cap: usize)
-> Study {
let mut study = Study::sample();
let mut value = self.value_of_information(&study);
let mut top_study = study.clone();
let mut top_value = value;
let mut samples = 1;
loop {
i... | burning_question | identifier_name |
mod.rs | #![allow(dead_code)]
pub mod hypotheses;
use std::collections::HashMap;
use std::hash::Hash;
use std::cmp::{Eq, Ordering};
use std::iter::FromIterator;
use ansi_term::Style;
use triangles::Study;
use inference::triangle::hypotheses::BasicHypothesis;
use inference::triangle::hypotheses::JoinedHypothesis;
pub use inf... |
study = Study::sample();
value = self.value_of_information(&study);
samples += 1;
}
top_study
}
pub fn inspect(&self, n: usize) {
let mut backing = self.backing().iter().collect::<Vec<_>>();
backing.sort_by(|a, b| b.1.partial_cmp(a.1).unwrap_... | {
break;
} | conditional_block |
lib.rs | #![allow(clippy::many_single_char_names, non_snake_case)]
pub mod chase;
pub mod mvd;
mod parser;
mod sorted_uvec;
use itertools::Itertools;
use mvd::MVD;
use rand::prelude::Distribution;
use sorted_uvec::SortedUVec;
use std::{borrow::Borrow, mem, ops::Not};
use std::{
collections::HashMap,
fmt::{self, Displa... |
}
bcnf
}
pub struct NumberOfAttrs(u32);
impl NumberOfAttrs {
pub fn new(n: u32) -> Self {
Self(n)
}
}
impl Distribution<FD> for NumberOfAttrs {
fn sample<R: rand::Rng +?Sized>(&self, rng: &mut R) -> FD {
let n = self.0;
let mut source = vec![];
let mut target = v... | {
bcnf.push(rel);
} | conditional_block |
lib.rs | #![allow(clippy::many_single_char_names, non_snake_case)]
pub mod chase;
pub mod mvd;
mod parser;
mod sorted_uvec;
use itertools::Itertools;
use mvd::MVD;
use rand::prelude::Distribution;
use sorted_uvec::SortedUVec;
use std::{borrow::Borrow, mem, ops::Not};
use std::{
collections::HashMap,
fmt::{self, Displa... | (&self, f: &mut Formatter) -> fmt::Result {
<Self as fmt::Debug>::fmt(self, f)
}
}
pub fn categorize(sub: &Attrs, rel: &Attrs, FDs: &[FD]) -> Category {
let closure = closure_of(sub, FDs);
if!closure.is_superset(&rel) {
return Category::Nonkey;
}
let has_subkey = sub
.iter()... | fmt | identifier_name |
lib.rs | #![allow(clippy::many_single_char_names, non_snake_case)]
pub mod chase;
pub mod mvd;
mod parser;
mod sorted_uvec;
use itertools::Itertools;
use mvd::MVD;
use rand::prelude::Distribution;
use sorted_uvec::SortedUVec;
use std::{borrow::Borrow, mem, ops::Not};
use std::{
collections::HashMap,
fmt::{self, Displa... |
while let Some((rel, FDs)) = candidates.pop() {
// every 2-attribute relation is in BCNF
if rel.len() <= 2 {
bcnf.push(rel);
continue;
}
if let Some(fd) = violation(&rel, &FDs) {
let rel_0 = closure_of(&fd.source, &FDs);
let FDs_0 = p... | pub fn bcnf_decomposition(rel: &Attrs, FDs: &[FD]) -> Vec<Attrs> {
let rel: Attrs = rel.clone();
let mut candidates: Vec<(Attrs, Vec<FD>)> = vec![(rel, FDs.to_vec())];
let mut bcnf: Vec<Attrs> = vec![]; | random_line_split |
lib.rs | #![allow(clippy::many_single_char_names, non_snake_case)]
pub mod chase;
pub mod mvd;
mod parser;
mod sorted_uvec;
use itertools::Itertools;
use mvd::MVD;
use rand::prelude::Distribution;
use sorted_uvec::SortedUVec;
use std::{borrow::Borrow, mem, ops::Not};
use std::{
collections::HashMap,
fmt::{self, Displa... |
pub fn with_names<'a>(&'a self, register: &'a NameRegister) -> DepWithNames<'a> {
DepWithNames {
arrow: "->",
source: &self.source,
target: &self.target,
register,
}
}
}
pub struct DepWithNames<'a> {
arrow: &'a str,
source: &'a Attrs,
... | {
self.target
.iter()
.map(move |&v| FD::new(self.source.clone(), attrs(&[v])))
} | identifier_body |
response.rs | // rust imports
use std::io::Read;
use std::ffi::OsStr;
use std::path::{PathBuf, Path};
use std::fs::{self, File};
use std::collections::HashMap;
// 3rd-party imports
use rusqlite::Connection;
use rusqlite::types::ToSql;
use hyper::http::h1::HttpReader;
use hyper::buffer::BufReader;
use hyper::net::NetworkStream;
u... | () -> Self {
ExpenseTracker(HashMap::new())
}
fn add(&mut self, date: NaiveDate, expenses: f64) {
let month = match date.month() {
1 => Month::January,
2 => Month::February,
3 => Month::March,
4 => Month::April,
5 => Month::May,
... | new | identifier_name |
response.rs | // rust imports
use std::io::Read;
use std::ffi::OsStr;
use std::path::{PathBuf, Path};
use std::fs::{self, File};
use std::collections::HashMap;
// 3rd-party imports
use rusqlite::Connection;
use rusqlite::types::ToSql;
use hyper::http::h1::HttpReader;
use hyper::buffer::BufReader;
use hyper::net::NetworkStream;
u... | }
}
fn process_multipart<R: Read>(headers: Headers, http_reader: R) -> Option<Multipart<R>> {
let boundary = headers.get::<ContentType>().and_then(|ct| {
use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value};
let ContentType(ref mime) = *ct;
let params = match *mime {
... | }
}
| random_line_split |
read_archive.rs | //! read-archive
use backup_cli::storage::{FileHandle, FileHandleRef};
use libra_types::access_path::AccessPath;
use libra_types::account_config::AccountResource;
use libra_types::account_state::AccountState;
use libra_types::write_set::{WriteOp, WriteSetMut};
use move_core_types::move_resource::MoveResource;
use ol_... |
/// Without modifying the data convert an AccountState struct, into a WriteSet Item which can be included in a genesis transaction. This should take all of the resources in the account.
fn get_unmodified_writeset(account_state: &AccountState) -> Result<WriteSetMut, Error> {
let mut ws = WriteSetMut::new(vec![]);
... | {
let mut write_set_mut = WriteSetMut::new(vec![]);
for blob in account_state_blobs {
let account_state = AccountState::try_from(blob)?;
// TODO: borrow
let clean = get_unmodified_writeset(&account_state)?;
let auth = authkey_rotate_change_item(&account_state, get_alice_authkey_f... | identifier_body |
read_archive.rs | //! read-archive
use backup_cli::storage::{FileHandle, FileHandleRef};
use libra_types::access_path::AccessPath;
use libra_types::account_config::AccountResource;
use libra_types::account_state::AccountState;
use libra_types::write_set::{WriteOp, WriteSetMut};
use move_core_types::move_resource::MoveResource;
use ol_... |
fn read_from_file(path: &str) -> Result<Vec<u8>> {
let mut data = Vec::<u8>::new();
let mut f = File::open(path).expect("Unable to open file");
f.read_to_end(&mut data).expect("Unable to read data");
Ok(data)
}
fn read_from_json(path: &PathBuf) -> Result<StateSnapshotBackup> {
let config = std::fs... | } | random_line_split |
read_archive.rs | //! read-archive
use backup_cli::storage::{FileHandle, FileHandleRef};
use libra_types::access_path::AccessPath;
use libra_types::account_config::AccountResource;
use libra_types::account_state::AccountState;
use libra_types::write_set::{WriteOp, WriteSetMut};
use move_core_types::move_resource::MoveResource;
use ol_... |
}
}
}
println!("processed account: {:?}", address);
address_processed = true;
break;
};
if!address_processed {
panic!("Address not found for {} in recovery list", &address... | {
panic!("MinerStateResource not found");
} | conditional_block |
read_archive.rs | //! read-archive
use backup_cli::storage::{FileHandle, FileHandleRef};
use libra_types::access_path::AccessPath;
use libra_types::account_config::AccountResource;
use libra_types::account_state::AccountState;
use libra_types::write_set::{WriteOp, WriteSetMut};
use move_core_types::move_resource::MoveResource;
use ol_... | (
archive_path: PathBuf,
) -> Result<WriteSetMut, Error> {
let backup = read_from_json(&archive_path)?;
let account_blobs = accounts_from_snapshot_backup(backup, &archive_path).await?;
accounts_into_writeset_swarm(&account_blobs)
}
/// take an archive file path and parse into a writeset
pub async fn ar... | archive_into_swarm_writeset | identifier_name |
main.rs | // This implementation is inspired by https://github.com/dlundquist/sniproxy, but I wrote it from
// scratch based on a careful reading of the TLS 1.3 specification.
use std::net::SocketAddr;
use std::path::PathBuf;
use std::time::Duration;
use tokio::io::{self, AsyncReadExt, AsyncWriteExt, Error, ErrorKind};
use toki... | // section 5.1: "The record layer fragments information blocks into TLSPlaintext
// records carrying data in chunks of 2^14 bytes or less."
if length > (1 << 14) {
return Err(TlsError::RecordOverflow);
}
self.offset += 5;
self.limi... | {
while self.offset >= self.limit {
self.fill_to(self.limit + 5).await?;
// section 5.1: "Handshake messages MUST NOT be interleaved with other record types.
// That is, if a handshake message is split over two or more records, there MUST NOT be
// any other reco... | identifier_body |
main.rs | // This implementation is inspired by https://github.com/dlundquist/sniproxy, but I wrote it from
// scratch based on a careful reading of the TLS 1.3 specification.
use std::net::SocketAddr;
use std::path::PathBuf;
use std::time::Duration;
use tokio::io::{self, AsyncReadExt, AsyncWriteExt, Error, ErrorKind};
use toki... |
_ => TlsError::InternalError,
})?;
// After this point, all I/O errors are internal errors.
// If this file exists, turn on the PROXY protocol.
// NOTE: This is a blocking syscall, but stat should be fast enough that it's not worth
// spawning off a thread.
if std::fs::metadat... | {
TlsError::UnrecognizedName
} | conditional_block |
main.rs | // This implementation is inspired by https://github.com/dlundquist/sniproxy, but I wrote it from
// scratch based on a careful reading of the TLS 1.3 specification.
use std::net::SocketAddr;
use std::path::PathBuf;
use std::time::Duration;
use tokio::io::{self, AsyncReadExt, AsyncWriteExt, Error, ErrorKind};
use toki... | Ok(v)
}
async fn read_length(&mut self, length: u8) -> TlsResult<usize> {
debug_assert!(length > 0 && length <= 4);
let mut result = 0;
for _ in 0..length {
result <<= 8;
result |= self.read().await? as usize;
}
Ok(result)
}
async... | }
self.fill_to(self.offset + 1).await?;
let v = self.buffer[self.offset];
self.offset += 1; | random_line_split |
main.rs | // This implementation is inspired by https://github.com/dlundquist/sniproxy, but I wrote it from
// scratch based on a careful reading of the TLS 1.3 specification.
use std::net::SocketAddr;
use std::path::PathBuf;
use std::time::Duration;
use tokio::io::{self, AsyncReadExt, AsyncWriteExt, Error, ErrorKind};
use toki... | (length: usize, limit: &mut usize) -> TlsResult<()> {
*limit = limit.checked_sub(length).ok_or(TlsError::DecodeError)?;
Ok(())
}
impl<R: AsyncReadExt> TlsHandshakeReader<R> {
fn new(source: R) -> Self {
TlsHandshakeReader {
source: source,
buffer: Vec::with_capacity(4096),
... | check_length | identifier_name |
app.rs | use crate::{
auth::Resource,
default_resource, diffable,
error::ServiceError,
generation,
models::{
fix_null_default,
sql::{slice_iter, SelectBuilder},
Lock, TypedAlias,
},
update_aliases, Client,
};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use core:... | let builder = SelectBuilder::new(select, Vec::new(), Vec::new())
.name(&name)
.labels(&labels.0)
.auth_read(&id)
.lock(lock)
.sort(sort)
.limit(limit)
.offset(offset);
let (select, params, types) = builder.build();
le... | {
let select = r#"
SELECT
NAME,
UID,
LABELS,
ANNOTATIONS,
CREATION_TIMESTAMP,
GENERATION,
RESOURCE_VERSION,
DELETION_TIMESTAMP,
FINALIZERS,
OWNER,
TRANSFER_OWNER,
MEMBERS,
DATA
FROM APPLICATIONS
"#
.to_string();
| identifier_body |
app.rs | use crate::{
auth::Resource,
default_resource, diffable,
error::ServiceError,
generation,
models::{
fix_null_default,
sql::{slice_iter, SelectBuilder},
Lock, TypedAlias,
},
update_aliases, Client,
};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use core:... | {
let select = r#"
SELECT
NAME,
UID,
LABELS,
ANNOTATIONS,
CREATION_TIMESTAMP,
GENERATION,
RESOURCE_VERSION,
DELETION_TIMESTAMP,
FINALIZERS,
OWNER,
TRANSFER_OWNER,
MEMBERS,
DATA
FROM APPLICATIONS
"#
.to_string();
let builder = SelectBuilder:... | offset: Option<usize>,
id: Option<&UserInformation>,
lock: Lock,
sort: &[&str],
) -> Result<Pin<Box<dyn Stream<Item = Result<Application, ServiceError>> + Send>>, ServiceError> | random_line_split |
app.rs | use crate::{
auth::Resource,
default_resource, diffable,
error::ServiceError,
generation,
models::{
fix_null_default,
sql::{slice_iter, SelectBuilder},
Lock, TypedAlias,
},
update_aliases, Client,
};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use core:... | (&self, id: &str) -> Result<(), ServiceError> {
let sql = "DELETE FROM APPLICATIONS WHERE NAME = $1";
let stmt = self.client.prepare_typed(sql, &[Type::VARCHAR]).await?;
let count = self.client.execute(&stmt, &[&id]).await?;
if count > 0 {
Ok(())
} else {
... | delete | identifier_name |
app.rs | use crate::{
auth::Resource,
default_resource, diffable,
error::ServiceError,
generation,
models::{
fix_null_default,
sql::{slice_iter, SelectBuilder},
Lock, TypedAlias,
},
update_aliases, Client,
};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use core:... |
let stmt = self
.client
.prepare_typed(
"INSERT INTO APPLICATION_ALIASES (APP, TYPE, ALIAS) VALUES ($1, $2, $3)",
&[Type::VARCHAR, Type::VARCHAR, Type::VARCHAR],
)
.await?;
for alias in aliases {
self.client
... | {
return Ok(());
} | conditional_block |
main.rs | #![no_std]
#![feature(
test,
start,
array_map,
const_panic, | isa_attribute,
core_intrinsics,
maybe_uninit_ref,
bindings_after_at,
stmt_expr_attributes,
default_alloc_error_handler,
const_fn_floating_point_arithmetic,
)]
extern crate alloc;
mod gfx;
mod heap;
mod mem;
use core::fmt::Write;
use alloc::{vec::Vec, vec};
use vek::*;
use num_traits::floa... | random_line_split | |
main.rs | #![no_std]
#![feature(
test,
start,
array_map,
const_panic,
isa_attribute,
core_intrinsics,
maybe_uninit_ref,
bindings_after_at,
stmt_expr_attributes,
default_alloc_error_handler,
const_fn_floating_point_arithmetic,
)]
extern crate alloc;
mod gfx;
mod heap;
mod mem;
use co... |
if flags.timer1() {
timer1_handler();
}
}
fn vblank_handler() { BIOS_IF.write(BIOS_IF.read().with_vblank(true)); }
fn hblank_handler() { BIOS_IF.write(BIOS_IF.read().with_hblank(true)); }
fn vcounter_handler() { BIOS_IF.write(BIOS_IF.read().with_vcounter(true)); }
fn timer0_handler() { BIOS_IF.write(B... | {
timer0_handler();
} | conditional_block |
main.rs | #![no_std]
#![feature(
test,
start,
array_map,
const_panic,
isa_attribute,
core_intrinsics,
maybe_uninit_ref,
bindings_after_at,
stmt_expr_attributes,
default_alloc_error_handler,
const_fn_floating_point_arithmetic,
)]
extern crate alloc;
mod gfx;
mod heap;
mod mem;
use co... | (m: Mat4<F32>, n: Mat4<F32>) -> Mat4<F32> {
(m.map(NumWrap) * n.map(NumWrap)).map(|e| e.0)
}
#[panic_handler]
fn panic(info: &core::panic::PanicInfo) ->! {
gba::error!("Panic: {:?}", info);
Mode3::clear_to(Color::from_rgb(0xFF, 0, 0));
loop {}
}
#[start]
fn main(_argc: isize, _argv: *const *const u8) ... | apply4 | identifier_name |
main.rs | #![no_std]
#![feature(
test,
start,
array_map,
const_panic,
isa_attribute,
core_intrinsics,
maybe_uninit_ref,
bindings_after_at,
stmt_expr_attributes,
default_alloc_error_handler,
const_fn_floating_point_arithmetic,
)]
extern crate alloc;
mod gfx;
mod heap;
mod mem;
use co... |
}
impl vek::ops::MulAdd<NumWrap, NumWrap> for NumWrap {
type Output = NumWrap;
fn mul_add(self, mul: NumWrap, add: NumWrap) -> NumWrap {
NumWrap(self.0 * mul.0 + add.0)
}
}
fn apply(m: Mat3<F32>, n: Mat3<F32>) -> Mat3<F32> {
(m.map(NumWrap) * n.map(NumWrap)).map(|e| e.0)
}
fn apply4(m: Mat4... | { NumWrap(self.0 * rhs.0) } | identifier_body |
main.rs | use cargo::core::dependency::Kind;
use cargo::core::manifest::ManifestMetadata;
use cargo::core::package::PackageSet;
use cargo::core::registry::PackageRegistry;
use cargo::core::resolver::Method;
use cargo::core::shell::Shell;
use cargo::core::{Package, PackageId, Resolve, Workspace};
use cargo::ops;
use cargo::util::... | graph: petgraph::Graph<Node<'a>, Kind>,
nodes: HashMap<PackageId, NodeIndex>,
}
fn build_graph<'a>(
resolve: &'a Resolve,
packages: &'a PackageSet<'_>,
root: PackageId,
target: Option<&str>,
cfgs: Option<&[Cfg]>,
) -> CargoResult<Graph<'a>> {
let mut graph = Graph {
graph: petgra... | > {
| identifier_name |
main.rs | use cargo::core::dependency::Kind;
use cargo::core::manifest::ManifestMetadata;
use cargo::core::package::PackageSet;
use cargo::core::registry::PackageRegistry;
use cargo::core::resolver::Method;
use cargo::core::shell::Shell;
use cargo::core::{Package, PackageId, Resolve, Workspace};
use cargo::ops;
use cargo::util::... | l_main(args: Args, config: &mut Config) -> CliResult {
config.configure(
args.verbose,
args.quiet,
&args.color,
args.frozen,
args.locked,
&args.target_dir,
&args.unstable_flags,
)?;
let workspace = workspace(config, args.manifest_path)?;
let packa... | v_logger::init();
let mut config = match Config::default() {
Ok(cfg) => cfg,
Err(e) => {
let mut shell = Shell::new();
cargo::exit_with_error(e.into(), &mut shell)
}
};
let Opts::Tree(args) = Opts::from_args();
if let Err(e) = real_main(args, &mut confi... | identifier_body |
main.rs | use cargo::core::dependency::Kind;
use cargo::core::manifest::ManifestMetadata;
use cargo::core::package::PackageSet;
use cargo::core::registry::PackageRegistry;
use cargo::core::resolver::Method;
use cargo::core::shell::Shell;
use cargo::core::{Package, PackageId, Resolve, Workspace};
use cargo::ops;
use cargo::util::... | for dep in it {
let dep_idx = match graph.nodes.entry(dep_id) {
Entry::Occupied(e) => *e.get(),
Entry::Vacant(e) => {
pending.push(dep_id);
let node = Node {
id: dep_id,
... | random_line_split | |
main.rs | use cargo::core::dependency::Kind;
use cargo::core::manifest::ManifestMetadata;
use cargo::core::package::PackageSet;
use cargo::core::registry::PackageRegistry;
use cargo::core::resolver::Method;
use cargo::core::shell::Shell;
use cargo::core::{Package, PackageId, Resolve, Workspace};
use cargo::ops;
use cargo::util::... | Resolve uses Hash data types internally but we want consistent output ordering
deps.sort_by_key(|n| n.id);
let name = match kind {
Kind::Normal => None,
Kind::Build => Some("[build-dependencies]"),
Kind::Development => Some("[dev-dependencies]"),
};
if let Prefix::Indent = pref... | return;
}
// | conditional_block |
arena.rs | // Copyright 2019 Fullstop000 <fullstop1005@gmail.com>.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by appli... |
#[test]
fn test_has_room_for() {
let arena = AggressiveArena::new(1);
assert_eq!(arena.has_room_for(100), false);
}
} | arena.alloc_node(MAX_HEIGHT); // 152
arena.alloc_node(1); // 64
arena.alloc_bytes(&Slice::from(vec![1u8, 2u8, 3u8, 4u8].as_slice())); // 4
assert_eq!(152 + 64 + 4, arena.memory_used())
} | random_line_split |
arena.rs | // Copyright 2019 Fullstop000 <fullstop1005@gmail.com>.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by appli... | () {
let arena = Arc::new(AggressiveArena::new(500));
let results = Arc::new(Mutex::new(vec![]));
let mut tests = vec![vec![1u8, 2, 3, 4, 5], vec![6u8, 7, 8, 9], vec![10u8, 11]];
for t in tests
.drain(..)
.map(|test| {
let cloned_arena = arena.clone(... | test_alloc_bytes_concurrency | identifier_name |
arena.rs | // Copyright 2019 Fullstop000 <fullstop1005@gmail.com>.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by appli... | (*node).height = height;
(*node).next_nodes = next_nodes;
node
}
}
fn alloc_bytes(&self, data: &Slice) -> u32 {
let start = self.offset.fetch_add(data.size(), Ordering::SeqCst);
unsafe {
let ptr = self.mem.as_ptr().add(start) as *mut u8;
... | {
let ptr_size = mem::size_of::<*mut u8>();
// truncate node size to reduce waste
let used_node_size = MAX_NODE_SIZE - (MAX_HEIGHT - height) * ptr_size;
let n = self.offset.fetch_add(used_node_size, Ordering::SeqCst);
unsafe {
let node_ptr = self.mem.as_ptr().add(n) a... | identifier_body |
keys.rs | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
// Version 2, December 2004
//
// Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co
//
// Everyone is permitted to copy and distribute verbatim or modified
// copies of this license document, and changing it is allowed as long... | }
(&input[1..], None)
}
}
| return (&input[length..], Some(Key {
modifier: mods,
value: Char(string.chars().next().unwrap())
}));
}
| conditional_block |
keys.rs | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
// Version 2, December 2004
//
// Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co
//
// Everyone is permitted to copy and distribute verbatim or modified
// copies of this license document, and changing it is allowed as long... |
#[derive(Eq, PartialEq, Copy, Clone, Debug)]
pub enum Value {
Escape,
Enter,
Down,
Up,
Left,
Right,
PageUp,
PageDown,
BackSpace,
BackTab,
Tab,
Delete,
Insert,
Home,
End,
Begin,
F(u8),
Char(char),
}
pub use self::Value::*;
impl Keys {
pub fn new(info: &info::Database) -> Self {
let mut map =... | Modifier::empty()
}
} | identifier_body |
keys.rs | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
// Version 2, December 2004
//
// Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co
//
// Everyone is permitted to copy and distribute verbatim or modified
// copies of this license document, and changing it is allowed as long... |
pub modifier: Modifier,
pub value: Value,
}
bitflags! {
pub struct Modifier: u8 {
const NONE = 0;
const ALT = 1 << 0;
const CTRL = 1 << 1;
const LOGO = 1 << 2;
const SHIFT = 1 << 3;
}
}
impl Default for Modifier {
fn default() -> Self {
Modifier::empty()
}
}
#[derive(Eq, PartialEq, Copy, C... | y { | identifier_name |
keys.rs | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
// Version 2, December 2004
//
// Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co
//
// Everyone is permitted to copy and distribute verbatim or modified
// copies of this license document, and changing it is allowed as long... | }));
}
let mut mods = Modifier::empty();
if input[0] == 0x1B {
mods.insert(Modifier::ALT);
input = &input[1..];
}
// Check if it's a control character.
if input[0] & 0b011_00000 == 0 {
return (&input[1..], Some(Key {
modifier: mods | Modifier::CTRL,
value: Char((input[0] | 0b010_00... | // Check if it's a single escape press.
if input == &[0x1B] {
return (&input[1..], Some(Key {
modifier: Modifier::empty(),
value: Escape, | random_line_split |
lib.rs | //! This crate provides an implementation of Chan-Vese level-sets
//! described in [Active contours without edges](http://ieeexplore.ieee.org/document/902291/)
//! by T. Chan and L. Vese.
//! It is a port of the Python implementation by Kevin Keraudren on
//! [Github](https://github.com/kevin-keraudren/chanvese)
//! an... |
else {
0
}
}
| {
c + 1
} | conditional_block |
lib.rs | //! This crate provides an implementation of Chan-Vese level-sets
//! described in [Active contours without edges](http://ieeexplore.ieee.org/document/902291/)
//! by T. Chan and L. Vese.
//! It is a port of the Python implementation by Kevin Keraudren on
//! [Github](https://github.com/kevin-keraudren/chanvese)
//! an... | };
phi
}
// Compute curvature along SDF
fn get_curvature(phi: &FloatGrid, idx: &Vec<(usize,usize)>) -> Vec<f64> {
// get central derivatives of SDF at x,y
let (phi_x, phi_y, phi_xx, phi_yy, phi_xy) = {
let (mut res_x, mut res_y, mut res_xx, mut res_yy, mut res_xy)
: (Vec<f64>, Vec... | {
let inv_init_a = {
let mut result = init_a.clone();
for (_, _, value) in result.iter_mut() {
*value = !*value;
}
result
};
let phi = {
let dist_a = bwdist(&init_a);
let dist_inv_a = bwdist(&inv_init_a);
let mut result = FloatGrid::new(in... | identifier_body |
lib.rs | //! This crate provides an implementation of Chan-Vese level-sets
//! described in [Active contours without edges](http://ieeexplore.ieee.org/document/902291/)
//! by T. Chan and L. Vese.
//! It is a port of the Python implementation by Kevin Keraudren on
//! [Github](https://github.com/kevin-keraudren/chanvese)
//! an... |
for y in 0..grid.height() {
for x in 0..grid.width() {
let a_p_dval = *a.get(x, y).unwrap();
let a_n_dval = *a.get(x, y).unwrap();
let b_p_dval = *b.get(x, y).unwrap();
let b_n_dval = *b.get(x, y).unwrap();
let c_p_dval... | let mut d_n_res = FloatGrid::new(grid.width(), grid.height()); | random_line_split |
lib.rs | //! This crate provides an implementation of Chan-Vese level-sets
//! described in [Active contours without edges](http://ieeexplore.ieee.org/document/902291/)
//! by T. Chan and L. Vese.
//! It is a port of the Python implementation by Kevin Keraudren on
//! [Github](https://github.com/kevin-keraudren/chanvese)
//! an... | (d: &FloatGrid) -> FloatGrid {
let mut res = FloatGrid::new(d.width(), d.height());
for (x, y, value) in res.iter_mut() {
let v = d.get(x, y).unwrap();
*value = v/(v*v + 1.).sqrt();
}
res
}
// Convergence test
fn convergence(p_mask: &BoolGrid,
n_mask: &BoolGrid,
... | sussman_sign | identifier_name |
controller.rs | //! Contains ZX Spectrum System contrller (like ula or so) of emulator
use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};
// use almost everything :D
use utils::{split_word, Clocks};
use utils::screen::*;
use utils::events::*;
use utils::InstantFlag;
use z80::Z80Bus;
use zx::{ZXMemory, RomType, RamT... | fn frame_pos(&self) -> f64 {
let val = self.frame_clocks.count() as f64 / self.machine.specs().clocks_frame as f64;
if val > 1.0 {
1.0
} else {
val
}
}
/// loads rom from file
/// for 128-K machines path must contain ".0" in the tail
/// and s... | out
}
/// returns current frame emulation pos in percents | random_line_split |
controller.rs | //! Contains ZX Spectrum System contrller (like ula or so) of emulator
use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};
// use almost everything :D
use utils::{split_word, Clocks};
use utils::screen::*;
use utils::events::*;
use utils::InstantFlag;
use z80::Z80Bus;
use zx::{ZXMemory, RomType, RamT... |
/// check events count
pub fn no_events(&self) -> bool {
self.events.is_empty()
}
/// Returns last event
pub fn pop_event(&mut self) -> Option<Event> {
self.events.receive_event()
}
/// Returns true if all frame clocks has been passed
pub fn frames_count(&self) -> usi... | {
self.events.clear();
} | identifier_body |
controller.rs | //! Contains ZX Spectrum System contrller (like ula or so) of emulator
use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};
// use almost everything :D
use utils::{split_word, Clocks};
use utils::screen::*;
use utils::events::*;
use utils::InstantFlag;
use z80::Z80Bus;
use zx::{ZXMemory, RomType, RamT... |
return 0xFF;
}
/// make contention
fn do_contention(&mut self) {
let contention = self.machine.contention_clocks(self.frame_clocks);
self.wait_internal(contention);
}
///make contention + wait some clocks
fn do_contention_and_wait(&mut self, wait_time: Clocks) {
... | {
if clocks % 2 == 0 {
return self.memory.read(bitmap_line_addr(row) + col as u16);
} else {
let byte = (row / 8) * 32 + col;
return self.memory.read(0x5800 + byte as u16);
};
} | conditional_block |
controller.rs | //! Contains ZX Spectrum System contrller (like ula or so) of emulator
use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};
// use almost everything :D
use utils::{split_word, Clocks};
use utils::screen::*;
use utils::events::*;
use utils::InstantFlag;
use z80::Z80Bus;
use zx::{ZXMemory, RomType, RamT... | (&mut self, port: u16) {
if self.addr_is_contended(port) {
self.do_contention();
};
self.wait_internal(Clocks(1));
}
/// Returns late IO contention clocks
fn io_contention_last(&mut self, port: u16) {
if self.machine.port_is_contended(port) {
self.do_... | io_contention_first | identifier_name |
storage.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
smoke_test_environment::new_local_swarm,
test_utils::{
assert_balance, create_and_fund_account, diem_swarm_utils::insert_waypoint, transfer_coins,
},
workspace_builder,
workspace_builder::workspa... |
transfer_coins(client, transaction_factory, account0, account1, 1);
}
Ok(())
}
| {
let current_version = client.get_metadata()?.into_inner().diem_version.unwrap();
let txn = root_account.sign_with_transaction_builder(
transaction_factory.update_diem_version(0, current_version + 1),
);
client.submit(&txn)?;
client.wait_for_s... | conditional_block |
storage.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
smoke_test_environment::new_local_swarm,
test_utils::{
assert_balance, create_and_fund_account, diem_swarm_utils::insert_waypoint, transfer_coins,
},
workspace_builder,
workspace_builder::workspa... | &transaction_batch_size.to_string(),
"--state-snapshot-interval",
&state_snapshot_interval.to_string(),
"--metadata-cache-dir",
metadata_cache_path1.path().to_str().unwrap(),
"local-fs",
"--dir",
backup_path.path().to_str().... | {
let now = Instant::now();
let bin_path = workspace_builder::get_bin("db-backup");
let metadata_cache_path1 = TempPath::new();
let metadata_cache_path2 = TempPath::new();
let backup_path = TempPath::new();
metadata_cache_path1.create_as_dir().unwrap();
metadata_cache_path2.create_as_dir().... | identifier_body |
storage.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
smoke_test_environment::new_local_swarm,
test_utils::{
assert_balance, create_and_fund_account, diem_swarm_utils::insert_waypoint, transfer_coins,
},
workspace_builder,
workspace_builder::workspa... | (
client: &BlockingClient,
transaction_factory: &TransactionFactory,
root_account: &mut LocalAccount,
account0: &mut LocalAccount,
account1: &LocalAccount,
transfers: usize,
) -> Result<()> {
for _ in 0..transfers {
if random::<u16>() % 10 == 0 {
let current_version = cli... | transfer_and_reconfig | identifier_name |
storage.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
smoke_test_environment::new_local_swarm,
test_utils::{
assert_balance, create_and_fund_account, diem_swarm_utils::insert_waypoint, transfer_coins,
},
workspace_builder,
workspace_builder::workspa... |
fn wait_for_backups(
target_epoch: u64,
target_version: u64,
now: Instant,
bin_path: &Path,
metadata_cache_path: &Path,
backup_path: &Path,
trusted_waypoints: &[Waypoint],
) -> Result<()> {
for _ in 0..60 {
// the verify should always succeed.
db_backup_verify(backup_pat... | if !output.status.success() {
panic!("db-backup-verify failed, output: {:?}", output);
}
println!("Backup verified in {} seconds.", now.elapsed().as_secs());
} | random_line_split |
lib.rs | use crossbeam_channel as channel;
use indexmap::IndexMap as Map;
use isahc::{
config::{Configurable, RedirectPolicy},
HttpClient,
};
use once_cell::sync::Lazy;
use onig::Regex;
use rayon::prelude::*;
use select::{
document::Document,
predicate::{Class, Name},
};
use std::{
borrow::Cow,
env,
... | }
}
} | random_line_split | |
lib.rs | use crossbeam_channel as channel;
use indexmap::IndexMap as Map;
use isahc::{
config::{Configurable, RedirectPolicy},
HttpClient,
};
use once_cell::sync::Lazy;
use onig::Regex;
use rayon::prelude::*;
use select::{
document::Document,
predicate::{Class, Name},
};
use std::{
borrow::Cow,
env,
... | (output_dir: &Path) -> Cow<'_, Path> {
use std::fs;
use std::os::unix::fs::MetadataExt;
let os_tmp = env::temp_dir();
match (
fs::metadata(output_dir).map(|v| v.dev()),
fs::metadata(&os_tmp).map(|v| v.dev()),
) {
(Ok(num1), Ok(num2)) if num1 =... | get_tmp_dir | identifier_name |
lib.rs | use crossbeam_channel as channel;
use indexmap::IndexMap as Map;
use isahc::{
config::{Configurable, RedirectPolicy},
HttpClient,
};
use once_cell::sync::Lazy;
use onig::Regex;
use rayon::prelude::*;
use select::{
document::Document,
predicate::{Class, Name},
};
use std::{
borrow::Cow,
env,
... |
}
}
Ok(node.text())
})
});
match result {
... | {
return Err("Not a valid NPC ID".into());
} | conditional_block |
mmio.rs | #![cfg_attr(rustfmt, rustfmt::skip)]
//! Contains all the MMIO address definitions for the GBA's components.
//!
//! This module contains *only* the MMIO addresses. The data type definitions
//! for each MMIO control value are stored in the appropriate other modules such
//! as [`video`](crate::video), [`interrupts`](... |
// Timers
def_mmio!(0x0400_0100 = TIMER0_COUNT/["TM0CNT_L"]: VolAddress<u16, Safe, ()>; "Timer 0 Count read");
def_mmio!(0x0400_0100 = TIMER0_RELOAD/["TM0CNT_L"]: VolAddress<u16, (), Safe>; "Timer 0 Reload write");
def_mmio!(0x0400_0102 = TIMER0_CONTROL/["TM0CNT_H"]: VolAddress<TimerControl, Safe, Safe>; "Timer 0 con... | def_mmio!(0x0400_00DE = DMA3_CONTROL/["DMA3_CNT_H"]: VolAddress<DmaControl, Safe, Unsafe>; "DMA3 Control Bits"); | random_line_split |
mmio.rs | #![cfg_attr(rustfmt, rustfmt::skip)]
//! Contains all the MMIO address definitions for the GBA's components.
//!
//! This module contains *only* the MMIO addresses. The data type definitions
//! for each MMIO control value are stored in the appropriate other modules such
//! as [`video`](crate::video), [`interrupts`](... |
#[inline]
#[must_use]
#[cfg_attr(feature="track_caller", track_caller)]
pub const fn obj_palbank(bank: usize) -> VolBlock<Color, Safe, Safe, 16> {
let u = OBJ_PALETTE.index(bank * 16).as_usize();
unsafe { VolBlock::new(u) }
}
// Video RAM (VRAM)
/// The VRAM byte offset per screenblock index.
///
/// This is th... | {
let u = BG_PALETTE.index(bank * 16).as_usize();
unsafe { VolBlock::new(u) }
} | identifier_body |
mmio.rs | #![cfg_attr(rustfmt, rustfmt::skip)]
//! Contains all the MMIO address definitions for the GBA's components.
//!
//! This module contains *only* the MMIO addresses. The data type definitions
//! for each MMIO control value are stored in the appropriate other modules such
//! as [`video`](crate::video), [`interrupts`](... | (bank: usize) -> VolBlock<Color, Safe, Safe, 16> {
let u = OBJ_PALETTE.index(bank * 16).as_usize();
unsafe { VolBlock::new(u) }
}
// Video RAM (VRAM)
/// The VRAM byte offset per screenblock index.
///
/// This is the same for all background types and sizes.
pub const SCREENBLOCK_INDEX_OFFSET: usize = 2 * 1_024;... | obj_palbank | identifier_name |
lib.rs | //! This crate adds support for subscriptions as defined in [here].
//!
//! [here]: https://github.com/ethereum/go-ethereum/wiki/RPC-PUB-SUB
extern crate futures;
extern crate jsonrpc_client_core;
extern crate jsonrpc_client_utils;
#[macro_use]
extern crate serde;
extern crate serde_json;
extern crate tokio;
#[macro_... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
SubscriptionId::Num(n) => write!(f, "{}", n),
SubscriptionId::String(s) => write!(f, "{}", s),
}
}
}
#[derive(Debug)]
enum SubscriberMsg {
NewMessage(SubscriptionMessage),
NewSubscriber(SubscriptionId, mps... | fmt | identifier_name |
lib.rs | //! This crate adds support for subscriptions as defined in [here].
//!
//! [here]: https://github.com/ethereum/go-ethereum/wiki/RPC-PUB-SUB
extern crate futures;
extern crate jsonrpc_client_core;
extern crate jsonrpc_client_utils;
#[macro_use]
extern crate serde;
extern crate serde_json;
extern crate tokio;
#[macro_... |
_ => true,
},
}
}
}
impl Future for NotificationHandler {
type Item = ();
type Error = ();
fn poll(&mut self) -> Poll<(), ()> {
while self.ready_for_next_connection() {
match self.messages.poll()? {
Async::NotReady => {
... | {
self.current_future = Some(fut);
false
} | conditional_block |
lib.rs | //! This crate adds support for subscriptions as defined in [here]. | extern crate jsonrpc_client_utils;
#[macro_use]
extern crate serde;
extern crate serde_json;
extern crate tokio;
#[macro_use]
extern crate log;
#[macro_use]
extern crate error_chain;
use futures::{future, future::Either, sync::mpsc, Async, Future, Poll, Sink, Stream};
use jsonrpc_client_core::server::{
types::... | //!
//! [here]: https://github.com/ethereum/go-ethereum/wiki/RPC-PUB-SUB
extern crate futures;
extern crate jsonrpc_client_core; | random_line_split |
boxed.rs | self.ptr.as_ptr(),
self.len,
)
}
}
/// Instantiates a new [`Box`] that can hold `len` elements of type
/// `T`. This [`Box`] will be unlocked and *must* be locked before
/// it is dropped.
///
/// TODO: make `len` a `NonZero` when it's stabilized and remov... | #[should_panic(expected = "secrets: releases exceeded retains")]
fn it_doesnt_allow_negative_users() {
Box::<u64>::zero(10).lock();
} | random_line_split | |
boxed.rs | const_for_fn)] // not usable on min supported Rust
pub(crate) fn is_empty(&self) -> bool {
self.len == 0
}
/// Returns the size in bytes of the data contained in the [`Box`].
/// This does not include incidental metadata used in the
/// implementation of [`Box`] itself, only the size of the... |
#[test]
fn it_initializes_with_zero_refs() {
let boxed = Box::<u8>::zero(10);
assert_eq!(0, boxed.refs.get());
}
#[test]
fn it_tracks_ref_counts_accurately() {
let mut boxed = Box::<u8>::random(10);
let _ = boxed.unlock();
let _ = boxed.unlock();
... | {
let boxed_1 = Box::<u8>::from(&mut [0, 0, 0, 0][..]);
let boxed_2 = Box::<u8>::from(&mut [0, 0, 0, 0, 0][..]);
assert_ne!(boxed_1, boxed_2);
assert_ne!(boxed_2, boxed_1);
} | identifier_body |
boxed.rs | const_for_fn)] // not usable on min supported Rust
pub(crate) fn is_empty(&self) -> bool {
self.len == 0
}
/// Returns the size in bytes of the data contained in the [`Box`].
/// This does not include incidental metadata used in the
/// implementation of [`Box`] itself, only the size of the... | (&self) {
// When releasing, we should always have at least one retain
// outstanding. This is enforced by all users through
// refcounting on allocation and drop.
proven!(self.refs.get()!= 0,
"secrets: releases exceeded retains");
// When releasing, our protection l... | release | identifier_name |
boxed.rs | const_for_fn)] // not usable on min supported Rust
pub(crate) fn is_empty(&self) -> bool {
self.len == 0
}
/// Returns the size in bytes of the data contained in the [`Box`].
/// This does not include incidental metadata used in the
/// implementation of [`Box`] itself, only the size of the... |
}
/// Returns true if the protection level is [`NoAccess`]. Ignores
/// ref count.
fn is_locked(&self) -> bool {
self.prot.get() == Prot::NoAccess
}
}
impl<T: Bytes + Randomizable> Box<T> {
/// Instantiates a new [`Box`] with crypotgraphically-randomized
/// contents.
pub(crat... | {
mprotect(self.ptr.as_ptr(), Prot::NoAccess);
self.prot.set(Prot::NoAccess);
} | conditional_block |
mod.rs | /*
Copyright 2021 Integritee AG and Supercomputing Systems AG
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... | (
account: sr25519::Pair,
shard: ShardIdentifier,
direct_client: &DirectClient,
) -> Index {
let getter = Getter::trusted(
TrustedGetter::nonce(account.public().into()).sign(&KeyPair::Sr25519(account.clone())),
);
let getter_start_timer = Instant::now();
let getter_result = get_state(direct_client, shard, &ge... | get_nonce | identifier_name |
mod.rs | /*
Copyright 2021 Integritee AG and Supercomputing Systems AG
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... |
// Create new account.
let account_keys: sr25519::AppPair = store.generate().unwrap();
let new_account =
get_pair_from_str(trusted_args, account_keys.public().to_string().as_str());
println!(" Transfer amount: {}", EXISTENTIAL_DEPOSIT);
println!(" From: {:?}", client.account.public(... | {
random_wait(random_wait_before_transaction_ms);
} | conditional_block |
mod.rs | /*
Copyright 2021 Integritee AG and Supercomputing Systems AG
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... |
output
})
.collect();
println!(
"Finished benchmark with {} clients and {} transactions in {} ms",
self.number_clients,
self.number_iterations,
overall_start.elapsed().as_millis()
);
print_benchmark_statistic(outputs, self.wait_for_confirmation)
}
}
fn get_balance(
account: sr25519::Pa... | break;
}
}
client.client_api.close().unwrap(); | random_line_split |
lib.rs | //! dfconfig is a lib for parsing and manipulating Dwarf Fortress' `init.txt` and `d_init.txt` config files (and possibly many others using the same format).
//! This lib's functionality has been specifically tailored to behave similar as DF internal parser, which implies:
//!
//! * [`Config::get`] returns the last occ... | (&self) -> &str {
&self.value
}
pub fn get_key(&self) -> &str {
&self.key
}
pub fn set_value(&mut self, value: String) {
self.value = value;
}
}
/// The main struct of this crate. Represents DF config file, while also providing functions to parse and manipulate the data.
/... | get_value | identifier_name |
lib.rs | //! dfconfig is a lib for parsing and manipulating Dwarf Fortress' `init.txt` and `d_init.txt` config files (and possibly many others using the same format).
//! This lib's functionality has been specifically tailored to behave similar as DF internal parser, which implies:
//!
//! * [`Config::get`] returns the last occ... | if let Line::Entry(entry) = e {
if entry.get_key() == key {
entry.set_value(value.clone());
n += 1;
}
}
}
if n == 0 {
self.lines
.push(Line::Entry(Entry::new(key.to_string(), value... | }
let mut n = 0;
for e in self.lines.iter_mut() { | random_line_split |
lib.rs | //! dfconfig is a lib for parsing and manipulating Dwarf Fortress' `init.txt` and `d_init.txt` config files (and possibly many others using the same format).
//! This lib's functionality has been specifically tailored to behave similar as DF internal parser, which implies:
//!
//! * [`Config::get`] returns the last occ... |
}
impl Default for Config {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};
use std::fs::read_to_string;
use std::iter;
use super::*;
fn random_alphanumeric() -> String {
let mut rng ... | {
let mut output = HashMap::new();
conf.keys_values_iter().for_each(|(key, value)| {
output.insert(key.to_owned(), value.to_owned());
});
output
} | identifier_body |
ctrl_map.rs | //! Maps MIDI controllers to synth parameters.
use super::{ParamId, MenuItem};
use super::SoundData;
use super::SynthParam;
use super::ValueRange;
use log::{info, trace};
use serde::{Serialize, Deserialize};
use std::collections::HashMap;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
#[derive(... | (&mut self, ctrl_no: u64, ctrl_type: MappingType) {
let val_range = MenuItem::get_val_range(self.param_id.function, self.param_id.parameter);
self.map.add_mapping(1,
ctrl_no,
ctrl_type,
self.param_id,
... | add_controller | identifier_name |
ctrl_map.rs | //! Maps MIDI controllers to synth parameters.
use super::{ParamId, MenuItem};
use super::SoundData;
use super::SynthParam;
use super::ValueRange;
use log::{info, trace};
use serde::{Serialize, Deserialize};
use std::collections::HashMap;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
#[derive(... |
MappingType::None => panic!(),
};
Ok(result)
}
// Load controller mappings from file
pub fn load(&mut self, filename: &str) -> std::io::Result<()> {
info!("Reading controller mapping from {}", filename);
let file = File::open(filename)?;
let mut reader =... | {
// For relative: Increase/ decrease value
let sound_value = sound.get_value(&mapping.id);
let delta = if value >= 64 { -1 } else { 1 };
result.value = mapping.val_range.add_value(sound_value, delta);
} | conditional_block |
ctrl_map.rs | //! Maps MIDI controllers to synth parameters.
use super::{ParamId, MenuItem};
use super::SoundData;
use super::SynthParam;
use super::ValueRange;
use log::{info, trace};
use serde::{Serialize, Deserialize};
use std::collections::HashMap;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
#[derive(... | controller: u64,
value: u64,
sound: &SoundData) -> Result<SynthParam, ()> {
// Get mapping
if!self.map[set].contains_key(&controller) {
return Err(());
}
let mapping = &self.map[set][&controller];
let mut res... | set: usize, | random_line_split |
ctrl_map.rs | //! Maps MIDI controllers to synth parameters.
use super::{ParamId, MenuItem};
use super::SoundData;
use super::SynthParam;
use super::ValueRange;
use log::{info, trace};
use serde::{Serialize, Deserialize};
use std::collections::HashMap;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
#[derive(... |
#[test]
fn value_can_be_changed_absolute() {
let mut context = TestContext::new();
assert_eq!(context.has_value(50.0), true);
context.add_controller(1, MappingType::Absolute);
assert_eq!(context.handle_controller(1, 0), true);
assert_eq!(context.has_value(0.0), true);
}
#[test]
fn relative_contro... | {
let mut context = TestContext::new();
context.add_controller(1, MappingType::Absolute);
assert_eq!(context.handle_controller(1, 50), true);
} | identifier_body |
random.rs |
///
/// TODO: We should disallow re-seeding this RNG.
pub fn global_rng() -> GlobalRng {
GLOBAL_RNG_STATE.clone()
}
/// Call me if you want a cheap but insecure RNG seeded by the current system
/// time.
pub fn clocked_rng() -> MersenneTwisterRng {
let mut rng = MersenneTwisterRng::mt19937();
let seed = s... | }
pub fn seed_u32(&mut self, seed: u32) {
self.x.resize(self.n, 0);
self.index = self.n;
self.x[0] = seed;
for i in 1..self.n {
self.x[i] = (self.x[i - 1] ^ (self.x[i - 1] >> (self.w - 2)))
.wrapping_mul(self.f)
.wrapping_add(i as u32)... | {
Self {
w: 32,
n: 624,
m: 397,
r: 31,
a: 0x9908B0DF,
u: 11,
d: 0xffffffff,
s: 7,
b: 0x9D2C5680,
t: 15,
c: 0xEFC60000,
l: 18,
f: 1812433253,
x... | identifier_body |
random.rs | }
let mut buf = vec![];
buf.resize(upper.byte_width(), 0);
let mut num_bytes = ceil_div(upper.value_bits(), 8);
let msb_mask: u8 = {
let r = upper.value_bits() % 8;
if r == 0 {
0xff
} else {
!((1 << (8 - r)) - 1)
}
};
// TODO: Refactor ... | assert!(bucket > 71254 && bucket < 81780, "Bucket is {}", bucket); | random_line_split | |
random.rs |
///
/// TODO: We should disallow re-seeding this RNG.
pub fn global_rng() -> GlobalRng {
GLOBAL_RNG_STATE.clone()
}
/// Call me if you want a cheap but insecure RNG seeded by the current system
/// time.
pub fn clocked_rng() -> MersenneTwisterRng {
let mut rng = MersenneTwisterRng::mt19937();
let seed = s... | () -> Self {
Self {
state: Mutex::new(ChaCha20RNGState {
key: [0u8; CHACHA20_KEY_SIZE],
nonce: 0,
plaintext: [0u8; CHACHA20_BLOCK_SIZE],
}),
}
}
}
#[async_trait]
impl SharedRng for ChaCha20RNG {
fn seed_size(&self) -> usize... | new | identifier_name |
random.rs |
///
/// TODO: We should disallow re-seeding this RNG.
pub fn global_rng() -> GlobalRng {
GLOBAL_RNG_STATE.clone()
}
/// Call me if you want a cheap but insecure RNG seeded by the current system
/// time.
pub fn clocked_rng() -> MersenneTwisterRng {
let mut rng = MersenneTwisterRng::mt19937();
let seed = s... |
let mut buf = vec![];
buf.resize(upper.byte_width(), 0);
let mut num_bytes = ceil_div(upper.value_bits(), 8);
let msb_mask: u8 = {
let r = upper.value_bits() % 8;
if r == 0 {
0xff
} else {
!((1 << (8 - r)) - 1)
}
};
// TODO: Refactor ou... | {
return Err(err_msg("Invalid upper/lower range"));
} | conditional_block |
main.rs | use futures_util::future::Either;
use futures_util::stream::StreamExt;
use std::collections::{BTreeMap, HashMap};
use std::io::{self};
use structopt::StructOpt;
use termion::raw::IntoRawMode;
use tokio::prelude::*;
use tui::backend::Backend;
use tui::backend::TermionBackend;
use tui::layout::{Constraint, Direction, Lay... | {
window: BTreeMap<usize, String>,
}
fn main() -> Result<(), io::Error> {
let opt = Opt::from_args();
if termion::is_tty(&io::stdin().lock()) {
eprintln!("Don't type input to this program, that's silly.");
return Ok(());
}
let stdout = io::stdout().into_raw_mode()?;
let backe... | Thread | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.