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 |
|---|---|---|---|---|
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... | (&mut self, _snapshot: &dyn Snapshot, _mailbox: &mut Mailbox) {}
}
impl From<SampleRuntime> for (u32, Box<dyn Runtime>) {
fn from(inner: SampleRuntime) -> Self {
(SampleRuntime::ID, Box::new(inner))
}
}
impl WellKnownRuntime for SampleRuntime {
const ID: u32 = 255;
}
fn node_config() -> (NodeConf... | after_commit | identifier_name |
game.rs | use std::collections::BTreeMap;
use std::fmt::{self, Debug, Formatter};
use std::sync::Arc;
use tokio::sync::{
mpsc::{self, error::TrySendError},
oneshot,
};
use tokio::time;
use logic::components::{Movement, WorldInteraction};
use logic::legion::prelude::{Entity, World};
use logic::resources::DeadEntities;
us... |
/// Attempt to send the value, returning false if the receiver was closed.
pub fn send(self, value: T) -> bool {
match self.sender.send(value) {
Ok(()) => true,
Err(_) => false,
}
}
}
| {
let (sender, receiver) = oneshot::channel();
(Callback { sender }, receiver)
} | identifier_body |
game.rs | use std::collections::BTreeMap;
use std::fmt::{self, Debug, Formatter};
use std::sync::Arc;
use tokio::sync::{
mpsc::{self, error::TrySendError},
oneshot,
};
use tokio::time;
use logic::components::{Movement, WorldInteraction};
use logic::legion::prelude::{Entity, World};
use logic::resources::DeadEntities;
us... | (&mut self) -> crate::Result<Snapshot> {
self.send_with(|callback| Command::Snapshot { callback })
.await
}
/// Handle an action performed by a player
pub async fn handle_action(&mut self, action: Action, player: PlayerId) -> crate::Result<()> {
self.sender
.send(Comma... | snapshot | identifier_name |
game.rs | use std::collections::BTreeMap;
use std::fmt::{self, Debug, Formatter};
use std::sync::Arc;
use tokio::sync::{
mpsc::{self, error::TrySendError},
oneshot,
};
use tokio::time;
use logic::components::{Movement, WorldInteraction};
use logic::legion::prelude::{Entity, World};
use logic::resources::DeadEntities;
us... | #[derive(Debug)]
enum Command {
Request {
request: Request,
callback: Callback<Response>,
},
RegisterPlayer {
callback: Callback<PlayerHandle>,
},
DisconnectPlayer(PlayerId),
Snapshot {
callback: Callback<Snapshot>,
},
PerformAction {
action: Actio... | pub struct GameHandle {
sender: mpsc::Sender<Command>,
}
| random_line_split |
par_granges.rs | YTE * channel_size_modifier) * threads / size_of(R::P)
channel_size_modifier: f64,
/// The rayon threadpool to operate in
pool: rayon::ThreadPool,
/// The implementation of [RegionProcessor] that will be used to process regions
processor: R,
}
impl<R: RegionProcessor + Send + Sync> ParGranges<R> {
... | else {
None
};
let restricted_ivs = match (bed_intervals, bcf_intervals) {
(Some(bed_ivs), Some(bcf_ivs)) => Some(Self::merge_intervals(bed_ivs, bcf_ivs)),
(Some(bed_ivs), None) => Some(bed_ivs),
(None, Some... | {
Some(
Self::bcf_to_intervals(&header, regions_bcf)
.expect("Parsed BCF/VCF to intervals"),
)
} | conditional_block |
par_granges.rs | YTE * channel_size_modifier) * threads / size_of(R::P)
channel_size_modifier: f64,
/// The rayon threadpool to operate in
pool: rayon::ThreadPool,
/// The implementation of [RegionProcessor] that will be used to process regions
processor: R,
}
impl<R: RegionProcessor + Send + Sync> ParGranges<R> {
... |
// An empty BAM with correct header
// A BED file with the randomly generated intervals (with expected number of positions)
// proptest generate random chunksize, cpus
proptest! {
#[test]
// add random chunksize and random cpus
// NB: using any larger numbers for this tends to b... | {
prop::collection::vec(arb_ivs(max_iv, max_ivs), 0..max_chr)
} | identifier_body |
par_granges.rs | ABYTE * channel_size_modifier) * threads / size_of(R::P)
channel_size_modifier: f64,
/// The rayon threadpool to operate in
pool: rayon::ThreadPool,
/// The implementation of [RegionProcessor] that will be used to process regions
processor: R,
}
impl<R: RegionProcessor + Send + Sync> ParGranges<R> ... | .collect())
}
/// Merge two sets of restriction intervals together
fn merge_intervals(
a_ivs: Vec<Lapper<u32, ()>>,
b_ivs: Vec<Lapper<u32, ()>>,
) -> Vec<Lapper<u32, ()>> {
let mut intervals = vec![vec![]; a_ivs.len()];
for (i, (a_lapper, b_lapper)) in a_ivs.i... | lapper.merge_overlaps();
lapper
}) | random_line_split |
par_granges.rs | .regions_bed {
Some(
Self::bed_to_intervals(&header, regions_bed)
.expect("Parsed BED to intervals"),
)
} else {
None
};
let bcf_intervals = if let Some(regions_... | process_region | identifier_name | |
medrs.rs | extern crate config;
extern crate mediawiki;
extern crate papers;
extern crate regex;
extern crate wikibase;
#[macro_use]
extern crate lazy_static;
/*
use papers::crossref2wikidata::Crossref2Wikidata;
use papers::orcid2wikidata::Orcid2Wikidata;
use papers::pubmed2wikidata::Pubmed2Wikidata;
use papers::semanticscholar2... | ("action", "query"),
("prop", "extlinks"),
("ellimit", "500"),
("titles", title.as_str()),
]);
let result = api
.get_query_api_json_all(¶ms)
.expect("query.extlinks failed");
let mut urls: Vec<String> = vec![];
result["query"]["pages"]
.as_object(... | random_line_split | |
medrs.rs | extern crate config;
extern crate mediawiki;
extern crate papers;
extern crate regex;
extern crate wikibase;
#[macro_use]
extern crate lazy_static;
/*
use papers::crossref2wikidata::Crossref2Wikidata;
use papers::orcid2wikidata::Orcid2Wikidata;
use papers::pubmed2wikidata::Pubmed2Wikidata;
use papers::semanticscholar2... | (filename: &str) -> Vec<String> {
if filename.is_empty() {
return vec![];
}
let file = File::open(filename).expect(format!("no such file: {}", filename).as_str());
let buf = BufReader::new(file);
buf.lines()
.map(|l| l.expect("Could not parse line"))
.collect()
}
fn read_file_... | lines_from_file | identifier_name |
medrs.rs | extern crate config;
extern crate mediawiki;
extern crate papers;
extern crate regex;
extern crate wikibase;
#[macro_use]
extern crate lazy_static;
/*
use papers::crossref2wikidata::Crossref2Wikidata;
use papers::orcid2wikidata::Orcid2Wikidata;
use papers::pubmed2wikidata::Pubmed2Wikidata;
use papers::semanticscholar2... |
fn output_sparql_result_items(sparql: &String) {
let api = Api::new("https://www.wikidata.org/w/api.php").expect("Can't connect to Wikidata");
let result = api.sparql_query(&sparql).expect("SPARQL query failed");
let varname = result["head"]["vars"][0]
.as_str()
.expect("Can't find first var... | {
let rep: String = if lines.is_empty() {
"".to_string()
} else {
"wd:".to_string() + &lines.join(" wd:")
};
sparql.replace(pattern, &rep)
} | identifier_body |
main.rs | /*
Authors: Prof. John Lindsay
Created: 15/08/2023 (oringinally in Whitebox Toolset Extension)
Last Modified: 15/08/2023
License: MIT
*/
use rstar::primitives::GeomWithData;
use rstar::RTree;
use std::env;
use std::f64;
use std::io::{Error, ErrorKind};
use std::ops::Index;
use std::path;
use std::str;
use std::time::... | working directory contained in the WhiteboxTools settings.json file.
Example Usage:
>>.*EXE_NAME run --routes=footpath.shp --dem=DEM.tif -o=assessedRoutes.shp --length=50.0 --dist=200
Note: Use of this tool requires a valid license. To obtain a license,
contact Whitebox Geospatial Inc. (support@wh... | Input/output file names can be fully qualified, or can rely on the | random_line_split |
main.rs | /*
Authors: Prof. John Lindsay
Created: 15/08/2023 (oringinally in Whitebox Toolset Extension)
Last Modified: 15/08/2023
License: MIT
*/
use rstar::primitives::GeomWithData;
use rstar::RTree;
use std::env;
use std::f64;
use std::io::{Error, ErrorKind};
use std::ops::Index;
use std::path;
use std::str;
use std::time::... | else if flag_val == "-outlet" {
outlet_file = if keyval {
vec[1].to_string()
} else {
args[i + 1].to_string()
};
} else if flag_val == "-o" || flag_val == "-output" {
output_file = if keyval {
vec[1].to_string()
... | {
input_file = if keyval {
vec[1].to_string()
} else {
args[i + 1].to_string()
};
} | conditional_block |
main.rs | /*
Authors: Prof. John Lindsay
Created: 15/08/2023 (oringinally in Whitebox Toolset Extension)
Last Modified: 15/08/2023
License: MIT
*/
use rstar::primitives::GeomWithData;
use rstar::RTree;
use std::env;
use std::f64;
use std::io::{Error, ErrorKind};
use std::ops::Index;
use std::path;
use std::str;
use std::time::... |
fn get_tool_name() -> String {
String::from("CorrectStreamVectorDirection") // This should be camel case and is a reference to the tool name.
}
fn run(args: &Vec<String>) -> Result<(), std::io::Error> {
let tool_name = get_tool_name();
let sep: String = path::MAIN_SEPARATOR.to_string();
// Read in ... | {
const VERSION: Option<&'static str> = option_env!("CARGO_PKG_VERSION");
println!(
"correct_stream_vector_direction v{} by Dr. John B. Lindsay (c) 2023.",
VERSION.unwrap_or("Unknown version")
);
} | identifier_body |
main.rs | /*
Authors: Prof. John Lindsay
Created: 15/08/2023 (oringinally in Whitebox Toolset Extension)
Last Modified: 15/08/2023
License: MIT
*/
use rstar::primitives::GeomWithData;
use rstar::RTree;
use std::env;
use std::f64;
use std::io::{Error, ErrorKind};
use std::ops::Index;
use std::path;
use std::str;
use std::time::... | (&self) -> Point2D {
self[0]
}
fn get_last_node(&self) -> Point2D {
self[self.vertices.len() - 1]
}
} | get_first_node | identifier_name |
spmc.rs | pub use super::{
NoRecv,
RecvErr::{self, *},
};
use incin::Pause;
use owned_alloc::OwnedAlloc;
use ptr::{bypass_null, check_null_align};
use removable::Removable;
use std::{
fmt,
ptr::{null_mut, NonNull},
sync::{
atomic::{AtomicPtr, Ordering::*},
Arc,
},
};
/// Creates an asynch... | <T> {
back: NonNull<Node<T>>,
}
impl<T> Sender<T> {
/// Sends a message and if the receiver disconnected, an error is returned.
pub fn send(&mut self, message: T) -> Result<(), NoRecv<T>> {
// First we allocate the node for our message.
let alloc = OwnedAlloc::new(Node {
message... | Sender | identifier_name |
spmc.rs | pub use super::{
NoRecv,
RecvErr::{self, *},
};
use incin::Pause;
use owned_alloc::OwnedAlloc;
use ptr::{bypass_null, check_null_align};
use removable::Removable;
use std::{
fmt,
ptr::{null_mut, NonNull},
sync::{
atomic::{AtomicPtr, Ordering::*},
Arc,
},
};
/// Creates an asynch... |
}
impl<T> Drop for Sender<T> {
fn drop(&mut self) {
// This dereferral is safe because the queue always have at least one
// node. This single node is only dropped when the last side to
// disconnect drops.
let res = unsafe {
// Let's try to mark next's bit so that rece... | {
// Safe because we always have at least one node, which is only dropped
// in the last side to disconnect's drop.
let back = unsafe { self.back.as_ref() };
back.next.load(Relaxed).is_null()
} | identifier_body |
spmc.rs | pub use super::{
NoRecv,
RecvErr::{self, *},
};
use incin::Pause;
use owned_alloc::OwnedAlloc;
use ptr::{bypass_null, check_null_align};
use removable::Removable;
use std::{
fmt,
ptr::{null_mut, NonNull},
sync::{
atomic::{AtomicPtr, Ordering::*},
Arc,
},
};
/// Creates an asynch... | // Safe to by-pass the check since we only store non-null
// pointers on the front.
Ok(bypass_null(next))
}
}
}
impl<T> Clone for Receiver<T> {
fn clone(&self) -> Self {
Self { inner: self.inner.clone() }
}
}
impl<T> fmt::Debug for Receiver<T> {
fn ... | {
let ptr = expected.as_ptr();
// We are not oblied to succeed. This is just cleanup and some other
// thread might do it.
let next = match self
.inner
.front
.compare_exchange(ptr, next, Relaxed, Relaxed)
{
... | conditional_block |
spmc.rs | pub use super::{
NoRecv,
RecvErr::{self, *},
};
use incin::Pause;
use owned_alloc::OwnedAlloc;
use ptr::{bypass_null, check_null_align};
use removable::Removable;
use std::{
fmt,
ptr::{null_mut, NonNull},
sync::{
atomic::{AtomicPtr, Ordering::*},
Arc,
},
};
/// Creates an asynch... | // the front.
let mut front_nnptr = unsafe {
// First we load pointer stored in the front.
bypass_null(self.inner.front.load(Relaxed))
};
loop {
// Let's remove the node logically first. Safe to derefer this
// pointer because we paused th... | // suffers from it, yeah.
let pause = self.inner.incin.inner.pause();
// Bypassing null check is safe because we never store null in | random_line_split |
intcode.rs | //! This module implements an IntCode interpreter.
use std::convert::TryFrom;
// The following terminology notes are taken from day 2 part 2
// - memory: the list of integers used when interpreting
// - address/position: the value at a given index into memory
// - opcode: mark the beginning of an instruction and d... | /// `mem` is the initial machine memory state, it is modified during the run
///
/// Will panic if it encounters an unknown opcode
pub fn interpret(mut mem: &mut [isize], mut input: impl Input, mut output: impl Output) -> isize {
let mut ip: usize = 0;
loop {
match step(&mut mem, ip, &mut input, &mut ou... | random_line_split | |
intcode.rs | //! This module implements an IntCode interpreter.
use std::convert::TryFrom;
// The following terminology notes are taken from day 2 part 2
// - memory: the list of integers used when interpreting
// - address/position: the value at a given index into memory
// - opcode: mark the beginning of an instruction and d... |
}
#[derive(Debug, PartialEq)]
enum AddrMode {
Pos = 0,
Imm = 1,
}
impl TryFrom<isize> for AddrMode {
type Error = &'static str;
fn try_from(num: isize) -> Result<Self, Self::Error> {
match num {
0 => Ok(Self::Pos),
1 => Ok(Self::Imm),
_ => Err("invalid add... | {
match num {
1 => Ok(Self::Add),
2 => Ok(Self::Multiply),
3 => Ok(Self::ReadIn),
4 => Ok(Self::WriteOut),
5 => Ok(Self::JmpIfTrue),
6 => Ok(Self::JmpIfFalse),
7 => Ok(Self::LessThan),
8 => Ok(Self::Equals),
... | identifier_body |
intcode.rs | //! This module implements an IntCode interpreter.
use std::convert::TryFrom;
// The following terminology notes are taken from day 2 part 2
// - memory: the list of integers used when interpreting
// - address/position: the value at a given index into memory
// - opcode: mark the beginning of an instruction and d... | (num: isize) -> Result<Self, Self::Error> {
match num {
1 => Ok(Self::Add),
2 => Ok(Self::Multiply),
3 => Ok(Self::ReadIn),
4 => Ok(Self::WriteOut),
5 => Ok(Self::JmpIfTrue),
6 => Ok(Self::JmpIfFalse),
7 => Ok(Self::LessThan),
... | try_from | identifier_name |
main.rs | #![recursion_limit="128"]
//#![allow(unused_imports)]
//#![allow(dead_code)]
extern crate gl;
extern crate glutin;
#[macro_use] extern crate nom;
extern crate image;
extern crate time;
extern crate cupid;
extern crate sysinfo;
extern crate systemstat;
extern crate bytesize;
// extern crate subprocess;
use {
gl::*,
... |
fn cpu_name() -> String {
// use cupid;
let info = cupid::master();
match info {
Some(x) => {
match x.brand_string() {
Some(x) => { ["CPU: ".to_owned(), x.to_owned()].join("") }
_ => { "Could not get CPU Name".to_owned() }
}
}
_ => { "Could not get CPU Name".to_owned() }
... | {
let ram_used = get_ram_used(system);
[cpu.to_owned(), ram.to_owned(), ram_used].join("\n")
} | identifier_body |
main.rs | #![recursion_limit="128"]
//#![allow(unused_imports)]
//#![allow(dead_code)]
extern crate gl;
extern crate glutin;
#[macro_use] extern crate nom;
extern crate image;
extern crate time;
extern crate cupid;
extern crate sysinfo;
extern crate systemstat;
extern crate bytesize;
// extern crate subprocess;
use {
gl::*,
... |
if is_dir_or_subdir_linux(&mnt, "/snap") { continue; }
if is_dir_or_subdir_linux(&mnt, "/sys") { continue; }
out = format!("{}\n{} Size: {}; Free: {}",
out, mount.fs_mounted_on, mount.total, mount.avail);
}
}
Err(x) => println!("\nMounts: error: {}", x)
}
out
}
fn i... | { continue; } | conditional_block |
main.rs | #![recursion_limit="128"]
//#![allow(unused_imports)]
//#![allow(dead_code)]
extern crate gl;
extern crate glutin;
#[macro_use] extern crate nom;
extern crate image;
extern crate time;
extern crate cupid;
extern crate sysinfo;
extern crate systemstat;
extern crate bytesize;
// extern crate subprocess;
use {
gl::*,
... | () -> String {
let sys = System::new();
let mut out = String::new();
match sys.mounts() {
Ok(mounts) => {
for mount in mounts.iter() {
if mount.total == bytesize::ByteSize::b(0) { continue; }
let mnt = mount.fs_mounted_on.clone();
if is_dir_or_subdir_linux(&mnt, "/boot") { contin... | get_hdd | identifier_name |
main.rs | #![recursion_limit="128"]
//#![allow(unused_imports)]
//#![allow(dead_code)]
extern crate gl;
extern crate glutin;
#[macro_use] extern crate nom;
extern crate image;
extern crate time;
extern crate cupid;
extern crate sysinfo;
extern crate systemstat;
extern crate bytesize;
// extern crate subprocess;
use {
gl::*,
... | out = format!("{}\n{} Size: {}; Free: {}",
out, mount.fs_mounted_on, mount.total, mount.avail);
}
}
Err(x) => println!("\nMounts: error: {}", x)
}
out
}
fn is_dir_or_subdir_linux(test: &str, path: &str) -> bool {
let tc = test.chars().count();
let pc = path.chars().count();
le... | random_line_split | |
lib.rs | #[macro_use]
extern crate compre_combinee;
extern crate combine;
mod errors;
mod details;
mod traits;
mod stop_watch;
use std::collections::{HashMap};
use combine::{parser, eof, satisfy, choice, attempt};
use combine::parser::range::{take_while1};
use combine::parser::char::*;
use combine::{Parser, many, optional, sk... | __ <- satisfy(|c: char| c == 'e' || c == 'E'),
sign_char <- optional(satisfy(|c: char| c == '+' || c == '-')),
digits <- digit_sequence();
{
let sign = match sign_char {
Some('-') => -1.0,
_ => 1.0
};
let mut acc = 0;
... | fn exponent_parser<'a>() -> impl Parser<&'a str, Output = f64> {
c_hx_do!{ | random_line_split |
lib.rs | #[macro_use]
extern crate compre_combinee;
extern crate combine;
mod errors;
mod details;
mod traits;
mod stop_watch;
use std::collections::{HashMap};
use combine::{parser, eof, satisfy, choice, attempt};
use combine::parser::range::{take_while1};
use combine::parser::char::*;
use combine::{Parser, many, optional, sk... |
fn null_parser<'a>() -> impl Parser<&'a str, Output = Node> {
c_hx_do!{
_word <- string("null");
Node::Null
}
}
macro_rules! ref_parser {
($parser_fn:ident) => {
parser(|input| {
let _: &mut &str = input;
$parser_fn().parse_stream(input).into_result()
... | {
c_hx_do!{
word <- string("true").or(string("false"));
match word {
"true" => Node::Boolean(true),
_ => Node::Boolean(false)
}
}
} | identifier_body |
lib.rs | #[macro_use]
extern crate compre_combinee;
extern crate combine;
mod errors;
mod details;
mod traits;
mod stop_watch;
use std::collections::{HashMap};
use combine::{parser, eof, satisfy, choice, attempt};
use combine::parser::range::{take_while1};
use combine::parser::char::*;
use combine::{Parser, many, optional, sk... | <'a>() -> impl Parser<&'a str, Output = Node> {
c_hx_do!{
word <- string("true").or(string("false"));
match word {
"true" => Node::Boolean(true),
_ => Node::Boolean(false)
}
}
}
fn null_parser<'a>() -> impl Parser<&'a str, Output = Node> {
c_hx_do!{
_... | bool_parser | identifier_name |
main.rs | // ~Similar to the ST Heart Rate Sensor example
#![no_main]
#![no_std]
#![allow(non_snake_case)]
use panic_rtt_target as _;
// use panic_halt as _;
use rtt_target::{rprintln, rtt_init_print};
use stm32wb_hal as hal;
use core::time::Duration;
use cortex_m_rt::{entry, exception};
use nb::block;
use byteorder::{ByteOr... | extended_packet_length_enable: 1,
pr_write_list_size: 0x3A,
mb_lock_count: 0x79,
att_mtu: 312,
slave_sca: 500,
master_sca: 0,
ls_source: 1,
max_conn_event_length: 0xFFFFFFFF,
hs_startup_time: 0x148,
viterbi_enable: 1,
ll_only: 0,
... | num_attr_serv: 10,
attr_value_arr_size: 3500, //2788,
num_of_links: 8, | random_line_split |
main.rs | // ~Similar to the ST Heart Rate Sensor example
#![no_main]
#![no_std]
#![allow(non_snake_case)]
use panic_rtt_target as _;
// use panic_halt as _;
use rtt_target::{rprintln, rtt_init_print};
use stm32wb_hal as hal;
use core::time::Duration;
use cortex_m_rt::{entry, exception};
use nb::block;
use byteorder::{ByteOr... | else {
rprintln!("Unexpected response to init_gap command");
return Err(());
};
perform_command(|rc| {
rc.update_characteristic_value(&UpdateCharacteristicValueParameters {
service_handle,
characteristic_handle: dev_name_handle,
offset: 0,
... | {
(service_handle, dev_name_handle, appearance_handle)
} | conditional_block |
main.rs | // ~Similar to the ST Heart Rate Sensor example
#![no_main]
#![no_std]
#![allow(non_snake_case)]
use panic_rtt_target as _;
// use panic_halt as _;
use rtt_target::{rprintln, rtt_init_print};
use stm32wb_hal as hal;
use core::time::Duration;
use cortex_m_rt::{entry, exception};
use nb::block;
use byteorder::{ByteOr... | () -> BdAddr {
let mut bytes = [0u8; 6];
let lhci_info = LhciC1DeviceInformationCcrp::new();
bytes[0] = (lhci_info.uid64 & 0xff) as u8;
bytes[1] = ((lhci_info.uid64 >> 8) & 0xff) as u8;
bytes[2] = ((lhci_info.uid64 >> 16) & 0xff) as u8;
bytes[3] = lhci_info.device_type_id;
bytes[4] = (lhci_... | get_bd_addr | identifier_name |
main.rs | // ~Similar to the ST Heart Rate Sensor example
#![no_main]
#![no_std]
#![allow(non_snake_case)]
use panic_rtt_target as _;
// use panic_halt as _;
use rtt_target::{rprintln, rtt_init_print};
use stm32wb_hal as hal;
use core::time::Duration;
use cortex_m_rt::{entry, exception};
use nb::block;
use byteorder::{ByteOr... |
const DISCOVERY_PARAMS: DiscoverableParameters = DiscoverableParameters {
advertising_type: AdvertisingType::ConnectableUndirected,
advertising_interval: Some((
Duration::from_millis(ADV_INTERVAL_MS),
Duration::from_millis(ADV_INTERVAL_MS),
)),
address_type: OwnAddressType::Public,
... | {
EncryptionKey(BLE_CFG_ERK)
} | identifier_body |
main.rs | // Rust notes
fn main () {
let mut x = String::from("Hey there");
let mut y = String::from("Hello dawg woof");
println!("{}",first_word(&x));
println!("{}",second_word(&y));
}
fn | (x : &String) -> &str {
let bytes = x.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b''{
return &x[0..i];
}
}
&x[..]
}
fn second_word(x : &String) -> &str {
let mut bytes = x.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' '{
let y = &x[i+1..];
bytes... | first_word | identifier_name |
main.rs | // Rust notes
fn main () {
let mut x = String::from("Hey there");
let mut y = String::from("Hello dawg woof");
println!("{}",first_word(&x));
println!("{}",second_word(&y));
}
fn first_word(x : &String) -> &str |
fn second_word(x : &String) -> &str {
let mut bytes = x.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' '{
let y = &x[i+1..];
bytes = y.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b''{
return &y[0..i];
}
}
// Return this IF there were on... | {
let bytes = x.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &x[0..i];
}
}
&x[..]
} | identifier_body |
main.rs | // Rust notes
fn main () {
let mut x = String::from("Hey there");
let mut y = String::from("Hello dawg woof");
println!("{}",first_word(&x));
println!("{}",second_word(&y));
}
fn first_word(x : &String) -> &str {
let bytes = x.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b''{
return... | &x[..]
}
fn second_word(x : &String) -> &str {
let mut bytes = x.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' '{
let y = &x[i+1..];
bytes = y.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b''{
return &y[0..i];
}
}
// Return this IF ther... | random_line_split | |
main.rs | // Rust notes
fn main () {
let mut x = String::from("Hey there");
let mut y = String::from("Hello dawg woof");
println!("{}",first_word(&x));
println!("{}",second_word(&y));
}
fn first_word(x : &String) -> &str {
let bytes = x.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b''{
return... |
}
&x[..]
}
//__________________________________________________________________________________________________________ //
//--------------------------------------------------//
//*** GENERAL NOTES ***
//*** Info: Random Notes I found either important, ***
//*** hard to remember, funny, coo... | {
let y = &x[i+1..];
bytes = y.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &y[0..i];
}
}
// Return this IF there were only two words.
return &y[..];
} | conditional_block |
client.rs | use std::io;
use std::io::prelude::*;
use std::net::TcpStream;
use std::cmp;
use rand::{Rng, OsRng};
use alert;
use tls_result::{TlsResult, TlsError, TlsErrorKind};
use tls_result::TlsErrorKind::{UnexpectedMessage, InternalError, DecryptError, IllegalParameter};
use util::{SurugaError, crypto_compare};
use cipher::{se... | (&mut self, buf: &[u8]) -> io::Result<()> {
let result = self.writer.write_application_data(buf);
match result {
Ok(()) => Ok(()),
Err(err) => {
let err = self.send_tls_alert(err);
// FIXME more verbose io error
Err(io::Error::new(i... | write_all | identifier_name |
client.rs | use std::io;
use std::io::prelude::*;
use std::net::TcpStream;
use std::cmp;
use rand::{Rng, OsRng};
use alert;
use tls_result::{TlsResult, TlsError, TlsErrorKind};
use tls_result::TlsErrorKind::{UnexpectedMessage, InternalError, DecryptError, IllegalParameter};
use util::{SurugaError, crypto_compare};
use cipher::{se... | try!(self.writer.write_handshake(&client_key_exchange));
try!(self.writer.write_change_cipher_spec());
// SECRET
let master_secret = {
let mut label_seed = b"master secret".to_vec();
label_seed.extend(&cli_random);
label_seed.extend(&server_hello_dat... | random_line_split | |
client.rs | use std::io;
use std::io::prelude::*;
use std::net::TcpStream;
use std::cmp;
use rand::{Rng, OsRng};
use alert;
use tls_result::{TlsResult, TlsError, TlsErrorKind};
use tls_result::TlsErrorKind::{UnexpectedMessage, InternalError, DecryptError, IllegalParameter};
use util::{SurugaError, crypto_compare};
use cipher::{se... |
impl<R: Read, W: Write> Read for TlsClient<R, W> {
// if ssl connection is failed, return `EndOfFile`.
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let mut pos: usize = 0;
let len = buf.len();
while pos < len {
let remaining = len - pos;
if self.buf... | {
to.write(from).unwrap()
} | identifier_body |
codec.rs | use std::pin::Pin;
use std::task::{Context, Poll};
use async_trait::async_trait;
use bytes::BytesMut;
// We use `futures::stream::Stream` because `std::async_iter::AsyncIterator` (previously known as
// `std::stream::Stream`) is still a bare-bones implementation - it does not even have an
// `async fn next` method!
us... | buffer.put_u8(item.len().try_into().unwrap());
buffer.put_slice(item.as_bytes());
}
#[tokio::test]
async fn sink() {
let (stream, mut mock) = SendStream::new_mock(4096);
let mut sink = Sink::new(stream, encode);
assert_matches!(sink.feed("hello world".to_string()).a... | fn encode(item: &String, buffer: &mut BytesMut) { | random_line_split |
codec.rs | use std::pin::Pin;
use std::task::{Context, Poll};
use async_trait::async_trait;
use bytes::BytesMut;
// We use `futures::stream::Stream` because `std::async_iter::AsyncIterator` (previously known as
// `std::stream::Stream`) is still a bare-bones implementation - it does not even have an
// `async fn next` method!
us... |
#[tokio::test]
async fn source() {
let (stream, mut mock) = RecvStream::new_mock(4096);
let mut source = Source::new(stream, decode);
mock.write_all(b"\x0bhello world\x03foo\x03bar")
.await
.unwrap();
drop(mock);
assert_matches!(source.next().await... | {
if buffer.remaining() < 1 {
return Ok(None);
}
let size = usize::from(buffer[0]);
if buffer.remaining() < 1 + size {
return Ok(None);
}
let mut vec = vec![0u8; size];
buffer.get_u8();
buffer.copy_to_slice(&mut vec);
Ok(Som... | identifier_body |
codec.rs | use std::pin::Pin;
use std::task::{Context, Poll};
use async_trait::async_trait;
use bytes::BytesMut;
// We use `futures::stream::Stream` because `std::async_iter::AsyncIterator` (previously known as
// `std::stream::Stream`) is still a bare-bones implementation - it does not even have an
// `async fn next` method!
us... | (&mut self, stream: &mut Stream) -> Result<Option<Self::Item>, Self::Error> {
loop {
if let Some(item) = self(&mut stream.buffer())? {
return Ok(Some(item));
}
if stream.recv_or_eof().await?.is_none() {
if stream.buffer().is_empty() {
... | decode | identifier_name |
aes.rs | 11] = [
0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36,
];
const SBOX: [u8; 256] = [
0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,
0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,
0xB7, 0xFD, 0x9... |
const COLUMN_MATRIX: [u8; 16] = [2, 3, 1, 1, 1, 2, 3, 1, 1, 1, 2, 3, 3, 1, 1, 2];
const INV_COLUMN_MATRIX: [u8; 16] = [14, 11, 13, 9, 9, 14, 11, 13, 13, 9, 14, 11, 11, 13, 9, 14];
fn gmul(mut a: u8, mut b: u8) -> u8 {
let mut p = 0;
for _ in 0..8 {
if (b & 0x1)!= 0 {
p.bitxor_assign(a);
}
let h... | {
let mut rows = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
shift_rows(&mut rows);
assert_ne!(
rows,
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
);
inv_shift_rows(&mut rows);
assert_eq!(
rows,
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
);
} | identifier_body |
aes.rs | 11] = [
0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36,
];
const SBOX: [u8; 256] = [
0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,
0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,
0xB7, 0xFD, 0x9... | (key: &[u8]) -> Vec<u8> {
let key_length = key.len();
let (rounds, sbox_round, extra_expansions) = match key_length {
16 => (10, false, 0),
24 => (12, false, 2),
32 => (14, true, 3),
len => panic!("Unsupported key length {}", len),
};
let expanded_key_size = 16 * (rounds + 1);
let mut expanded... | expand_key | identifier_name |
aes.rs | 8; 11] = [
0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36,
];
const SBOX: [u8; 256] = [
0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,
0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,
0xB7, 0xFD, 0... | impl CBCCipherMode {
fn transform(&mut self, chunk: &[u8; 16], transform: &Fn(&[u8; 16]) -> [u8; 16]) -> [u8; 16] {
match self.operation {
Operation::Encrypt => {
xor::buffer_mut(&mut self.initialization_vector, xor::Key::FullBuffer(chunk));
self.initialization_vector = transform(&self.initi... | }
| random_line_split |
tcp.rs | //! TcpStream wrappers that supports connecting with options
#[cfg(unix)]
use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
#[cfg(windows)]
use std::os::windows::io::{AsRawSocket, FromRawSocket, IntoRawSocket, RawSocket};
use std::{
io::{self, ErrorKind},
net::SocketAddr,
ops::{Deref, DerefMut... | debug!(
"0.0.0.0:{} may have already been occupied, retry with IPV6_V6ONLY",
addr.port()
);
set_only_v6(&socket, true);
socket.bind(*addr)?;
}
Err(err) => retu... | // This is probably 0.0.0.0 with the same port has already been occupied | random_line_split |
tcp.rs | //! TcpStream wrappers that supports connecting with options
#[cfg(unix)]
use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
#[cfg(windows)]
use std::os::windows::io::{AsRawSocket, FromRawSocket, IntoRawSocket, RawSocket};
use std::{
io::{self, ErrorKind},
net::SocketAddr,
ops::{Deref, DerefMut... | (self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<io::Result<()>> {
self.project().0.poll_flush(cx)
}
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<io::Result<()>> {
self.project().0.poll_shutdown(cx)
}
}
/// `TcpListener` for accepting inbound connect... | poll_flush | identifier_name |
tcp.rs | //! TcpStream wrappers that supports connecting with options
#[cfg(unix)]
use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
#[cfg(windows)]
use std::os::windows::io::{AsRawSocket, FromRawSocket, IntoRawSocket, RawSocket};
use std::{
io::{self, ErrorKind},
net::SocketAddr,
ops::{Deref, DerefMut... | #[cfg(windows)]
impl AsRawSocket for TcpStream {
fn as_raw_socket(&self) -> RawSocket {
self.0.as_raw_socket()
}
}
| self.0.as_raw_fd()
}
}
| identifier_body |
piv.rs | // Copyright 2021 Gravitational, 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 agree... | else {
let mut ret: Vec<u8> = len
.to_be_bytes()
.iter()
.skip_while(|&x| *x == 0)
.cloned()
.collect();
ret.insert(0, 0x80 | ret.len() as u8);
ret
}
}
| {
vec![len as u8]
} | conditional_block |
piv.rs | // Copyright 2021 Gravitational, 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 agree... |
}
// SELECT command tags.
const TLV_TAG_PIV_APPLICATION_PROPERTY_TEMPLATE: u8 = 0x61;
const TLV_TAG_AID: u8 = 0x4F;
const TLV_TAG_COEXISTENT_TAG_ALLOCATION_AUTHORITY: u8 = 0x79;
const TLV_TAG_DATA_FIELD: u8 = 0x53;
const TLV_TAG_FASC_N: u8 = 0x30;
const TLV_TAG_GUID: u8 = 0x34;
const TLV_TAG_EXPIRATION_DATE: u8 = 0x3... | {
let mut buf = Vec::new();
if let Some(data) = &self.data {
buf.extend_from_slice(data);
}
let status: [u8; 2] = self.status.into();
buf.extend_from_slice(&status);
buf
} | identifier_body |
piv.rs | // Copyright 2021 Gravitational, 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 agree... | status,
}
}
pub fn encode(&self) -> Vec<u8> {
let mut buf = Vec::new();
if let Some(data) = &self.data {
buf.extend_from_slice(data);
}
let status: [u8; 2] = self.status.into();
buf.extend_from_slice(&status);
buf
}
}
// SELEC... | random_line_split | |
piv.rs | // Copyright 2021 Gravitational, 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 agree... | (len: usize) -> Vec<u8> {
if len < 0x7f {
vec![len as u8]
} else {
let mut ret: Vec<u8> = len
.to_be_bytes()
.iter()
.skip_while(|&x| *x == 0)
.cloned()
.collect();
ret.insert(0, 0x80 | ret.len() as u8);
ret
}
}
| len_to_vec | identifier_name |
git.rs | use anyhow::{anyhow, Context, Result};
use git2::{
build::CheckoutBuilder, ApplyLocation, Delta, Diff, DiffFormat, DiffOptions, ErrorCode,
IndexAddOption, Oid, Repository, ResetType, Signature, StashApplyOptions, Time,
};
use itertools::Itertools;
use std::cell::RefCell;
use std::collections::HashSet;
use std::... | {
stash_id: Oid,
merge_status: MergeStatus,
}
#[derive(Debug)]
struct MergeStatus {
merge_head: Option<String>,
merge_mode: Option<String>,
merge_msg: Option<String>,
}
| Stash | identifier_name |
git.rs | use anyhow::{anyhow, Context, Result};
use git2::{
build::CheckoutBuilder, ApplyLocation, Delta, Diff, DiffFormat, DiffOptions, ErrorCode,
IndexAddOption, Oid, Repository, ResetType, Signature, StashApplyOptions, Time,
};
use itertools::Itertools;
use std::cell::RefCell;
use std::collections::HashSet;
use std::... |
pub fn save_snapshot(&mut self, staged_files: Vec<PathBuf>) -> Result<Snapshot> {
let inner = || -> Result<Snapshot> {
let deleted_files = self.get_deleted_files()?;
let unstaged_diff = self.save_unstaged_diff()?;
let backup_stash = self.save_snapshot_stash()?;
... | {
// When strict hash verification is disabled, it means libgit2 will not
// compute the "object id" of Git objects (which is a SHA-1 hash) after
// reading them to verify they match the object ids being used to look
// them up. This improves performance, and I don't have in front of me
... | identifier_body |
git.rs | use anyhow::{anyhow, Context, Result};
use git2::{
build::CheckoutBuilder, ApplyLocation, Delta, Diff, DiffFormat, DiffOptions, ErrorCode,
IndexAddOption, Oid, Repository, ResetType, Signature, StashApplyOptions, Time,
};
use itertools::Itertools;
use std::cell::RefCell;
use std::collections::HashSet;
use std::... |
Ok(())
}
}
#[derive(Debug)]
pub struct Snapshot {
pub staged_files: Vec<PathBuf>,
backup_stash: Option<Stash>,
unstaged_diff: Option<Vec<u8>>,
}
#[derive(Debug)]
struct Stash {
stash_id: Oid,
merge_status: MergeStatus,
}
#[derive(Debug)]
struct MergeStatus {
merge_head: Option<St... | "Encountered error when deleting {}.",
file.as_ref().display()
)
})?;
} | random_line_split |
client.rs | //! Common client functionalities.
use crate::rdsys;
use crate::rdsys::types::*;
use std::ffi::{CStr, CString};
use std::mem;
use std::os::raw::c_char;
use std::os::raw::c_void;
use std::ptr;
use std::slice;
use std::string::ToString;
use std::time::Duration;
use serde_json;
use crate::config::{ClientConfig, NativeC... | let mut group_list_ptr: *const RDKafkaGroupList = ptr::null_mut();
trace!("Starting group list fetch");
let ret = unsafe {
rdsys::rd_kafka_list_groups(
self.native_ptr(),
group_c_ptr,
&mut group_list_ptr as *mut *const RDKafkaGroupList,... | random_line_split | |
client.rs | //! Common client functionalities.
use crate::rdsys;
use crate::rdsys::types::*;
use std::ffi::{CStr, CString};
use std::mem;
use std::os::raw::c_char;
use std::os::raw::c_void;
use std::ptr;
use std::slice;
use std::string::ToString;
use std::time::Duration;
use serde_json;
use crate::config::{ClientConfig, NativeC... |
pub(crate) unsafe extern "C" fn native_stats_cb<C: ClientContext>(
_conf: *mut RDKafka,
json: *mut c_char,
json_len: usize,
opaque: *mut c_void,
) -> i32 {
let context = Box::from_raw(opaque as *mut C);
let mut bytes_vec = Vec::new();
bytes_vec.extend_from_slice(slice::from_raw_parts(json... | {
let fac = CStr::from_ptr(fac).to_string_lossy();
let log_message = CStr::from_ptr(buf).to_string_lossy();
let context = Box::from_raw(rdsys::rd_kafka_opaque(client) as *mut C);
(*context).log(
RDKafkaLogLevel::from_int(level),
fac.trim(),
log_message.trim(),
);
mem::fo... | identifier_body |
client.rs | //! Common client functionalities.
use crate::rdsys;
use crate::rdsys::types::*;
use std::ffi::{CStr, CString};
use std::mem;
use std::os::raw::c_char;
use std::os::raw::c_void;
use std::ptr;
use std::slice;
use std::string::ToString;
use std::time::Duration;
use serde_json;
use crate::config::{ClientConfig, NativeC... | <T: Into<Option<Duration>>>(
&self,
topic: &str,
partition: i32,
timeout: T,
) -> KafkaResult<(i64, i64)> {
let mut low = -1;
let mut high = -1;
let topic_c = CString::new(topic.to_string())?;
let ret = unsafe {
rdsys::rd_kafka_query_waterm... | fetch_watermarks | identifier_name |
pageserver.rs | backend::AuthType};
use anyhow::{bail, ensure, Context, Result};
use clap::{App, Arg, ArgMatches};
use daemonize::Daemonize;
use pageserver::{
branches,
defaults::{DEFAULT_HTTP_LISTEN_ADDR, DEFAULT_PG_LISTEN_ADDR},
http, page_service, tenant_mgr, PageServerConf, RelishStorageConfig, S3Config, LOG_FILE_NAM... | () -> Result<()> {
let arg_matches = App::new("Zenith page server")
.about("Materializes WAL stream to pages and serves them to the postgres")
.arg(
Arg::with_name("listen-pg")
.short("l")
.long("listen-pg")
.alias("listen") // keep some compati... | main | identifier_name |
pageserver.rs | backend::AuthType};
use anyhow::{bail, ensure, Context, Result};
use clap::{App, Arg, ArgMatches};
use daemonize::Daemonize;
use pageserver::{
branches,
defaults::{DEFAULT_HTTP_LISTEN_ADDR, DEFAULT_PG_LISTEN_ADDR},
http, page_service, tenant_mgr, PageServerConf, RelishStorageConfig, S3Config, LOG_FILE_NAM... |
// Initialize tenant manager.
tenant_mgr::init(conf);
// keep join handles for spawned threads
let mut join_handles = vec![];
// initialize authentication for incoming connections
let auth = match &conf.auth_type {
AuthType::Trust | AuthType::MD5 => None,
AuthType::ZenithJWT ... | {
info!("daemonizing...");
// There shouldn't be any logging to stdin/stdout. Redirect it to the main log so
// that we will see any accidental manual fprintf's or backtraces.
let stdout = log_file.try_clone().unwrap();
let stderr = log_file;
let daemonize = Daemonize::... | conditional_block |
pageserver.rs | _backend::AuthType};
use anyhow::{bail, ensure, Context, Result};
use clap::{App, Arg, ArgMatches};
use daemonize::Daemonize;
use pageserver::{
branches,
defaults::{DEFAULT_HTTP_LISTEN_ADDR, DEFAULT_PG_LISTEN_ADDR},
http, page_service, tenant_mgr, PageServerConf, RelishStorageConfig, S3Config, LOG_FILE_NA... |
auth_validation_public_key_path,
auth_type,
relish_storage_config,
})
}
}
fn main() -> Result<()> {
let arg_matches = App::new("Zenith page server")
.about("Materializes WAL stream to pages and serves them to the postgres")
.arg(
Arg::with_... | random_line_split | |
executor.rs | //! Functions for setting configuration and executing the generator.
use cpp_to_rust_generator::common::errors::Result;
use cpp_to_rust_generator::common::{log, toml};
use cpp_to_rust_generator::common::file_utils::{PathBufWithAdded, repo_crate_local_path};
use cpp_to_rust_generator::config::{Config, CacheUsage, Debug... | type1.doc = Some(doc.0);
if let CppTypeKind::Enum { ref mut values } = type1.kind {
let enum_namespace = if let Some(index) = type1.name.rfind("::") {
type1.name[0..index + 2].to_string()
} else {
String::new()
... | for type1 in &mut cpp_data.types {
match parser.doc_for_type(&type1.name) {
Ok(doc) => {
// log::debug(format!("Found doc for type: {}", type1.name)); | random_line_split |
executor.rs | //! Functions for setting configuration and executing the generator.
use cpp_to_rust_generator::common::errors::Result;
use cpp_to_rust_generator::common::{log, toml};
use cpp_to_rust_generator::common::file_utils::{PathBufWithAdded, repo_crate_local_path};
use cpp_to_rust_generator::config::{Config, CacheUsage, Debug... | (cpp_methods: &mut [CppMethod], data: &mut DocParser) -> Result<()> {
for cpp_method in cpp_methods {
if let Some(ref info) = cpp_method.class_membership {
if info.visibility == CppVisibility::Private {
continue;
}
}
if let Some(ref declaration_code) = cpp_method.declaration_code {
... | find_methods_docs | identifier_name |
set3.rs | use std::collections::VecDeque;
use std::time::{SystemTime, UNIX_EPOCH};
use std::{u8, u16};
use rand::{self, Rng};
use rand::distributions::{IndependentSample, Range};
use rayon::iter::{IntoParallelIterator, ParallelIterator};
use errors::*;
use prelude::*;
use set1::{decrypt_single_byte_xor_cipher, break_repeating_... |
pub fn get_mt19937_ciphertext() -> Result<(u16, Vec<u8>)> {
let mut thread_rng = rand::thread_rng();
let prefix_len = Range::new(0, u8::MAX).ind_sample(&mut thread_rng);
let mut plaintext = random_bytes(prefix_len as usize)?;
plaintext.extend(b"AAAAAAAAAAAAAA");
let seed = Range::new(0, u16::MAX).ind_samp... | {
let key: Vec<_> = MersenneTwister::new(seed as u32).keystream().take(data.len()).collect();
fixed_xor(data, &key)
} | identifier_body |
set3.rs | use std::collections::VecDeque;
use std::time::{SystemTime, UNIX_EPOCH};
use std::{u8, u16};
use rand::{self, Rng};
use rand::distributions::{IndependentSample, Range};
use rayon::iter::{IntoParallelIterator, ParallelIterator};
use errors::*;
use prelude::*;
use set1::{decrypt_single_byte_xor_cipher, break_repeating_... | }
let (_, key) = break_repeating_key_xor(&concated_ciphertext, min_length..min_length + 1);
let mut result = Vec::new();
for ciphertext in ciphertexts {
result.push(fixed_xor(ciphertext, &key));
}
// this only extracts min_length bytes for each ciphertext
// TODO extract the rest of the plaintexts..... | for ciphertext in ciphertexts {
println!("{:?}", ciphertext.len());
concated_ciphertext.extend(&ciphertext[..min_length]); | random_line_split |
set3.rs | use std::collections::VecDeque;
use std::time::{SystemTime, UNIX_EPOCH};
use std::{u8, u16};
use rand::{self, Rng};
use rand::distributions::{IndependentSample, Range};
use rayon::iter::{IntoParallelIterator, ParallelIterator};
use errors::*;
use prelude::*;
use set1::{decrypt_single_byte_xor_cipher, break_repeating_... | () -> Result<Vec<u8>> {
let mut thread_rng = rand::thread_rng();
let prefix_len = Range::new(0, u8::MAX).ind_sample(&mut thread_rng);
let mut plaintext = random_bytes(prefix_len as usize)?;
plaintext.extend(b"user_id=123456&expires=1000");
let unix_duration = SystemTime::now().duration_since(UNIX_EPOCH)?;
... | generate_password_reset_token | identifier_name |
set3.rs | use std::collections::VecDeque;
use std::time::{SystemTime, UNIX_EPOCH};
use std::{u8, u16};
use rand::{self, Rng};
use rand::distributions::{IndependentSample, Range};
use rayon::iter::{IntoParallelIterator, ParallelIterator};
use errors::*;
use prelude::*;
use set1::{decrypt_single_byte_xor_cipher, break_repeating_... |
}
}
}
let vec = Vec::from(result);
if is_pkcs7_padded(&vec) {
unpad_pkcs7(&vec)
} else {
Ok(vec)
}
}
pub fn get_base64_strings() -> Result<Vec<Vec<u8>>> {
let mut base64_strings = Vec::new();
base64_strings.push(from_base64_string("SSBoYXZlIG1ldCB0aGVtIGF0IGNsb3NlIG9mIGRheQ==")?);
b... | {
result.push_front(previous_block[i] ^ z ^ padding);
c1_suffix.push_front(z);
break;
} | conditional_block |
mm.rs | collections::BTreeMap;
use crate::acpi::MAX_CORES;
use rangeset::RangeSet;
use boot_args::{KERNEL_PHYS_WINDOW_BASE, KERNEL_PHYS_WINDOW_SIZE};
use boot_args::KERNEL_VMEM_BASE;
use page_table::{PhysMem, PhysAddr, PageType, VirtAddr};
/// Table which is indexed by an APIC identifier to map to a physical range
/// which... | {
/// Virtual address of the next `FreeListNode`
next: usize,
/// Number of free slots in `free_mem`
free_slots: usize,
/// Virtual addresses of free allocations
free_addrs: [*mut u8; 0],
}
/// A free list which holds free entries of `size` bytes in a semi-linked list
/// table thingy.
p... | FreeListNode | identifier_name |
mm.rs | alloc::collections::BTreeMap;
use crate::acpi::MAX_CORES;
use rangeset::RangeSet;
use boot_args::{KERNEL_PHYS_WINDOW_BASE, KERNEL_PHYS_WINDOW_SIZE};
use boot_args::KERNEL_VMEM_BASE;
use page_table::{PhysMem, PhysAddr, PageType, VirtAddr};
/// Table which is indexed by an APIC identifier to map to a physical range
/... | let total_phys = core!().boot_args
.total_physical_memory.load(Ordering::Relaxed);
// Get physical memory in use
let phys_inuse =
total_phys - GLOBAL_ALLOCATOR.free_physical.load(Ordering::Relaxed);
print!("Allocs {:8} | Frees {:8} | Physical {:10.2} MiB / {:10.2} MiB | \
... | /// Print the allocation statistics to the screen
pub fn print_alloc_stats() {
// Get total amount of physical memory | random_line_split |
mm.rs | collections::BTreeMap;
use crate::acpi::MAX_CORES;
use rangeset::RangeSet;
use boot_args::{KERNEL_PHYS_WINDOW_BASE, KERNEL_PHYS_WINDOW_SIZE};
use boot_args::KERNEL_VMEM_BASE;
use page_table::{PhysMem, PhysAddr, PageType, VirtAddr};
/// Table which is indexed by an APIC identifier to map to a physical range
/// which... | } else {
// There's room in the current stack, just throw us in there
let fl = &mut *(self.head as *mut FreeListNode);
// Decrement the number of free slots
fl.free_slots -= 1;
// Store our newly freed virtual address into thi... | {
// Check if there is room for this allocation in the free stack,
// or if we need to create a new stack
if self.head == 0 ||
(*(self.head as *const FreeListNode)).free_slots == 0 {
// No free slots, create a new stack out of the freed vaddr
... | conditional_block |
main.rs | ]
}
}
}
const VERTICES: &[Vertex] = &[
// Changed
Vertex { position: [-0.0868241, 0.49240386, 0.0], tex_coords: [0.4131759, 0.00759614], }, // A
Vertex { position: [-0.49513406, 0.06958647, 0.0], tex_coords: [0.0048659444, 0.43041354], }, // B
Vertex { position: [-0.21918549, -0.... | {
surface: wgpu::Surface,
device: wgpu::Device,
queue: wgpu::Queue,
sc_desc: wgpu::SwapChainDescriptor,
swap_chain: wgpu::SwapChain,
size: winit::dpi::PhysicalSize<u32>,
mouse_pos: cgmath::Point2<f64>,
render_pipeline: wgpu::RenderPipeline,
vertex_buffer: wgpu::Buffer,
index_buf... | State | identifier_name |
main.rs | ]
}
}
}
const VERTICES: &[Vertex] = &[
// Changed
Vertex { position: [-0.0868241, 0.49240386, 0.0], tex_coords: [0.4131759, 0.00759614], }, // A
Vertex { position: [-0.49513406, 0.06958647, 0.0], tex_coords: [0.0048659444, 0.43041354], }, // B
Vertex { position: [-0.21918549, -0... | let diffuse_rgba = diffuse_image.as_rgba8().expect("Can't transform image info");
use image::GenericImageView;
let dimensions = diffuse_image.dimensions();
let texture_size = wgpu::Extent3d {
width: dimensions.0,
height: dimensions.1,
// All textures... | random_line_split | |
main.rs | ]
}
}
}
const VERTICES: &[Vertex] = &[
// Changed
Vertex { position: [-0.0868241, 0.49240386, 0.0], tex_coords: [0.4131759, 0.00759614], }, // A
Vertex { position: [-0.49513406, 0.06958647, 0.0], tex_coords: [0.0048659444, 0.43041354], }, // B
Vertex { position: [-0.21918549, -0.... |
};
render_pass.set_pipeline(&self.render_pipeline);
render_pass.set_bind_group(0, &self.diffuse_bind_group, &[]);
render_pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
render_pass.set_index_buffer(data.0.slice(..), wgpu::IndexFormat::Uint16);
... | {
(&self.index_buffer, self.num_indices)
} | conditional_block |
main.rs | ]
}
}
}
const VERTICES: &[Vertex] = &[
// Changed
Vertex { position: [-0.0868241, 0.49240386, 0.0], tex_coords: [0.4131759, 0.00759614], }, // A
Vertex { position: [-0.49513406, 0.06958647, 0.0], tex_coords: [0.0048659444, 0.43041354], }, // B
Vertex { position: [-0.21918549, -0.... |
fn input(&mut self, event: &WindowEvent) -> bool {
match event {
WindowEvent::CursorMoved {position,..} => {
self.mouse_pos.x = position.x;
self.mouse_pos.y = position.y;
// debug!("Mouse moved to point: {:?}", self.mouse_pos);
tr... | {
self.size = new_size;
self.sc_desc.width = new_size.width;
self.sc_desc.height = new_size.height;
self.swap_chain = self.device.create_swap_chain(&self.surface, &self.sc_desc);
} | identifier_body |
upload.rs | ,
/// Do not interactively prompt for username/password if the required credentials are missing.
///
/// Can also be set via MATURIN_NON_INTERACTIVE environment variable.
#[arg(long, env = "MATURIN_NON_INTERACTIVE")]
non_interactive: bool,
}
impl PublishOpt {
const DEFAULT_REPOSITORY_URL: &'sta... | Err(keyring::Error::NoEntry)
| Err(keyring::Error::NoStorageAccess(_)) | random_line_split | |
upload.rs | #[arg(short, long, env = "MATURIN_USERNAME")]
username: Option<String>,
/// Password for pypi or your custom registry.
///
/// Can also be set via MATURIN_PASSWORD environment variable.
#[arg(short, long, env = "MATURIN_PASSWORD", hide_env_values = true)]
password: Option<String>,
/// Conti... | config
}
fn load_pypi_cred_from_config(config: &Ini, registry_name: &str) -> Option<(String, String)> {
if let (Some(username), Some(password)) = (
config.get(registry_name, "username"),
config.get(registry_name, "password"),
) {
return Some((username, password));
}
None
}
/// ... | config_path.push(".pypirc");
if let Ok(pypirc) = fs::read_to_string(config_path.as_path()) {
let _ = config.read(pypirc);
}
}
| conditional_block |
upload.rs | #[arg(short, long, env = "MATURIN_USERNAME")]
username: Option<String>,
/// Password for pypi or your custom registry.
///
/// Can also be set via MATURIN_PASSWORD environment variable.
#[arg(short, long, env = "MATURIN_PASSWORD", hide_env_values = true)]
password: Option<String>,
/// Conti... | // Attempts to fetch the password from the keyring (if enabled)
/// and falls back to the interactive password prompt.
fn get_password(_username: &str) -> String {
#[cfg(feature = "keyring")]
{
let service = env!("CARGO_PKG_NAME");
let keyring = keyring::Entry::new(service, _username);
i... | Registry {
username,
password,
url,
}
}
}
/ | identifier_body |
upload.rs | #[arg(short, long, env = "MATURIN_USERNAME")]
username: Option<String>,
/// Password for pypi or your custom registry.
///
/// Can also be set via MATURIN_PASSWORD environment variable.
#[arg(short, long, env = "MATURIN_PASSWORD", hide_env_values = true)]
password: Option<String>,
/// Conti... | : String,
}
#[derive(Debug, Deserialize)]
struct OidcTokenResponse {
value: String,
}
#[derive(Debug, Deserialize)]
struct MintTokenResponse {
token: String,
}
/// Trusted Publisher support for GitHub Actions
fn resolve_pypi_token_via_oidc(registry_url: &str) -> Result<Option<String>> {
if env::var_os("G... | ponse {
audience | identifier_name |
lib.rs | use std::ops::{Deref, DerefMut};
use std::any::Any;
use std::fmt::Debug;
use std::fmt;
pub use cod_node_derive::Node;
mod id;
mod context;
mod danger_zone;
#[cfg(test)]
mod test;
pub use id::ID;
use id::new_id;
use context::{CONTEXT, Context, PollReason, Replacement, IDMapUpdate};
use danger_zone::downcast_rc;
//... |
fn cod(&self) {
let _ = self.clone();
}
}
pub struct Child<T: NodeClone> {
inner_ref: Rc<T>,
}
pub struct ParentID(ID);
impl From<ID> for ParentID {
fn from(id: ID) -> Self { ParentID(id) }
}
impl From<&Header> for ParentID {
fn from(header: &Header) -> Self { ParentID(header.id) }
}
imp... | {
Rc::new(self.clone())
} | identifier_body |
lib.rs | use std::ops::{Deref, DerefMut};
use std::any::Any;
use std::fmt::Debug;
use std::fmt;
pub use cod_node_derive::Node;
mod id;
mod context;
mod danger_zone;
#[cfg(test)]
mod test;
pub use id::ID;
use id::new_id;
use context::{CONTEXT, Context, PollReason, Replacement, IDMapUpdate};
use danger_zone::downcast_rc;
//... | (&self) -> Rc<T> {
Rc::clone(&self.inner_ref)
}
pub fn get_id(&self) -> ID {
self.inner_ref.header().id
}
pub fn set_parent(&mut self, parent: impl Into<ParentID>) {
self.make_mut().header_mut().parent_id = Some(parent.into().0);
}
/// Deep clone and set new parent... | get_ref | identifier_name |
lib.rs | use std::ops::{Deref, DerefMut};
use std::any::Any;
use std::fmt::Debug;
use std::fmt;
pub use cod_node_derive::Node;
mod id;
mod context;
mod danger_zone;
#[cfg(test)]
mod test;
pub use id::ID;
use id::new_id;
use context::{CONTEXT, Context, PollReason, Replacement, IDMapUpdate};
use danger_zone::downcast_rc;
//... | // so going to an old state after catching an unwind _should_ be fine.
if std::thread::panicking() { return }
CONTEXT.with(|c| {
Context::poll(c, PollReason::Drop, Rc::clone(&self.inner_ref));
});
}
}
pub struct MakeMutRef<'a, T: NodeClone> {
child: &'a mut Child<T>
... | }
impl<T: NodeClone> Drop for Child<T> {
fn drop(&mut self) {
// XXX: This should only create inconsistencies in the newest version of the data, | random_line_split |
main.rs | extern crate hyper;
extern crate rustc_serialize;
extern crate url;
mod errors;
mod structs;
use errors::*;
use errors::ResourceError::*;
use structs::*;
use hyper::client::Client;
use std::fs::File;
use hyper::header::*;
use std::io::prelude::*;
use std::path::Path;
use std::thread;
use std::sync::Arc;
use rustc_se... |
}
#[allow(unused_must_use)]
#[allow(dead_code)]
fn save_response_to_file(url : &str, content : &str, provider : &Provider) {
let fs = provider.fs();
let id = provider.extract_id(url);
fs.store(&provider.format_file_name(&id), content);
}
trait Meshup {
fn artist_resource_by_id (&self, id : &str) -> Str... | {
std::fs::create_dir_all(Path::new(&self.directory));
let path = Path::new(&self.directory).join(id);
if !path.exists() {
File::create(path)
.and_then(|mut f| f.write_all(content.as_bytes()));
};
} | identifier_body |
main.rs | extern crate hyper;
extern crate rustc_serialize;
extern crate url;
mod errors;
mod structs;
use errors::*;
use errors::ResourceError::*;
use structs::*;
use hyper::client::Client;
use std::fs::File;
use hyper::header::*;
use std::io::prelude::*;
use std::path::Path;
use std::thread;
use std::sync::Arc;
use rustc_se... | (&self) -> SimpleFs {
match *self {
Provider::Musicbrainz => SimpleFs { directory : "tmp".to_string() },
Provider::CoverArt => SimpleFs { directory : "tmp".to_string() }
}
}
fn extract_id(&self, url: &str) -> String {
let parsed : Url = Url::parse(url).unwrap();
par... | fs | identifier_name |
main.rs | extern crate hyper;
extern crate rustc_serialize;
extern crate url;
mod errors;
mod structs;
use errors::*;
use errors::ResourceError::*;
use structs::*;
use hyper::client::Client;
use std::fs::File;
use hyper::header::*;
use std::io::prelude::*;
use std::path::Path;
use std::thread;
use std::sync::Arc;
use rustc_se... | macro_rules! musicbrainz_file {
($id : expr) => ( format!("mb_{}.json", $id))
}
macro_rules! cover_art_url {
($id : expr) => ( format!("http://coverartarchive.org/release-group/{}", $id) )
}
macro_rules! cover_art_file {
($id : expr) => ( format!("ca_{}.json", $id) )
}
#[allow(dead_code)]
#[allow(unused_must_use)... | ($id : expr) => ( format!("http://musicbrainz.org/ws/2/artist/{}?&fmt=json&inc=url-rels+release-groups", $id))
//($id : expr) => ( format!("http://localhost:8000/ws/2/artist/{}?&fmt=json&inc=url-rels+release-groups", $id))
}
| random_line_split |
memory.rs | use std::mem::transmute;
use world::World;
use geometry::Point;
use sprite::Sprite;
use util;
// In Hex's Cellar, the player's spells manipulate an u8[40] of bytes that
// affect the world around her. This file gives a "RAM map" for that array.
// Color (3 bits = 8 bright colors) and character (5 bits, offset added t... | world.player.timer_delta = value,
DAMAGE_OFFSET =>
world.player.damage_offset = unsafe { transmute(value) },
0x36 =>
// TODO:???
{},
0x37 =>
// TODO:???
{},
TEXT_SYNC =>
world.player.text_sync = value... |
STAIRS_DELTA =>
world.player.stairs_delta = value,
TIMER_DELTA => | random_line_split |
memory.rs | use std::mem::transmute;
use world::World;
use geometry::Point;
use sprite::Sprite;
use util;
// In Hex's Cellar, the player's spells manipulate an u8[40] of bytes that
// affect the world around her. This file gives a "RAM map" for that array.
// Color (3 bits = 8 bright colors) and character (5 bits, offset added t... | (world: &World, address: u8) -> u8 {
match address {
PLAYER_APPEARANCE =>
world.player_appearance_byte,
_ if address >= PLAYER_NAME && address < MONSTERS =>
world.player.name[(address - PLAYER_NAME) as usize],
_ if address >= MONSTERS && address < SPELL_MEMORY => {
... | peek | identifier_name |
memory.rs | use std::mem::transmute;
use world::World;
use geometry::Point;
use sprite::Sprite;
use util;
// In Hex's Cellar, the player's spells manipulate an u8[40] of bytes that
// affect the world around her. This file gives a "RAM map" for that array.
// Color (3 bits = 8 bright colors) and character (5 bits, offset added t... | monster.venomous = value & 0b0010!= 0;
monster.corrupted = value & 0b0001!= 0;
},
MONSTER_POSITION => monster.position = Point::of_byte(value),
MONSTER_HP => monster.hp = value,
_ => unreachable!()
}
... | {
match address {
PLAYER_APPEARANCE => {
let old_sprite = Sprite::of_byte(world.player_appearance_byte, true);
let new_sprite = Sprite::of_byte(value, true);
report_player_appearance_change(world, old_sprite, new_sprite);
world.player_appearance_byte = value;
... | identifier_body |
client.rs | use crate::parser::*;
use crate::*;
use ::reqwest::blocking as reqwest;
use itertools::*;
use std::cell::RefCell;
use std::env;
use std::fs::File;
use std::io::BufWriter;
use std::io::Write;
use std::ops::Range;
use std::time::SystemTime;
use std::sync::{Arc, Mutex};
use chrono::{Utc, Local, DateTime, NaiveDateTime};
... | Command]) -> Response {
let resp = self.send(&format!(
"[4, {}, [{}]]",
self.player_key,
cs.iter().join(", ")
));
let resp = parse(resp);
self.gui("RESP", &response_to_json(&resp));
return resp;
}
}
pub fn get_num(a: &E) -> i32 {
if let E::Num(a) = a {
*a as i32
} else {
panic!("not number");... | at!(
"[3, {}, [{}, {}, {}, {}]]",
self.player_key, energy, power, cool, life
));
parse(resp)
}
pub fn command(&self, cs: &[ | identifier_body |
client.rs | use crate::parser::*;
use crate::*;
use ::reqwest::blocking as reqwest;
use itertools::*;
use std::cell::RefCell;
use std::env;
use std::fs::File;
use std::io::BufWriter;
use std::io::Write;
use std::ops::Range;
use std::time::SystemTime;
use std::sync::{Arc, Mutex};
use chrono::{Utc, Local, DateTime, NaiveDateTime};
... | {
if let Ok(_) = env::var("JUDGE_SERVER") {
return;
}
let t = match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
Ok(t) => t.as_nanos(),
_ => 0,
};
let msg = format!("###GUI\t{}\t{}\t{}\t{}\n", t, self.player_key, name, msg);
let mut printed = false;
if let Some(f) = &self.file {
... | tr) | identifier_name |
client.rs | use crate::parser::*;
use crate::*;
use ::reqwest::blocking as reqwest;
use itertools::*;
use std::cell::RefCell;
use std::env;
use std::fs::File;
use std::io::BufWriter;
use std::io::Write;
use std::ops::Range;
use std::time::SystemTime;
use std::sync::{Arc, Mutex};
use chrono::{Utc, Local, DateTime, NaiveDateTime};
... | // [src/bin/app.rs:177] &commands = [
// Pair(
// Num(
// 0,
// ),
// Pair(
// Pair(
// Num(
// 0,
// ),
// Num(
// -1,
// ),
// ),
// Nil,
// ),
// ),
// ]
let commands = commands.into_iter().ma... | let max_accelarate = get_num(&s[7]);
// [1, 1, [256, 1, [448, 2, 128], [16, 128], []], [1, [16, 128], [[[1, 0, <34, -46>, <0, 2>, [445, 0, 0, 1], 8, 128, 2], [[0, <0, -1>]]], [[0, 1, <-34, 48>, <0, 0>, [445, 0, 0, 1], 8, 128, 2], [[0, <0, -1>]]]]]] | random_line_split |
mod.rs | //! # Ready-to-use NLP pipelines and models
//!
//! Based on Huggingface's pipelines, ready to use end-to-end NLP pipelines are available as part of this crate. The following capabilities are currently available:
//!
//! **Disclaimer**
//! The contributors of this repository are not responsible for any generation from ... | //! ```ignore
//! # use rust_bert::pipelines::sequence_classification::Label;
//! let output = [
//! [
//! Label {
//! text: "politics".to_string(),
//! score: 0.972,
//! id: 0,
//! sentence: 0,
//! },
//! Label {
//! text: "public ... | //! # Ok(())
//! # }
//! ```
//!
//! outputs: | random_line_split |
call.rs | // This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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.a... | let fn_name = methods.iter().map(|method| &method.name).collect::<Vec<_>>();
let call_index = methods.iter().map(|method| method.call_index).collect::<Vec<_>>();
let new_call_variant_fn_name = fn_name
.iter()
.map(|fn_name| quote::format_ident!("new_call_variant_{}", fn_name))
.collect::<Vec<_>>();
let new_c... | {
let (span, where_clause, methods, docs) = match def.call.as_ref() {
Some(call) => {
let span = call.attr_span;
let where_clause = call.where_clause.clone();
let methods = call.methods.clone();
let docs = call.docs.clone();
(span, where_clause, methods, docs)
},
None => (def.item.span(), def.con... | identifier_body |
call.rs | // This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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.a... | (def: &mut Def) -> proc_macro2::TokenStream {
let (span, where_clause, methods, docs) = match def.call.as_ref() {
Some(call) => {
let span = call.attr_span;
let where_clause = call.where_clause.clone();
let methods = call.methods.clone();
let docs = call.docs.clone();
(span, where_clause, methods, do... | expand_call | identifier_name |
call.rs | // This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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.a... | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::{
pallet::{
parse::call::{CallVariantDef, CallWeightDef},
Def,
},
COUNTER,
};
use proc_macro2::TokenStream as TokenStrea... | // Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, | random_line_split |
day13.rs | //! # --- Day 13: Shuttle Search ---
//!
//! Your ferry can make it safely to a nearby port, but it won't get much
//! further. When you call to book another ship, you discover that no ships
//! embark from that port to your vacation island. You'll need to get from the
//! port to the nearest airport.
//!
//! Fortunate... | (input: &str) -> (usize, Vec<Bus>) {
let mut it = input.lines();
let first_line = it.next().unwrap();
let second_line = it.next().unwrap();
let depart_time = first_line.parse::<usize>().unwrap();
let shuttles = second_line
.split(',')
.enumerate()
.filter_map(|(serial, x)| {
... | parse_input | identifier_name |
day13.rs | //! # --- Day 13: Shuttle Search ---
//!
//! Your ferry can make it safely to a nearby port, but it won't get much
//! further. When you call to book another ship, you discover that no ships
//! embark from that port to your vacation island. You'll need to get from the
//! port to the nearest airport.
//!
//! Fortunate... |
}
}
earliest
}
fn main() -> Result<(), &'static str> {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
return Err("not enough arguments");
}
let filename = &args[1];
println!("Load input file {}.", filename);
let input = fs::read_to_string(filename).... | {
n += 1;
} | conditional_block |
day13.rs | //! # --- Day 13: Shuttle Search ---
//!
//! Your ferry can make it safely to a nearby port, but it won't get much
//! further. When you call to book another ship, you discover that no ships
//! embark from that port to your vacation island. You'll need to get from the
//! port to the nearest airport.
//!
//! Fortunate... | //!
//! ```
//! time bus 7 bus 13 bus 59 bus 31 bus 19
//! 929 . . . . .
//! 930 . . . D .
//! 931 D . . . D
//! 932 . . . . .
//! 933 . . . . .
//! 934 . . . . .
//!... | //!
//! Here, the earliest timestamp you could depart is `939`, and the bus IDs in
//! service are `7`, `13`, `59`, `31`, and `19`. Near timestamp `939`, these bus
//! IDs depart at the times marked `D`: | random_line_split |
day13.rs | //! # --- Day 13: Shuttle Search ---
//!
//! Your ferry can make it safely to a nearby port, but it won't get much
//! further. When you call to book another ship, you discover that no ships
//! embark from that port to your vacation island. You'll need to get from the
//! port to the nearest airport.
//!
//! Fortunate... |
}
| {
let earliest = clac_contest(&TEST_ARRAY);
assert_eq!(earliest, 1068781);
} | identifier_body |
samplesheet.rs | //! This module contains tools to build sample sheets from lists of samples,
//! and to export sample sheets to ARResT-compatible formats.
use std::{collections::HashMap, convert::TryInto, fs::File, io::Write, path::{Path, PathBuf}};
use std::error::Error;
use crate::{models, vaultdb::MatchStatus};
use calamine::{Re... | // write header
for (col, title) in basic_header.iter().chain(all_sans_basic.iter()).enumerate() {
sheet.write_string(0, col.clamp(0, u16::MAX.into()) as u16, title, None)?;
}
let has_multiple_runs = self.has_multiple_runs();
for (row, e) in self.entries.iter().enume... |
let basic_header = vec!["Sample", "run", "DNA nr", "primer set", "project", "LIMS ID", "cells"];
// extra_cols hashmap is not necessarily fully populated for every sample, so check all
let mut all_headers: Vec<String> = self.entries
.iter()
.map::<Vec<S... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.