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 |
|---|---|---|---|---|
path.rs | //! File path utilities.
//!
//! Some of the functions are similar to [`std::path::Path`] ones, but here they
//! work directly upon [`&str`](str) instead of [`&OsStr`](std::ffi::OsStr).
use crate::co;
use crate::decl::*;
use crate::guard::*;
use crate::prelude::*;
/// Returns an iterator over the files and... |
/// Extracts the full path, but the last part.
///
/// # Examples
///
/// ```no_run
/// use winsafe::{self as w, prelude::*};
///
/// let p = w::path::get_path("C:\\Temp\\xx\\a.txt"); // C:\Temp\xx
/// let q = w::path::get_path("C:\\Temp\\xx\\"); // C:\Temp\xx
/// let r = w::path::get_path("C:\\Temp\\... | {
match full_path.rfind('\\') {
None => Some(full_path), // if no backslash, the whole string is the file name
Some(idx) => if idx == full_path.chars().count() - 1 {
None // last char is '\\', no file name
} else {
Some(&full_path[idx + 1..])
},
}
} | identifier_body |
path.rs | //! File path utilities.
//!
//! Some of the functions are similar to [`std::path::Path`] ones, but here they
//! work directly upon [`&str`](str) instead of [`&OsStr`](std::ffi::OsStr).
use crate::co;
use crate::decl::*;
use crate::guard::*;
use crate::prelude::*;
/// Returns an iterator over the files and... |
match &mut self.subdir_runner {
None => {
let cur_file = self.runner.next();
match cur_file {
None => None,
Some(cur_file) => {
match cur_file {
Err(e) => {
self.no_more = true; // prevent further iterations
Some(Err(e))
},
Ok(cur_file) =>... | {
return None;
} | conditional_block |
path.rs | //! File path utilities.
//!
//! Some of the functions are similar to [`std::path::Path`] ones, but here they
//! work directly upon [`&str`](str) instead of [`&OsStr`](std::ffi::OsStr).
use crate::co;
use crate::decl::*;
use crate::guard::*;
use crate::prelude::*;
/// Returns an iterator over the files and... | (full_path: &str, new_extension: &str) -> String {
if let Some(last) = full_path.chars().last() {
if last == '\\' { // full_path is a directory, do nothing
return rtrim_backslash(full_path).to_owned();
}
}
let new_has_dot = new_extension.chars().next() == Some('.');
match full_path.rfind('.') {
N... | replace_extension | identifier_name |
lib.rs | //! [](https://github.com/time-rs/time)
//!
//! [ => return Err(error),
}
};
}
/// Try to unwrap an expression, returning if not possible.
///
/// This is similar to the `?` operator, but is usable in `const` contexts.
macro_rules! const_try_opt {
($e:expr) => {
match $e {
Some(value) => value,
No... | macro_rules! const_try {
($e:expr) => {
match $e {
Ok(value) => value, | random_line_split |
play15old2.rs | use ndarray::Array2;
use rand::Rng;
use std::borrow::Borrow;
use std::cmp::Ordering;
use std::collections::{BinaryHeap, HashMap, HashSet, VecDeque};
use std::fmt::{Display, Formatter};
pub const WIDTH: usize = 4;
pub const HEIGHT: usize = 4;
#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)]
pub struct Board([[u8; WI... | ;
impl Board {
pub fn new() -> Self {
let mut arr = [[0u8; WIDTH]; HEIGHT];
for y in 0..WIDTH {
for x in 0..HEIGHT {
arr[y][x] = ((y * WIDTH + x + 1) % (WIDTH * HEIGHT)) as u8
}
}
Board(arr)
}
pub fn from_array(arr: [[u8; WIDTH]; HEIG... | BoardCreateError | identifier_name |
play15old2.rs | use ndarray::Array2;
use rand::Rng;
use std::borrow::Borrow;
use std::cmp::Ordering;
use std::collections::{BinaryHeap, HashMap, HashSet, VecDeque};
use std::fmt::{Display, Formatter};
pub const WIDTH: usize = 4;
pub const HEIGHT: usize = 4;
#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)]
pub struct Board([[u8; WI... |
#[inline(always)]
pub fn swap(&mut self, p1: (usize, usize), p2: (usize, usize)) {
let arr = &mut self.0;
let t1 = arr[p1.1][p1.0];
let t2 = arr[p2.1][p2.0];
arr[p1.1][p1.0] = t2;
arr[p2.1][p2.0] = t1;
}
pub fn apply(&mut self, dir: Dir) -> Result<(), ()> {
... | {
for y in 0..HEIGHT {
for x in 0..WIDTH {
if self.0[y][x] == 0 {
return (x, y);
}
}
}
panic!()
} | identifier_body |
play15old2.rs | use ndarray::Array2;
use rand::Rng;
use std::borrow::Borrow;
use std::cmp::Ordering;
use std::collections::{BinaryHeap, HashMap, HashSet, VecDeque};
use std::fmt::{Display, Formatter};
pub const WIDTH: usize = 4;
pub const HEIGHT: usize = 4;
#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)]
pub struct Board([[u8; WI... | // .indexed_iter()
// .map(|((x, y), v)| {
// let (w, h) = self.0.current_board().size();
// let (ox, oy) = if *v == 0 {
// (w - 1, h - 1)
// } else {
// let v = (*v - 1) as usize;
// (v % w... | random_line_split | |
webhdfs.rs | use webhdfs::*;
fn main() {
use std::fs::File;
use std::path::Path;
use std::fs::create_dir_all;
use commandline::*;
let (mut client, op) = parse_command_line();
match op {
Operation::Get(mut fs) => {
match &fs[..] {
&[ref input] => {
let... |
};
(client, operation)
}
}
//-------------------------
mod commandline {
/// Prints two-part message to stderr and exits
pub fn error_exit(msg: &str, detail: &str) ->! {
eprint!("Error: {}", msg);
if detail.is_empty() {
eprintln!()
} else {
... | { error_exit("must specify at least one input file for --get", "") } | conditional_block |
webhdfs.rs | use webhdfs::*;
fn main() {
use std::fs::File;
use std::path::Path;
use std::fs::create_dir_all;
use commandline::*;
let (mut client, op) = parse_command_line();
match op {
Operation::Get(mut fs) => {
match &fs[..] {
&[ref input] => {
let... |
}
#[derive(Debug)]
pub enum CmdLn {
Switch(String),
Arg(String),
Item(String)
}
impl std::fmt::Display for CmdLn {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
CmdLn::Switch(s) => write!(fmt, "Switc... | {
match self {
Some(v) => v,
None => error_exit(msg, "")
}
} | identifier_body |
webhdfs.rs | use webhdfs::*;
fn main() {
use std::fs::File;
use std::path::Path;
use std::fs::create_dir_all;
use commandline::*;
let (mut client, op) = parse_command_line();
match op {
Operation::Get(mut fs) => {
match &fs[..] {
&[ref input] => {
let... | impl std::fmt::Display for CmdLn {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
CmdLn::Switch(s) => write!(fmt, "Switch '{}'", s),
CmdLn::Arg(s) => write!(fmt, "Arg '{}'", s),
CmdLn::Item(s) => write!(fmt, "It... | Switch(String),
Arg(String),
Item(String)
}
| random_line_split |
webhdfs.rs | use webhdfs::*;
fn main() {
use std::fs::File;
use std::path::Path;
use std::fs::create_dir_all;
use commandline::*;
let (mut client, op) = parse_command_line();
match op {
Operation::Get(mut fs) => {
match &fs[..] {
&[ref input] => {
let... | () ->! {
println!(
"{} ({}) version {}",
env!("CARGO_PKG_DESCRIPTION"),
env!("CARGO_PKG_NAME"),
env!("CARGO_PKG_VERSION")
);
std::process::exit(0);
}
fn usage() ->! {
println!("USAGE:
webhdfs <options>... <command> <files>...
webhdfs -h|--help
webhdfs -v|--version
optio... | version | identifier_name |
prefilter.rs | ystack: &[u8], span: Span) -> Candidate;
}
impl<P: PrefilterI +?Sized> PrefilterI for Arc<P> {
#[inline(always)]
fn find_in(&self, haystack: &[u8], span: Span) -> Candidate {
(**self).find_in(haystack, span)
}
}
/// A builder for constructing the best possible prefilter. When constructed,
/// this... | {
/// Whether this prefilter should account for ASCII case insensitivity or
/// not.
ascii_case_insensitive: bool,
/// A set of rare bytes, indexed by byte value.
rare_set: ByteSet,
/// A set of byte offsets associated with bytes in a pattern. An entry
/// corresponds to a particular bytes ... | RareBytesBuilder | identifier_name |
prefilter.rs | ystack: &[u8], span: Span) -> Candidate;
}
impl<P: PrefilterI +?Sized> PrefilterI for Arc<P> {
#[inline(always)]
fn find_in(&self, haystack: &[u8], span: Span) -> Candidate {
(**self).find_in(haystack, span)
}
}
/// A builder for constructing the best possible prefilter. When constructed,
/// this... |
}
}
/// A prefilter for scanning for a single "rare" byte.
#[cfg(feature = "perf-literal")]
#[derive(Clone, Debug)]
struct RareBytesOne {
byte1: u8,
offset: RareByteOffset,
}
#[cfg(feature = "perf-literal")]
impl PrefilterI for RareBytesOne {
fn find_in(&self, haystack: &[u8], span: Span) -> Candidat... | {
self.rare_set.add(byte);
self.count += 1;
self.rank_sum += freq_rank(byte) as u16;
} | conditional_block |
prefilter.rs | ystack: &[u8], span: Span) -> Candidate;
}
impl<P: PrefilterI +?Sized> PrefilterI for Arc<P> {
#[inline(always)]
fn find_in(&self, haystack: &[u8], span: Span) -> Candidate {
(**self).find_in(haystack, span)
}
}
/// A builder for constructing the best possible prefilter. When constructed,
/// this... |
}
/// A builder for constructing a rare byte prefilter.
///
/// A rare byte prefilter attempts to pick out a small set of rare bytes that
/// occurr in the patterns, and then quickly scan to matches of those rare
/// bytes.
#[derive(Clone, Debug)]
struct RareBytesBuilder {
/// Whether this prefilter should accoun... | {
use crate::util::primitives::PatternID;
self.0.find(&haystack[span]).map_or(Candidate::None, |i| {
let start = span.start + i;
let end = start + self.0.needle().len();
// N.B. We can declare a match and use a fixed pattern ID here
// because a Memmem pr... | identifier_body |
prefilter.rs | haystack: &[u8], span: Span) -> Candidate;
}
impl<P: PrefilterI +?Sized> PrefilterI for Arc<P> {
#[inline(always)]
fn find_in(&self, haystack: &[u8], span: Span) -> Candidate {
(**self).find_in(haystack, span)
}
}
/// A builder for constructing the best possible prefilter. When constructed,
/// t... | for b in 0..=255 {
if builder.rare_set.contains(b) {
bytes[len] = b as u8;
len += 1;
}
}
let finder: Arc<dyn PrefilterI> = match len {
0 => return None,
1 => Arc::new(RareBytesOne ... | }
let (mut bytes, mut len) = ([0; 3], 0); | random_line_split |
proxy.rs | Request<Body>) -> Response<Body>
where
T: AsyncRead + AsyncWrite + Send +'static + Sync,
{
let uc = UpstreamConnect::new(t);
let mut res = Response::new(Body::empty());
*res.status_mut() = StatusCode::OK;
res
}
fn result_502_resolve_failed<'a>(m: &'a str) -> Response<Body> {
let mut res = Resp... |
}
pub enum Trace {
TraceId(String),
TraceSecurity(String, openssl::x509::X509),
TraceRequest(String, Request<Body>),
TraceResponse(String, Request<Body>),
}
fn make_absolute(req: &mut Request<Body>) {
/* RFC 7312 5.4
When a proxy receives a request with an absolute-form of
request-ta... | {
Ok(Identity::Anonymous)
} | identifier_body |
proxy.rs | pub friendly_name: Option<String>,
pub attributes: Option<HashMap<String, String>>,
}
pub enum Identity {
User(UserIdentity),
Anonymous,
Role(String),
}
pub trait Authenticate {
fn authenticate(&self, req: &Request<Body>) -> Result<Identity, String>;
}
pub enum AuthzResult {
Allow,
Di... | }
println!("Trace recv");
Ok(())
}); | random_line_split | |
proxy.rs | Request<Body>) -> Response<Body>
where
T: AsyncRead + AsyncWrite + Send +'static + Sync,
{
let uc = UpstreamConnect::new(t);
let mut res = Response::new(Body::empty());
*res.status_mut() = StatusCode::OK;
res
}
fn result_502_resolve_failed<'a>(m: &'a str) -> Response<Body> {
let mut res = Resp... | (&self) -> Proxy<U, S, A> {
Proxy {
tracer: self.tracer.iter().map(|t| t.clone()).next(),
ca: self.ca.clone(),
auth_config: self.auth_config.clone(),
upstream_ssl_pool: pool::Pool::empty(100),
}
}
fn handle<C: Connect +'static>(
&self,
... | dup | identifier_name |
main.rs | use std::{collections::HashSet, fs::File, sync::Arc, time::Duration};
use anyhow::{Context as _, Result};
use serenity::{
async_trait,
client::bridge::gateway::GatewayIntents,
framework::standard::{
macros::{command, group},
Args, CommandResult, StandardFramework,
},
futures::Stream... | let committee_msg = committee_channel
.say(
ctx,
&MessageBuilder::new()
.push("Received request from ")
.mention(&msg.author)
.push(if is_external {
format!(
" to forward message to {}",
... |
let cleaned_content = content_safe(ctx, args.rest(), &ContentSafeOptions::default()).await;
let typing = msg.channel_id.start_typing(&ctx.http)?;
| random_line_split |
main.rs | use std::{collections::HashSet, fs::File, sync::Arc, time::Duration};
use anyhow::{Context as _, Result};
use serenity::{
async_trait,
client::bridge::gateway::GatewayIntents,
framework::standard::{
macros::{command, group},
Args, CommandResult, StandardFramework,
},
futures::Stream... | mmand("forward")]
async fn forward(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult {
let config = {
let data = ctx.data.read().await;
data.get::<ConfigContainer>().unwrap().clone()
};
let delegate_member = if let Ok(member) = ctx
.http
.get_member(config.guild_i... |
#[co | identifier_name |
main.rs | use std::{collections::HashSet, fs::File, sync::Arc, time::Duration};
use anyhow::{Context as _, Result};
use serenity::{
async_trait,
client::bridge::gateway::GatewayIntents,
framework::standard::{
macros::{command, group},
Args, CommandResult, StandardFramework,
},
futures::Stream... | fn parse_name_and_discriminator(
args: &mut Args,
) -> Option<Result<(String, u16), &'static str>> {
let mut name = String::new();
while let Ok(arg) = args.single::<String>() {
let mut fragment = arg.as_str();
if name.is_empty() {
match fragment.strip_prefix('@') {
... | et mut iter = text.splitn(2, pat);
Some((iter.next()?, iter.next()?))
}
async | identifier_body |
pars_upload.rs | use crate::{
create_manager::models::BlobMetadata,
document_manager::{accept_job, check_in_document_handler, delete_document_handler},
models::{Document, FileSource, JobStatusResponse, UniqueDocumentIdentifier},
multipart_form_data::{collect_fields, Field},
state_manager::{with_state, JobStatusClien... | }
fn document_from_form_data(storage_file: StorageFile, metadata: BlobMetadata) -> Document {
Document {
id: metadata.file_name.to_string(),
name: metadata.title.to_string(),
document_type: DocumentType::Par,
author: metadata.author.to_string(),
products: metadata.product_na... | random_line_split | |
pars_upload.rs | use crate::{
create_manager::models::BlobMetadata,
document_manager::{accept_job, check_in_document_handler, delete_document_handler},
models::{Document, FileSource, JobStatusResponse, UniqueDocumentIdentifier},
multipart_form_data::{collect_fields, Field},
state_manager::{with_state, JobStatusClien... | products.push(group);
}
}
}
let file_name = file_field
.as_ref()
.and_then(|field| field.file_name())
.ok_or(SubmissionError::MissingField { name: "file" })?
.to_string();
let file_data = file_field
.and_then(|field| field.into_file_da... | {
let mut products = Vec::new();
let mut file_field = None;
for field in fields {
if field.name == "file" {
file_field = Some(field.value);
continue;
}
if field.name == "product_name" {
products.push(vec![]);
}
match products.las... | identifier_body |
pars_upload.rs | use crate::{
create_manager::models::BlobMetadata,
document_manager::{accept_job, check_in_document_handler, delete_document_handler},
models::{Document, FileSource, JobStatusResponse, UniqueDocumentIdentifier},
multipart_form_data::{collect_fields, Field},
state_manager::{with_state, JobStatusClien... |
None => {
let group = vec![field];
products.push(group);
}
}
}
let file_name = file_field
.as_ref()
.and_then(|field| field.file_name())
.ok_or(SubmissionError::MissingField { name: "file" })?
.to_string();
let fi... | {
group.push(field);
} | conditional_block |
pars_upload.rs | use crate::{
create_manager::models::BlobMetadata,
document_manager::{accept_job, check_in_document_handler, delete_document_handler},
models::{Document, FileSource, JobStatusResponse, UniqueDocumentIdentifier},
multipart_form_data::{collect_fields, Field},
state_manager::{with_state, JobStatusClien... | {
job_ids: Vec<Uuid>,
}
#[derive(Debug, Serialize)]
struct UpdateResponse {
delete: JobStatusResponse,
upload: Vec<Uuid>,
}
async fn read_pars_upload(
form_data: FormData,
) -> Result<(Vec<BlobMetadata>, Vec<u8>), SubmissionError> {
let fields = collect_fields(form_data)
.await
.map... | UploadResponse | identifier_name |
main.rs | /// easiGrow
///
/// by Paul White (Nov 2014--2017)
/// written in rust (www.rust-lang.org)
///
/// A program to match crack growth predictions to measurements.
///
/// The program calculates fatigue crack growth rates and finds the
/// optimum parameters of a crack growth model to match predictions
/// with measuremen... |
// Finally grow the crack with the current parameters which may have been optimised.
// We exit here if the scale has not been set. Otherwise we
// would go through and do a default calculation which confuses
// people if they just want to start the program to see how to get
// help.
fn generate_crack_history(option... | {
match options.optimise.method {
OptimMethod::Sweep => sweep::sweep(options, &mut factors),
OptimMethod::Nelder => optimise::nelder_match_crack(&options, &mut factors),
OptimMethod::Levenberg => optimise_gsl::gsl_match_crack(&options, &mut factors),
OptimMethod::All => {
... | identifier_body |
main.rs | /// easiGrow
///
/// by Paul White (Nov 2014--2017)
/// written in rust (www.rust-lang.org)
///
/// A program to match crack growth predictions to measurements.
///
/// The program calculates fatigue crack growth rates and finds the
/// optimum parameters of a crack growth model to match predictions
/// with measuremen... | OptimMethod::Nelder => optimise::nelder_match_crack(&options, &mut factors),
OptimMethod::Levenberg => optimise_gsl::gsl_match_crack(&options, &mut factors),
OptimMethod::All => {
sweep::sweep(options, &mut factors);
optimise::nelder_match_crack(options, &mut factors);
... | fn optimise_error(options: &options::EasiOptions, mut factors: &mut [f64]) {
match options.optimise.method {
OptimMethod::Sweep => sweep::sweep(options, &mut factors), | random_line_split |
main.rs | /// easiGrow
///
/// by Paul White (Nov 2014--2017)
/// written in rust (www.rust-lang.org)
///
/// A program to match crack growth predictions to measurements.
///
/// The program calculates fatigue crack growth rates and finds the
/// optimum parameters of a crack growth model to match predictions
/// with measuremen... |
};
}
// Finally grow the crack with the current parameters which may have been optimised.
// We exit here if the scale has not been set. Otherwise we
// would go through and do a default calculation which confuses
// people if they just want to start the program to see how to get
// help.
fn generate_crack_histo... | {
sweep::sweep(options, &mut factors);
optimise::nelder_match_crack(options, &mut factors);
optimise_gsl::gsl_match_crack(options, &mut factors)
} | conditional_block |
main.rs | /// easiGrow
///
/// by Paul White (Nov 2014--2017)
/// written in rust (www.rust-lang.org)
///
/// A program to match crack growth predictions to measurements.
///
/// The program calculates fatigue crack growth rates and finds the
/// optimum parameters of a crack growth model to match predictions
/// with measuremen... | (options: &options::EasiOptions, mut factors: &mut [f64]) {
match options.optimise.method {
OptimMethod::Sweep => sweep::sweep(options, &mut factors),
OptimMethod::Nelder => optimise::nelder_match_crack(&options, &mut factors),
OptimMethod::Levenberg => optimise_gsl::gsl_match_crack(&options... | optimise_error | identifier_name |
aio.rs | ::DirectFile;
use libaio::raw::{IoOp, Iocontext};
use std::os::unix::io::AsRawFd;
use tokio::runtime::current_thread;
use tokio_net::util::PollEvented;
use libc;
use slab::Slab;
use log::{info, trace};
#[derive(Debug)]
pub enum Message {
PRead(
DirectFile,
usize,
usize,
BytesMut,... | // let file = DirectFile::open(path.clone(), Mode::Open, FileAccess::Read, 4096).unwrap();
// let mut buf = BytesMut::with_capacity(512);
// unsafe { buf.set_len(512) };
// let (tx, rx) = oneshot::channel();
// session.inner.send(Message::PRead(file, 0, 512, b... |
// let reads = (0..5).map(|_| {
// println!("foo"); | random_line_split |
aio.rs | DirectFile;
use libaio::raw::{IoOp, Iocontext};
use std::os::unix::io::AsRawFd;
use tokio::runtime::current_thread;
use tokio_net::util::PollEvented;
use libc;
use slab::Slab;
use log::{info, trace};
#[derive(Debug)]
pub enum Message {
PRead(
DirectFile,
usize,
usize,
BytesMut,
... | {
curr_polls: u64,
curr_preads: u64,
curr_pwrites: u64,
prev_polls: u64,
prev_preads: u64,
prev_pwrites: u64,
}
impl Future for AioThread {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
trace!(
"============ AioThread... | AioStats | identifier_name |
handshake.rs | // Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! The handshake module implements the handshake part of the protocol.
//! This module also implements additional anti-DoS mitigation,
//! by including a timestamp in each handshake initialization message.
//! Refer to the module's do... | their_public_key
),
));
}
}
// if on a mutually authenticated network
if let Some(anti_replay_timestamps) = &anti_replay_timestamps {
// check that the payload received as the client timestamp (in seconds)
... | // TODO: security logging (mimoo)
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!(
"noise: client connecting to us with an unknown public key: {}", | random_line_split |
handshake.rs | // Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! The handshake module implements the handshake part of the protocol.
//! This module also implements additional anti-DoS mitigation,
//! by including a timestamp in each handshake initialization message.
//! Refer to the module's do... |
};
self.dial(socket, anti_replay_timestamps.is_some(), remote_public_key)
.await?
}
ConnectionOrigin::Inbound => {
self.accept(socket, anti_replay_timestamps, trusted_peers)
.await?
}
};
... | {
return Err(std::io::Error::new(
std::io::ErrorKind::Other,
"noise: SHOULD NOT HAPPEN: missing server's key when dialing",
));
} | conditional_block |
handshake.rs | // Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! The handshake module implements the handshake part of the protocol.
//! This module also implements additional anti-DoS mitigation,
//! by including a timestamp in each handshake initialization message.
//! Refer to the module's do... | (&self, pubkey: x25519::PublicKey, timestamp: u64) -> bool {
if let Some(last_timestamp) = self.0.get(&pubkey) {
×tamp <= last_timestamp
} else {
false
}
}
/// Stores the timestamp
pub fn store_timestamp(&mut self, pubkey: x25519::PublicKey, timestamp: u... | is_replay | identifier_name |
acpi.rs | //! This module provides access to ACPI.
use core::convert::TryInto;
use crate::utils;
use crate::{Error, Ptr};
/// Signature of the RSDP structure.
const ACPI_RSDP_SIGNATURE: &[u8] = b"RSD PTR ";
/// Size of the SDT header.
const ACPI_SDT_SIZE: usize = core::mem::size_of::<AcpiSdtHeader>();
/// Root System Descri... | (&self) -> u32 {
self.fields.flags
}
/// Returns the detected local APIC structures.
pub fn lapic(&self) -> &[MadtLapic] {
&self.lapic_entries[..self.num_lapic_entries]
}
}
| flags | identifier_name |
acpi.rs | //! This module provides access to ACPI.
use core::convert::TryInto;
use crate::utils;
use crate::{Error, Ptr};
/// Signature of the RSDP structure.
const ACPI_RSDP_SIGNATURE: &[u8] = b"RSD PTR ";
/// Size of the SDT header.
const ACPI_SDT_SIZE: usize = core::mem::size_of::<AcpiSdtHeader>();
/// Root System Descri... |
}
// If we reach this point, the table could not be found.
Err(Error::NotFound)
}
}
/// Size of the SDT header.
const ACPI_MADT_FIELDS_SIZE: usize = core::mem::size_of::<AcpiMadtFields>();
/// Maximum number of entries in the MADT.
const ACPI_MADT_ENTRIES_LEN: usize = 256;
/// Extra fie... | {
return unsafe { Madt::new(entry.try_into()?) };
} | conditional_block |
acpi.rs | //! This module provides access to ACPI.
use core::convert::TryInto;
use crate::utils;
use crate::{Error, Ptr};
/// Signature of the RSDP structure.
const ACPI_RSDP_SIGNATURE: &[u8] = b"RSD PTR ";
/// Size of the SDT header.
const ACPI_SDT_SIZE: usize = core::mem::size_of::<AcpiSdtHeader>();
/// Root System Descri... | let length = core::ptr::read_unaligned(ptr.add(1));
// LAPIC.
if ty == 0 {
if num_lapic_entries >= ACPI_MADT_ENTRIES_LEN {
return Err(Error::BufferTooSmall);
}
let lapic =
core::ptr::read_unalig... | {
// Parse header.
let hdr = AcpiSdtHeader::new(madt_ptr, SdtType::Madt)?;
// Parse fields.
let fields = core::ptr::read_unaligned(
(madt_ptr.0 as *const u8).add(ACPI_SDT_SIZE)
as *const AcpiMadtFields,
);
// Parse entries.
let mut nu... | identifier_body |
acpi.rs | //! This module provides access to ACPI.
use core::convert::TryInto;
use crate::utils;
use crate::{Error, Ptr};
/// Signature of the RSDP structure.
const ACPI_RSDP_SIGNATURE: &[u8] = b"RSD PTR ";
/// Size of the SDT header.
const ACPI_SDT_SIZE: usize = core::mem::size_of::<AcpiSdtHeader>();
/// Root System Descri... | Xsdt,
Madt,
}
impl SdtType {
/// Returns the signature of the SDT.
fn signature(&self) -> &[u8] {
match self {
SdtType::Xsdt => b"XSDT",
SdtType::Madt => b"APIC",
}
}
}
/// System Description Table header of the ACPI specification. It is common to
/// all Sy... | random_line_split | |
snapshot.rs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#[cfg(target_family = "unix")]
use crate::disk_usage;
use crate::{
format_error,
image::{Block, Image},
};
use clap::ValueEnum;
use elf::{abi::PT_LOAD, endian::NativeEndian, segment::ProgramHeader};
#[cfg(not(target... | let ranges = [10..20, 30..35, 45..55];
let core_ranges = [
Block {
range: 10..20,
offset: 0,
},
Block {
range: 25..35,
offset: 10,
},
Block {
range: 40..50,
... | mod tests {
use super::*;
#[test]
fn translate_ranges() { | random_line_split |
snapshot.rs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#[cfg(target_family = "unix")]
use crate::disk_usage;
use crate::{
format_error,
image::{Block, Image},
};
use clap::ValueEnum;
use elf::{abi::PT_LOAD, endian::NativeEndian, segment::ProgramHeader};
#[cfg(not(target... |
// try to perform an action, either returning on success, or having the result
// of the error in an indented string.
//
// This special cases `DiskUsageEstimateExceeded` errors, as we want this to
// fail fast and bail out of the `try_method` caller.
macro_rules! try_method {
($func:expr) => {{
match $fu... | {
metadata(Path::new("/proc/kcore"))
.map(|x| x.len() > 0x2000)
.unwrap_or(false)
&& can_open(Path::new("/proc/kcore"))
} | identifier_body |
snapshot.rs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#[cfg(target_family = "unix")]
use crate::disk_usage;
use crate::{
format_error,
image::{Block, Image},
};
use clap::ValueEnum;
use elf::{abi::PT_LOAD, endian::NativeEndian, segment::ProgramHeader};
#[cfg(not(target... | () {
let ranges = [10..20, 30..35, 45..55];
let core_ranges = [
Block {
range: 10..20,
offset: 0,
},
Block {
range: 25..35,
offset: 10,
},
Block {
range: 40..50,
... | translate_ranges | identifier_name |
snapshot.rs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#[cfg(target_family = "unix")]
use crate::disk_usage;
use crate::{
format_error,
image::{Block, Image},
};
use clap::ValueEnum;
use elf::{abi::PT_LOAD, endian::NativeEndian, segment::ProgramHeader};
#[cfg(not(target... | else if can_open(Path::new("/dev/crash")) {
self.create_source(&Source::DevCrash)?;
} else if can_open(Path::new("/dev/mem")) {
self.create_source(&Source::DevMem)?;
} else {
return Err(Error::UnableToCreateSnapshot(
"no source... | {
self.create_source(&Source::ProcKcore)?;
} | conditional_block |
row.rs | notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MER... | header_crc32c, header_crc32c_calculated);
}
let len = (&header[ROW_LAYOUT.size() - 8..]).read_u32::<LittleEndian>().unwrap();
let mut row = BoxRow { ptr: Self::alloc(len) };
row.as_bytes_mut().copy_from_slice(&header);
debug_assert!(row.len == len);
io... | random_line_split | |
row.rs | notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERC... | (&self) -> &[u8] {
&self.0.get_ref()[self.0.position() as usize..]
}
}
pub fn print_row<W: fmt::Write + fmt::Debug>(buf: &mut W, row: &Row,
handler: &dyn Fn(&mut W, u16, &[u8])) -> Result<()> {
fn int_flag(name: &str, default: bool) -> bool {
let fla... | unparsed | identifier_name |
lib.rs | // This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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.a... |
}
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
fn integrity_test() {
// If you hit this error, you need to try to `Box` big dispatchable parameters.
assert!(
sp_std::mem::size_of::<<T as Config>::RuntimeCall>() as u32 <= CALL_ALIGN,
"Call enum size should be smaller tha... | {
let allocator_limit = sp_core::MAX_POSSIBLE_ALLOCATION;
let call_size = ((sp_std::mem::size_of::<<T as Config>::RuntimeCall>() as u32 +
CALL_ALIGN - 1) / CALL_ALIGN) *
CALL_ALIGN;
// The margin to take into account vec doubling capacity.
let margin_factor = 3;
allocator_limit / margin_factor /... | identifier_body |
lib.rs | // This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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.a... | () {
// If you hit this error, you need to try to `Box` big dispatchable parameters.
assert!(
sp_std::mem::size_of::<<T as Config>::RuntimeCall>() as u32 <= CALL_ALIGN,
"Call enum size should be smaller than {} bytes.",
CALL_ALIGN,
);
}
}
#[pallet::error]
pub enum Error<T> {
/// Too many ca... | integrity_test | identifier_name |
lib.rs | // This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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.a... |
let is_root = ensure_root(origin.clone()).is_ok();
let calls_len = calls.len();
ensure!(calls_len <= Self::batched_calls_limit() as usize, Error::<T>::TooManyCalls);
// Track the actual weight of each of the batch calls.
let mut weight = Weight::zero();
for (index, call) in calls.into_iter().enumer... | {
return Err(BadOrigin.into())
} | conditional_block |
lib.rs | // This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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.a... | /// event is deposited. If a call failed and the batch was interrupted, then the
/// `BatchInterrupted` event is deposited, along with the number of successful calls made
/// and the error of the failed call. If all were successful, then the `BatchCompleted`
/// event is deposited.
#[pallet::call_index(0)]
... | /// - O(C) where C is the number of calls to be batched.
///
/// This will return `Ok` in all circumstances. To determine the success of the batch, an | random_line_split |
mod.rs | mod console_tests;
mod iterator;
use std::borrow::Cow;
use ansi_term::Style;
use itertools::Itertools;
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;
use iterator::{AnsiElementIterator, Element};
pub const ANSI_CSI_CLEAR_TO_EOL: &str = "\x1b[0K";
pub const ANSI_CSI_CLEAR_TO_BOL: ... | asure_text_width_osc_hyperlink_non_ascii() {
assert_eq!(measure_text_width("\x1b[38;5;4m\x1b]8;;file:///Users/dan/src/delta/src/ansi/mod.rs\x1b\\src/ansi/modバー.rs\x1b]8;;\x1b\\\x1b[0m"),
measure_text_width("src/ansi/modバー.rs"));
}
#[test]
fn test_parse_first_style() {
let... | _text_width("\x1b[38;5;4m\x1b]8;;file:///Users/dan/src/delta/src/ansi/mod.rs\x1b\\src/ansi/mod.rs\x1b]8;;\x1b\\\x1b[0m"),
measure_text_width("src/ansi/mod.rs"));
}
#[test]
fn test_me | identifier_body |
mod.rs | mod console_tests;
mod iterator;
use std::borrow::Cow;
use ansi_term::Style;
use itertools::Itertools;
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;
use iterator::{AnsiElementIterator, Element};
pub const ANSI_CSI_CLEAR_TO_EOL: &str = "\x1b[0K";
pub const ANSI_CSI_CLEAR_TO_BOL: ... | ure_text_width("\x1b[38;5;4m\x1b]8;;file:///Users/dan/src/delta/src/ansi/mod.rs\x1b\\src/ansi/modバー.rs\x1b]8;;\x1b\\\x1b[0m"),
measure_text_width("src/ansi/modバー.rs"));
}
#[test]
fn test_parse_first_style() {
let minus_line_from_unconfigured_git = "\x1b[31m-____\x1b[m\n";
... | hyperlink_non_ascii() {
assert_eq!(meas | identifier_name |
mod.rs | mod console_tests;
mod iterator;
use std::borrow::Cow;
use ansi_term::Style;
use itertools::Itertools;
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;
use iterator::{AnsiElementIterator, Element};
pub const ANSI_CSI_CLEAR_TO_EOL: &str = "\x1b[0K";
pub const ANSI_CSI_CLEAR_TO_BOL: ... |
}
Cow::from(format!("{result}{result_tail}"))
}
pub fn parse_style_sections(s: &str) -> Vec<(ansi_term::Style, &str)> {
let mut sections = Vec::new();
let mut curr_style = Style::default();
for element in AnsiElementIterator::new(s) {
match element {
Element::Text(start, end) ... | {
result.push_str(t);
} | conditional_block |
mod.rs | mod console_tests;
mod iterator;
use std::borrow::Cow;
use ansi_term::Style;
use itertools::Itertools;
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;
use iterator::{AnsiElementIterator, Element};
pub const ANSI_CSI_CLEAR_TO_EOL: &str = "\x1b[0K";
pub const ANSI_CSI_CLEAR_TO_BOL: ... | measure_text_width("src/ansi/mod.rs"));
}
#[test]
fn test_measure_text_width_osc_hyperlink_non_ascii() {
assert_eq!(measure_text_width("\x1b[38;5;4m\x1b]8;;file:///Users/dan/src/delta/src/ansi/mod.rs\x1b\\src/ansi/modバー.rs\x1b]8;;\x1b\\\x1b[0m"),
measure_text_w... | random_line_split | |
main.rs | #![no_std]
#![no_main]
#![feature(asm)]
#![feature(collections)]
extern crate stm32f7_discovery as stm32f7;
extern crate collections;
extern crate r0;
pub mod plot;
pub mod model;
pub mod temp_sensor;
pub mod time;
pub mod util;
pub mod pid;
pub mod ramp;
pub mod state_button;
mod leak;
use stm32f7::{system_clock,b... | let drag_color = Color::from_hex(0x000000);
let grid_color = Color::from_hex(0x444444);
// lcd controller
let mut lcd = lcd::init(ltdc, rcc, &mut gpio);
touch::check_family_id(&mut i2c_3).unwrap();
loop {
SYSCLOCK.reset();
lcd.clear_screen();
lcd.set_background_color(Color::from_h... | gpio::Resistor::NoPull)
.expect("Could not configure pwm pin");
let axis_color = Color::from_hex(0xffffff); | random_line_split |
main.rs | #![no_std]
#![no_main]
#![feature(asm)]
#![feature(collections)]
extern crate stm32f7_discovery as stm32f7;
extern crate collections;
extern crate r0;
pub mod plot;
pub mod model;
pub mod temp_sensor;
pub mod time;
pub mod util;
pub mod pid;
pub mod ramp;
pub mod state_button;
mod leak;
use stm32f7::{system_clock,b... | (hw: board::Hardware) ->! {
let board::Hardware {
rcc,
pwr,
flash,
fmc,
ltdc,
gpio_a,
gpio_b,
gpio_c,
gpio_d,
gpio_e,
gpio_f,
gpio_g,
gpio_h,
gpio_i,
gpio_j,
gpio_k,
spi_2,
... | main | identifier_name |
main.rs | #![no_std]
#![no_main]
#![feature(asm)]
#![feature(collections)]
extern crate stm32f7_discovery as stm32f7;
extern crate collections;
extern crate r0;
pub mod plot;
pub mod model;
pub mod temp_sensor;
pub mod time;
pub mod util;
pub mod pid;
pub mod ramp;
pub mod state_button;
mod leak;
use stm32f7::{system_clock,b... | // enable floating point unit
let scb = stm32f7::cortex_m::peripheral::scb_mut();
scb.cpacr.modify(|v| v | 0b1111 << 20);
asm!("DSB; ISB;"::::"volatile"); // pipeline flush
main(board::hw());
}
// WORKAROUND: rust compiler will inline & reorder fp instructions into
#[inline(ne... | {
extern "C" {
static __DATA_LOAD: u32;
static __DATA_END: u32;
static mut __DATA_START: u32;
static mut __BSS_START: u32;
static mut __BSS_END: u32;
}
let data_load = &__DATA_LOAD;
let data_start = &mut __DATA_START;
let data_end = &__DATA_END;
let bss_s... | identifier_body |
system_information.rs | use crate::{SMBiosStruct, UndefinedStruct};
use serde::{ser::SerializeStruct, Serialize, Serializer};
use core::{
array::TryFromSliceError,
convert::{TryFrom, TryInto},
fmt,
ops::Deref,
any
};
#[cfg(feature = "no_std")]
use alloc::{string::String, format};
/// # System Information (Type 1)
///
/// ... | fn parts(&self) -> &'a UndefinedStruct {
self.parts
}
}
impl<'a> SMBiosSystemInformation<'a> {
/// Manufacturer
pub fn manufacturer(&self) -> Option<String> {
self.parts.get_field_string(0x04)
}
/// Product name
pub fn product_name(&self) -> Option<String> {
self.pa... | Self { parts }
}
| identifier_body |
system_information.rs | use crate::{SMBiosStruct, UndefinedStruct};
use serde::{ser::SerializeStruct, Serialize, Serializer};
use core::{
array::TryFromSliceError,
convert::{TryFrom, TryInto},
fmt,
ops::Deref,
any
};
#[cfg(feature = "no_std")]
use alloc::{string::String, format};
/// # System Information (Type 1)
///
/// ... | /// Raw value
///
/// _raw_ is most useful when _value_ is None.
/// This is most likely to occur when the standard was updated but
/// this library code has not been updated to match the current
/// standard.
pub raw: u8,
/// The contained [SystemWakeUpType] value
pub value: SystemW... |
/// # System - Wake-up Type Data
pub struct SystemWakeUpTypeData { | random_line_split |
system_information.rs | use crate::{SMBiosStruct, UndefinedStruct};
use serde::{ser::SerializeStruct, Serialize, Serializer};
use core::{
array::TryFromSliceError,
convert::{TryFrom, TryInto},
fmt,
ops::Deref,
any
};
#[cfg(feature = "no_std")]
use alloc::{string::String, format};
/// # System Information (Type 1)
///
/// ... | >(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(format!("{}", self).as_str())
}
}
/// # System - Wake-up Type Data
pub struct SystemWakeUpTypeData {
/// Raw value
///
/// _raw_ is most useful when _value_ is None.
/// This i... | rialize<S | identifier_name |
loader.rs | extern crate xml;
use std;
use std::fs::File;
use std::path::{Path, PathBuf};
use std::ffi::OsStr;
use std::io::{BufReader, Cursor, Read};
use std::sync::mpsc::Sender;
use std::collections::HashMap;
use zip::read::{ZipArchive, ZipFile};
use loader::xml::reader::{EventReader, XmlEvent};
use rodio::source::Source;
... | println!("Unknown song field {}", name.local_name);
xml_skip_tag(&mut reader).unwrap();
State::Song(None)
}
},
XmlEvent::EndElement {.. } => {
if song_rhythm.is_empty() {
// TODO: be graceful
panic!("Empty rhythm");
}
let song = SongData {
name: song_name... | "buildup" => State::Song(Some(SongField::Buildup)),
"buildupRhythm" => State::Song(Some(SongField::BuildupRhythm)),
_ => { | random_line_split |
loader.rs | extern crate xml;
use std;
use std::fs::File;
use std::path::{Path, PathBuf};
use std::ffi::OsStr;
use std::io::{BufReader, Cursor, Read};
use std::sync::mpsc::Sender;
use std::collections::HashMap;
use zip::read::{ZipArchive, ZipFile};
use loader::xml::reader::{EventReader, XmlEvent};
use rodio::source::Source;
... | {
pub info: PackInfo,
pub images: Vec<ImageLoader>,
pub songs: Vec<Song>,
}
pub struct ImageLoader {
//data: SurfaceContext
pub name: String,
pub fullname: Option<String>,
pub data: Surface,
pub source: Option<String>,
pub source_other: Option<String>,
}
pub struct SongData {
pub name: String,
pub title: ... | ResPack | identifier_name |
lib.rs | ///////////////////////////////////////////////////////////////////////////////
//
// Copyright 2018-2021 Robonomics Network <research@robonomics.network>
//
// 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 cop... | (
uri: &str,
technics: &TechnicsFor<Runtime>,
economics: &EconomicsFor<Runtime>,
) -> (AccountId32, MultiSignature) {
let pair = sr25519::Pair::from_string(uri, None).unwrap();
let sender = <MultiSignature as Verify>::Signer::from(pair.public()).into_account();
let si... | get_params_proof | identifier_name |
lib.rs | ///////////////////////////////////////////////////////////////////////////////
//
// Copyright 2018-2021 Robonomics Network <research@robonomics.network>
//
// 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 cop... |
/// How to report of agreement execution.
type Report: dispatch::Parameter + Report<Self::Index, Self::AccountId>;
/// The overarching event type.
type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;
}
pub type TechnicsFor<T> =
<<T as Config>:... | /// How to make and process agreement between two parties.
type Agreement: dispatch::Parameter + Processing + Agreement<Self::AccountId>; | random_line_split |
brush.rs | ty: wgpu::BindingType::Texture {
view_dimension: wgpu::TextureViewDimension::D2,
sample_type: wgpu::TextureSampleType::Float { filterable: true },
multisampled: false,
},
count: None,
},
// fullbright texture
wgpu:... | let texture =
state.create_texture(None, lightmap.width(), lightmap.height(), &lightmap_data);
let id = self.lightmaps.len();
self.lightmaps.push(texture);
//self.lightmap_views
//.push(self.lightmaps[id].create_view(&Default::default()));
... | lightmap: Cow::Borrowed(lightmap.data()),
});
| random_line_split |
brush.rs |
pub fn pipeline(&self) -> &wgpu::RenderPipeline {
&self.pipeline
}
pub fn bind_group_layouts(&self) -> &[wgpu::BindGroupLayout] {
&self.bind_group_layouts
}
pub fn bind_group_layout(&self, id: BindGroupLayoutId) -> &wgpu::BindGroupLayout {
assert!(id as usize >= BindGroupL... |
let layout_refs: Vec<_> = world_bind_group_layouts
.iter()
.chain(self.bind_group_layouts.iter())
.collect();
self.pipeline = BrushPipeline::recreate(device, compiler, &layout_refs, sample_count);
}
| identifier_body | |
brush.rs | ty: wgpu::BindingType::Texture {
view_dimension: wgpu::TextureViewDimension::D2,
sample_type: wgpu::TextureSampleType::Float { filterable: true },
multisampled: false,
},
count: None,
},
// fullbright texture
wgpu:... | width,
height,
tex.name(),
)
})
|
let primary_frames: Vec<_> = primary
.iter()
.map(|f| {
self.create_brush_texture_frame(
state,
f.mipmap(BspTextureMipmap::Full),
width,
... | conditional_block |
brush.rs | &self) -> &[wgpu::BindGroupLayout] {
&self.bind_group_layouts
}
pub fn bind_group_layout(&self, id: BindGroupLayoutId) -> &wgpu::BindGroupLayout {
assert!(id as usize >= BindGroupLayoutId::PerTexture as usize);
&self.bind_group_layouts[id as usize - BindGroupLayoutId::PerTexture as usiz... | ind_group_layouts( | identifier_name | |
glsl3.rs | use std::mem::size_of;
use std::ptr;
use crossfont::RasterizedGlyph;
use log::info;
use alacritty_terminal::term::cell::Flags;
use crate::display::content::RenderableCell;
use crate::display::SizeInfo;
use crate::gl;
use crate::gl::types::*;
use crate::renderer::shader::{ShaderProgram, ShaderVersion};
use crate::ren... |
unsafe {
self.program.set_rendering_pass(RenderingPass::Background);
gl::DrawElementsInstanced(
gl::TRIANGLES,
6,
gl::UNSIGNED_INT,
ptr::null(),
self.batch.len() as GLsizei,
);
self.... | {
unsafe {
gl::BindTexture(gl::TEXTURE_2D, self.batch.tex());
}
*self.active_tex = self.batch.tex();
} | conditional_block |
glsl3.rs | use std::mem::size_of;
use std::ptr;
use crossfont::RasterizedGlyph;
use log::info;
use alacritty_terminal::term::cell::Flags;
use crate::display::content::RenderableCell;
use crate::display::SizeInfo;
use crate::gl;
use crate::gl::types::*;
use crate::renderer::shader::{ShaderProgram, ShaderVersion};
use crate::ren... |
impl TextShaderProgram {
pub fn new(shader_version: ShaderVersion) -> Result<TextShaderProgram, Error> {
let program = ShaderProgram::new(shader_version, None, TEXT_SHADER_V, TEXT_SHADER_F)?;
Ok(Self {
u_projection: program.get_uniform_location(cstr!("projection"))?,
u_cell_... | /// Rendering is split into two passes; one for backgrounds, and one for text.
u_rendering_pass: GLint,
} | random_line_split |
glsl3.rs | use std::mem::size_of;
use std::ptr;
use crossfont::RasterizedGlyph;
use log::info;
use alacritty_terminal::term::cell::Flags;
use crate::display::content::RenderableCell;
use crate::display::SizeInfo;
use crate::gl;
use crate::gl::types::*;
use crate::renderer::shader::{ShaderProgram, ShaderVersion};
use crate::ren... | <'a> {
active_tex: &'a mut GLuint,
batch: &'a mut Batch,
atlas: &'a mut Vec<Atlas>,
current_atlas: &'a mut usize,
program: &'a mut TextShaderProgram,
}
impl<'a> TextRenderApi<Batch> for RenderApi<'a> {
fn batch(&mut self) -> &mut Batch {
self.batch
}
fn render_batch(&mut self) ... | RenderApi | identifier_name |
glsl3.rs | use std::mem::size_of;
use std::ptr;
use crossfont::RasterizedGlyph;
use log::info;
use alacritty_terminal::term::cell::Flags;
use crate::display::content::RenderableCell;
use crate::display::SizeInfo;
use crate::gl;
use crate::gl::types::*;
use crate::renderer::shader::{ShaderProgram, ShaderVersion};
use crate::ren... |
#[inline]
pub fn capacity(&self) -> usize {
BATCH_MAX
}
#[inline]
pub fn size(&self) -> usize {
self.len() * size_of::<InstanceData>()
}
pub fn clear(&mut self) {
self.tex = 0;
self.instances.clear();
}
}
/// Text drawing program.
///
/// Uniforms are... | {
self.instances.len()
} | identifier_body |
service.rs | use crate::{
common::client::{ClientId, Credentials, Token},
coordinator,
};
use bytes::Bytes;
use derive_more::From;
use futures::{ready, stream::Stream};
use std::{
collections::HashMap,
error::Error,
future::Future,
pin::Pin,
task::{Context, Poll},
};
use tarpc::context::current as rpc_co... | /// A future that orchestrates the entire aggregator service.
// TODO: maybe add a HashSet or HashMap of clients who already
// uploaded their weights to prevent a client from uploading weights
// multiple times. Or we could just remove that ID from the
// `allowed_ids` map.
// TODO: maybe add a HashSet for clients th... | random_line_split | |
service.rs | use crate::{
common::client::{ClientId, Credentials, Token},
coordinator,
};
use bytes::Bytes;
use derive_more::From;
use futures::{ready, stream::Stream};
use std::{
collections::HashMap,
error::Error,
future::Future,
pin::Pin,
task::{Context, Poll},
};
use tarpc::context::current as rpc_co... |
}
impl<A> ServiceHandle<A>
where
A: Aggregator +'static,
{
pub fn new() -> (Self, ServiceRequests<A>) {
let (upload_tx, upload_rx) = unbounded_channel::<UploadRequest>();
let (download_tx, download_rx) = unbounded_channel::<DownloadRequest>();
let (aggregate_tx, aggregate_rx) = unbound... | {
Self {
upload: self.upload.clone(),
download: self.download.clone(),
aggregate: self.aggregate.clone(),
select: self.select.clone(),
}
} | identifier_body |
service.rs | use crate::{
common::client::{ClientId, Credentials, Token},
coordinator,
};
use bytes::Bytes;
use derive_more::From;
use futures::{ready, stream::Stream};
use std::{
collections::HashMap,
error::Error,
future::Future,
pin::Pin,
task::{Context, Poll},
};
use tarpc::context::current as rpc_co... | (&mut self, request: SelectRequest<A>) {
info!("handling select request");
let SelectRequest {
credentials,
response_tx,
} = request;
let (id, token) = credentials.into_parts();
self.allowed_ids.insert(id, token);
if response_tx.send(Ok(())).is_err... | handle_select_request | identifier_name |
service.rs | use crate::{
common::client::{ClientId, Credentials, Token},
coordinator,
};
use bytes::Bytes;
use derive_more::From;
use futures::{ready, stream::Stream};
use std::{
collections::HashMap,
error::Error,
future::Future,
pin::Pin,
task::{Context, Poll},
};
use tarpc::context::current as rpc_co... |
pin.poll_aggregation(cx);
Poll::Pending
}
}
pub struct ServiceRequests<A>(Pin<Box<dyn Stream<Item = Request<A>> + Send>>)
where
A: Aggregator;
impl<A> Stream for ServiceRequests<A>
where
A: Aggregator,
{
type Item = Request<A>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Co... | {
return Poll::Ready(());
} | conditional_block |
bg.rs | of all background layers. The cache is created lazily
/// (when BG layer pixels are looked up), so we will not waste time caching a disabled BG layer.
#[derive(Default)]
pub struct BgCache {
layers: [BgLayerCache; 4],
}
/// Data that's stored in the BG layer caches for a single pixel
#[derive(Copy, Clone, Default... | (&mut self) {
self.valid = false;
}
}
impl BgCache {
/// Invalidates the BG cache of all layers
fn invalidate_all(&mut self) {
self.layers[0].valid = false;
self.layers[1].valid = false;
self.layers[2].valid = false;
self.layers[3].valid = false;
}
}
/// Collect... | invalidate | identifier_name |
bg.rs | line of all background layers. The cache is created lazily
/// (when BG layer pixels are looked up), so we will not waste time caching a disabled BG layer.
#[derive(Default)]
pub struct BgCache {
layers: [BgLayerCache; 4],
}
/// Data that's stored in the BG layer caches for a single pixel
#[derive(Copy, Clone, Def... | let color_bits = self.color_bits_for_bg(bg_num);
if color_bits == 8 {
// can use direct color mode
debug_assert!(self.cgwsel & 0x01 == 0, "NYI: direct color mode");
}
let mut tile_x = x.wrapping_add(hofs) / tile_size as u16;
let tile_y = y.wrapping_add(vo... | random_line_split | |
topology.rs | //
//! Copyright 2020 Alibaba Group Holding Limited.
//!
//! 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 ... |
#[inline]
pub fn count_edges(&self) -> usize {
self.count
}
}
#[cfg(test)]
mod test {
use super::*;
use std::path::PathBuf;
#[test]
fn test_segment_list() {
let mut list = SegmentList::new(6);
for i in 0..1024 {
list.push(i);
}
for ... | {
self.neighbors.len()
} | identifier_body |
topology.rs | //
//! Copyright 2020 Alibaba Group Holding Limited.
//!
//! 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 ... | (id: u64) -> Self {
Vertex {
id,
#[cfg(feature = "padding")]
padding_1: [0; 8],
#[cfg(feature = "padding")]
padding_2: [0; 7]
}
}
}
pub struct NeighborIter {
cursor: usize,
len: usize,
inner: Arc<Vec<u64>>
}
impl NeighborIter ... | new | identifier_name |
topology.rs | //
//! Copyright 2020 Alibaba Group Holding Limited.
//!
//! 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 ... | if peers == 1 || (d % peers as u64) as u32 == partition {
let n = neighbors.entry(*d).or_insert(Vec::new());
if!directed {
n.push(*s);
count += 1;
}
}
}
let mut arc_neighbors = HashMap::new();... | count += 1;
}
| random_line_split |
lib.rs | //! Contract module which acts as a timelocked controller. When set as the
//! owner of an `Ownable` smart contract, it enforces a timelock on all
//! `onlyOwner` maintenance operations. This gives time for users of the
//! controlled contract to exit before a potentially dangerous maintenance
//! operation is applied.... |
impl<E> Default for Data<E>
where
E: Env,
{
fn default() -> Self {
Self {
min_delay: Lazy::new(E::Timestamp::from(1_u8)),
timestamps: StorageHashMap::default(),
}
}
}
impl<E: Env> Data<E> {}
/// The `EventEmit` impl the event emit api for component.
pub trait Event... | pub fn new() -> Self {
Self::default()
}
} | random_line_split |
lib.rs | //! Contract module which acts as a timelocked controller. When set as the
//! owner of an `Ownable` smart contract, it enforces a timelock on all
//! `onlyOwner` maintenance operations. This gives time for users of the
//! controlled contract to exit before a potentially dangerous maintenance
//! operation is applied.... |
/// Execute an operation's call.
///
/// Emits a `CallExecuted` event.
fn _call(
&mut self,
id: [u8; 32],
target: E::AccountId,
value: E::Balance,
data: Vec<u8>,
) {
let mut receiver =
<Receiver as FromAccountId<E>>::from_account_id(targe... | {
assert!(
self.is_operation_ready(&id),
"TimelockController: operation is not ready"
);
Storage::<E, Data<E>>::get_mut(self)
.timestamps
.insert(id, E::Timestamp::from(_DONE_TIMESTAMP));
} | identifier_body |
lib.rs | //! Contract module which acts as a timelocked controller. When set as the
//! owner of an `Ownable` smart contract, it enforces a timelock on all
//! `onlyOwner` maintenance operations. This gives time for users of the
//! controlled contract to exit before a potentially dangerous maintenance
//! operation is applied.... | (&self, id: &[u8; 32]) -> bool {
self.get_timestamp(id) > E::Timestamp::from(_DONE_TIMESTAMP)
}
/// Returns whether an operation is ready or not.
fn is_operation_ready(&self, id: &[u8; 32]) -> bool {
let timestamp = self.get_timestamp(id);
timestamp > E::Timestamp::from(_DONE_TIMEST... | is_operation_pending | identifier_name |
scheduling.rs | use super::*;
use crate::domain::scheduling::*;
use chrono::{DateTime, SecondsFormat};
use futures::{Async, Future, Stream};
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::Duration;
use tokio::timer::{
delay_queue::{Expired, Key as DelayQueueKey},
DelayQueue,
};
enum DelayQueueItem<T> {
TaskS... | (
&mut self,
response_tx: CommandResponseSender,
command: TaskSchedulingCommand<T>,
) {
let result = match command {
TaskSchedulingCommand::RescheduleAll(task_schedules) => {
self.scheduled_tasks
.lock_inner()
.resched... | handle_command | identifier_name |
scheduling.rs | use super::*;
use crate::domain::scheduling::*;
use chrono::{DateTime, SecondsFormat};
use futures::{Async, Future, Stream};
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::Duration;
use tokio::timer::{
delay_queue::{Expired, Key as DelayQueueKey},
DelayQueue,
};
enum DelayQueueItem<T> {
TaskS... | impl<T> TaskSchedulingActor<T>
where
T: TaskSchedule + Send + std::fmt::Debug,
{
pub fn create(
task_scheduler: Box<dyn TaskScheduler<TaskSchedule = T> + Send>,
) -> (
impl Future<Item = (), Error = ()>,
TaskSchedulingActionSender<T>,
TaskSchedulingNotificationReceiver,
)... | scheduled_tasks: ScheduledTasks<T>,
}
| random_line_split |
scheduling.rs | use super::*;
use crate::domain::scheduling::*;
use chrono::{DateTime, SecondsFormat};
use futures::{Async, Future, Stream};
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::Duration;
use tokio::timer::{
delay_queue::{Expired, Key as DelayQueueKey},
DelayQueue,
};
enum DelayQueueItem<T> {
TaskS... |
}
impl<T> Stream for ScheduledTasks<T> {
type Item = <DelayQueue<DelayQueueItem<T>> as Stream>::Item;
type Error = <DelayQueue<DelayQueueItem<T>> as Stream>::Error;
fn poll(&mut self) -> Result<Async<Option<Self::Item>>, Self::Error> {
self.lock_inner().poll()
}
}
#[derive(Debug, Clone, Copy... | {
ScheduledTasks(self.0.clone())
} | identifier_body |
handler.rs | // Copyright 2019 Parity Technologies (UK) Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, mer... | KeepAlive::Yes
} else {
KeepAlive::No
}
}
fn poll(&mut self) -> Poll<ProtocolsHandlerEvent<protocol::Ping, (), PingResult>, Self::Error> {
if let Some(result) = self.pending_results.pop_back() {
if let Ok(PingSuccess::Ping {.. }) = result {
... | random_line_split | |
handler.rs | // Copyright 2019 Parity Technologies (UK) Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, mer... |
e => panic!("Unexpected event: {:?}", e)
}
}
h.inject_dial_upgrade_error((), ProtocolsHandlerUpgrErr::Timeout);
match tick(&mut h) {
Err(PingFailure::Timeout) => {
assert_eq!(h.failures, h.config.max_failures.get());
}
... | {} | conditional_block |
handler.rs | // Copyright 2019 Parity Technologies (UK) Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, mer... | (config: PingConfig) -> Self {
PingHandler {
config,
next_ping: Delay::new(Instant::now()),
pending_results: VecDeque::with_capacity(2),
failures: 0,
_marker: std::marker::PhantomData
}
}
}
impl<TSubstream> ProtocolsHandler for PingHandler... | new | identifier_name |
handler.rs | // Copyright 2019 Parity Technologies (UK) Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, mer... |
fn inject_fully_negotiated_outbound(&mut self, rtt: Duration, _info: ()) {
// A ping initiated by the local peer was answered by the remote.
self.pending_results.push_front(Ok(PingSuccess::Ping { rtt }));
}
fn inject_event(&mut self, _: Void) {}
fn inject_dial_upgrade_error(&mut self... | {
// A ping from a remote peer has been answered.
self.pending_results.push_front(Ok(PingSuccess::Pong));
} | identifier_body |
dict.rs | use bitflags::bitflags;
use std::{ffi::CStr, fmt, marker::PhantomData};
pub trait ReadableDict {
/// Obtain the pointer to the raw `spa_dict` struct.
fn get_dict_ptr(&self) -> *const spa_sys::spa_dict;
/// An iterator over all raw key-value pairs.
/// The iterator element type is `(&CStr, &CStr)`.
... | () {
let (_strings, _items, raw) = make_raw_dict(2);
let dict = unsafe { ForeignDict::from_ptr(&raw) };
let mut iter = dict.iter_cstr();
assert_eq!(
(
CString::new("K0").unwrap().as_c_str(),
CString::new("V0").unwrap().as_c_str()
)... | test_iter_cstr | identifier_name |
dict.rs | use bitflags::bitflags;
use std::{ffi::CStr, fmt, marker::PhantomData};
pub trait ReadableDict {
/// Obtain the pointer to the raw `spa_dict` struct.
fn get_dict_ptr(&self) -> *const spa_sys::spa_dict;
/// An iterator over all raw key-value pairs.
/// The iterator element type is `(&CStr, &CStr)`.
... |
}
fn size_hint(&self) -> (usize, Option<usize>) {
let bound: usize = unsafe { self.next.offset_from(self.end) as usize };
// We know the exact value, so lower bound and upper bound are the same.
(bound, Some(bound))
}
}
pub struct Iter<'a> {
inner: CIter<'a>,
}
impl<'a> Iter... | {
None
} | conditional_block |
dict.rs | use bitflags::bitflags;
use std::{ffi::CStr, fmt, marker::PhantomData};
pub trait ReadableDict {
/// Obtain the pointer to the raw `spa_dict` struct.
fn get_dict_ptr(&self) -> *const spa_sys::spa_dict;
/// An iterator over all raw key-value pairs.
/// The iterator element type is `(&CStr, &CStr)`.
... |
}
| {
let (_strings, _items, raw) = make_raw_dict(1);
let dict = unsafe { ForeignDict::from_ptr(&raw) };
assert_eq!(r#"{"K0": "V0"}"#, &format!("{:?}", dict))
} | identifier_body |
dict.rs | use bitflags::bitflags;
use std::{ffi::CStr, fmt, marker::PhantomData};
pub trait ReadableDict {
/// Obtain the pointer to the raw `spa_dict` struct.
fn get_dict_ptr(&self) -> *const spa_sys::spa_dict;
/// An iterator over all raw key-value pairs.
/// The iterator element type is `(&CStr, &CStr)`.
... | fn is_empty(&self) -> bool {
self.len() == 0
}
/// Returns the bitflags that are set for the dict.
fn flags(&self) -> Flags {
Flags::from_bits_truncate(unsafe { (*self.get_dict_ptr()).flags })
}
/// Get the value associated with the provided key.
///
/// If the dict doe... | random_line_split | |
lib.rs | //! # Substrate Enterprise Sample - Product Tracking pallet
#![cfg_attr(not(feature = "std"), no_std)]
use codec::alloc::string::ToString;
use core::convert::TryInto;
use frame_support::{
debug, decl_error, decl_event, decl_module, decl_storage, dispatch, ensure,
sp_runtime::offchain::{
self as rt_off... |
// --- Offchain worker methods ---
fn process_ocw_notifications(block_number: T::BlockNumber) {
// Check last processed block
let last_processed_block_ref =
StorageValueRef::persistent(b"product_tracking_ocw::last_proccessed_block");
let mut last_processed_block: u32 = mat... | {
ensure!(
props.len() <= SHIPMENT_MAX_PRODUCTS,
Error::<T>::ShipmentHasTooManyProducts,
);
Ok(())
} | identifier_body |
lib.rs | //! # Substrate Enterprise Sample - Product Tracking pallet
#![cfg_attr(not(feature = "std"), no_std)]
use codec::alloc::string::ToString;
use core::convert::TryInto;
use frame_support::{
debug, decl_error, decl_event, decl_module, decl_storage, dispatch, ensure,
sp_runtime::offchain::{
self as rt_off... | let status = shipment.status.clone();
// Create shipping event
let event = Self::new_shipping_event()
.of_type(ShippingEventType::ShipmentRegistration)
.for_shipment(id.clone())
.at_location(None)
.with_readings(vec![])
... | .registered_at(<timestamp::Module<T>>::now())
.with_products(products)
.build(); | random_line_split |
lib.rs | //! # Substrate Enterprise Sample - Product Tracking pallet
#![cfg_attr(not(feature = "std"), no_std)]
use codec::alloc::string::ToString;
use core::convert::TryInto;
use frame_support::{
debug, decl_error, decl_event, decl_module, decl_storage, dispatch, ensure,
sp_runtime::offchain::{
self as rt_off... |
}
fn notify_listener(ev: &ShippingEvent<T::Moment>) -> Result<(), &'static str> {
debug::info!("notifying listener: {:?}", ev);
let request =
sp_runtime::offchain::http::Request::post(&LISTENER_ENDPOINT, vec![ev.to_string()]);
let timeout =
sp_io::offchain::ti... | {
last_processed_block_ref.set(&last_processed_block);
debug::info!(
"[product_tracking_ocw] Notifications successfully processed up to block {}",
last_processed_block
);
} | conditional_block |
lib.rs | //! # Substrate Enterprise Sample - Product Tracking pallet
#![cfg_attr(not(feature = "std"), no_std)]
use codec::alloc::string::ToString;
use core::convert::TryInto;
use frame_support::{
debug, decl_error, decl_event, decl_module, decl_storage, dispatch, ensure,
sp_runtime::offchain::{
self as rt_off... | (block_number: T::BlockNumber) {
// Check last processed block
let last_processed_block_ref =
StorageValueRef::persistent(b"product_tracking_ocw::last_proccessed_block");
let mut last_processed_block: u32 = match last_processed_block_ref.get::<T::BlockNumber>() {
Some(Som... | process_ocw_notifications | identifier_name |
app.rs | use audio;
use audio::cpal;
use find_folder;
use glium::glutin;
use state;
use std;
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::marker::PhantomData;
use std::path::PathBuf;
use std::sync::{mpsc, Arc};
use std::thread;
use std::time::Duration;
use window::{self, Window};
use ui;
/// An **App... | model,
sample_rate: None,
channels: None,
frames_per_buffer: None,
device: None,
sample_format: PhantomData,
}
}
}
impl Proxy {
/// Wake up the application!
///
/// This wakes up the **App**'s inner event loop and inserts a... | random_line_split | |
app.rs | use audio;
use audio::cpal;
use find_folder;
use glium::glutin;
use state;
use std;
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::marker::PhantomData;
use std::path::PathBuf;
use std::sync::{mpsc, Arc};
use std::thread;
use std::time::Duration;
use window::{self, Window};
use ui;
/// An **App... |
}
| {
self.events_loop_proxy.wakeup()
} | identifier_body |
app.rs | use audio;
use audio::cpal;
use find_folder;
use glium::glutin;
use state;
use std;
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::marker::PhantomData;
use std::path::PathBuf;
use std::sync::{mpsc, Arc};
use std::thread;
use std::time::Duration;
use window::{self, Window};
use ui;
/// An **App... | (&self) -> Result<PathBuf, find_folder::Error> {
let exe_path = std::env::current_exe()?;
find_folder::Search::ParentsThenKids(5, 3)
.of(exe_path.parent().expect("executable has no parent directory to search").into())
.for_folder(Self::ASSETS_DIRECTORY_NAME)
}
/// Begin bu... | assets_path | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.