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
state.rs
// Copyright 2014 The Gfx-rs 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 ag...
else {gl::TRUE}, if (color.mask & s::BLUE ).is_empty() {gl::FALSE} else {gl::TRUE}, if (color.mask & s::ALPHA).is_empty() {gl::FALSE} else {gl::TRUE} )}; } pub fn bind_blend_slot(gl: &gl::Gl, slot: ColorSlot, color: s::Color) { let buf = slot as gl::types::GLuint; match color.blend { ...
{gl::FALSE}
conditional_block
state.rs
// Copyright 2014 The Gfx-rs 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 ag...
(gl: &gl::Gl, color: s::Color) { match color.blend { Some(b) => unsafe { gl.Enable(gl::BLEND); gl.BlendEquationSeparate( map_equation(b.color.equation), map_equation(b.alpha.equation) ); gl.BlendFuncSeparate( map...
bind_blend
identifier_name
state.rs
// Copyright 2014 The Gfx-rs 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 ag...
}, } } pub fn bind_rasterizer(gl: &gl::Gl, r: &s::Rasterizer, is_embedded: bool) { unsafe { gl.FrontFace(match r.front_face { FrontFace::Clockwise => gl::CW, FrontFace::CounterClockwise => gl::CCW, }) }; match r.cull_face { CullFace::Nothing ...
random_line_split
state.rs
// Copyright 2014 The Gfx-rs 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 ag...
pub fn bind_blend(gl: &gl::Gl, color: s::Color) { match color.blend { Some(b) => unsafe { gl.Enable(gl::BLEND); gl.BlendEquationSeparate( map_equation(b.color.equation), map_equation(b.alpha.equation) ); gl.BlendFuncSeparate( ...
{ match factor { s::Factor::Zero => gl::ZERO, s::Factor::One => gl::ONE, s::Factor::ZeroPlus(BlendValue::SourceColor) => gl::SRC_COLOR, s::Factor::OneMinus(BlendValue::SourceColor) => gl::ONE_MINUS_SRC_COLOR, s::Facto...
identifier_body
proxy.rs
// Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! Runs hardware devices in child processes. use std::fmt::{self, Display}; use std::time::Duration; use std::{self, io}; use base::{error, net::Uni...
Ok(r) => Some(r), } } } impl BusDevice for ProxyDevice { fn debug_label(&self) -> String { self.debug_label.clone() } fn config_register_write(&mut self, reg_idx: usize, offset: u64, data: &[u8]) { let len = data.len() as u32; let mut buffer = [0u8; 4]; ...
{ error!( "failed to read result of {:?} from child device process {}: {}", cmd, self.debug_label, e, ); None }
conditional_block
proxy.rs
// Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! Runs hardware devices in child processes. use std::fmt::{self, Display}; use std::time::Duration; use std::{self, io}; use base::{error, net::Uni...
(&mut self, info: BusAccessInfo, data: &[u8]) { let mut buffer = [0u8; 8]; let len = data.len() as u32; buffer[0..data.len()].clone_from_slice(data); self.send_no_result(&Command::Write { len, info, data: buffer, }); } } impl Drop for Prox...
write
identifier_name
proxy.rs
// Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! Runs hardware devices in child processes. use std::fmt::{self, Display}; use std::time::Duration; use std::{self, io}; use base::{error, net::Uni...
self.data = data[0]; } fn read(&mut self, _info: BusAccessInfo, data: &mut [u8]) { assert!(data.len() == 1); data[0] = self.data; } fn config_register_write(&mut self, _reg_idx: usize, _offset: u64, data: &[u8]) { assert!(data.len() == 1)...
"EchoDevice".to_owned() } fn write(&mut self, _info: BusAccessInfo, data: &[u8]) { assert!(data.len() == 1);
random_line_split
client.rs
// Copyright (C) 2020 Jason Ish // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // ...
.map_err(|_| ClientError::VersionParseError(s.to_string()))?; } } let version = Version { version: s.to_string(), major, minor, patch, }; Ok(version) } pub fn as_u64(&self) -> u64 { (self.majo...
patch = part .parse::<u64>()
random_line_split
client.rs
// Copyright (C) 2020 Jason Ish // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // ...
(&mut self, yes: bool) -> &Self { self.disable_certificate_validation = yes; self } pub fn with_username(&mut self, username: &str) -> &Self { self.username = Some(username.to_string()); self } pub fn with_password(&mut self, password: &str) -> &Self { self.pass...
disable_certificate_validation
identifier_name
client.rs
// Copyright (C) 2020 Jason Ish // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // ...
} #[cfg(test)] mod test { use super::*; #[test] pub fn test_version_compare() { assert_eq!( Version::parse("1.1.1").unwrap(), Version::parse("1.1.1").unwrap() ); assert!(Version::parse("7.7.0").unwrap() < Version::parse("7.7.1").unwrap()); assert!(V...
{ if !self.has_error() { return None; } if let Some(error) = &self.error { return Some(error.to_string()); } if let Some(items) = &self.items { for item in items { if let serde_json::Value::String(err) = &item["index"]["error"][...
identifier_body
client.rs
// Copyright (C) 2020 Jason Ish // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // ...
; Ok(request) } pub fn post(&self, path: &str) -> Result<reqwest::RequestBuilder, reqwest::Error> { let url = format!("{}/{}", self.url, path); let request = self .get_http_client()? .post(&url) .header("Content-Type", "application/json"); let re...
{ request }
conditional_block
interactive.rs
event::{Event, KeyCode, KeyEvent, KeyModifiers}, style::{style, Attribute, Color, ContentStyle, Print, PrintStyledContent, StyledContent}, terminal, QueueableCommand, }; use std::convert::TryFrom; use std::io::{stdin, stdout}; use std::path::Path; const HELP: &'static str = r##"y - apply this suggestion n ...
pub fn to_bandaid(&self) -> BandAid { if self.is_custom_entry() { BandAid::from(( self.custom_replacement.clone(), self.suggestion.span.clone(), )) } else { BandAid::try_from((self.suggestion, self.pick_idx)) .expec...
{ self.pick_idx + 1 == self.n_items }
identifier_body
interactive.rs
event::{Event, KeyCode, KeyEvent, KeyModifiers}, style::{style, Attribute, Color, ContentStyle, Print, PrintStyledContent, StyledContent}, terminal, QueueableCommand, }; use std::convert::TryFrom; use std::io::{stdin, stdout}; use std::path::Path; const HELP: &'static str = r##"y - apply this suggestion n ...
{ Replacement(BandAid), /// Skip this suggestion and move on to the next suggestion. Skip, /// Jump to the previous suggestion. Previous, /// Print the help message and exit. Help, /// Skip the remaining fixes for the current file. SkipFile, /// Stop execution. Quit, ///...
Pick
identifier_name
interactive.rs
use crossterm; use crossterm::{ cursor, event::{Event, KeyCode, KeyEvent, KeyModifiers}, style::{style, Attribute, Color, ContentStyle, Print, PrintStyledContent, StyledContent}, terminal, QueueableCommand, }; use std::convert::TryFrom; use std::io::{stdin, stdout}; use std::path::Path; const HELP: &...
//! //! The result of that pick is a bandaid. use super::*;
random_line_split
hackc.rs
// Copyright (c) Meta Platforms, Inc. and affiliates. // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. mod assemble; mod cmp_unit; mod compile; mod crc; mod expr_trees; mod facts; mod parse; mod util; mod verify; use ::compile::EnvFlags; us...
#[cfg(test)] mod tests { use super::*; /// Just make sure json parsing produces a proper list. /// If the alias map length changes, keep this test in sync. #[test] fn test_auto_namespace_map() { let dp_opts = Opts::default().decl_opts(); assert_eq!(dp_opts.auto_namespace_map.len()...
{ use std::io::Write; for line in std::io::stdin().lock().lines() { let mut buf = Vec::new(); f(Path::new(&line?).to_path_buf(), &mut buf)?; // Account for utf-8 encoding and text streams with the python test runner: // https://stackoverflow.com/questions/3586923/counting-unicode...
identifier_body
hackc.rs
// Copyright (c) Meta Platforms, Inc. and affiliates. // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. mod assemble; mod cmp_unit; mod compile; mod crc; mod expr_trees; mod facts; mod parse; mod util; mod verify; use ::compile::EnvFlags; us...
{ /// Input file(s) filenames: Vec<PathBuf>, /// Read a list of files (one-per-line) from this file #[clap(long)] input_file_list: Option<PathBuf>, } #[derive(Parser, Debug)] enum Command { /// Assemble HHAS file(s) into HackCUnit. Prints those HCUs' HHAS representation. Assemble(assemble...
FileOpts
identifier_name
hackc.rs
// Copyright (c) Meta Platforms, Inc. and affiliates. // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. mod assemble; mod cmp_unit; mod compile; mod crc; mod expr_trees; mod facts; mod parse; mod util; mod verify; use ::compile::EnvFlags; us...
// Test Decls-in-Compilation None if opts.daemon && opts.flag_commands.test_compile_with_decls => { compile::test_decl_compile_daemon(&mut opts) } None if opts.flag_commands.test_compile_with_decls => { compile::test_decl_compile(&mut opts, &mut std::io::stdout(...
{ facts::run_flag(&mut opts, &mut std::io::stdout()) }
conditional_block
hackc.rs
// Copyright (c) Meta Platforms, Inc. and affiliates. // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. mod assemble; mod cmp_unit; mod compile; mod crc; mod expr_trees; mod facts; mod parse; mod util; mod verify; use ::compile::EnvFlags; us...
for_debugger_eval: bool, #[clap(long, default_value("0"))] emit_class_pointers: i32, #[clap(long, default_value("0"))] check_int_overflow: i32, /// Number of parallel worker threads for subcommands that support parallelism, /// otherwise ignored. If 0, use available parallelism, typically...
#[clap(long)] disable_toplevel_elaboration: bool, /// Mutate the program as if we're in the debugger repl #[clap(long)]
random_line_split
fiber.rs
//! Сooperative multitasking module //! //! With the fiber module, you can: //! - create, run and manage [fibers](struct.Fiber.html), //! - use a synchronization mechanism for fibers, similar to “condition variables” and similar to operating-system //! functions such as `pthread_cond_wait()` plus `pthread_cond_signal()...
pub fn try_lock(&self) -> Option<LatchGuard> { if unsafe { ffi::box_latch_trylock(self.inner) } == 0 { Some(LatchGuard { latch_inner: self.inner, }) } else { None } } } impl Drop for Latch { fn drop(&mut self) { unsafe { ff...
/// - `None` - the latch is locked.
random_line_split
fiber.rs
//! Сooperative multitasking module //! //! With the fiber module, you can: //! - create, run and manage [fibers](struct.Fiber.html), //! - use a synchronization mechanism for fibers, similar to “condition variables” and similar to operating-system //! functions such as `pthread_cond_wait()` plus `pthread_cond_signal()...
{ unsafe { ffi::fiber_wakeup(self.inner) } } /// Wait until the fiber is dead and then move its execution status to the caller. /// /// “Join” a joinable fiber. That is, let the fiber’s function run and wait until the fiber’s status is **dead** /// (normally a status becomes **dead** when ...
&self)
identifier_name
fiber.rs
//! Сooperative multitasking module //! //! With the fiber module, you can: //! - create, run and manage [fibers](struct.Fiber.html), //! - use a synchronization mechanism for fibers, similar to “condition variables” and similar to operating-system //! functions such as `pthread_cond_wait()` plus `pthread_cond_signal()...
op for Latch { fn drop(&mut self) { unsafe { ffi::box_latch_delete(self.inner) } } } /// An RAII implementation of a "scoped lock" of a latch. When this structure is dropped (falls out of scope), /// the lock will be unlocked. pub struct LatchGuard { latch_inner: *mut ffi::Latch, } impl Drop for L...
e } } } impl Dr
conditional_block
fiber.rs
//! Сooperative multitasking module //! //! With the fiber module, you can: //! - create, run and manage [fibers](struct.Fiber.html), //! - use a synchronization mechanism for fibers, similar to “condition variables” and similar to operating-system //! functions such as `pthread_cond_wait()` plus `pthread_cond_signal()...
the execution of the current fiber (i.e. yield) until [signal()](#method.signal) is called. /// /// Like pthread_cond, FiberCond can issue spurious wake ups caused by explicit /// [Fiber::wakeup()](struct.Fiber.html#method.wakeup) or [Fiber::cancel()](struct.Fiber.html#method.cancel) /// calls. It is h...
{ ffi::fiber_cond_broadcast(self.inner) } } /// Suspend
identifier_body
ballot.rs
use indexmap::IndexMap; use prost::Message; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Ballot { pub id: String, pub contests: Vec<u32>, // List of contest indexes /// Application specific properties. /// /// Hashmaps are not allowed because their unstable ordering leads to non-dete...
#[serde(default)] pub write_in: bool, /// Score has different meanings depending on the tally type: /// STV, Condorcet, Borda and Schulze: `score` means candidate rank, where a zero is the best rank that can be assigned to a candidate. /// Score: `score` is the points assinged to this candidate. Ze...
#[derive(Serialize, Deserialize, Clone, Message, PartialEq, Eq)] pub struct Selection { /// true if the `selection` field is a free-form write-in, false if the `selection` field corresponds to a known candidate-id #[prost(bool)]
random_line_split
ballot.rs
use indexmap::IndexMap; use prost::Message; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct
{ pub id: String, pub contests: Vec<u32>, // List of contest indexes /// Application specific properties. /// /// Hashmaps are not allowed because their unstable ordering leads to non-determinism. #[serde(default)] #[serde(skip_serializing_if = "IndexMap::is_empty")] pub properties: In...
Ballot
identifier_name
universe.rs
/*! # RS Mate Poe: Universe */ use crate::{ Frame, Position, State, }; #[cfg(feature = "director")] use crate::{Animation, dom}; use std::sync::atomic::{ AtomicU8, AtomicU32, AtomicU64, Ordering::SeqCst, }; #[cfg(feature = "director")] use std::sync::atomic::AtomicU16; #[cfg(target_arch = "wasm32")] use wasm_bi...
[cfg(feature = "firefox")] /// # Fix Element Bindings? /// /// Returns `true` if one or both elements seem to have disappeared from /// the document body since the last time this method was called. pub(crate) fn fix_bindings() -> bool { let old = FLAGS.fetch_and(! Self::FIX_BINDINGS, SeqCst); let expected = Se...
let old = FLAGS.fetch_and(! Self::ASSIGN_CHILD, SeqCst); Self::ASSIGN_CHILD == old & Self::ASSIGN_CHILD } #
identifier_body
universe.rs
/*! # RS Mate Poe: Universe */ use crate::{ Frame, Position, State, }; #[cfg(feature = "director")] use crate::{Animation, dom}; use std::sync::atomic::{ AtomicU8, AtomicU32, AtomicU64, Ordering::SeqCst, }; #[cfg(feature = "director")] use std::sync::atomic::AtomicU16; #[cfg(target_arch = "wasm32")] use wasm_bi...
> bool { let old = FLAGS.fetch_and(! Self::ASSIGN_CHILD, SeqCst); Self::ASSIGN_CHILD == old & Self::ASSIGN_CHILD } #[cfg(feature = "firefox")] /// # Fix Element Bindings? /// /// Returns `true` if one or both elements seem to have disappeared from /// the document body since the last time this method was cal...
gn_child() -
identifier_name
universe.rs
/*! # RS Mate Poe: Universe */ use crate::{ Frame, Position, State, }; #[cfg(feature = "director")] use crate::{Animation, dom}; use std::sync::atomic::{ AtomicU8, AtomicU32, AtomicU64, Ordering::SeqCst, }; #[cfg(feature = "director")] use std::sync::atomic::AtomicU16; #[cfg(target_arch = "wasm32")] use wasm_bi...
assert_eq!(Universe::rand_mod(0), 0, "Random zero broke!"); let set = (0..5000_u16).into_iter() .map(|_| Universe::rand_mod(100)) .collect::<HashSet<u16>>(); assert!(set.iter().all(|n| *n < 100), "Value(s) out of range."); assert_eq!( set.len(), 100, "Failed to collect 100/100 possibilities in ...
use super::*; use std::collections::HashSet; #[test] fn t_rand() {
random_line_split
lib.rs
//working off example (spi): https://github.com/japaric/mfrc522/blob/master/src/lib.rs //another example: https://github.com/JohnDoneth/hd44780-driver/blob/master/examples/raspberrypi/src/main.rs //#![no_std] //FIXME TODO remove all std lib dependencies extern crate embedded_hal as hal; #[macro_use] extern crate bitfl...
(&mut self) -> Result<(),&'static str> { //self.cs.set_high(); //check if the radio responds by seeing if we can change a register let mut synced = false; for _attempt in 0..100 { self.write_reg(Register::Syncvalue1, 0xAA); //170 self.delay.delay_ms(1); if self.read_reg(Register::Syncvalue1) == 0xAA {...
init
identifier_name
lib.rs
//working off example (spi): https://github.com/japaric/mfrc522/blob/master/src/lib.rs //another example: https://github.com/JohnDoneth/hd44780-driver/blob/master/examples/raspberrypi/src/main.rs //#![no_std] //FIXME TODO remove all std lib dependencies extern crate embedded_hal as hal; #[macro_use] extern crate bitfl...
fn switch_transceiver_mode(&mut self, new_mode: RadioMode) { use registers::OpMode; let old_flag = self.register_flags.mode - OpMode::Mode; self.register_flags.mode = match new_mode { RadioMode::Sleep => old_flag | OpMode::Sleep, // Xtal Off RadioMode::Standby => old_flag | OpMode::Standby, // Xtal On ...
{ if !self.register_flags.mode.contains(registers::OpMode::Sequencer_Off) { self.register_flags.mode |= registers::OpMode::Sequencer_Off; self.write_reg(Register::Opmode, self.register_flags.mode.bits()); self.switch_freq()?; self.register_flags.mode -= registers::OpMode::Sequencer_Off; self.wr...
identifier_body
lib.rs
//working off example (spi): https://github.com/japaric/mfrc522/blob/master/src/lib.rs //another example: https://github.com/JohnDoneth/hd44780-driver/blob/master/examples/raspberrypi/src/main.rs //#![no_std] //FIXME TODO remove all std lib dependencies extern crate embedded_hal as hal; #[macro_use] extern crate bitfl...
//self.cs.set_high(); //check if the radio responds by seeing if we can change a register let mut synced = false; for _attempt in 0..100 { self.write_reg(Register::Syncvalue1, 0xAA); //170 self.delay.delay_ms(1); if self.read_reg(Register::Syncvalue1) == 0xAA { synced = true; break; } } ...
random_line_split
http_service_util.rs
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { failure::{bail, Error, ResultExt}, fidl_fuchsia_net_oldhttp::{self as http, HttpServiceProxy}, fuchsia_async as fasync, fuchsia_syslo...
#[test] fn zero_byte_download_triggers_error() { let test_url = "https://test.example/sample/url"; let url_req = create_url_request(test_url.to_string()); // creating a response with some bytes "downloaded" let bytes = "".as_bytes(); let (s1, s2) = zx::Socket::create(z...
{ let test_url = "https://test.example/sample/url"; let url_req = create_url_request(test_url.to_string()); // creating a response with some bytes "downloaded" let bytes = "there are some bytes".as_bytes(); let (s1, s2) = zx::Socket::create(zx::SocketOpts::STREAM).unwrap(); ...
identifier_body
http_service_util.rs
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { failure::{bail, Error, ResultExt}, fidl_fuchsia_net_oldhttp::{self as http, HttpServiceProxy}, fuchsia_async as fasync, fuchsia_syslo...
( request: UrlRequest, mut response: UrlResponse, ) -> Result<IndividualDownload, Error> { let mut exec = fasync::Executor::new().expect("failed to create an executor"); let (http_service, server) = create_http_service_util(); let mut next_http_service_req = server.into_futur...
trigger_download_with_supplied_response
identifier_name
http_service_util.rs
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { failure::{bail, Error, ResultExt}, fidl_fuchsia_net_oldhttp::{self as http, HttpServiceProxy}, fuchsia_async as fasync, fuchsia_syslo...
// Object to hold results of a single download #[derive(Default)] pub struct IndividualDownload { pub bytes: u64, pub nanos: u64, pub goodput_mbps: f64, } // TODO (NET-1664): verify checksum on data received pub async fn fetch_and_discard_url( http_service: &HttpServiceProxy, mut url_request: http...
auto_follow_redirects: true, cache_mode: http::CacheMode::Default, response_body_mode: http::ResponseBodyMode::Stream, } }
random_line_split
sumtree.rs
Actual data Leaf(T::Sum), /// Node with 2^n children Internal { lchild: Box<NodeData<T>>, rchild: Box<NodeData<T>>, sum: T::Sum, }, } impl<T: Summable> Summable for Node<T> { type Sum = T::Sum; fn sum(&self) -> T::Sum { match *self { Node::Pruned(ref sum) => sum.clone(), Node::Leaf(ref sum) => sum...
(node: &NodeData<T>) -> NodeData<T> { if node.full { // replaces full internal nodes, leaves and already pruned nodes are full // as well NodeData { full: true, node: Node::Pruned(node.sum()), hash: node.hash, depth: node.depth, } } else { if let Node::...
clone_pruned_recurse
identifier_name
sumtree.rs
/// Actual data Leaf(T::Sum), /// Node with 2^n children Internal { lchild: Box<NodeData<T>>, rchild: Box<NodeData<T>>, sum: T::Sum, }, } impl<T: Summable> Summable for Node<T> { type Sum = T::Sum; fn sum(&self) -> T::Sum { match *self { Node::Pruned(ref sum) => sum.clone(), Node::Leaf(ref sum) => ...
TestElem([0, 0, 0, 3]), TestElem([0, 0, 0, 4]), TestElem([0, 0, 0, 5]), TestElem([0, 0, 0, 6]), TestElem([0, 0, 0, 7]), TestElem([1, 0, 0, 0]), ]; assert_eq!(tree.root_sum(), None); assert_eq!(tree.root_sum(), compute_root(elems[0..0].iter())); assert_eq!(tree.len(), 0); assert_eq!(tree.con...
TestElem([0, 0, 0, 2]),
random_line_split
ply.rs
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 License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS...
{ format: Format, elements: Vec<Element>, offset: Vector3<f64>, } #[derive(Debug, Copy, Clone, PartialEq)] enum DataType { Int8, Uint8, Int16, Uint16, Int32, Uint32, Float32, Float64, } impl DataType { fn from_str(input: &str) -> Result<Self> { match input { ...
Header
identifier_name
ply.rs
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 License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDI...
create_and_return_reading_fn!($assign, $size, 8, LittleEndian::read_f64) } } }; } // Similar to 'create_and_return_reading_fn', but creates a function that just advances the read // pointer. macro_rules! create_skip_fn { (&mut $size:ident, $num_bytes:expr) => {{ $siz...
} DataType::Float64 => {
random_line_split
ply.rs
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 License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS...
current_element.as_mut().unwrap().properties.push(property); } "end_header" => break, "comment" => { if entries.len() == 5 && entries[1] == "offset:" { let x = entries[2] .parse::<f64>() ...
{ if current_element.is_none() { return Err( InvalidInput(format!("property outside of element: {}", line)).into(), ); }; let property = match entries[1] { "list" if entries.len() == 5 => ...
conditional_block
main.rs
let (border, (bw, bh)) = (self.border, self.button_dim); if y >= border && y < border + bh && x >= border && (x - border) % (bw + border) < bw { Some((x - border) / (bw + border)) } else { None } } pub fn button_bounds(&self, i: us...
} else { self.cfg.nb }; } else { shm[(i, j)] = (self.cfg.nb & 0xffffff) | 0x22000000; } } } let scale = |v: u8, s: u8| ((v as u32 * s as u32) / 255) as u8; let (nf, sf...
{ if self.buffer.locked { return; } let shm = &mut self.buffer; let (bw, bh) = self.cfg.button_dim; let focus = { let cfg = &self.cfg; (self.ptr.btn) .filter(|s| s == &wl_pointer::ButtonState::Pressed) .and(self...
identifier_body
main.rs
let (border, (bw, bh)) = (self.border, self.button_dim); if y >= border && y < border + bh && x >= border && (x - border) % (bw + border) < bw { Some((x - border) / (bw + border)) } else { None } } pub fn button_bounds(&self, i: u...
Surface { wl, layer, committed: false, configured: false, } } fn render(&mut self) { if self.buffer.locked { return; } let shm = &mut self.buffer; let (bw, bh) = self.cfg.button_dim; let focus ...
random_line_split
main.rs
let (border, (bw, bh)) = (self.border, self.button_dim); if y >= border && y < border + bh && x >= border && (x - border) % (bw + border) < bw { Some((x - border) / (bw + border)) } else { None } } pub fn button_bounds(&self, i: us...
(pub u32); static ARGB_FORMAT_MSG: &str = "Argb must be specified by a '#' followed by exactly 3, 4, 6, or 8 digits"; impl FromStr for Argb { type Err = anyhow::Error; fn from_str(s: &str) -> Result<Self> { if!s.starts_with('#') ||!s[1..].chars().all(|c| c.is_ascii_hexdigit...
Argb
identifier_name
lib.rs
#![cfg_attr(feature = "nightly", feature(const_panic))] extern crate proc_macro; use proc_macro2::TokenStream; use quote::{quote, quote_spanned}; use syn::parse_macro_input; use syn::Item; /// Generate B1, B2,.., B64 with implementation of the Specifier trait #[proc_macro] pub fn generate_bit_specifiers(_input: proc...
} None }); let getters_setters = define_getters_setters(&s.fields); // Total size calculated as the sum of the inner `<T as Specifier>::BITS` associated consts let total_bit_size = quote!(0 #(+ <#fields_ty as Specifier>::BITS)...
{ // At this point `attr.tokens` is the following part of the attribute: // #[bits=..] // ^^^ let bits = syn::parse2::<BitAttribute>(attr.tokens.clone()).ok()?.bits; return S...
conditional_block
lib.rs
#![cfg_attr(feature = "nightly", feature(const_panic))] extern crate proc_macro; use proc_macro2::TokenStream; use quote::{quote, quote_spanned}; use syn::parse_macro_input; use syn::Item; /// Generate B1, B2,.., B64 with implementation of the Specifier trait #[proc_macro] pub fn generate_bit_specifiers(_input: proc...
// Check that fields with #[bits=X] attribute have a type of size `X` // We use an array size check to validate the size is correct let bits_attrs_check = s .fields .iter() .filter_map(|field| { let ty = &field.ty; ...
random_line_split
lib.rs
#![cfg_attr(feature = "nightly", feature(const_panic))] extern crate proc_macro; use proc_macro2::TokenStream; use quote::{quote, quote_spanned}; use syn::parse_macro_input; use syn::Item; /// Generate B1, B2,.., B64 with implementation of the Specifier trait #[proc_macro] pub fn generate_bit_specifiers(_input: proc...
() -> TokenStream { quote!( #[doc = "Simple trait to extract bits from primitive integer type"] trait BitOps { fn first(self, n: usize) -> u8; fn last(self, n: usize) -> u8; fn mid(self, start: usize, len: usize) -> u8; } #[doc = "Ops to extract b...
bit_ops_impl
identifier_name
lib.rs
#![cfg_attr(feature = "nightly", feature(const_panic))] extern crate proc_macro; use proc_macro2::TokenStream; use quote::{quote, quote_spanned}; use syn::parse_macro_input; use syn::Item; /// Generate B1, B2,.., B64 with implementation of the Specifier trait #[proc_macro] pub fn generate_bit_specifiers(_input: proc...
if attr.path.is_ident("bits") { // At this point `attr.tokens` is the following part of the attribute: // #[bits=..] // ^^^ let bits = syn::parse2::<BitAttribute>(attr.tokens.clo...
{ let _ = args; let item = parse_macro_input!(input as syn::Item); match item { Item::Struct(s) => { let ident = &s.ident; let fields_ty = s.fields.iter().map(|field| &field.ty); // Check that fields with #[bits=X] attribute have a type of size `X` /...
identifier_body
frontend.rs
//! General algorithms for frontends. //! //! The frontend is concerned with executing the abstract behaviours given by the backend in terms //! of the actions of the frontend types. This means translating Redirect errors to the correct //! Redirect http response for example or optionally sending internal errors to log...
pub enum Authentication { Failed, InProgress, Authenticated(String), } struct AccessTokenParameter<'a> { valid: bool, client_id: Option<Cow<'a, str>>, redirect_url: Option<Cow<'a, str>>, grant_type: Option<Cow<'a, str>>, code: Option<Cow<'a, str>>, authorization: Option<(String, Vec...
#[derive(Clone)]
random_line_split
frontend.rs
//! General algorithms for frontends. //! //! The frontend is concerned with executing the abstract behaviours given by the backend in terms //! of the actions of the frontend types. This means translating Redirect errors to the correct //! Redirect http response for example or optionally sending internal errors to log...
} impl<'s> AuthorizationParameter<'s> { fn invalid() -> Self { AuthorizationParameter { valid: false, method: None, client_id: None, scope: None, redirect_url: None, state: None } } } impl AuthorizationFlow { /// Idempotent data processing, checks formats. pub fn prepare<W: WebReq...
{ self.method.as_ref().map(|c| c.as_ref().into()) }
identifier_body
frontend.rs
//! General algorithms for frontends. //! //! The frontend is concerned with executing the abstract behaviours given by the backend in terms //! of the actions of the frontend types. This means translating Redirect errors to the correct //! Redirect http response for example or optionally sending internal errors to log...
<'l, Req> where Req: WebRequest + 'l, { request: &'l mut Req, urldecoded: AuthorizationParameter<'l>, } fn extract_parameters(params: HashMap<String, Vec<String>>) -> AuthorizationParameter<'static> { let map = params.iter() .filter(|&(_, v)| v.len() == 1) .map(|(k, v)| (k.as_str(), v[0]....
PreparedAuthorization
identifier_name
router.rs
//! Top-level semantic block verification for Zebra. //! //! Verifies blocks using the [`CheckpointVerifier`] or full [`SemanticBlockVerifier`], //! depending on the config and block height. //! //! # Correctness //! //! Block and transaction verification requests should be wrapped in a timeout, because: //! - checkpoi...
<S>( config: Config, network: Network, mut state_service: S, debug_skip_parameter_preload: bool, ) -> ( Buffer<BoxService<Request, block::Hash, RouterError>, Request>, Buffer< BoxService<transaction::Request, transaction::Response, TransactionError>, transaction::Request, >, ...
init
identifier_name
router.rs
//! Top-level semantic block verification for Zebra. //! //! Verifies blocks using the [`CheckpointVerifier`] or full [`SemanticBlockVerifier`], //! depending on the config and block height. //! //! # Correctness //! //! Block and transaction verification requests should be wrapped in a timeout, because: //! - checkpoi...
Err(e) => { #[cfg(not(test))] tracing::warn!( "unexpected error: {e:?} in state request while verifying previous \ state checkpoints. Is Zebra shutting down?" ); ...
unreachable!("unexpected response type: {response:?} from state request") }
conditional_block
router.rs
//! Top-level semantic block verification for Zebra. //! //! Verifies blocks using the [`CheckpointVerifier`] or full [`SemanticBlockVerifier`], //! depending on the config and block height. //! //! # Correctness //! //! Block and transaction verification requests should be wrapped in a timeout, because: //! - checkpoi...
// # Consensus // // We want to verify all available checkpoints, even if the node is not configured // to use them for syncing. Zebra's checkpoints are updated with every release, // which makes sure they include the latest settled network upgrade. ...
tracing::info!("starting state checkpoint validation");
random_line_split
javascript.rs
mod expression; mod pattern; #[cfg(test)] mod tests; use crate::{ast::*, error::GleamExpect, fs::Utf8Writer, line_numbers::LineNumbers, pretty::*}; use itertools::Itertools; const INDENT: isize = 2; const DEEP_EQUAL: &str = " function $equal(x, y) { let toCheck = [x, y]; while (toCheck) { let a = toCheck.po...
fn imported_external_function( &mut self, public: bool, name: &'a str, module: &'a str, fun: &'a str, ) -> Document<'a> { let import = if name == fun { docvec!["import { ", name, r#" } from ""#, module, r#"";"#] } else { docvec![ ...
{ if module.is_empty() { self.global_external_function(public, name, arguments, fun) } else { self.imported_external_function(public, name, module, fun) } }
identifier_body
javascript.rs
mod expression; mod pattern; #[cfg(test)] mod tests; use crate::{ast::*, error::GleamExpect, fs::Utf8Writer, line_numbers::LineNumbers, pretty::*}; use itertools::Itertools; const INDENT: isize = 2; const DEEP_EQUAL: &str = " function $equal(x, y) { let toCheck = [x, y]; while (toCheck) { let a = toCheck.po...
<'a>( items: impl Iterator<Item = (Document<'a>, Option<Document<'a>>)>, ) -> Document<'a> { let fields = items.map(|(key, value)| match value { Some(value) => docvec![key, ": ", value,], None => key.to_doc(), }); docvec![ docvec![ "{", break_("", " "), ...
wrap_object
identifier_name
javascript.rs
mod expression; mod pattern; #[cfg(test)] mod tests; use crate::{ast::*, error::GleamExpect, fs::Utf8Writer, line_numbers::LineNumbers, pretty::*}; use itertools::Itertools; const INDENT: isize = 2; const DEEP_EQUAL: &str = " function $equal(x, y) { let toCheck = [x, y]; while (toCheck) { let a = toCheck.po...
"export function " } else { "function " }; Ok(docvec![ head, maybe_escape_identifier(name), fun_args(args), " {", docvec![line(), generator.function_body(body)?] .nest(INDENT) .group...
&mut self.object_equality_used, self.module_scope.clone(), ); let head = if public {
random_line_split
benchmarks.rs
use std::time::{Instant, Duration}; use ordered_float::OrderedFloat; use rand::seq::SliceRandom; use crate::actions::*; use crate::simulation::*; use crate::simulation_state::*; use crate::start_and_strategy_ai::{Strategy, FastStrategy, CombatResult, play_out, collect_starting_points}; use crate::neural_net_ai::Neural...
let mut fast_genetic: ExplorationOptimizer<FastStrategy, _> = ExplorationOptimizer::new (| candidates: & [CandidateStrategy <FastStrategy>] | { if candidates.len() < 2 { FastStrategy::random() } else { FastStrategy::offspring(& candidates.choose_multiple(&mut rand::thread_rng(), 2).map (| cand...
random_line_split
benchmarks.rs
use std::time::{Instant, Duration}; use ordered_float::OrderedFloat; use rand::seq::SliceRandom; use crate::actions::*; use crate::simulation::*; use crate::simulation_state::*; use crate::start_and_strategy_ai::{Strategy, FastStrategy, CombatResult, play_out, collect_starting_points}; use crate::neural_net_ai::Neural...
<T> { strategy: T, playouts: usize, total_score: f64, } fn playout_result(state: & CombatState, strategy: & impl Strategy)->CombatResult { let mut state = state.clone(); play_out ( &mut Runner::new (&mut state, true, false), strategy, ); CombatResult::new (& state) } ...
CandidateStrategy
identifier_name
benchmarks.rs
use std::time::{Instant, Duration}; use ordered_float::OrderedFloat; use rand::seq::SliceRandom; use crate::actions::*; use crate::simulation::*; use crate::simulation_state::*; use crate::start_and_strategy_ai::{Strategy, FastStrategy, CombatResult, play_out, collect_starting_points}; use crate::neural_net_ai::Neural...
let mut neural_random_only: ExplorationOptimizer<NeuralStrategy, _> = ExplorationOptimizer::new (|_: &[CandidateStrategy <NeuralStrategy>] | NeuralStrategy::new_random(&ghost_state, 16)); let mut neural_training_only = NeuralStrategy::new_random(&ghost_state, 16); let mut neural_random_training: ExplorationOpt...
stStrategy::offspring(& candidates.choose_multiple(&mut rand::thread_rng(), 2).map (| candidate | & candidate.strategy).collect::<Vec<_>>()) } });
conditional_block
benchmarks.rs
use std::time::{Instant, Duration}; use ordered_float::OrderedFloat; use rand::seq::SliceRandom; use crate::actions::*; use crate::simulation::*; use crate::simulation_state::*; use crate::start_and_strategy_ai::{Strategy, FastStrategy, CombatResult, play_out, collect_starting_points}; use crate::neural_net_ai::Neural...
NeuralStrategy::new_random(&ghost_state, 16) } else { let mut improved = //candidates.choose (&mut thread_rng).clone(); candidates.iter().enumerate().max_by_key(| (index, strategy) | { (strategy.playouts, -(*index as i32)) }).unwrap().1.strategy.clone(); for _ in 0.....
timization_playouts = 1000000; let test_playouts = 10000; let ghost_file = std::fs::File::open ("data/hexaghost.json").unwrap(); let ghost_state: CombatState = serde_json::from_reader (std::io::BufReader::new (ghost_file)).unwrap(); let mut fast_random: ExplorationOptimizer<FastStrategy, _> = ExplorationOpti...
identifier_body
klogd.rs
use crate::libbb::ptr_to_globals::bb_errno; use libc; use libc::openlog; use libc::syslog; extern "C" { #[no_mangle] fn strtoul( __nptr: *const libc::c_char, __endptr: *mut *mut libc::c_char, __base: libc::c_int, ) -> libc::c_ulong; #[no_mangle] fn signal(__sig: libc::c_int, __handler: __sighandl...
( mut _argc: libc::c_int, mut argv: *mut *mut libc::c_char, ) -> libc::c_int { let mut i: libc::c_int = 0i32; let mut opt_c: *mut libc::c_char = 0 as *mut libc::c_char; let mut opt: libc::c_int = 0; let mut used: libc::c_int = 0; opt = getopt32( argv, b"c:n\x00" as *const u8 as *const libc::c_char...
klogd_main
identifier_name
klogd.rs
use crate::libbb::ptr_to_globals::bb_errno; use libc; use libc::openlog; use libc::syslog; extern "C" { #[no_mangle] fn strtoul( __nptr: *const libc::c_char, __endptr: *mut *mut libc::c_char, __base: libc::c_int, ) -> libc::c_ulong; #[no_mangle] fn signal(__sig: libc::c_int, __handler: __sighandl...
fn getopt32(argv: *mut *mut libc::c_char, applet_opts: *const libc::c_char, _:...) -> u32; #[no_mangle] fn write_pidfile_std_path_and_ext(path: *const libc::c_char); #[no_mangle] fn remove_pidfile_std_path_and_ext(path: *const libc::c_char); #[no_mangle] static mut logmode: smallint; #[no_mangle] fn b...
random_line_split
klogd.rs
use crate::libbb::ptr_to_globals::bb_errno; use libc; use libc::openlog; use libc::syslog; extern "C" { #[no_mangle] fn strtoul( __nptr: *const libc::c_char, __endptr: *mut *mut libc::c_char, __base: libc::c_int, ) -> libc::c_ulong; #[no_mangle] fn signal(__sig: libc::c_int, __handler: __sighandl...
unsafe extern "C" fn klogd_close() { /* FYI: cmd 7 is equivalent to setting console_loglevel to 7 * via klogctl(8, NULL, 7). */ klogctl(7i32, 0 as *mut libc::c_char, 0i32); /* "7 -- Enable printk's to console" */ klogctl(0i32, 0 as *mut libc::c_char, 0i32); /* "0 -- Close the log. Currently a NOP" */ } /* T...
{ /* "2 -- Read from the log." */ return klogctl(2i32, bufp, len); }
identifier_body
klogd.rs
use crate::libbb::ptr_to_globals::bb_errno; use libc; use libc::openlog; use libc::syslog; extern "C" { #[no_mangle] fn strtoul( __nptr: *const libc::c_char, __endptr: *mut *mut libc::c_char, __base: libc::c_int, ) -> libc::c_ulong; #[no_mangle] fn signal(__sig: libc::c_int, __handler: __sighandl...
*fresh0 = '\u{0}' as i32 as libc::c_char } /* Extract the priority */ priority = 6i32; if *start as libc::c_int == '<' as i32 { start = start.offset(1); if *start!= 0 { let mut end: *mut libc::c_char = 0 as *mut libc::c_char; priority...
{ *start.offset(n as isize) = '\u{0}' as i32 as libc::c_char; /* Process each newline-terminated line in the buffer */ start = bb_common_bufsiz1.as_mut_ptr(); loop { let mut newline: *mut libc::c_char = strchrnul(start, '\n' as i32); if *newline as libc::c_int == '\u{0}' as i32 {...
conditional_block
protocol_adapter.rs
use crate::HandlerError; use bigdecimal::{BigDecimal, FromPrimitive}; use graphql_parser::query::{ Definition, Document, OperationDefinition, Selection as GqlSelection, SelectionSet, Value, }; use query_core::query_document::*; /// Protocol adapter for GraphQL -> Query Document. /// /// GraphQL is mapped as follow...
fn convert_query(selection_set: SelectionSet<String>) -> crate::Result<Vec<Operation>> { Self::convert_selection_set(selection_set).map(|fields| fields.into_iter().map(Operation::Read).collect()) } fn convert_mutation(selection_set: SelectionSet<String>) -> crate::Result<Vec<Operation>> { ...
{ match def { Definition::Fragment(f) => Err(HandlerError::unsupported_feature( "Fragment definition", format!("Fragment '{}', at position {}.", f.name, f.position), )), Definition::Operation(op) => match op { OperationDefinitio...
identifier_body
protocol_adapter.rs
use crate::HandlerError; use bigdecimal::{BigDecimal, FromPrimitive}; use graphql_parser::query::{ Definition, Document, OperationDefinition, Selection as GqlSelection, SelectionSet, Value, }; use query_core::query_document::*; /// Protocol adapter for GraphQL -> Query Document. /// /// GraphQL is mapped as follow...
(gql_doc: Document<String>, operation: Option<String>) -> crate::Result<Operation> { let mut operations: Vec<Operation> = match operation { Some(ref op) => gql_doc .definitions .into_iter() .find(|def| Self::matches_operation(def, op)) .ok_...
convert
identifier_name
protocol_adapter.rs
use crate::HandlerError; use bigdecimal::{BigDecimal, FromPrimitive}; use graphql_parser::query::{ Definition, Document, OperationDefinition, Selection as GqlSelection, SelectionSet, Value, }; use query_core::query_document::*; /// Protocol adapter for GraphQL -> Query Document. /// /// GraphQL is mapped as follow...
( "categories".to_string(), ArgumentValue::object([( "create".to_string(), ArgumentValue::list([ ArgumentValue::object([("id".to_string(), ArgumentValue::int(1))]), ArgumentValue::object([...
let write = operation.into_write().unwrap(); let data_args = ArgumentValue::object([ ("id".to_string(), ArgumentValue::int(1)),
random_line_split
parser.rs
// This file is part of the uutils coreutils package. // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. // spell-checker:ignore (grammar) BOOLOP STRLEN FILETEST FILEOP INTOP STRINGOP ; (vars) LParen StrlenOp use std::ffi::{OsStr, OsString...
/// as a literal /// fn lparen(&mut self) -> ParseResult<()> { // Look ahead up to 3 tokens to determine if the lparen is being used // as a grouping operator or should be treated as a literal string let peek3: Vec<Symbol> = self .tokens .clone() .t...
random_line_split
parser.rs
// This file is part of the uutils coreutils package. // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. // spell-checker:ignore (grammar) BOOLOP STRLEN FILETEST FILEOP INTOP STRINGOP ; (vars) LParen StrlenOp use std::ffi::{OsStr, OsString...
thesized expression. /// /// test has no reserved keywords, so "(" will be interpreted as a literal /// in certain cases: /// /// * when found at the end of the token stream /// * when followed by a binary operator that is not _itself_ interpreted /// as a literal /// fn lparen(&mu...
oken(); match symbol { Symbol::LParen => self.lparen()?, Symbol::Bang => self.bang()?, Symbol::UnaryOp(_) => self.uop(symbol), Symbol::None => self.stack.push(symbol), literal => self.literal(literal)?, } Ok(()) } /// Parse a ...
identifier_body
parser.rs
// This file is part of the uutils coreutils package. // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. // spell-checker:ignore (grammar) BOOLOP STRLEN FILETEST FILEOP INTOP STRINGOP ; (vars) LParen StrlenOp use std::ffi::{OsStr, OsString...
let symbol = self.next_token(); match symbol { Symbol::LParen => self.lparen()?, Symbol::Bang => self.bang()?, Symbol::UnaryOp(_) => self.uop(symbol), Symbol::None => self.stack.push(symbol), literal => self.literal(literal)?, } ...
{
identifier_name
cpu_time.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. // Modified from https://github.com/rust-lang/cargo/blob/426fae51f39ebf6c545a2c12f78bc09fbfdb7aa9/src/cargo/util/cpu.rs // TODO: Maybe use https://github.com/heim-rs/heim is better after https://github.com/heim-rs/heim/issues/233 is fixed. use std::{ ...
} }; let kt = filetime_to_ns100(kernel_time); let ut = filetime_to_ns100(user_time); // convert ns // // Note: make it ns unit may overflow in some cases. // For example, a machine with 128 cores runs for one year. let cpu = (kt + ut) * 100; ...
{ let (kernel_time, user_time) = unsafe { let process = GetCurrentProcess(); let mut create_time = mem::zeroed(); let mut exit_time = mem::zeroed(); let mut kernel_time = mem::zeroed(); let mut user_time = mem::zeroed(); let ret = GetProce...
identifier_body
cpu_time.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. // Modified from https://github.com/rust-lang/cargo/blob/426fae51f39ebf6c545a2c12f78bc09fbfdb7aa9/src/cargo/util/cpu.rs // TODO: Maybe use https://github.com/heim-rs/heim is better after https://github.com/heim-rs/heim/issues/233 is fixed. use std::{ ...
() -> io::Result<std::time::Duration> { let mut time = unsafe { std::mem::zeroed() }; if unsafe { libc::getrusage(libc::RUSAGE_SELF, &mut time) } == 0 { let sec = time.ru_utime.tv_sec as u64 + time.ru_stime.tv_sec as u64; let nsec = (time.ru_utime.tv_usec as u32 + time.ru_stime....
cpu_time
identifier_name
cpu_time.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. // Modified from https://github.com/rust-lang/cargo/blob/426fae51f39ebf6c545a2c12f78bc09fbfdb7aa9/src/cargo/util/cpu.rs // TODO: Maybe use https://github.com/heim-rs/heim is better after https://github.com/heim-rs/heim/issues/233 is fixed. use std::{ ...
} }; let kt = filetime_to_ns100(kernel_time); let ut = filetime_to_ns100(user_time); // convert ns // // Note: make it ns unit may overflow in some cases. // For example, a machine with 128 cores runs for one year. let cpu = (kt + ut) * 100; ...
random_line_split
cpu_time.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. // Modified from https://github.com/rust-lang/cargo/blob/426fae51f39ebf6c545a2c12f78bc09fbfdb7aa9/src/cargo/util/cpu.rs // TODO: Maybe use https://github.com/heim-rs/heim is better after https://github.com/heim-rs/heim/issues/233 is fixed. use std::{ ...
else { Ok(0.0) } } } #[cfg(any(target_os = "linux", target_os = "freebsd"))] mod imp { use std::{fs::File, io, io::Read, time::Duration}; pub fn current() -> io::Result<super::LinuxStyleCpuTime> { let mut state = String::new(); File::open("/proc/stat")?.read_to_string(...
{ let cpu_time = new_time .checked_sub(old_time) .map(|dur| dur.as_secs_f64()) .unwrap_or(0.0); Ok(cpu_time / real_time) }
conditional_block
cargo_workspace.rs
//! FIXME: write short doc here use std::{ ops, path::{Path, PathBuf}, }; use anyhow::{Context, Result}; use cargo_metadata::{BuildScript, CargoOpt, Message, MetadataCommand, PackageId}; use ra_arena::{Arena, Idx}; use ra_cargo_watch::run_cargo; use ra_db::Edition; use rustc_hash::FxHashMap; use serde::Deseri...
} } #[derive(Debug, Clone, Default)] pub struct ExternResources { out_dirs: FxHashMap<PackageId, PathBuf>, proc_dylib_paths: FxHashMap<PackageId, PathBuf>, } pub fn load_extern_resources(cargo_toml: &Path, cargo_features: &CargoFeatures) -> ExternResources { let mut args: Vec<String> = vec![ "...
.copied() } pub fn workspace_root(&self) -> &Path { &self.workspace_root
random_line_split
cargo_workspace.rs
//! FIXME: write short doc here use std::{ ops, path::{Path, PathBuf}, }; use anyhow::{Context, Result}; use cargo_metadata::{BuildScript, CargoOpt, Message, MetadataCommand, PackageId}; use ra_arena::{Arena, Idx}; use ra_cargo_watch::run_cargo; use ra_db::Edition; use rustc_hash::FxHashMap; use serde::Deseri...
{ /// Do not activate the `default` feature. pub no_default_features: bool, /// Activate all available features pub all_features: bool, /// List of features to activate. /// This will be ignored if `cargo_all_features` is true. pub features: Vec<String>, /// Runs cargo check on launc...
CargoFeatures
identifier_name
main.rs
use std::env; use tokio::stream::StreamExt; use twilight::{ cache::{ twilight_cache_inmemory::config::{EventType, InMemoryConfigBuilder}, InMemoryCache, }, gateway::cluster::{config::ShardScheme, Cluster, ClusterConfig}, gateway::shard::Event, http::Client as HttpClient, model::...
Some("!setroleassign") => { handle_set_reaction_message( &words.collect::<Vec<_>>(), msg.channel_id, msg.guild_id.expect("Tried to set role assignment message in non-guild"), &msg.author, http, msg, ...
{ handle_show_theme_count( msg.channel_id, msg.guild_id.expect("Tried to show theme idea count in non-guild"), &msg.author, http ).await?; }
conditional_block
main.rs
use std::env; use tokio::stream::StreamExt; use twilight::{ cache::{ twilight_cache_inmemory::config::{EventType, InMemoryConfigBuilder}, InMemoryCache, }, gateway::cluster::{config::ShardScheme, Cluster, ClusterConfig}, gateway::shard::Event, http::Client as HttpClient, model::...
( http: HttpClient, channel_id: ChannelId, user_id: UserId, guild_id: GuildId, ) -> Result<()> { let standard_message = //"Send me a PM to submit theme ideas.\n\n\ "Get a role to signify one of your skill sets with the command `!role <role name>`\n\ and leave a role with `!le...
send_help_message
identifier_name
main.rs
use std::env; use tokio::stream::StreamExt; use twilight::{ cache::{ twilight_cache_inmemory::config::{EventType, InMemoryConfigBuilder}, InMemoryCache, }, gateway::cluster::{config::ShardScheme, Cluster, ClusterConfig}, gateway::shard::Event, http::Client as HttpClient, model::...
async fn handle_event( event: (u64, Event), http: HttpClient, current_user: &CurrentUser ) -> Result<()> { match event { (_, Event::MessageCreate(msg)) => { // Don't send replies to yourself if msg.author.id!= current_user.id { if is_pm(&http, msg.channe...
{ match http.channel(channel_id).await?.unwrap() { Channel::Private(_) => Ok(true), _ => Ok(false) } }
identifier_body
main.rs
use std::env; use tokio::stream::StreamExt; use twilight::{ cache::{ twilight_cache_inmemory::config::{EventType, InMemoryConfigBuilder}, InMemoryCache, }, gateway::cluster::{config::ShardScheme, Cluster, ClusterConfig}, gateway::shard::Event, http::Client as HttpClient, model::...
}; send_message(&http, channel_id, user_id, help_message).await?; Ok(()) }
if has_role(&http, guild_id, user_id, ORGANIZER).await? { format!("{}\n\n{}", standard_message, organizer_message) } else { standard_message.to_string()
random_line_split
main.rs
use futures::future::join_all; use generational_arena::{Arena, Index}; use nalgebra::Vector2; use std::env::args; use std::error::Error; use std::net::SocketAddr; use std::num::Wrapping; use std::time::Duration; use std::time::SystemTime; use tokio::net::{TcpListener, TcpStream, UdpSocket}; use tokio::prelude::*; use t...
// Set the user ID to some combinaiton of the arena index and generation. let id = idx.into_raw_parts().0 as u8; players[idx].player.id = id; // TODO(jack) Broadcast PlayerLeft messages. // Broadcast PlayerJoined messages. let mut tcp_txs: Vec<_> = players .iter() .filter(|(other...
random_line_split
main.rs
use futures::future::join_all; use generational_arena::{Arena, Index}; use nalgebra::Vector2; use std::env::args; use std::error::Error; use std::net::SocketAddr; use std::num::Wrapping; use std::time::Duration; use std::time::SystemTime; use tokio::net::{TcpListener, TcpStream, UdpSocket}; use tokio::prelude::*; use t...
0.0 } else { dampened_velocity_unclamped }; let velocity_unit = player .player .velocity .try_normalize(0.0) .unwrap_or(Vector2::new(0.0, 0.0)); player.player.velocity = dampened_velocity * velocity_unit; player...
{ // Apply player impulse. for (_, player) in players.iter_mut() { let acceleration = 64.0; let max_velocity = 16.0; let friction = 16.0; // Acceleration ranges from `friction` to `friction + acceleration`, // and is inversely proportional to the projection of the curren...
identifier_body
main.rs
use futures::future::join_all; use generational_arena::{Arena, Index}; use nalgebra::Vector2; use std::env::args; use std::error::Error; use std::net::SocketAddr; use std::num::Wrapping; use std::time::Duration; use std::time::SystemTime; use tokio::net::{TcpListener, TcpStream, UdpSocket}; use tokio::prelude::*; use t...
( players: &mut Arena<Player>, bullets: &Arena<Bullet>, stream: TcpStream, mut internal_tcp_tx: Sender<(Index, Option<game::TcpServerMessage>)>, tick_rate: u32, tick_zero: SystemTime, tick: game::Tick, ) { println!("connection!"); let (tx, mut rx) = channel(4); let idx = match p...
accept
identifier_name
main.rs
.help("include path") .takes_value(true), ) .arg( Arg::new("define") .short('D') ...
{ config: String, header: String, } fn do_run(matches: ArgMatches, tmp_dir: &TempDir) -> Result<(), std::io::Error> { let rs_path = tmp_dir.path().join("input.rs"); let concat_path = tmp_dir.path().join("concat.h"); match matches.subcommand_matches("repro") { None => { let subm...
ReproCase
identifier_name
main.rs
.help("include path") .takes_value(true), ) .arg( Arg::new("define") .short('D') ...
fn announce_progress(msg: &str) { println!("=== {msg} ==="); } fn print_minimized_case(concat_path: &Path) -> Result<(), std::io::Error> { announce_progress("Completed. Minimized test case:"); let contents = std::fs::read_to_string(concat_path)?; println!("{contents}"); Ok(()) } /// Arguments we...
{ let haystack = std::fs::read_to_string(concat_path)?; Ok(["class Box", "class Vec", "class Slice"] .iter() .all(|needle| haystack.contains(needle))) }
identifier_body
main.rs
.takes_value(true), ) .arg( Arg::new("header") .long("header") .multiple_occurrences(true) ...
gen_cmd: &str,
random_line_split
main.rs
.help("include path") .takes_value(true), ) .arg( Arg::new("define") .short('D') ...
}; Ok(()) } /// Try to detect whether the preprocessed source code already contains /// a preprocessed version of cxx.h. This is hard because all the comments /// and preprocessor symbols may have been removed, and in fact if we're /// part way through reduction, parts of the code may have been removed too. f...
{ std::fs::copy(&concat_path, PathBuf::from(output_path))?; }
conditional_block
block_stream.rs
use anyhow::Error; use async_stream::stream; use futures03::Stream; use std::fmt; use std::sync::Arc; use thiserror::Error; use tokio::sync::mpsc::{self, Receiver, Sender}; use super::{Block, BlockPtr, Blockchain}; use crate::anyhow::Result; use crate::components::store::{BlockNumber, DeploymentLocator}; use crate::da...
stream: Box<dyn BlockStream<C>>, size_hint: usize, ) -> Box<dyn BlockStream<C>> { let (sender, receiver) = mpsc::channel::<Result<BlockStreamEvent<C>, Error>>(size_hint); crate::spawn(async move { BufferedBlockStream::stream_blocks(stream, sender).await }); Box::new(Buffered...
inner: Pin<Box<dyn Stream<Item = Result<BlockStreamEvent<C>, Error>> + Send>>, } impl<C: Blockchain + 'static> BufferedBlockStream<C> { pub fn spawn_from_stream(
random_line_split
block_stream.rs
use anyhow::Error; use async_stream::stream; use futures03::Stream; use std::fmt; use std::sync::Arc; use thiserror::Error; use tokio::sync::mpsc::{self, Receiver, Sender}; use super::{Block, BlockPtr, Blockchain}; use crate::anyhow::Result; use crate::components::store::{BlockNumber, DeploymentLocator}; use crate::da...
(block: C::Block, mut trigger_data: Vec<C::TriggerData>, logger: &Logger) -> Self { // This is where triggers get sorted. trigger_data.sort(); let old_len = trigger_data.len(); // This is removing the duplicate triggers in the case of multiple // data sources fetching the same ...
new
identifier_name
lib.rs
// Copyright 2018 Benjamin Fry <benjaminfry@me.com> // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed exce...
( _attr: proc_macro::TokenStream, item: proc_macro::TokenStream, ) -> proc_macro::TokenStream { // get a usable token stream let ast: syn::Item = parse_macro_input!(item as syn::Item); // Build the impl let expanded: TokenStream = impl_info_for_fdw(&ast); // Return the generated impl p...
pg_foreignwrapper
identifier_name
lib.rs
// Copyright 2018 Benjamin Fry <benjaminfry@me.com> // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed exce...
fn impl_info_for_fdw(item: &syn::Item) -> TokenStream { let typ = if let syn::Item::Struct(typ) = item { typ } else { panic!("Annotation only supported on structs") }; let mut decl = item.clone().into_token_stream(); let struct_name = &typ.ident; let func_name = syn::Ident::n...
{ let ty = match outputs { syn::ReturnType::Default => quote!(()), syn::ReturnType::Type(_, ty) => quote!(#ty), }; quote!(pg_extend::pg_type::PgType::from_rust::<#ty>().return_stmt()) }
identifier_body
lib.rs
// Copyright 2018 Benjamin Fry <benjaminfry@me.com> // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed exce...
// arbitrary Datum conversions occur here, and could panic // so this is inside the catch unwind #get_args_from_datums // this is the meat of the function call into the extension code let result = #func_name(#func_params); ...
// guard the Postgres process against the panic, and give us an oportunity to cleanup let panic_result = panic::catch_unwind(|| { // extract the argument list let (mut args, mut args_null) = pg_extend::get_args(func_info);
random_line_split
sync.rs
// Copyright 2017 The xi-editor Authors. // // 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 ag...
/// Run this in a thread, it will return when it encounters an error /// reading the channel or when the `Stop` message is recieved. pub fn work(&self) -> Result<(), RecvError> { loop { let msg = self.chan.recv()?; match msg { SyncMsg::Stop => return Ok(()),...
{ SyncUpdater { container_ref, chan } }
identifier_body
sync.rs
// Copyright 2017 The xi-editor Authors. // // 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 ag...
(ledger: &mut Ledger_Proxy, key: Vec<u8>) { let (s1, s2) = Channel::create(ChannelOpts::Normal).unwrap(); let resolver_client = ConflictResolverFactory_Client::from_handle(s1.into_handle()); let resolver_client_ptr = ::fidl::InterfacePtr { inner: resolver_client, version: ConflictResolverFac...
start_conflict_resolver_factory
identifier_name
sync.rs
// Copyright 2017 The xi-editor Authors. // // 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 ag...
let watcher = PageWatcherServer { updates: updates.clone(), buffer: buffer.clone() }; let _ = fidl::Server::new(watcher, s2).spawn(); let (mut snap, snap_request) = PageSnapshot_new_pair(); page.get_snapshot(snap_request, Some(key.clone()), Some(watcher_client_ptr)) .with(led...
let watcher_client = PageWatcher_Client::from_handle(s1.into_handle()); let watcher_client_ptr = ::fidl::InterfacePtr { inner: watcher_client, version: PageWatcher_Metadata::VERSION };
random_line_split
lib.rs
// Copyright 2020 The Exonum Team // // 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 i...
else { Command::from_args() }; if let StandardResult::Run(run_config) = command.execute()? { let genesis_config = Self::genesis_config(&run_config, self.builtin_instances); let db_options = &run_config.node_config.private_config.database; let database =...
{ Command::from_iter(args) }
conditional_block
lib.rs
// Copyright 2020 The Exonum Team // // 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 i...
/// Adds new Rust service to the list of available services. pub fn with_rust_service(mut self, service: impl ServiceFactory) -> Self { self.rust_runtime = self.rust_runtime.with_factory(service); self } /// Adds a new `Runtime` to the list of available runtimes. /// /// Note ...
{ let temp_dir = TempDir::new()?; let mut this = Self::with_args(vec![ OsString::from("run-dev"), OsString::from("--artifacts-dir"), temp_dir.path().into(), ]); this.temp_dir = Some(temp_dir); Ok(this) }
identifier_body
lib.rs
// Copyright 2020 The Exonum Team // // 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 i...
use std::{env, ffi::OsString, iter, path::PathBuf}; use crate::command::{run::NodeRunConfig, Command, ExonumCommand, StandardResult}; pub mod command; pub mod config; pub mod io; pub mod password; mod config_manager; /// Rust-specific node builder used for constructing a node with a list /// of provided services. ...
use tempfile::TempDir;
random_line_split
lib.rs
// Copyright 2020 The Exonum Team // // 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 i...
(run_config: &NodeRunConfig) -> InstanceInitParams { let mode = run_config .node_config .public_config .general .supervisor_mode .clone(); Supervisor::builtin_instance(SupervisorConfig { mode }) } }
supervisor_service
identifier_name
main.rs
// Copyright 2020 The Exonum Team // // 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 i...
fn is_artifact_deployed(&self, id: &ArtifactId) -> bool { self.deployed_artifacts.contains_key(id) } /// Initiates adding a new service and sets the counter value for this. fn initiate_adding_service( &self, context: ExecutionContext<'_>, artifact: &ArtifactId, ...
{ Receiver::with_result(self.deploy_artifact(artifact, spec)) }
identifier_body
main.rs
// Copyright 2020 The Exonum Team // // 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 i...
Some(InstanceStatus::Stopped) => { let instance = self.started_services.remove(&spec.id); println!("Stopping service {}: {:?}", spec, instance); } _ => { // We aren't interested in other possible statuses. } } ...
{ // Unwrap here is safe, since by invocation of this method // `exonum` guarantees that `initiate_adding_service` was invoked // before and it returned `Ok(..)`. let instance = self .start_service(&spec.artifact, &spec.as_descriptor())...
conditional_block
main.rs
// Copyright 2020 The Exonum Team // // 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 i...
}) } /// In the present simplest case, the artifact is added into the deployed artifacts table. fn deploy_artifact( &mut self, artifact: ArtifactId, spec: Vec<u8>, ) -> Result<(), ExecutionError> { // Invariant guaranteed by the core assert!(!self.deploye...
_name: instance.name.to_owned(), ..SampleService::default()
random_line_split