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 |
|---|---|---|---|---|
functional_dependencies.rs |
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the ... | /// this flag is `false`.
/// Note that as the schema changes between different stages in a plan,
/// such as after LEFT JOIN or RIGHT JOIN operations, this property may
/// change.
pub nullable: bool,
// The functional dependency mode:
pub mode: Dependency,
}
/// Describes functional depen... | pub target_indices: Vec<usize>,
/// Flag indicating whether one of the `source_indices` can receive NULL values.
/// For a data source, if the constraint in question is `Constraint::Unique`,
/// this flag is `true`. If the constraint in question is `Constraint::PrimaryKey`, | random_line_split |
functional_dependencies.rs |
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the Lic... | DataFusionError::Execution(
"Primary key doesn't exist".to_string(),
)
})?;
Ok(idx)
})
.collect::<Res... | {
let constraints = constraints
.iter()
.map(|c: &TableConstraint| match c {
TableConstraint::Unique {
columns,
is_primary,
..
} => {
// Get primary key and/or unique indices i... | identifier_body |
functional_dependencies.rs |
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the Lic... | (dependencies: Vec<FunctionalDependence>) -> Self {
Self { deps: dependencies }
}
/// Creates a new `FunctionalDependencies` object from the given constraints.
pub fn new_from_constraints(
constraints: Option<&Constraints>,
n_field: usize,
) -> Self {
if let Some(Constra... | new | identifier_name |
functional_dependencies.rs |
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the Lic... | else {
Constraint::Unique(indices)
})
}
TableConstraint::ForeignKey {.. } => Err(DataFusionError::Plan(
"Foreign key constraints are not currently supported".to_string(),
)),
TableConstraint:... | {
Constraint::PrimaryKey(indices)
} | conditional_block |
apigroup.rs | use super::{
parse::{self, GroupVersionData},
version::Version,
};
use crate::{error::DiscoveryError, Client, Result};
use k8s_openapi::apimachinery::pkg::apis::meta::v1::{APIGroup, APIVersions};
pub use kube_core::discovery::{verbs, ApiCapabilities, ApiResource, Scope};
use kube_core::gvk::{GroupVersion, Group... |
}
Err(DiscoveryError::MissingKind(format!("{:?}", gvk)).into())
}
// shortcut method to give cheapest return for a pinned group
pub(crate) async fn query_gv(client: &Client, gv: &GroupVersion) -> Result<Self> {
let apiver = gv.api_version();
let list = if gv.group.is_empty(... | {
let ar = parse::parse_apiresource(res, &list.group_version)?;
let caps = parse::parse_apicapabilities(&list, &res.name)?;
return Ok((ar, caps));
} | conditional_block |
apigroup.rs | use super::{
parse::{self, GroupVersionData},
version::Version,
};
use crate::{error::DiscoveryError, Client, Result};
use k8s_openapi::apimachinery::pkg::apis::meta::v1::{APIGroup, APIVersions};
pub use kube_core::discovery::{verbs, ApiCapabilities, ApiResource, Scope};
use kube_core::gvk::{GroupVersion, Group... | (&mut self) {
self.data
.sort_by_cached_key(|gvd| Version::parse(gvd.version.as_str()))
}
// shortcut method to give cheapest return for a single GVK
pub(crate) async fn query_gvk(
client: &Client,
gvk: &GroupVersionKind,
) -> Result<(ApiResource, ApiCapabilities)> {
... | sort_versions | identifier_name |
apigroup.rs | use super::{
parse::{self, GroupVersionData},
version::Version,
};
use crate::{error::DiscoveryError, Client, Result};
use k8s_openapi::apimachinery::pkg::apis::meta::v1::{APIGroup, APIVersions};
pub use kube_core::discovery::{verbs, ApiCapabilities, ApiResource, Scope};
use kube_core::gvk::{GroupVersion, Group... | /// for inst in api.list(&Default::default()).await? {
/// println!("Found {}: {}", ar.kind, inst.name());
/// }
/// }
/// Ok(())
/// }
/// ```
///
/// This is equivalent to taking the [`ApiGroup::versioned_resources`] at the [`ApiGroup::preferred_... | /// for (ar, caps) in apigroup.recommended_resources() {
/// if !caps.supports_operation(verbs::LIST) {
/// continue;
/// }
/// let api: Api<DynamicObject> = Api::all_with(client.clone(), &ar); | random_line_split |
apigroup.rs | use super::{
parse::{self, GroupVersionData},
version::Version,
};
use crate::{error::DiscoveryError, Client, Result};
use k8s_openapi::apimachinery::pkg::apis::meta::v1::{APIGroup, APIVersions};
pub use kube_core::discovery::{verbs, ApiCapabilities, ApiResource, Scope};
use kube_core::gvk::{GroupVersion, Group... |
// shortcut method to give cheapest return for a pinned group
pub(crate) async fn query_gv(client: &Client, gv: &GroupVersion) -> Result<Self> {
let apiver = gv.api_version();
let list = if gv.group.is_empty() {
client.list_core_api_resources(&apiver).await?
} else {
... | {
let apiver = gvk.api_version();
let list = if gvk.group.is_empty() {
client.list_core_api_resources(&apiver).await?
} else {
client.list_api_group_resources(&apiver).await?
};
for res in &list.resources {
if res.kind == gvk.kind && !res.name.... | identifier_body |
tlcell.rs | use std::any::TypeId;
use std::cell::UnsafeCell;
use std::collections::HashSet;
use std::marker::PhantomData;
use super::Invariant;
std::thread_local! {
static SINGLETON_CHECK: std::cell::RefCell<HashSet<TypeId>> = std::cell::RefCell::new(HashSet::new());
}
struct NotSendOrSync(*const ());
/// Borrowing-owner o... | else {
Box::new(ACell::new(Integers(init as u64)))
}
}
let own = &mut owner;
let cell1 = series(4, false);
let cell2 = series(7, true);
let cell3 = series(3, true);
assert_eq!(cell1.ro(own).value(), 4);
cell1.rw(own).step();
a... | {
Box::new(ACell::new(Squares(init)))
} | conditional_block |
tlcell.rs | use std::any::TypeId;
use std::cell::UnsafeCell;
use std::collections::HashSet;
use std::marker::PhantomData;
use super::Invariant;
std::thread_local! {
static SINGLETON_CHECK: std::cell::RefCell<HashSet<TypeId>> = std::cell::RefCell::new(HashSet::new());
}
struct NotSendOrSync(*const ());
/// Borrowing-owner o... | /// thread, `Sync` is not supported for this type. However it *is*
/// possible to send the cell to another thread, which then allows its
/// contents to be borrowed using the owner in that thread.
///
/// See also [crate documentation](index.html).
///
/// [`TLCellOwner`]: struct.TLCellOwner.html
#[repr(transparent)]... | /// [`TLCellOwner`].
///
/// To borrow from this cell, use the borrowing calls on the
/// [`TLCellOwner`] instance that shares the same marker type. Since
/// there may be another indistinguishable [`TLCellOwner`] in another | random_line_split |
tlcell.rs | use std::any::TypeId;
use std::cell::UnsafeCell;
use std::collections::HashSet;
use std::marker::PhantomData;
use super::Invariant;
std::thread_local! {
static SINGLETON_CHECK: std::cell::RefCell<HashSet<TypeId>> = std::cell::RefCell::new(HashSet::new());
}
struct | (*const ());
/// Borrowing-owner of zero or more [`TLCell`](struct.TLCell.html)
/// instances.
///
/// See [crate documentation](index.html).
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
pub struct TLCellOwner<Q:'static> {
// Use NotSendOrSync to disable Send and Sync,
not_send_or_sync: PhantomData<NotSendOr... | NotSendOrSync | identifier_name |
mod.rs | // Copyright (c) The XPeer Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! In a leader based consensus algorithm, each participant maintains a block tree that looks like
//! the following:
//! ```text
//! Height 5 6 7 ...
//!
//! Committed -> B5 -> B6 -> B7
//! |
//! ... | id,
);
}
hash_map::Entry::Vacant(_) => bail_err!(AddBlockError::ParentNotFound { block }),
}
Ok(())
}
//
/ Returns a reference to a specific block, if it exists in the tree.
pub fn get_block(&self, id: HashValue) -> Option<&B> {
... | assert!(!self.id_to_block.contains_key(&self.last_committed_id));
let id = block.id();
if self.id_to_block.contains_key(&id) {
bail_err!(AddBlockError::BlockAlreadyExists { block });
}
let parent_id = block.parent_id();
if parent_id == self.last_committed_id {
... | identifier_body |
mod.rs | // Copyright (c) The XPeer Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! In a leader based consensus algorithm, each participant maintains a block tree that looks like
//! the following:
//! ```text
//! Height 5 6 7 ...
//!
//! Committed -> B5 -> B6 -> B7
//! |
//! ... | lf, last_committed_id: HashValue) {
let mut new_block_tree = BlockTree::new(last_committed_id);
std::mem::swap(self, &mut new_block_tree);
}
}
/// An error returned by `add_block`. The error contains the block being added so the caller does
/// not lose it.
#[derive(Debug, Eq, PartialEq)]
pub enum ... | ut se | identifier_name |
mod.rs | // Copyright (c) The XPeer Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! In a leader based consensus algorithm, each participant maintains a block tree that looks like
//! the following:
//! ```text
//! Height 5 6 7 ...
//!
//! Committed -> B5 -> B6 -> B7
//! |
//! ... | let mut current_heads = self.heads.clone();
while let Some(committed_head) = self.get_committed_head(¤t_heads) {
assert!(
current_heads.remove(&committed_head),
"committed_head should exist.",
);
for id in current_heads {
... |
// First find if there is a committed block in current heads. Since these blocks are at the
// same height, at most one of them can be committed. If all of them are pending we have
// nothing to do here. Otherwise, one of the branches is committed. Throw away the rest of
// them and ad... | random_line_split |
mod.rs | use anyhow::{bail, format_err, Error};
use std::ffi::{CStr, CString};
mod tm_editor;
pub use tm_editor::*;
/// Safe bindings to libc timelocal
///
/// We set tm_isdst to -1.
/// This also normalizes the parameter
pub fn timelocal(t: &mut libc::tm) -> Result<i64, Error> {
t.tm_isdst = -1;
let epoch = unsafe {... |
Ok(digit - 48)
};
let check_max = |i: i32, max: i32| {
if i > max {
bail!("value too large ({} > {})", i, max);
}
Ok(i)
};
crate::try_block!({
if input.len() < 20 || input.len() > 25 {
bail!("timestamp of unexpected length");
}
... | {
bail!("unexpected char at pos {}", pos);
} | conditional_block |
mod.rs | use anyhow::{bail, format_err, Error};
use std::ffi::{CStr, CString};
mod tm_editor;
pub use tm_editor::*;
/// Safe bindings to libc timelocal
///
/// We set tm_isdst to -1.
/// This also normalizes the parameter
pub fn timelocal(t: &mut libc::tm) -> Result<i64, Error> {
t.tm_isdst = -1;
let epoch = unsafe {... | (format: &str, epoch: i64) -> Result<String, Error> {
let localtime = localtime(epoch)?;
strftime(format, &localtime)
}
/// Format epoch as utc time
pub fn strftime_utc(format: &str, epoch: i64) -> Result<String, Error> {
let gmtime = gmtime(epoch)?;
strftime(format, &gmtime)
}
/// Convert Unix epoch ... | strftime_local | identifier_name |
mod.rs | use anyhow::{bail, format_err, Error};
use std::ffi::{CStr, CString};
mod tm_editor;
pub use tm_editor::*;
/// Safe bindings to libc timelocal
///
/// We set tm_isdst to -1.
/// This also normalizes the parameter
pub fn timelocal(t: &mut libc::tm) -> Result<i64, Error> {
t.tm_isdst = -1;
let epoch = unsafe {... |
/// Convert Unix epoch into RFC3339 UTC string
pub fn epoch_to_rfc3339_utc(epoch: i64) -> Result<String, Error> {
let gmtime = gmtime(epoch)?;
let year = gmtime.tm_year + 1900;
if year < 0 || year > 9999 {
bail!("epoch_to_rfc3339_utc: wrong year '{}'", year);
}
strftime("%010FT%TZ", &gmt... | {
let gmtime = gmtime(epoch)?;
strftime(format, &gmtime)
} | identifier_body |
mod.rs | use anyhow::{bail, format_err, Error};
use std::ffi::{CStr, CString};
mod tm_editor;
pub use tm_editor::*;
/// Safe bindings to libc timelocal
///
/// We set tm_isdst to -1.
/// This also normalizes the parameter
pub fn timelocal(t: &mut libc::tm) -> Result<i64, Error> {
t.tm_isdst = -1;
let epoch = unsafe {... | let parsed =
parse_rfc3339(lower_str).expect("parsing lower bound of RFC3339 range should work");
assert_eq!(parsed, lower);
let parsed =
parse_rfc3339(upper_str).expect("parsing upper bound of RFC3339 range should work");
assert_eq!(parsed, upper);
epoch_to_rfc3339_utc(lower - 1)
... | let converted =
epoch_to_rfc3339_utc(upper).expect("converting upper bound of RFC3339 range should work");
assert_eq!(converted, upper_str);
| random_line_split |
mc6845.rs | /*
MartyPC
https://github.com/dbalsom/martypc
Copyright 2022-2023 Daniel Balsom
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 limi... | self.update_start_address();
}
CrtcRegister::StartAddressL => {
// (R13) 8 bit write only
self.reg[13] = byte;
trace_regs!(self);
trace!(
self,
"CRTC Register Write (0Dh): Star... | "CRTC Register Write (0Ch): StartAddressH updated: {:02X}",
byte
); | random_line_split |
mc6845.rs | /*
MartyPC
https://github.com/dbalsom/martypc
Copyright 2022-2023 Daniel Balsom
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 limi... | reg: [u8; 18], // Externally-accessable CRTC register file
reg_select: CrtcRegister, // Selected CRTC register
start_address: u16, // Calculated value from R12 & R13
cursor_address: u16, // Calculated value from R14 & R15
lightpen_position: u16, // ... | {
| identifier_name |
mc6845.rs | /*
MartyPC
https://github.com/dbalsom/martypc
Copyright 2022-2023 Daniel Balsom
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 limi... |
trace_regs!(self);
trace!(
self,
"CRTC Register Write (04h): VerticalTotal updated: {}",
self.reg[4]
)
},
CrtcRegister::VerticalTotalAdjust => {
// (R5) 5 bit write only
... | match self.reg_select {
CrtcRegister::HorizontalTotal => {
// (R0) 8 bit write only
self.reg[0] = byte;
},
CrtcRegister::HorizontalDisplayed => {
// (R1) 8 bit write only
self.reg[1] = byte;
}
... | identifier_body |
coeditor.rs | use druid::{Selector, WidgetPod, WidgetId, ExtEventSink, EventCtx, Event, Env, Widget, UpdateCtx, LayoutCtx, PaintCtx, BoxConstraints, Target, LifeCycle, LifeCycleCtx, Size};
use std::sync::Arc;
use tokio::sync::broadcast::{Sender};
use tokio::task::JoinHandle;
use parking_lot::RwLock;
use crate::{RustpadClient, Edit};... |
let data = message.unwrap().to_string();
println!("Received: {}", &data);
client2.write().handle_message(serde_json::from_slice(data.as_bytes()).expect("parse data failed"));
});
client.write().send_info();
client.write().send_cursor_data();
if let Some(outstan... | {
return;
} | conditional_block |
coeditor.rs | use druid::{Selector, WidgetPod, WidgetId, ExtEventSink, EventCtx, Event, Env, Widget, UpdateCtx, LayoutCtx, PaintCtx, BoxConstraints, Target, LifeCycle, LifeCycleCtx, Size};
use std::sync::Arc;
use tokio::sync::broadcast::{Sender};
use tokio::task::JoinHandle;
use parking_lot::RwLock;
use crate::{RustpadClient, Edit};... | use futures::StreamExt;
use log::{info, warn};
pub const COEDITOR_INIT_CLIENT: Selector<Arc<RwLock<RustpadClient>>> = Selector::new("coeditor-init-client");
pub const USER_EDIT_SELECTOR: Selector<Edit> = Selector::new("user-edit");
pub const USER_CURSOR_UPDATE_SELECTOR: Selector<()> = Selector::new("user-cursor-data")... | use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::connect_async; | random_line_split |
coeditor.rs | use druid::{Selector, WidgetPod, WidgetId, ExtEventSink, EventCtx, Event, Env, Widget, UpdateCtx, LayoutCtx, PaintCtx, BoxConstraints, Target, LifeCycle, LifeCycleCtx, Size};
use std::sync::Arc;
use tokio::sync::broadcast::{Sender};
use tokio::task::JoinHandle;
use parking_lot::RwLock;
use crate::{RustpadClient, Edit};... |
}
impl CoEditorWidget {
pub fn new(server_url: String) -> Self {
println!("CoEditorWidget created");
CoEditorWidget {
inner: WidgetPod::new(CodeEditor::<EditorBinding>::multiline()),
server_url,
id: WidgetId::next(),
client: None,
connect... | {
self.close_tx.send(()).unwrap();
futures::executor::block_on(
tokio::time::timeout(Duration::from_secs(5),
self.connection_handle.take().unwrap(),
)
);
println!("CoEditorWidget destructed");
} | identifier_body |
coeditor.rs | use druid::{Selector, WidgetPod, WidgetId, ExtEventSink, EventCtx, Event, Env, Widget, UpdateCtx, LayoutCtx, PaintCtx, BoxConstraints, Target, LifeCycle, LifeCycleCtx, Size};
use std::sync::Arc;
use tokio::sync::broadcast::{Sender};
use tokio::task::JoinHandle;
use parking_lot::RwLock;
use crate::{RustpadClient, Edit};... | (&mut self, ctx: &mut EventCtx, event: &Event, data: &mut EditorBinding, env: &Env) {
if let Event::Command(cmd) = event {
println!("received {:?}", cmd);
}
match event {
Event::Command(command) if command.get(COEDITOR_INIT_CLIENT).is_some()
&& command.tar... | event | identifier_name |
lib.rs | /*!
[](https://ci.appveyor.com/project/jaemk/self-update/branch/master)
[](https://travis-ci.org/jaemk/self_update)
[ -> Result<()> {
let source = fs::File::open(self.source)?;
let archive: Box<io::Read> = match self.encoding {
EncodingKind::Plain => Box::new(source),
EncodingKind::Gz => {
let reader = flate2::read::GzDecoder::new(source);
... | extract_into | identifier_name |
lib.rs | /*!
[](https://ci.appveyor.com/project/jaemk/self-update/branch/master)
[](https://travis-ci.org/jaemk/self_update)
[ -> bool {
match *self {
Status::Updated(_) => true,
_ => false,
}
}
}
impl std::fmt::Display for Status {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
use Status::*;
match *self {
UpToDate(ref s) =... | _ => false,
}
}
/// Returns `true` if `Status::Updated` | random_line_split |
lib.rs | /*!
[](https://ci.appveyor.com/project/jaemk/self-update/branch/master)
[](https://travis-ci.org/jaemk/self_update)
[)
}
}
/// Download things into files
///
/// With optional progress bar
#[derive(Debug)]
pub struct Download {
show_progress: bool,
url: String,
}
impl Download {
/// Specify download url
pub fn from_url(url: &str) -> Self {
Self {
show_progress: false,
... | {
match self.temp {
None => {
fs::rename(self.source, dest)?;
}
Some(temp) => {
if dest.exists() {
fs::rename(dest, temp)?;
match fs::rename(self.source, dest) {
Err(e) => {
... | identifier_body |
mod.rs | mod default_types;
mod jsont;
mod stats;
use crate::cache::Digest;
use crate::process::ShellCommand;
use anyhow::Result;
use once_cell::sync::Lazy;
use std::borrow::Cow;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::ops::Range;
use std::path::{Path, PathBuf};
use std::process::Command;
use utils::... | {
ShellCommand::new(RG_EXEC_CMD.into(), PathBuf::from(dir.as_ref()))
} | identifier_body | |
mod.rs | mod default_types;
mod jsont;
mod stats;
use crate::cache::Digest;
use crate::process::ShellCommand;
use anyhow::Result;
use once_cell::sync::Lazy;
use std::borrow::Cow;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::ops::Range;
use std::path::{Path, PathBuf};
use std::process::Command;
use utils::... | pub re: regex::Regex,
}
impl Word {
pub fn new(re_word: String, re: regex::Regex) -> Word {
Self {
len: re_word.len(),
raw: re_word,
re,
}
}
pub fn find(&self, line: &str) -> Option<usize> {
self.re.find(line).map(|mat| mat.start())
}
}
... | random_line_split | |
mod.rs | mod default_types;
mod jsont;
mod stats;
use crate::cache::Digest;
use crate::process::ShellCommand;
use anyhow::Result;
use once_cell::sync::Lazy;
use std::borrow::Cow;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::ops::Range;
use std::path::{Path, PathBuf};
use std::process::Command;
use utils::... |
}
}
impl Match {
/// Returns a pair of the formatted `String` and the offset of origin match indices.
///
/// The formatted String is same with the output line using rg's -vimgrep option.
fn grep_line_format(&self, enable_icon: bool) -> (String, usize) {
let path = self.path();
let... | {
Err("Not Message::Match type".into())
} | conditional_block |
mod.rs | mod default_types;
mod jsont;
mod stats;
use crate::cache::Digest;
use crate::process::ShellCommand;
use anyhow::Result;
use once_cell::sync::Lazy;
use std::borrow::Cow;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::ops::Range;
use std::path::{Path, PathBuf};
use std::process::Command;
use utils::... | (&self) -> dumb_analyzer::Priority {
self.path()
.rsplit_once('.')
.and_then(|(_, file_ext)| {
dumb_analyzer::calculate_pattern_priority(self.pattern(), file_ext)
})
.unwrap_or_default()
}
/// Returns a pair of the formatted `String` and the ... | pattern_priority | identifier_name |
tls_accept.rs | #![cfg(test)]
// These are basically integration tests for the `connection` submodule, but
// they cannot be "real" integration tests because `connection` isn't a public
// interface and because `connection` exposes a `#[cfg(test)]`-only API for use
// by these tests.
use linkerd2_error::Never;
use linkerd2_identity:... | },
Accepting(<AcceptTls<A, CrtKey> as Accept<<Listen as CoreListen>::Connection>>::Future),
Serving(<AcceptTls<A, CrtKey> as Accept<<Listen as CoreListen>::Connection>>::ConnectionFuture),
}
#[derive(Clone)]
struct Target(SocketAddr, Conditional<Name>);
#[derive(Clone)]
struct ClientTls(CrtKey);
impl<A: ... | AcceptTls<A, CrtKey>: Accept<<Listen as CoreListen>::Connection>,
{
Init {
listen: Listen,
accept: AcceptTls<A, CrtKey>, | random_line_split |
tls_accept.rs | #![cfg(test)]
// These are basically integration tests for the `connection` submodule, but
// they cannot be "real" integration tests because `connection` isn't a public
// interface and because `connection` exposes a `#[cfg(test)]`-only API for use
// by these tests.
use linkerd2_error::Never;
use linkerd2_identity:... |
}
/// Runs a test for a single TCP connection. `client` processes the connection
/// on the client side and `server` processes the connection on the server
/// side.
fn run_test<C, CF, CR, S, SF, SR>(
client_tls: tls::Conditional<(CrtKey, Name)>,
client: C,
server_tls: tls::Conditional<CrtKey>,
server... | {
self.peer_identity
.as_ref()
.map(|i| i.is_some())
.unwrap_or(false)
} | identifier_body |
tls_accept.rs | #![cfg(test)]
// These are basically integration tests for the `connection` submodule, but
// they cannot be "real" integration tests because `connection` isn't a public
// interface and because `connection` exposes a `#[cfg(test)]`-only API for use
// by these tests.
use linkerd2_error::Never;
use linkerd2_identity:... | (CrtKey);
impl<A: Accept<ServerConnection> + Clone> Future for Server<A> {
type Item = ();
type Error = ();
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
loop {
*self = match self {
Server::Init {
ref mut listen,
ref mut a... | ClientTls | identifier_name |
wasm_vm.rs | use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::PathBuf;
use std::process;
use std::str::FromStr;
use std::sync::{mpsc::Sender, Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};
use zellij_utils::{serde, zellij_tile};
use serde::{de::DeserializeOwned, Serialize};
use wasmer::{
... |
PluginInstruction::Render(buf_tx, pid, rows, cols) => {
let (instance, plugin_env) = plugin_map.get(&pid).unwrap();
let render = instance.exports.get_function("render").unwrap();
render
.call(&[Value::I32(rows as i32), Value::I32(cols as ... | {
for (&i, (instance, plugin_env)) in &plugin_map {
let subs = plugin_env.subscriptions.lock().unwrap();
// FIXME: This is very janky... Maybe I should write my own macro for Event -> EventType?
let event_type = EventType::from_str(&event.to_st... | conditional_block |
wasm_vm.rs | use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::PathBuf;
use std::process;
use std::str::FromStr;
use std::sync::{mpsc::Sender, Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};
use zellij_utils::{serde, zellij_tile};
use serde::{de::DeserializeOwned, Serialize};
use wasmer::{
... | {
Load(Sender<u32>, PathBuf),
Update(Option<u32>, Event), // Focused plugin / broadcast, event data
Render(Sender<String>, u32, usize, usize), // String buffer, plugin id, rows, cols
Unload(u32),
Exit,
}
impl From<&PluginInstruction> for PluginContext {
fn from(plugin_instruction: &PluginInstr... | PluginInstruction | identifier_name |
wasm_vm.rs | use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::PathBuf;
use std::process;
use std::str::FromStr;
use std::sync::{mpsc::Sender, Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};
use zellij_utils::{serde, zellij_tile};
use serde::{de::DeserializeOwned, Serialize};
use wasmer::{
... |
fn host_open_file(plugin_env: &PluginEnv) {
let path: PathBuf = wasi_read_object(&plugin_env.wasi_env);
plugin_env
.senders
.send_to_pty(PtyInstruction::SpawnTerminal(Some(path)))
.unwrap();
}
fn host_set_timeout(plugin_env: &PluginEnv, secs: f64) {
// There is a fancy, high-performa... | {
let ids = PluginIds {
plugin_id: plugin_env.plugin_id,
zellij_pid: process::id(),
};
wasi_write_object(&plugin_env.wasi_env, &ids);
} | identifier_body |
wasm_vm.rs | use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::PathBuf;
use std::process;
use std::str::FromStr;
use std::sync::{mpsc::Sender, Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};
use zellij_utils::{serde, zellij_tile};
use serde::{de::DeserializeOwned, Serialize};
use wasmer::{
... | }
PluginInstruction::Unload(pid) => drop(plugin_map.remove(&pid)),
PluginInstruction::Exit => break,
}
}
}
// Plugin API ---------------------------------------------------------------------------------------------------------
pub(crate) fn zellij_exports(store: &Store,... | buf_tx.send(wasi_read_string(&plugin_env.wasi_env)).unwrap(); | random_line_split |
state.rs | use std::any::type_name;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use cosmwasm_std::{Api, CanonicalAddr, ReadonlyStorage, StdError, StdResult, Storage};
use cosmwasm_storage::{PrefixedStorage, ReadonlyPrefixedStorage};
use secret_toolkit::{
serialization::{Bincode2, Serde},
storage::{Appen... | (self, versions: &[ContractInfo]) -> StdResult<Hero> {
let hero = Hero {
name: self.name,
token_info: TokenInfo {
token_id: self.token_info.token_id,
address: versions[self.token_info.version as usize].address.clone(),
},
pre_battle... | into_humanized | identifier_name |
state.rs | use std::any::type_name;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use cosmwasm_std::{Api, CanonicalAddr, ReadonlyStorage, StdError, StdResult, Storage};
use cosmwasm_storage::{PrefixedStorage, ReadonlyPrefixedStorage};
use secret_toolkit::{
serialization::{Bincode2, Serde},
storage::{Appen... | /// * `api` - a reference to the Api used to convert human and canonical addresses
/// * `storage` - a reference to the contract's storage
/// * `address` - a reference to the address whose battles to display
/// * `page` - page to start displaying
/// * `page_size` - number of txs per page
pub fn get_history<A: Api, S... | /// Returns StdResult<Vec<Battle>> of the battles to display
///
/// # Arguments
/// | random_line_split |
state.rs | use std::any::type_name;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use cosmwasm_std::{Api, CanonicalAddr, ReadonlyStorage, StdError, StdResult, Storage};
use cosmwasm_storage::{PrefixedStorage, ReadonlyPrefixedStorage};
use secret_toolkit::{
serialization::{Bincode2, Serde},
storage::{Appen... |
}
/// code hash and address of a contract
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct StoreContractInfo {
/// contract's code hash string
pub code_hash: String,
/// contract's address
pub address: CanonicalAddr,
}
impl StoreContractInfo {
/// Returns StdResult<ContractInfo> from co... | {
let battle = BattleDump {
battle_number: self.battle_number,
timestamp: self.timestamp,
heroes: self
.heroes
.drain(..)
.map(|h| h.into_dump(api, versions))
.collect::<StdResult<Vec<HeroDump>>>()?,
... | identifier_body |
state.rs | use std::any::type_name;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use cosmwasm_std::{Api, CanonicalAddr, ReadonlyStorage, StdError, StdResult, Storage};
use cosmwasm_storage::{PrefixedStorage, ReadonlyPrefixedStorage};
use secret_toolkit::{
serialization::{Bincode2, Serde},
storage::{Appen... | else {
return Ok(vec![]);
};
let config: Config = load(storage, CONFIG_KEY)?;
let versions = config
.card_versions
.iter()
.map(|v| v.to_humanized(api))
.collect::<StdResult<Vec<ContractInfo>>>()?;
// access battle storage
let his_store = ReadonlyPrefixedStorage:... | {
result?
} | conditional_block |
testingfrog.rs | #![allow(dead_code)]
#![allow(unused_variables)]
#![allow(unreachable_code)]
#![allow(unused_imports)]
#![allow(clippy::all)]
//****************************************
// tracing test
//****************************************
// use axum::{routing::get, Router};
// use std::error::Error;
//
// use tracing_subscriber... | // loop {
// match prev {
// Some(v) => match self.rx.recv_timeout(self.d) {
// Ok(newval) => {
// prev = Some(newval);
// continue;
// }
// Err(_) => break Ok(v),
// ... | //
// impl<T> Debounced<T> {
// fn recv(&self) -> Result<T, mpsc::RecvError> {
// let mut prev = None;
// | random_line_split |
testingfrog.rs | #![allow(dead_code)]
#![allow(unused_variables)]
#![allow(unreachable_code)]
#![allow(unused_imports)]
#![allow(clippy::all)]
//****************************************
// tracing test
//****************************************
// use axum::{routing::get, Router};
// use std::error::Error;
//
// use tracing_subscriber... |
fn post_header(input: &str) -> IResult<&str, (&str, Vec<&str>, PostStatus)> {
delimited(
pair(tag("---"), newline),
tuple((post_title, post_tags, post_status)),
pair(tag("---"), newline),
)(input)
}
impl<'a> Post<'a> {
fn from_str(input: &'a str) -> Result<Post<'a>, Box<dyn Error>... | {
delimited(
tag("status:"),
delimited(
space1,
alt((
map(tag("published"), |_| PostStatus::Published),
map(tag("draft"), |_| PostStatus::Draft),
)),
space0,
),
newline,
)(input)
} | identifier_body |
testingfrog.rs | #![allow(dead_code)]
#![allow(unused_variables)]
#![allow(unreachable_code)]
#![allow(unused_imports)]
#![allow(clippy::all)]
//****************************************
// tracing test
//****************************************
// use axum::{routing::get, Router};
// use std::error::Error;
//
// use tracing_subscriber... | (input: &str) -> IResult<&str, PostStatus> {
delimited(
tag("status:"),
delimited(
space1,
alt((
map(tag("published"), |_| PostStatus::Published),
map(tag("draft"), |_| PostStatus::Draft),
)),
space0,
),
... | post_status | identifier_name |
sync.rs | //! This module supports synchronizing a UPM database with a copy on a remote repository. The
//! remote repository should be an HTTP or HTTPS server supporting the "download", "upload", and
//! "delete" primitives of the UPM sync protocol.
use reqwest::multipart;
use std::io::Read;
use std::path::{Path, PathBuf};
us... | self.check_response(&mut response)?;
Ok(())
}
/// Upload the provided database to the remote repository. The database is provided in raw
/// form as a byte buffer.
fn upload(&mut self, database_name: &str, database_bytes: Vec<u8>) -> Result<(), UpmError> {
let url: String = sel... | // Process response | random_line_split |
sync.rs | //! This module supports synchronizing a UPM database with a copy on a remote repository. The
//! remote repository should be an HTTP or HTTPS server supporting the "download", "upload", and
//! "delete" primitives of the UPM sync protocol.
use reqwest::multipart;
use std::io::Read;
use std::path::{Path, PathBuf};
us... | (&self, response: &mut reqwest::Response) -> Result<(), UpmError> {
if!response.status().is_success() {
return Err(UpmError::Sync(format!("{}", response.status())));
}
let mut response_code = String::new();
response.read_to_string(&mut response_code)?;
if response_cod... | check_response | identifier_name |
sync.rs | //! This module supports synchronizing a UPM database with a copy on a remote repository. The
//! remote repository should be an HTTP or HTTPS server supporting the "download", "upload", and
//! "delete" primitives of the UPM sync protocol.
use reqwest::multipart;
use std::io::Read;
use std::path::{Path, PathBuf};
us... |
let local_password = match database.password() {
Some(p) => p,
None => return Err(UpmError::NoDatabasePassword),
};
let remote_password = match remote_password {
Some(p) => p,
None => local_password,
};
// 1. Download the remote database.
// If the remote databa... | {
// Collect all the facts.
if database.sync_url.is_empty() {
return Err(UpmError::NoSyncURL);
}
if database.sync_credentials.is_empty() {
return Err(UpmError::NoSyncCredentials);
}
let sync_account = match database.account(&database.sync_credentials) {
Some(a) => a,
... | identifier_body |
model.rs |
false => None,
}
}
}
#[allow(dead_code)]
pub struct DxModel {
// Window
aspect_ratio: f32,
// D3D12 Targets
device: ComRc<ID3D12Device>,
command_queue: ComRc<ID3D12CommandQueue>,
swap_chain: ComRc<IDXGISwapChain3>,
dc_dev: ComRc<IDCompositionDevice>,
dc_target:... | {
let rc = self.item[self.index];
self.index += 1;
Some(rc)
} | conditional_block | |
model.rs | (window: &Window) -> Result<DxModel, HRESULT> {
// window params
let size = window.inner_size();
println!("inner_size={:?}", size);
let hwnd = window.raw_window_handle();
let aspect_ratio = (size.width as f32) / (size.height as f32);
let viewport = D3D12_VIEWPORT {
... | new | identifier_name | |
model.rs | file(file, None, None, "PSMain", "ps_5_0", flags, 0)?;
// Define the vertex input layout.
let input_element_descs = {
let a = D3D12_INPUT_ELEMENT_DESC::new(
*t::POSITION,
0,
DXGI_FORMAT_R32G32B32_FLOAT,
... | _heap.as_ref();
let rtv_descriptor_size = self.rtv_descriptor_size;
let viewport = &self.viewport;
let scissor_rect = &self.scissor_rect;
let render_targets = self.render_targets.as_slice();
let frame_index = self.frame_index as usize;
let vertex_buffer_view = &self.verte... | identifier_body | |
model.rs | desc.RasterizerState = D3D12_RASTERIZER_DESC::default();
desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;
desc.BlendState = alpha_blend;
desc.DepthStencilState.DepthEnable = FALSE;
desc.DepthStencilState.StencilEnable = FALSE;
de... | Ok(())
}
}
// WAITING FOR THE FRAME TO COMPLETE BEFORE CONTINUING IS NOT BEST PRACTICE. | random_line_split | |
lib.rs | //! Configures and runs the outbound proxy.
//!
//! The outound proxy is responsible for routing traffic from the local
//! application to external network endpoints.
#![deny(warnings, rust_2018_idioms)]
use linkerd2_app_core::{
classify,
config::Config,
dns, drain,
dst::DstAddr,
errors, http_requ... | <A, R, P>(
config: &Config,
local_identity: tls::Conditional<identity::Local>,
listen: transport::Listen<A>,
resolve: R,
dns_resolver: dns::Resolver,
profiles_client: linkerd2_app_core::profiles::Client<P>,
tap_layer: linkerd2_app_core::tap::Layer,
handle_time: http_metrics::handle_time:... | spawn | identifier_name |
lib.rs | //! Configures and runs the outbound proxy.
//!
//! The outound proxy is responsible for routing traffic from the local
//! application to external network endpoints.
#![deny(warnings, rust_2018_idioms)]
use linkerd2_app_core::{
classify,
config::Config,
dns, drain,
dst::DstAddr,
errors, http_requ... |
}
impl transport::metrics::TransportLabels<proxy::server::Protocol> for TransportLabels {
type Labels = transport::labels::Key;
fn transport_labels(&self, proto: &proxy::server::Protocol) -> Self::Labels {
transport::labels::Key::accept("outbound", proto.tls.peer_identity.as_ref())
}
}
| {
transport::labels::Key::connect("outbound", endpoint.identity.as_ref())
} | identifier_body |
lib.rs | //! Configures and runs the outbound proxy.
//!
//! The outound proxy is responsible for routing traffic from the local
//! application to external network endpoints.
#![deny(warnings, rust_2018_idioms)]
use linkerd2_app_core::{
classify,
config::Config,
dns, drain,
dst::DstAddr,
errors, http_requ... | //
// This is shared across addr-stacks so that multiple addrs that
// canonicalize to the same DstAddr use the same dst-stack service.
let dst_router = dst_stack
.push(trace::layer(
|dst: &DstAddr| info_span!("logical", dst.logical = %dst.dst_logical()),
))
.push_buffe... |
// Routes request using the `DstAddr` extension. | random_line_split |
lib.rs | use reqwest::Client;
use serde::{Deserialize, Serialize};
pub use url::Url;
/// Data types to interract with the folder API. Check [FolderApi](folder::FolderApi) for the
/// available actions. You can also check the [HTTP
/// API](https://git.mdns.eu/nextcloud/passwords/wikis/Developers/Api/Folder-Api)
pub mod folder;... | {
status: String,
id: u64,
message: String,
}
#[derive(Serialize, Deserialize)]
#[serde(untagged)]
pub enum EndpointResponse<T> {
Error(EndpointError),
Success(T),
}
/// Represent how to first connect to a nextcloud instance
/// The best way to obtain some is using [Login flow
/// v2](https://doc... | EndpointError | identifier_name |
lib.rs | use reqwest::Client;
use serde::{Deserialize, Serialize};
pub use url::Url;
/// Data types to interract with the folder API. Check [FolderApi](folder::FolderApi) for the
/// available actions. You can also check the [HTTP
/// API](https://git.mdns.eu/nextcloud/passwords/wikis/Developers/Api/Folder-Api)
pub mod folder;... | /// Disconnect from the session
pub async fn disconnect(self) -> Result<(), Error> {
#[derive(Deserialize)]
struct CloseSession {
success: bool,
}
let s: CloseSession = self.passwords_get("1.0/session/close", ()).await.unwrap();
if!s.success {
Err... |
Ok((api, session_id))
}
| random_line_split |
main.rs | use shared::{
grid::{self as sg, Grid, GridTile, Coordinate},
input::read_stdin_lines
};
use lazy_static::*;
use regex::Regex;
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
enum Tile {
Clay, Sand, Spring, Water, WaterAtRest
}
struct Map {
data: Vec<Vec<Tile>>,
xstart: usize
}
im... |
fn flow_down(&mut self, y: usize, x: usize) -> (usize, usize) {
for yf in y+1.. self.data.len() {
if self.data[yf][x] == Tile::Sand {
self.data[yf][x] = Tile::Water;
} else if self.data[yf][x]!= Tile::Water {
return (yf - 1, x);
}
... | {
data[0][500 - xstart + 2] = Tile::Spring;
Map {
data,
xstart
}
} | identifier_body |
main.rs | use shared::{
grid::{self as sg, Grid, GridTile, Coordinate},
input::read_stdin_lines
};
use lazy_static::*;
use regex::Regex;
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
enum Tile {
Clay, Sand, Spring, Water, WaterAtRest
}
struct Map {
data: Vec<Vec<Tile>>,
xstart: usize
}
im... | (&self, c: &Self::Coord) -> &Self::Tile {
&self.data[c.y()][c.x()]
}
}
impl sg::GridTile for Tile {
fn to_char(&self) -> char {
match self {
Tile::Clay => '#',
Tile::Sand => '.',
Tile::Spring => '+',
Tile::Water => '|',
Tile::WaterAtRe... | tile_at | identifier_name |
main.rs | use shared::{
grid::{self as sg, Grid, GridTile, Coordinate},
input::read_stdin_lines
};
use lazy_static::*;
use regex::Regex;
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
enum Tile {
Clay, Sand, Spring, Water, WaterAtRest
}
struct Map {
data: Vec<Vec<Tile>>,
xstart: usize
}
im... | let (mut enclosed_left, mut enclosed_right) = (None, None);
for xf in (0..x).rev() {
if self.data[y][xf] == Tile::Clay
|| self.data[y + 1][xf] == Tile::Sand
{
enclosed_left = Some(xf + 1);
break;
}
}
fo... | random_line_split | |
lib.rs | Error::AccountBorrowFailed,
ProgramError::MaxSeedLengthExceeded => InstructionError::MaxSeedLengthExceeded,
ProgramError::InvalidSeeds => InstructionError::InvalidSeeds,
}
}
thread_local! {
static INVOKE_CONTEXT:RefCell<Rc<MockInvokeContext>> = RefCell::new(Rc::new(MockInvokeContext::default())... | (other_invoke_context: &RefCell<Rc<MockInvokeContext>>) {
INVOKE_CONTEXT.with(|invoke_context| {
invoke_context.swap(&other_invoke_context);
});
}
struct SyscallStubs {}
impl program_stubs::SyscallStubs for SyscallStubs {
fn sol_log(&self, message: &str) {
INVOKE_CONTEXT.with(|invoke_contex... | swap_invoke_context | identifier_name |
lib.rs | Error::AccountBorrowFailed,
ProgramError::MaxSeedLengthExceeded => InstructionError::MaxSeedLengthExceeded,
ProgramError::InvalidSeeds => InstructionError::InvalidSeeds,
}
}
thread_local! {
static INVOKE_CONTEXT:RefCell<Rc<MockInvokeContext>> = RefCell::new(Rc::new(MockInvokeContext::default())... |
/// Override default BPF program selection
pub fn prefer_bpf(&mut self, prefer_bpf: bool) {
self.prefer_bpf = prefer_bpf;
}
/// Override the BPF compute budget
pub fn set_bpf_compute_max_units(&mut self, bpf_compute_max_units: u64) {
self.bpf_compute_max_units = Some(bpf_compute_m... | {
let mut me = Self::default();
me.add_program(program_name, program_id, process_instruction);
me
} | identifier_body |
lib.rs | InstructionError::AccountBorrowFailed,
ProgramError::MaxSeedLengthExceeded => InstructionError::MaxSeedLengthExceeded,
ProgramError::InvalidSeeds => InstructionError::InvalidSeeds,
}
}
thread_local! {
static INVOKE_CONTEXT:RefCell<Rc<MockInvokeContext>> = RefCell::new(Rc::new(MockInvokeContext... | if (program_file.is_some() && self.prefer_bpf) || process_instruction.is_none() {
let program_file = program_file.unwrap_or_else(|| {
panic!(
"Program file data not available for {} ({})",
program_name, program_id
);
... | }
| random_line_split |
utils.rs | // Copyright (c) 2011 Jan Kokemüller
// Copyright (c) 2020 Sebastian Dröge <sebastian@centricular.com>
//
// 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 wit... | self.data.len()
}
#[inline]
fn split_at(self, sample: usize) -> (Self, Self) {
assert!(self.start + sample <= self.end);
(
Planar {
data: self.data,
start: self.start,
end: self.start + sample,
},
P... | fn channels(&self) -> usize { | random_line_split |
utils.rs | // Copyright (c) 2011 Jan Kokemüller
// Copyright (c) 2020 Sebastian Dröge <sebastian@centricular.com>
//
// 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 wit... | mut self) -> Option<Signal<A>> {
if self.size < self.seed.data.len() {
// Generate a smaller vector by removing size elements
let xs1 = if self.tried_one_channel {
Vec::from(&self.seed.data[..self.size])
} else {
self.se... | xt(& | identifier_name |
utils.rs | // Copyright (c) 2011 Jan Kokemüller
// Copyright (c) 2020 Sebastian Dröge <sebastian@centricular.com>
//
// 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 wit... |
impl AsF32 for f64 {
#[inline]
fn as_f32_scaled(self) -> f32 {
self as f32
}
}
/// Trait for converting samples into f64 in the range [0,1].
pub trait AsF64: AsF32 + Copy + PartialOrd {
const MAX: f64;
fn as_f64(self) -> f64;
#[inline]
fn as_f64_scaled(self) -> f64 {
sel... | self
}
} | identifier_body |
utils.rs | // Copyright (c) 2011 Jan Kokemüller
// Copyright (c) 2020 Sebastian Dröge <sebastian@centricular.com>
//
// 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 wit... | lse {
1
};
} else {
self.size *= 2;
}
Some(Signal {
data: xs1,
channels: if self.tried_one_channel {
self.seed.channels
} e... | self.seed.channels as usize
} e | conditional_block |
router.rs | use anyhow::{bail, Result};
use indexmap::indexmap;
use serde::Deserialize;
use serde_json::json;
use turbo_tasks::{
primitives::{JsonValueVc, StringsVc},
CompletionVc, CompletionsVc, Value,
};
use turbo_tasks_fs::{
json::parse_json_rope_with_source_context, to_sys_path, File, FileSystemPathVc,
};
use turbo... | (
execution_context: ExecutionContextVc,
request: RouterRequestVc,
next_config: NextConfigVc,
server_addr: ServerAddrVc,
routes_changed: CompletionVc,
) -> Result<RouterResultVc> {
let ExecutionContext {
project_path,
chunking_context,
env,
} = *execution_context.awai... | route_internal | identifier_name |
router.rs | use anyhow::{bail, Result};
use indexmap::indexmap;
use serde::Deserialize;
use serde_json::json;
use turbo_tasks::{
primitives::{JsonValueVc, StringsVc},
CompletionVc, CompletionsVc, Value,
};
use turbo_tasks_fs::{
json::parse_json_rope_with_source_context, to_sys_path, File, FileSystemPathVc,
};
use turbo... | AssetIdentVc::from_path(project_path),
context,
chunking_context.with_layer("router"),
None,
vec![
JsonValueVc::cell(request),
JsonValueVc::cell(dir.to_string_lossy().into()),
],
CompletionsVc::all(vec![next_config_changed, routes_changed])... | };
let result = evaluate(
router_asset,
project_path,
env, | random_line_split |
minimize.rs | : bool) -> Self {
Self {
delta,
allow_nondet,
}
}
pub fn with_delta(self, delta: f32) -> Self {
Self { delta,..self }
}
pub fn with_allow_nondet(self, allow_nondet: bool) -> Self {
Self {
allow_nondet,
..self
}
... | W: WeaklyDivisibleSemiring + WeightQuantize,
W::ReverseWeight: WeightQuantize,
{
let delta = config.delta;
let allow_nondet = config.allow_nondet;
let props = ifst.compute_and_update_properties(
FstProperties::ACCEPTOR
| FstProperties::I_DETERMINISTIC
| FstProperties... | /// and also non-deterministic ones if they use an idempotent semiring.
/// For transducers, the algorithm produces a compact factorization of the minimal transducer.
pub fn minimize_with_config<W, F>(ifst: &mut F, config: MinimizeConfig) -> Result<()>
where
F: MutableFst<W> + ExpandedFst<W> + AllocableFst<W>, | random_line_split |
minimize.rs | bool) -> Self {
Self {
delta,
allow_nondet,
}
}
pub fn with_delta(self, delta: f32) -> Self {
Self { delta,..self }
}
pub fn with_allow_nondet(self, allow_nondet: bool) -> Self {
Self {
allow_nondet,
..self
}
}... | <W: Semiring, F: MutableFst<W> + ExpandedFst<W>>(
ifst: &mut F,
allow_acyclic_minimization: bool,
) -> Result<()> {
let props = ifst.compute_and_update_properties(
FstProperties::ACCEPTOR | FstProperties::UNWEIGHTED | FstProperties::ACYCLIC,
)?;
if!props.contains(FstProperties::ACCEPTOR | Fs... | acceptor_minimize | identifier_name |
minimize.rs | bool) -> Self {
Self {
delta,
allow_nondet,
}
}
pub fn with_delta(self, delta: f32) -> Self {
Self { delta,..self }
}
pub fn with_allow_nondet(self, allow_nondet: bool) -> Self {
Self {
allow_nondet,
..self
}
}... | else {
if!W::properties().contains(SemiringProperties::IDEMPOTENT) {
bail!("Cannot minimize a non-deterministic FST over a non-idempotent semiring")
} else if!allow_nondet {
bail!("Refusing to minimize a non-deterministic FST with allow_nondet = false")
}
false
... | {
true
} | conditional_block |
diag.rs | // Diagnostics engine
use super::{Span, SrcMgr};
use std::cell::RefCell;
use std::cmp;
use std::fmt;
use std::rc::Rc;
use colored::{Color, Colorize};
/// Severity of the diagnostic message.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Severity {
Remark,
Info,
Warning,
Error,
Fatal,
}
im... |
/// Clear exsting diagnostics
pub fn clear(&self) {
let mut m = self.mutable.borrow_mut();
m.diagnostics.clear();
}
/// Check if there is any fatal error.
pub fn has_fatal(&self) -> bool {
let m = self.mutable.borrow();
m.diagnostics
.iter()
.... | {
self.report(Diagnostic::new(Severity::Fatal, msg.into(), span));
std::panic::panic_any(Severity::Fatal);
} | identifier_body |
diag.rs | // Diagnostics engine
use super::{Span, SrcMgr};
use std::cell::RefCell;
use std::cmp;
use std::fmt;
use std::rc::Rc;
use colored::{Color, Colorize};
/// Severity of the diagnostic message.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Severity {
Remark,
Info,
Warning,
Error,
Fatal,
}
im... | }
}
// Reserve a column for end-of-line character
columns.push(vlen + 1);
VisualString {
str: vstr,
columns: columns,
}
}
fn visual_column(&self, pos: usize) -> usize {
self.columns[pos]
}
fn visual_length(&self) -> ... | }
for _ in 0..ch.len_utf8() {
columns.push(vlen); | random_line_split |
diag.rs | // Diagnostics engine
use super::{Span, SrcMgr};
use std::cell::RefCell;
use std::cmp;
use std::fmt;
use std::rc::Rc;
use colored::{Color, Colorize};
/// Severity of the diagnostic message.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Severity {
Remark,
Info,
Warning,
Error,
Fatal,
}
im... | (&self, diag: Diagnostic) {
let mut m = self.mutable.borrow_mut();
diag.print(&m.src, true, 4);
m.diagnostics.push(diag);
}
/// Create a errpr diagnostic from message and span and report it.
pub fn report_span<M: Into<String>>(&self, severity: Severity, msg: M, span: Span) {
... | report | identifier_name |
lib.rs | // Copyright 2016 The android_logger Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except a... |
/// Set multiple allowed module paths.
///
/// Same as `with_allowed_module_path`, but accepts list of paths.
///
/// ## Example:
///
/// ```
/// use android_logger::Filter;
///
/// let filter = Filter::default()
/// .with_allowed_module_paths(["A", "B"].iter().map(|i| i... | {
self.allow_module_paths.push(path.into());
self
} | identifier_body |
lib.rs | // Copyright 2016 The android_logger Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except a... | (_priority: Level, _tag: &CStr, _msg: &CStr) {}
/// Underlying android logger backend
pub struct AndroidLogger {
filter: RwLock<Filter>,
}
lazy_static! {
static ref ANDROID_LOGGER: AndroidLogger = AndroidLogger::default();
}
const LOGGING_TAG_MAX_LEN: usize = 23;
const LOGGING_MSG_MAX_LEN: usize = 4000;
impl... | android_log | identifier_name |
lib.rs | // Copyright 2016 The android_logger Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except a... | }
/// Copy `len` bytes from `index` position to starting position.
fn copy_bytes_to_start(&mut self, index: usize, len: usize) {
let src = unsafe { self.buffer.as_ptr().offset(index as isize) };
let dst = self.buffer.as_mut_ptr();
unsafe { ptr::copy(src, dst, len) };
}
}
impl<'... | *unsafe { self.buffer.get_unchecked_mut(len) } = last_byte; | random_line_split |
lib.rs | // Copyright 2016 The android_logger Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except a... |
});
// update last \n index
if let Some(newline) = last_newline {
self.last_newline_index = len + newline;
}
// calculate how many bytes were written
let written_len = if new_len <= LOGGING_MSG_MAX_LEN {
// if... | {
acc
} | conditional_block |
tags.rs | use crate::{ResponseValue, ViewWrap};
use std::fmt::Debug;
use htmldom_read::{Node};
use crate::events::OnClick;
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};
use std::fmt::Formatter;
use std::sync::Arc;
/// The functions that allow to load images concurrently.
pub mod image_loader {
use std::sync... |
pub fn set_href<T: AsRef<str>>(&mut self, href: T) {
self.set_attribute("href", href.as_ref())
}
pub fn onclick(&self) -> &OnClick<A> {
&self.onclick
}
pub fn onclick_mut(&mut self) -> &mut OnClick<A> {
&mut self.onclick
}
}
impl ImageContent for Img {
fn set_im... | {
if let Some(s) = self.attribute("href") {
s
} else {
String::new()
}
} | identifier_body |
tags.rs | use crate::{ResponseValue, ViewWrap};
use std::fmt::Debug;
use htmldom_read::{Node};
use crate::events::OnClick;
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};
use std::fmt::Formatter;
use std::sync::Arc;
/// The functions that allow to load images concurrently.
pub mod image_loader {
use std::sync... |
Unknown(String)
}
/// Supported canvas image formats.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ImageFormat {
Png,
Jpg,
}
/// Element in the HTML DOM that can be accessed by Rust interface.
pub trait Element: Debug {
/// Tag name of the element.
fn tag_name(&self) -> TagName;
//... | random_line_split | |
tags.rs | use crate::{ResponseValue, ViewWrap};
use std::fmt::Debug;
use htmldom_read::{Node};
use crate::events::OnClick;
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};
use std::fmt::Formatter;
use std::sync::Arc;
/// The functions that allow to load images concurrently.
pub mod image_loader {
use std::sync... | (node: &Node) -> Option<Self> {
let tag_name = node.tag_name();
if let Some(tag_name) = tag_name {
let tag_name = TagName::from(tag_name);
Some(tag_name)
} else {
None
}
}
/// Try creating implementation of the Element from this node.
///
... | try_from_node | identifier_name |
destination.rs | use super::pandas_columns::{
BooleanBlock, BytesBlock, DateTimeBlock, Float64Block, HasPandasColumn, Int64Block,
PandasColumn, PandasColumnObject, StringBlock,
};
use super::types::{PandasDType, PandasTypeSystem};
use anyhow::anyhow;
use connectorx::{
ConnectorAgentError, Consume, DataOrder, Destination, De... |
let code = format!(
r#"import pandas as pd
import numpy as np
blocks = [{}]
block_manager = pd.core.internals.BlockManager(
blocks, [pd.Index(['{}']), pd.RangeIndex(start=0, stop={}, step=1)])
df = pd.DataFrame(block_manager)
blocks = [b.values for b in df._mgr.blocks]
index = [(i, j) for i, j in zip(d... | // blknos[i] identifies the block from self.blocks that contains this column.
// blklocs[i] identifies the column of interest within
// self.blocks[self.blknos[i]] | random_line_split |
destination.rs | use super::pandas_columns::{
BooleanBlock, BytesBlock, DateTimeBlock, Float64Block, HasPandasColumn, Int64Block,
PandasColumn, PandasColumnObject, StringBlock,
};
use super::types::{PandasDType, PandasTypeSystem};
use anyhow::anyhow;
use connectorx::{
ConnectorAgentError, Consume, DataOrder, Destination, De... | (&self) -> &[PandasTypeSystem] {
static EMPTY_SCHEMA: Vec<PandasTypeSystem> = vec![];
self.schema.as_ref().unwrap_or(EMPTY_SCHEMA.as_ref())
}
}
pub struct PandasPartitionDestination<'a> {
nrows: usize,
columns: Vec<Box<dyn PandasColumnObject + 'a>>,
schema: &'a [PandasTypeSystem],
s... | schema | identifier_name |
destination.rs | use super::pandas_columns::{
BooleanBlock, BytesBlock, DateTimeBlock, Float64Block, HasPandasColumn, Int64Block,
PandasColumn, PandasColumnObject, StringBlock,
};
use super::types::{PandasDType, PandasTypeSystem};
use anyhow::anyhow;
use connectorx::{
ConnectorAgentError, Consume, DataOrder, Destination, De... |
}
pub struct PandasPartitionDestination<'a> {
nrows: usize,
columns: Vec<Box<dyn PandasColumnObject + 'a>>,
schema: &'a [PandasTypeSystem],
seq: usize,
}
impl<'a> PandasPartitionDestination<'a> {
fn new(
nrows: usize,
columns: Vec<Box<dyn PandasColumnObject + 'a>>,
schema:... | {
static EMPTY_SCHEMA: Vec<PandasTypeSystem> = vec![];
self.schema.as_ref().unwrap_or(EMPTY_SCHEMA.as_ref())
} | identifier_body |
main.rs | //! CSIS-616 - Program #3
//!
//! Some parts were originally made by: Ralph W. Crosby PhD.
//! Edited and added to by: Paige Peck
//!
//!
//! Process a yaml format deterministic finite automaton producing
//! - A textual representation of the internal state graph
//! - A Graphviz `.dot` file representing the graph
/... |
let stdin = io::stdin();
for line in stdin.lock().lines() {
// Get the line out of the Result, should never error
let sentence = &line.unwrap();
println!("Processing sentence <{}>", sentence);
match self.test_sentence(sentence) {
Ok(b) => println!("{}",
... | self) { | identifier_name |
main.rs | //! CSIS-616 - Program #3
//!
//! Some parts were originally made by: Ralph W. Crosby PhD.
//! Edited and added to by: Paige Peck
//!
//!
//! Process a yaml format deterministic finite automaton producing
//! - A textual representation of the internal state graph
//! - A Graphviz `.dot` file representing the graph
/... | //At the end, add 2 to current state to get back, and set previous_char as *
else if c == '*' {
dfa.transitions.remove(dfa.transitions.len()-1);
let mut pushed_forward = false;
next_state -= 2;
current_state -= 2;
for a in dfa.alphabet.iter() {
if a == &previous_char {
next_state ... | // Potential fix is similar to + operator with iterating over transitions instead of just checking index 0. | random_line_split |
main.rs | //! CSIS-616 - Program #3
//!
//! Some parts were originally made by: Ralph W. Crosby PhD.
//! Edited and added to by: Paige Peck
//!
//!
//! Process a yaml format deterministic finite automaton producing
//! - A textual representation of the internal state graph
//! - A Graphviz `.dot` file representing the graph
/... |
// *********************************************************************
/// Return the RegEx passed as the first parameter
fn get_regex(args: std::env::Args) -> String {
// Get the arguments as a vector
let args: Vec<String> = args.collect();
// Make sure only one argument was passed
if args.len()!... | {
//Get and validate the RegEx on the command line
let regex = get_regex(std::env::args());
let dfa = DFA::new_from_regex(®ex);
//Create the dfa structure based on in RegEx entered from the command line
let state_graph = StateGraph::new_from_dfa(&dfa);
//eprintln!("{:?}", state_graph);
state_graph.... | identifier_body |
i2c.rs | //! I2C Peripheral
use crate::common::{ Register, Frequency, I2CInterrupt, I2CFlags, I2CBitMode, MasterMode, DutyCycle, DualAddress };
use crate::common::enums::RCCPeripheral;
use crate::common::structs::pins::Pin;
use embedded_hal::blocking::i2c::{ Read, Write, WriteRead };
use crate::peripherals::extended::{ gpio:... | (&mut self, a: I2CBitMode) -> &mut Self {
match a {
I2CBitMode::Bit7 => self.clear(2, 15),
_ => self.set(2, 15),
}
}
/// Writes the interface address 1
/// To be set **after** the interface bit size is set (7-bit or 10-bit)
pub fn set_address_1(&mut self, addr: u32) -> &mut Self {
match self.is_set(2, ... | address_mode | identifier_name |
i2c.rs | //! I2C Peripheral
use crate::common::{ Register, Frequency, I2CInterrupt, I2CFlags, I2CBitMode, MasterMode, DutyCycle, DualAddress };
use crate::common::enums::RCCPeripheral;
use crate::common::structs::pins::Pin;
use embedded_hal::blocking::i2c::{ Read, Write, WriteRead };
use crate::peripherals::extended::{ gpio:... |
/// Clear the given flag
/// If the flag is cleared by hardware, it does nothing
pub fn clear_flag(&mut self, f: I2CFlags) -> &mut Self {
match f.offsets() {
(5, o) => match o {
8...15 => self.clear(5, o),
_ => self
},
_ => self
}
}
/// Set CCR
/// Refer to the STM32F4 user manual
pub fn... | {
(self.block[6].read() >> 8) & 0b1111_1111
} | identifier_body |
i2c.rs | //! I2C Peripheral
use crate::common::{ Register, Frequency, I2CInterrupt, I2CFlags, I2CBitMode, MasterMode, DutyCycle, DualAddress };
use crate::common::enums::RCCPeripheral;
use crate::common::structs::pins::Pin;
use embedded_hal::blocking::i2c::{ Read, Write, WriteRead };
use crate::peripherals::extended::{ gpio:... |
// Clear condition by reading SR2
let _ = self.block[6].read();
// Store bytes
for i in 0..last {
buffer[i] = self.recv_byte()?;
}
self.nack()
.stop();
// Read last byte
buffer[last] = self.recv_byte()?;
Ok(())
}
}
impl Write for I2c {
type Error = I2CError;
/// Send a buffer of bytes
... | while !self.is_set(5, 1) {} | random_line_split |
download.rs | use std::collections::{HashMap, HashSet};
use console::style;
use dialoguer::Confirm;
use fimfic_tracker::{
Config, Id, Result, SensibilityLevel, Story, StoryData, StoryStatus, StoryUpdate, TrackerError,
};
use crate::args::{Download, Prompt};
use crate::readable::ReadableDate;
use crate::Requester;
macro_rules... | StoryDownload::Forced(id) => match story_data.get(id) {
Some(story) => requester.download(story)?,
None => warn!("{} is not present in the tracker file.", id),
},
};
// Insert the update once it downloads.
if let StoryDownload::Update(id, ... | // So I throw in a `match` to "safely" unwrap it and throw a warning if it is not
// present. | random_line_split |
download.rs | use std::collections::{HashMap, HashSet};
use console::style;
use dialoguer::Confirm;
use fimfic_tracker::{
Config, Id, Result, SensibilityLevel, Story, StoryData, StoryStatus, StoryUpdate, TrackerError,
};
use crate::args::{Download, Prompt};
use crate::readable::ReadableDate;
use crate::Requester;
macro_rules... |
set_printed!();
let status_notice = format!(
"{} has been marked as {} by the author",
format_story!(story),
format_status!(story)
);
match prompt {
Prompt::AssumeYes => {
info!("{}. Checking for an update on it anyways.... | {
continue;
} | conditional_block |
download.rs | use std::collections::{HashMap, HashSet};
use console::style;
use dialoguer::Confirm;
use fimfic_tracker::{
Config, Id, Result, SensibilityLevel, Story, StoryData, StoryStatus, StoryUpdate, TrackerError,
};
use crate::args::{Download, Prompt};
use crate::readable::ReadableDate;
use crate::Requester;
macro_rules... | }
for (id, story) in story_data.iter().filter_map(|(id, story)| {
if selected_ids.contains(id) {
Some((*id, story))
} else {
None
}
}) {
if let StoryStatus::Incomplete = story.status {
continue;
}
set_printed!();
... | {
let selected_ids: Vec<Id> = if ids.is_empty() {
story_data.keys().cloned().collect()
} else {
story_data
.keys()
.filter(|id| ids.contains(id))
.cloned()
.collect()
};
let mut ignored_ids: HashSet<Id> = HashSet::with_capacity(selected_ids... | identifier_body |
download.rs | use std::collections::{HashMap, HashSet};
use console::style;
use dialoguer::Confirm;
use fimfic_tracker::{
Config, Id, Result, SensibilityLevel, Story, StoryData, StoryStatus, StoryUpdate, TrackerError,
};
use crate::args::{Download, Prompt};
use crate::readable::ReadableDate;
use crate::Requester;
macro_rules... | {
Update(Id, Story),
Forced(Id),
}
pub fn download(
config: &Config,
requester: &Requester,
story_data: &mut StoryData,
Download {
force,
prompt,
ref ids,
}: Download,
) -> Result<()> {
let selected_ids: Vec<Id> = if ids.is_empty() {
story_data.keys().cl... | StoryDownload | identifier_name |
asnd.rs | //! The ``asnd`` module of ``ogc-rs``.
//!
//! This module implements a safe wrapper around the audio functions found in ``asndlib.h``.
use crate::{ffi, OgcError, Result};
use alloc::format;
use core::time::Duration;
macro_rules! if_not {
($valid:ident => $error_output:expr, $var:ident $(,)*) => {
if $var... | () -> u32 {
unsafe { ffi::ASND_GetSampleCounter() }
}
/// Returns the samples sent from the IRQ in one tick.
pub fn get_samples_per_tick() -> u32 {
unsafe { ffi::ASND_GetSamplesPerTick() }
}
/// Sets the global time, in milliseconds.
pub fn set_time(time: u32) {
unsafe ... | get_sample_counter | identifier_name |
asnd.rs | //! The ``asnd`` module of ``ogc-rs``.
//!
//! This module implements a safe wrapper around the audio functions found in ``asndlib.h``.
use crate::{ffi, OgcError, Result};
use alloc::format;
use core::time::Duration;
macro_rules! if_not {
($valid:ident => $error_output:expr, $var:ident $(,)*) => {
if $var... |
/// Tests to determine if the voice is ready to receive a new buffer sample
/// with `Asnd::add_voice()`. Returns true if voice is ready.
pub fn test_voice_buffer_ready(voice: u32) -> bool {
assert!(voice < 16, "Voice index {} is >= 16", voice);
unsafe { ffi::ASND_TestVoiceBufferReady(voic... | {
assert!(voice < 16, "Voice index {} is >= 16", voice);
unsafe { ffi::ASND_TestPointer(voice as i32, pointer as *mut _) }
} | identifier_body |
asnd.rs | //! The ``asnd`` module of ``ogc-rs``.
//!
//! This module implements a safe wrapper around the audio functions found in ``asndlib.h``.
use crate::{ffi, OgcError, Result};
use alloc::format;
use core::time::Duration;
macro_rules! if_not {
($valid:ident => $error_output:expr, $var:ident $(,)*) => {
if $var... | } | random_line_split | |
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... |
impl<'a> DirWalkIter<'a> {
pub(in crate::kernel) fn new(dir_path: String) -> Self {
Self {
runner: DirListIter::new(dir_path, None),
subdir_runner: None,
no_more: false,
}
}
} | },
}
}
}
| random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.