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
runtime.rs
//#![allow(dead_code)] use std::sync::{Arc}; use std::path::{PathBuf}; use cgmath::{Vector2, Point2}; use input::{Input, Button, Key, ButtonState, ButtonArgs}; use window::{Window, WindowSettings}; use slog::{Logger}; use calcium_flowy::FlowyRenderer; use flowy::{Ui, Element}; use flowy::style::{Style, Position, Size...
); normaltexture.push_rectangle_full_texture( // position is centered in the texture Rectangle::new(self.position + -self.size/2.0, self.position + self.size/2.0) ); batches.push(normaltexture); if self.selected { let mut selectiontexture = Re...
} pub fn render(&mut self, batches: &mut Vec<RenderBatch<R>>) { //let mut batches = Vec::new(); let mut normaltexture = RenderBatch::new( ShaderMode::Texture(self.tex.clone()), UvMode::YDown
random_line_split
runtime.rs
//#![allow(dead_code)] use std::sync::{Arc}; use std::path::{PathBuf}; use cgmath::{Vector2, Point2}; use input::{Input, Button, Key, ButtonState, ButtonArgs}; use window::{Window, WindowSettings}; use slog::{Logger}; use calcium_flowy::FlowyRenderer; use flowy::{Ui, Element}; use flowy::style::{Style, Position, Size...
} pub fn get_position(&mut self) -> Point2<f32> { self.position } pub fn get_name(&mut self) -> &String { &self.name } } struct PlayerInput { pub w: bool, pub a: bool, pub s: bool, pub d: bool, pub tab: bool, } pub struct StaticRuntime { pub log: Logger, } ...
{ //let mut batches = Vec::new(); let mut normaltexture = RenderBatch::new( ShaderMode::Texture(self.tex.clone()), UvMode::YDown ); normaltexture.push_rectangle_full_texture( // position is centered in the texture Rectangle::new(self.position + -self.s...
identifier_body
array.rs
/* #![feature(collections_range)] #![feature(drain_filter)] #![feature(slice_rsplit)] #![feature(slice_get_slice)] #![feature(vec_resize_default)] #![feature(vec_remove_item)] #![feature(collections_range)] #![feature(slice_rotate)] #![feature(swap_with_slice)] */ foo bar baz use collections::range::RangeArgument; us...
{ self.0.splice(range,replace_with) } pub fn drain_filter<F:FnMut(&mut T)->bool>(&mut self, filter: F) -> DrainFilter<T, F> { self.0.drain_filter(filter) } } impl<T,INDEX:IndexTrait> Deref for Array<T,INDEX>{ type Target=[T]; fn deref(&self)->&Self::Target { self.0.deref() } } impl<T,INDEX:IndexTrait> Array...
impl<T,INDEX:IndexTrait> Array<T,INDEX>{ /// TODO - figure out how to convert RangeArguemnt indices pub fn splice<I:IntoIterator<Item=T>,R:RangeArgument<usize>>(&mut self, range:R, replace_with:I)-> Splice<<I as IntoIterator>::IntoIter>
random_line_split
array.rs
/* #![feature(collections_range)] #![feature(drain_filter)] #![feature(slice_rsplit)] #![feature(slice_get_slice)] #![feature(vec_resize_default)] #![feature(vec_remove_item)] #![feature(collections_range)] #![feature(slice_rotate)] #![feature(swap_with_slice)] */ foo bar baz use collections::range::RangeArgument; us...
(&self)->*const T{self.0.as_ptr()} fn as_mut_ptr(&mut self)->*mut T{self.0.as_mut_ptr()} fn swap(&mut self, a:INDEX,b:INDEX){ self.0.swap(a.my_into(),b.my_into()) } fn reverse(&mut self){self.0.reverse()} fn iter(&self)->Iter<T>{self.0.iter()} fn iter_mut(&mut self)->IterMut<T>{self.0.iter_mut()} fn windows(&s...
as_ptr
identifier_name
array.rs
/* #![feature(collections_range)] #![feature(drain_filter)] #![feature(slice_rsplit)] #![feature(slice_get_slice)] #![feature(vec_resize_default)] #![feature(vec_remove_item)] #![feature(collections_range)] #![feature(slice_rotate)] #![feature(swap_with_slice)] */ foo bar baz use collections::range::RangeArgument; us...
pub fn as_slice(&self) -> &[T]{ self.0.as_slice() } pub fn as_mut_slice(&mut self) -> &mut [T]{ self.0.as_mut_slice() } pub fn swap_remove(&mut self, index: I) -> T{ self.0.swap_remove(index.my_into()) } pub fn insert(&mut self, index: I, element: T){ self.0.insert(index.my_into(),element) } pub fn re...
{ self.0.truncate(len.my_into()); }
identifier_body
codemap.rs
use std::cell::RefCell; use std::cmp; use std::env; use std::{fmt, fs}; use std::io::{self, Read}; use std::ops::{Add, Sub}; use std::path::{Path, PathBuf}; use std::rc::Rc; use ast::Name; pub trait Pos { fn from_usize(n: usize) -> Self; fn to_usize(&self) -> usize; } /// A byte offset. Keep this small (currentl...
let end_pos = start_pos + src.len(); let filemap = Rc::new(FileMap { name: filename, abs_path: abs_path, src: Some(Rc::new(src)), start_pos: Pos::from_usize(start_pos), end_pos: Pos::from_usize(end_pos), lines: RefCell::new(Vec::new()), multibyte_chars: RefCell::new(...
{ src.drain(..3); }
conditional_block
codemap.rs
use std::cell::RefCell; use std::cmp; use std::env; use std::{fmt, fs}; use std::io::{self, Read}; use std::ops::{Add, Sub}; use std::path::{Path, PathBuf}; use std::rc::Rc; use ast::Name; pub trait Pos { fn from_usize(n: usize) -> Self; fn to_usize(&self) -> usize; } /// A byte offset. Keep this small (currentl...
/// The absolute path of the file that the source came from. pub abs_path: Option<FileName>, /// The complete source code pub src: Option<Rc<String>>, /// The start position of this source in the CodeMap pub start_pos: BytePos, /// The end position of this source in the CodeMap pub end_pos: BytePos, /...
/// originate from files has names between angle brackets by convention, /// e.g. `<anon>` pub name: FileName,
random_line_split
codemap.rs
use std::cell::RefCell; use std::cmp; use std::env; use std::{fmt, fs}; use std::io::{self, Read}; use std::ops::{Add, Sub}; use std::path::{Path, PathBuf}; use std::rc::Rc; use ast::Name; pub trait Pos { fn from_usize(n: usize) -> Self; fn to_usize(&self) -> usize; } /// A byte offset. Keep this small (currentl...
(self, other: Span) -> Option<Span> { if self.hi > other.hi { Some(Span { lo: cmp::max(self.lo, other.hi),.. self }) } else { None } } } #[derive(Clone, PartialEq, Eq, Hash, Debug, Copy)] pub struct Spanned<T> { pub node: T, pub span: Span, } /// A collection of spans. Spans have two ort...
trim_start
identifier_name
canvas.rs
use crate::color::Color; use std::collections::VecDeque; use std::io::{self, BufRead, BufReader, Read}; #[derive(Clone, Debug)] pub struct Canvas { pub width: usize, pub height: usize, data: Vec<Vec<Color>>, } const MAX_COLOR_VAL: u16 = 255; const MAX_PPM_LINE_LENGTH: usize = 70; // length of "255" is 3 /...
lines.next().unwrap(), "153 255 204 153 255 204 153 255 204 153 255 204 153" ); assert_eq!( lines.next().unwrap(), "255 204 153 255 204 153 255 204 153 255 204 153 255 204 153 255 204" ); assert_eq!( lines.next().unwrap(), ...
{ let mut canvas = Canvas::new(10, 2); let color = color!(1, 0.8, 0.6); // TODO: maybe turn this into a function on canvas? for row in 0..canvas.height { for column in 0..canvas.width { canvas.write_pixel(column, row, color); } } le...
identifier_body
canvas.rs
use crate::color::Color; use std::collections::VecDeque; use std::io::{self, BufRead, BufReader, Read}; #[derive(Clone, Debug)] pub struct Canvas { pub width: usize, pub height: usize, data: Vec<Vec<Color>>, } const MAX_COLOR_VAL: u16 = 255; const MAX_PPM_LINE_LENGTH: usize = 70; // length of "255" is 3 /...
(&self, line: &mut String, ppm: &mut String) { if line.len() < MAX_PPM_LINE_LENGTH - MAX_COLOR_VAL_STR_LEN { (*line).push(' '); } else { ppm.push_str(&line); ppm.push('\n'); line.clear(); } } // Return string containing PPM (portable pixel...
write_rgb_separator
identifier_name
canvas.rs
use crate::color::Color; use std::collections::VecDeque; use std::io::{self, BufRead, BufReader, Read}; #[derive(Clone, Debug)] pub struct Canvas { pub width: usize, pub height: usize, data: Vec<Vec<Color>>, } const MAX_COLOR_VAL: u16 = 255; const MAX_PPM_LINE_LENGTH: usize = 70; // length of "255" is 3 /...
if i!= self.width - 1 { self.write_rgb_separator(&mut current_line, &mut ppm); } } if!current_line.is_empty() { ppm.push_str(&current_line); ppm.push('\n'); } } ppm } } // TODO: p...
current_line.push_str(&b.to_string()); // if not at end of row yet, write a space or newline if the next point will be on this line
random_line_split
canvas.rs
use crate::color::Color; use std::collections::VecDeque; use std::io::{self, BufRead, BufReader, Read}; #[derive(Clone, Debug)] pub struct Canvas { pub width: usize, pub height: usize, data: Vec<Vec<Color>>, } const MAX_COLOR_VAL: u16 = 255; const MAX_PPM_LINE_LENGTH: usize = 70; // length of "255" is 3 /...
} } Ok(canvas) } fn clean_line( (index, line): (usize, Result<String, std::io::Error>), ) -> Option<(usize, Result<String, std::io::Error>)> { match line { Ok(s) => { let s = s.trim(); if s.starts_with("#") || s.is_empty() { None } el...
{ x = 0; y += 1; }
conditional_block
handshake.rs
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 //! The handshake module implements the handshake part of the protocol. //! This module also implements additional anti-DoS mitigation, //! by including a timestamp in each handshake initialization message. //! Refer to the module's do...
let server_auth = HandshakeAuthMode::mutual(trusted_peers); (client_auth, server_auth) } else { (HandshakeAuthMode::ServerOnly, HandshakeAuthMode::ServerOnly) }; let client = NoiseUpgrader::new(client_private, client_auth); let server = NoiseUpgrader:...
vec![(client_id, client_keys), (server_id, server_keys)] .into_iter() .collect(), )); let client_auth = HandshakeAuthMode::mutual(trusted_peers.clone());
random_line_split
handshake.rs
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 //! The handshake module implements the handshake part of the protocol. //! This module also implements additional anti-DoS mitigation, //! by including a timestamp in each handshake initialization message. //! Refer to the module's do...
fn anti_replay_timestamps(&self) -> Option<&RwLock<AntiReplayTimestamps>> { match &self { HandshakeAuthMode::Mutual { anti_replay_timestamps, .. } => Some(&anti_replay_timestamps), HandshakeAuthMode::ServerOnly => None, } } ...
{ HandshakeAuthMode::Mutual { anti_replay_timestamps: RwLock::new(AntiReplayTimestamps::default()), trusted_peers, } }
identifier_body
handshake.rs
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 //! The handshake module implements the handshake part of the protocol. //! This module also implements additional anti-DoS mitigation, //! by including a timestamp in each handshake initialization message. //! Refer to the module's do...
<TSocket>( &self, socket: TSocket, origin: ConnectionOrigin, remote_public_key: Option<x25519::PublicKey>, ) -> io::Result<(x25519::PublicKey, NoiseStream<TSocket>)> where TSocket: AsyncRead + AsyncWrite + Unpin, { // perform the noise handshake let so...
upgrade
identifier_name
lib.rs
// This crate is a library #![crate_type = "lib"] // This crate is named "pixel" #![crate_name = "pixel"] // Use +nightly to overpass this #![feature(test)] #[cfg(test)] mod tests; extern crate rand; use std::ops::Not; use std::path::Path; use std::fs::File; use std::io::BufReader; use std::io::prelude::*; use rand...
(red: u8, green: u8, blue:u8) -> Color { return Color {r : red, g : green, b : blue}; } /// Conctructor with random values for each color pub fn new_random() -> Color { let mut r = rand::thread_rng(); return Color { r : r.gen::<u8>(), g : r.gen::<u8>...
new
identifier_name
lib.rs
// This crate is a library #![crate_type = "lib"] // This crate is named "pixel" #![crate_name = "pixel"] // Use +nightly to overpass this #![feature(test)] #[cfg(test)] mod tests; extern crate rand; use std::ops::Not; use std::path::Path; use std::fs::File; use std::io::BufReader; use std::io::prelude::*; use rand...
/// Width's getter pub fn width(&self) -> u32 { return self.width; } /// Height's getter pub fn height(&self) -> u32 { return self.height; } /// Pixels getter pub fn pixels(&self) -> &Vec<Color> { return &self.pixels; } /// Equals() pub fn eq(&sel...
{ return Image {width : width, height : height, pixels : pixels}; }
identifier_body
lib.rs
// This crate is a library #![crate_type = "lib"] // This crate is named "pixel" #![crate_name = "pixel"] // Use +nightly to overpass this #![feature(test)] #[cfg(test)] mod tests; extern crate rand; use std::ops::Not; use std::path::Path; use std::fs::File; use std::io::BufReader; use std::io::prelude::*; use rand...
pub fn blue(&self) -> u8 { return self.b; } /// toString() to display a Color pub fn display(&self) { println!("r : {}, g : {}, b : {}", self.r, self.g, self.b); } /// Equals to determine if the two Color in parameters are equals. /// Return true if self and other and equal...
} /// Blue's getter
random_line_split
timer.rs
//! POSIX per-process timer interface. //! //! This module provides a wrapper around POSIX timers (see `timer_create(2)`) and utilities to //! setup thread-targeted signaling and signal masks. use std::mem::MaybeUninit; use std::time::Duration; use std::{io, mem}; use libc::{c_int, clockid_t, pid_t}; /// Timers can ...
(v: libc::timespec) -> Option<Duration> { if v.tv_sec == 0 && v.tv_nsec == 0 { None } else { Some(Duration::new(v.tv_sec as u64, v.tv_nsec as u32)) } } impl TimerSpec { // Helpers to convert between TimerSpec and libc::itimerspec fn to_itimerspec(&self) -> libc::itimerspec { ...
timespec_to_opt_duration
identifier_name
timer.rs
//! POSIX per-process timer interface. //! //! This module provides a wrapper around POSIX timers (see `timer_create(2)`) and utilities to //! setup thread-targeted signaling and signal masks. use std::mem::MaybeUninit; use std::time::Duration; use std::{io, mem}; use libc::{c_int, clockid_t, pid_t}; /// Timers can ...
TimerEvent::ThreadSignal(tid, signo) => { ev.sigev_signo = signo.0; ev.sigev_notify = libc::SIGEV_THREAD_ID; ev.sigev_notify_thread_id = tid.0; } TimerEvent::ThisThreadSignal(signo) => { ev.sigev_signo = signo.0; ...
{ ev.sigev_signo = signo.0; ev.sigev_notify = libc::SIGEV_SIGNAL; }
conditional_block
timer.rs
//! POSIX per-process timer interface. //! //! This module provides a wrapper around POSIX timers (see `timer_create(2)`) and utilities to //! setup thread-targeted signaling and signal masks. use std::mem::MaybeUninit; use std::time::Duration; use std::{io, mem}; use libc::{c_int, clockid_t, pid_t}; /// Timers can ...
}, } } fn timespec_to_opt_duration(v: libc::timespec) -> Option<Duration> { if v.tv_sec == 0 && v.tv_nsec == 0 { None } else { Some(Duration::new(v.tv_sec as u64, v.tv_nsec as u32)) } } impl TimerSpec { // Helpers to convert between TimerSpec and libc::itimerspec fn to_...
Some(value) => libc::timespec { tv_sec: value.as_secs() as i64, tv_nsec: value.subsec_nanos() as i64,
random_line_split
ias_proxy_server.rs
/* Copyright 2018 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, ...
// Cache is present, it can be sent Some(cache_present) => Ok(cache_present.clone()), // Cache is not presnet, request from IAS and add to cache None => { let result = ias_client_obj.post_verify_attestation( quote.as_bytes(), Option::from(json_...
.lock() .expect("Error acquiring AVR cache lock"); let cached_avr = attestation_cache_lock.get(&quote); let avr = match cached_avr {
random_line_split
ias_proxy_server.rs
/* Copyright 2018 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, ...
() { let client_response = Err(ClientError); let ias_response = ias_response_from_client_response(client_response); match ias_response { Ok(_unexpected) => assert!(false), Err(_expected) => assert!(true), }; } }
test_erraneous_ias_response_from_client_response
identifier_name
ias_proxy_server.rs
/* Copyright 2018 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, ...
Err(error_response) => Err(error_response), } } /// Function to construct ```IasProxyServer``` object with the input proxy configuration file. /// 'new()' for ```IasProxyServer``` is private, so use this public method to get instance of it. /// /// return: A ```IasProxyServer``` object pub fn get_proxy_se...
{ // Start conversion, need to parse client_resposne match client_response { Ok(successful_response) => { // If there's successful response, then read body to string let body_string_result = client_utils::read_body_as_string(successful_response.body); // If reading b...
identifier_body
mod.rs
use crate::graph::Graph; use log::debug; use std::collections::HashMap; use std::fmt; use ndarray::Array2; use thiserror::Error; mod builder; mod word; mod cell; mod add_word; mod random; mod spacing; mod properties; mod pdf_conversion; mod matrix; mod merge; mod validity; use word::Word; use cell::Cell; pub use bui...
FillBlack, } #[derive(Error,Debug,PartialEq)] pub enum CrosswordError { #[error("Adjacent cells {0:?} {1:?} incompatible - no word found that links them.")] AdjacentCellsNoLinkWord(Location, Location), #[error("Adjacent cells {0:?} {1:?} incompatible - should have a shared word which links them, but t...
#[error("Attempted to fill a cell already marked as black")]
random_line_split
mod.rs
use crate::graph::Graph; use log::debug; use std::collections::HashMap; use std::fmt; use ndarray::Array2; use thiserror::Error; mod builder; mod word; mod cell; mod add_word; mod random; mod spacing; mod properties; mod pdf_conversion; mod matrix; mod merge; mod validity; use word::Word; use cell::Cell; pub use bui...
Graph { let edges = self.get_all_intersections(); let mut graph = Graph::new_from_edges(edges); for (word_id, _word) in self.word_map.iter().filter(|(_id, w)| w.is_placed()) { graph.add_node(*word_id); } graph } pub fn to_string_with_coords(&self) -> String ...
elf) ->
identifier_name
mod.rs
use crate::graph::Graph; use log::debug; use std::collections::HashMap; use std::fmt; use ndarray::Array2; use thiserror::Error; mod builder; mod word; mod cell; mod add_word; mod random; mod spacing; mod properties; mod pdf_conversion; mod matrix; mod merge; mod validity; use word::Word; use cell::Cell; pub use bui...
n unplace_word(&mut self, word_id: usize) { for (_location, cell) in self.cell_map.iter_mut() { cell.remove_word(word_id); } if let Some(word) = self.word_map.get_mut(&word_id) { word.remove_placement(); } self.fit_to_size(); debug!("Now have {} wo...
elf.unplace_word(word_id); self.word_map.remove(&word_id); } pub f
identifier_body
codec.rs
//! encode and decode the frames for the mux protocol. //! The frames include the length of a PDU as well as an identifier //! that informs us how to decode it. The length, ident and serial //! number are encoded using a variable length integer encoding. //! Rather than rely solely on serde to serialize and deserializ...
(value: u64) -> usize { struct NullWrite {}; impl std::io::Write for NullWrite { fn write(&mut self, buf: &[u8]) -> std::result::Result<usize, std::io::Error> { Ok(buf.len()) } fn flush(&mut self) -> std::result::Result<(), std::io::Error> { Ok(()) } }...
encoded_length
identifier_name
codec.rs
//! encode and decode the frames for the mux protocol. //! The frames include the length of a PDU as well as an identifier //! that informs us how to decode it. The length, ident and serial //! number are encoded using a variable length integer encoding. //! Rather than rely solely on serde to serialize and deserializ...
pub serial: u64, pub pdu: Pdu, } /// If the serialized size is larger than this, then we'll consider compressing it const COMPRESS_THRESH: usize = 32; fn serialize<T: serde::Serialize>(t: &T) -> Result<(Vec<u8>, bool), Error> { let mut uncompressed = Vec::new(); let mut encode = varbincode::Serializer...
#[derive(Debug, PartialEq)] pub struct DecodedPdu {
random_line_split
macro.rs
#![crate_name = "docopt_macros"] #![crate_type = "dylib"] #![feature(plugin_registrar, quote, rustc_private)] //! This crate defines the `docopt!` macro. It is documented in the //! documentation of the `docopt` crate. extern crate syntax; extern crate rustc_plugin; extern crate docopt; use std::borrow::Borrow; use...
let public = self.p.eat_keyword(symbol::keywords::Pub); let mut info = StructInfo { name: try!(self.p.parse_ident()), public: public, deriving: vec![], }; if self.p.eat(&token::Comma) { return Ok(info); } let deriving = try!(self.p.parse_ident(...
random_line_split
macro.rs
#![crate_name = "docopt_macros"] #![crate_type = "dylib"] #![feature(plugin_registrar, quote, rustc_private)] //! This crate defines the `docopt!` macro. It is documented in the //! documentation of the `docopt` crate. extern crate syntax; extern crate rustc_plugin; extern crate docopt; use std::borrow::Borrow; use...
fn meta_item(cx: &ExtCtxt, s: &str) -> codemap::Spanned<ast::NestedMetaItemKind> { codemap::Spanned { node: ast::NestedMetaItemKind::MetaItem(cx.meta_word(codemap::DUMMY_SP, intern(s))), span: cx.call_site(), } } fn intern(s: &str) -> symbol::Symbol { symbol::Symbol::intern(s) } fn ty_ve...
{ let sp = codemap::DUMMY_SP; let its = items.into_iter().map(|s| meta_item(cx, s.borrow())).collect(); let mi = cx.meta_list(sp, intern(name.borrow()), its); cx.attribute(sp, mi) }
identifier_body
macro.rs
#![crate_name = "docopt_macros"] #![crate_type = "dylib"] #![feature(plugin_registrar, quote, rustc_private)] //! This crate defines the `docopt!` macro. It is documented in the //! documentation of the `docopt` crate. extern crate syntax; extern crate rustc_plugin; extern crate docopt; use std::borrow::Borrow; use...
(&self, cx: &ExtCtxt) -> Vec<ast::StructField> { let mut fields: Vec<ast::StructField> = vec!(); for (atom, opts) in self.doc.parser().descs.iter() { let name = ArgvMap::key_to_struct_field(&*atom.to_string()); let ty = match self.types.get(atom) { None => self.pa...
struct_fields
identifier_name
table.rs
use std::sync::Arc; use arrow::array::*; use arrow::datatypes::*; use arrow::record_batch::RecordBatch; use crate::error::*; #[derive(Clone)]
chunks: Vec<Arc<dyn Array>>, num_rows: usize, null_count: usize, } impl ChunkedArray { /// Construct a `ChunkedArray` from a list of `Array`s. /// /// There must be at least 1 array, and all arrays must have the same data type. fn from_arrays(arrays: Vec<Arc<dyn Array>>) -> Self { a...
pub struct ChunkedArray {
random_line_split
table.rs
use std::sync::Arc; use arrow::array::*; use arrow::datatypes::*; use arrow::record_batch::RecordBatch; use crate::error::*; #[derive(Clone)] pub struct ChunkedArray { chunks: Vec<Arc<dyn Array>>, num_rows: usize, null_count: usize, } impl ChunkedArray { /// Construct a `ChunkedArray` from a list of...
(&self, i: usize) -> &Arc<dyn Array> { &self.chunks[i] } pub fn chunks(&self) -> &Vec<Arc<dyn Array>> { &self.chunks } /// Construct a zero-copy slice of the chunked array with the indicated offset and length. /// /// The `offset` is the position of the first element in the con...
chunk
identifier_name
table.rs
use std::sync::Arc; use arrow::array::*; use arrow::datatypes::*; use arrow::record_batch::RecordBatch; use crate::error::*; #[derive(Clone)] pub struct ChunkedArray { chunks: Vec<Arc<dyn Array>>, num_rows: usize, null_count: usize, } impl ChunkedArray { /// Construct a `ChunkedArray` from a list of...
else if consumed_len + chunk_size > total_len { chunk_size } else { total_len - consumed_len }; let slice = indices.slice(consumed_len, bounded_len); let slice = slice.as_any().downcast_ref::<UInt32Array>().unwrap(); let taken ...
{ total_len }
conditional_block
table.rs
use std::sync::Arc; use arrow::array::*; use arrow::datatypes::*; use arrow::record_batch::RecordBatch; use crate::error::*; #[derive(Clone)] pub struct ChunkedArray { chunks: Vec<Arc<dyn Array>>, num_rows: usize, null_count: usize, } impl ChunkedArray { /// Construct a `ChunkedArray` from a list of...
/// Slice the table from an offset pub fn slice(&self, offset: usize, limit: usize) -> Self { Self { schema: self.schema.clone(), columns: self .columns .clone() .into_iter() .map(|col| col.slice(offset, Some(limit))) ...
{ // TODO validate that schema and columns match Self { schema, columns } }
identifier_body
client.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::sync::Arc; use log::debug; use log::info; use crate::backoff::DEFAULT_REGION_BACKOFF; use crate::config::Config; use crate::pd::PdClient; use crate::pd::PdRpcClient; use crate::proto::pdpb::Timestamp; use crate::request::plan::CleanupLocksRe...
/// Retrieve the current [`Timestamp`]. /// /// # Examples /// /// ```rust,no_run /// # use tikv_client::{Config, TransactionClient}; /// # use futures::prelude::*; /// # futures::executor::block_on(async { /// let client = TransactionClient::new(vec!["192.168.0.100"]).await.unwrap()...
Snapshot::new(self.new_transaction(timestamp, options.read_only())) }
random_line_split
client.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::sync::Arc; use log::debug; use log::info; use crate::backoff::DEFAULT_REGION_BACKOFF; use crate::config::Config; use crate::pd::PdClient; use crate::pd::PdRpcClient; use crate::proto::pdpb::Timestamp; use crate::request::plan::CleanupLocksRe...
Ok(res) } pub async fn cleanup_locks( &self, range: impl Into<BoundRange>, safepoint: &Timestamp, options: ResolveLocksOptions, ) -> Result<CleanupLocksResult> { debug!("invoking cleanup async commit locks"); // scan all locks with ts <= safepoint ...
{ info!("new safepoint != user-specified safepoint"); }
conditional_block
client.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::sync::Arc; use log::debug; use log::info; use crate::backoff::DEFAULT_REGION_BACKOFF; use crate::config::Config; use crate::pd::PdClient; use crate::pd::PdRpcClient; use crate::proto::pdpb::Timestamp; use crate::request::plan::CleanupLocksRe...
/// Retrieve the current [`Timestamp`]. /// /// # Examples /// /// ```rust,no_run /// # use tikv_client::{Config, TransactionClient}; /// # use futures::prelude::*; /// # futures::executor::block_on(async { /// let client = TransactionClient::new(vec!["192.168.0.100"]).await.unwrap...
{ debug!("creating new snapshot"); Snapshot::new(self.new_transaction(timestamp, options.read_only())) }
identifier_body
client.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::sync::Arc; use log::debug; use log::info; use crate::backoff::DEFAULT_REGION_BACKOFF; use crate::config::Config; use crate::pd::PdClient; use crate::pd::PdRpcClient; use crate::proto::pdpb::Timestamp; use crate::request::plan::CleanupLocksRe...
<S: Into<String>>(pd_endpoints: Vec<S>) -> Result<Client> { // debug!("creating transactional client"); Self::new_with_config(pd_endpoints, Config::default()).await } /// Create a transactional [`Client`] with a custom configuration, and connect to the TiKV cluster. /// /// Because TiKV...
new
identifier_name
main.rs
0); let c = v / 100.0 * s / 100.0; let x = c * (1.0 - (((h / 60.0) % 2.0) - 1.0).abs()); let m = (v / 100.0) - c; let (mut r, mut g, mut b) = match h { h if h < 60.0 => (c, x, 0.0), h if h < 120.0 => (x, c, 0.0), h if h < 180.0 => (0.0, c, x), h if h < 240.0 => (0.0, x,...
// should be more careful (this assumes that the client expects CreateView() to be called // multiple times, which clients commonly don't). let sender = self.internal_sender.clone(); fasync::Task::spawn(async move { let mut layout_info_stream = HangingGetStrea...
// link after data from the new link, just before the old link is closed. Non-example code
random_line_split
main.rs
(h: f32, s: f32, v: f32) -> [u8; 4] { assert!(s <= 100.0); assert!(v <= 100.0); let h = pos_mod(h, 360.0); let c = v / 100.0 * s / 100.0; let x = c * (1.0 - (((h / 60.0) % 2.0) - 1.0).abs()); let m = (v / 100.0) - c; let (mut r, mut g, mut b) = match h { h if h < 60.0 => (c, x, 0.0...
hsv_to_rgba
identifier_name
main.rs
let c = v / 100.0 * s / 100.0; let x = c * (1.0 - (((h / 60.0) % 2.0) - 1.0).abs()); let m = (v / 100.0) - c; let (mut r, mut g, mut b) = match h { h if h < 60.0 => (c, x, 0.0), h if h < 120.0 => (x, c, 0.0), h if h < 180.0 => (0.0, c, x), h if h < 240.0 => (0.0, x, c)...
while let Some(result) = layout_info_stream.next().await { match result { Ok(layout_info) => { let mut width = 0; let mut height = 0; if let Some(logical_size) = layout_info.logical_size { ...
{ let (parent_viewport_watcher, server_end) = create_proxy::<fland::ParentViewportWatcherMarker>() .expect("failed to create ParentViewportWatcherProxy"); // NOTE: it isn't necessary to call maybe_present() for this to take effect, because we will // relayout when re...
identifier_body
main.rs
self.1.x { if self.0.y < self.1.y { ( Polarity::Vertical, Bounds { low: self.0.y, high: self.1.y, bar: self.0.x, }, ) } else { ...
} macro_rules! route_vec { (@route R $num:expr) => {
random_line_split
main.rs
(&self) -> u64 { self.x.abs() as u64 + self.y.abs() as u64 } fn flat_distance_to(&self, other: &Self) -> u64 { (self.x - other.x).abs() as u64 + (self.y - other.y).abs() as u64 } } enum Polarity { Vertical, Horizontal, } #[allow(dead_code)] impl Polarity { fn is_horizontal(&se...
manhattan_distance
identifier_name
translate.rs
use rustast; use rustast::DUMMY_SP; use rustast::AstBuilder; pub use self::RustUse::*; pub use self::Expr::*; pub struct Grammar { pub imports: Vec<RustUse>, pub rules: Vec<Rule>, } #[deriving(Clone)] pub enum RustUse { RustUseSimple(String), RustUseGlob(String), RustUseList(String, Vec<String>), } pub struct R...
pub struct CharSetCase { pub start: char, pub end: char } pub struct TaggedExpr { pub name: Option<String>, pub expr: Box<Expr>, } pub enum Expr { AnyCharExpr, LiteralExpr(String), CharSetExpr(bool, Vec<CharSetCase>), RuleExpr(String), SequenceExpr(Vec<Expr>), ChoiceExpr(Vec<Expr>), OptionalExpr(Box<Expr>...
pub exported: bool, }
random_line_split
translate.rs
use rustast; use rustast::DUMMY_SP; use rustast::AstBuilder; pub use self::RustUse::*; pub use self::Expr::*; pub struct Grammar { pub imports: Vec<RustUse>, pub rules: Vec<Rule>, } #[deriving(Clone)] pub enum RustUse { RustUseSimple(String), RustUseGlob(String), RustUseList(String, Vec<String>), } pub struct
{ pub name: String, pub expr: Box<Expr>, pub ret_type: String, pub exported: bool, } pub struct CharSetCase { pub start: char, pub end: char } pub struct TaggedExpr { pub name: Option<String>, pub expr: Box<Expr>, } pub enum Expr { AnyCharExpr, LiteralExpr(String), CharSetExpr(bool, Vec<CharSetCase>), R...
Rule
identifier_name
translate.rs
use rustast; use rustast::DUMMY_SP; use rustast::AstBuilder; pub use self::RustUse::*; pub use self::Expr::*; pub struct Grammar { pub imports: Vec<RustUse>, pub rules: Vec<Rule>, } #[deriving(Clone)] pub enum RustUse { RustUseSimple(String), RustUseGlob(String), RustUseList(String, Vec<String>), } pub struct R...
fn compile_rule_export(ctxt: &rustast::ExtCtxt, rule: &Rule) -> rustast::P<rustast::Item> { let name = rustast::str_to_ident(rule.name.as_slice()); let ret = rustast::parse_type(rule.ret_type.as_slice()); let parse_fn = rustast::str_to_ident(format!("parse_{}", rule.name).as_slice()); (quote_item!(ctxt, pub fn ...
{ let name = rustast::str_to_ident(format!("parse_{}", rule.name).as_slice()); let ret = rustast::parse_type(rule.ret_type.as_slice()); let body = compile_expr(ctxt, &*rule.expr, rule.ret_type.as_slice() != "()"); (quote_item!(ctxt, fn $name<'input>(input: &'input str, state: &mut ParseState, pos: uint) -> ParseR...
identifier_body
lib.rs
use std::fs ; use std::collections::HashMap; use std::collections::HashSet; use std::iter::FromIterator; use std::iter::Iterator; use ndarray::Array2; use rayon; use rayon::prelude::*; use flate2::read::GzDecoder; use std::io::prelude::*; use glob::glob; use pyo3::prelude::*; use pyo3::wrap_pyfunction; #[derive(Debug)...
let mut s = String::new(); gz.read_to_string(&mut s)?; Ok(s) } fn read_cluster_results( file: &str) ->ClusterResults { let mut handle = fs::File::open(file).expect("Bad file input"); let mut buffer = Vec::new(); handle.read_to_end(&mut buffer).expect("couldnt read file"); let file_string = de...
return entropy(&new_clu.grouped_barcodes, &new_clu.labels); } } fn decode_reader(bytes: Vec<u8>) -> std::io::Result<String> { let mut gz = GzDecoder::new(&bytes[..]);
random_line_split
lib.rs
use std::fs ; use std::collections::HashMap; use std::collections::HashSet; use std::iter::FromIterator; use std::iter::Iterator; use ndarray::Array2; use rayon; use rayon::prelude::*; use flate2::read::GzDecoder; use std::io::prelude::*; use glob::glob; use pyo3::prelude::*; use pyo3::wrap_pyfunction; #[derive(Debug)...
fn write_csv_simple(&self, outfile:&str)->std::io::Result<()>{ let mut lines: Vec<String> = vec![String::new();self.cluster_ids.len()]; for i in 0..self.cluster_ids.len(){ lines[i] = format!("{},{},{}\n",self.cluster_ids[i], self.stability_scores[i],self.purity_scores[i]) } ...
{ let mut lines: Vec<String> = vec![String::new();self.cluster_ids.len()]; for i in 0..self.cluster_ids.len(){ lines[i] = format!("{},{},{}\n",self.cluster_ids[i], self.stability_scores[i],self.purity_scores[i]) } let outfile = format!("{}/{}", outpath, self.exp_param); ...
identifier_body
lib.rs
use std::fs ; use std::collections::HashMap; use std::collections::HashSet; use std::iter::FromIterator; use std::iter::Iterator; use ndarray::Array2; use rayon; use rayon::prelude::*; use flate2::read::GzDecoder; use std::io::prelude::*; use glob::glob; use pyo3::prelude::*; use pyo3::wrap_pyfunction; #[derive(Debug)...
(v:Vec<f64>) -> f64{ return v.iter().sum::<f64>() / v.len() as f64 } fn purity_k(ref_bc_set: &HashSet<i64>, query_map: &HashMap<i64, HashSet<i64>>) -> f64{ let mut max_overlap = 0; let mut max_overlap_key:i64 = -100000000; for query_key in query_map.keys(){ let q_cluster_set = query_map.get(query...
vmean
identifier_name
lib.rs
use std::fs ; use std::collections::HashMap; use std::collections::HashSet; use std::iter::FromIterator; use std::iter::Iterator; use ndarray::Array2; use rayon; use rayon::prelude::*; use flate2::read::GzDecoder; use std::io::prelude::*; use glob::glob; use pyo3::prelude::*; use pyo3::wrap_pyfunction; #[derive(Debug)...
let ns: HashSet<i64> = HashSet::new(); current_set = ns; current_set.insert(current_barcode.clone()); old_label = current_label; } } grouped_barcodes.insert(current_label.clone(), current_set); let h_tot = entropy(&grou...
{ // HashMap.insert returns None when new key is added panic!("A duplicate key was added when making a ClusterResults; input data is not sorted by label") }
conditional_block
vt-3.rs
CString::new("VK_LAYER_KHRONOS_validation").unwrap(), ]; let layers_names_raw: Vec<*const i8> = layer_names .iter() .map(|raw_name| raw_name.as_ptr()) .collect(); let extension_names_raw = extension_names(); let debug_utils_create_info = vk::DebugUtilsMessengerCreateInfoEXT ...
{ use winit::os::unix::WindowExt; let x11_display = window.get_xlib_display().unwrap(); let x11_window = window.get_xlib_window().unwrap(); let x11_create_info = vk::XlibSurfaceCreateInfoKHR { s_type: vk::StructureType::XLIB_SURFACE_CREATE_INFO_KHR, p_next: ptr::null(), flags: D...
identifier_body
vt-3.rs
CString::new("VK_LAYER_LUNARG_standard_validation").unwrap(), CString::new("VK_LAYER_KHRONOS_validation").unwrap(), ]; let layers_names_raw: Vec<*const i8> = layer_names .iter() .map(|raw_name| raw_name.as_ptr()) .collect(); let extension_names_raw = extension_names(); ...
queue_family_index, queue_count: 1, p_queue_priorities: [1.0].as_ptr(), }; let device_extensions_raw = get_device_extensions_raw(); let device_create_info = vk::DeviceCreateInfo { s_type: vk::StructureType::DEVICE_CREATE_INFO, p_next: ptr::null(), flags: vk:...
flags: vk::DeviceQueueCreateFlags::empty(),
random_line_split
vt-3.rs
CString::new("VK_LAYER_LUNARG_standard_validation").unwrap(), CString::new("VK_LAYER_KHRONOS_validation").unwrap(), ]; let layers_names_raw: Vec<*const i8> = layer_names .iter() .map(|raw_name| raw_name.as_ptr()) .collect(); let extension_names_raw = extension_names(); ...
( message_severity: vk::DebugUtilsMessageSeverityFlagsEXT, message_type: vk::DebugUtilsMessageTypeFlagsEXT, p_callback_data: *const vk::DebugUtilsMessengerCallbackDataEXT, _p_user_data: *mut c_void, ) -> vk::Bool32 { let severity = match message_severity { vk::DebugUtilsMessageSeverityFlagsE...
vulkan_debug_utils_callback
identifier_name
mod.rs
// Copyright (c) The XPeer Core Contributors // SPDX-License-Identifier: Apache-2.0 //! Protocol for fire-and-forget style message delivery to a peer //! //! DirectSend protocol takes advantage of [muxers] and [substream negotiation] to build a simple //! best effort message delivery protocol. Concretely, //! //! 1. E...
( executor: TaskExecutor, ds_requests_rx: channel::Receiver<DirectSendRequest>, ds_notifs_tx: channel::Sender<DirectSendNotification>, peer_mgr_notifs_rx: channel::Receiver<PeerManagerNotification<TSubstream>>, peer_mgr_reqs_tx: PeerManagerRequestSender<TSubstream>, ) -> Self...
new
identifier_name
mod.rs
// Copyright (c) The XPeer Core Contributors // SPDX-License-Identifier: Apache-2.0 //! Protocol for fire-and-forget style message delivery to a peer //! //! DirectSend protocol takes advantage of [muxers] and [substream negotiation] to build a simple //! best effort message delivery protocol. Concretely, //! //! 1. E...
//! that only the dialer sends a message to the listener, but no messages or acknowledgements //! sending back on the other direction. So the message delivery is best effort and not //! guaranteed. Because the substreams are independent, there is no guarantee on the ordering //! of the message delivery eith...
random_line_split
mod.rs
// Copyright (c) The XPeer Core Contributors // SPDX-License-Identifier: Apache-2.0 //! Protocol for fire-and-forget style message delivery to a peer //! //! DirectSend protocol takes advantage of [muxers] and [substream negotiation] to build a simple //! best effort message delivery protocol. Concretely, //! //! 1. E...
; write!( f, "Message {{ protocol: {:?}, mdata: {} }}", self.protocol, mdata_str ) } } /// The DirectSend actor. pub struct DirectSend<TSubstream> { /// A handle to a tokio executor. executor: TaskExecutor, /// Channel to receive requests from other u...
{ format!("{:?}...", self.mdata.slice_to(10)) }
conditional_block
test_1.rs
const USAGE: &str = " Usage: test_1 [--dt N] [--plots] test_1 --help A template for DEM spherical particles modelling. This benchmark is taken from author: XXXX paper: XXXX link: XXXX Description: ----------- Describe the test in a few lines. Method: -------- What specific DEM model is used to model the...
{ flag_tf: f64, flag_dt: f64, flag_plots: bool, } pub fn main(args: &[String]) { // -------------------------------------- // GET THE COMMAND LINE VARIABLES // -------------------------------------- let args: Args = Docopt::new(USAGE) .and_then(|d| d.argv(args).deserialize()) ...
Args
identifier_name
test_1.rs
const USAGE: &str = " Usage: test_1 [--dt N] [--plots] test_1 --help A template for DEM spherical particles modelling. This benchmark is taken from author: XXXX paper: XXXX link: XXXX Description: ----------- Describe the test in a few lines. Method: -------- What specific DEM model is used to model the...
let rho = 2600.; sand.rho = vec![rho; x.len()]; sand.m = vec![rho * PI * radius[0] * radius[0]; x.len()]; sand.m_inv = vec![1. / sand.m[0]; x.len()]; let inertia = 4. * (2. * radius[0]) * (2. * radius[0]) / 10.; sand.mi = vec![inertia; x.len()]; sand.mi_inv = vec![1. / sand.mi[0]; x.len()];...
{ // -------------------------------------- // GET THE COMMAND LINE VARIABLES // -------------------------------------- let args: Args = Docopt::new(USAGE) .and_then(|d| d.argv(args).deserialize()) .unwrap_or_else(|e| e.exit()); // println!("{:?}", args); // ---------------------...
identifier_body
test_1.rs
const USAGE: &str = " Usage: test_1 [--dt N] [--plots] test_1 --help A template for DEM spherical particles modelling. This benchmark is taken from author: XXXX paper: XXXX link: XXXX Description: ----------- Describe the test in a few lines. Method: -------- What specific DEM model is used to model the...
; // ---------------------------------------- // SOLVER DATA ENDS // ---------------------------------------- // ---------------------------------------- // OUTPUT DIRECTORY // ---------------------------------------- let project_root = env!("CARGO_MANIFEST_DIR"); let dir_name = project...
{ total_steps / total_output_file }
conditional_block
test_1.rs
const USAGE: &str = " Usage: test_1 [--dt N] [--plots] test_1 --help A template for DEM spherical particles modelling. This benchmark is taken from author: XXXX paper: XXXX link: XXXX Description: ----------- Describe the test in a few lines. Method: -------- What specific DEM model is used to model the...
// let px = 1000; // fg.save_to_png( // &format!( // "{}/chung_test_4_incident_angle_vs_rebound_angle.png", // &dir_name // ), // px, // px, // ) //.unwrap(); // if args.flag_plots { // fg.show().unwrap(); // } // --------------...
// &[Caption("Al oxide"), Color("blue")], // );
random_line_split
lib.rs
//! An incomplete wrapper over the WinRT toast api //! //! Tested in Windows 10 and 8.1. Untested in Windows 8, might work. //! //! Todo: //! //! * Add support for Adaptive Content //! * Add support for Actions //! //! Known Issues: //! //! * Will not work for Windows 7. //! * Will not build when targeting the 32-bit g...
Call, Call2, Call3, Call4, Call5, Call6, Call7, Call8, Call9, Call10, } #[allow(dead_code)] #[derive(Clone, Copy)] pub enum IconCrop { Square, Circular, } #[doc(hidden)] impl fmt::Display for Sound { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt...
Alarm9, Alarm10,
random_line_split
lib.rs
//! An incomplete wrapper over the WinRT toast api //! //! Tested in Windows 10 and 8.1. Untested in Windows 8, might work. //! //! Todo: //! //! * Add support for Adaptive Content //! * Add support for Actions //! //! Known Issues: //! //! * Will not work for Windows 7. //! * Will not build when targeting the 32-bit g...
{ /// 7 seconds Short, /// 25 seconds Long, } #[derive(Debug, EnumString, Clone, Copy)] pub enum Sound { Default, IM, Mail, Reminder, SMS, /// Play the loopable sound only once #[strum(disabled)] Single(LoopableSound), /// Loop the loopable sound for the entire dur...
Duration
identifier_name
lib.rs
//! An incomplete wrapper over the WinRT toast api //! //! Tested in Windows 10 and 8.1. Untested in Windows 8, might work. //! //! Todo: //! //! * Add support for Adaptive Content //! * Add support for Actions //! //! Known Issues: //! //! * Will not work for Windows 7. //! * Will not build when targeting the 32-bit g...
{} {}{}{} </binding> </visual> {} </toast>", self.duration, template_binding, self.images, self.title, self.line1, self....
//using this to get an instance of XmlDocument let toast_xml = XmlDocument::new()?; let template_binding = if windows_check::is_newer_than_windows81() { "ToastGeneric" } else //win8 or win81 { // Need to do this or an empty placeholder will be shown i...
identifier_body
authorization.rs
use rocket::{Request, Outcome}; use rocket::response::{Redirect, Flash}; use rocket::request::{FromRequest, FromForm, FormItems, FormItem}; use rocket::http::{Cookie, Cookies}; use std::collections::HashMap; use std::marker::Sized; use sanitization::*; #[derive(Debug, Clone)] pub struct UserQuery { pub user: Str...
<'a>() -> &'a str { "sid" } } /// ## Cookie Data /// The AuthorizeCookie trait is used with a custom data structure that /// will contain the data in the cookie. This trait provides methods /// to store and retrieve a data structure from a cookie's string contents. /// /// Using a request guard a route c...
cookie_id
identifier_name
authorization.rs
use rocket::{Request, Outcome}; use rocket::response::{Redirect, Flash}; use rocket::request::{FromRequest, FromForm, FormItems, FormItem}; use rocket::http::{Cookie, Cookies}; use std::collections::HashMap; use std::marker::Sized; use sanitization::*; #[derive(Debug, Clone)] pub struct UserQuery { pub user: Stri...
/// // Change the return type to match your type /// fn from_request(request: &'a Request<'r>) -> ::rocket::request::Outcome<AdministratorCookie,Self::Error>{ /// let cid = AdministratorCookie::cookie_id(); /// let mut cookies = request.cookies(); /// /// mat...
/// type Error = ();
random_line_split
authorization.rs
use rocket::{Request, Outcome}; use rocket::response::{Redirect, Flash}; use rocket::request::{FromRequest, FromForm, FormItems, FormItem}; use rocket::http::{Cookie, Cookies}; use std::collections::HashMap; use std::marker::Sized; use sanitization::*; #[derive(Debug, Clone)] pub struct UserQuery { pub user: Str...
, // _ => {}, a => { // extras.insert( a.to_string(), A::clean_extras( &value.url_decode().unwrap_or(String::new()) ) ); extras.insert( a.to_string(), value.url_decode().unwrap_or(String::new()) ); }, } } ...
{ pass = A::clean_password(&value.url_decode().unwrap_or(String::new())); }
conditional_block
authorization.rs
use rocket::{Request, Outcome}; use rocket::response::{Redirect, Flash}; use rocket::request::{FromRequest, FromForm, FormItems, FormItem}; use rocket::http::{Cookie, Cookies}; use std::collections::HashMap; use std::marker::Sized; use sanitization::*; #[derive(Debug, Clone)] pub struct UserQuery { pub user: Str...
} /// ## Form Data /// The AuthorizeForm trait handles collecting a submitted login form into a /// data structure and authenticating the credentials inside. It also contains /// default methods to process the login and conditionally redirecting the user /// to the correct page depending upon successful authenticat...
{ cookies.remove_private( Cookie::named( Self::cookie_id() ) ); }
identifier_body
binder.rs
// Copyright 2021 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 { crate::{ capability::{ CapabilityProvider, CapabilitySource, ComponentCapability, InternalCapability, OptionalTas...
.expect("task is empty") .await; let client_end = AsyncChannel::from_channel(client_end).expect("failed to create AsyncChanel"); let client = Client::new(client_end, "binder_service"); let mut event_receiver = client.take_event_receiver(); assert_matche...
{ let fixture = BinderCapabilityTestFixture::new(vec![( "root", ComponentDeclBuilder::new() .add_lazy_child("target") .add_lazy_child("unresolvable") .build(), )]) .await; let (client_end, mut server_end) = ...
identifier_body
binder.rs
// Copyright 2021 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 { crate::{ capability::{ CapabilityProvider, CapabilitySource, ComponentCapability, InternalCapability, OptionalTas...
#[async_trait] impl CapabilityProvider for BinderCapabilityProvider { async fn open( self: Box<Self>, _flags: u32, _open_mode: u32, _relative_path: PathBuf, server_end: &mut zx::Channel, ) -> Result<OptionalTask, ModelError> { let host = self.host.clone(); ...
}
random_line_split
binder.rs
// Copyright 2021 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 { crate::{ capability::{ CapabilityProvider, CapabilitySource, ComponentCapability, InternalCapability, OptionalTas...
else { Ok(capability_provider) } } } #[async_trait] impl Hook for BinderCapabilityHost { async fn on(self: Arc<Self>, event: &Event) -> Result<(), ModelError> { if let Ok(EventPayload::CapabilityRouted { source: CapabilitySource::Framework { capability, component }, ...
{ let model = self.model.upgrade().ok_or(ModelError::ModelNotAvailable)?; let target = WeakComponentInstance::new(&model.look_up(&target_moniker.to_partial()).await?); Ok(Some(Box::new(BinderCapabilityProvider::new(source, target, self.clone())) as Box...
conditional_block
binder.rs
// Copyright 2021 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 { crate::{ capability::{ CapabilityProvider, CapabilitySource, ComponentCapability, InternalCapability, OptionalTas...
(components: Vec<(&'static str, ComponentDecl)>) -> Self { let TestModelResult { builtin_environment,.. } = TestEnvironmentBuilder::new().set_components(components).build().await; BinderCapabilityTestFixture { builtin_environment } } async fn new_event_stream( ...
new
identifier_name
lib.rs
(arg: *mut #name) { unsafe { assert!(!arg.is_null()); &*arg; } } }; let default_name = swig_fn(&name, "default"); // TOOD: Add more derive capabilities // Extracting the derived methods from `#[swig_deri...
} acc }, _ => Vec::new(), } }) }, syn::Item::Struct(syn::ItemStruct { attrs, ident,.. }) | syn::Item::Fn(syn::ItemFn { attrs, ident,...
debug!("{:#?}", iim); if iim.sig.ident.to_string().starts_with(SwigTag::SwigInject.to_str()) { acc.extend_from_slice(&iim.attrs[..]);
random_line_split
lib.rs
arg: *mut #name) { unsafe { assert!(!arg.is_null()); &*arg; } } }; let default_name = swig_fn(&name, "default"); // TOOD: Add more derive capabilities // Extracting the derived methods from `#[swig_deriv...
/// Write the swig code (injected via doc comments) into `swig.i`. /// This parses expanded Rust code, and writes the SWIG code to a file. pub fn gen_swig(pkg_name: &str, src: &str) { let mut tmp_file = File::create("swig.i").unwrap(); tmp_file.write_all(format!("\ %module {name} #define PKG_NAME {name} %inc...
{ let ifn = InternalFn { base: base_name, fn_def: ast, }; let tok = ifn.as_extern(); let comment = ifn.to_swig(); let hidden = swig_fn(&ast.ident, "hidden_ffi"); quote! { #[allow(non_snake_case)] #[doc=#comment] fn #hidden(){} #tok } }
identifier_body
lib.rs
#ty) } } } /// Similar to above, make sure that we return primitives when /// recognised fn convert_ret_type(rty: &syn::ReturnType, base: &Option<syn::Ident>) -> syn::ReturnType { match rty { syn::ReturnType::Default => syn::ReturnType::Default, syn::ReturnType::Type(_, ty) => { ...
split_out_externs
identifier_name
park.rs
use std::{ cell::Cell, sync::atomic::{AtomicBool, Ordering}, thread::{self, Thread}, }; use conquer_util::BackOff; use crate::{ cell::{Block, Unblock}, state::{ AtomicOnceState, BlockedState, OnceState::{Ready, Uninit, WouldBlock}, }, POISON_PANIC_MSG, }; use self::interna...
(state: &AtomicOnceState) { // spin a little before parking the thread in case the state is // quickly unlocked again let back_off = BackOff::new(); let blocked = match Self::try_block_spinning(state, &back_off) { Ok(_) => return, Err(blocked) => blocked, ...
block
identifier_name
park.rs
use std::{ cell::Cell, sync::atomic::{AtomicBool, Ordering}, thread::{self, Thread}, }; use conquer_util::BackOff; use crate::{ cell::{Block, Unblock}, state::{ AtomicOnceState, BlockedState, OnceState::{Ready, Uninit, WouldBlock}, }, POISON_PANIC_MSG, }; use self::interna...
// SAFETY: `head` is a valid pointer to a `StackWaiter` that will live // for the duration of this function, which in turn will only return // when no other thread can still observe any pointer to it // (wait:2) this acq-rel CAS syncs-with itself and the acq load (wait:1) while l...
{ // spin a little before parking the thread in case the state is // quickly unlocked again let back_off = BackOff::new(); let blocked = match Self::try_block_spinning(state, &back_off) { Ok(_) => return, Err(blocked) => blocked, }; // create a li...
identifier_body
park.rs
use std::{ cell::Cell, sync::atomic::{AtomicBool, Ordering}, thread::{self, Thread}, }; use conquer_util::BackOff; use crate::{ cell::{Block, Unblock}, state::{ AtomicOnceState, BlockedState, OnceState::{Ready, Uninit, WouldBlock}, }, POISON_PANIC_MSG, }; use self::interna...
} } } impl Unblock for ParkThread { /// Unblocks all blocked waiting threads. #[inline] unsafe fn on_unblock(state: BlockedState) { let mut curr = state.as_ptr() as *const StackWaiter; while!curr.is_null() { let thread = { // SAFETY: no mutable refere...
back_off.spin();
random_line_split
proof.rs
use std::cmp::Ordering; use std::hash::{Hash, Hasher}; use ring::digest::Algorithm; use crate::hashutils::HashUtils; use crate::tree::Tree; /// An inclusion proof represent the fact that a `value` is a member /// of a `MerkleTree` with root hash `root_hash`, and hash function `algorithm`. #[cfg_attr(feature = "seria...
} impl<T: Ord> Ord for Proof<T> { fn cmp(&self, other: &Proof<T>) -> Ordering { self.root_hash .cmp(&other.root_hash) .then(self.value.cmp(&other.value)) .then_with(|| self.lemma.cmp(&other.lemma)) } } impl<T: Hash> Hash for Proof<T> { fn hash<H: Hasher>(&self, st...
{ Some(self.cmp(other)) }
identifier_body
proof.rs
use std::cmp::Ordering; use std::hash::{Hash, Hasher}; use ring::digest::Algorithm; use crate::hashutils::HashUtils; use crate::tree::Tree; /// An inclusion proof represent the fact that a `value` is a member /// of a `MerkleTree` with root hash `root_hash`, and hash function `algorithm`. #[cfg_attr(feature = "seria...
else { None } } fn new_tree_proof<T>( hash: &[u8], needle: &[u8], left: &Tree<T>, right: &Tree<T>, ) -> Option<Lemma> { Lemma::new(left, needle) .map(|lemma| { let right_hash = right.hash().clone(); let ...
{ Some(Lemma { node_hash: hash.into(), sibling_hash: None, sub_lemma: None, }) }
conditional_block
proof.rs
use std::cmp::Ordering; use std::hash::{Hash, Hasher}; use ring::digest::Algorithm; use crate::hashutils::HashUtils; use crate::tree::Tree; /// An inclusion proof represent the fact that a `value` is a member /// of a `MerkleTree` with root hash `root_hash`, and hash function `algorithm`. #[cfg_attr(feature = "seria...
<T>( hash: &[u8], needle: &[u8], left: &Tree<T>, right: &Tree<T>, ) -> Option<Lemma> { Lemma::new(left, needle) .map(|lemma| { let right_hash = right.hash().clone(); let sub_lemma = Some(Positioned::Right(right_hash)); ...
new_tree_proof
identifier_name
proof.rs
use std::cmp::Ordering; use std::hash::{Hash, Hasher}; use ring::digest::Algorithm; use crate::hashutils::HashUtils; use crate::tree::Tree; /// An inclusion proof represent the fact that a `value` is a member /// of a `MerkleTree` with root hash `root_hash`, and hash function `algorithm`. #[cfg_attr(feature = "seria...
ref hash, ref value, .. } => { if count!= 1 { return None; } let lemma = Lemma { node_hash: hash.clone(), sibling_hash: None, sub_lem...
random_line_split
main.rs
mod capture; mod d3d; mod displays; mod hotkey; mod media; mod resolution; mod video; use std::{path::Path, time::Duration}; use clap::{App, Arg, SubCommand}; use hotkey::HotKey; use windows::{ core::{Result, RuntimeName}, Foundation::Metadata::ApiInformation, Graphics::{ Capture::{GraphicsCapture...
if verbose { println!( "Using index \"{}\" and path \"{}\".", display_index, output_path ); } // Get the display handle using the provided index let display_handle = get_display_handle_from_index(display_index) .expect("The provided display index was out ...
if !required_capture_features_supported()? { exit_with_error("The required screen capture features are not supported on this device for this release of Windows!\nPlease update your operating system (minimum: Windows 10 Version 1903, Build 18362)."); }
random_line_split
main.rs
mod capture; mod d3d; mod displays; mod hotkey; mod media; mod resolution; mod video; use std::{path::Path, time::Duration}; use clap::{App, Arg, SubCommand}; use hotkey::HotKey; use windows::{ core::{Result, RuntimeName}, Foundation::Metadata::ApiInformation, Graphics::{ Capture::{GraphicsCapture...
fn required_capture_features_supported() -> Result<bool> { let result = ApiInformation::IsTypePresent(GraphicsCaptureSession::NAME)? && // Windows.Graphics.Capture is present GraphicsCaptureSession::IsSupported()? && // The CaptureService is available win32_programmatic_capture_supported()?; Ok(result...
{ ApiInformation::IsApiContractPresentByMajor("Windows.Foundation.UniversalApiContract", 8) }
identifier_body
main.rs
mod capture; mod d3d; mod displays; mod hotkey; mod media; mod resolution; mod video; use std::{path::Path, time::Duration}; use clap::{App, Arg, SubCommand}; use hotkey::HotKey; use windows::{ core::{Result, RuntimeName}, Foundation::Metadata::ApiInformation, Graphics::{ Capture::{GraphicsCapture...
if verbose { println!( "Using index \"{}\" and path \"{}\".", display_index, output_path ); } // Get the display handle using the provided index let display_handle = get_display_handle_from_index(display_index) .expect("The provided display index was out...
{ exit_with_error("The required screen capture features are not supported on this device for this release of Windows!\nPlease update your operating system (minimum: Windows 10 Version 1903, Build 18362)."); }
conditional_block
main.rs
mod capture; mod d3d; mod displays; mod hotkey; mod media; mod resolution; mod video; use std::{path::Path, time::Duration}; use clap::{App, Arg, SubCommand}; use hotkey::HotKey; use windows::{ core::{Result, RuntimeName}, Foundation::Metadata::ApiInformation, Graphics::{ Capture::{GraphicsCapture...
( display_index: usize, output_path: &str, bit_rate: u32, frame_rate: u32, resolution: Resolution, encoder_index: usize, verbose: bool, wait_for_debugger: bool, console_mode: bool, ) -> Result<()> { unsafe { RoInitialize(RO_INIT_MULTITHREADED)?; } unsafe { MFStart...
run
identifier_name
receiver.rs
(&mut self) -> Pin<&mut T> { Pin::new(&mut self.sock) } fn ack_interval(&mut self) -> Pin<&mut Interval> { Pin::new(&mut self.ack_interval) } fn nak_interval(&mut self) -> Pin<&mut Delay> { Pin::new(&mut self.nak_interval) } fn release_delay(&mut self) -> Pin<&mut Dela...
{ let vec: Vec<_> = lost_seq_nums.collect(); debug!("Sending NAK for={:?}", vec); let pack = self.make_control_packet(ControlTypes::Nak( compress_loss_list(vec.iter().cloned()).collect(), )); self.send_to_remote(cx, pack)?; Ok(()) }
identifier_body
receiver.rs
/// wakes the thread when there is a new packet to be released release_delay: Delay, /// A buffer of packets to send to the underlying sink send_wrapper: SinkSendWrapper<(Packet, SocketAddr)>, } impl<T> Receiver<T> where T: Stream<Item = Result<(Packet, SocketAddr), Error>> + Sink<(Packet,...
(&mut self, cx: &mut Context, packet: Packet) -> Result<(), Error> { self.send_wrapper .send(&mut self.sock, (packet, self.settings.remote), cx) } fn reset_timeout(&mut self) { self.timeout_timer.reset(time::Instant::from_std( Instant::now() + self.listen_timeout, ...
send_to_remote
identifier_name
receiver.rs
/// wakes the thread when there is a new packet to be released release_delay: Delay, /// A buffer of packets to send to the underlying sink send_wrapper: SinkSendWrapper<(Packet, SocketAddr)>, } impl<T> Receiver<T> where T: Stream<Item = Result<(Packet, SocketAddr), Error>> + Sink<(Packet...
return Ok(()); } trace!("Received packet: {:?}", packet); match packet { Packet::Control(ctrl) => { // handle the control packet match &ctrl.control_type { ControlTypes::Ack {.. } => warn!("Receiver received ACK packe...
info!( "Packet send to socket id ({}) that does not match local ({})", packet.dest_sockid().0, self.settings.local_sockid.0 );
random_line_split
main.rs
#[macro_use] extern crate clap; extern crate irb; extern crate las; extern crate palette; extern crate riscan_pro; extern crate scanifc; #[macro_use] extern crate serde_derive; #[macro_use] extern crate text_io; extern crate toml; use clap::{App, ArgMatches}; use irb::Irb; use las::Color; use las::point::Format; use p...
match err.kind() { ErrorKind::NotFound => Vec::new(), _ => panic!("io error: {}", err), } } } } fn outfile<P: AsRef<Path>>(&self, scan_position: &ScanPosition, infile: P) -> PathBuf { let mut outfile = self.las_...
} Err(err) => { use std::io::ErrorKind;
random_line_split
main.rs
#[macro_use] extern crate clap; extern crate irb; extern crate las; extern crate palette; extern crate riscan_pro; extern crate scanifc; #[macro_use] extern crate serde_derive; #[macro_use] extern crate text_io; extern crate toml; use clap::{App, ArgMatches}; use irb::Irb; use las::Color; use las::point::Format; use p...
(&self, socs: &Point<Socs>) -> Option<f64> { let cmcs = socs.to_cmcs(self.image.cop, self.mount_calibration); self.camera_calibration.cmcs_to_ics(&cmcs).map(|(mut u, mut v)| { if self.rotate { let new_u = self.camera_calibration.height as f64 - v; v ...
temperature
identifier_name
main.rs
#[macro_use] extern crate clap; extern crate irb; extern crate las; extern crate palette; extern crate riscan_pro; extern crate scanifc; #[macro_use] extern crate serde_derive; #[macro_use] extern crate text_io; extern crate toml; use clap::{App, ArgMatches}; use irb::Irb; use las::Color; use las::point::Format; use p...
}) .collect() } Err(err) => { use std::io::ErrorKind; match err.kind() { ErrorKind::NotFound => Vec::new(), _ => panic!("io error: {}", err), } } } ...
{ None }
conditional_block
map_output_tracker.rs
use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::sync::Arc; use std::time::Duration; use crate::serialized_data_capnp::serialized_data; use crate::{Error, NetworkError, Result}; use capnp::message::{Builder as MsgBuilder, ReaderOptions}; use capnp_futures::serialize as capnp_serialize; use dashmap::{DashMap, Das...
pub fn update_generation(&mut self, new_gen: i64) { if new_gen > *self.generation.lock() { self.server_uris = Arc::new(DashMap::new()); *self.generation.lock() = new_gen; } } } #[derive(Debug, Error)] pub enum MapOutputError { #[error("Shuffle id output #{0} not foun...
random_line_split
map_output_tracker.rs
use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::sync::Arc; use std::time::Duration; use crate::serialized_data_capnp::serialized_data; use crate::{Error, NetworkError, Result}; use capnp::message::{Builder as MsgBuilder, ReaderOptions}; use capnp_futures::serialize as capnp_serialize; use dashmap::{DashMap, Das...
(is_master: bool, master_addr: SocketAddr) -> Self { let output_tracker = MapOutputTracker { is_master, server_uris: Arc::new(DashMap::new()), fetching: Arc::new(DashSet::new()), generation: Arc::new(Mutex::new(0)), master_addr, }; outp...
new
identifier_name
map_output_tracker.rs
use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::sync::Arc; use std::time::Duration; use crate::serialized_data_capnp::serialized_data; use crate::{Error, NetworkError, Result}; use capnp::message::{Builder as MsgBuilder, ReaderOptions}; use capnp_futures::serialize as capnp_serialize; use dashmap::{DashMap, Das...
else { // TODO: error logging } } pub async fn get_server_uris(&self, shuffle_id: usize) -> Result<Vec<String>> { log::debug!( "trying to get uri for shuffle task #{}, current server uris: {:?}", shuffle_id, self.server_uris ); i...
{ if arr.get(map_id).unwrap() == &Some(server_uri) { self.server_uris .get_mut(&shuffle_id) .unwrap() .insert(map_id, None) } self.increment_generation(); }
conditional_block
lib.rs
//! Everything related to meshes. //! //! **TODO**: Everything. #![feature(trivial_bounds)] #![feature(never_type)] #![feature(doc_cfg)] #![feature(proc_macro_hygiene)] #![feature(try_blocks)] #![feature(specialization)] #![feature(associated_type_defaults)] #![feature(associated_type_bounds)] #![feature(array_value_i...
{ Edge, Face, Vertex, } // =========================================================================== // ===== `Sealed` trait // =========================================================================== pub(crate) mod sealed { /// A trait that cannot be implemented outside of this crate. /// ...
MeshElement
identifier_name
lib.rs
//! Everything related to meshes. //! //! **TODO**: Everything. #![feature(trivial_bounds)] #![feature(never_type)] #![feature(doc_cfg)] #![feature(proc_macro_hygiene)] #![feature(try_blocks)] #![feature(specialization)] #![feature(associated_type_defaults)] #![feature(associated_type_bounds)] #![feature(array_value_i...
/// }; /// /// /// #[derive(MemSource)] /// struct MyMesh { /// #[lox(core_mesh)] /// mesh: SharedVertexMesh, /// /// #[lox(vertex_position)] /// positions: DenseMap<VertexHandle, Point3<f32>>, /// } /// ``` /// /// Deriving this trait works very similar to deriving [`MemSink`]. See its /// documentatio...
/// MemSource, VertexHandle, /// cgmath::Point3, /// ds::SharedVertexMesh, /// map::DenseMap,
random_line_split
main.rs
#[macro_use] extern crate log; extern crate simplelog; use futures::future; use futures::future::{BoxFuture, FutureExt}; use reqwest as request; use base64::encode; use dirs::home_dir; use futures::io::SeekFrom; use regex::Regex; use request::header::{HeaderMap, AUTHORIZATION, CONTENT_TYPE, USER_AGENT}; use scraper::...
> String { let mut home_path = home_dir().unwrap(); home_path.push(".sure"); home_path.push(filename); String::from(home_path.to_str().unwrap()) } /// /// /// Definitions and Implementations /// /// /// /// DesiredListing /// #[derive(Debug)] struct DesiredListing { active: bool, interested: bool, mls: String,...
filename: &str) -
identifier_name
main.rs
#[macro_use] extern crate log; extern crate simplelog; use futures::future; use futures::future::{BoxFuture, FutureExt}; use reqwest as request; use base64::encode; use dirs::home_dir; use futures::io::SeekFrom; use regex::Regex; use request::header::{HeaderMap, AUTHORIZATION, CONTENT_TYPE, USER_AGENT}; use scraper::...
io::stdout() .write( format!( "\rdownloading listings {}/{}: [{}>{}]", current, total, "=".repeat(percentage), " ".repeat(50 - percentage), ) .as_bytes(), ) .unwrap(); io::stdout().flush().unwrap(); size += content_length; documents.ins...
(Ok((id, _idx, document, content_length)), _index, remaining) => { current += 1.0; let percentage = (((current / total as f32) * 100.0) / 2.0) as usize;
random_line_split