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
channel_router.rs
// Copyright 2019 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
(&self) -> bool { self == &ChannelState::Free } pub fn contains_net(&self) -> bool { matches!(self, ChannelState::Net(_)) } pub fn is_constant_on(&self) -> bool { matches!(self, ChannelState::Constant) } } #[derive(Copy, Clone, PartialEq, Debug)] pub enum ChannelOp { M...
is_free
identifier_name
channel_router.rs
// Copyright 2019 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
} else { self.tasks.insert(from, vec![to]); } } fn into_tasks(mut self, src: &ChannelLayout) -> Vec<Task> { self.tasks .drain() .map(|(k, v)| { let net = match src[k] { ChannelState::Net(i) => i, _...
if let Some(k) = self.tasks.get_mut(&from) { k.push(to);
random_line_split
channel_router.rs
// Copyright 2019 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
} #[derive(Copy, Clone, PartialEq, Debug)] pub enum ChannelState { Free, // Occupied means no connection. This is the same as a constant false. Occupied, // Constant true. Constant, Net(usize), } pub type ChannelLayout = [ChannelState]; impl ChannelState { pub fn is_free(&self) -> bool { ...
{ self.ranges.iter().map(|r| r.end - r.start).sum() }
identifier_body
chain.rs
use std::collections::HashSet; use std::io::{self, Write}; use crate::disk::bam::BamRef; use crate::disk::block::{BlockDeviceRef, Location, BLOCK_SIZE}; use crate::disk::directory::DirectoryEntry; use crate::disk::error::DiskError; /// A "zero" chain link is a link that indicates that this is a tail block, and /// it...
visited_sectors: HashSet<Location>, block: [u8; BLOCK_SIZE], } impl ChainIterator { /// Create a new chain iterator starting at the specified location. pub fn new(blocks: BlockDeviceRef, starting_sector: Location) -> ChainIterator { ChainIterator { blocks, next_sector: S...
/// Returns a ChainSector which includes the NTS (next track and sector) link. pub struct ChainIterator { blocks: BlockDeviceRef, next_sector: Option<Location>,
random_line_split
chain.rs
use std::collections::HashSet; use std::io::{self, Write}; use crate::disk::bam::BamRef; use crate::disk::block::{BlockDeviceRef, Location, BLOCK_SIZE}; use crate::disk::directory::DirectoryEntry; use crate::disk::error::DiskError; /// A "zero" chain link is a link that indicates that this is a tail block, and /// it...
(&mut self) -> io::Result<()> { // Write the current block let mut blocks = self.blocks.borrow_mut(); blocks .sector_mut(self.location)? .copy_from_slice(&self.block); Ok(()) } } impl Drop for ChainWriter { fn drop(&mut self) { let _result = self.fl...
write_current_block
identifier_name
main.rs
use std::{ collections::HashSet, fmt, fs::{File, OpenOptions}, io::{self, prelude::*, BufRead, Cursor}, net::{IpAddr, Ipv4Addr}, process::Command, }; use failure::Fail; use nom::{ branch::alt, bytes::complete::tag, character::complete::{alpha1, alphanumeric1, digit1, hex_digit1, on...
<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, &'a str, E> { preceded(tag("#"), rest)(input) } #[derive(Debug)] struct HostsLine { ip: IpAddr, canonical_hostname: String, aliases: Vec<String>, comment: Option<String>, } impl HostsLine { fn new(ip: IpAddr, canonical_hostname: ...
comment
identifier_name
main.rs
use std::{ collections::HashSet, fmt, fs::{File, OpenOptions}, io::{self, prelude::*, BufRead, Cursor}, net::{IpAddr, Ipv4Addr}, process::Command, }; use failure::Fail; use nom::{ branch::alt, bytes::complete::tag, character::complete::{alpha1, alphanumeric1, digit1, hex_digit1, on...
#[derive(Debug)] struct HostsLine { ip: IpAddr, canonical_hostname: String, aliases: Vec<String>, comment: Option<String>, } impl HostsLine { fn new(ip: IpAddr, canonical_hostname: String) -> HostsLine { let aliases = Vec::new(); let comment = None; HostsLine { i...
fn comment<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, &'a str, E> { preceded(tag("#"), rest)(input) }
random_line_split
attr.rs
//! Parameters for modifying the appearance or behavior of [`ContentItem`]s. use { std::{ convert::{ TryFrom, TryInto, }, fmt, str::FromStr, }, css_color_parser::ColorParseError, url::Url, crate::{ ContentItem, Menu, }, }; ...
s: P) -> Command { Command { params: args.into(), terminal: false, } } } /// Used by `ContentItem::image` and `ContentItem::template_image`. #[derive(Debug, Clone)] pub struct Image { /// The base64-encoded image data. pub base64_data: String, /// If this is `tru...
(arg
identifier_name
attr.rs
//! Parameters for modifying the appearance or behavior of [`ContentItem`]s. use { std::{ convert::{ TryFrom, TryInto, }, fmt, str::FromStr, }, css_color_parser::ColorParseError, url::Url, crate::{ ContentItem, Menu, }, }; ...
type Error = Vec<T>; fn try_from(mut v: Vec<T>) -> Result<Params, Vec<T>> { match v.len() { 1..=6 => Ok(Params { cmd: v.remove(0).to_string(), params: v.into_iter().map(|x| x.to_string()).collect(), }), _ => Err(v), } } } ...
} } impl<T: ToString> TryFrom<Vec<T>> for Params {
random_line_split
state.rs
use std::sync::Mutex; use wasm_bindgen::prelude::*; use web_sys::CanvasRenderingContext2d; #[wasm_bindgen] extern "C" { pub type TimeoutId; #[wasm_bindgen(js_name = "setTimeout")] pub fn set_timeout_inner(cb: &JsValue, timeout: f64) -> TimeoutId; #[wasm_bindgen(js_name = "clearTimeout")] pub fn c...
if id > self.last_rendered { self.reset_buffer(); self.last_rendered = id; } let mut bright = vec![0_u32; self.config.rendering.width * self.config.rendering.height]; array.copy_to(&mut bright); for i in 0..bright.len() { self.buffer[i] += br...
{ let (worker, busy, queued) = &mut self.workers[worker]; match queued { None => { // log!("Finished a thread"); *busy = false } Some(message) => { // log!("Sending a new config to render"...
conditional_block
state.rs
use std::sync::Mutex; use wasm_bindgen::prelude::*; use web_sys::CanvasRenderingContext2d; #[wasm_bindgen] extern "C" { pub type TimeoutId; #[wasm_bindgen(js_name = "setTimeout")] pub fn set_timeout_inner(cb: &JsValue, timeout: f64) -> TimeoutId; #[wasm_bindgen(js_name = "clearTimeout")] pub fn c...
() -> bool { match STATE.lock().unwrap().as_mut() { Some(_) => true, None => false, } } pub fn with<R, F: FnOnce(&mut State) -> R>(f: F) -> R { match STATE.lock().unwrap().as_mut() { Some(mut state) => f(&mut state), None => { log!("!!! Error: tried to handle sta...
has_state
identifier_name
state.rs
use std::sync::Mutex; use wasm_bindgen::prelude::*; use web_sys::CanvasRenderingContext2d; #[wasm_bindgen] extern "C" { pub type TimeoutId; #[wasm_bindgen(js_name = "setTimeout")] pub fn set_timeout_inner(cb: &JsValue, timeout: f64) -> TimeoutId; #[wasm_bindgen(js_name = "clearTimeout")] pub fn c...
pub fn add_worker(&mut self, worker: web_sys::Worker) { self.workers.push((worker, false, None)) } pub fn invalidate_past_renders(&mut self) { self.render_id += 1; self.last_rendered = self.render_id; } pub fn undo(&mut self) -> Result<(), JsValue> { log!("Undo {}...
{ self.buffer = vec![0_u32; self.config.rendering.width * self.config.rendering.height]; self.invalidate_past_renders(); }
identifier_body
state.rs
use std::sync::Mutex; use wasm_bindgen::prelude::*; use web_sys::CanvasRenderingContext2d; #[wasm_bindgen] extern "C" { pub type TimeoutId; #[wasm_bindgen(js_name = "setTimeout")] pub fn set_timeout_inner(cb: &JsValue, timeout: f64) -> TimeoutId; #[wasm_bindgen(js_name = "clearTimeout")] pub fn c...
pub fn handle_render( &mut self, worker: usize, id: usize, array: js_sys::Uint32Array, ) -> Result<(), JsValue> { if id < self.last_rendered { let (worker, busy, queued) = &mut self.workers[worker]; match queued { None => { ...
// } }
random_line_split
lib.rs
#![cfg_attr(not(feature = "std"), no_std)] //! Kalman filter and Rauch-Tung-Striebel smoothing implementation //! //! Characteristics: //! - Uses the [nalgebra](https://nalgebra.org) crate for math. //! - Supports `no_std` to facilitate running on embedded microcontrollers. //! - Includes [various methods of computing ...
( &self, prior: &StateAndCovariance<R, SS>, observation: &OVector<R, OS>, covariance_method: CoverianceUpdateMethod, ) -> Result<StateAndCovariance<R, SS>, Error> { // Use conventional (e.g. wikipedia) names for these variables let h = self.observation_matrix(); ...
update
identifier_name
lib.rs
#![cfg_attr(not(feature = "std"), no_std)] //! Kalman filter and Rauch-Tung-Striebel smoothing implementation //! //! Characteristics: //! - Uses the [nalgebra](https://nalgebra.org) crate for math. //! - Supports `no_std` to facilitate running on embedded microcontrollers. //! - Includes [various methods of computing ...
#[inline] fn is_nan<R: RealField>(x: R) -> bool { x.partial_cmp(&R::zero()).is_none() } #[test] fn test_is_nan() { assert_eq!(is_nan::<f64>(-1.0), false); assert_eq!(is_nan::<f64>(0.0), false); assert_eq!(is_nan::<f64>(1.0), false); assert_eq!(is_nan::<f64>(1.0 / 0.0), false); assert_eq!(is_na...
Ok(StateAndCovariance::new(state, covariance)) } }
random_line_split
wallpaper.rs
use std::ffi::{OsStr, OsString}; use std::iter::once; use std::os::windows::ffi::{OsStrExt, OsStringExt}; use std::ptr::null_mut; use std::process::Command; use serde::{Serialize, Deserialize}; use winapi::shared::windef::{HWND, RECT, PPOINT, POINT}; use winapi::shared::minwindef::LPARAM; use winapi::um::errhandlinga...
} if handle.is_null() { eprintln!("Cannot find handle using selector: {:?}", selector); return false; } self.add_window_by_handle(handle, properties) } pub fn remove_wallpaper(&self, hwnd: HWND) { // TODO ensure that provided handle is ...
{ break; }
conditional_block
wallpaper.rs
use std::ffi::{OsStr, OsString}; use std::iter::once; use std::os::windows::ffi::{OsStrExt, OsStringExt}; use std::ptr::null_mut; use std::process::Command; use serde::{Serialize, Deserialize}; use winapi::shared::windef::{HWND, RECT, PPOINT, POINT}; use winapi::shared::minwindef::LPARAM; use winapi::um::errhandlinga...
fn to_wide(s: &str) -> Vec<u16> { OsStr::new(s).encode_wide().chain(once(0)).collect() } pub fn get_window_name(hwnd: HWND) -> String { use winapi::um::winuser::{GetWindowTextLengthW, GetWindowTextW}; if hwnd.is_null() { panic!("Invalid HWND"); } let text = unsafe { let text_len...
{ use winapi::um::winuser::FindWindowW; unsafe { FindWindowW(to_wide(class).as_ptr(), null_mut()) } }
identifier_body
wallpaper.rs
use std::ffi::{OsStr, OsString}; use std::iter::once; use std::os::windows::ffi::{OsStrExt, OsStringExt}; use std::ptr::null_mut; use std::process::Command; use serde::{Serialize, Deserialize}; use winapi::shared::windef::{HWND, RECT, PPOINT, POINT}; use winapi::shared::minwindef::LPARAM; use winapi::um::errhandlinga...
let wnd_class = { let wnd_class: &mut [u16] = &mut [0; 512]; GetClassNameW(wnd, wnd_class.as_mut_ptr(), wnd_class.len() as i32 - 1); OsString::from_wide(&wnd_class[..wnd_class.iter().position(|&c| c == 0).unwrap()]) }; if wallpaper == wnd || wnd_class == "Shell_TrayWnd" { ep...
WS_EX_DLGMODALFRAME, WS_EX_COMPOSITED, WS_EX_WINDOWEDGE, WS_EX_CLIENTEDGE, WS_EX_LAYERED, WS_EX_STATICEDGE, WS_EX_TOOLWINDOW, WS_EX_APPWINDOW, };
random_line_split
wallpaper.rs
use std::ffi::{OsStr, OsString}; use std::iter::once; use std::os::windows::ffi::{OsStrExt, OsStringExt}; use std::ptr::null_mut; use std::process::Command; use serde::{Serialize, Deserialize}; use winapi::shared::windef::{HWND, RECT, PPOINT, POINT}; use winapi::shared::minwindef::LPARAM; use winapi::um::errhandlinga...
(wnd: HWND, data: LPARAM) -> i32 { let mut data = data as *mut Data; unsafe { let mut this_pid: DWORD = 0; GetWindowThreadProcessId(wnd, &mut this_pid as LPDWORD); if this_pid == (*data).pid { (*data).handle = wnd; return 0; ...
enum_windows
identifier_name
tile.rs
//! Representation of tiles //! //! Items within a hex are usually given in hexagon-space. This is a 3D space //! where the axis are at 60° to each other. An example of the axis is given //! below. Note that the orientation of the axis when the hexagons are oriented //! with horizontal edges differs from when the hexag...
} impl TileSpec for TileDefinition { fn paths(&self) -> Vec<Path> { self.paths.clone() } fn cities(&self) -> Vec<City> { self.cities.clone() } fn stops(&self) -> Vec<Stop> { self.stops.clone() } fn is_lawson(&self) -> bool { self.is_lawson } fn color(&self) -> colors::Color { colors::GROUND } f...
TileDefinition { name: "NoName".to_string(), paths: vec![], cities: vec![], stops: vec![], is_lawson: false, text: vec![], } }
identifier_body
tile.rs
//! Representation of tiles //! //! Items within a hex are usually given in hexagon-space. This is a 3D space //! where the axis are at 60° to each other. An example of the axis is given //! below. Note that the orientation of the axis when the hexagons are oriented //! with horizontal edges differs from when the hexag...
{ Rough, Hill, Mountain, River, Marsh, } /// Reads and parses all tile definitions in./tiledefs/ pub fn definitions(options: &super::Options) -> HashMap<String, TileDefinition> { println!("Reading tile definitions from file..."); let def_files: Vec<PathBuf> = match fs::read_dir("til...
errainType
identifier_name
tile.rs
//! Representation of tiles //! //! Items within a hex are usually given in hexagon-space. This is a 3D space //! where the axis are at 60° to each other. An example of the axis is given //! below. Note that the orientation of the axis when the hexagons are oriented //! with horizontal edges differs from when the hexag...
//! * `C`: center of hexagon //! //!![Coordinate system](../../../../axes.svg) extern crate nalgebra as na; extern crate serde_yaml; use std::collections::HashMap; use std::f64::consts::PI; use std::fs; use std::path::PathBuf; use std::fs::File; use std::process; /// Standard colors that can be used pub mod colors ...
random_line_split
account_transform.rs
//! Functionality for modifying accounts according to actions. use std::{collections::BTreeMap, marker::PhantomData}; use anyhow::bail; use async_trait::*; use ed25519_dalek::Signer; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use crate::blockdata::{Action, MainBlock, SendInfo}; use crate::crypto::{has...
let recipient: HashCode = get_arg(&action.args, 0)?; let send_amount: u128 = get_arg(&action.args, 1)?; let initialize_spec: Option<Hash<Vec<u8>>> = get_arg(&action.args, 2)?; let message: Vec<u8> = get_arg(&action.args, 3)?; verify_signature_argument(at.this_account, action, 4)...
{ bail!("send can't initialize an account"); }
conditional_block
account_transform.rs
//! Functionality for modifying accounts according to actions. use std::{collections::BTreeMap, marker::PhantomData}; use anyhow::bail; use async_trait::*; use ed25519_dalek::Signer; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use crate::blockdata::{Action, MainBlock, SendInfo}; use crate::crypto::{has...
pub fn from_path(path: HexPath) -> TypedDataField<T> { TypedDataField { path, phantom: PhantomData, } } } /// Account balance field. pub fn field_balance() -> TypedDataField<u128> { TypedDataField::from_path(bytes_to_path(b"balance")) } /// Account stake field. pub ...
impl<T> TypedDataField<T> { /// Creates a `TypedDataField` given a path.
random_line_split
account_transform.rs
//! Functionality for modifying accounts according to actions. use std::{collections::BTreeMap, marker::PhantomData}; use anyhow::bail; use async_trait::*; use ed25519_dalek::Signer; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use crate::blockdata::{Action, MainBlock, SendInfo}; use crate::crypto::{has...
/// A context providing operations related to transforming an account (e.g. /// running actions). pub struct AccountTransform<'a, HL: HashLookup> { /// The `HashLookup` used to look up previous account data. pub hl: &'a HL, /// Whether this account is initializing. pub is_initializing: bool, /// T...
{ let mut path = bytes_to_path(b"received"); path.0.extend(&bytes_to_path(&send.code).0); TypedDataField::from_path(path) }
identifier_body
account_transform.rs
//! Functionality for modifying accounts according to actions. use std::{collections::BTreeMap, marker::PhantomData}; use anyhow::bail; use async_trait::*; use ed25519_dalek::Signer; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use crate::blockdata::{Action, MainBlock, SendInfo}; use crate::crypto::{has...
<'a, HL: HashLookup> { /// The `HashLookup` used to look up previous account data. pub hl: &'a HL, /// Whether this account is initializing. pub is_initializing: bool, /// The account being transformed. pub this_account: HashCode, /// The hash code of the last main block. pub last_main: ...
AccountTransform
identifier_name
server.rs
// Copyright Materialize, Inc. and contributors. All rights reserved. // // Use of this software is governed by the Business Source License // included in the LICENSE file. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by ...
async fn build_timely( user_worker_config: Worker, config: TimelyConfig, epoch: ClusterStartupEpoch, persist_clients: Arc<PersistClientCache>, tracing_handle: Arc<TracingHandle>, tokio_executor: Handle, ) -> Result<TimelyContainer<C, R, Worker::Activatable>, Error...
worker: worker_config, } }
random_line_split
server.rs
// Copyright Materialize, Inc. and contributors. All rights reserved. // // Use of this software is governed by the Business Source License // included in the LICENSE file. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by ...
<Worker, C, R>( config: ClusterConfig, worker_config: Worker, ) -> Result< ( TimelyContainerRef<C, R, Worker::Activatable>, impl Fn() -> Box<ClusterClient<PartitionedClient<C, R, Worker::Activatable>, Worker, C, R>>, ), Error, > where C: Send +'static, R: Send +'static, (...
serve
identifier_name
clipmap.rs
use crate::prelude::{ChunkKey, ChunkKey3, ChunkUnits, OctreeNode, OctreeSet, VisitStatus}; use building_blocks_core::prelude::*; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct ClipMapConfig3 { /// The number of levels of detail. num_lods: u8, /// The radius (in chunks) of a clipbox at any level o...
) .abs() .max_component() } fn octant_chunk_key(chunk_log2: i32, octant: &Octant) -> ChunkKey3 { let lod = octant.exponent(); ChunkKey { lod, minimum: (octant.minimum() << chunk_log2) >> lod, } } // ████████╗███████╗███████╗████████╗ // ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝ // ...
{ c }
conditional_block
clipmap.rs
use crate::prelude::{ChunkKey, ChunkKey3, ChunkUnits, OctreeNode, OctreeSet, VisitStatus}; use building_blocks_core::prelude::*; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct ClipMapConfig3 { /// The number of levels of detail. num_lods: u8, /// The radius (in chunks) of a clipbox at any level o...
( &self, octree: &OctreeSet, mut update_rx: impl FnMut(LodChunkUpdate3), ) { octree.visit_all_octants_in_preorder(&mut |node: &OctreeNode| { let octant = node.octant(); let lod = octant.exponent(); if lod >= self.num_lods || lod == 0 { ...
find_chunk_updates
identifier_name
clipmap.rs
use crate::prelude::{ChunkKey, ChunkKey3, ChunkUnits, OctreeNode, OctreeSet, VisitStatus}; use building_blocks_core::prelude::*; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct ClipMapConfig3 { /// The number of levels of detail. num_lods: u8, /// The radius (in chunks) of a clipbox at any level o...
// We should end up with the same result from moving the clipmap as we do just constructing it from scratch at the // new location. assert_eq!( active_chunks, ActiveChunks::new(config, octree, new_lod0_center), "Failed on edge: {:?} -->...
ClipMapUpdate3::new(config, old_lod0_center, new_lod0_center) .find_chunk_updates(octree, |update| active_chunks.apply_update(update));
random_line_split
clipmap.rs
use crate::prelude::{ChunkKey, ChunkKey3, ChunkUnits, OctreeNode, OctreeSet, VisitStatus}; use building_blocks_core::prelude::*; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct ClipMapConfig3 { /// The number of levels of detail. num_lods: u8, /// The radius (in chunks) of a clipbox at any level o...
.max_component() } fn octant_chunk_key(chunk_log2: i32, octant: &Octant) -> ChunkKey3 { let lod = octant.exponent(); ChunkKey { lod, minimum: (octant.minimum() << chunk_log2) >> lod, } } // ████████╗███████╗███████╗████████╗ // ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝ // ██║ █████╗...
{ let lod = octant.exponent(); let lod_p = octant.minimum() >> lod; let lod_center = centers[lod as usize]; (lod_p - lod_center) // For calculating offsets from the clipmap center, we need to bias any nonnegative components to make voxel coordinates // symmetric about the center. ...
identifier_body
pool.rs
// This module provides a relatively simple thread-safe pool of reusable // objects. For the most part, it's implemented by a stack represented by a // Mutex<Vec<T>>. It has one small trick: because unlocking a mutex is somewhat // costly, in the case where a pool is accessed by the first thread that tried // to get a ...
} impl<'a, T: Send> PoolGuard<'a, T> { /// Return the underlying value. pub fn value(&self) -> &T { match self.value { None => &self.pool.owner_val, Some(ref v) => &**v, } } } impl<'a, T: Send> Drop for PoolGuard<'a, T> { #[cfg_attr(feature = "perf-inline", inl...
{ PoolGuard { pool: self, value: Some(value) } }
identifier_body
pool.rs
// This module provides a relatively simple thread-safe pool of reusable // objects. For the most part, it's implemented by a stack represented by a // Mutex<Vec<T>>. It has one small trick: because unlocking a mutex is somewhat // costly, in the case where a pool is accessed by the first thread that tried // to get a ...
<T> { /// A stack of T values to hand out. These are used when a Pool is /// accessed by a thread that didn't create it. stack: Mutex<Vec<Box<T>>>, /// A function to create more T values when stack is empty and a caller /// has requested a T. create: CreateFn<T>, /// The ID of the thread tha...
Pool
identifier_name
pool.rs
// This module provides a relatively simple thread-safe pool of reusable // objects. For the most part, it's implemented by a stack represented by a // Mutex<Vec<T>>. It has one small trick: because unlocking a mutex is somewhat // costly, in the case where a pool is accessed by the first thread that tried // to get a ...
/// gets 'owner_val' directly instead of returning a T from'stack'. /// See comments elsewhere for details, but this is intended to be an /// optimization for the common case that makes getting a T faster. /// /// It is initialized to a value of zero (an impossible thread ID) as a /// sentinel t...
/// The ID of the thread that owns this pool. The owner is the thread /// that makes the first call to 'get'. When the owner calls 'get', it
random_line_split
vmctx.rs
//! Interfaces for accessing instance data from hostcalls. //! //! This module contains both a Rust-friendly API ([`Vmctx`](struct.Vmctx.html)) as well as C-style //! exports for compatibility with hostcalls written against `lucet-runtime-c`. pub use crate::c_api::lucet_vmctx; use crate::alloc::instance_heap_offset; ...
/// Return the underlying `vmctx` pointer. pub fn as_raw(&self) -> *mut lucet_vmctx { self.vmctx } /// Return the WebAssembly heap as a slice of bytes. /// /// If the heap is already mutably borrowed by `heap_mut()`, the instance will /// terminate with `TerminationDetails::Borrow...
{ let inst = instance_from_vmctx(vmctx); assert!(inst.valid_magic()); let res = Vmctx { vmctx, heap_view: RefCell::new(Box::<[u8]>::from_raw(inst.heap_mut())), globals_view: RefCell::new(Box::<[GlobalValue]>::from_raw(inst.globals_mut())), }; ...
identifier_body
vmctx.rs
//! Interfaces for accessing instance data from hostcalls. //! //! This module contains both a Rust-friendly API ([`Vmctx`](struct.Vmctx.html)) as well as C-style //! exports for compatibility with hostcalls written against `lucet-runtime-c`. pub use crate::c_api::lucet_vmctx; use crate::alloc::instance_heap_offset; ...
}
HOST_CTX.with(|host_ctx| unsafe { Context::set(&*host_ctx.get()) }) }
random_line_split
vmctx.rs
//! Interfaces for accessing instance data from hostcalls. //! //! This module contains both a Rust-friendly API ([`Vmctx`](struct.Vmctx.html)) as well as C-style //! exports for compatibility with hostcalls written against `lucet-runtime-c`. pub use crate::c_api::lucet_vmctx; use crate::alloc::instance_heap_offset; ...
(&self) -> RefMut<'_, [GlobalValue]> { let r = self .globals_view .try_borrow_mut() .unwrap_or_else(|_| panic!(TerminationDetails::BorrowError("globals_mut"))); RefMut::map(r, |b| b.borrow_mut()) } /// Get a function pointer by WebAssembly table and function ind...
globals_mut
identifier_name
hwdetect.rs
use anyhow::anyhow; use nom::character::complete::{newline, satisfy, space0}; use nom::combinator::{map, map_res, opt}; use nom::multi::{many1, separated_list1}; use nom::sequence::{preceded, terminated, tuple}; use nom::Parser; use nom_supreme::tag::complete::tag; use tako::hwstats::GpuFamily; use tako::internal::has...
} } } gpus } /// Try to find out how many Nvidia GPUs are available on the current node. fn read_nvidia_linux_gpu_count() -> anyhow::Result<usize> { Ok(std::fs::read_dir("/proc/driver/nvidia/gpus")?.count()) } /// Try to get total memory on the current node. fn read_linux_memory() -> ...
{ if let Ok(devices) = parse_comma_separated_values(&devices_str) { log::info!( "Detected GPUs {} from `{}`", format_comma_delimited(&devices), gpu_env.env_var, ); if !has_unique_elements(&devices) {...
conditional_block
hwdetect.rs
use anyhow::anyhow; use nom::character::complete::{newline, satisfy, space0}; use nom::combinator::{map, map_res, opt}; use nom::multi::{many1, separated_list1}; use nom::sequence::{preceded, terminated, tuple}; use nom::Parser; use nom_supreme::tag::complete::tag; use tako::hwstats::GpuFamily; use tako::internal::has...
gpu_families.insert(gpu.family); items.push(ResourceDescriptorItem { name: gpu.resource_name.to_string(), kind: gpu.resource, }); } } } if!has_resource(items, MEM_RESOURCE_NAME) { if let Ok(mem) ...
{ let mut gpu_families = Set::new(); let has_resource = |items: &[ResourceDescriptorItem], name: &str| items.iter().any(|x| x.name == name); let detected_gpus = detect_gpus_from_env(); if detected_gpus.is_empty() && !has_resource(items, NVIDIA_GPU_RESOURCE_NAME) { if let Ok(count) = rea...
identifier_body
hwdetect.rs
use nom::sequence::{preceded, terminated, tuple}; use nom::Parser; use nom_supreme::tag::complete::tag; use tako::hwstats::GpuFamily; use tako::internal::has_unique_elements; use tako::resources::{ ResourceDescriptorItem, ResourceDescriptorKind, ResourceIndex, ResourceLabel, AMD_GPU_RESOURCE_NAME, MEM_RESOURCE...
use anyhow::anyhow; use nom::character::complete::{newline, satisfy, space0}; use nom::combinator::{map, map_res, opt}; use nom::multi::{many1, separated_list1};
random_line_split
hwdetect.rs
use anyhow::anyhow; use nom::character::complete::{newline, satisfy, space0}; use nom::combinator::{map, map_res, opt}; use nom::multi::{many1, separated_list1}; use nom::sequence::{preceded, terminated, tuple}; use nom::Parser; use nom_supreme::tag::complete::tag; use tako::hwstats::GpuFamily; use tako::internal::has...
() -> anyhow::Result<u64> { Ok(psutil::memory::virtual_memory()?.total()) } /// Try to find the CPU NUMA configuration. /// /// Returns a list of NUMA nodes, each node contains a list of assigned CPUs. fn read_linux_numa() -> anyhow::Result<Vec<Vec<ResourceIndex>>> { let nodes = parse_range(&std::fs::read_to_s...
read_linux_memory
identifier_name
server.rs
packet: &PublicPacket) -> Self { Self { src_cid: ConnectionId::from(packet.scid()), dst_cid: ConnectionId::from(packet.dcid()), token: packet.token().to_vec(), version: packet.version().unwrap(), } } } struct EchConfig { config: u8, public_nam...
} if c.borrow().has_events() { qtrace!([self], "Connection active: {:?}", c); self.active.insert(ActiveConnectionRef { c: Rc::clone(&c) }); } if *c.borrow().state() > State::Handshaking { // Remove any active connection attempt now that this is no lo...
{ self.remove_timer(&c); }
conditional_block
server.rs
/// as this depends on there being some distribution of events. const TIMER_GRANULARITY: Duration = Duration::from_millis(4); /// The number of buckets in the timer. As mentioned in the definition of `Timer`, /// the granularity and capacity need to multiply to be larger than the largest /// delay that might be used. ...
const MIN_INITIAL_PACKET_SIZE: usize = 1200; /// The size of timer buckets. This is higher than the actual timer granularity
random_line_split
server.rs
} impl DerefMut for ServerConnectionState { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.c } } /// A `AttemptKey` is used to disambiguate connection attempts. /// Multiple connection attempts with the same key won't produce multiple connections. #[derive(Clone, Debug, Hash, PartialEq, Eq)...
{ &self.c }
identifier_body
server.rs
{ // Using the remote address is sufficient for disambiguation, // until we support multiple local socket addresses. remote_address: SocketAddr, odcid: ConnectionId, } /// A `ServerZeroRttChecker` is a simple wrapper around a single checker. /// It uses `RefCell` so that the wrapped checker can be sha...
AttemptKey
identifier_name
spacetime.rs
// // 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 writing, software distributed // under the...
(attribute_id: SolitonId, existing: &AttributeMap) -> AttributeBuilder { existing.get(&attribute_id) .map(AttributeBuilder::to_modify_attribute) .unwrap_or_else(AttributeBuilder::default) } // Group mutations by impacted solitonId. let mut builders: BTreeMap<SolitonId,...
attribute_builder_to_modify
identifier_name
spacetime.rs
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 writing, software distributed // under...
fn attribute_builder_to_modify(attribute_id: SolitonId, existing: &AttributeMap) -> AttributeBuilder { existing.get(&attribute_id) .map(AttributeBuilder::to_modify_attribute) .unwrap_or_else(AttributeBuilder::default) } // Group mutations by impacted solitonId. let...
/// This is suiBlock for producing a `AttributeMap` from the `schemaReplicant` materialized view, which does not /// contain install and alter markers. /// /// Returns a report summarizing the mutations that were applied. pub fn update_attribute_map_from_causetid_triples(attribute_map: &mut AttributeMap, assertions: Ve...
random_line_split
spacetime.rs
// // 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 writing, software distributed // under the...
builder.component(false); }, v => { bail!(DbErrorKind::BadSchemaReplicantAssertion(format!("Attempted to retract :edb/isComponent with the wrong value {:?}.", v))); }, } }, ...
{ fn attribute_builder_to_modify(attribute_id: SolitonId, existing: &AttributeMap) -> AttributeBuilder { existing.get(&attribute_id) .map(AttributeBuilder::to_modify_attribute) .unwrap_or_else(AttributeBuilder::default) } // Group mutations by impacted solitonId. ...
identifier_body
spacetime.rs
// // 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 writing, software distributed // under the...
} } Ok(SpacetimeReport { attributes_installed: attributes_installed, attributes_altered: attributes_altered, causetIds_altered: BTreeMap::default(), }) } /// Update a `SchemaReplicant` in place from the given `[e a typed_value added]` quadruples. /// /// This layer enforces t...
builder.validate_alter_attribute().context(DbErrorKind::BadSchemaReplicantAssertion(format!("SchemaReplicant alteration for existing attribute with solitonId {} is not valid", solitonId)))?; let mutations = builder.mutate(entry.get_mut()); attributes_altered.insert(solitonI...
conditional_block
init.rs
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT use super::{get_app, Target}; use crate::helpers::{config::get as get_tauri_config, template::JsonMap}; use crate::Result; use handlebars::{Context, Handlebars, Helper, HelperRes...
r: &Helper, _: &Handlebars, ctx: &Context, _: &mut RenderContext, out: &mut dyn Output, ) -> HelperResult { out .write( util::unprefix_path(app_root(ctx)?, get_str(helper)) .map_err(|_| { RenderError::new("Attempted to unprefix a path that wasn't in the app root dir.") })? ...
path( helpe
identifier_name
init.rs
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT use super::{get_app, Target}; use crate::helpers::{config::get as get_tauri_config, template::JsonMap}; use crate::Result; use handlebars::{Context, Handlebars, Helper, HelperRes...
#[allow(unused_variables)] non_interactive: bool, #[allow(unused_variables)] reinstall_deps: bool, skip_targets_install: bool, ) -> Result<App> { let current_dir = current_dir()?; let tauri_config = get_tauri_config(None)?; let tauri_config_guard = tauri_config.lock().unwrap(); let tauri_config_ = tauri_...
pub fn exec( target: Target, wrapper: &TextWrapper,
random_line_split
init.rs
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT use super::{get_app, Target}; use crate::helpers::{config::get as get_tauri_config, template::JsonMap}; use crate::Result; use handlebars::{Context, Handlebars, Helper, HelperRes...
build_args.insert(0, var("npm_lifecycle_event").unwrap()); } if is_npm { build_args.insert(0, "run".into()); } } } map.insert("tauri-binary", binary.to_string_lossy()); map.insert("tauri-binary-args", &build_args); map.insert("tauri-binary-args-str", build_args.join(" "))...
{ if let Some(npm_execpath) = var_os("npm_execpath").map(PathBuf::from) { let manager_stem = npm_execpath.file_stem().unwrap().to_os_string(); let is_npm = manager_stem == "npm-cli"; let is_npx = manager_stem == "npx-cli"; binary = if is_npm { "npm".into() } else if is_npx { ...
conditional_block
init.rs
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT use super::{get_app, Target}; use crate::helpers::{config::get as get_tauri_config, template::JsonMap}; use crate::Result; use handlebars::{Context, Handlebars, Helper, HelperRes...
( helper: &Helper, _: &Handlebars, _: &Context, _: &mut RenderContext, out: &mut dyn Output, ) -> HelperResult { out .write( &get_str_array(helper, |s| s.to_string()) .ok_or_else(|| RenderError::new("`join` helper wasn't given an array"))? .join(", "), ) .map_err(Into::into) } ...
.write(&handlebars::html_escape(get_str(helper))) .map_err(Into::into) } fn join
identifier_body
consensus.rs
// Copyright 2020 The Grin Developers // 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 t...
} /// Difficulty calculation based on a Weighted Target Exponential Moving Average /// of difficulty, using the ratio of the last block time over the target block time. pub fn next_wtema_difficulty<T>(_height: u64, cursor: T) -> HeaderInfo where T: IntoIterator<Item = HeaderInfo>, { let mut last_headers = cursor.int...
let difficulty = max(MIN_DMA_DIFFICULTY, diff_sum * BLOCK_TIME_SEC / adj_ts); HeaderInfo::from_diff_scaling(Difficulty::from_num(difficulty), sec_pow_scaling)
random_line_split
consensus.rs
// Copyright 2020 The Grin Developers // 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 t...
(actual: u64, goal: u64, damp_factor: u64) -> u64 { (actual + (damp_factor - 1) * goal) / damp_factor } /// limit value to be within some factor from a goal pub fn clamp(actual: u64, goal: u64, clamp_factor: u64) -> u64 { max(goal / clamp_factor, min(actual, goal * clamp_factor)) } /// Computes the proof-of-work di...
damp
identifier_name
consensus.rs
// Copyright 2020 The Grin Developers // 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 t...
else { // should not get here 1 } } /// Calculate block overage based on height and claimed BTCUtxos pub fn calc_block_overage(height: u64) -> u64 { if height == 0 { 0 } else if height <= get_epoch_start(2) { (REWARD1 * height) + get_overage_offset_start_epoch(1) } else if height <= get_epoch_start(3) { ...
{ get_epoch_start(9) * REWARD8 + get_epoch_start(8) * REWARD7 + get_epoch_start(7) * REWARD6 + get_epoch_start(6) * REWARD5 + get_epoch_start(5) * REWARD4 + get_epoch_start(4) * REWARD3 + get_epoch_start(3) * REWARD2 + get_epoch_start(2) * REWARD1 + REWARD0 }
conditional_block
consensus.rs
// Copyright 2020 The Grin Developers // 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 t...
/// Number of blocks used to calculate difficulty adjustment by Damped Moving Average pub const DMA_WINDOW: u64 = HOUR_HEIGHT; /// Difficulty adjustment half life (actually, 60s * number of 0s-blocks to raise diff by factor e) is 4 hours pub const WTEMA_HALF_LIFE: u64 = 4 * HOUR_SEC; /// Average time span of the DM...
{ version == header_version(height) }
identifier_body
lib.rs
// Copyright 2016 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...
contents.push(' '); column += 1; } last_pos = pos; } column += token.node.len(); contents.push_str(&token.node); } return contents; } pub fn span_to_cpp_directive(ecx: &ExtCtxt, span: Span) -> String { let codemap = ecx.parse...
// Pad the code such that the token remains on the same column while column < pos.col.0 {
random_line_split
lib.rs
// Copyright 2016 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...
<'a>(ecx: &ExtCtxt<'a>, span: Span, tts: &[TokenTree]) -> PResult<'a, Function<L>> { let mut parser = ecx.new_parser_from_tts(tts); let args = if parser.check(&token::OpenDelim(token::Paren)) { Some(try!(Self::parse_args(ecx, &mut parser))) ...
parse
identifier_name
server.rs
use std::thread; use std::sync::mpsc; use websocket; use websocket::{Message, Sender, Receiver}; use websocket::server::sender; use websocket::stream::WebSocketStream; use websocket::message::CloseData; use std::io::prelude::*; use std::fs::{OpenOptions, File}; use std::net::Shutdown; use rustc_serialize::json::{Json, ...
(json: &Json) -> Self { json.as_string().unwrap().to_owned() } } impl<T: FromJson> FromJson for Vec<T> { fn from_json(json: &Json) -> Self { json.as_array().unwrap().iter().map(|t| FromJson::from_json(t)).collect() } } #[derive(Debug, Clone)] pub struct Event { pub changes: Changes, ...
from_json
identifier_name
server.rs
use std::thread; use std::sync::mpsc; use websocket; use websocket::{Message, Sender, Receiver}; use websocket::server::sender; use websocket::stream::WebSocketStream; use websocket::message::CloseData; use std::io::prelude::*; use std::fs::{OpenOptions, File}; use std::net::Shutdown; use rustc_serialize::json::{Json, ...
} #[derive(Debug, Clone)] pub struct Event { pub changes: Changes, pub session: String, } impl ToJson for Event { fn to_json(&self) -> Json { Json::Object(vec![ ("changes".to_string(), Json::Array( self.changes.iter().map(|&(ref view_id, ref view_changes)| { ...
{ json.as_array().unwrap().iter().map(|t| FromJson::from_json(t)).collect() }
identifier_body
server.rs
use std::thread; use std::sync::mpsc; use websocket; use websocket::{Message, Sender, Receiver}; use websocket::server::sender; use websocket::stream::WebSocketStream; use websocket::message::CloseData; use std::io::prelude::*; use std::fs::{OpenOptions, File}; use std::net::Shutdown; use rustc_serialize::json::{Json, ...
("changes".to_string(), Json::Array( self.changes.iter().map(|&(ref view_id, ref view_changes)| { Json::Array(vec![ view_id.to_json(), view_changes.fields.to_json(), view_changes.insert.to_json(), ...
Json::Object(vec![
random_line_split
mpsc.rs
//! A multi-producer, single-consumer, futures-aware, FIFO queue with back //! pressure, for use communicating between tasks on the same thread. //! //! These queues are the same as those in `futures::sync`, except they're not //! intended to be sent across threads. use std::any::Any; use std::cell::RefCell; use std::...
(&mut self, msg: T) -> StartSend<T, SendError<T>> { self.do_send(msg) } fn poll_complete(&mut self) -> Poll<(), SendError<T>> { Ok(Async::Ready(())) } fn close(&mut self) -> Poll<(), SendError<T>> { Ok(Async::Ready(())) } } impl<T> Drop for Sender<T> { fn drop(&mut sel...
start_send
identifier_name
mpsc.rs
//! A multi-producer, single-consumer, futures-aware, FIFO queue with back //! pressure, for use communicating between tasks on the same thread. //! //! These queues are the same as those in `futures::sync`, except they're not //! intended to be sent across threads. use std::any::Any; use std::cell::RefCell; use std::...
/// /// An unbounded buffer is used, which means that values will be buffered as /// fast as `stream` can produce them, without any backpressure. Therefore, if /// `stream` is an infinite stream, it can use an unbounded amount of memory, and /// potentially hog CPU resources. In particular, if `stream` is infinite /// ...
/// When `stream` has additional items available, then the `SpawnHandle` /// will have those same items available.
random_line_split
mpsc.rs
//! A multi-producer, single-consumer, futures-aware, FIFO queue with back //! pressure, for use communicating between tasks on the same thread. //! //! These queues are the same as those in `futures::sync`, except they're not //! intended to be sent across threads. use std::any::Any; use std::cell::RefCell; use std::...
} impl<T> Stream for UnboundedReceiver<T> { type Item = T; type Error = (); fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { self.0.poll() } } /// Creates an unbounded in-memory channel with buffered storage. /// /// Identical semantics to `channel`, except with no limit to buff...
{ self.0.close(); }
identifier_body
stopwords.rs
use lazy_static::lazy_static; use std::collections::{HashMap, HashSet}; lazy_static! { /// ignore these as keywords pub(crate) static ref STOPWORDS: HashSet<&'static str> = [ "a", "sys", "ffi", "placeholder", "app", "loops", "master", "library", "rs", "accidentally", "additional", "adds", "against", "a...
}
].iter().copied().collect();
random_line_split
rasterbackend.rs
use crate::aabb::*; use crate::mesh::*; use crate::picture::*; use crate::zbuffer::*; use std::f32::consts::PI; use std::time::{Duration, Instant}; #[derive(Debug)] pub struct RenderOptions { pub view_pos: Vec3, pub light_pos: Vec3, pub light_color: Vec3, pub ambient_color: Vec3, pub model_color: ...
w0 * v0.y + w1 * v1.y + w2 * v2.y, w0 * v0.z + w1 * v1.z + w2 * v2.z, ); // fragment position in world space let fp = Vec3::new( w0 * v0m.x + w1 * v1m.x + w2 * v2m...
random_line_split
rasterbackend.rs
use crate::aabb::*; use crate::mesh::*; use crate::picture::*; use crate::zbuffer::*; use std::f32::consts::PI; use std::time::{Duration, Instant}; #[derive(Debug)] pub struct RenderOptions { pub view_pos: Vec3, pub light_pos: Vec3, pub light_color: Vec3, pub ambient_color: Vec3, pub model_color: ...
fn view_projection(&self, zoom: f32) -> Mat4 { // calculate view projection matrix let proj = glm::ortho( zoom * 0.5 * self.aspect_ratio, -zoom * 0.5 * self.aspect_ratio, -zoom * 0.5, zoom * 0.5, 0.0, 1.0, ); l...
{ Self { render_options: RenderOptions::default(), width, height, aspect_ratio: width as f32 / height as f32, } }
identifier_body
rasterbackend.rs
use crate::aabb::*; use crate::mesh::*; use crate::picture::*; use crate::zbuffer::*; use std::f32::consts::PI; use std::time::{Duration, Instant}; #[derive(Debug)] pub struct RenderOptions { pub view_pos: Vec3, pub light_pos: Vec3, pub light_color: Vec3, pub ambient_color: Vec3, pub model_color: ...
( &self, mesh: impl IntoIterator<Item = Triangle> + Copy, model_scale: f32, aabb: &AABB, timeout: Option<Duration>, ) -> Picture { let start_time = Instant::now(); let mut pic = Picture::new(self.width, self.height); let mut zbuf = ZBuffer::new(self.w...
render
identifier_name
rasterbackend.rs
use crate::aabb::*; use crate::mesh::*; use crate::picture::*; use crate::zbuffer::*; use std::f32::consts::PI; use std::time::{Duration, Instant}; #[derive(Debug)] pub struct RenderOptions { pub view_pos: Vec3, pub light_pos: Vec3, pub light_color: Vec3, pub ambient_color: Vec3, pub model_color: ...
pic.stroke_string( margin, pic.height() - text_size - margin, &text, text_size as f32, &"FFFFFFFF".into(), ); } pic } } fn edge_fn(a: &Vec2, b: &Vec2, c: &Vec2) -> f32 { (c.x - a.x) * (b.y...
{ let margin = 3; let text_to_height_ratio = 16; let text = format!( "{}x{}x{}", aabb.size().x as i32, aabb.size().y as i32, aabb.size().z as i32 ); let text_size = pic.height() / text_to_height...
conditional_block
mod.rs
use crate::{ data::{Key, Metakey, Value}, error::*, Aggregator, AggregatorState, Backend, Handle, MapState, Reducer, ReducerState, ValueState, VecState, }; use rocksdb::{ checkpoint::Checkpoint, ColumnFamily, ColumnFamilyDescriptor, DBPinnableSlice, Options, SliceTransform, WriteBatch, WriteOpt...
(&self, cf_name: &str, opts: Options) -> Result<()> { if self.db().cf_handle(cf_name).is_none() { self.db_mut().create_cf(cf_name, &opts)?; } Ok(()) } } fn common_options<IK, N>() -> Options where IK: Metakey, N: Metakey, { let prefix_size = IK::SIZE + N::SIZE; ...
create_column_family
identifier_name
mod.rs
use crate::{ data::{Key, Metakey, Value}, error::*, Aggregator, AggregatorState, Backend, Handle, MapState, Reducer, ReducerState, ValueState, VecState, }; use rocksdb::{ checkpoint::Checkpoint, ColumnFamily, ColumnFamilyDescriptor, DBPinnableSlice, Options, SliceTransform, WriteBatch, WriteOpt...
checkpointer.create_checkpoint(checkpoint_path)?; Ok(()) } fn register_value_handle<'s, T: Value, IK: Metakey, N: Metakey>( &'s self, handle: &'s mut Handle<ValueState<T>, IK, N>, ) { handle.registered = true; let opts = common_options::<IK, N>(); s...
{ // TODO: add a warning log here // warn!(logger, "Checkpoint path {:?} exists, deleting"); fs::remove_dir_all(checkpoint_path)? }
conditional_block
mod.rs
use crate::{ data::{Key, Metakey, Value}, error::*, Aggregator, AggregatorState, Backend, Handle, MapState, Reducer, ReducerState, ValueState, VecState, }; use rocksdb::{ checkpoint::Checkpoint, ColumnFamily, ColumnFamilyDescriptor, DBPinnableSlice, Options, SliceTransform, WriteBatch, WriteOpt...
impl Backend for Rocks { fn name(&self) -> &str { self.name.as_str() } fn create(path: &Path, name: String) -> Result<Self> where Self: Sized, { let mut opts = Options::default(); opts.create_if_missing(true); let path: PathBuf = path.into(); if!pa...
{ let prefix_size = IK::SIZE + N::SIZE; let mut opts = Options::default(); // for map state to work properly, but useful for all the states, so the bloom filters get // populated opts.set_prefix_extractor(SliceTransform::create_fixed_prefix(prefix_size as usize)); opts }
identifier_body
mod.rs
use crate::{ data::{Key, Metakey, Value}, error::*, Aggregator, AggregatorState, Backend, Handle, MapState, Reducer, ReducerState, ValueState, VecState, }; use rocksdb::{ checkpoint::Checkpoint, ColumnFamily, ColumnFamilyDescriptor, DBPinnableSlice, Options, SliceTransform, WriteBatch, WriteOpt...
} checkpointer.create_checkpoint(checkpoint_path)?; Ok(()) } fn register_value_handle<'s, T: Value, IK: Metakey, N: Metakey>( &'s self, handle: &'s mut Handle<ValueState<T>, IK, N>, ) { handle.registered = true; let opts = common_options::<IK, N>(); ...
// TODO: add a warning log here // warn!(logger, "Checkpoint path {:?} exists, deleting"); fs::remove_dir_all(checkpoint_path)?
random_line_split
reading.rs
use crate::{protocols::ReturnableConnection, Pea2Pea}; use async_trait::async_trait; use tokio::{ io::{AsyncRead, AsyncReadExt}, sync::mpsc, time::sleep, }; use tracing::*; use std::{io, net::SocketAddr, time::Duration}; /// Can be used to specify and enable reading, i.e. receiving inbound messages. /// ...
}
{ // don't do anything by default Ok(()) }
identifier_body
reading.rs
use crate::{protocols::ReturnableConnection, Pea2Pea}; use async_trait::async_trait; use tokio::{ io::{AsyncRead, AsyncReadExt}, sync::mpsc, time::sleep, }; use tracing::*; use std::{io, net::SocketAddr, time::Duration}; /// Can be used to specify and enable reading, i.e. receiving inbound messages. /// ...
(&self, source: SocketAddr, message: Self::Message) -> io::Result<()> { // don't do anything by default Ok(()) } }
process_message
identifier_name
reading.rs
use crate::{protocols::ReturnableConnection, Pea2Pea}; use async_trait::async_trait; use tokio::{ io::{AsyncRead, AsyncReadExt}, sync::mpsc, time::sleep, }; use tracing::*; use std::{io, net::SocketAddr, time::Duration}; /// Can be used to specify and enable reading, i.e. receiving inbound messages. /// ...
buffer: &[u8], ) -> io::Result<Option<(Self::Message, usize)>>; /// Processes an inbound message. Can be used to update state, send replies etc. #[allow(unused_variables)] async fn process_message(&self, source: SocketAddr, message: Self::Message) -> io::Result<()> { // don't do anythin...
&self, source: SocketAddr,
random_line_split
reading.rs
use crate::{protocols::ReturnableConnection, Pea2Pea}; use async_trait::async_trait; use tokio::{ io::{AsyncRead, AsyncReadExt}, sync::mpsc, time::sleep, }; use tracing::*; use std::{io, net::SocketAddr, time::Duration}; /// Can be used to specify and enable reading, i.e. receiving inbound messages. /// ...
else { node.disconnect(addr); break; } } }); conn.tasks.push(inbound_processing_task); // the task for reading messages from a stream ...
{ if let Err(e) = processing_clone.process_message(addr, msg).await { error!(parent: node.span(), "can't process an inbound message: {}", e); node.known_peers().register_failure(addr); ...
conditional_block
lib.rs
// Copyright 2018 Torsten Weber // // 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. This file may not be copied, modified, or distributed // except according t...
fn cause(&self) -> Option<&error::Error> { match *self { ReadError::Io(ref err) => Some(err), ReadError::Nom(_) => None, } } } /// A struct for process information /// /// This is the per process information contained in the `init` section /// of `lhe` files. /// When r...
{ match *self { ReadError::Io(..) => &"Failed to read the lhe file with an IO error", ReadError::Nom(..) => &"Failed to read the lhe file with a parse error", } }
identifier_body
lib.rs
// Copyright 2018 Torsten Weber // // 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. This file may not be copied, modified, or distributed // except according t...
self.color_1, self.color_2, self.momentum.px, self.momentum.py, self.momentum.pz, self.momentum.e, self.mass, self.proper_lifetime, self.spin ) } } #[cfg(test)] impl Arbitrary for Particle { fn a...
self.mother_2_id,
random_line_split
lib.rs
// Copyright 2018 Torsten Weber // // 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. This file may not be copied, modified, or distributed // except according t...
(input: &[u8]) -> nom::IResult<&[u8], Particle> { do_parse!( input, pdg_id: ws!(parse_i64) >> status: ws!(parse_i64) >> mother_1_id: ws!(parse_i64) >> mother_2_id: ws!(parse_i64) >> color_1: ws!(parse_i64) >> color_2: ws!(parse_i64) >> px: ws!(parse_f64) >...
read_lhe
identifier_name
lib.rs
use byteorder::{ByteOrder, LittleEndian}; use num_derive::FromPrimitive; use solana_program::{ account_info::next_account_info, account_info::AccountInfo, decode_error::DecodeError, entrypoint, entrypoint::ProgramResult, msg, program_error::ProgramError, program_pack::{Pack, Sealed}, ...
if bet_amount == 0 { msg!("Inavalid Bet"); return Err(DiceErr::InvalidBet.into()); } let lucky_number:u8 = 20; println!("Result {}", lucky_number); let mut win_amount:u32 = 0; if (1 == roll_type && lucky_number <= threshold) || (2 == roll_type && lucky_number >= threshold) { ...
{ msg!("Not Enough Balance"); return Err(DiceErr::NotEnoughBalance.into()); }
conditional_block
lib.rs
use byteorder::{ByteOrder, LittleEndian}; use num_derive::FromPrimitive; use solana_program::{ account_info::next_account_info, account_info::AccountInfo, decode_error::DecodeError, entrypoint, entrypoint::ProgramResult, msg, program_error::ProgramError, program_pack::{Pack, Sealed}, ...
let sysvar_account = next_account_info(accounts_iter)?; let rent = &Rent::from_account_info(sysvar_account)?; if!sysvar::rent::check_id(sysvar_account.key) { msg!("Rent system account is not rent system account"); return Err(ProgramError::InvalidAccountData); } if!rent.is_exempt(play...
} // The account must be rent exempt, i.e. live forever
random_line_split
lib.rs
use byteorder::{ByteOrder, LittleEndian}; use num_derive::FromPrimitive; use solana_program::{ account_info::next_account_info, account_info::AccountInfo, decode_error::DecodeError, entrypoint, entrypoint::ProgramResult, msg, program_error::ProgramError, program_pack::{Pack, Sealed}, ...
{ #[error("Unexpected Roll Mode")] UnexpectedRollMode, #[error("Incrrect Threshold")] IncorrectThreshold, #[error("Incorrect Owner")] IncorrectOwner, #[error("Account Not Rent Exempt")] AccountNotRentExempt, #[error("Account Not Balance Account")] AccountNotBalanceAccount, #...
DiceErr
identifier_name
main.rs
extern crate csv; extern crate serde; // This lets us write `#[derive(Deserialize)]`. #[macro_use] extern crate serde_derive; use std::collections::HashMap; use std::env; use std::fs::File; use std::io; use std::{error::Error, ffi::OsString, process}; // fn main_not_recover() { // println!("Hello, world!"); // ...
// 一度だけ、メモ リにアロケーションする。読み込まれるたびに上書きされていくため、高速化する。 let mut record = csv::ByteRecord::new(); let mut count = 0; while reader.read_byte_record(&mut record)? { if &record[0] == b"us" && &record[3] == b"MA" { count += 1; } } Ok(count) } #[derive(Debug, Deserialize)] #[...
cpu 5.094 total // String からbyteで処理をするように変更した。 fn performance2_read_csv() -> Result<u64, Box<dyn Error>> { let mut reader = csv::Reader::from_reader(io::stdin()); let mut count = 0; for result in reader.byte_records() { let record = result?; if &record[0] == b"us" && &record[3] == b"MA" { ...
identifier_body
main.rs
extern crate csv; extern crate serde; // This lets us write `#[derive(Deserialize)]`. #[macro_use] extern crate serde_derive; use std::collections::HashMap; use std::env; use std::fs::File; use std::io; use std::{error::Error, ffi::OsString, process}; // fn main_not_recover() { // println!("Hello, world!"); // ...
} // utf-8に変換できない場合の対処法。 // byteで読み込む!!! fn read_and_write_byte_csv() -> Result<(), Box<dyn Error>> { let argss = match env::args().nth(1) { None => return Err(From::from("expected 1 argument, but got none")), Some(argument) => argument, }; // CSVリーダー(stdin)とCSVライター(stdout)を構築する let mu...
} wtr.flush()?; Ok(())
random_line_split
main.rs
extern crate csv; extern crate serde; // This lets us write `#[derive(Deserialize)]`. #[macro_use] extern crate serde_derive; use std::collections::HashMap; use std::env; use std::fs::File; use std::io; use std::{error::Error, ffi::OsString, process}; // fn main_not_recover() { // println!("Hello, world!"); // ...
us" && &record[3] == "MA" { count += 1; } } Ok(count) } //./csv_example < worldcitiespop.csv 1.69s user 0.05s system 34% cpu 5.094 total // String からbyteで処理をするように変更した。 fn performance2_read_csv() -> Result<u64, Box<dyn Error>> { let mut reader = csv::Reader::from_reader(io::stdin()); ...
ord[0] == "
identifier_name
planning.rs
use cargo::CargoError; use cargo::core::Dependency; use cargo::core::Package as CargoPackage; use cargo::core::PackageId; use cargo::core::PackageSet; use cargo::core::Resolve; use cargo::core::SourceId; use cargo::core::Workspace; use cargo::core::dependency::Kind; use cargo::ops::Packages; use cargo::ops; use cargo::...
(&mut self, host: String) -> CargoResult<()> { match host.to_url().map(|url| SourceId::for_registry(&url)) { Ok(registry_id) => { self.registry = Some(registry_id); Ok(()) }, Err(value) => Err(CargoError::from(value)) } } pub fn plan_build(&self) -> CargoResult<PlannedBuil...
set_registry_from_url
identifier_name
planning.rs
use cargo::CargoError; use cargo::core::Dependency; use cargo::core::Package as CargoPackage; use cargo::core::PackageId; use cargo::core::PackageSet; use cargo::core::Resolve; use cargo::core::SourceId; use cargo::core::Workspace; use cargo::core::dependency::Kind; use cargo::ops::Packages; use cargo::ops; use cargo::...
else { normal_deps }; crate_contexts.push(CrateContext { pkg_name: id.name().to_owned(), pkg_version: id.version().to_string(), features: features, is_root_dependency: root_direct_deps.contains(&id), metadeps: Vec::n...
{ normal_deps.into_iter() .filter(|d| !s.skipped_deps.contains(&format!("{}-{}", d.name, d.version))) .collect::<Vec<_>>() }
conditional_block
planning.rs
use cargo::CargoError; use cargo::core::Dependency; use cargo::core::Package as CargoPackage; use cargo::core::PackageId; use cargo::core::PackageSet;
use cargo::ops::Packages; use cargo::ops; use cargo::util::CargoResult; use cargo::util::Cfg; use cargo::util::Config; use cargo::util::ToUrl; use context::BuildDependency; use context::BuildTarget; use context::CrateContext; use context::WorkspaceContext; use settings::RazeSettings; use settings::GenMode; use std::col...
use cargo::core::Resolve; use cargo::core::SourceId; use cargo::core::Workspace; use cargo::core::dependency::Kind;
random_line_split
main.rs
fn main() { // defining a variable println!("-------defining a variable"); println!("Hello, Hooman!"); let mut x = 45; // all variables initially are immutable otherwise it is mentioned println!("The value of x is {}", x); x = 10; println!("The value of x is {}", x); let y: i64; y =...
(c: &Color2) { println!("Color - R:{} G:{} B:{}", c.0, c.1, c.2); } print_color(bg); /* print_color(bg); *impossible */ print_color2(&bg2); print_color2(&bg2); print_color2(&bg2); // it is possible to have multile function invocation due to it is called by reference // array...
print_color2
identifier_name
main.rs
fn main() { // defining a variable println!("-------defining a variable"); println!("Hello, Hooman!"); let mut x = 45; // all variables initially are immutable otherwise it is mentioned println!("The value of x is {}", x); x = 10; println!("The value of x is {}", x); let y: i64; y =...
else { println!("{} is odd", i); } } } count_to(7); fn is_even(num: u32) -> bool { return num % 2 == 0; } let number = 12; println!("is {} even? {}", number, is_even(number)); // reference println!("-------references"); let mut x = 7; ...
{ println!("{} is even", i); }
conditional_block
main.rs
fn main() { // defining a variable println!("-------defining a variable"); println!("Hello, Hooman!"); let mut x = 45; // all variables initially are immutable otherwise it is mentioned println!("The value of x is {}", x); x = 10; println!("The value of x is {}", x); let y: i64; y =...
} let rectangle: Rectangle = Rectangle {height: 30, width: 10, }; rectangle.print_description(); println!("The given rectangle is square? {}", rectangle.is_square()); println!("Area is {} and perimeter is {}", rectangle.area(), rectangle.perimeter()); // Strings println!("-------Strings")...
{ return (self.width + self.height) * 2; }
identifier_body
main.rs
fn main() { // defining a variable println!("-------defining a variable"); println!("Hello, Hooman!"); let mut x = 45; // all variables initially are immutable otherwise it is mentioned println!("The value of x is {}", x); x = 10; println!("The value of x is {}", x); let y: i64; y =...
}
random_line_split
timer.rs
//! The nRF51822 timer system operates off of the high frequency clock //! (HFCLK) and provides three timers from the clock. Timer0 is tied //! to the radio through some hard-coded peripheral linkages (e.g., there //! are dedicated PPI connections between Timer0's compare events and //! radio tasks, its capture tasks a...
(&self, which: u8) { let _ = self.capture(which); } /// Shortcuts can automatically stop or clear the timer on a particular /// compare event; refer to section 18.3 of the nRF reference manual /// for details. Implementation currently provides shortcuts as the /// raw bitmask. pub fn ge...
capture_to
identifier_name
timer.rs
//! The nRF51822 timer system operates off of the high frequency clock //! (HFCLK) and provides three timers from the clock. Timer0 is tied //! to the radio through some hard-coded peripheral linkages (e.g., there //! are dedicated PPI connections between Timer0's compare events and //! radio tasks, its capture tasks a...
_ => { self.timer().task_capture[3].set(1); self.timer().cc[3].get() } } } /// Capture the current value to the CC register specified by /// which and do not return the value. pub fn capture_to(&self, which: u8) { let _ = self.cap...
{ self.timer().task_capture[2].set(1); self.timer().cc[2].get() }
conditional_block
timer.rs
//! The nRF51822 timer system operates off of the high frequency clock //! (HFCLK) and provides three timers from the clock. Timer0 is tied //! to the radio through some hard-coded peripheral linkages (e.g., there //! are dedicated PPI connections between Timer0's compare events and //! radio tasks, its capture tasks a...
pub fn set_shortcuts(&self, shortcut: u32) { self.timer().shorts.set(shortcut); } pub fn get_cc0(&self) -> u32 { self.timer().cc[0].get() } pub fn set_cc0(&self, val: u32) { self.timer().cc[0].set(val); } pub fn get_cc1(&self) -> u32 { self.timer().cc[1].get...
{ self.timer().shorts.get() }
identifier_body
timer.rs
//! The nRF51822 timer system operates off of the high frequency clock //! (HFCLK) and provides three timers from the clock. Timer0 is tied //! to the radio through some hard-coded peripheral linkages (e.g., there //! are dedicated PPI connections between Timer0's compare events and //! radio tasks, its capture tasks a...
//! This implementation provides a full-fledged Timer interface to //! timers 0 and 2, and exposes Timer1 as an HIL Alarm, for a Tock //! timer system. It may be that the Tock timer system should be ultimately //! placed on top of the RTC (from the low frequency clock). It's currently //! implemented this way as a demo...
random_line_split
session_data.rs
use super::{ configuration::{self, CoreConfig, SessionConfig}, core_data::{CoreData, CoreHandle}, }; use crate::cmd::dap_server::{ debug_adapter::{ dap::adapter::DebugAdapter, dap::dap_types::Source, protocol::ProtocolAdapter, }, DebuggerError, }; use anyhow::{anyhow, Result}; use probe_rs::...
/// A breakpoint was requested using an instruction address, and usually a result of a user requesting a /// breakpoint while in a 'disassembly' view. InstructionBreakpoint, /// A breakpoint that has a Source, and usually a result of a user requesting a breakpoint while in a'source' view. SourceBrea...
/// The supported breakpoint types #[derive(Clone, Debug, PartialEq)] pub(crate) enum BreakpointType {
random_line_split