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
hls_live.rs
} let mut all_mimes = self.all_mimes.clone(); all_mimes.sort(); all_mimes.dedup(); let playlist = MasterPlaylist { version: Some(7), variants: self .video_streams .iter() .map(|stream| { let m...
fn update_manifest(state: &mut StreamState) { // Now write the manifest let mut path = state.path.clone(); path.push("manifest.m3u8"); println!("writing manifest to {}", path.display()); trim_segments(state); let playlist = MediaPlaylist { version: Some(7), target_duration: 2....
break; } } }
random_line_split
hls_live.rs
} let mut all_mimes = self.all_mimes.clone(); all_mimes.sort(); all_mimes.dedup(); let playlist = MasterPlaylist { version: Some(7), variants: self .video_streams .iter() .map(|stream| { let mu...
first = buffer_list.get(0).unwrap(); } // If the buffer only has the HEADER flag set then this is a segment header that is // followed by one or more actual media buffers. assert!(first.flags().contains(gst::BufferFlags::HEADER)); ...
{ let mut path = state.path.clone(); std::fs::create_dir_all(&path).expect("failed to create directory"); path.push("init.cmfi"); println!("writing header to {}", path.display()); let map = first.map_readable().unwrap()...
conditional_block
hls_live.rs
} let mut all_mimes = self.all_mimes.clone(); all_mimes.sort(); all_mimes.dedup(); let playlist = MasterPlaylist { version: Some(7), variants: self .video_streams .iter() .map(|stream| { let mu...
// The muxer only outputs non-empty buffer lists let mut buffer_list = sample.buffer_list_owned().expect("no buffer list"); assert!(!buffer_list.is_empty()); let mut first = buffer_list.get(0).unwrap(); // Each list contains a full segmen...
{ let mut path: PathBuf = path.into(); path.push(name); let state = Arc::new(Mutex::new(StreamState { segments: VecDeque::new(), trimmed_segments: VecDeque::new(), path, start_date_time: None, start_time: gst::ClockTime::NONE, media_sequence: 0, segme...
identifier_body
hls_live.rs
} let mut all_mimes = self.all_mimes.clone(); all_mimes.sort(); all_mimes.dedup(); let playlist = MasterPlaylist { version: Some(7), variants: self .video_streams .iter() .map(|stream| { let mu...
{ name: String, bitrate: u64, width: u64, height: u64, } struct AudioStream { name: String, lang: String, default: bool, wave: String, } fn trim_segments(state: &mut StreamState) { // Arbitrary 5 segments window while state.segments.len() > 5 { let segment = state.segm...
VideoStream
identifier_name
mod.rs
use std::collections::HashMap; use std::borrow::Cow; use chrono::{DateTime, Utc, NaiveDateTime}; use log; pub use self::chunked_message::{ChunkSize, ChunkedMessage}; pub use self::compression::MessageCompression; pub use self::wire_message::WireMessage; use crate::{Level, util, Error}; use crate::errors::Result; use ...
/// Return a metadata field with given key pub fn metadata(&self, key: &'a str) -> Option<&Cow<'a, str>> { self.metadata.get(key) } /// Return all metadata pub fn all_metadata(&self) -> &HashMap<Cow<'a, str>, Cow<'a, str>> { &self.metadata } /// Set a metadata field with ...
{ self.level = level; self }
identifier_body
mod.rs
use std::collections::HashMap; use std::borrow::Cow; use chrono::{DateTime, Utc, NaiveDateTime}; use log; pub use self::chunked_message::{ChunkSize, ChunkedMessage}; pub use self::compression::MessageCompression; pub use self::wire_message::WireMessage; use crate::{Level, util, Error}; use crate::errors::Result; use ...
<S>( short_message: S, level: Level, ) -> Self where S: Into<Cow<'a, str>> + AsRef<str> { Message { short_message: short_message.into(), level, full_message: None, timestamp: None, metadata: HashMap::new(), ...
new_with_level
identifier_name
mod.rs
use std::collections::HashMap; use std::borrow::Cow; use chrono::{DateTime, Utc, NaiveDateTime}; use log; pub use self::chunked_message::{ChunkSize, ChunkedMessage}; pub use self::compression::MessageCompression; pub use self::wire_message::WireMessage; use crate::{Level, util, Error}; use crate::errors::Result; use ...
self } /// Return the `level` pub fn level(&self) -> Level { self.level } /// Set the `level` pub fn set_level(&mut self, level: Level) -> &mut Self { self.level = level; self } /// Return a metadata field with given key pub fn metadata(&self, key: ...
/// Clear the `timestamp` pub fn clear_timestamp(&mut self) -> &mut Self { self.timestamp = None;
random_line_split
main.rs
#[macro_use] extern crate log; extern crate mio_multithread_unix; extern crate env_logger; extern crate httparse; extern crate mio; extern crate net2; extern crate num_cpus; extern crate slab; extern crate time; use std::ascii::AsciiExt; use std::env; use std::fmt; use std::io::{self, Read, Write}; use std::mem; use s...
struct Connection { socket: TcpStream, input: Vec<u8>, output: Output, keepalive: bool, closed: bool, read_closed: bool, events: EventSet, } struct Output { buf: Vec<u8>, } impl Connection { fn new(socket: TcpStream) -> Connection { Connection { socket: socket,...
random_line_split
main.rs
#[macro_use] extern crate log; extern crate mio_multithread_unix; extern crate env_logger; extern crate httparse; extern crate mio; extern crate net2; extern crate num_cpus; extern crate slab; extern crate time; use std::ascii::AsciiExt; use std::env; use std::fmt; use std::io::{self, Read, Write}; use std::mem; use s...
<'a> { count: u64, listener: &'a TcpListener, connections: Slab<Connection, usize>, } impl<'a> Server<'a> { fn new(listener: &'a TcpListener) -> Server<'a> { Server { count: 0, listener: listener, connections: Slab::new_starting_at(1, 1024), } } ...
Server
identifier_name
parser.rs
use crate::error::Error; use crate::resolve_import::resolve_import; use std::sync::Arc; use std::sync::Mutex; use swc_common::comments::SingleThreadedComments; use swc_common::errors::Diagnostic; use swc_common::errors::DiagnosticBuilder; use swc_common::errors::Emitter; use swc_common::errors::Handler; use swc_common:...
() { let url = Url::parse("https://deno.land/x/oak@v6.4.2/router.ts").unwrap(); let source = r#" delete<P extends RouteParams = RP, S extends State = RS>( name: string, path: string, ...middleware: RouterMiddleware<P, S>[] ): Router<P extends RP? P : (P & RP), S extends RS? S ...
complex_types
identifier_name
parser.rs
use crate::error::Error; use crate::resolve_import::resolve_import; use std::sync::Arc; use std::sync::Mutex; use swc_common::comments::SingleThreadedComments; use swc_common::errors::Diagnostic; use swc_common::errors::DiagnosticBuilder; use swc_common::errors::Emitter; use swc_common::errors::Handler; use swc_common:...
#[test] fn jsx() { let url = Url::parse( "https://deno.land/x/dext@0.10.3/example/pages/dynamic/%5Bname%5D.tsx", ) .unwrap(); let source = r#" import { Fragment, h } from "../../deps.ts"; import type { PageProps } from "../../deps.ts"; function UserPage(props: PageProps) { ...
{ // Prefer content-type over extension. let url = Url::parse("https://deno.land/x/foo@0.1.0/bar.js").unwrap(); let content_type = Some("text/jsx".to_string()); let syntax = get_syntax(&url, &content_type); assert!(syntax.jsx()); assert!(!syntax.typescript()); // Fallback to extension if co...
identifier_body
parser.rs
use crate::error::Error; use crate::resolve_import::resolve_import; use std::sync::Arc; use std::sync::Mutex; use swc_common::comments::SingleThreadedComments; use swc_common::errors::Diagnostic; use swc_common::errors::DiagnosticBuilder; use swc_common::errors::Emitter; use swc_common::errors::Handler; use swc_common:...
let syntax = get_syntax(&url, &content_type); assert!(syntax.jsx()); assert!(!syntax.typescript()); // Fallback to extension if content-type is unsupported. let url = Url::parse("https://deno.land/x/foo@0.1.0/bar.tsx").unwrap(); let content_type = Some("text/unsupported".to_string()); let s...
fn test_get_syntax() { // Prefer content-type over extension. let url = Url::parse("https://deno.land/x/foo@0.1.0/bar.js").unwrap(); let content_type = Some("text/jsx".to_string());
random_line_split
main.rs
use once_cell::sync::Lazy; use libp2p::{PeerId, Transport, mplex, Swarm, NetworkBehaviour}; use libp2p::identity; use libp2p::floodsub::{Topic, Floodsub, FloodsubEvent}; use libp2p::noise::{X25519Spec, Keypair, NoiseConfig}; use libp2p::tcp::TokioTcpConfig; use libp2p::core::upgrade; use libp2p::mdns::{TokioMdns, MdnsE...
{ floodsub: Floodsub, mdns: TokioMdns, #[behaviour(ignore)] response_sender: mpsc::UnboundedSender<ListResponse>, } #[tokio::main] async fn main() { pretty_env_logger::init(); info!("Peer Id: {}", PEER_ID.clone()); let (response_sender, mut response_rcv) = tokio::sync::mpsc::unbounded_cha...
RecipeBehaviour
identifier_name
main.rs
use once_cell::sync::Lazy; use libp2p::{PeerId, Transport, mplex, Swarm, NetworkBehaviour}; use libp2p::identity; use libp2p::floodsub::{Topic, Floodsub, FloodsubEvent}; use libp2p::noise::{X25519Spec, Keypair, NoiseConfig}; use libp2p::tcp::TokioTcpConfig; use libp2p::core::upgrade; use libp2p::mdns::{TokioMdns, MdnsE...
}); write_local_recipes(&local_recipes).await?; info!("create recipe:"); info!("name: {}", name); info!("ingredients: {}", ingredients); info!("instruments: {}", instructions); Ok(()) } async fn publish_recipe(id: usize) -> Result<()> { let mut local_recipes = read_local_recipes().awai...
id: new_id, name: name.to_owned(), ingredients: ingredients.to_owned(), instructions: instructions.to_owned(), public: false
random_line_split
main.rs
use once_cell::sync::Lazy; use libp2p::{PeerId, Transport, mplex, Swarm, NetworkBehaviour}; use libp2p::identity; use libp2p::floodsub::{Topic, Floodsub, FloodsubEvent}; use libp2p::noise::{X25519Spec, Keypair, NoiseConfig}; use libp2p::tcp::TokioTcpConfig; use libp2p::core::upgrade; use libp2p::mdns::{TokioMdns, MdnsE...
} } } fn respond_with_publish_recipes(sender: mpsc::UnboundedSender<ListResponse>, receiver: String) { tokio::spawn(async move { match read_local_recipes().await { Ok(recipes) => { let resp = ListResponse { mode: ListMode::ALL, ...
{ error!("error creating recipe: {}", e); }
conditional_block
main.rs
use once_cell::sync::Lazy; use libp2p::{PeerId, Transport, mplex, Swarm, NetworkBehaviour}; use libp2p::identity; use libp2p::floodsub::{Topic, Floodsub, FloodsubEvent}; use libp2p::noise::{X25519Spec, Keypair, NoiseConfig}; use libp2p::tcp::TokioTcpConfig; use libp2p::core::upgrade; use libp2p::mdns::{TokioMdns, MdnsE...
async fn write_local_recipes(recipes: &Recipes) -> Result<()> { let json = serde_json::to_string(&recipes)?; tokio::fs::write(STORAGE_FILE_PATH, &json).await?; Ok(()) }
{ let content = tokio::fs::read(STORAGE_FILE_PATH).await?; let result = serde_json::from_slice(&content)?; Ok(result) }
identifier_body
scheduler.rs
//! Scheduler is responsible for allocating containers on cluster nodes according to the currently //! submitted jobs and concurrency levels. It is only used on the master node. use crate::executor::*; use actix::fut::wrap_future; use actix::prelude::*; use actix::registry::SystemService; use actix::spawn; use actix_w...
() { let job: JobSpec = serde_yaml::from_str(TEST_JOB_SPEC).expect("Failed to parse sample job spec"); with_bootstrap_node(|| { Scheduler::from_registry() .send(SchedulerCommand::CreateJob(String::from("test-job"), job)) .and_then(move |res| { ...
test_create_job
identifier_name
scheduler.rs
//! Scheduler is responsible for allocating containers on cluster nodes according to the currently //! submitted jobs and concurrency levels. It is only used on the master node. use crate::executor::*; use actix::fut::wrap_future; use actix::prelude::*; use actix::registry::SystemService; use actix::spawn; use actix_w...
} // Remove any allocations that don't correspond to any service for allocs in service_allocs.values() { to_remove.extend(allocs.iter().cloned()); } // Now we drop the index service_allocs and we can mutate the state for alloc_id in to_remove { s...
to_remove.extend(existing.iter().take(diff.abs() as usize).cloned()); } }
random_line_split
scheduler.rs
//! Scheduler is responsible for allocating containers on cluster nodes according to the currently //! submitted jobs and concurrency levels. It is only used on the master node. use crate::executor::*; use actix::fut::wrap_future; use actix::prelude::*; use actix::registry::SystemService; use actix::spawn; use actix_w...
}
{ let job: JobSpec = serde_yaml::from_str(TEST_JOB_SPEC).expect("Failed to parse sample job spec"); with_bootstrap_node(|| { Scheduler::from_registry() .send(SchedulerCommand::CreateJob(String::from("test-job"), job)) .and_then(move |res| { ...
identifier_body
lib.rs
//! Write your own tests and benchmarks that look and behave like built-in tests! //! //! This is a simple and small test harness that mimics the original `libtest` //! (used by `cargo test`/`rustc --test`). That means: all output looks pretty //! much like `cargo test` and most CLI arguments are understood and used. W...
for skip_filter in &self.skip { match self.exact { true if test_name == skip_filter => return true, false if test_name.contains(skip_filter) => return true, _ => {} } } if self.ignored &&!test.info.is_ignored { ...
_ => {} }; } // If any skip pattern were specified, test for all patterns.
random_line_split
lib.rs
//! Write your own tests and benchmarks that look and behave like built-in tests! //! //! This is a simple and small test harness that mimics the original `libtest` //! (used by `cargo test`/`rustc --test`). That means: all output looks pretty //! much like `cargo test` and most CLI arguments are understood and used. W...
{ /// The test passed. Passed, /// The test or benchmark failed. Failed(Failed), /// The test or benchmark was ignored. Ignored, /// The benchmark was successfully run. Measured(Measurement), } /// Contains information about the entire test run. Is returned by[`run`]. /// /// This t...
Outcome
identifier_name
lib.rs
//! Write your own tests and benchmarks that look and behave like built-in tests! //! //! This is a simple and small test harness that mimics the original `libtest` //! (used by `cargo test`/`rustc --test`). That means: all output looks pretty //! much like `cargo test` and most CLI arguments are understood and used. W...
/// Creates a benchmark with the given name and runner. /// /// If the runner's parameter `test_mode` is `true`, the runner function /// should run all code just once, without measuring, just to make sure it /// does not panic. If the parameter is `false`, it should perform the /// actual benc...
{ Self { runner: Box::new(move |_test_mode| match runner() { Ok(()) => Outcome::Passed, Err(failed) => Outcome::Failed(failed), }), info: TestInfo { name: name.into(), kind: String::new(), is_igno...
identifier_body
websocket.rs
use serde_json; use ws::{listen, Handler, Factory, Sender, Handshake, Request, Response as WsResponse, Message, CloseCode}; use ws::{Error as WsError, ErrorKind as WsErrorKind, Result as WsResult}; use graph::{PossibleErr as GraphErr, *}; use std::thread; use std::thread::{JoinHandle}; use std::fmt; use std::result; ...
fn encode_update<T: Into<Update>>(update: T) -> WsResult<Message>{ match serde_json::to_string(&update.into()){ Ok(s) => Ok(Message::Text(s)), Err(e) => Err(WsError::new(WsErrorKind::Internal, format!("encode_update failed {:?}", e))) } } struct ClientCommon; impl ClientCommon{ fn on_ope...
{ match serde_json::to_string(&response){ Ok(s) => Ok(Message::Text(s)), Err(e) => Err(WsError::new(WsErrorKind::Internal, format!("encode_response failed {:?}", e))) } }
identifier_body
websocket.rs
use serde_json; use ws::{listen, Handler, Factory, Sender, Handshake, Request, Response as WsResponse, Message, CloseCode}; use ws::{Error as WsError, ErrorKind as WsErrorKind, Result as WsResult}; use graph::{PossibleErr as GraphErr, *}; use std::thread; use std::thread::{JoinHandle}; use std::fmt; use std::result; ...
} impl Factory for ServerFactory{ type Handler = ServerHandler; fn connection_made(&mut self, out: Sender) -> Self::Handler{ ServerHandler{ out, store: self.store.clone(), state: ClientState::AwaitingType, addr: "0.0.0.0:0".into() } } } pu...
struct ServerFactory{ store: GraphStore,
random_line_split
websocket.rs
use serde_json; use ws::{listen, Handler, Factory, Sender, Handshake, Request, Response as WsResponse, Message, CloseCode}; use ws::{Error as WsError, ErrorKind as WsErrorKind, Result as WsResult}; use graph::{PossibleErr as GraphErr, *}; use std::thread; use std::thread::{JoinHandle}; use std::fmt; use std::result; ...
(out: &Sender, store: &GraphStore, id: GraphId) -> Result<Self>{ ClientCommon::on_open(out, store, id, ClientType::Backend)?; trace!("Backend attached to GraphId {}", id); Ok(BackendClient{ graph: id }) } fn on_command(&self, out: &Sender, store: &GraphStore, command:...
on_open
identifier_name
v2.rs
use std::fs::{File, OpenOptions}; use std::io::Write; use std::path::{Path, PathBuf}; use serde_json::{Deserializer, Value}; use tempfile::NamedTempFile; use crate::index_controller::dump_actor::loaders::compat::{asc_ranking_rule, desc_ranking_rule}; use crate::index_controller::dump_actor::Metadata; use crate::index...
patch_updates(update_dir, update_path)?; v3::load_dump( meta, src, dst, index_db_size, update_db_size, indexing_options, ) } fn patch_index_uuid_path(path: &Path) -> Option<PathBuf> { let uuid = path.file_name()?.to_str()?.trim_start_matches("index-"); ...
{ let indexes_path = src.as_ref().join("indexes"); let dir_entries = std::fs::read_dir(indexes_path)?; for entry in dir_entries { let entry = entry?; // rename the index folder let path = entry.path(); let new_path = patch_index_uuid_path(&path).expect("invalid index folder...
identifier_body
v2.rs
use std::fs::{File, OpenOptions}; use std::io::Write; use std::path::{Path, PathBuf}; use serde_json::{Deserializer, Value}; use tempfile::NamedTempFile; use crate::index_controller::dump_actor::loaders::compat::{asc_ranking_rule, desc_ranking_rule}; use crate::index_controller::dump_actor::Metadata; use crate::index...
(path: &Path) -> Option<PathBuf> { let uuid = path.file_name()?.to_str()?.trim_start_matches("index-"); let new_path = path.parent()?.join(uuid); Some(new_path) } fn patch_settings(path: impl AsRef<Path>) -> anyhow::Result<()> { let mut meta_file = File::open(&path)?; let mut meta: Value = serde_js...
patch_index_uuid_path
identifier_name
v2.rs
use std::fs::{File, OpenOptions}; use std::io::Write; use std::path::{Path, PathBuf}; use serde_json::{Deserializer, Value}; use tempfile::NamedTempFile; use crate::index_controller::dump_actor::loaders::compat::{asc_ranking_rule, desc_ranking_rule}; use crate::index_controller::dump_actor::Metadata; use crate::index...
compat::UpdateResult::DocumentsAddition(r) => Self::DocumentsAddition(r), compat::UpdateResult::DocumentDeletion { deleted } => { Self::DocumentDeletion { deleted } } compat::UpdateResult::Other => Self::Other, } } } /// compat structure from ...
impl From<compat::UpdateResult> for UpdateResult { fn from(other: compat::UpdateResult) -> Self { match other {
random_line_split
lib.rs
//! This crate contains structures and generators for specifying how to generate //! historical and real-time test data for Delorean. The rules for how to //! generate data and what shape it should take can be specified in a TOML file. //! //! Generators can output in line protocol, Parquet, or can be used to generate ...
let data_points = agent.generate().await?; assert!( data_points.is_empty(), "expected no data points, got {:?}", data_points ); Ok(()) } }
let expected_line_protocol = "cpu up=f 10000000000\n"; assert_eq!(line_protocol, expected_line_protocol); // Don't get any points anymore because we're past the ending datetime
random_line_split
lib.rs
//! This crate contains structures and generators for specifying how to generate //! historical and real-time test data for Delorean. The rules for how to //! generate data and what shape it should take can be specified in a TOML file. //! //! Generators can output in line protocol, Parquet, or can be used to generate ...
(&mut self, dest: &mut [u8]) { self.rng.fill_bytes(dest); } fn try_fill_bytes(&mut self, dest: &mut [u8]) -> std::result::Result<(), rand::Error> { self.rng.try_fill_bytes(dest) } } /// Gets the current time in nanoseconds since the epoch pub fn now_ns() -> i64 { let since_the_epoch = ...
fill_bytes
identifier_name
lib.rs
//! This crate contains structures and generators for specifying how to generate //! historical and real-time test data for Delorean. The rules for how to //! generate data and what shape it should take can be specified in a TOML file. //! //! Generators can output in line protocol, Parquet, or can be used to generate ...
/// Generate a random GUID pub fn guid(&mut self) -> uuid::Uuid { let mut bytes = [0u8; 16]; self.rng.fill_bytes(&mut bytes); uuid::Builder::from_bytes(bytes) .set_variant(uuid::Variant::RFC4122) .set_version(uuid::Version::Random) .build() } } imp...
{ let seed = seed.into(); Self { rng: Seeder::from(&seed).make_rng(), seed, } }
identifier_body
lib.rs
//! This crate contains structures and generators for specifying how to generate //! historical and real-time test data for Delorean. The rules for how to //! generate data and what shape it should take can be specified in a TOML file. //! //! Generators can output in line protocol, Parquet, or can be used to generate ...
let mut agent = agent::Agent::<T>::new( agent_spec, &agent_name, agent_id, &seed, agent_tags, start_datetime, end_datetime, execution_start_time, continue_on, ...
{ agent_tags.push(tag::Tag::new(name_tag_key, &agent_name)); }
conditional_block
main.rs
message)); } } } else { PickYourAuth::None(NoToken) }; let bindle_client = Client::new(&opts.server_url, token)?; let local = bindle::provider::file::FileProvider::new( bindle_dir, bindle::search::NoopEngine::default(), ) .await; let cache = DumbC...
.into_inner(), ) .await?; }
random_line_split
main.rs
.await? } Some(format) => { return Err(ClientError::Other(format!("Unknown format: {}", format))) } None => tokio::io::stdout().write_all(&toml::to_vec(&inv)?).await?, } } SubCommand::GetInvoice(gi_opts) => {...
{ match name.as_str() { "c" | "creator" => Ok(SignatureRole::Creator), "h" | "host" => Ok(SignatureRole::Host), "a" | "approver" => Ok(SignatureRole::Approver), "p" | "proxy" => Ok(SignatureRole::Proxy), _ => Err(ClientError::Other("Unknown role".to_owned())), } }
identifier_body
main.rs
} } else { PickYourAuth::None(NoToken) }; let bindle_client = Client::new(&opts.server_url, token)?; let local = bindle::provider::file::FileProvider::new( bindle_dir, bindle::search::NoopEngine::default(), ) .await; let cache = DumbCache::new(bindle_client.cl...
load_keyring
identifier_name
fsevents.rs
#![allow(non_camel_case_types, non_uppercase_statics)] // C types use std::collections::{HashSet}; use std::c_str::CString; use std::io::{IoError, IoResult}; use std::io::fs::PathExtensions; use std::mem; use std::ptr; use std::raw::Slice; use std::os; use std::io::{Timer}; use std::time::Duration; //use super; use ...
data: events, len: size as uint, }) }; let ids: &[u64] = unsafe { mem::transmute(Slice { data: ids, len: size as uint, }) }; let paths: &[*const i8] = unsafe { mem::transmute(Slice { data: paths, le...
let events: &[u32] = unsafe { mem::transmute(Slice {
random_line_split
fsevents.rs
#![allow(non_camel_case_types, non_uppercase_statics)] // C types use std::collections::{HashSet}; use std::c_str::CString; use std::io::{IoError, IoResult}; use std::io::fs::PathExtensions; use std::mem; use std::ptr; use std::raw::Slice; use std::os; use std::io::{Timer}; use std::time::Duration; //use super; use ...
Exit => { debug!("Received watcher exit event - performing graceful shutdown"); break } } } } }); watcher } pub fn watch(&mut self, path: &Pa...
{ debug!("Updating watcher loop with {}", paths); *stream.lock() = recreate_stream(*eventloop.lock(), &context, paths); CFRunLoopRun(); }
conditional_block
fsevents.rs
#![allow(non_camel_case_types, non_uppercase_statics)] // C types use std::collections::{HashSet}; use std::c_str::CString; use std::io::{IoError, IoResult}; use std::io::fs::PathExtensions; use std::mem; use std::ptr; use std::raw::Slice; use std::os; use std::io::{Timer}; use std::time::Duration; //use super; use ...
{ Create(String), Remove(String), //ModifyMeta, Modify(String), RenameOld(String), RenameNew(String), } enum Control { Update(HashSet<String>), Exit, } #[repr(C)] struct FSEventStreamContext { version: c_int, info: *mut c_void, retain: *const c_void, release: *const c_...
Event
identifier_name
fsevents.rs
#![allow(non_camel_case_types, non_uppercase_statics)] // C types use std::collections::{HashSet}; use std::c_str::CString; use std::io::{IoError, IoResult}; use std::io::fs::PathExtensions; use std::mem; use std::ptr; use std::raw::Slice; use std::os; use std::io::{Timer}; use std::time::Duration; //use super; use ...
}
{ super::Unknown }
identifier_body
kmodules.rs
//! This file contains all the stuff needed by Kernel Modules use super::message::push_message; use super::process::get_file_content; use super::scheduler::Scheduler; use super::thread_group::Credentials; use super::vfs::{Path, VFS}; use super::{IpcResult, SysResult}; use alloc::boxed::Box; use alloc::vec::Vec; use an...
(s: &str) { eprint!("{}", s); } /// Just used for a symbol list test #[no_mangle] #[link_section = ".kernel_exported_functions"] pub fn symbol_list_test() { log::info!("symbol_list_test function sucessfully called by a module!"); } #[no_mangle] #[link_section = ".kernel_exported_functions"] pub fn add_syslog_...
emergency_write
identifier_name
kmodules.rs
//! This file contains all the stuff needed by Kernel Modules use super::message::push_message; use super::process::get_file_content; use super::scheduler::Scheduler; use super::thread_group::Credentials; use super::vfs::{Path, VFS}; use super::{IpcResult, SysResult}; use alloc::boxed::Box; use alloc::vec::Vec; use an...
.as_mut_ptr() .write_bytes(0, h.memsz as usize - h.filez as usize); // Modify the rights on pages by following the ELF specific restrictions HIGH_KERNEL_MEMORY .as_mut() .unwrap() .change_range...
// With BSS (so a NOBITS section), the memsz value exceed the filesz. Setting next bytes as 0 segment[h.filez as usize..h.memsz as usize]
random_line_split
kmodules.rs
//! This file contains all the stuff needed by Kernel Modules use super::message::push_message; use super::process::get_file_content; use super::scheduler::Scheduler; use super::thread_group::Credentials; use super::vfs::{Path, VFS}; use super::{IpcResult, SysResult}; use alloc::boxed::Box; use alloc::vec::Vec; use an...
ModConfig::Keyboard(KeyboardConfig { enable_irq, disable_irq, callback: push_message, }), ), "syslog" => ( &mut self.kernel_modules.syslog, "/turbofish/mod/syslog.mod", ...
{ let (module_opt, module_pathname, mod_config) = match modname { "dummy" => ( &mut self.kernel_modules.dummy, "/turbofish/mod/dummy.mod", ModConfig::Dummy, ), "rtc" => ( &mut self.kernel_modules.rtc, ...
identifier_body
mod.rs
#![warn(missing_docs)] //! Contains all structures and methods to create and manage scenes. //! //! Scene is container for graph nodes, animations and physics. pub mod base; pub mod camera; pub mod graph; pub mod light; pub mod mesh; pub mod node; pub mod particle_system; pub mod sprite; pub mod transform; use crate...
} Self { graph, animations, physics, physics_binder, render_target: Default::default(), lightmap: self.lightmap.clone(), } } } impl Visit for Scene { fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitR...
{ // Re-use of body handle is fine here because physics copy bodies // directly and handles from previous pool is still suitable for copy. physics_binder.bind(new_node, body); }
conditional_block
mod.rs
#![warn(missing_docs)] //! Contains all structures and methods to create and manage scenes. //! //! Scene is container for graph nodes, animations and physics. pub mod base; pub mod camera; pub mod graph; pub mod light; pub mod mesh; pub mod node; pub mod particle_system; pub mod sprite; pub mod transform; use crate...
pub(in crate) fn resolve(&mut self) { Log::writeln("Starting resolve...".to_owned()); self.graph.resolve(); self.animations.resolve(&self.graph); Log::writeln("Resolve succeeded!".to_owned()); } /// Tries to set new lightmap to scene. pub fn set_lightmap(&mut self, lig...
{ for descendant in self.graph.traverse_handle_iter(handle) { // Remove all associated animations. self.animations.retain(|animation| { for track in animation.get_tracks() { if track.get_node() == descendant { return false; ...
identifier_body
mod.rs
#![warn(missing_docs)] //! Contains all structures and methods to create and manage scenes. //! //! Scene is container for graph nodes, animations and physics. pub mod base; pub mod camera; pub mod graph; pub mod light; pub mod mesh; pub mod node; pub mod particle_system; pub mod sprite; pub mod transform; use crate...
impl Scene { /// Creates new scene with single root node. /// /// # Notes /// /// This method differs from Default trait implementation! Scene::default() creates /// empty graph with no nodes. #[inline] pub fn new() -> Self { Self { // Graph must be created with `new`...
}
random_line_split
mod.rs
#![warn(missing_docs)] //! Contains all structures and methods to create and manage scenes. //! //! Scene is container for graph nodes, animations and physics. pub mod base; pub mod camera; pub mod graph; pub mod light; pub mod mesh; pub mod node; pub mod particle_system; pub mod sprite; pub mod transform; use crate...
(&mut self, scene: Scene) -> Handle<Scene> { self.pool.spawn(scene) } /// Removes all scenes from container. #[inline] pub fn clear(&mut self) { self.pool.clear() } /// Removes given scene from container. #[inline] pub fn remove(&mut self, handle: Handle<Scene>) { ...
add
identifier_name
index.rs
/*! Indexing within memory elements. This module provides types which guarantee certain properties about selecting bits within a memory element. These types enable their use sites to explicitly declare the indexing behavior they require, and move safety checks from runtime to compile time. # Bit Indexing The [`BitId...
-> BitPos<M> where M: BitMemory { unsafe { BitPos::<M>::new_unchecked(self) } } } #[cfg(test)] mod tests { use super::*; #[test] fn jump_far_up() { // isize::max_value() is 0x7f...ff, so the result bit will be one less // than the start bit. for n in 1.. 8 { let (elt, bit) = n.idx::<u8>().offset(isi...
l::<M>::new_unchecked(self) } } fn pos<M>(self)
identifier_body
index.rs
/*! Indexing within memory elements. This module provides types which guarantee certain properties about selecting bits within a memory element. These types enable their use sites to explicitly declare the indexing behavior they require, and move safety checks from runtime to compile time. # Bit Indexing The [`BitId...
se, downshift the bit distance to compute the number of elements moved in either direction, and mask to compute the absolute bit index in the destination element. */ else { (far >> M::INDX, (far as u8 & M::MASK).idx()) } } else { /* Overflowing `isize` addition happens to produce ordinary `usi...
as u8).idx()) } /* Otherwi
conditional_block
index.rs
/*! Indexing within memory elements. This module provides types which guarantee certain properties about selecting bits within a memory element. These types enable their use sites to explicitly declare the indexing behavior they require, and move safety checks from runtime to compile time. # Bit Indexing The [`BitId...
::Target { &self.sel } } /** A multi-bit selector mask. Unlike [`BitSel`], which enforces a strict one-hot mask encoding, this mask type permits any number of bits to be set or unset. This is used to combine batch operations in an element. It is only constructed by accumulating [`BitPos`] or [`BitSel`] values. As...
&Self
identifier_name
index.rs
/*! Indexing within memory elements. This module provides types which guarantee certain properties about selecting bits within a memory element. These types enable their use sites to explicitly declare the indexing behavior they require, and move safety checks from runtime to compile time. # Bit Indexing The [`BitId...
{ /// The termination index. pub const END: Self = Self { end: M::BITS, _ty: PhantomData, }; /// Mark that `end` is a tail index for a type. /// /// # Parameters /// /// - `end` must be in the range `0..= M::BITS`. pub(crate) unsafe fn new_unchecked(end: u8) -> Self { debug_assert!( end <= M::BITS, ...
random_line_split
transaction.rs
use std::{ collections::HashMap, future::Future, pin::Pin, sync::Arc, task::{Context, Poll}, }; use futures::{ stream::{FuturesUnordered, StreamExt}, FutureExt, }; use tower::{Service, ServiceExt}; use tracing::Instrument; use zebra_chain::{ block, parameters::{Network, NetworkUpgr...
transaction, known_utxos, upgrade, } => (transaction, known_utxos, upgrade), }; let mut spend_verifier = primitives::groth16::SPEND_VERIFIER.clone(); let mut output_verifier = primitives::groth16::OUTPUT_VERIFIER.clone(); let ...
{ let is_mempool = match req { Request::Block { .. } => false, Request::Mempool { .. } => true, }; if is_mempool { // XXX determine exactly which rules apply to mempool transactions unimplemented!(); } let (tx, known_utxos, upgrade...
identifier_body
transaction.rs
use std::{ collections::HashMap, future::Future, pin::Pin, sync::Arc, task::{Context, Poll}, }; use futures::{ stream::{FuturesUnordered, StreamExt}, FutureExt, }; use tower::{Service, ServiceExt}; use tracing::Instrument; use zebra_chain::{ block, parameters::{Network, NetworkUpgr...
// https://zips.z.cash/protocol/protocol.pdf#sproutnonmalleability // https://zips.z.cash/protocol/protocol.pdf#txnencodingandconsensus let rsp = ed25519_verifier .ready_and() .await? ...
// adding the resulting future to our collection of // async checks that (at a minimum) must pass for the // transaction to verify. //
random_line_split
transaction.rs
use std::{ collections::HashMap, future::Future, pin::Pin, sync::Arc, task::{Context, Poll}, }; use futures::{ stream::{FuturesUnordered, StreamExt}, FutureExt, }; use tower::{Service, ServiceExt}; use tracing::Instrument; use zebra_chain::{ block, parameters::{Network, NetworkUpgr...
{ /// Verify the supplied transaction as part of a block. Block { /// The transaction itself. transaction: Arc<Transaction>, /// Additional UTXOs which are known at the time of verification. known_utxos: Arc<HashMap<transparent::OutPoint, zs::Utxo>>, /// The height of th...
Request
identifier_name
main.rs
; use sdl2::event::Event; use sdl2::event::WindowEvent; use sdl2::keyboard::Keycode; use sdl2::gfx::primitives::DrawRenderer; use sdl2::render::Renderer; use std::f32; use std::f32::consts::PI; use std::collections::HashMap; use keyboard::Keyboard; use keyboard::HexAddr; use keyboard::HexKey; use keyboard::HarmonicKeyb...
.build() .unwrap(); let mut renderer = window.renderer().build().unwrap(); let font_rwop = RWops::from_bytes(ttf_font_bytes).unwrap(); let keyboard_font = ttf_context.load_font_from_rwops(font_rwop, 20).unwrap(); // be bold // keyboard_font.set_style(sdl2::ttf::STYLE_BOLD); ...
let window = video_subsystem.window("Isomidi", screen_width, screen_height) .position_centered() .opengl() .resizable()
random_line_split
main.rs
use sdl2::event::Event; use sdl2::event::WindowEvent; use sdl2::keyboard::Keycode; use sdl2::gfx::primitives::DrawRenderer; use sdl2::render::Renderer; use std::f32; use std::f32::consts::PI; use std::collections::HashMap; use keyboard::Keyboard; use keyboard::HexAddr; use keyboard::HexKey; use keyboard::HarmonicKeybo...
}; self.active_presses_map.insert(oid, addr); } fn get_pressed(&self) -> Vec<HexAddr> { // TODO this iteration is SLOW and this function is called once per hexagon // TODO make this function FAST! let mut vec = Vec::new(); for (_, &value) in &self.active_presses_...
{ if addr != old_addr { self.start_note(addr, keyboard); self.end_note(old_addr, keyboard); } }
conditional_block
main.rs
use sdl2::event::Event; use sdl2::event::WindowEvent; use sdl2::keyboard::Keycode; use sdl2::gfx::primitives::DrawRenderer; use sdl2::render::Renderer; use std::f32; use std::f32::consts::PI; use std::collections::HashMap; use keyboard::Keyboard; use keyboard::HexAddr; use keyboard::HexKey; use keyboard::HarmonicKeybo...
(xo:f32, yo:f32, hexagon:&HexagonDescription) -> HexAddr { let hex_height = hexagon.half_height as f32; let plane1 = yo / hex_height; let incangle = INCREMENT_ANGLE * -2.0; // -120 degrees //let x = xo * incangle.cos() + yo * incangle.sin(); let y = xo * incangle.sin() + yo * incangle.cos(...
get_hex_address
identifier_name
main.rs
use sdl2::event::Event; use sdl2::event::WindowEvent; use sdl2::keyboard::Keycode; use sdl2::gfx::primitives::DrawRenderer; use sdl2::render::Renderer; use std::f32; use std::f32::consts::PI; use std::collections::HashMap; use keyboard::Keyboard; use keyboard::HexAddr; use keyboard::HexKey; use keyboard::HarmonicKeybo...
fn translate_hexagon(xlist:[i16;6], ylist:[i16;6], x:i16, y:i16) -> ([i16;6], [i16;6]) { let mut xs: [i16;6] = [0; 6]; let mut ys: [i16;6] = [0; 6]; for i in 0..6 { xs[i] = xlist[i] + x; ys[i] = ylist[i] + y; } return (xs, ys) } /// Given the x and y locations of a click, return ...
{ // TODO this function needs to be broken up into a calculate and translate section, we don't // need to redo the sin math every time. let r:f32 = radius as f32; let mut angle:f32 = INCREMENT_ANGLE/2.0; let mut xs: [i16;6] = [0; 6]; let mut ys: [i16;6] = [0; 6]; for i in 0..6 { let...
identifier_body
render.rs
use crate::{ html::{Attribute, Children, Element, EventListener, EventToMessage, Html}, program::Program, }; use itertools::{EitherOrBoth, Itertools}; use std::fmt::Debug; use std::rc::Rc; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; pub struct Renderer<Model, Msg> { program: Rc<Program<Model, M...
node_et .add_event_listener_with_callback(&type_, closure.as_ref().unchecked_ref())?; let ret = js_closure.0.replace(Some(closure)); if ret.is_some() { log::warn!("to_message did already have a closure???"); } ...
let node_et: &web_sys::EventTarget = &node;
random_line_split
render.rs
use crate::{ html::{Attribute, Children, Element, EventListener, EventToMessage, Html}, program::Program, }; use itertools::{EitherOrBoth, Itertools}; use std::fmt::Debug; use std::rc::Rc; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; pub struct Renderer<Model, Msg> { program: Rc<Program<Model, M...
( &mut self, parent: &web_sys::Node, new: Option<&Html<Msg>>, old: Option<&Html<Msg>>, index: u32, ) -> Result<(), JsValue> { match (old, new) { (None, Some(new_html)) => { // Node is added parent.append_child(&self.create_n...
update_element
identifier_name
render.rs
use crate::{ html::{Attribute, Children, Element, EventListener, EventToMessage, Html}, program::Program, }; use itertools::{EitherOrBoth, Itertools}; use std::fmt::Debug; use std::rc::Rc; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; pub struct Renderer<Model, Msg> { program: Rc<Program<Model, M...
} Ok(()) }
{ if let Some(closure) = js_closure.0.replace(None) { let node_et: &web_sys::EventTarget = &node; node_et.remove_event_listener_with_callback( &type_, closure.as_ref().unchecked_ref(), )?; } else { ...
conditional_block
main.rs
// index is now at qtype let qtype = u16::from_be_bytes(self.datagram[index..index + 2].try_into().unwrap()); // A = 1, AAAA = 28 if qtype!= 1 && qtype!= 28 { log::error!("Problem parsing qname, qtype is not 1 or 28: {}", qtype); return Err...
let mut entry_count = entries.len(); if entry_count > 128 { entry_count = 128; } *i.next()? = entry_count.try_into().ok()?; // Start filling in the addreses for addr in entries.keys() { match addr { &IpAddr::V4(a) => { // IPv4 *i.next(...
// 128 is just a conservative value rounded down.
random_line_split
main.rs
// index is now at qtype let qtype = u16::from_be_bytes(self.datagram[index..index + 2].try_into().unwrap()); // A = 1, AAAA = 28 if qtype!= 1 && qtype!= 28 { log::error!("Problem parsing qname, qtype is not 1 or 28: {}", qtype); return Err(...
} pub struct Resolver { /// DnsServerManager is a service of the Net crate that automatically updates the DNS server list mgr: net::protocols::DnsServerManager, socket: UdpSocket, buf: [u8; DNS_PKT_MAX_LEN], trng: trng::Trng, freeze: bool, } impl Resolver { pub fn new(xns: &xous_names::Xou...
{ match (self.header() >> 11) & 0xF { 0 => DnsResponseCode::NoError, 1 => DnsResponseCode::FormatError, 2 => DnsResponseCode::ServerFailure, 3 => DnsResponseCode::NameError, 4 => DnsResponseCode::NotImplemented, 5 => DnsResponseCode::Refuse...
identifier_body
main.rs
// index is now at qtype let qtype = u16::from_be_bytes(self.datagram[index..index + 2].try_into().unwrap()); // A = 1, AAAA = 28 if qtype!= 1 && qtype!= 28 { log::error!("Problem parsing qname, qtype is not 1 or 28: {}", qtype); return Err(...
(&mut self, freeze: bool) { self.freeze = freeze; self.mgr.set_freeze(freeze); } pub fn get_freeze(&self) -> bool { self.freeze } /// this allows us to re-use the TRNG object pub fn trng_u32(&self) -> u32 { self.trng.get_u32().unwrap() } pub fn resolve(&mut se...
set_freeze_config
identifier_name
sudoku_server_basic.rs
use std::future::Future; use bytes::Buf; use bytes::BytesMut; use log::error; use log::info; use recipes::shutdown::Shutdown; use subslice::SubsliceExt; use thiserror::Error; use tokio::io::AsyncReadExt; use tokio::io::AsyncWriteExt; use tokio::io::BufWriter; use tokio::runtime::Builder; use tokio::signal; use tokio::...
(&mut self) -> anyhow::Result<Option<Frame>> { loop { // Attempt to parse a frame from the buffered data. If enough data // has been buffered, the frame is returned. if let Some(frame) = self.parse_frame()? { return Ok(Some(frame)); } ...
read_frame
identifier_name
sudoku_server_basic.rs
use std::future::Future; use bytes::Buf; use bytes::BytesMut; use log::error; use log::info; use recipes::shutdown::Shutdown; use subslice::SubsliceExt; use thiserror::Error; use tokio::io::AsyncReadExt; use tokio::io::AsyncWriteExt; use tokio::io::BufWriter; use tokio::runtime::Builder; use tokio::signal; use tokio::...
#[inline] fn sudoku_resolve(req: &str) -> String { recipes::sudoku::sudoku_resolve(&req) }
// the `mpsc` channel will close and `recv()` will return `None`. let _ = shutdown_complete_rx.recv().await; Ok(()) }
random_line_split
sudoku_server_basic.rs
use std::future::Future; use bytes::Buf; use bytes::BytesMut; use log::error; use log::info; use recipes::shutdown::Shutdown; use subslice::SubsliceExt; use thiserror::Error; use tokio::io::AsyncReadExt; use tokio::io::AsyncWriteExt; use tokio::io::BufWriter; use tokio::runtime::Builder; use tokio::signal; use tokio::...
self.stream.write_all(ans.as_bytes()).await?; self.stream.write_all(b"\r\n").await?; self.stream.flush().await?; Ok(()) } // frame id:puzzle\r\n or puzzle\r\n fn parse_frame(&mut self) -> anyhow::Result<Option<Frame>> { // let mut buf = Cursor::new(&self.buffer[..]);...
{ self.stream.write_all(id.as_bytes()).await?; self.stream.write_u8(b':').await?; }
conditional_block
sudoku_server_basic.rs
use std::future::Future; use bytes::Buf; use bytes::BytesMut; use log::error; use log::info; use recipes::shutdown::Shutdown; use subslice::SubsliceExt; use thiserror::Error; use tokio::io::AsyncReadExt; use tokio::io::AsyncWriteExt; use tokio::io::BufWriter; use tokio::runtime::Builder; use tokio::signal; use tokio::...
} } _ = shutdown => { // The shutdown signal has been received. info!("shutting down"); } } let Listener { mut shutdown_complete_rx, shutdown_complete_tx, notify_shutdown, .. } = server; // When `notify_shutdown`...
{ let (notify_shutdown, _) = broadcast::channel(1); let (shutdown_complete_tx, shutdown_complete_rx) = mpsc::channel(1); let mut server = Listener { listener, notify_shutdown, shutdown_complete_tx, shutdown_complete_rx, }; tokio::select! { res = server.run() ...
identifier_body
rule_builder.rs
use { crate::{ mir::{self, BlockRef, LValLink}, mir_ext::mark_persistent_recursive, optimizer::{ BuildGroups, ClosureBuilder, GroupBuilder, GroupDyn, GroupSet, MatchMap, OptimizerAspect, SuccBuilder, closure::{Closure, ClosureId, ClosureSeed}, closure_interner::{Closure...
, } } crate fn build_origin_stmts(&mut self, cursor: &mut Cursor) { let stmts = self.origin_stmts.clone(); let stmts = stmts.borrow(); for (k, v) in stmts.iter() { k.build_mir_dyn(&**v, self, cursor); } } pub fn build_set(&mut self, mut cursor: Cursor, closure: Closure) { if clo...
{ let job = BuildJob::BuildSet { cursor, closure: succ_closure }; self.build_queue.push_back(job); }
conditional_block
rule_builder.rs
use { crate::{ mir::{self, BlockRef, LValLink}, mir_ext::mark_persistent_recursive, optimizer::{ BuildGroups, ClosureBuilder, GroupBuilder, GroupDyn, GroupSet, MatchMap, OptimizerAspect, SuccBuilder, closure::{Closure, ClosureId, ClosureSeed}, closure_interner::{Closure...
(&mut self, seed: ClosureSeed, pair: GroupPair) -> BlockRef { let closure = seed.into_closure(); self.resolve(closure, |cursor, closure| { BuildJob::BuildOne { cursor, closure, pair } }) } crate fn successors(&self, seed: Closure) -> ClosureSeed { let mut builder = SuccBuilder::new(seed.entri...
resolve_one
identifier_name
rule_builder.rs
use { crate::{ mir::{self, BlockRef, LValLink}, mir_ext::mark_persistent_recursive, optimizer::{ BuildGroups, ClosureBuilder, GroupBuilder, GroupDyn, GroupSet, MatchMap, OptimizerAspect, SuccBuilder, closure::{Closure, ClosureId, ClosureSeed}, closure_interner::{Closure...
self.fail_block = Some(fail_block); } pub fn add_value_map<A: ToNodeId, B: ToNodeId>(&mut self, from: A, to: B) { self.value_map.insert(from.to_top(), to.to_top()); } pub fn at_origin(&self) -> bool { self.num_built <= 2 } pub fn build( &mut self, grammar: Rc<Grammar>, rules: &Vec<NodeId...
{ let seed = { let model = self.visitor.input_model.borrow(); let first_rule = model.get::<_, mir::ItemRule>(rules[0]).unwrap(); self.rule_ty = Some(first_rule.rule_ty.clone()); model.iter(rules) .borrow_cast_nodes_to::<mir::ItemRule>() .filter_map(|r| r.blocks.first().clon...
identifier_body
rule_builder.rs
use { crate::{ mir::{self, BlockRef, LValLink}, mir_ext::mark_persistent_recursive, optimizer::{ BuildGroups, ClosureBuilder, GroupBuilder, GroupDyn, GroupSet, MatchMap, OptimizerAspect, SuccBuilder, closure::{Closure, ClosureId, ClosureSeed}, closure_interner::{Closure...
crate rule_ty: Option<Link<mir::TypeFn>>, crate iter_locals: Vec<LValLink>, crate locals: Vec<Child<mir::RuleLocal>>, crate blocks: Vec<Child<mir::Block>>, } impl RuleBuilder { pub fn new(comp: &Compiler, options: Options) -> Self { let visitor = comp.aspect_mut::<VisitorAspect>(); let closure_bu...
crate origin_stmts: Rc<RefCell<Vec<GroupPair>>>,
random_line_split
trainer.rs
// p.inc(1); // } Some((score, string)) }) .collect(); // Fill seed_sentencepieces for (count, character) in sall_chars { seed_sentencepieces.push((character.to_string(), count.into())); } // sort by decreasing sco...
random_line_split
trainer.rs
#[derive(thiserror::Error, Debug)] pub enum UnigramTrainerError { #[error("The vocabulary is not large enough to contain all chars")] VocabularyTooSmall, } fn to_log_prob(pieces: &mut [SentencePiece]) { let sum: f64 = pieces.iter().map(|(_, score)| score).sum(); let logsum = sum.ln(); for (_, sco...
{ let mut result = 0.0; while x < 7.0 { result -= 1.0 / x; x += 1.0; } x -= 1.0 / 2.0; let xx = 1.0 / x; let xx2 = xx * xx; let xx4 = xx2 * xx2; result += x.ln() + (1.0 / 24.0) * xx2 - 7.0 / 960.0 * xx4 + (31.0 / 8064.0) * xx4 * xx2 - (127.0 / 30720.0) * xx4 * xx4...
identifier_body
trainer.rs
}; let vocab_size_without_special_tokens = if need_add_unk { self.vocab_size as usize - self.special_tokens.len() - 1 } else { self.vocab_size as usize - self.special_tokens.len() }; for (token, score) in model.iter() { if inserted.contains::<str...
(&self, word_counts: &[Sentence]) -> HashSet<String> { word_counts .iter() .flat_map(|(s, _count)| s.chars()) .chain(self.initial_alphabet.iter().copied()) .map(|c| c.to_string()) .collect() } fn make_seed_sentence_pieces( &self, sen...
required_chars
identifier_name
trainer.rs
}; let vocab_size_without_special_tokens = if need_add_unk { self.vocab_size as usize - self.special_tokens.len() - 1 } else { self.vocab_size as usize - self.special_tokens.len() }; for (token, score) in model.iter() { if inserted.contains::<str...
f /= vsum; // normalizes by all sentence frequency. let logprob_sp = freq[id].ln() - logsum; // After removing the sentencepiece[i], its frequency freq[i] is // re-assigned to alternatives. // new_sum = current_sum - freq[i] + freq[i] * a...
{ // new_pieces.push((token.to_string(), *score)); continue; }
conditional_block
manager.rs
use crate::{ asset::{Asset, AssetHandle}, loaders::{LoadStatus, Loader}, sources::Source, }; use std::path::{Path, PathBuf}; use std::sync::mpsc::{Receiver, Sender}; use std::{collections::HashMap, io::ErrorKind, sync::Arc}; /// Manages the loading and unloading of one struct that implements the Asset trai...
)) } } impl<A, L> Iterator for Manager<A, L> where A: Asset<L>, L: Loader, { type Item = Option<Arc<A::Structure>>; fn next(&mut self) -> Option<Self::Item> { self.asset_handles .iter() .next() .map(|(_, a)| a.get().map(|a| a.clone())) } }
} } pub fn strong_count<P: AsRef<Path>>(&mut self, path: P) -> Option<usize> { Some(Arc::strong_count( self.asset_handles.get(path.as_ref())?.get()?,
random_line_split
manager.rs
use crate::{ asset::{Asset, AssetHandle}, loaders::{LoadStatus, Loader}, sources::Source, }; use std::path::{Path, PathBuf}; use std::sync::mpsc::{Receiver, Sender}; use std::{collections::HashMap, io::ErrorKind, sync::Arc}; /// Manages the loading and unloading of one struct that implements the Asset trai...
<A, L> where A: Asset<L>, L: Loader, { drop: bool, unload: bool, loader_id: usize, load_send: Sender<(usize, PathBuf, L::TransferSupplement)>, load_recv: Receiver<(PathBuf, <L::Source as Source>::Output)>, asset_handles: HashMap<PathBuf, AssetHandle<A, L>>, loaded_once: Vec<PathBuf>,...
Manager
identifier_name
manager.rs
use crate::{ asset::{Asset, AssetHandle}, loaders::{LoadStatus, Loader}, sources::Source, }; use std::path::{Path, PathBuf}; use std::sync::mpsc::{Receiver, Sender}; use std::{collections::HashMap, io::ErrorKind, sync::Arc}; /// Manages the loading and unloading of one struct that implements the Asset trai...
else { a.status = LoadStatus::Loading; let package = (self.loader_id, path.as_ref().into(), supp); self .load_send .send(package) .map_err(|e| std::io::Error::new( ErrorKind::ConnectionReset, format...
{ Err(std::io::Error::new( ErrorKind::AlreadyExists, format!("Image already loading! {:?}", path.as_ref()), )) }
conditional_block
manager.rs
use crate::{ asset::{Asset, AssetHandle}, loaders::{LoadStatus, Loader}, sources::Source, }; use std::path::{Path, PathBuf}; use std::sync::mpsc::{Receiver, Sender}; use std::{collections::HashMap, io::ErrorKind, sync::Arc}; /// Manages the loading and unloading of one struct that implements the Asset trai...
}
{ self.asset_handles .iter() .next() .map(|(_, a)| a.get().map(|a| a.clone())) }
identifier_body
metadata.rs
// Copyright 2018 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in...
source: serde_json::to_string(&dependency.source_id()).unwrap(), req: dependency.version_req().to_string(), kind: match dependency.kind() { CargoKind::Normal => None, CargoKind::Development => Some("dev".to_owned()), CargoKind::Build => Some(...
name: dependency.package_name().to_string(), // UNWRAP: It's cargo's responsibility to ensure a serializable source_id
random_line_split
metadata.rs
// Copyright 2018 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in...
}
{ let dir = TempDir::new("test_cargo_raze_metadata_dir").unwrap(); let toml_path = { let path = dir.path().join("Cargo.toml"); let mut toml = File::create(&path).unwrap(); toml.write_all(b"hello").unwrap(); path }; let files = CargoWorkspaceFiles { lock_path_opt: None, ...
identifier_body
metadata.rs
// Copyright 2018 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in...
() { let dir = TempDir::new("test_cargo_raze_metadata_dir").unwrap(); let toml_path = { let path = dir.path().join("Cargo.toml"); let mut toml = File::create(&path).unwrap(); toml.write_all(basic_toml().as_bytes()).unwrap(); path }; let lock_path = { let path = dir.path().j...
test_cargo_subcommand_metadata_fetcher_works_with_lock
identifier_name
non_copy_const.rs
/// ### Why is this bad? /// Consts are copied everywhere they are referenced, i.e., /// every time you refer to the const a fresh instance of the `Cell` or `Mutex` /// or `AtomicXxxx` will be created, which defeats the whole purpose of using /// these types in the first place. /// /// The `c...
// bounded other traits could have their bound at the trait defs; // and, in that case, the definition is *not* generic. cx.tcx.normalize_erasing_regions( cx.tcx.param_env(of_trait_def_id)...
{ if let ImplItemKind::Const(hir_ty, body_id) = &impl_item.kind { let item_hir_id = cx.tcx.hir().get_parent_node(impl_item.hir_id()); let item = cx.tcx.hir().expect_item(item_hir_id); match &item.kind { ItemKind::Impl(Impl { of_trait: Some...
identifier_body
non_copy_const.rs
// the content of the atomic is unchanged /// assert_eq!(CONST_ATOM.load(SeqCst), 12); // because the CONST_ATOM in these lines are distinct /// /// // Good. /// static STATIC_ATOM: AtomicUsize = AtomicUsize::new(15); /// STATIC_ATOM.store(9, SeqCst); /// assert_eq!(STATIC_ATOM.load(SeqCst), 9)...
{ cx.typeck_results().expr_ty(dereferenced_expr) }
conditional_block
non_copy_const.rs
/// ### Why is this bad? /// Consts are copied everywhere they are referenced, i.e., /// every time you refer to the const a fresh instance of the `Cell` or `Mutex` /// or `AtomicXxxx` will be created, which defeats the whole purpose of using /// these types in the first place. /// /// The `c...
<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { // Ignore types whose layout is unknown since `is_freeze` reports every generic types as `!Freeze`, // making it indistinguishable from `UnsafeCell`. i.e. it isn't a tool to prove a type is // 'unfrozen'. However, this code causes a false negative in wh...
is_unfrozen
identifier_name
non_copy_const.rs
/// ### Why is this bad?
/// /// The `const` should better be replaced by a `static` item if a global /// variable is wanted, or replaced by a `const fn` if a constructor is wanted. /// /// ### Known problems /// A "non-constant" const item is a legacy way to supply an /// initialized value to downstream `static` it...
/// Consts are copied everywhere they are referenced, i.e., /// every time you refer to the const a fresh instance of the `Cell` or `Mutex` /// or `AtomicXxxx` will be created, which defeats the whole purpose of using /// these types in the first place.
random_line_split
lib.rs
/* 8888888b. 8888888b. d8888 88888888888 d8888 888888b. 888 8888888888.d8888b. 888 Y88b 888 "Y88b d88888 888 d88888 888 "88b 888 888 d88P Y88b 888 888 888 888 d88P888 888 d88P888 888 .88P 888 888 Y88b. 888 d88P ...
} } } } #[allow(non_snake_case)] #[derive(Debug, Clone)] pub struct DataTableQuery { pub draw: i32, /* Stands for the n-th time that we're drawing */ pub columns: Vec<( Option<i32>, Option<String>, Option<bool>, Option<bool>, Option<String>, ...
random_line_split
lib.rs
/* 8888888b. 8888888b. d8888 88888888888 d8888 888888b. 888 8888888888.d8888b. 888 Y88b 888 "Y88b d88888 888 d88888 888 "88b 888 888 d88P Y88b 888 888 888 888 d88P888 888 d88P888 888 .88P 888 888 Y88b. 888 d88P ...
"start" if start.is_none() => { let decoded = item.value.url_decode().map_err(|_| ())?; start = Some(match decoded.parse::<i32>() { Ok(item_val) => item_val, Err(_err_msg) => 0, }); ...
{ let decoded = item.value.url_decode().map_err(|_| ())?; draw = Some(match decoded.parse::<i32>() { Ok(item_val) => item_val, Err(_err_msg) => 0, }); }
conditional_block
lib.rs
/* 8888888b. 8888888b. d8888 88888888888 d8888 888888b. 888 8888888888.d8888b. 888 Y88b 888 "Y88b d88888 888 d88888 888 "88b 888 888 d88P Y88b 888 888 888 888 d88P888 888 d88P888 888 .88P 888 888 Y88b. 888 d88P ...
) }) .collect::<String>(); self.query = Some( format!("{} {}", self.query.to_owned().unwrap(), stmt.to_owned()).to_owned(), ); self.to_owned() } None => self.to_o...
{ /* # How this works? ## We will match the existing needing of appending the "join statement" or not As well we do on other self sql generators functions, we'll opt to not do an if stmt for seeking the "last" target and doing a exactly cut for the string to append. ...
identifier_body
lib.rs
/* 8888888b. 8888888b. d8888 88888888888 d8888 888888b. 888 8888888888.d8888b. 888 Y88b 888 "Y88b d88888 888 d88888 888 "88b 888 888 d88P Y88b 888 888 888 888 d88P888 888 d88P888 888 .88P 888 888 Y88b. 888 d88P ...
<'a> { pub origin: (&'a str, &'a str), /* From */ pub fields: Vec<&'a str>, /* Fields to seek for */ pub join_targets: Option<Vec<(&'a str, (&'a str, &'a str), (&'a str, &'a str))>>, /* Join Targets explained over here */ pub datatables_post_query: DataTableQuery, /* Incoming Query */ pub quer...
Tables
identifier_name
main.rs
use alis_bot_rs::*; use clap::{App, Arg, ArgMatches}; use failure::Error; use futures::prelude::*; use glob::glob; use irc::client::prelude::*; use log::{debug, error, info}; use std::path::PathBuf; use std::sync::mpsc::channel; use std::sync::{Arc, Condvar, Mutex}; use std::thread; use tokio::runtime::Runtime; #[macro...
async fn run_instance(config: &PathBuf) -> irc::error::Result<()> { let config = Config::load(&config)?; let mut client = Client::from_config(config.clone()).await?; client.identify()?; let mut stream = client.stream()?; if let Some(server) = config.server { info!("Connected to {}", server...
{ let path = match config_file_is_valid(PathBuf::from(DEFAULT_CONFIG_FILE)) { Ok(p) => p, Err(e) => return Err(e), }; info!( "Using default configuration file: {}", path.as_path().display().to_string() ); Ok(vec![path]) }
identifier_body
main.rs
use alis_bot_rs::*; use clap::{App, Arg, ArgMatches}; use failure::Error; use futures::prelude::*; use glob::glob; use irc::client::prelude::*; use log::{debug, error, info}; use std::path::PathBuf; use std::sync::mpsc::channel; use std::sync::{Arc, Condvar, Mutex}; use std::thread; use tokio::runtime::Runtime; #[macro...
Ok(paths) } fn config_file_is_valid(path: PathBuf) -> Result<PathBuf, Error> { let error; if let Ok(config) = Config::load(&path) { if let Some(_server) = config.server { return Ok(path); } else { error = format_err!( "Configuration file: {}, no ser...
{ return Err(format_err!("No valid configuration files found")); }
conditional_block
main.rs
use alis_bot_rs::*; use clap::{App, Arg, ArgMatches}; use failure::Error; use futures::prelude::*; use glob::glob; use irc::client::prelude::*; use log::{debug, error, info}; use std::path::PathBuf; use std::sync::mpsc::channel; use std::sync::{Arc, Condvar, Mutex}; use std::thread; use tokio::runtime::Runtime; #[macro...
"/tmp/test/1_file.toml", "/tmp/test/2_file.toml", "/tmp/test/error_file.toml", ] .iter(); let matches = build_app().get_matches_from(cmd); let result = get_config_paths_from_cli(matches).unwrap(); assert_eq!(result, expected); } #[test] ...
"-c",
random_line_split
main.rs
use alis_bot_rs::*; use clap::{App, Arg, ArgMatches}; use failure::Error; use futures::prelude::*; use glob::glob; use irc::client::prelude::*; use log::{debug, error, info}; use std::path::PathBuf; use std::sync::mpsc::channel; use std::sync::{Arc, Condvar, Mutex}; use std::thread; use tokio::runtime::Runtime; #[macro...
() { let cmd = ["alis-bot-rs", "-d", "/unaccessible/path"].iter(); let matches = build_app().get_matches_from(cmd); assert!(get_config_paths_from_cli(matches).is_err()); let _dir = Builder::new() .prefix("empty") .rand_bytes(0) .tempdir() .unwr...
directory_failures_errors
identifier_name
encode.rs
match n_down { 1 => { for t in text.split_whitespace() { grams.push(vec![t]); } // for some reason the ngrams crate has difficulty when n == 1, // so in this case we generate the n gram ourselves by a simple whitespace // delimiter. }, _ => { ...
(matches: &ArgMatches) -> Result<(), String> { let file =
encode
identifier_name
encode.rs
match n_down { 1 => { for t in text.split_whitespace() { grams.push(vec![t]); } // for some reason the ngrams crate has difficulty when n == 1, // so in this case we generate the n gram ourselves by a simple whitespace // delimiter. }, _ => { ...
while num_bits_remain > 0 { let num_bits_to_read = if num_bits_remain < num_bits as usize { num_bits_remain as u32 } else { num_bits as u32 }; let value: u8 = bitreader.read(num_bits_to_read).unwrap(); let char_str = utils::get_chars_from_value(value, bit_to_char_map, &sorted_keys); ...
{ let mut cursor = Cursor::new(&file_contents); let mut num_bits_remain = file_contents.len() * 8; let mut bitreader = BitReader::endian(&mut cursor, BigEndian); let mut sorted_keys = vec![]; let mut value_vec = vec![]; for byte_val in bit_to_char_map.keys() { sorted_keys.push(*byte_val); } sorted_...
identifier_body
encode.rs
match n_down { 1 => { for t in text.split_whitespace() { grams.push(vec![t]); } // for some reason the ngrams crate has difficulty when n == 1, // so in this case we generate the n gram ourselves by a simple whitespace // delimiter. }, _ => { ...
let mut cursor = Cursor::new(&file_contents); let mut num_bits_remain = file_contents.len() * 8; let mut bitreader = BitReader::endian(&mut cursor, BigEndian); let mut value_vec = vec![]; while num_bits_remain > 0 { let num_bits_to_read = if num_bits_remain < num_bits as usize { num_bits_remain as ...
use_shuffle: bool, rng: &mut StdRng, char_to_value_map: &mut HashMap<char, usize>, ) -> Vec<u8> {
random_line_split
rcu.rs
//! Reset and clock unit use crate::pac::RCU; use riscv::interrupt; use crate::time::Hertz; use core::cmp; /// Extension trait that sets up the `RCU` peripheral pub trait RcuExt { /// Configure the clocks of the `RCU` peripheral fn configure(self) -> UnconfiguredRcu; } impl RcuExt for RCU { fn configure...
bus_enable!(DMA1 => (ahben, dma1en)); bus_enable!(EXMC => (ahben, exmcen));
} bus_enable!(CRC => (ahben, crcen)); bus_enable!(DMA0 => (ahben, dma0en));
random_line_split
rcu.rs
//! Reset and clock unit use crate::pac::RCU; use riscv::interrupt; use crate::time::Hertz; use core::cmp; /// Extension trait that sets up the `RCU` peripheral pub trait RcuExt { /// Configure the clocks of the `RCU` peripheral fn configure(self) -> UnconfiguredRcu; } impl RcuExt for RCU { fn configure...
/// Returns the frequency of the TIMER1..6 base clock pub fn timerx(&self) -> Hertz { let pclk1 = self.pclk1(); if self.apb1_psc == 1 { pclk1 } else { Hertz(pclk1.0 * 2) } } /// Returns whether the USBCLK clock frequency is valid for the USB per...
{ let pclk2 = self.pclk2(); if self.apb2_psc == 1 { pclk2 } else { Hertz(pclk2.0 * 2) } }
identifier_body
rcu.rs
//! Reset and clock unit use crate::pac::RCU; use riscv::interrupt; use crate::time::Hertz; use core::cmp; /// Extension trait that sets up the `RCU` peripheral pub trait RcuExt { /// Configure the clocks of the `RCU` peripheral fn configure(self) -> UnconfiguredRcu; } impl RcuExt for RCU { fn configure...
(&self) -> Hertz { Hertz(self.sysclk.0 / 4) } /// Returns the frequency of the TIMER0 base clock pub fn timer0(&self) -> Hertz { let pclk2 = self.pclk2(); if self.apb2_psc == 1 { pclk2 } else { Hertz(pclk2.0 * 2) } } /// Returns the f...
systick
identifier_name