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 |
|---|---|---|---|---|
samplesheet.rs | //! This module contains tools to build sample sheets from lists of samples,
//! and to export sample sheets to ARResT-compatible formats.
use std::{collections::HashMap, convert::TryInto, fs::File, io::Write, path::{Path, PathBuf}};
use std::error::Error;
use crate::{models, vaultdb::MatchStatus};
use calamine::{Re... | }
}
fn extract_from_zip(path: &Path, fastqs: &[String], targetdir: &Path, sample_prefix: Option<String>) -> Result<()> {
let zipfile = std::fs::File::open(path)?;
let mut zip = zip::ZipArchive::new(zipfile)?;
let prefix = sample_prefix.unwrap_or_else(|| String::from(""));
for f in fastqs {
... | SampleSheet {
entries: ss.into_iter().map(|s| s.into()).collect()
} | random_line_split |
samplesheet.rs | //! This module contains tools to build sample sheets from lists of samples,
//! and to export sample sheets to ARResT-compatible formats.
use std::{collections::HashMap, convert::TryInto, fs::File, io::Write, path::{Path, PathBuf}};
use std::error::Error;
use crate::{models, vaultdb::MatchStatus};
use calamine::{Re... | &self, db: &PgConnection) -> Result<Vec<String>> {
use crate::schema::fastq;
Ok(fastq::table.select(fastq::filename).filter(fastq::sample_id.eq(self.model.id)).load(db)?)
}
// generate a short but unique string representation of the run
// to keep samples with same characteristics in differ... | astq_paths( | identifier_name |
samplesheet.rs | //! This module contains tools to build sample sheets from lists of samples,
//! and to export sample sheets to ARResT-compatible formats.
use std::{collections::HashMap, convert::TryInto, fs::File, io::Write, path::{Path, PathBuf}};
use std::error::Error;
use crate::{models, vaultdb::MatchStatus};
use calamine::{Re... |
"primer set" => { e.model.primer_set.as_ref().unwrap_or(&String::from("")).to_string() },
"project" => { e.model.project.as_ref().map(|s| s.clone()).unwrap_or(String::from("")) },
"LIMS ID" => { e.model.lims_id.map(|i| i.to_string()).unwrap_or_els... | e.model.dna_nr.as_ref().map(|s| s.clone()).unwrap_or(String::from("")) }, | conditional_block |
lib.rs | #![allow(clippy::mutable_key_type)]
use common::{anyhow::Result, NetworkType};
use core_extensions::{build_extensions, ExtensionsConfig, CURRENT_EPOCH, MATURE_THRESHOLD};
use core_rpc::{
CkbRpc, CkbRpcClient, MercuryRpc, MercuryRpcImpl, CURRENT_BLOCK_NUMBER, TX_POOL_CACHE,
USE_HEX_FORMAT,
};
use core_storage::... | match self
.get_block_by_number(tip_number + 1, use_hex_format)
.await
{
Ok(Some(block)) => {
self.change_current_epoch(block.epoch().to_rational());
if block.parent_hash() == tip_h... |
let mut prune = false;
if let Some((tip_number, tip_hash)) = indexer.tip().expect("get tip should be OK") {
tip = tip_number;
| random_line_split |
lib.rs | #![allow(clippy::mutable_key_type)]
use common::{anyhow::Result, NetworkType};
use core_extensions::{build_extensions, ExtensionsConfig, CURRENT_EPOCH, MATURE_THRESHOLD};
use core_rpc::{
CkbRpc, CkbRpcClient, MercuryRpc, MercuryRpcImpl, CURRENT_BLOCK_NUMBER, TX_POOL_CACHE,
USE_HEX_FORMAT,
};
use core_storage::... |
fn change_current_epoch(&self, current_epoch: RationalU256) {
self.change_maturity_threshold(current_epoch.clone());
let mut epoch = CURRENT_EPOCH.write();
*epoch = current_epoch;
}
fn change_maturity_threshold(&self, current_epoch: RationalU256) {
if current_epoch < self... | {
if height % self.snapshot_interval != 0 {
return;
}
let mut path = self.snapshot_path.clone();
path.push(height.to_string());
let store = self.store.clone();
tokio::spawn(async move {
if let Err(e) = create_checkpoint(store.inner(), path) {
... | identifier_body |
lib.rs | #![allow(clippy::mutable_key_type)]
use common::{anyhow::Result, NetworkType};
use core_extensions::{build_extensions, ExtensionsConfig, CURRENT_EPOCH, MATURE_THRESHOLD};
use core_rpc::{
CkbRpc, CkbRpcClient, MercuryRpc, MercuryRpcImpl, CURRENT_BLOCK_NUMBER, TX_POOL_CACHE,
USE_HEX_FORMAT,
};
use core_storage::... | (ckb_client: &CkbRpcClient, raw_pool: RawTxPool) {
let mut input_set: HashSet<packed::OutPoint> = HashSet::new();
let hashes = tx_hash_list(raw_pool);
if let Ok(res) = ckb_client.get_transactions(hashes).await {
for item in res.iter() {
if let Some(tx) = item {
for input... | handle_raw_tx_pool | identifier_name |
main.rs | use std::convert::TryInto;
use std::fs::File;
use std::io::{ErrorKind, Read, Write};
use std::os::unix::io::{FromRawFd, RawFd};
use std::ptr::NonNull;
use std::sync::{Arc, Mutex};
use std::{slice, usize};
use pcid_interface::{PciBar, PciFeature, PciFeatureInfo, PciFunction, PcidServerHandle};
use syscall::{
CloneF... | () {
// Daemonize
if unsafe { syscall::clone(CloneFlags::empty()).unwrap() }!= 0 {
return;
}
let _logger_ref = setup_logging();
let mut pcid_handle =
PcidServerHandle::connect_default().expect("nvmed: failed to setup channel to pcid");
let pci_config = pcid_handle
.fetch... | main | identifier_name |
main.rs | use std::convert::TryInto;
use std::fs::File;
use std::io::{ErrorKind, Read, Write};
use std::os::unix::io::{FromRawFd, RawFd};
use std::ptr::NonNull;
use std::sync::{Arc, Mutex};
use std::{slice, usize};
use pcid_interface::{PciBar, PciFeature, PciFeatureInfo, PciFunction, PcidServerHandle};
use syscall::{
CloneF... |
Err(error) => {
eprintln!("nvmed: failed to set default logger: {}", error);
None
}
}
}
fn main() {
// Daemonize
if unsafe { syscall::clone(CloneFlags::empty()).unwrap() }!= 0 {
return;
}
let _logger_ref = setup_logging();
let mut pcid_handle =... | {
eprintln!("nvmed: enabled logger");
Some(logger_ref)
} | conditional_block |
main.rs | use std::convert::TryInto;
use std::fs::File;
use std::io::{ErrorKind, Read, Write};
use std::os::unix::io::{FromRawFd, RawFd};
use std::ptr::NonNull;
use std::sync::{Arc, Mutex};
use std::{slice, usize};
use pcid_interface::{PciBar, PciFeature, PciFeatureInfo, PciFunction, PcidServerHandle};
use syscall::{
CloneF... |
let bsp_cpu_id =
irq_helpers::read_bsp_apic_id().expect("nvmed: failed to read APIC ID");
let bsp_lapic_id = bsp_cpu_id
.try_into()
.expect("nvmed: BSP local apic ID couldn't fit inside u8");
let (vector, irq_handle) = irq_helpers::alloc... | use msi_x86_64::DeliveryMode;
use pcid_interface::msi::x86_64 as msi_x86_64;
let entry: &mut MsixTableEntry = &mut table_entries[0]; | random_line_split |
postgres.rs | use crate::{connect, connection_wrapper::Connection, error::quaint_error_to_connector_error, SqlFlavour};
use enumflags2::BitFlags;
use indoc::indoc;
use migration_connector::{ConnectorError, ConnectorResult, MigrationDirectory, MigrationFeature};
use quaint::{connector::PostgresUrl, error::ErrorKind as QuaintKind, pre... | conn.raw_cmd(&drop_and_recreate_schema).await?;
Ok(())
}
async fn reset(&self, connection: &Connection) -> ConnectorResult<()> {
let schema_name = connection.connection_info().schema_name();
connection
.raw_cmd(&format!("DROP SCHEMA \"{}\" CASCADE", schema_name))
... | {
let mut url = Url::parse(database_str).map_err(|err| ConnectorError::url_parse_error(err, database_str))?;
strip_schema_param_from_url(&mut url);
let conn = create_postgres_admin_conn(url.clone()).await?;
let schema = self.url.schema();
let db_name = self.url.dbname();
... | identifier_body |
postgres.rs | use crate::{connect, connection_wrapper::Connection, error::quaint_error_to_connector_error, SqlFlavour};
use enumflags2::BitFlags;
use indoc::indoc;
use migration_connector::{ConnectorError, ConnectorResult, MigrationDirectory, MigrationFeature};
use quaint::{connector::PostgresUrl, error::ErrorKind as QuaintKind, pre... |
temporary_database.raw_cmd(&create_schema).await?;
for migration in migrations {
let script = migration.read_migration_script()?;
tracing::debug!(
"Applying migration `{}` to temporary database.",
... | random_line_split | |
postgres.rs | use crate::{connect, connection_wrapper::Connection, error::quaint_error_to_connector_error, SqlFlavour};
use enumflags2::BitFlags;
use indoc::indoc;
use migration_connector::{ConnectorError, ConnectorResult, MigrationDirectory, MigrationFeature};
use quaint::{connector::PostgresUrl, error::ErrorKind as QuaintKind, pre... | (&self, connection: &Connection) -> ConnectorResult<()> {
let schema_name = connection.connection_info().schema_name();
connection
.raw_cmd(&format!("DROP SCHEMA \"{}\" CASCADE", schema_name))
.await?;
connection
.raw_cmd(&format!("CREATE SCHEMA \"{}\"", schema... | reset | identifier_name |
postgres.rs | use crate::{connect, connection_wrapper::Connection, error::quaint_error_to_connector_error, SqlFlavour};
use enumflags2::BitFlags;
use indoc::indoc;
use migration_connector::{ConnectorError, ConnectorResult, MigrationDirectory, MigrationFeature};
use quaint::{connector::PostgresUrl, error::ErrorKind as QuaintKind, pre... |
Err(err) => return Err(err.into()),
};
// Now create the schema
url.set_path(&format!("/{}", db_name));
let conn = connect(&url.to_string()).await?;
let schema_sql = format!("CREATE SCHEMA IF NOT EXISTS \"{}\";", &self.schema_name());
conn.raw_cmd(&schema... | {
database_already_exists_error = Some(err)
} | conditional_block |
bench.rs | use super::config::*;
use super::errors::*;
use super::out;
use super::symbols;
use bencher::stats::Summary;
use libc::c_void;
#[cfg(unix)]
use libc::{RTLD_GLOBAL, RTLD_LAZY, RTLD_LOCAL, RTLD_NOW};
#[cfg(unix)]
use libloading;
use libloading::{Library, Symbol};
use precision::{self, Elapsed, Precision};
use std::collec... |
let test_results = run_tests(config, global_ctx, tests)?;
if let Some(global_teardown) = tests_runner.global_teardown {
unsafe { global_teardown(global_ctx) }
}
Ok(test_results)
}
/// Run an optional guard command
/// Returns `false` on success (return code = `0`), `true` on failure
fn disable... | {
unsafe { global_setup(&mut global_ctx) }
} | conditional_block |
bench.rs | use super::config::*;
use super::errors::*;
use super::out;
use super::symbols;
use bencher::stats::Summary;
use libc::c_void;
#[cfg(unix)]
use libc::{RTLD_GLOBAL, RTLD_LAZY, RTLD_LOCAL, RTLD_NOW};
#[cfg(unix)]
use libloading;
use libloading::{Library, Symbol};
use precision::{self, Elapsed, Precision};
use std::collec... | {
pub grand_summary: Summary,
pub bodies_summary: Vec<TestBodySummary>,
}
impl Default for AnonymousTestResult {
fn default() -> Self {
Self {
grand_summary: Summary::new(&[0.0]),
bodies_summary: vec![],
}
}
}
impl From<TestResult> for AnonymousTestResult {
... | AnonymousTestResult | identifier_name |
bench.rs | use super::config::*;
use super::errors::*;
use super::out;
use super::symbols;
use bencher::stats::Summary;
use libc::c_void;
#[cfg(unix)]
use libc::{RTLD_GLOBAL, RTLD_LAZY, RTLD_LOCAL, RTLD_NOW};
#[cfg(unix)]
use libloading;
use libloading::{Library, Symbol};
use precision::{self, Elapsed, Precision};
use std::collec... | let test_results = bench_library(&config, Path::new(library_path))?;
for test_result in test_results {
let test_name_key = test_result.name.clone();
let anonymous_test_result = test_result.into();
if!test_suites_results.contains_key(&test_name_key) {
t... | let library_path = &test_suite.library_path; | random_line_split |
bench.rs | use super::config::*;
use super::errors::*;
use super::out;
use super::symbols;
use bencher::stats::Summary;
use libc::c_void;
#[cfg(unix)]
use libc::{RTLD_GLOBAL, RTLD_LAZY, RTLD_LOCAL, RTLD_NOW};
#[cfg(unix)]
use libloading;
use libloading::{Library, Symbol};
use precision::{self, Elapsed, Precision};
use std::collec... | .clone()
.iter()
.map(|body| body.body_fn)
.collect(),
};
let bench_result = bench_runner.bench(&mut test_bodies_bench);
let mut bodies_summary = vec![];
for (body_id, body) in (*test).bodies.iter().enumerate() {
let test_body_summary = TestBodySummary... | {
let mut ctx: TestCtx = ptr::null_mut();
if let Some(setup) = (*test).setup_fn {
unsafe { setup(global_ctx, &mut ctx) }
}
let bench_runner = AdaptiveRunner::new(
config
.initial_round_size
.unwrap_or(DEFAULT_INITIAL_ROUND_SIZE),
config.min_sample_size.un... | identifier_body |
opmapi.rs | // Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// All files in the project carrying such notice may not be copied, modified, or distributed
// except according ... |
extern "system" {
pub fn OPMGetVideoOutputsFromHMONITOR(
hMonitor: HMONITOR,
vos: OPM_VIDEO_OUTPUT_SEMANTICS,
pulNumVideoOutputs: *mut ULONG,
pppOPMVideoOutputArray: *mut *mut *mut IOPMVideoOutput,
) -> HRESULT;
pub fn OPMGetVideoOutputForTarget(
pAdapterLuid: *mut L... | {
ulBusTypeAndImplementation & OPM_BUS_IMPLEMENTATION_MODIFIER_NON_STANDARD
} | identifier_body |
opmapi.rs | // Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// All files in the project carrying such notice may not be copied, modified, or distributed
// except according ... | (ulBusTypeAndImplementation: ULONG) -> ULONG {
(ulBusTypeAndImplementation & OPM_BUS_IMPLEMENTATION_MODIFIER_MASK) >> 16
}
#[inline]
pub fn IsNonStandardBusImplementation(ulBusTypeAndImplementation: ULONG) -> ULONG {
ulBusTypeAndImplementation & OPM_BUS_IMPLEMENTATION_MODIFIER_NON_STANDARD
}
extern "system" {
... | GetBusImplementation | identifier_name |
opmapi.rs | // Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// All files in the project carrying such notice may not be copied, modified, or distributed
// except according ... | OPM_PROTECTION_STANDARD_CEA805A_TYPEA_1125I = 0x80,
OPM_PROTECTION_STANDARD_CEA805A_TYPEB_525P = 0x100,
OPM_PROTECTION_STANDARD_CEA805A_TYPEB_750P = 0x200,
OPM_PROTECTION_STANDARD_CEA805A_TYPEB_1125I = 0x400,
OPM_PROTECTION_STANDARD_ARIBTRB15_525I = 0x800,
OPM_PROTECTION_STANDARD_ARIBTRB15_525P ... | OPM_PROTECTION_STANDARD_CEA805A_TYPEA_525P = 0x20,
OPM_PROTECTION_STANDARD_CEA805A_TYPEA_750P = 0x40, | random_line_split |
oauth.rs | extern crate rand;
//Concurrency stuff
use std::io::Read;
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
use tiny_http::{Response, Server};
use serde::{Deserialize, Serialize};
use curl::easy::{Easy, List};
#[derive(Debug)]
enum OAuthState {
IDLE,
AUTHORIZED,
ERROR,
}
#[derive(Serialize... |
let mut file = File::create("access_token.rvp").expect("Unable to create file");
file.write_all(serialized_token.as_bytes())
.expect("Unable to write access token");
}
fn generate_random_string(n: usize) -> String {
use rand::Rng;
const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
... | {
fs::remove_file("access_token.rvp").expect("Could not remove file");
} | conditional_block |
oauth.rs | extern crate rand;
//Concurrency stuff
use std::io::Read;
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
use tiny_http::{Response, Server};
use serde::{Deserialize, Serialize};
use curl::easy::{Easy, List};
#[derive(Debug)]
enum OAuthState {
IDLE,
AUTHORIZED,
ERROR,
}
#[derive(Serialize... | {
client_id: String,
client_state: String,
authorization_link: String,
auth_state: OAuthState,
oauth_token: Option<OAuthToken>,
pub error_state: String,
pub code: String,
}
struct AuthBox {
has_error: bool,
error_msg: String,
code: String,
state: String,
}
impl OAuthClient... | OAuthClient | identifier_name |
oauth.rs | extern crate rand;
//Concurrency stuff
use std::io::Read;
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
use tiny_http::{Response, Server};
use serde::{Deserialize, Serialize};
use curl::easy::{Easy, List};
#[derive(Debug)]
enum OAuthState {
IDLE,
AUTHORIZED,
ERROR,
}
#[derive(Serialize... | }
let auth_box = AuthBox {
has_error: true,
error_msg: "Reached timeout. User did not authorize usage of RPV in time".to_string(),
code: "".to_string(),
state: "".to_string(),
};
println!("Timeout during authentication");
tx_countdo... | for passed_seconds in 0..wait_time {
thread::sleep(Duration::from_secs(1)); | random_line_split |
connection.rs |
enum ReceiverStatus {
Udp(Vec<u8>),
Websocket(VoiceEvent),
}
#[allow(dead_code)]
struct ThreadItems {
rx: MpscReceiver<ReceiverStatus>,
udp_close_sender: MpscSender<i32>,
udp_thread: JoinHandle<()>,
ws_close_sender: MpscSender<i32>,
ws_thread: JoinHandle<()>,
}
#[allow(dead_code)]
pub str... | let index = HEADER_LEN + crypted.len();
packet[HEADER_LEN..index].clone_from_slice(&crypted);
self.sequence = self.sequence.wrapping_add(1);
self.timestamp = self.timestamp.wrapping_add(960);
Ok(HEADER_LEN + crypted.len())
}
fn set_speaking(&mut self, speaking: bool) -... | let crypted = {
let slice = &packet[HEADER_LEN..HEADER_LEN + len];
secretbox::seal(slice, &nonce, &self.key)
}; | random_line_split |
connection.rs | enum ReceiverStatus {
Udp(Vec<u8>),
Websocket(VoiceEvent),
}
#[allow(dead_code)]
struct ThreadItems {
rx: MpscReceiver<ReceiverStatus>,
udp_close_sender: MpscSender<i32>,
udp_thread: JoinHandle<()>,
ws_close_sender: MpscSender<i32>,
ws_thread: JoinHandle<()>,
}
#[allow(dead_code)]
pub stru... | (&mut self, speaking: bool) -> Result<()> {
if self.speaking == speaking {
return Ok(());
}
self.speaking = speaking;
self.client.lock().send_json(&payload::build_speaking(speaking))
}
}
impl Drop for Connection {
fn drop(&mut self) {
let _ = self.thread_it... | set_speaking | identifier_name |
connection.rs | enum ReceiverStatus {
Udp(Vec<u8>),
Websocket(VoiceEvent),
}
#[allow(dead_code)]
struct ThreadItems {
rx: MpscReceiver<ReceiverStatus>,
udp_close_sender: MpscSender<i32>,
udp_thread: JoinHandle<()>,
ws_close_sender: MpscSender<i32>,
ws_thread: JoinHandle<()>,
}
#[allow(dead_code)]
pub stru... | ,
};
// May need to force interleave/copy.
combine_audio(buffer, &mut mix_buffer, source_stereo, vol);
len = len.max(temp_len);
i += if temp_len > 0 {
1
} else {
sources.remove(i);
... | {
let buffer_len = if source_stereo { 960 * 2 } else { 960 };
match stream.read_pcm_frame(&mut buffer[..buffer_len]) {
Some(len) => len,
None => 0,
}
} | conditional_block |
connection.rs | enum ReceiverStatus {
Udp(Vec<u8>),
Websocket(VoiceEvent),
}
#[allow(dead_code)]
struct ThreadItems {
rx: MpscReceiver<ReceiverStatus>,
udp_close_sender: MpscSender<i32>,
udp_thread: JoinHandle<()>,
ws_close_sender: MpscSender<i32>,
ws_thread: JoinHandle<()>,
}
#[allow(dead_code)]
pub stru... |
fn generate_url(endpoint: &mut String) -> Result<WebsocketUrl> {
if endpoint.ends_with(":80") {
let len = endpoint.len();
endpoint.truncate(len - 3);
}
WebsocketUrl::parse(&format!("wss://{}/?v={}", endpoint, VOICE_GATEWAY_VERSION))
.or(Err(Error::Voice(VoiceError::EndpointUrl)))
... | {
for i in 0..1920 {
let sample_index = if true_stereo { i } else { i/2 };
let sample = (raw_buffer[sample_index] as f32) / 32768.0;
float_buffer[i] = float_buffer[i] + sample * volume;
}
} | identifier_body |
initializer.rs | //! Reactor used to initialize a node.
use std::fmt::{self, Display, Formatter};
use datasize::DataSize;
use derive_more::From;
use prometheus::Registry;
use reactor::ReactorEvent;
use serde::Serialize;
use thiserror::Error;
use tracing::info;
use crate::{
components::{
chainspec_loader::{self, Chainspec... | (&self) -> Option<ReactorExit> {
self.chainspec_loader.reactor_exit()
}
}
#[cfg(test)]
pub mod test {
use super::*;
use crate::{
components::network::ENABLE_LIBP2P_NET_ENV_VAR, testing::network::NetworkedReactor,
types::Chainspec,
};
use std::{env, sync::Arc};
impl Reac... | maybe_exit | identifier_name |
initializer.rs | //! Reactor used to initialize a node.
use std::fmt::{self, Display, Formatter};
use datasize::DataSize;
use derive_more::From;
use prometheus::Registry;
use reactor::ReactorEvent;
use serde::Serialize;
use thiserror::Error;
use tracing::info;
use crate::{
components::{
chainspec_loader::{self, Chainspec... | NodeId::from(&self.network_identity)
}
}
}
} | random_line_split | |
initializer.rs | //! Reactor used to initialize a node.
use std::fmt::{self, Display, Formatter};
use datasize::DataSize;
use derive_more::From;
use prometheus::Registry;
use reactor::ReactorEvent;
use serde::Serialize;
use thiserror::Error;
use tracing::info;
use crate::{
components::{
chainspec_loader::{self, Chainspec... |
}
impl From<NetworkRequest<NodeId, gossiper::Message<GossipedAddress>>> for Event {
fn from(_request: NetworkRequest<NodeId, gossiper::Message<GossipedAddress>>) -> Self {
unreachable!("no gossiper events happen during initialization")
}
}
impl From<ConsensusRequest> for Event {
fn from(_request:... | {
unreachable!("no linear chain events happen during initialization")
} | identifier_body |
main.rs | use anyhow::{anyhow, Result};
use colored::*;
use dunce::canonicalize;
use git2::{Commit, ObjectType, Oid, Repository, Tree};
use regex::Regex;
use std::{
collections::{HashMap, HashSet},
convert::{TryFrom, TryInto},
env,
ffi::OsString,
path::{Path, PathBuf},
};
use structopt::StructOpt;
#[derive(D... | {
#[structopt(
help = "The pattern to search for. Shall be a regular expression passed to regex crate."
)]
pattern: String,
#[structopt(help = "Root repo to grep")]
repo: Option<PathBuf>,
#[structopt(short, long, help = "Branch name")]
branch: Option<String>,
#[structopt(
... | Opt | identifier_name |
main.rs | use anyhow::{anyhow, Result};
use colored::*;
use dunce::canonicalize;
use git2::{Commit, ObjectType, Oid, Repository, Tree};
use regex::Regex;
use std::{
collections::{HashMap, HashSet},
convert::{TryFrom, TryInto},
env,
ffi::OsString,
path::{Path, PathBuf},
};
use structopt::StructOpt;
#[derive(D... | let blob = obj.peel_to_blob().ok()?;
if blob.is_binary() {
return None;
}
let ext = PathBuf::from(name).extension()?.to_owned();
if!self.settings.extensions.contains(&ext.to_ascii_lowercase()) {
retur... | random_line_split | |
main.rs | use anyhow::{anyhow, Result};
use colored::*;
use dunce::canonicalize;
use git2::{Commit, ObjectType, Oid, Repository, Tree};
use regex::Regex;
use std::{
collections::{HashMap, HashSet},
convert::{TryFrom, TryInto},
env,
ffi::OsString,
path::{Path, PathBuf},
};
use structopt::StructOpt;
#[derive(D... |
}
}
if settings.color_code {
if settings.output_grouping &&!*visited {
println!("\ncommit {}:", commit.id().to_string().bright_blue());
*visited = true;
}
let mut content = if line_start < found.start() {
i... | {
line_end = (i as usize).max(line_start);
break;
} | conditional_block |
lib.rs | //! [![github]](https://github.com/dtolnay/trybuild) [![crates-io]](https://crates.io/crates/trybuild) [![docs-rs]](https://docs.rs/trybuild)
//!
//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
//! [crates-io]: https://img.shields.io/badge/crates.io-f... | (&mut self) {
if!thread::panicking() {
self.runner.borrow_mut().run();
}
}
}
| drop | identifier_name |
lib.rs | //! [![github]](https://github.com/dtolnay/trybuild) [![crates-io]](https://crates.io/crates/trybuild) [![docs-rs]](https://docs.rs/trybuild)
//!
//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
//! [crates-io]: https://img.shields.io/badge/crates.io-f... |
}
}
| {
self.runner.borrow_mut().run();
} | conditional_block |
lib.rs | //! [![github]](https://github.com/dtolnay/trybuild) [![crates-io]](https://crates.io/crates/trybuild) [![docs-rs]](https://docs.rs/trybuild)
//!
//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
//! [crates-io]: https://img.shields.io/badge/crates.io-f... | //! [`ref-cast`]: https://github.com/dtolnay/ref-cast
//!
//! ```console
//! error: RefCast trait requires #[repr(C)] or #[repr(transparent)]
//! --> $DIR/missing-repr.rs:3:10
//! |
//! 3 | #[derive(RefCast)]
//! | ^^^^^^^
//! ```
//!
//! Macros that consume helper attributes will want to check that unrec... | //! by a procedural macro. For example the derive macro from the [`ref-cast`]
//! crate is required to be placed on a type that has either `#[repr(C)]` or
//! `#[repr(transparent)]` in order for the expansion to be free of undefined
//! behavior, which it enforces at compile time:
//! | random_line_split |
20.rs | use std::io::{self, BufRead};
use std::collections::HashMap;
const IMAGEDIM: usize = 8;
type Image = [u16; IMAGEDIM];
// the bool encodes flip
#[derive(Debug, Copy, Clone)]
enum Orientation {
Up(bool),
Left(bool),
Down(bool),
Right(bool),
}
fn rot_orientation(ori: Orientation) -> Orientation {
us... |
if false {
dump_sea(sea);
println!();
}
let monster_weight = (MONS0.count_ones() + MONS1.count_ones() + MONS2.count_ones()) as usize;
println!("quick check: {}", initial_roughness - monsters.len() * monster_weight);
for (y, row) in sea.iter().enumerate() {
for c in (0..128... | println!("rouff with monsters {}, {} total", initial_roughness, monsters.len()); | random_line_split |
20.rs | use std::io::{self, BufRead};
use std::collections::HashMap;
const IMAGEDIM: usize = 8;
type Image = [u16; IMAGEDIM];
// the bool encodes flip
#[derive(Debug, Copy, Clone)]
enum Orientation {
Up(bool),
Left(bool),
Down(bool),
Right(bool),
}
fn rot_orientation(ori: Orientation) -> Orientation {
us... | true
}
}
fn flipbits(mut bits: u16) -> u16 {
// careful, just the lowest 10 bits, not 16
// 0123456789
// 9876543210
let mut out = 0;
for _ in 0..(IMAGEDIM + 2) {
out <<= 1;
out |= bits & 1;
bits >>= 1;
}
out
}
// counting from the right, MSB is top
fn ... | {
assert!(self.map[pos].is_none());
let x = pos % self.dim;
let y = pos / self.dim;
if y > 0 && self.bottom_border(self.coord(x, y - 1)).map(|border| border !=
tile.borders.0).unwrap_or(false) {
return false;
... | identifier_body |
20.rs | use std::io::{self, BufRead};
use std::collections::HashMap;
const IMAGEDIM: usize = 8;
type Image = [u16; IMAGEDIM];
// the bool encodes flip
#[derive(Debug, Copy, Clone)]
enum Orientation {
Up(bool),
Left(bool),
Down(bool),
Right(bool),
}
fn rot_orientation(ori: Orientation) -> Orientation {
us... | (&self, pos: usize, tile: &Tile) -> bool {
assert!(self.map[pos].is_none());
let x = pos % self.dim;
let y = pos / self.dim;
if y > 0 && self.bottom_border(self.coord(x, y - 1)).map(|border| border!=
tile.borders.0).unwrap_... | accepts | identifier_name |
snapshot_cmd.rs | // Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.
// Parity Ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at yo... | // true,
// self.max_round_blocks_to_import,
// );
//
// client_config.snapshot = self.snapshot_conf;
//
// let restoration_db_handler = db::restoration_db_handler(&client_path, &client_config);
// let client_db = restoration_db_handler.open(&client_path)
// .map_err(|e| format!("Failed to open database {:?}"... | random_line_split | |
snapshot_cmd.rs | // Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.
// Parity Ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at yo... | {
pub cache_config: CacheConfig,
pub dirs: Directories,
pub spec: SpecType,
pub pruning: Pruning,
pub pruning_history: u64,
pub pruning_memory: usize,
pub tracing: Switch,
pub fat_db: Switch,
// pub compaction: DatabaseCompactionProfile,
pub file_path: Option<String>,
pub kind: Kind,
pub block_at: BlockId,
... | SnapshotCommand | identifier_name |
config.rs | use anyhow::{Context, Error};
use clipboard::{ClipboardContext, ClipboardProvider};
use image::Rgba;
use silicon::directories::PROJECT_DIRS;
use silicon::formatter::{ImageFormatter, ImageFormatterBuilder};
use silicon::utils::{Background, ShadowAdder, ToRgba};
use std::ffi::OsString;
use std::fs::File;
use std::io::{st... |
fn parse_str_color(s: &str) -> Result<Rgba<u8>, Error> {
s.to_rgba()
.map_err(|_| format_err!("Invalid color: `{}`", s))
}
fn parse_font_str(s: &str) -> Vec<(String, f32)> {
let mut result = vec![];
for font in s.split(';') {
let tmp = font.split('=').collect::<Vec<_>>();
let font_... | {
let args = std::fs::read_to_string(config_file())
.ok()
.and_then(|content| {
content
.split('\n')
.map(|line| line.trim())
.filter(|line| !line.starts_with('#') && !line.is_empty())
.map(shell_words::split)
... | identifier_body |
config.rs | use anyhow::{Context, Error};
use clipboard::{ClipboardContext, ClipboardProvider};
use image::Rgba;
use silicon::directories::PROJECT_DIRS;
use silicon::formatter::{ImageFormatter, ImageFormatterBuilder};
use silicon::utils::{Background, ShadowAdder, ToRgba};
use std::ffi::OsString;
use std::fs::File;
use std::io::{st... | (&self) -> Option<PathBuf> {
let need_expand = self.output.as_ref().map(|p| p.starts_with("~")) == Some(true);
if let (Ok(home_dir), true) = (std::env::var("HOME"), need_expand) {
self.output
.as_ref()
.map(|p| p.to_string_lossy().replacen('~', &home_dir, 1).in... | get_expanded_output | identifier_name |
config.rs | use anyhow::{Context, Error};
use clipboard::{ClipboardContext, ClipboardProvider};
use image::Rgba;
use silicon::directories::PROJECT_DIRS;
use silicon::formatter::{ImageFormatter, ImageFormatterBuilder};
use silicon::utils::{Background, ShadowAdder, ToRgba};
use std::ffi::OsString;
use std::fs::File;
use std::io::{st... | pub struct Config {
/// Background image
#[structopt(long, value_name = "IMAGE", conflicts_with = "background")]
pub background_image: Option<PathBuf>,
/// Background color of the image
#[structopt(
long,
short,
value_name = "COLOR",
default_value = "#aaaaff",
... | type Lines = Vec<u32>;
#[derive(StructOpt, Debug)]
#[structopt(name = "silicon")]
#[structopt(global_setting(ColoredHelp))] | random_line_split |
config.rs | use anyhow::{Context, Error};
use clipboard::{ClipboardContext, ClipboardProvider};
use image::Rgba;
use silicon::directories::PROJECT_DIRS;
use silicon::formatter::{ImageFormatter, ImageFormatterBuilder};
use silicon::utils::{Background, ShadowAdder, ToRgba};
use std::ffi::OsString;
use std::fs::File;
use std::io::{st... |
let mut stdin = stdin();
let mut s = String::new();
stdin.read_to_string(&mut s)?;
let language = possible_language.unwrap_or_else(|| {
ps.find_syntax_by_first_line(&s)
.ok_or_else(|| format_err!("Failed to detect the language"))
})?;
Ok((la... | {
let mut s = String::new();
let mut file = File::open(path)?;
file.read_to_string(&mut s)?;
let language = possible_language.unwrap_or_else(|| {
ps.find_syntax_for_file(path)?
.ok_or_else(|| format_err!("Failed to detect the language"... | conditional_block |
import.rs | use std::{io, path::PathBuf};
use std::collections::HashMap;
use crate::mm0::{SortId, TermId, ThmId};
#[cfg(debug_assertions)] use mm0b_parser::BasicMmbFile as MmbFile;
#[cfg(not(debug_assertions))] use mm0b_parser::BareMmbFile as MmbFile;
use super::Mm0Writer;
macro_rules! const_assert { ($cond:expr) => { let _ = [... | <T:?Sized>(T);
static HOL_MMB: &Aligned<[u8]> = &Aligned(*include_bytes!("../../hol.mmb"));
let mmb = MmbFile::parse(&HOL_MMB.0).unwrap();
#[cfg(debug_assertions)] check_consts(&mmb);
Mm0Writer::new(out, temp, &mmb)
}
| Aligned | identifier_name |
import.rs | use std::{io, path::PathBuf};
use std::collections::HashMap;
use crate::mm0::{SortId, TermId, ThmId};
#[cfg(debug_assertions)] use mm0b_parser::BasicMmbFile as MmbFile;
#[cfg(not(debug_assertions))] use mm0b_parser::BareMmbFile as MmbFile;
use super::Mm0Writer;
macro_rules! const_assert { ($cond:expr) => { let _ = [... | Mm0Writer::new(out, temp, &mmb)
} | let mmb = MmbFile::parse(&HOL_MMB.0).unwrap();
#[cfg(debug_assertions)] check_consts(&mmb); | random_line_split |
lib.rs | //! Async concurrent hashmap built on top of [dashmap](https://docs.rs/dashmap/).
//!
//! # Wait
//! [`WaitMap`](crate::WaitMap) is a concurrent hashmap with an asynchronous `wait` operation.
//! ```
//! # extern crate async_std;
//! # extern crate waitmap;
//! # use async_std::main;
//! # use waitmap::WaitMap;
//! # #... | /// assert!(*kv.key() == emma);
/// assert!(*kv.value() == 0);
/// assert!(kv.pair() == (&"Emma Goldman".to_string(), &0));
/// # Ok(())
/// # }
/// ```
pub struct Ref<'a, K, V, S> {
inner: one::Ref<'a, K, WaitEntry<V>, S>,
}
impl<'a, K: Eq + Hash, V, S: BuildHasher> Ref<'a, K, V, S> {
pub fn key(&self) -> &K ... | /// let emma = "Emma Goldman".to_string();
///
/// map.insert(emma.clone(), 0);
/// let kv: Ref<String, i32, _> = map.get(&emma).unwrap();
/// | random_line_split |
lib.rs | //! Async concurrent hashmap built on top of [dashmap](https://docs.rs/dashmap/).
//!
//! # Wait
//! [`WaitMap`](crate::WaitMap) is a concurrent hashmap with an asynchronous `wait` operation.
//! ```
//! # extern crate async_std;
//! # extern crate waitmap;
//! # use async_std::main;
//! # use waitmap::WaitMap;
//! # #... |
}
enum WaitEntry<V> {
Waiting(WakerSet),
Filled(V),
}
/// A shared reference to a `WaitMap` key-value pair.
/// ```
/// # extern crate async_std;
/// # extern crate waitmap;
/// # use async_std::main;
/// # use waitmap::{Ref, WaitMap};
/// # #[async_std::main]
/// # async fn main() -> std::io::Result<()> {
/... | {
self.map.retain(|_, entry| {
if let Waiting(wakers) = entry {
// NB: In theory, there is a deadlock risk: if a task is awoken before the
// retain is completed, it may see a waiting entry with an empty waker set,
// rather than a missing entry.
... | identifier_body |
lib.rs | //! Async concurrent hashmap built on top of [dashmap](https://docs.rs/dashmap/).
//!
//! # Wait
//! [`WaitMap`](crate::WaitMap) is a concurrent hashmap with an asynchronous `wait` operation.
//! ```
//! # extern crate async_std;
//! # extern crate waitmap;
//! # use async_std::main;
//! # use waitmap::WaitMap;
//! # #... | (&mut self) -> &mut V {
match self.inner.value_mut() {
Filled(value) => value,
_ => panic!(),
}
}
pub fn pair(&self) -> (&K, &V) {
(self.key(), self.value())
}
pub fn pair_mut(&mut self) -> (&K, &mut V) {
match self.inner.pair_mut() {
... | value_mut | identifier_name |
lib.rs | //! Async concurrent hashmap built on top of [dashmap](https://docs.rs/dashmap/).
//!
//! # Wait
//! [`WaitMap`](crate::WaitMap) is a concurrent hashmap with an asynchronous `wait` operation.
//! ```
//! # extern crate async_std;
//! # extern crate waitmap;
//! # use async_std::main;
//! # use waitmap::WaitMap;
//! # #... | else { false });
}
pub fn len(&self) -> usize {
self.map.len()
}
/// Cancels all outstanding `waits` on the map.
/// ```
/// # extern crate async_std;
/// # extern crate waitmap;
/// # use async_std::{main, stream, prelude::*};
/// # use waitmap::WaitMap;
/// # #[async... | { true } | conditional_block |
maimemo_client.rs | use crate::client::*;
use crate::config::*;
use chrono::Local;
use cookie_store::CookieStore;
use reqwest::Client;
use scraper::{Html, Selector};
use serde::{Deserialize, Serialize};
use std::fmt;
/// notepad包含必要的header info和内容detail
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Notepad { | brief: String,
created_time: Option<String>,
updated_time: Option<String>,
contents: Option<String>,
}
impl Notepad {
pub fn get_notepad_id(&self) -> &str {
&self.notepad_id
}
pub fn set_contents(&mut self, contents: Option<String>) {
self.contents = contents;
}
pu... | is_private: u8,
notepad_id: String,
title: String, | random_line_split |
maimemo_client.rs | use crate::client::*;
use crate::config::*;
use chrono::Local;
use cookie_store::CookieStore;
use reqwest::Client;
use scraper::{Html, Selector};
use serde::{Deserialize, Serialize};
use std::fmt;
/// notepad包含必要的header info和内容detail
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Notepad {
is_private: ... | gin().await.map_err(|e| format!("{:?}", e))?;
Ok(())
}
#[tokio::test]
async fn get_notepad_list() -> Result<(), String> {
init_log();
let config = Config::from_yaml_file(CONFIG_PATH).unwrap();
let mut client = MaimemoClient::new(config.maimemo.unwrap())?;
if!client.h... | _selector)
.next()
.map(|e| e.inner_html())
.ok_or_else(|| {
error!("not found element {} in html: \n{}", id, html);
format!("not found element {} in html", id)
})
}
}
#[cfg(test)]
mod tests {
use super::*;
const CONFIG_PATH: &... | identifier_body |
maimemo_client.rs | use crate::client::*;
use crate::config::*;
use chrono::Local;
use cookie_store::CookieStore;
use reqwest::Client;
use scraper::{Html, Selector};
use serde::{Deserialize, Serialize};
use std::fmt;
/// notepad包含必要的header info和内容detail
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Notepad {
is_private: ... | ser_token = self.get_user_token_val().expect("not found user token");
url.to_string() + user_token
};
let payload = serde_json::json!({"keyword":null,"scope":"MINE","recommend":false,"offset":0,"limit":30,"total":-1});
let resp = send_request(
&self.config,
&s... | token}
let url_handler = |url: &str| {
let u | conditional_block |
maimemo_client.rs | use crate::client::*;
use crate::config::*;
use chrono::Local;
use cookie_store::CookieStore;
use reqwest::Client;
use scraper::{Html, Selector};
use serde::{Deserialize, Serialize};
use std::fmt;
/// notepad包含必要的header info和内容detail
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Notepad {
is_private: ... | t!(notepads.len() > 0);
Ok(())
}
#[tokio::test]
async fn get_notepad_contents() -> Result<(), String> {
init_log();
let config = Config::from_yaml_file(CONFIG_PATH).unwrap();
let mut client = MaimemoClient::new(config.maimemo.unwrap())?;
if!client.has_logged() {
... | ?;
asser | identifier_name |
process_packet.rs | 120*1000*1000*1000; // 120 seconds
// The jumping off point for all of our logic. This function inspects a packet
// that has come in the tap interface. We do not yet have any idea if we care
// about it; it might not even be TLS. It might not even be TCP!
#[no_mangle]
pub extern "C" fn rust_process_packet(ptr: *mut ... |
}
pub fn establish_bidi(&mut self,
tcp_pkt: &TcpPacket, flow: &Flow,
tag_payload: &Vec<u8>,
wscale_and_mss: WscaleAndMSS) -> bool
{
let (_, master_key, server_random, client_random, session_id) =
parse_tag_pa... | { // upload-only eavesdropped TLS
// (don't mark as TD in FlowTracker until you have the Rc<RefCell>)
self.establish_upload_only(tcp_pkt, flow, &tag_payload)
} | conditional_block |
process_packet.rs | 120*1000*1000*1000; // 120 seconds
// The jumping off point for all of our logic. This function inspects a packet
// that has come in the tap interface. We do not yet have any idea if we care
// about it; it might not even be TLS. It might not even be TCP!
#[no_mangle]
pub extern "C" fn rust_process_packet(ptr: *mut ... | return false;
}
td.expect_bidi_reconnect = false;
if let Some(cov_err) = cov_error {
td.end_whole_session_error(cov_err);
self.cli_ssl_driver
.sessions_to_drop.push_back(td.session_id);
}
let... | {
let (_, master_key, server_random, client_random, session_id) =
parse_tag_payload(tag_payload);
let (tcp_ts, tcp_ts_ecr) = util::get_tcp_timestamps(tcp_pkt);
let mut client_ssl = BufferableSSL::new(session_id);
let ssl_success =
client_ssl.construct_forged_ssl... | identifier_body |
process_packet.rs | = 120*1000*1000*1000; // 120 seconds
// The jumping off point for all of our logic. This function inspects a packet
// that has come in the tap interface. We do not yet have any idea if we care
// about it; it might not even be TLS. It might not even be TCP!
#[no_mangle]
pub extern "C" fn rust_process_packet(ptr: *mu... | },
EtherTypes::Ipv4 => ð_payload[0..],
_ => return,
};
match Ipv4Packet::new(ip_data) {
Some(pkt) => global.process_ipv4_packet(pkt, rust_view_len),
None => return,
}
}
fn is_tls_app_pkt(tcp_pkt: &TcpPacket) -> bool
{
let payload = tcp_pkt.payload();
paylo... | // + (eth_payload[1] as u16);
ð_payload[4..]
} else {
return
} | random_line_split |
process_packet.rs | 120*1000*1000*1000; // 120 seconds
// The jumping off point for all of our logic. This function inspects a packet
// that has come in the tap interface. We do not yet have any idea if we care
// about it; it might not even be TLS. It might not even be TCP!
#[no_mangle]
pub extern "C" fn rust_process_packet(ptr: *mut ... | (&mut self,
flow: &Flow,
tcp_pkt: &TcpPacket) -> bool
{
let tag_payload = elligator::extract_telex_tag(&self.priv_key,
&tcp_pkt.payload());
self.stats.elligator_this_period += 1;
... | try_establish_tapdance | identifier_name |
agent.rs | use crate::agent::Capabilities;
use crate::experiments::{Assignee, Experiment};
use crate::prelude::*;
use crate::results::{DatabaseDB, EncodingType, ProgressData};
use crate::server::api_types::{AgentConfig, ApiResponse};
use crate::server::auth::{auth_filter, AuthDetails, TokenType};
use crate::server::messages::Mess... | {
let error = if let Some(compat) = err.find::<Compat<HttpError>>() {
Some(*compat.get_ref())
} else if err.is_not_found() {
Some(HttpError::NotFound)
} else {
None
};
match error {
Some(HttpError::NotFound) => Ok(ApiResponse::not_found().into_response().unwrap()),
... | identifier_body | |
agent.rs | use crate::agent::Capabilities;
use crate::experiments::{Assignee, Experiment};
use crate::prelude::*;
use crate::results::{DatabaseDB, EncodingType, ProgressData};
use crate::server::api_types::{AgentConfig, ApiResponse};
use crate::server::auth::{auth_filter, AuthDetails, TokenType};
use crate::server::messages::Mess... | .1
.wait_while(
self.in_flight_requests
.0
.lock()
.unwrap_or_else(|l| l.into_inner()),
|g| *g!= 0,
)
.unwrap_or_else(|g| g.into_inner()),
);
... | // Ignore the mutex guard (see above).
drop(
self.in_flight_requests | random_line_split |
agent.rs | use crate::agent::Capabilities;
use crate::experiments::{Assignee, Experiment};
use crate::prelude::*;
use crate::results::{DatabaseDB, EncodingType, ProgressData};
use crate::server::api_types::{AgentConfig, ApiResponse};
use crate::server::auth::{auth_filter, AuthDetails, TokenType};
use crate::server::messages::Mess... | ;
Ok(ApiResponse::Success { result }.into_response()?)
}
#[derive(Clone)]
pub struct RecordProgressThread {
// String is the worker name
queue: Sender<(ExperimentData<ProgressData>, String)>,
in_flight_requests: Arc<(Mutex<usize>, Condvar)>,
}
impl RecordProgressThread {
pub fn new(
db: c... | {
None
} | conditional_block |
agent.rs | use crate::agent::Capabilities;
use crate::experiments::{Assignee, Experiment};
use crate::prelude::*;
use crate::results::{DatabaseDB, EncodingType, ProgressData};
use crate::server::api_types::{AgentConfig, ApiResponse};
use crate::server::auth::{auth_filter, AuthDetails, TokenType};
use crate::server::messages::Mess... | {
thread: RecordProgressThread,
}
impl Drop for RequestGuard {
fn drop(&mut self) {
*self
.thread
.in_flight_requests
.0
.lock()
.unwrap_or_else(|l| l.into_inner()) -= 1;
self.thread.in_flight_requests.1.notify_one();
}
}
// This endp... | RequestGuard | identifier_name |
message.rs | //! https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-marshaling
use byteorder::{LittleEndian, BigEndian, ReadBytesExt, ByteOrder, WriteBytesExt};
use crate::names::{BusName, InterfaceName, ErrorName, MemberName};
use crate::writer::{DbusWriter, DbusWrite};
use crate::reader::{DbusReader, DbusR... | <T1, T2>(&self, writer: &mut DbusWriter<T1>) -> Result<(), io::Error>
where T1: io::Write,
T2: ByteOrder
{
writer.write_u8(self.0)
}
}
bitflags! {
struct HeaderFlags: u8 {
/// This message does not expect method return replies or error replies,
/// even if it i... | write | identifier_name |
message.rs | //! https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-marshaling
use byteorder::{LittleEndian, BigEndian, ReadBytesExt, ByteOrder, WriteBytesExt};
use crate::names::{BusName, InterfaceName, ErrorName, MemberName};
use crate::writer::{DbusWriter, DbusWrite};
use crate::reader::{DbusReader, DbusR... | /// The body of the message is made up of zero or more arguments,
/// which are typed values, such as an integer or a byte array.
body: Body,
}
impl Message {
fn write<T>(&self, writer:T) -> Result<(), io::Error>
where T: io::Write
{
let mut writer = DbusWriter::new(writer);
mat... | struct Message {
/// The message delivery system uses the header information to figure out
/// where to send the message and how to interpret it.
header: Header, | random_line_split |
message.rs | //! https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-marshaling
use byteorder::{LittleEndian, BigEndian, ReadBytesExt, ByteOrder, WriteBytesExt};
use crate::names::{BusName, InterfaceName, ErrorName, MemberName};
use crate::writer::{DbusWriter, DbusWrite};
use crate::reader::{DbusReader, DbusR... |
}
struct Body {
}
impl DbusWrite for Body {
fn write<T1, T2>(&self, writer: &mut DbusWriter<T1>) -> Result<(), io::Error>
where T1: io::Write,
T2: ByteOrder {
unimplemented!();
}
} | {
writer.write_u8(self.endianess_flag as u8)?;
writer.write_u8(self.message_type as u8)?;
writer.write_u8(self.flags.bits())?;
writer.write_u8(self.major_protocol_version.0)?;
writer.write_u32::<T2>(self.length_message_body)?;
writer.write_u32::<T2>(self.serial.0)?... | identifier_body |
lib.rs | mod business_logic_layer;
mod data_access_layer;
mod entities;
use crate::business_logic_layer as bll;
pub use crate::data_access_layer::MAX_DATAGRAM_SIZE;
use crate::data_access_layer::{TypedClientSocket, TypedServerSocket};
pub use crate::entities::Exception;
use std::collections::HashMap;
use std::net::{SocketAddr,... | (&mut self, client: &SocketAddr) {
self.servers.remove(&client);
}
pub fn add(&mut self, client: &SocketAddr) {
if!self.servers.contains_key(client) {
self.servers.insert(client.clone(), bll::Server::new());
}
}
pub fn send_to_all(&mut self, state: Vec<u8>) -> Vec<(... | remove | identifier_name |
lib.rs | mod business_logic_layer;
mod data_access_layer;
mod entities;
use crate::business_logic_layer as bll;
pub use crate::data_access_layer::MAX_DATAGRAM_SIZE;
use crate::data_access_layer::{TypedClientSocket, TypedServerSocket};
pub use crate::entities::Exception;
use std::collections::HashMap;
use std::net::{SocketAddr,... |
}
struct ServerSocket {
socket: TypedServerSocket,
servers: HashMap<SocketAddr, bll::Server>,
}
impl ServerSocket {
pub fn new(port: u16) -> Result<ServerSocket, Exception> {
Ok(ServerSocket {
socket: TypedServerSocket::new(port)?,
servers: HashMap::new(),
})
}... | {
let state = self.socket.read()?;
let (state, lost) = self.client.recv(state)?;
for command in lost {
self.socket.write(&command)?;
}
Ok(state)
} | identifier_body |
lib.rs | mod business_logic_layer;
mod data_access_layer;
mod entities;
use crate::business_logic_layer as bll;
pub use crate::data_access_layer::MAX_DATAGRAM_SIZE;
use crate::data_access_layer::{TypedClientSocket, TypedServerSocket};
pub use crate::entities::Exception;
use std::collections::HashMap;
use std::net::{SocketAddr,... |
}
pub fn send_to_all(&mut self, state: Vec<u8>) -> Vec<(SocketAddr, Exception)> {
let mut exceptions = Vec::new();
for (a, s) in &mut self.servers {
let _ = self
.socket
.write(a, &s.send(state.clone()))
.map_err(|e| exceptions.push((*a,... | {
self.servers.insert(client.clone(), bll::Server::new());
} | conditional_block |
lib.rs | mod business_logic_layer;
mod data_access_layer;
mod entities;
use crate::business_logic_layer as bll;
pub use crate::data_access_layer::MAX_DATAGRAM_SIZE;
use crate::data_access_layer::{TypedClientSocket, TypedServerSocket};
pub use crate::entities::Exception;
use std::collections::HashMap;
use std::net::{SocketAddr,... | exceptions
}
}
const DRAW_PERIOD_IN_MILLIS: u64 = 30;
///Game server to run [`Game`]
pub struct GameServer<T: Game> {
game: T,
socket: ServerSocket,
is_running: bool,
draw_timer: bll::timer::WaitTimer,
update_timer: bll::timer::ElapsedTimer,
after_draw_elapsed_timer: bll::timer::El... | let _ = self
.socket
.write(a, &s.send(state.clone()))
.map_err(|e| exceptions.push((*a, e)));
} | random_line_split |
main.rs | #![allow(unused)]
#![allow(non_snake_case)]
use crate::db::MyDbContext;
use serenity::model::prelude::*;
use sqlx::Result;
use serenity::{
async_trait,
client::bridge::gateway::{GatewayIntents, ShardId, ShardManager},
framework::standard::{
buckets::{LimitedFor, RevertBucket},
help_commands... | (ctx: &Context, msg: &Message, error: DispatchError) {
if let DispatchError::Ratelimited(info) = error {
// We notify them only once.
if info.is_first_try {
let _ = msg
.channel_id
.say(
&ctx.http,
&format!("Try this a... | dispatch_error | identifier_name |
main.rs | #![allow(unused)]
#![allow(non_snake_case)]
use crate::db::MyDbContext;
use serenity::model::prelude::*;
use sqlx::Result;
use serenity::{
async_trait,
client::bridge::gateway::{GatewayIntents, ShardId, ShardManager},
framework::standard::{
buckets::{LimitedFor, RevertBucket},
help_commands... | else {
Some(out)
}
}
async fn greet_new_guild(ctx: &Context, guild: &Guild) {
println!("h");
if let Some(channelvec) = better_default_channel(guild, UserId(802019556801511424_u64)).await {
println!("i");
for channel in channelvec {
println!("{}", channel.name);
... | {
None
} | conditional_block |
main.rs | #![allow(unused)]
#![allow(non_snake_case)]
use crate::db::MyDbContext;
use serenity::model::prelude::*;
use sqlx::Result;
use serenity::{
async_trait,
client::bridge::gateway::{GatewayIntents, ShardId, ShardManager},
framework::standard::{
buckets::{LimitedFor, RevertBucket},
help_commands... | pub async fn better_default_channel(guild: &Guild, uid: UserId) -> Option<Vec<&GuildChannel>> {
let member = guild.members.get(&uid)?;
let mut out = vec![];
for channel in guild.channels.values() {
if channel.kind == ChannelType::Text
&& guild
.user_permissions_in(channel... | random_line_split | |
irc_comm.rs | use super::bot_cmd;
use super::irc_msgs::is_msg_to_nick;
use super::irc_msgs::OwningMsgPrefix;
use super::irc_send::push_to_outbox;
use super::irc_send::OutboxPort;
use super::parse_msg_to_nick;
use super::pkg_info;
use super::reaction::LibReaction;
use super::trigger;
use super::BotCmdResult;
use super::ErrorKind;
use... | ));
Ok(())
})?;
}
match wrapped_msg.len() {
0 => Ok(None),
1 => Ok(Some(wrapped_msg.remove(0))),
_ => Ok(Some(LibReaction::Multi(wrapped_msg.into_vec()))),
}
}
fn compose_msgs<S1, S2, M>(
&self,
... | {
let final_msg = format!(
"{}{}{}",
addressee.borrow(),
if addressee.borrow().is_empty() {
""
} else {
&self.addressee_suffix
},
msg,
);
info!("Sending message to {:?}: {:?}", dest, final_ms... | identifier_body |
irc_comm.rs | use super::bot_cmd;
use super::irc_msgs::is_msg_to_nick;
use super::irc_msgs::OwningMsgPrefix;
use super::irc_send::push_to_outbox;
use super::irc_send::OutboxPort;
use super::parse_msg_to_nick;
use super::pkg_info;
use super::reaction::LibReaction;
use super::trigger;
use super::BotCmdResult;
use super::ErrorKind;
use... | <'a>(msg: Option<Cow<'a, str>>) -> LibReaction<Message> {
let quit = aatxe::Command::QUIT(
msg.map(Cow::into_owned)
.or_else(|| Some(pkg_info::BRIEF_CREDITS_STRING.clone())),
).into();
LibReaction::RawMsg(quit)
}
pub(super) fn handle_msg(
state: &Arc<State>,
server_id: ServerId,... | mk_quit | identifier_name |
irc_comm.rs | use super::bot_cmd;
use super::irc_msgs::is_msg_to_nick;
use super::irc_msgs::OwningMsgPrefix;
use super::irc_send::push_to_outbox;
use super::irc_send::OutboxPort;
use super::parse_msg_to_nick;
use super::pkg_info;
use super::reaction::LibReaction;
use super::trigger;
use super::BotCmdResult;
use super::ErrorKind;
use... | state: &Arc<State>,
server_id: ServerId,
outbox: &OutboxPort,
prefix: OwningMsgPrefix,
target: String,
msg: String,
) -> Result<()> {
trace!(
"[{}] Handling PRIVMSG: {:?}",
state.server_socket_addr_dbg_string(server_id),
msg
);
let bot_nick = state.nick(serve... | random_line_split | |
irc_comm.rs | use super::bot_cmd;
use super::irc_msgs::is_msg_to_nick;
use super::irc_msgs::OwningMsgPrefix;
use super::irc_send::push_to_outbox;
use super::irc_send::OutboxPort;
use super::parse_msg_to_nick;
use super::pkg_info;
use super::reaction::LibReaction;
use super::trigger;
use super::BotCmdResult;
use super::ErrorKind;
use... |
_ => Ok(()),
}
}
fn handle_privmsg(
state: &Arc<State>,
server_id: ServerId,
outbox: &OutboxPort,
prefix: OwningMsgPrefix,
target: String,
msg: String,
) -> Result<()> {
trace!(
"[{}] Handling PRIVMSG: {:?}",
state.server_socket_addr_dbg_string(server_id),
... | {
push_to_outbox(outbox, server_id, handle_004(state, server_id)?);
Ok(())
} | conditional_block |
settings.rs | use super::{
AddCertToStore, AddExtraChainCert, DerExportError, FileOpenFailed, FileReadFailed, MaybeTls,
NewStoreBuilder, ParsePkcs12, Pkcs12Error, PrivateKeyParseError, Result, SetCertificate,
SetPrivateKey, SetVerifyCert, TlsError, TlsIdentityError, X509ParseError,
};
use openssl::{
pkcs12::{ParsedPk... |
#[test]
fn from_options_ca() {
let options = TlsOptions {
ca_path: Some("tests/data/Vector_CA.crt".into()),
..Default::default()
};
let settings = TlsSettings::from_options(&Some(options))
.expect("Failed to load authority certificate");
assert... | {
let options = TlsOptions {
crt_path: Some(TEST_PEM_CRT.into()),
key_path: Some(TEST_PEM_KEY.into()),
..Default::default()
};
let settings =
TlsSettings::from_options(&Some(options)).expect("Failed to load PEM certificate");
assert!(settin... | identifier_body |
settings.rs | use super::{
AddCertToStore, AddExtraChainCert, DerExportError, FileOpenFailed, FileReadFailed, MaybeTls,
NewStoreBuilder, ParsePkcs12, Pkcs12Error, PrivateKeyParseError, Result, SetCertificate,
SetPrivateKey, SetVerifyCert, TlsError, TlsIdentityError, X509ParseError,
};
use openssl::{
pkcs12::{ParsedPk... | () {
let options = TlsOptions {
crt_path: Some(TEST_PKCS12.into()),
key_pass: Some("NOPASS".into()),
..Default::default()
};
let settings =
TlsSettings::from_options(&Some(options)).expect("Failed to load PKCS#12 certificate");
assert!(setti... | from_options_pkcs12 | identifier_name |
settings.rs | use super::{
AddCertToStore, AddExtraChainCert, DerExportError, FileOpenFailed, FileReadFailed, MaybeTls,
NewStoreBuilder, ParsePkcs12, Pkcs12Error, PrivateKeyParseError, Result, SetCertificate,
SetPrivateKey, SetVerifyCert, TlsError, TlsIdentityError, X509ParseError,
};
use openssl::{
pkcs12::{ParsedPk... | let name = crt_path.to_string_lossy().to_string();
let cert_data = open_read(crt_path, "certificate")?;
let key_pass: &str = options.key_pass.as_ref().map(|s| s.as_str()).unwrap_or("");
match Pkcs12::from_der(&cert_data) {
// Certifica... | let identity = match options.crt_path {
None => None,
Some(ref crt_path) => { | random_line_split |
layout_rope.rs | //! A rope-based vector of layouts.
use std::ops::Range;
use std::sync::Arc;
use druid::piet::{PietTextLayout, TextLayout};
use xi_rope::interval::{Interval, IntervalBounds};
use xi_rope::tree::{Cursor, DefaultMetric, Leaf, Metric, Node, NodeInfo, TreeBuilder};
/// A type representing a height measure.
///
/// Inte... | (&mut self, index: usize) {
let mut b = TreeBuilder::new();
self.push_subseq(&mut b, Interval::new(0, index));
self.push_subseq(&mut b, Interval::new(index + 1, self.len()));
self.0 = b.build();
}
pub fn set(&mut self, index: usize, item: Layout) {
let mut b = TreeBuilde... | remove | identifier_name |
layout_rope.rs | //! A rope-based vector of layouts.
use std::ops::Range;
use std::sync::Arc;
use druid::piet::{PietTextLayout, TextLayout};
use xi_rope::interval::{Interval, IntervalBounds};
use xi_rope::tree::{Cursor, DefaultMetric, Leaf, Metric, Node, NodeInfo, TreeBuilder};
/// A type representing a height measure.
///
/// Inte... |
fn push_subseq(&self, b: &mut TreeBuilder<LayoutInfo>, iv: Interval) {
// TODO: if we make the push_subseq method in xi-rope public, we can save some
// allocations.
b.push(self.0.subseq(iv));
}
}
impl LayoutRopeBuilder {
pub fn new() -> LayoutRopeBuilder {
LayoutRopeBuild... | {
self.0
.count_base_units::<HeightMetric>(height.as_raw_frac())
} | identifier_body |
layout_rope.rs | //! A rope-based vector of layouts.
use std::ops::Range;
use std::sync::Arc;
use druid::piet::{PietTextLayout, TextLayout};
use xi_rope::interval::{Interval, IntervalBounds};
use xi_rope::tree::{Cursor, DefaultMetric, Leaf, Metric, Node, NodeInfo, TreeBuilder};
/// A type representing a height measure.
///
/// Inte... |
}
}
impl From<Vec<(Height, Arc<Layout>)>> for LayoutRope {
fn from(v: Vec<(Height, Arc<Layout>)>) -> Self {
LayoutRope(Node::from_leaf(LayoutLeaf { data: v }))
}
}
impl LayoutRope {
/// The number of layouts in the rope.
pub fn len(&self) -> usize {
self.0.len()
}
/// The... | {
let splitpoint = self.len() / 2;
let right_vec = self.data.split_off(splitpoint);
Some(LayoutLeaf { data: right_vec })
} | conditional_block |
layout_rope.rs | //! A rope-based vector of layouts.
use std::ops::Range;
use std::sync::Arc;
use druid::piet::{PietTextLayout, TextLayout};
use xi_rope::interval::{Interval, IntervalBounds};
use xi_rope::tree::{Cursor, DefaultMetric, Leaf, Metric, Node, NodeInfo, TreeBuilder};
/// A type representing a height measure.
///
/// Inte... | type Output = Self;
fn add(self, other: Self) -> Self {
Height(self.0 + other.0)
}
}
impl std::ops::AddAssign for Height {
fn add_assign(&mut self, other: Self) {
self.0 += other.0
}
}
impl Height {
/// The number of fractional bits in the representation.
pub const HEIGHT_... | random_line_split | |
embeddings.rs | use std::cmp::Ordering;
use std::collections::hash_map::Entry;
use std::collections::{BinaryHeap, HashMap, HashSet};
use std::iter::Enumerate;
use std::slice;
use failure::Error;
use ndarray::{Array1, Array2, ArrayView1, ArrayView2, Axis};
/// A word similarity.
///
/// This data structure is used to store a pair con... | self.words.push(word.clone());
self.embeddings.push(embedding);
Ok(())
}
}
/// Word embeddings.
///
/// This data structure stores word embeddings (also known as *word vectors*)
/// and provides some useful methods on the embeddings, such as similarity
/// and analogy queries.
pub struct E... | Entry::Vacant(vacant) => vacant.insert(self.words.len()),
Entry::Occupied(_) => bail!(BuilderError::DuplicateWord { word: word }),
};
| random_line_split |
embeddings.rs | use std::cmp::Ordering;
use std::collections::hash_map::Entry;
use std::collections::{BinaryHeap, HashMap, HashSet};
use std::iter::Enumerate;
use std::slice;
use failure::Error;
use ndarray::{Array1, Array2, ArrayView1, ArrayView2, Axis};
/// A word similarity.
///
/// This data structure is used to store a pair con... |
/// Get an iterator over pairs of words and the corresponding embeddings.
pub fn iter(&self) -> Iter {
Iter {
embeddings: self,
inner: self.words.iter().enumerate(),
}
}
/// Normalize the embeddings using their L2 (euclidean) norms.
///
/// **Note:** wh... | {
&self.indices
} | identifier_body |
embeddings.rs | use std::cmp::Ordering;
use std::collections::hash_map::Entry;
use std::collections::{BinaryHeap, HashMap, HashSet};
use std::iter::Enumerate;
use std::slice;
use failure::Error;
use ndarray::{Array1, Array2, ArrayView1, ArrayView2, Axis};
/// A word similarity.
///
/// This data structure is used to store a pair con... |
}
}
impl<'a> PartialOrd for WordSimilarity<'a> {
fn partial_cmp(&self, other: &WordSimilarity) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<'a> Eq for WordSimilarity<'a> {}
impl<'a> PartialEq for WordSimilarity<'a> {
fn eq(&self, other: &WordSimilarity) -> bool {
self.cmp(oth... | {
self.word.cmp(other.word)
} | conditional_block |
embeddings.rs | use std::cmp::Ordering;
use std::collections::hash_map::Entry;
use std::collections::{BinaryHeap, HashMap, HashSet};
use std::iter::Enumerate;
use std::slice;
use failure::Error;
use ndarray::{Array1, Array2, ArrayView1, ArrayView2, Axis};
/// A word similarity.
///
/// This data structure is used to store a pair con... | {
#[fail(
display = "invalid embedding shape, expected: {}, got: {}",
expected_len, len
)]
InvalidEmbeddingLength { expected_len: usize, len: usize },
#[fail(display = "word not unique: {}", word)]
DuplicateWord { word: String },
}
/// Builder for word embedding matrices.
///
/// T... | BuilderError | identifier_name |
utils.rs | use std::cmp::Ordering;
use std::collections::HashSet;
use crate::id;
use serde::{Deserialize, Serialize};
use swc_core::common::{Mark, Span, SyntaxContext, DUMMY_SP};
use swc_core::ecma::ast::{self, Id};
use swc_core::ecma::atoms::{js_word, JsWord};
pub fn match_member_expr(expr: &ast::MemberExpr, idents: Vec<&str>,... | BailoutReason::NonStaticAccess => (
"Non-static access of an `import` or `require`. This causes tree shaking to be disabled for the resolved module.",
"https://parceljs.org/features/scope-hoisting/#dynamic-member-accesses"
),
}
}
}
#[macro_export]
macro_rules! fold_member_expr_skip_pr... | "https://parceljs.org/features/scope-hoisting/#dynamic-imports"
), | random_line_split |
utils.rs | use std::cmp::Ordering;
use std::collections::HashSet;
use crate::id;
use serde::{Deserialize, Serialize};
use swc_core::common::{Mark, Span, SyntaxContext, DUMMY_SP};
use swc_core::ecma::ast::{self, Id};
use swc_core::ecma::atoms::{js_word, JsWord};
pub fn match_member_expr(expr: &ast::MemberExpr, idents: Vec<&str>,... | (specifier: swc_core::ecma::atoms::JsWord) -> ast::CallExpr {
let mut normalized_specifier = specifier;
if normalized_specifier.starts_with("node:") {
normalized_specifier = normalized_specifier.replace("node:", "").into();
}
ast::CallExpr {
callee: ast::Callee::Expr(Box::new(ast::Expr::Ident(ast::Iden... | create_require | identifier_name |
utils.rs | use std::cmp::Ordering;
use std::collections::HashSet;
use crate::id;
use serde::{Deserialize, Serialize};
use swc_core::common::{Mark, Span, SyntaxContext, DUMMY_SP};
use swc_core::ecma::ast::{self, Id};
use swc_core::ecma::atoms::{js_word, JsWord};
pub fn match_member_expr(expr: &ast::MemberExpr, idents: Vec<&str>,... |
}
MemberProp::Ident(Ident { ref sym,.. }) => sym,
_ => return false,
};
if prop!= expected {
return false;
}
match &*member.obj {
Expr::Member(m) => member = m,
Expr::Ident(id) => {
return idents.len() == 1 && &id.sym == idents.pop().unwrap() &&!decls.conta... | {
return false;
} | conditional_block |
projectstate.rs | use std::collections::HashMap;
use std::fmt;
use std::mem;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Instant;
use chrono::{DateTime, Utc};
use parking_lot::RwLock;
use serde::de::DeserializeOwned;
use url::Url;
use uuid::Uuid;
use config::AortaConfig;
use event::StoreChangeset;... |
/// Returns the time of the last config fetch.
pub fn last_config_fetch(&self) -> Option<DateTime<Utc>> {
self.current_snapshot
.read()
.as_ref()
.map(|x| x.last_fetch.clone())
}
/// Returns the time of the last config change.
pub fn last_config_change(&se... | {
*self.last_event.read()
} | identifier_body |
projectstate.rs | use std::collections::HashMap;
use std::fmt;
use std::mem;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Instant;
use chrono::{DateTime, Utc};
use parking_lot::RwLock;
use serde::de::DeserializeOwned;
use url::Url;
use uuid::Uuid;
use config::AortaConfig;
use event::StoreChangeset;... | {
/// URLs that are permitted for cross original JavaScript requests.
pub allowed_domains: Vec<String>,
}
/// The project state snapshot represents a known server state of
/// a project.
///
/// This is generally used by an indirection of `ProjectState` which
/// manages a view over it which supports concurre... | ProjectConfig | identifier_name |
projectstate.rs | use std::collections::HashMap;
use std::fmt;
use std::mem;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Instant;
use chrono::{DateTime, Utc};
use parking_lot::RwLock;
use serde::de::DeserializeOwned;
use url::Url;
use uuid::Uuid;
use config::AortaConfig;
use event::StoreChangeset;... | .and_then(|x| x.last_change.clone())
}
/// Requests an update to the project config to be fetched.
pub fn request_updated_project_config(&self) {
if self.requested_new_snapshot
.compare_and_swap(false, true, Ordering::Relaxed)
{
return;
}
d... | random_line_split | |
network_context.rs | },
time::{Duration, SystemTime},
};
use crate::blocks::{FullTipset, Tipset, TipsetKeys};
use crate::libp2p::{
chain_exchange::{
ChainExchangeRequest, ChainExchangeResponse, CompactedMessages, TipsetBundle, HEADERS,
MESSAGES,
},
hello::{HelloRequest, HelloResponse},
rpc::RequestResp... | .await
.is_ok();
match self.db.get_cbor(&content) {
Ok(Some(b)) => Ok(b),
Ok(None) => Err(format!(
"Not found in db, bitswap. success: {success} cid, {content:?}"
)),
Err(e) => Err(format!(
"Error retrieving from db. ... | {
// Check if what we are fetching over Bitswap already exists in the
// database. If it does, return it, else fetch over the network.
if let Some(b) = self.db.get_cbor(&content).map_err(|e| e.to_string())? {
return Ok(b);
}
let (tx, rx) = flume::bounded(1);
... | identifier_body |
network_context.rs | },
time::{Duration, SystemTime},
};
use crate::blocks::{FullTipset, Tipset, TipsetKeys};
use crate::libp2p::{
chain_exchange::{
ChainExchangeRequest, ChainExchangeResponse, CompactedMessages, TipsetBundle, HEADERS,
MESSAGES,
},
hello::{HelloRequest, HelloResponse},
rpc::RequestResp... | (
network_send: flume::Sender<NetworkMessage>,
peer_manager: Arc<PeerManager>,
db: Arc<DB>,
) -> Self {
Self {
network_send,
peer_manager,
db,
}
}
/// Returns a reference to the peer manager of the network context.
pub fn peer_... | new | identifier_name |
network_context.rs | },
time::{Duration, SystemTime},
};
use crate::blocks::{FullTipset, Tipset, TipsetKeys};
use crate::libp2p::{
chain_exchange::{
ChainExchangeRequest, ChainExchangeResponse, CompactedMessages, TipsetBundle, HEADERS,
MESSAGES,
},
hello::{HelloRequest, HelloResponse},
rpc::RequestResp... |
}
}
Err(e) => {
network_failures.fetch_add(1, Ordering::Relaxed);
debug!("Failed chain_exchange request to peer {peer_id:?}: {e}");
Err... | {
lookup_failures.fetch_add(1, Ordering::Relaxed);
debug!("Failed chain_exchange response: {e}");
Err(e)
} | conditional_block |
network_context.rs | },
time::{Duration, SystemTime}, | use crate::blocks::{FullTipset, Tipset, TipsetKeys};
use crate::libp2p::{
chain_exchange::{
ChainExchangeRequest, ChainExchangeResponse, CompactedMessages, TipsetBundle, HEADERS,
MESSAGES,
},
hello::{HelloRequest, HelloResponse},
rpc::RequestResponseError,
NetworkMessage, PeerId, Pee... | };
| random_line_split |
main.rs | _num() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1, 101);
loop {
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
let guess... | // }
//// Item is the placeholder type.
///
// 4. Fully Qualified Syntax for Disambiguation: Calling Methods with the Same Name
trait Pilot {
fn fly(&self);
}
trait Wizard {
fn fly(&self);
}
struct Human;
impl Pilot for Human {
fn fly(&self) {
println!("This is your captain speaking. Pilot!");
... | random_line_split | |
main.rs | _num() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1, 101);
loop {
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
let guess... | );
}
struct Duck();
impl Quack for Duck {
fn quack(&self) {
println!("quack!");
}
}
struct RandomBird {
is_a_parrot: bool,
}
impl Quack for RandomBird {
fn quack(&self) {
if!self.is_a_parrot {
println!("quack!");
} else {
println!("squawk!");
}... | self | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.