lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
src/lib.rs
kevinheavey/based58
671fb9c8082c86b8a0997e45a2f3b505182dc21c
use std::error::Error; use bs58::{decode, encode, Alphabet as AlphabetOriginal}; use pyo3::exceptions::PyValueError; use pyo3::prelude::*; use pyo3::types::PyBytes; fn to_py_value_err<T: Error>(err: T) -> PyErr { PyValueError::new_err(err.to_string()) } #[pyclass] #[derive(Debug, Clone)] #[pyo3(text_signature = ...
use std::error::Error; use bs58::{decode, encode, Alphabet as AlphabetOriginal}; use pyo3::exceptions::PyValueError; use pyo3::prelude::*; use pyo3::types::PyBytes; fn to_py_value_err<T: Error>(err: T) -> PyErr { PyValueError::new_err(err.to_string()) } #[pyclass] #[derive(Debug, Clone)] #[pyo3(text_signature = ...
n!(b58decode, m)?)?; m.add_function(wrap_pyfunction!(b58encode, m)?)?; m.add_function(wrap_pyfunction!(b58decode_check, m)?)?; m.add_function(wrap_pyfunction!(b58encode_check, m)?)?; m.add_class::<Alphabet>()?; Ok(()) }
; Ok(byte_vec_to_pybytes(&byte_vec, py)) } #[pyfunction(alphabet = "Alphabet::BITCOIN", expected_ver = "None")] #[pyo3(text_signature = "(val, alphabet, expected_ver = None)")] pub fn b58encode_check<'a>( val: &[u8], alphabet: Alphabet, expected_ver: Option<u8>, py: Python<'a>, ) -> &'a PyBytes { ...
random
[ { "content": "def alphabet(request) -> str:\n", "file_path": "tests/test_encode_decode.py", "rank": 5, "score": 67299.23370169851 }, { "content": "def test_empty_decode_bytes():\n\n data = b58decode(b\"1\")\n", "file_path": "tests/test_encode_decode.py", "rank": 8, "score": 39...
Rust
src/render.rs
kezenator/beam
f8ed74d1d21fffe030274778ef8b7668a61b18e6
use crate::color; use crate::desc::SceneDescription; use crate::math::Scalar; use crate::scene::{SamplingMode, Scene, SceneSampleStats}; use crate::sample::Sampler; use std::time::{Instant, Duration}; use std::thread::JoinHandle; use crossbeam::channel::{Sender}; use itertools::Itertools; use rand::{thread_rng, seq::S...
use crate::color; use crate::desc::SceneDescription; use crate::math::Scalar; use crate::scene::{SamplingMode, Scene, SceneSampleStats}; use crate::sample::Sampler; use std::time::{Instant, Duration}; use std::thread::JoinHandle; use crossbeam::channel::{Sender}; use itertools::Itertools; use rand::{thread_rng, seq::S...
let final_update = RenderUpdate { progress: format!("Completed: {}", stats_to_string(&state)), complete: true, pixels: Vec::new(), }; let _ = sender.send(final_update); } fn render_pass(state: &mut RenderState, step: u32, all_pixels: bool, new_samples_per_pixel: usize, ...
if state.options.illumination_mode == RenderIlluminationMode::Global { let mut completed_samples = 1; for requested_samples in [8, 32, 128, 512, 2048, 8096].iter() { let new_samples = requested_samples - completed_samples; if !render_pass(&mut state, 1, tr...
if_condition
[ { "content": "pub fn generate_scene(desc: &SceneDescription, options: &RenderOptions) -> Scene\n\n{\n\n let mut lighting_region = LightingRegion::new(Aabb::new(Point3::new(-50.0, -50.0, -50.0), Point3::new(50.0, 50.0, 50.0)));\n\n let mut objects = Vec::new();\n\n\n\n // Walls\n\n {\n\n let m...
Rust
src/lib.rs
cognitedata/rocket-enumform
651733851f53fc8d33034e9b1d9fc2ba8623ff87
use std::ops::{Deref, DerefMut}; use std::{error, fmt, io}; use rocket::data::{Data, FromData, Limits, Outcome}; use rocket::error_; use rocket::form::prelude as form; use rocket::http::uri::fmt::{Formatter as UriFormatter, FromUriParam, Query, UriDisplay}; use rocket::http::{ContentType, Status}; use rocket::reques...
use std::ops::{Deref, DerefMut}; use std::{error, fmt, io}; use rocket::data::{Data, FromData, Limits, Outcome}; use rocket::error_; use rocket::form::prelude as form; use rocket::http::uri::fmt::{Formatter as UriFormatter, FromUriParam, Query, UriDisplay}; use rocket::http::{ContentType, Status}; use rocket::reques...
} impl<'r, T: Serialize> Responder<'r, 'static> for UrlEncoded<T> { fn respond_to(self, req: &'r Request<'_>) -> response::Result<'static> { let string = ::serde_urlencoded::to_string(&self.0).map_err(|e| { error_!("UrlEncoding failed to serialize: {:?}", e); Status::InternalServer...
Err(Error::Parse(s, e)) => { error_!("{:?}", e); Outcome::Failure((Status::UnprocessableEntity, Error::Parse(s, e))) } Err(e) => Outcome::Failure((Status::BadRequest, e)), } }
function_block-function_prefix_line
[ { "content": "# Rocket extension to permit enums in application/x-www-form-urlencoded forms\n\n\n\nThis crate is a workaround for [https://github.com/SergioBenitez/Rocket/issues/1937](rocket#1937).\n\n\n\nIt is derived from the included serde_json implementation in rocket.\n\n\n\n```rust\n\n#[derive(Debug, Dese...
Rust
src/duo/symmetric_difference.rs
Kerollmops/setiter
fae9a7f6ec2e31e7c141ea6966e38ca1f863c300
use std::cmp::Ordering; use crate::set::Set; use crate::{SetOperation, Collection}; #[derive(Copy, Clone)] pub struct SymmetricDifference<'a, T: 'a> { a: &'a [T], b: &'a [T], } impl<'a, T> SymmetricDifference<'a, T> { pub fn new(a: &'a Set<T>, b: &'a Set<T>) -> Self { Self { a: a....
use std::cmp::Ordering; use crate::set::Set; use crate::{SetOperation, Collection}; #[derive(Copy, Clone)] pub struct SymmetricDifference<'a, T: 'a> { a: &'a [T], b: &'a [T], } impl<'a, T> SymmetricDifference<'a, T> { pub fn new(a: &'a Set<T>, b: &'a Set<T>) -> Self { Self { a: a....
:black_box(|| symmetric_difference_); }); } #[bench] fn two_slices_big2(bench: &mut Bencher) { let a: Vec<_> = (0..100).collect(); let b: Vec<_> = (51..151).collect(); bench.iter(|| { let symmetric_difference_: SetBuf<i32> = SymmetricDifference { a: &a, b: &b }....
erence(a: Vec<i32>, b: Vec<i32>) -> bool { use std::collections::BTreeSet; use std::iter::FromIterator; let mut a = a; let mut b = b; sort_dedup_vec(&mut a); sort_dedup_vec(&mut b); let x: SetBuf<i32> = SymmetricDifference { a: &a, b...
random
[ { "content": "#[inline]\n\npub fn exponential_search_by_key<T, B, F>(slice: &[T], b: &B, mut f: F) -> Result<usize, usize>\n\nwhere F: FnMut(&T) -> B,\n\n B: Ord\n\n{\n\n exponential_search_by(slice, |k| f(k).cmp(b))\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 0, "score": 202007.04868515...
Rust
crypto-bigint/src/uint/cmp.rs
mikelodder7/utils
c6ce4c2cd028044d0c38f6fcef2e1b03153f76c2
use super::UInt; use crate::limb::{Inner, SignedInner, SignedWide, BIT_SIZE}; use crate::Limb; use core::cmp::Ordering; use subtle::{Choice, ConstantTimeEq, ConstantTimeGreater, ConstantTimeLess}; impl<const LIMBS: usize> UInt<LIMBS> { pub fn is_zero(&self) -> Choice { self.ct_eq...
use super::UInt; use crate::limb::{Inner, SignedInner, SignedWide, BIT_SIZE}; use crate::Limb; use core::cmp::Ordering; use subtle::{Choice, ConstantTimeEq, ConstantTimeGreater, ConstantTimeLess}; impl<const LIMBS: usize> UInt<LIMBS> { pub fn is_zero(&self) -> Choice { self.ct_eq...
#[inline] pub(crate) const fn ct_cmp(&self, rhs: Self) -> SignedInner { let mut gt = 0; let mut lt = 0; let mut i = LIMBS; while i > 0 { let a = self.limbs[i - 1].0 as SignedWide; let b = rhs.limbs[i - 1].0 as SignedWide; ...
i = 0; while i < LIMBS { b |= self.limbs[i].0; i += 1; } Limb::is_nonzero(Limb(b)) }
function_block-function_prefixed
[ { "content": "fn unreachable<S, B: ArrayLength<u8>>(_: &mut S) -> ParBlock<B, U1> {\n\n unreachable!();\n\n}\n", "file_path": "block-buffer/src/buffer.rs", "rank": 0, "score": 160061.70393861388 }, { "content": "/// Write a git-flavoured VLQ value into `buf`.\n\n///\n\n/// Returns the sli...
Rust
src/collision/shapes/chain.rs
Bastacyclop/Rust_Box2D
6ad87a96c9bb33b8d0cc597336d35b64f4faf409
use std::mem; use std::ptr; use std::slice; use wrap::*; use common::math::Vec2; use super::{Shape, EdgeShape}; wrap_shape! { ffi::ChainShape => ChainShape < ffi::ChainShape_as_shape > ffi::Shape_as_chain_shape } impl ChainShape { pub fn new() -> Self { unsafe { ChainShape::from_ffi(ffi::Chai...
use std::mem; use std::ptr; use std::slice; use wrap::*; use common::math::Vec2; use super::{Shape, EdgeShape}; wrap_shape! { ffi::ChainShape => ChainShape < ffi::ChainShape_as_shape > ffi::Shape_as_chain_shape } impl ChainShape { pub fn new() -> Self { unsafe { ChainShape::from_ffi(ffi::Chai...
b fn ChainShape_create_chain(slf: *mut ChainShape, vertices: *const Vec2, count: i32); pub fn ChainShape_get_vertices_const(slf: *const ChainShape) -> *const Vec2; pub fn ChainShape_get_vertex_count(slf: *const ChainShape) -> i32; pub fn ChainShape_get_prev_vertex(slf: *const ChainShape, prev: &...
} } pub fn create_chain(&mut self, vertices: &[Vec2]) { unsafe { ffi::ChainShape_create_chain(self.mut_ptr(), vertices.as_ptr(), vertices.len() as i32) } } pub fn vertices(&self) -> &[Vec2] { unsafe { let vertices = ffi::ChainShape_get_vertices_const(s...
random
[ { "content": "pub fn cross_vs(v: Vec2, s: f32) -> Vec2 {\n\n Vec2 {\n\n x: s * v.y,\n\n y: -s * v.x,\n\n }\n\n}\n\n\n", "file_path": "src/common/math.rs", "rank": 0, "score": 155766.0694704286 }, { "content": "pub fn cross_vv(a: Vec2, b: Vec2) -> f32 {\n\n a.x * b.y - ...
Rust
rafx-api/src/backends/vulkan/internal/framebuffer.rs
DavidVonDerau/rafx
5d42caed4bd7fcb5d32e3e26021669cf60071abd
use crate::backends::vulkan::RafxTextureVulkan; use crate::vulkan::{RafxDeviceContextVulkan, RafxRenderpassVulkan}; use crate::*; use ash::version::DeviceV1_0; use ash::vk; use std::sync::Arc; pub(crate) struct RafxFramebufferVulkanAttachment { pub(crate) texture: RafxTextureVulkan, pub(crate) array_slice: Opt...
use crate::backends::vulkan::RafxTextureVulkan; use crate::vulkan::{RafxDeviceContextVulkan, RafxRenderpassVulkan}; use crate::*; use ash::version::DeviceV1_0; use ash::vk; use std::sync::Arc; pub(crate) struct RafxFramebufferVulkanAttachment { pub(crate) texture: RafxTextureVulkan, pub(crate) array_slice: Opt...
Ok(RafxFramebufferVulkan { inner: Arc::new(inner), }) } }
let inner = RafxFramebufferVulkanInner { device_context: device_context.clone(), width: extents.width, height: extents.height, framebuffer, };
assignment_statement
[ { "content": "pub fn rendering_destroy(resources: &mut Resources) -> RafxResult<()> {\n\n // Destroy these first\n\n {\n\n {\n\n let swapchain_helper = resources.remove::<RafxSwapchainHelper>().unwrap();\n\n let mut asset_manager = resources.get_mut::<AssetManager>().unwrap();...
Rust
rust/optics-base/src/home.rs
aaronwinter/optics-monorepo
82b74a232b87064456bda20ba5f1171bd2b6fe70
use async_trait::async_trait; use color_eyre::Result; use ethers::core::types::H256; use optics_core::{ traits::{ ChainCommunicationError, Common, DoubleUpdate, Home, RawCommittedMessage, State, TxOutcome, }, Message, SignedUpdate, Update, }; use optics_ethereum::EthereumHome; use optics_test::mocks...
use async_trait::async_trait; use color_eyre::Result; use ethers::core::types::H256; use optics_core::{ traits::{ ChainCommunicationError, Common, DoubleUpdate, Home, RawCommittedMessage, State, TxOutcome, }, Message, SignedUpdate, Update, }; use optics_ethereum::EthereumHome; use optics_test::mocks...
async fn committed_root(&self) -> Result<H256, ChainCommunicationError> { match self { Homes::Ethereum(home) => home.committed_root().await, Homes::Mock(mock_home) => mock_home.committed_root().await, Homes::Other(home) => home.committed_root().await, } } ...
async fn state(&self) -> Result<State, ChainCommunicationError> { match self { Homes::Ethereum(home) => home.state().await, Homes::Mock(mock_home) => mock_home.state().await, Homes::Other(home) => home.state().await, } }
function_block-full_function
[ { "content": "/// Compute a root hash from a leaf and a Merkle proof.\n\npub fn merkle_root_from_branch(leaf: H256, branch: &[H256], depth: usize, index: usize) -> H256 {\n\n assert_eq!(branch.len(), depth, \"proof length should equal depth\");\n\n\n\n let mut current = leaf;\n\n\n\n for (i, next) in b...
Rust
src/lib.rs
alexjago/blinkt_spidev
989dfaecb3efa4848a3f2a12987c98b26eaf2bf3
extern crate spidev; use std::{io, result}; use std::io::prelude::*; use std::path::Path; use spidev::{Spidev, SpidevOptions, SpidevTransfer, SPI_MODE_0}; const NUM_PIXELS: usize = 8; const DEVPATH: &'static str = "/dev/spidev0.0"; const DEFAULT_BRIGHTNESS: u8 = 7; #[derive(Debug, Copy, Clone)] struct Pixel { ...
extern crate spidev; use std::{io, result}; use std::io::prelude::*; use std::path::Path; use spidev::{Spidev, SpidevOptions, SpidevTransfer, SPI_MODE_0}; const NUM_PIXELS: usize = 8; const DEVPATH: &'static str = "/dev/spidev0.0"; const DEFAULT_BRIGHTNESS: u8 = 7; #[derive(Debug, Copy, Clone)] struct Pixel { ...
pub fn set_all_pixels_rgbb(&mut self, red: u8, green: u8, blue: u8, brightness: f32) { let brightness: u8 = (31.0 * if brightness > 1.0 { 1.0 } else if brightness < 0.0 { 0.0 } else { brightness }) as u8; for pixe...
pub fn set_all_pixels(&mut self, red: u8, green: u8, blue: u8) { for pixel in &mut self.pixels { pixel.red = red; pixel.green = green; pixel.blue = blue; } }
function_block-full_function
[ { "content": "fn main() {\n\n let mut blinkt = BlinktSpidev::new().unwrap();\n\n let (red, green, blue) = (&mut 255, &mut 0, &mut 0);\n\n\n\n loop {\n\n blinkt.set_all_pixels(*red, *green, *blue);\n\n blinkt.show();\n\n\n\n thread::sleep(Duration::from_millis(250));\n\n\n\n ...
Rust
src/lib.rs
adelhult/koda
a4f2f82b2f7bf1fd3fb3ba0cf83abc8e7292fc82
use regex::Regex; use rlua::{Lua, Value, Error}; use std::collections::HashMap; use std::io::{stdin, stdout, Write}; mod prelude; mod lexer; use prelude::{get_prelude}; use lexer::{Token, lex}; pub fn transpile(code: &str) -> String { let mut next_is_then = false; lex(&code) ...
use regex::Regex; use rlua::{Lua, Value, Error}; use std::collections::HashMap; use std::io::{stdin, stdout, Write}; mod prelude; mod lexer; use prelude::{get_prelude}; use lexer::{Token, lex}; pub fn transpile(code: &str) -> String { let mut next_is_then = false; lex(&code) ...
fn escape_keywords(token: &str) -> String { let keywords = ["and", "break", "do", "else", "elseif", "end", "false", "for", "function", "if", "in", "local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while"]; ...
ation, re) in idents { replaced_code = re.replace_all(&replaced_code, eng_translation).into(); } replaced_code }
function_block-function_prefixed
[ { "content": "/// Lex the code into Tokens\n\npub fn lex(code: &str) -> Vec<Token> {\n\n let lex = Token::lexer(&code);\n\n lex.collect()\n\n}\n\n\n\n#[derive(Logos, Debug, PartialEq)]\n\npub enum Token {\n\n #[token(\"och\")]\n\n And,\n\n #[token(\"bryt\")]\n\n Break,\n\n #[token(\"gör\")]...
Rust
src/emu/event.rs
nbdd0121/r2vm
ec2001f85529c74bce9cdeec93a07a3893adde89
use futures::future::BoxFuture; use futures::task::ArcWake; use parking_lot::{Condvar, Mutex, MutexGuard}; use std::collections::BinaryHeap; use std::future::Future; use std::pin::Pin; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::Arc; use std::task::{Context, Poll, Waker}; use std::time::{...
use futures::future::BoxFuture; use futures::task::ArcWake; use parking_lot::{Condvar, Mutex, MutexGuard}; use std::collections::BinaryHeap; use std::future::Future; use std::pin::Pin; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::Arc; use std::task::{Context, Poll, Waker}; use std::time::{...
pub fn queue(&self, cycle: u64, handler: Box<dyn FnOnce() + Send>) { self.queue_handler(cycle, Handler::Func(handler)); } pub fn queue_time(&self, time: u64, handler: Box<dyn FnOnce() + Send>) { self.queue_handler(time.saturating_mul(100), Handler::Func(handler)); } ...
fn queue_handler(&self, cycle: u64, handler: Handler) { let mut guard = self.events.lock(); guard.push(Entry { time: cycle, handler }); if crate::threaded() { if guard.peek().unwrap().time == cycle { self.condvar.notify_one(); } } els...
function_block-full_function
[ { "content": "/// Walk the page table under SV39. We don't support SV48 at the moment.\n\npub fn walk_page(satp: u64, vpn: u64, mut read_mem: impl FnMut(u64) -> u64) -> PageWalkResult {\n\n // Check if the address is canonical.\n\n if (((vpn << (64 - 27)) as i64) >> (64 - 27 - 12)) as u64 >> 12 != vpn {\n...
Rust
src/ws.rs
andy128k/rust-parser-combinators
9f87600da8bb0ce424e9675a665abe17a46cf447
use crate::parser::{Parser, bytes, Applicator}; use crate::stream::ByteStream; #[derive(Debug)] pub struct Frame { pub fin: bool, pub opcode: u8, pub len: u32, pub mask: Option<[u8; 4]>, pub body: Vec<u8>, } impl Frame { pub fn text(body: &str) -> Frame { Frame { fin: true,...
use crate::parser::{Parser, bytes, Applicator}; use crate::stream::ByteStream; #[derive(Debug)] pub struct Frame { pub fin: bool, pub opcode: u8, pub len: u32, pub mask: Option<[u8; 4]>, pub body: Vec<u8>, } impl Frame { pub fn text(body: &str) -> Frame { Frame { fin: true,...
; stream.put(self.body.as_slice()); let r: &[u8] = stream.as_ref(); r.to_vec() } } fn frame_opts() -> Parser<FrameOpts> { Parser::init(|| ()) .then(bytes(2)) .map(|(_, word)| FrameOpts::new(word)) } pub fn parse_frame(stream: &mut ByteStream) -> Option<Frame> { let ...
if self.body.len() <= 125 { stream.put(&[self.body.len() as u8]); } else { stream.put(&[126u8]); let size = self.body.len() as u16; stream.put(&[(size >> 8) as u8, (size & 255) as u8]); }
if_condition
[]
Rust
graphql_client_codegen/src/codegen.rs
panicbit/graphql-client
b71c0e0cf8988808dab3cd28f5ea831cf9ba4023
use deprecation; use failure; use fragments::GqlFragment; use graphql_parser::query; use operations::Operation; use proc_macro2::TokenStream; use query::QueryContext; use schema; use selection::Selection; pub(crate) fn select_operation(query: &query::Document, struct_name: &str) -> Option<Operation> { let mut oper...
use deprecation; use failure; use fragments::GqlFragment; use graphql_parser::query; use operations::Operation; use proc_macro2::TokenStream; use query::QueryContext; use schema; use selection::Selection; pub(crate) fn select_operation(query: &query::Document, struct_name: &str) -> Option<Operation> { let mut oper...
a); let root_name: String = if let Some(root_name) = opt_root_name { root_name } else { panic!( "operation type '{:?}' not in schema", operation.operation_type ); }; let definition = context .schema ...
function_block-function_prefixed
[ { "content": "fn parse_repo_name(repo_name: &str) -> Result<(&str, &str), failure::Error> {\n\n let mut parts = repo_name.split(\"/\");\n\n match (parts.next(), parts.next()) {\n\n (Some(owner), Some(name)) => Ok((owner, name)),\n\n _ => Err(format_err!(\"wrong format for the repository name...
Rust
src/enums.rs
masahase0117/SlmpClient
7a57293f789f1a667a4ad1f1529b2952e327d8aa
#[derive(Copy, Clone, Debug, Hash)] pub enum SLMPCommand { DeviceRead = 0x0401, DeviceWrite = 0x1401, DeviceReadRandom = 0x0403, DeviceWriteRandom = 0x1402, EntryMonitorDevice = 0x0801, ExecuteMonitor = 0x0802, ReadBlock = 0x0406, WriteBlock = 0x01406, ArrayLabelRead = 0x0...
#[derive(Copy, Clone, Debug, Hash)] pub enum SLMPCommand { DeviceRead = 0x0401, DeviceWrite = 0x1401, DeviceReadRandom = 0x0403, DeviceWriteRandom = 0x1402, EntryMonitorDevice = 0x0801, ExecuteMonitor = 0x0802, ReadBlock = 0x0406, WriteBlock = 0x01406, ArrayLabelRead = 0x0...
pub fn set_timeout(&mut self, timeout: u64) { use TCPorUDP::*; let result = match self { TCP(stream) => stream.set_read_timeout(Some(Duration::from_millis(timeout))), UDP(socket, _) => socket.set_read_timeout(Some(Duration::from_millis(timeout))), ...
b fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { use TCPorUDP::*; match self { TCP(stream) => stream.read(buf), UDP(socket, _) => socket.recv(buf), } }
function_block-function_prefixed
[ { "content": "/// 形名要求に対する応答の処理\n\n/// # 引数\n\n/// * `buf` - 応答内容の入ったバッファ\n\n/// # 返値\n\n/// 形名と形名コード\n\npub fn decode_read_type_name_response(buf: &[u8]) -> (String, u16) {\n\n let mut s = String::new();\n\n for i in 0..16 {\n\n s.push(buf[i] as char);\n\n }\n\n let code = buf[16] as u16 + (...
Rust
src/channels/oneshot.rs
austinjones/postage-rs
90f93e608bb2d04e2ed97f9d34123a60c33cb5ed
use std::fmt; use std::sync::Arc; use super::SendMessage; use crate::{ sink::{PollSend, Sink}, stream::{PollRecv, Stream}, sync::transfer::Transfer, }; use static_assertions::{assert_impl_all, assert_not_impl_all}; pub fn channel<T>() -> (Sender<T>, Receiver<T>) { #[cfg(feature = "debug")] log::...
use std::fmt; use std::sync::Arc; use super::SendMessage; use crate::{ sink::{PollSend, Sink}, stream::{PollRecv, Stream}, sync::transfer::Transfer, }; use static_assertions::{assert_impl_all, assert_not_impl_all}; pub fn channel<T>() -> (Sender<T>, Receiver<T>) { #[cfg(feature = "debug")] log::...
} #[cfg(test)] mod async_std_tests { use async_std::{future::timeout, task::spawn}; use crate::{ sink::Sink, stream::Stream, test::{CHANNEL_TEST_ITERATIONS, TEST_TIMEOUT}, }; use super::channel; #[async_std::test] async fn simple() { for i in 0..CHANNEL_TEST_...
spawn(async move { tx.send(100usize).await }); let msg = timeout(TEST_TIMEOUT, async move { rx.recv().await }) .await .expect("test timeout"); assert_eq!(Some(100usize), msg); } }
function_block-function_prefix_line
[ { "content": "/// Constructs a pair of barrier endpoints, which transmits when the sender is dropped.\n\npub fn channel() -> (Sender, Receiver) {\n\n #[cfg(feature = \"debug\")]\n\n log::error!(\"Creating barrier channel\");\n\n let shared = Arc::new(Shared {\n\n state: Atomic::new(State::Pendin...
Rust
extendr-api/src/wrapper/environment.rs
multimeric/extendr
00fed0d8fce2ca0a3c4bf822f685d0d6ada0a1ae
use super::*; #[derive(Debug, PartialEq, Clone)] pub struct Environment { pub(crate) robj: Robj, } impl Environment { pub fn new_with_parent(parent: Environment) -> Self { Environment::new_with_capacity(parent, 14) } ...
use super::*; #[derive(Debug, PartialEq, Clone)] pub struct Environment { pub(crate) robj: Robj, } impl Environment { pub fn new_with_parent(parent: Environment) -> Self { Environment::new_with_capacity(parent, 14) } ...
} #[allow(clippy::wrong_self_convention)] pub fn from_pairs<NV>(parent: Environment, names_and_values: NV) -> Self where NV: IntoIterator, NV::Item: SymPair, { single_threaded(|| { let dict_len = 29; ...
if capacity <= 5 { new_env(parent, false, 0) } else { new_env(parent, true, capacity as i32 * 2 + 1) }
if_condition
[ { "content": "/// Current srcref, for debuggers\n\npub fn srcref() -> Robj {\n\n unsafe { new_sys(R_Srcref) }\n\n}\n\n\n", "file_path": "extendr-api/src/functions.rs", "rank": 0, "score": 166530.52211683046 }, { "content": "/// NA_STRING as a CHARSXP\n\npub fn na_string() -> Robj {\n\n ...
Rust
zinc-compiler/src/syntax/parser/pattern_match.rs
sunny-g/zinc
302a9ea570ba34e980fdeb313426e7c404c1cf4e
use std::cell::RefCell; use std::rc::Rc; use crate::error::Error; use crate::lexical::stream::TokenStream; use crate::lexical::token::lexeme::literal::Literal as LexicalLiteral; use crate::lexical::token::lexeme::symbol::Symbol; use crate::lexical::token::lexeme::Lexeme; use crate::lexical::token::Token; use crate::...
use std::cell::RefCell; use std::rc::Rc; use crate::error::Error; use crate::lexical::stream::TokenStream; use crate::lexical::token::lexeme::literal::Literal as LexicalLiteral; use crate::lexical::token::lexeme::symbol::Symbol; use crate::lexical::token::lexeme::Lexeme; use crate::lexical::token::Token; use crate::...
} State::PathOperand => { let (expression, next) = TerminalOperandParser::default().parse(stream.clone(), self.next.take())?; self.next = next; self.builder.push_path_element(expression); ...
match crate::syntax::parser::take_or_next(self.next.take(), stream.clone())? { Token { lexeme: Lexeme::Symbol(Symbol::DoubleColon), location, } => { self.builder ...
if_condition
[]
Rust
src/lib.rs
rizsotto/json_compilation_db
95f3a637855508edf39e0f272fe4581cc2be5f31
/*! This crate provides support for reading and writing JSON compilation database files. A compilation database is a set of records which describe the compilation of the source files in a given project. It describes the compiler invocation command to compile a source module to an object file. This database can have m...
/*! This crate provides support for reading and writing JSON compilation database files. A compilation database is a set of records which describe the compilation of the source files in a given project. It describes the compiler invocation command to compile a source module to an object file. This database can have m...
} impl From<io::Error> for Error { fn from(cause: io::Error) -> Self { Error::IoError(cause) } } impl From<serde_json::Error> for Error { fn from(cause: serde_json::Error) -> Self { Error::SyntaxError(cause) } } } mod api { use super::e...
fn source(&self) -> Option<&(dyn error::Error + 'static)> { match *self { Error::IoError(ref cause) => Some(cause), Error::SyntaxError(ref cause) => Some(cause), } }
function_block-full_function
[ { "content": "fn to_command(arguments: &[String]) -> String {\n\n shell_words::join(arguments)\n\n}\n", "file_path": "src/type_ser.rs", "rank": 0, "score": 32418.457574098888 }, { "content": "# JSON Compilation Database\n\n\n\nThis crate provides support for reading and writing JSON compi...
Rust
sys/src/gpu/mod.rs
divanvisagie/nvapi-rs
94ad7d5c4848cc4b185f6221cf2c8687b9eceb51
use status::NvAPI_Status; use handles::NvPhysicalGpuHandle; use types; pub mod cooler; pub mod pstate; pub mod clock; pub mod thermal; pub mod power; pub mod display; nvapi! { pub type EnumPhysicalGPUsFn = extern "C" fn(nvGPUHandle: *mut [NvPhysicalGpuHandle; types::NVAPI_MAX_PHYSICAL_GPUS], pGpuCount: *mut ...
use status::NvAPI_Status; use handles::NvPhysicalGpuHandle; use types; pub mod cooler; pub mod pstate; pub mod clock; pub mod thermal; pub mod power; pub mod display; nvapi! { pub type EnumPhysicalGPUsFn = extern "C" fn(nvGPUHandle: *mut [NvPhysicalGpuHandle; types::NVAPI_MAX_PHYSICAL_GPUS], pGpuCount: *mut ...
known = 0, NV_GPU_RAM_MAKER_SAMSUNG / Samsung = 1, NV_GPU_RAM_MAKER_QIMONDA / Qimonda = 2, NV_GPU_RAM_MAKER_ELPIDA / Elpida = 3, NV_GPU_RAM_MAKER_ETRON / Etron = 4, NV_GPU_RAM_MAKER_NANYA / Nanya = 5, NV_GPU_RAM_MAKER_HYNIX / Hynix = 6, ...
= extern "C" fn(hPhysicalGPU: NvPhysicalGpuHandle, szName: *mut types::NvAPI_ShortString) -> NvAPI_Status; pub unsafe fn NvAPI_GPU_GetFullName; } nvapi! { pub type GPU_GetPhysicalFrameBufferSizeFn = extern "C" fn(hPhysicalGPU: NvPhysicalGpuHandle, pSize: *mut u32) -> NvAPI_Status; pub unsa...
random
[]
Rust
network/src/validator_network/mempool.rs
nonmadden/libra
ea84db439c03fe8f74965896eb53ac2a66bfe537
use crate::{ counters, error::NetworkError, peer_manager::{PeerManagerRequest, PeerManagerRequestSender}, proto::MempoolSyncMsg, validator_network::network_builder::NetworkBuilder, validator_network::{NetworkEvents, NetworkSender}, ProtocolId, }; use channel::{libra_channel, message_queues...
use crate::{ counters, error::NetworkError, peer_manager::{PeerManagerRequest, PeerManagerRequestSender}, proto::MempoolSyncMsg, validator_network::network_builder::NetworkBuilder, validator_network::{NetworkEvents, NetworkSender}, ProtocolId, }; use channel::{libra_channel, message_queues...
erNotification::RecvMessage(peer_id, network_msg), ) .unwrap(); let event = block_on(stream.next()).unwrap().unwrap(); assert_eq!(event, Event::Message((peer_id, mempool_msg))); let f = async { control_notifs_tx .push( ...
(8).unwrap(), None); let mut stream = MempoolNetworkEvents::new(mempool_rx, control_notifs_rx); let peer_id = PeerId::random(); let mempool_msg = MempoolSyncMsg::default(); let network_msg = Message { protocol: ProtocolId::from_static(MEMPOOL_DIRECT_SEND_PROTOCOL), ...
random
[ { "content": "// Generate some random, well-formed, unsigned-varint length-prefixed byte arrays\n\n// for our fuzzer corpus to act as serialized inbound rpc calls.\n\npub fn generate_corpus(gen: &mut ValueGenerator) -> Vec<u8> {\n\n let small_data_strat = vec(any::<u8>(), 0..MAX_SMALL_MSG_BYTES);\n\n let ...
Rust
build.rs
sidit77/InfinityLoop
ea886b95141385ec301a8df398847662394a641e
use std::env; use std::fs; use std::path::Path; use std::io::Write; use anyhow::Result; use glam::Vec2; use std::ops::RangeInclusive; use std::f32::consts::PI; fn main() -> Result<()> { let mesh_path = "meshes.bin"; let mut mesh_file = fs::File::create(Path::new(env::var("OUT_DIR")?.as_str()).join(mesh_path))...
use std::env; use std::fs; use std::path::Path; use std::io::Write; use anyhow::Result; use glam::Vec2; use std::ops::RangeInclusive; use std::f32::consts::PI; fn main() -> Result<()> { let mesh_path = "meshes.bin"; let mut mesh_file = fs::File::create(Path::new(env::var("OUT_DIR")?.as_str()).join(mesh_path))...
fn draw_arc(center: Vec2, radius: f32, angle: RangeInclusive<f32>, thickness: f32, steps: u32) -> Vec<Vec2> { let mut result = Vec::new(); let pos = | i | { if i == steps { *angle.end() } else { angle.start() + (angle.end() - angle.start()) * (i as f32 / steps as f32) ...
for i in 0u32..4 { mesh_file.write_all(bytemuck::bytes_of(&hexagon_corner(0)))?; mesh_file.write_all(bytemuck::bytes_of(&hexagon_corner(i + 1)))?; mesh_file.write_all(bytemuck::bytes_of(&hexagon_corner(i + 2)))?; index += 3; } writeln!(module_file, "pub c...
function_block-function_prefix_line
[ { "content": "#[wasm_bindgen(start)]\n\npub fn main_js() -> Result<(), JsValue> {\n\n #[cfg(debug)]\n\n console_error_panic_hook::set_once();\n\n\n\n let window = web_sys::window().unwrap();\n\n let canvas = get_element::<web_sys::HtmlCanvasElement>(\"canvas\");\n\n let performance = window.perfo...
Rust
src/advert-rust/src/modules/ssp/dsp/medsp/mod.rs
nocai/study
eeed0bd8680da62626732d89efb378029f8abef7
pub mod idea; pub mod plan; pub mod slot; use async_std::task; use std::{cell::RefCell, collections::HashMap}; use log::info; use sqlx::MySqlPool; use crate::{common::{app_state::AppState, config, error::Error}, modules::{ssp::{self, dsp_slot::DspSlot}, weight::{self, Weight}}}; use self::{ idea::Idea, plan:...
pub mod idea; pub mod plan; pub mod slot; use async_std::task; use std::{cell::RefCell, collections::HashMap}; use log::info; use sqlx::MySqlPool; use crate::{common::{app_state::AppState, config, error::Error}, modules::{ssp::{self, dsp_slot::DspSlot}, weight::{self, Weight}}}; use self::{ idea::Idea, plan:...
fn group_by_bid_type( &self, vec: &[PlanIdeaIDs], ) -> (Vec<PlanIdeaIDs>, Vec<PlanIdeaIDs>, Vec<PlanIdeaIDs>) { let mut cpt = Vec::new(); let mut cpm = Vec::new(); let mut cpc = Vec::new(); for pii in vec { match pii.plan.bid_type { ...
async fn do_dsp2( &self, group_name: &str, group: &[PlanIdeaIDs], ) -> Result<Option<Idea>, Error> { info!("group: {}", group_name); if group.is_empty() { info!("group is empty! return"); return Ok(None); } let plan_ideaids = weight::r...
function_block-full_function
[ { "content": "fn mysqlpool(url: &str) -> Pool<MySql> {\n\n let pool = MySqlPoolOptions::new().max_connections(1).connect(url);\n\n\n\n block_on(pool).unwrap()\n\n}\n", "file_path": "src/advert-monitor-rust/src/database/mod.rs", "rank": 1, "score": 200750.73966448335 }, { "content": "pu...
Rust
todo_finder_lib/src/parser/issue.rs
schell/todo_finder
4f66b82aba275c25a77b5c49c183da4f971fa372
use nom::{bytes::complete as bytes, character::complete as character, combinator, multi, IResult}; use std::collections::HashMap; use super::{take_to_eol, IssueBody}; pub fn src_location0(i: &str) -> IResult<&str, (&str, usize)> { let (i, _) = bytes::tag("Located in ")(i)?; let dub_quote = character::char('"...
use nom::{bytes::complete as bytes, character::complete as character, combinator, multi, IResult}; use std::collections::HashMap; use super::{take_to_eol, IssueBody}; pub fn src_location0(i: &str) -> IResult<&str, (&str, usize)> {
pub fn repo_from_github_link(i: &str) -> IResult<&str, (&str, &str)> { let (i, user) = bytes::take_till(|c| c == '/')(i)?; let (i, _) = character::char('/')(i)?; let (i, repo) = bytes::take_till(|c| c == '/')(i)?; Ok((i, (user, repo))) } pub fn span_from_github_link(i: &str) -> IResult<&str, (usize, ...
let (i, _) = bytes::tag("Located in ")(i)?; let dub_quote = character::char('"'); let (i, _) = dub_quote(i)?; let (i, file) = bytes::take_till(|c| c == '"')(i)?; let (i, _) = dub_quote(i)?; let (i, _) = bytes::tag(" on line ")(i)?; let (i, ln_str) = character::digit1(i)?; let n = ln_str ...
function_block-function_prefix_line
[ { "content": "pub fn parse_rg_line(i: &str) -> IResult<&str, usize> {\n\n let (i, lnum) = character::digit1(i)?;\n\n let (i, _) = character::char(':')(i)?;\n\n let (i, _) = take_to_eol(i)?;\n\n let lnum: usize = lnum.parse().expect(\"line number is not a number\");\n\n Ok((i, lnum))\n\n}\n\n\n\n\...
Rust
crawl/src/bin/rudra-runner.rs
GeekMasher/Rudra
bdd7b0981f0c3456fe48160d32f61e4f7f990d45
use std::env; use std::ffi::OsStr; use std::fs::OpenOptions; use std::io::Write; use std::path::PathBuf; use log::*; use rayon::prelude::*; use structopt::{clap::arg_enum, StructOpt}; use crawl::error::Result; use crawl::krate::Crate; use crawl::utils::*; use crawl::{CampaignDir, RudraCacheDir, RudraHomeDir}; arg_en...
use std::env; use std::ffi::OsStr; use std::fs::OpenOptions; use std::io::Write; use std::path::PathBuf; use log::*; use rayon::prelude::*; use structopt::{clap::arg_enum, StructOpt}; use crawl::error::Result; use crawl::krate::Crate; use crawl::utils::*; use crawl::{CampaignDir, RudraCacheDir, RudraHomeDir}; arg_en...
}) .collect(); match opt.select { Selection::First => { crate_list.sort_by_key(|krate| krate.0.name().to_owned()); } Selection::Top => { crate_list .sort_by_key(|krate| std::u64::MAX - krate.0.latest_version_record().downloads); ...
match rudra_cache_dir.fetch_latest_version(&krate) { Ok(path) => Some((krate, path)), Err(e) => { warn!("{}: {}", krate.latest_version_tag(), &e); None } }
if_condition
[ { "content": "pub fn setup_logging(verbosity: Verbosity) -> Result<(), fern::InitError> {\n\n let mut base_config = fern::Dispatch::new();\n\n\n\n base_config = match verbosity {\n\n Verbosity::Normal => base_config.level(LevelFilter::Info),\n\n Verbosity::Verbose => base_config.level(LevelF...
Rust
src/server/conn.rs
Caoming/tikv
7c25c38965692ccfc17d175fbd529d64c6695e13
use std::cmp; use std::io::Read; use mio::{Token, EventLoop, EventSet, PollOpt}; use mio::tcp::TcpStream; use protobuf::Message as PbMessage; use kvproto::msgpb::Message; use kvproto::raft_serverpb::RaftSnapshotData; use super::{Result, ConnData}; use super::server::Server; use util::codec::rpc; use super::transpor...
use std::cmp; use std::io::Read; use mio::{Token, EventLoop, EventSet, PollOpt}; use mio::tcp::TcpStream; use protobuf::Message as PbMessage; use kvproto::msgpb::Message; use kvproto::raft_serverpb::RaftSnapshotData; use super::{Result, ConnData}; use super::server::Server; use util::codec::rpc; use super::transpor...
t_message().get_snapshot().get_data())); self.expect_size = snap_data.get_file_size() as usize; let expect_cap = cmp::min(SNAPSHOT_PAYLOAD_BUF, self.expect_size); self.recv_buffer.as_mut().unwrap().ensure(expect_cap); let register_task = SnapTask::Register(s...
send_buffer: PipeBuffer, recv_buffer: Option<PipeBuffer>, pub buffer_shrink_threshold: usize, } impl Conn { pub fn new(sock: TcpStream, token: Token, store_id: Option<u64>, snap_scheduler: Scheduler<SnapTask>) -> Conn { Conn { ...
random
[ { "content": "pub trait Snapshot: Send {\n\n fn get(&self, key: &Key) -> Result<Option<Value>>;\n\n fn get_cf(&self, cf: CfName, key: &Key) -> Result<Option<Value>>;\n\n #[allow(needless_lifetimes)]\n\n fn iter<'a>(&'a self,\n\n upper_bound: Option<&[u8]>,\n\n fill_cach...
Rust
boards/wio_terminal/src/storage.rs
theatrus/atsamd
8c4035668064609ff1561e32e17e92165cb70187
#[rustfmt::skip] use atsamd_hal::clock::{GenericClockController, Sercom6CoreClock}; use atsamd_hal::gpio::{ Floating, Input, Output, Pa10, Pa11, Pa8, Pa9, Pb10, Pb11, Pc16, Pc17, Pc18, Pc19, Pd21, PfC, Port, PushPull, }; use atsamd_hal::hal::spi; use atsamd_hal::prelude::*; use atsamd_hal::qspi; use atsamd_hal:...
#[rustfmt::skip] use atsamd_hal::clock::{GenericClockController, Sercom6CoreClock}; use atsamd_hal::gpio::{ Floating, Input, Output, Pa10, Pa11, Pa8, Pa9, Pb10, Pb11, Pc16, Pc17, Pc18, Pc19, Pd21, PfC, Port, PushPull, }; use atsamd_hal::hal::spi; use atsamd_hal::prelude::*; use atsamd_hal::qspi; use atsamd_hal:...
}
SDCardController { cont: embedded_sdmmc::Controller::new(SdMmcSpi::new(spi, cs), ts), sercom6_clk, }, self.det, )) }
function_block-function_prefix_line
[]
Rust
arcon/arcon_state/src/backend/ops.rs
arxra/arcon
bfaa73394f9a1d0261bfd4e6eda5335e9aba9e42
use crate::{ data::{Key, Metakey, Value}, error::*, handles::BoxedIteratorOfResult, Aggregator, AggregatorState, Handle, MapState, Reducer, ReducerState, ValueState, VecState, }; pub trait ValueOps { fn value_clear<T: Value, IK: Metakey, N: Metakey>( &self, handle: &Handle<ValueStat...
use crate::{ data::{Key, Metakey, Value}, error::*, handles::BoxedIteratorOfResult, Aggregator, AggregatorState, Handle, MapState, Reducer,
n map_get<K: Key, V: Value, IK: Metakey, N: Metakey>( &self, handle: &Handle<MapState<K, V>, IK, N>, key: &K, ) -> Result<Option<V>>; fn map_fast_insert<K: Key, V: Value, IK: Metakey, N: Metakey>( &self, handle: &Handle<MapState<K, V>, IK, N>, key: K, val...
ReducerState, ValueState, VecState, }; pub trait ValueOps { fn value_clear<T: Value, IK: Metakey, N: Metakey>( &self, handle: &Handle<ValueState<T>, IK, N>, ) -> Result<()>; fn value_get<T: Value, IK: Metakey, N: Metakey>( &self, handle: &Handle<ValueState<T>, IK, N>, )...
random
[]
Rust
src/ubig/shl.rs
gvissers/babs
21cf8611e4cb37dcfe945454cadec9254ccb066d
use crate::digit::Digit; pub fn shl_carry_assign_within_digit<T>(nr: &mut [T], shift: usize, carry: T) -> T where T: Digit { if shift == 0 { T::zero() } else { nr.iter_mut().fold(carry, |carry, d| d.shl_carry_assign(shift, carry)) } } #[cfg(test)] mod tests { use super::*...
use crate::digit::Digit; pub fn shl_carry_assign_within_digit<T>(nr: &mut [T], shift: usize, carry: T) -> T where T: Digit { if shift == 0 { T::zero() } else { nr.iter_mut().fold(carry, |carry, d| d.shl_carry_assign(shift, carry)) } } #[cfg(test)] mod tests { use super::*...
9440c93ffc)]); assert_eq!(carry, BinaryDigit(0)); let mut n = [BinaryDigit(0x7ff842defad35212_u64), BinaryDigit(0x187288192)]; let carry = shl_carry_assign_within_digit(&mut n, 52, BinaryDigit(0x8922017fff)); assert_eq!(n, [BinaryDigit(0x2120008922017fff), BinaryDigit(0x1927ff842defad35...
BinaryDigit(0x0672), BinaryDigit(0xdefe), BinaryDigit(0x16fa), BinaryDigit(0x4ad4), BinaryDigit(0x61c1) ]; let carry = shl_carry_assign_within_digit(&mut n, 15, BinaryDigit(0x7fff)); assert_eq!(n, [ BinaryDigit(0x7fff), ...
function_block-random_span
[ { "content": "/// Shift the number represented by the digits in `nr` right by `shift` bits, and whift in `carry`\n\n/// as the most significant bits. The carry `carry` must fit in `shift` bits, which in turn must be\n\n/// smaller than the bit width of the digit, i.e. `carry` < 2<sup>`shift`</sup> < `b`. Retur...
Rust
src/gl/context.rs
nstoddard/gl-wrapper
a6d6567807dd789c7d6b4fcfded81c257dc0d3e9
use glow::HasContext; use std::cell::RefCell; use std::rc::Rc; #[cfg(target_arch = "wasm32")] use wasm_bindgen::JsCast; #[cfg(target_arch = "wasm32")] use web_sys::{window, HtmlCanvasElement, WebGl2RenderingContext, WebGlContextAttributes}; use super::framebuffer::*; use super::mesh::*; use super::program::*; use supe...
use glow::HasContext; use std::cell::RefCell; use std::rc::Rc; #[cfg(target_arch = "wasm32")] use wasm_bindgen::JsCast; #[cfg(target_arch = "wasm32")] use web_sys::{window, HtmlCanvasElement, WebGl2RenderingContext, WebGlContextAttributes}; use super::framebuffer::*; use super::mesh::*; use super::program::*; use supe...
glow::Context, debug_context: bool) -> Self { unsafe { context.enable(glow::BLEND); context.blend_func(glow::ONE, glow::ONE_MINUS_SRC_ALPHA); context.pixel_store_i32(glow::UNPACK_ALIGNMENT, 1); let instanced_vbo = context.create_buffer().unwrap(); co...
nt .get_element_by_id(canvas_id) .expect("Unable to find canvas element") .dyn_into::<HtmlCanvasElement>() .unwrap(); let context = glow::Context::from_webgl2_context( canvas .get_context_with_context_options( "webgl...
random
[ { "content": "fn set_window_hints(glfw: &mut Glfw, debug_context: bool) {\n\n glfw.window_hint(glfw::WindowHint::Visible(false));\n\n glfw.window_hint(glfw::WindowHint::OpenGlDebugContext(debug_context));\n\n glfw.window_hint(glfw::WindowHint::Samples(Some(4))); // TODO: make this configurable\n\n g...
Rust
examples/3_render_to_texture/src/lib.rs
RSSchermer/web_glitz.rs
a2e26ef0156705f0b5ac7707c4fc24a4a994d84b
#![feature(const_fn_trait_bound, const_ptr_offset_from)] use futures::FutureExt; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use wasm_bindgen_futures::spawn_local; use web_sys::{window, HtmlCanvasElement}; use web_glitz::buffer::{Buffer, UsageHint}; use web_glitz::image::format::RGBA8; use web_glitz::i...
#![feature(const_fn_trait_bound, const_ptr_offset_from)] use futures::FutureExt; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use wasm_bindgen_futures::spawn_local; use web_sys::{window, HtmlCanvasElement}; use web_glitz::buffer::{Buffer, UsageHint}; use web_glitz::image::format::RGBA8; use web_glitz::i...
pub fn start() { let document = window().unwrap().document().unwrap(); let canvas: HtmlCanvasElement = document .get_element_by_id("canvas") .unwrap() .dyn_into() .unwrap(); let (context, mut default_render_target) = unsafe { single_threaded::init(&canvas, &ContextO...
function_block-full_function
[ { "content": "struct TextureDropCommand {\n\n id: JsId,\n\n}\n\n\n\nunsafe impl GpuTask<Connection> for TextureDropCommand {\n\n type Output = ();\n\n\n\n fn context_id(&self) -> ContextId {\n\n ContextId::Any\n\n }\n\n\n\n fn progress(&mut self, connection: &mut Connection) -> Progress<Se...
Rust
src/frontend/gui/overlay/tabnavigator.rs
bcully/wezterm
ea401e1f58ca5a088ac5d5e1d7963f36269afb76
use crate::mux::tab::TabId; use crate::mux::window::WindowId; use crate::mux::Mux; use crate::termwiztermtab::TermWizTerminal; use anyhow::anyhow; use termwiz::cell::{AttributeChange, CellAttributes}; use termwiz::color::ColorAttribute; use termwiz::input::{InputEvent, KeyCode, KeyEvent, MouseButtons, MouseEvent}; use ...
use crate::mux::tab::TabId; use crate::mux::window::WindowId; use crate::mux::Mux; use crate::termwiztermtab::TermWizTerminal; use anyhow::anyhow; use termwiz::cell::{AttributeChange, CellAttributes}; use termwiz::color::ColorAttribute; use termwiz::input::{InputEvent, KeyCode, KeyEvent, MouseButtons, MouseEvent}; use ...
} while let Ok(Some(event)) = term.poll_input(None) { match event { InputEvent::Key(KeyEvent { key: KeyCode::Char('k'), .. }) | InputEvent::Key(KeyEvent { key: KeyCode::UpArrow, .. }) => { ...
if idx >= tab_list.len() { false } else { promise::spawn::spawn_into_main_thread(async move { let mux = Mux::get().unwrap(); let mut window = mux .get_window_mut(mux_window_id) .ok_or_else(|| anyhow!("no such window"...
if_condition
[ { "content": "pub fn alloc_tab_id() -> TabId {\n\n TAB_ID.fetch_add(1, ::std::sync::atomic::Ordering::Relaxed)\n\n}\n\n\n\nconst PASTE_CHUNK_SIZE: usize = 1024;\n\n\n", "file_path": "src/mux/tab.rs", "rank": 0, "score": 279346.4800981285 }, { "content": "pub fn use_ime(enable: bool) {\n\n...
Rust
tique/examples/conditional_collector_tutorial.rs
caio/cantine
a66eaee1fd6c690339065ca0a31e3b3c627ddb95
use std::{cmp::Ordering, ops::Neg}; use tantivy::{ collector::TopDocs, fastfield::FastFieldReader, query::AllQuery, schema::{SchemaBuilder, Value, FAST, STORED}, Document, Index, Result, SegmentReader, }; use tique::conditional_collector::{Ascending, Descending, TopCollector}; pub fn main() -> Re...
use std::{cmp::Ordering, ops::Neg}; use tantivy::{ collector::TopDocs, fastfield::FastFieldReader, query::AllQuery, schema::{SchemaBuilder, Value, FAST, STORED}, Document, Index, Result, SegmentReader, }; use tique::conditional_collector::{Ascending, Descending, TopCollector}; pub fn main() -> Re...
ctor::<f64, Ascending, _>::new(3, true).top_fast_field(rank_field); let top_ids_collector = TopCollector::<u64, Descending, _>::new(3, true).top_fast_field(id_field); let (min_rank, top_ids) = searcher.search(&AllQuery, &(min_rank_collector, top_ids_collector))?; assert_eq!( vec![...
tique_next_collector, tique_next_collector_via_tantivy, ), )?; assert_eq!(tique_next.items, tique_same_next.items); assert_eq!(tantivy_until_next[PAGE_SIZE..], tique_next.items[..]); let min_rank_collector = TopColle
random
[ { "content": "// Source: Copy-pasta from tantivy::query::bm25::idf\n\nfn idf(doc_freq: u64, doc_count: u64) -> f32 {\n\n let x = ((doc_count - doc_freq) as f32 + 0.5) / (doc_freq as f32 + 0.5);\n\n (1f32 + x).ln()\n\n}\n\n\n\n/// TopTerms extracts the most relevant Keywords from your index\n\npub struct T...
Rust
sqlx-core/src/any/connection/executor.rs
JCapucho/sqlx
a31bd17f360c173c7814ae0e071ea10ce52e7a84
use crate::any::connection::AnyConnectionKind; use crate::any::{ Any, AnyColumn, AnyConnection, AnyQueryResult, AnyRow, AnyStatement, AnyTypeInfo, }; use crate::database::Database; use crate::describe::Describe; use crate::error::Error; use crate::executor::{Execute, Executor}; use either::Either; use futures_core:...
use crate::any::connection::AnyConnectionKind; use crate::any::{ Any, AnyColumn, AnyConnection, AnyQueryResult, AnyRow, AnyStatement, AnyTypeInfo, }; use crate::database::Database; use crate::describe::Describe; use crate::error::Error; use crate::executor::{Execute, Executor}; use either::Either; use futures_core:...
sql(conn) => conn.describe(sql).await.map(map_describe)?, }) }) } } fn map_describe<DB: Database>(info: Describe<DB>) -> Describe<Any> where AnyTypeInfo: From<DB::TypeInfo>, AnyColumn: From<DB::Column>, { let parameters = match info.parameters { None => None, Some(Ei...
ync move { Ok(match &mut self.0 { #[cfg(feature = "postgres")] AnyConnectionKind::Postgres(conn) => conn.describe(sql).await.map(map_describe)?, #[cfg(feature = "mysql")] AnyConnectionKind::MySql(conn) => conn.describe(sql).await.map(map_descr...
function_block-random_span
[ { "content": "/// Make a SQL query, with the given arguments.\n\npub fn query_with<'q, DB, A>(sql: &'q str, arguments: A) -> Query<'q, DB, A>\n\nwhere\n\n DB: Database,\n\n A: IntoArguments<'q, DB>,\n\n{\n\n Query {\n\n database: PhantomData,\n\n arguments: Some(arguments),\n\n sta...
Rust
core/src/xml/document.rs
davidar/ruffle
4fe5fc44a6b55bcd79f79269b6ae0230e8ca2d77
use crate::avm1::object::xml_idmap_object::XMLIDMapObject; use crate::avm1::Object; use crate::xml::{Error, ParseError, XMLName, XMLNode}; use gc_arena::{Collect, GcCell, MutationContext}; use quick_xml::events::{BytesDecl, Event}; use quick_xml::{Error as QXError, Writer}; use std::collections::{BTreeMap, HashSet}; ...
use crate::avm1::object::xml_idmap_object::XMLIDMapObject; use crate::avm1::Object; use crate::xml::{Error, ParseError, XMLName, XMLNode}; use gc_arena::{Collect, GcCell, MutationContext}; use quick_xml::events::{BytesDecl, Event}; use quick_xml::{Error as QXError, Writer}; use std::collections::{BTreeMap, HashSet}; ...
pub fn idmap_script_object(&mut self, gc_context: MutationContext<'gc, '_>) -> Object<'gc> { let mut object = self.0.read().idmap_script_object; if object.is_none() { object = Some(XMLIDMapObject::from_xml_document(gc_context, *self)); self.0.write(gc_context).idm...
s()), ); writer.write_event(Event::Decl(bd))?; Ok(Some(String::from_utf8(result)?)) } else { Ok(None) } }
function_block-function_prefixed
[ { "content": "pub fn root_error_handler<'gc>(activation: &mut Activation<'_, 'gc, '_>, error: Error<'gc>) {\n\n if let Error::ThrownValue(error) = &error {\n\n let message = error\n\n .coerce_to_string(activation)\n\n .unwrap_or_else(|_| \"undefined\".into());\n\n activati...
Rust
vm/src/op/math.rs
dalloriam/slang
1f96ecfe69c8ba8084c8044bd479637503961988
use crate::VM; #[inline] pub fn add(reg_src_a: u8, reg_src_b: u8, reg_dst: u8, vm: &mut VM) { let res = vm.registers()[reg_src_a as usize] + vm.registers()[reg_src_b as usize]; log::trace!( "add ${}/{:#06x} ${}/{:#06x} => ${}/{:#06x}", reg_src_a, vm.registers()[reg_src_a as usize], ...
use crate::VM; #[inline] pub fn add(reg_src_a: u8, reg_src_b: u8, reg_dst: u8, vm: &mut VM) { let res = vm.registers()[reg_src_a as usize] + vm.registers()[reg_src_b as usize]; log::trace!( "add ${}/{:#06x} ${}/{:#06x} => ${}/{:#06x}", reg_src_a, vm.registers()[reg_src_a as usize], ...
#[inline] pub fn mul(reg_src_a: u8, reg_src_b: u8, reg_dst: u8, vm: &mut VM) { let res = vm.registers()[reg_src_a as usize] * vm.registers()[reg_src_b as usize]; log::trace!( "mul ${}/{:#06x} ${}/{:#06x} => ${}/{:#06x}", reg_src_a, vm.registers()[reg_src_a as usize], reg_src_b,...
pub fn sub(reg_src_a: u8, reg_src_b: u8, reg_dst: u8, vm: &mut VM) { let res = vm.registers()[reg_src_a as usize] - vm.registers()[reg_src_b as usize]; log::trace!( "sub ${}/{:#06x} ${}/{:#06x} => ${}/{:#06x}", reg_src_a, vm.registers()[reg_src_a as usize], reg_src_b, vm....
function_block-full_function
[ { "content": "#[inline]\n\npub fn not(register: u8, vm: &mut VM) {\n\n let val = vm.registers()[register as usize];\n\n vm.registers_mut()[register as usize] = !val;\n\n log::trace!(\"not ${}/{:#06x} => {:#06x}\", register, val, !val);\n\n}\n\n\n", "file_path": "vm/src/op/bitwise.rs", "rank": 4...
Rust
gdk4/src/auto/popup_layout.rs
YaLTeR/gtk4-rs
a49bfe4b29c85cc8cc5c1a22f8c64b5835072d89
use crate::AnchorHints; use crate::Gravity; use crate::Rectangle; use glib::translate::*; glib::glib_wrapper! { #[derive(Debug, PartialOrd, Ord, Hash)] pub struct PopupLayout(Shared<ffi::GdkPopupLayout>); match fn { ref => |ptr| ffi::gdk_popup_layout_ref(ptr), unref => |ptr| ffi::gdk_pop...
use crate::AnchorHints; use crate::Gravity; use crate::Rectangle; use glib::translate::*; glib::glib_wrapper! { #[derive(Debug, PartialOrd, Ord, Hash)] pub struct PopupLayout(Shared<ffi::GdkPopupLayout>); match fn { ref => |ptr| ffi::gdk_popup_layout_ref(ptr), unref => |ptr| ffi::gdk_pop...
#[doc(alias = "gdk_popup_layout_get_anchor_rect")] pub fn get_anchor_rect(&self) -> Option<Rectangle> { unsafe { from_glib_none(ffi::gdk_popup_layout_get_anchor_rect(self.to_glib_none().0)) } } #[doc(alias = "gdk_popup_layout_get_rect_anchor")] pub fn get_rect_anchor(&self) -> Gravity { ...
pub fn get_anchor_hints(&self) -> AnchorHints { unsafe { from_glib(ffi::gdk_popup_layout_get_anchor_hints( self.to_glib_none().0, )) } }
function_block-function_prefix_line
[ { "content": "#[inline]\n\npub fn is_initialized() -> bool {\n\n skip_assert_initialized!();\n\n INITIALIZED.load(Ordering::Acquire)\n\n}\n\n\n\n/// Returns `true` if GTK has been initialized and this is the main thread.\n", "file_path": "gtk4/src/rt.rs", "rank": 0, "score": 232156.2541108307 ...
Rust
rs/crypto/src/tls_stub/rustls/node_cert_verifier/tests.rs
3cL1p5e7/ic
2b6011291d900454cedcf86ec41c8c1994fdf7d9
use crate::tls_stub::rustls::node_cert_verifier::NodeClientCertVerifier; use crate::tls_stub::rustls::node_cert_verifier::NodeServerCertVerifier; use ic_base_types::NodeId; use ic_crypto_test_utils::tls::registry::{TlsRegistry, REG_V1}; use ic_crypto_test_utils::tls::x509_certificates::{x509_public_key_cert, CertWithPr...
use crate::tls_stub::rustls::node_cert_verifier::NodeClientCertVerifier; use crate::tls_stub::rustls::node_cert_verifier::NodeServerCertVerifier; use ic_base_types::NodeId; use ic_crypto_test_utils::tls::registry::{TlsRegistry, REG_V1}; use ic_crypto_test_utils::tls::x509_certificates::{x509_public_key_cert, CertWithPr...
The peer certificate is not trusted since it differs from the registry certificate. \ NodeId of presented cert: 3jo2y-lqbaa-aaaaa-aaaap-2ai".to_string(), )) ); } #[test] fn should_return_error_if_presented_cert_node_id_cannot_be_parsed() { let cert_with_no_node_i...
te with node ID 32uhy-eydaa-aaaaa-aaaap-2ai is not allowed. \ Allowed node IDs: Some({3jo2y-lqbaa-aaaaa-aaaap-2ai, gfvbo-licaa-aaaaa-aaaap-2ai})" .to_string(), )) ); } #[test] fn should_return_error_if_node_id_allowed_but_cert_does_not_match_registry_...
random
[]
Rust
src/rust/src/programs/cube.rs
roberts-ivanovs/asteroid-wasm
c853befd8487f8d41af2bc1273a09e9efa811f45
pub mod plane; pub mod point; use crate::CanvasData; use crate::input::UserInput; use crate::programs::box_2d::AttributeLocations; use crate::programs::box_2d::UniformLocations; use crate::programs::colors::SingleColor; use crate::programs::cube::plane::Plane2D; use crate::transform::Transform; use crate::{utils::conso...
pub mod plane; pub mod point; use crate::CanvasData; use crate::input::UserInput; use crate::programs::box_2d::AttributeLocations; use crate::programs::box_2d::UniformLocations; use crate::programs::colors::SingleColor; use crate::programs::cube::plane::Plane2D; use crate::transform::Transform; use crate::{utils::conso...
} impl RenderObjectTrait for Cube { fn new(gl: &GL, program: WebGlProgram, transform: Transform) -> Self { let attribute_locations = AttributeLocations { vertex_position: gl.get_attrib_location(&program, "aVertexPosition"), vertex_color: gl.get_attrib_location(&program, "aVertexCol...
let vert_array = js_sys::Float32Array::view(&vertices); gl.buffer_data_with_array_buffer_view(GL::ARRAY_BUFFER, &vert_array, GL::STATIC_DRAW); } let color_buffer = gl.create_buffer().unwrap(); gl.bind_buffer(GL::ARRAY_BUFFER, Some(&color_buffer)); unsafe { let m...
function_block-function_prefix_line
[ { "content": "pub fn link_program(gl: &GL, vert_source: &str, frag_source: &str) -> Result<WebGlProgram, String> {\n\n console_log(\"Compilign shader\");\n\n let vertex_shader = compile_shader(gl, GL::VERTEX_SHADER, vert_source).unwrap();\n\n console_log(\"Compilign shader\");\n\n let fragment_shade...
Rust
src/prng/ctrl.rs
david-sawatzke/xmc1100-rs
d8aaaf4cdcdde32a2b8f62f26fad9506196104b9
#[doc = "Reader of register CTRL"] pub type R = crate::R<u16, super::CTRL>; #[doc = "Writer for register CTRL"] pub type W = crate::W<u16, super::CTRL>; #[doc = "Register CTRL `reset()`'s with value 0"] impl crate::ResetValue for super::CTRL { type Type = u16; #[inline(always)] fn reset_value() -> Self::Typ...
#[doc = "Reader of register CTRL"] pub type R = crate::R<u16, super::CTRL>; #[doc = "Writer for register CTRL"] pub type W = crate::W<u16, super::CTRL>; #[doc = "Register CTRL `reset()`'s with value 0"] impl crate::ResetValue for super::CTRL { type Type = u16; #[inline(always)] fn reset_value() -> Self::Typ...
alue1(&self) -> bool { *self == RDBS_A::VALUE1 } #[doc = "Checks if the value of the field is `VALUE2`"] #[inline(always)] pub fn is_value2(&self) -> bool { *self == RDBS_A::VALUE2 } #[doc = "Checks if the value of the field is `VALUE3`"] #[inline(always)] pub fn is_value...
bool { *self == KLD_A::VALUE2 } } #[doc = "Write proxy for field `KLD`"] pub struct KLD_W<'a> { w: &'a mut W, } impl<'a> KLD_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: KLD_A) -> &'a mut W { { self.bit(variant.into()) ...
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
runtime/src/ancestors.rs
zkblock/solana
dd13a31a5a6e9dc52b87137ee2dc60ecb9a06f1b
use solana_sdk::clock::Slot; use std::collections::HashMap; pub type AncestorsForSerialization = HashMap<Slot, usize>; #[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize, AbiExample)] pub struct Ancestors { min: Slot, slots: Vec<Option<usize>>, count: usize, max: Slot, large_range_s...
use solana_sdk::clock::Slot; use std::collections::HashMap; pub type AncestorsForSerialization = HashMap<Slot, usize>; #[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize, AbiExample)] pub struct Ancestors { min: Slot, slots: Vec<Option<usize>>, count: usize, max: Slot, large_range_s...
}
time2.stop(); info!( "{}, {}, {}", time.as_ms(), time2.as_ms(), time.as_ns() / time2.as_ns() ); assert_eq!(count, count2); } }
function_block-function_prefix_line
[ { "content": "pub fn recv_from(obj: &mut Packets, socket: &UdpSocket, max_wait_ms: u64) -> Result<usize> {\n\n let mut i = 0;\n\n //DOCUMENTED SIDE-EFFECT\n\n //Performance out of the IO without poll\n\n // * block on the socket until it's readable\n\n // * set the socket to non blocking\n\n ...
Rust
tests/if.rs
johan-smits/grass
68d3a0f8431d2a7b85b177ef478a8a3b4a6b3cc5
#[macro_use] mod macros; test!( if_toplevel_true, "@if true {\n a {\n color: foo;\n}\n}\n", "a {\n color: foo;\n}\n" ); test!( if_inner_true, "a {\n @if true {\n color: foo;\n}\n}\n", "a {\n color: foo;\n}\n" ); test!( if_toplevel_false, "@if false {\n a {\n color: foo;\n}...
#[macro_use] mod macros; test!( if_toplevel_true, "@if true {\n a {\n color: foo;\n}\n}\n", "a {\n color: foo;\n}\n" ); test!( if_inner_true, "a {\n @if true {\n color: foo;\n}\n}\n", "a {\n color: foo;\n}\n" ); test!( if_toplevel_false, "@if false {\n a {\n color: foo;\n}...
, "@if foo {", "Error: expected \"}\"." ); error!( first_condition_error, "@if 1 + 1 =s {\n}", "Error: expected \"=\"." ); test!( conditions_evaluated_lazily, "$p: null; @if $p==null {} @else if not comparable($p, 0) {}", "" ); test!( at_rule_inside_ruleset, "@mixin foo {\n co...
{\n color: bar;\n}\n" ); test!( if_else_inner_false, "a {\n @if false {\n color: foo;\n} @else {\n color: bar;\n}\n}\n", "a {\n color: bar;\n}\n" ); error!( no_brace_after_else, "@if false {} @else -}", "Error: expected \"{\"." ); test!( if_else_if_no_else, "a {\n @if false {\n ...
random
[ { "content": "#[macro_export]\n\nmacro_rules! test {\n\n (@base $( #[$attr:meta] ),*$func:ident, $input:expr, $output:expr, $options:expr) => {\n\n $(#[$attr])*\n\n #[test]\n\n #[allow(non_snake_case)]\n\n fn $func() {\n\n let sass = grass::from_string($input.to_string(...
Rust
crates/zoon/src/element/stack.rs
xrayzh/MoonZoon
d7da534dc09d69bace32dc548367afd49d2b59f4
use crate::{web_sys::HtmlElement, *}; use std::iter; use std::marker::PhantomData; make_flags!(Empty); pub struct Stack<EmptyFlag> { raw_el: RawHtmlEl, flags: PhantomData<EmptyFlag>, } impl Stack<EmptyFlagSet> { pub fn new() -> Self { Self::with_tag(Tag::Custom("div")) } } impl Element for S...
use crate::{web_sys::HtmlElement, *}; use std::iter; use std::marker::PhantomData; make_flags!(Empty); pub struct Stack<EmptyFlag> { raw_el: RawHtmlEl, flags: PhantomData<EmptyFlag>, } impl Stack<EmptyFlagSet> { pub fn new() -> Self { Self::with_tag(Tag::Custom("div")) } } impl Element for S...
pub fn layers( mut self, layers: impl IntoIterator<Item = impl IntoElement<'a> + 'a>, ) -> Stack<EmptyFlagNotSet> { self.raw_el = self.raw_el.children(layers); self.into_type() } pub fn layers_signal_vec( mut self, layers: impl SignalVec<Item = impl Int...
gnal( mut self, layer: impl Signal<Item = impl IntoOptionElement<'a>> + Unpin + 'static, ) -> Stack<EmptyFlagNotSet> { self.raw_el = self.raw_el.child_signal(layer); self.into_type() }
function_block-function_prefixed
[ { "content": "pub fn icon_open_in_new() -> impl Element {\n\n RawHtmlEl::new(\"i\")\n\n .class(\"eos-icons\")\n\n .child(\"open_in_new\")\n\n}\n\n\n\n\n\n// blocks!{\n\n// append_blocks![\n\n// els,\n\n// crate::login,\n\n// crate::clients_and_projects,\n\n// ...
Rust
src/main.rs
g2p/xvf
7db16c2554740df48052c59c134f8674923970a9
#[macro_use] extern crate clap; #[macro_use] extern crate lazy_static; extern crate libc; extern crate scmp; extern crate tempdir; use std::fs; use std::env; use std::ffi::OsStr; use std::ffi::CString; use std::io::Error; use std::os::raw::c_void; use std::os::unix::process::CommandExt; use std::os::unix::ffi::OsStrE...
#[macro_use] extern crate clap; #[macro_use] extern crate lazy_static; extern crate libc; extern crate scmp; extern crate tempdir; use std::fs; use std::env; use std::ffi::OsStr; use std::ffi::CString; use std::io::Error; use std::os::raw::c_void; use std::os::unix::process::CommandExt; use std::os::unix::ffi::OsStrE...
fn rename_or_suffix(path0 : &Path, path1 : &Path) -> Result<PathBuf, Error> { let rv = rename_noreplace(path0, path1); if let Err(err) = rv { if err.raw_os_error().expect("Error fails to wrap errno") != libc::EEXIST { return Err(err); } for suffix in 1.. { let m...
r> { unsafe { if libc::syscall(__NR_renameat2 as i64, libc::AT_FDCWD, path_to_cstring(path0).as_ptr(), libc::AT_FDCWD, path_to_cstring(path1).as_ptr(), RENAME_NOREPLACE, 0) == 0 { Ok(()) } else { Err(Error::last_os_error()) } } }
function_block-function_prefixed
[ { "content": "# xvf: easy archive extraction\n\n\n\n[![Version badge](https://img.shields.io/crates/v/xvf.svg)](https://crates.io/crates/xvf)\n\n[![Build status](https://travis-ci.org/g2p/xvf.svg?branch=master)](https://travis-ci.org/g2p/xvf)\n\n\n\nxvf extracts archives in various formats, from the command lin...
Rust
src/core/modules/simple_module.rs
KillingSpark/rs-event-sim
66f431d2253ef44687fb62c7b7f03a51e9fbea09
use crate::core::connection::connection::Port; use crate::core::contexts::EventHandleContext; use crate::core::events::event::{Event, TimerEvent}; use crate::core::events::text_event::{new_text_event, TextEvent}; use crate::core::id_mngmnt::id_types::{GateId, ModuleId, ModuleTypeId, PortId}; use crate::core::messages::...
use crate::core::connection::connection::Port; use crate::core::contexts::EventHandleContext; use crate::core::events::event::{Event, TimerEvent}; use crate::core::events::text_event::{new_text_event, TextEvent}; use crate::core::id_mngmnt::id_types::{GateId, ModuleId, ModuleTypeId, PortId}; use crate::core::messages::...
fn module_type_id(&self) -> ModuleTypeId { self.type_id } fn module_id(&self) -> ModuleId { self.id } fn name(&self) -> String { self.name.clone() } fn initialize( &mut self, gates: &std::collections::HashMap<GateId, std::collections::HashMap<Port...
fn handle_timer_event( &mut self, ev: &Event, ctx: &mut EventHandleContext, ) -> Result<HandleResult, Box<std::error::Error>> { if self.msg_time != ctx.mctx.time.now() { self.msg_counter = 0; self.msg_time = ctx.mctx.time.now(); } let te_type ...
function_block-full_function
[ { "content": "pub fn new_echo_module(id_reg: &mut IdRegistrar, name: String) -> EchoModule {\n\n EchoModule {\n\n id: id_reg.new_module_id(),\n\n type_id: id_reg.lookup_module_id(TYPE_STR.to_owned()).unwrap(),\n\n name: name,\n\n\n\n msgs_echoed: 0,\n\n }\n\n}\n\n\n\nimpl Modul...
Rust
tests/integration_test.rs
chrysn-pull-requests/minimq
3a7ca880d5c2d6d5703b94f61038bd0bde569ff4
use minimq::{Minimq, Property, QoS}; use std::io::{Read, Write}; use embedded_nal::{self, nb, IpAddr, Ipv4Addr, SocketAddr}; #[derive(Copy, Clone, Debug)] struct STACK; pub struct TcpSocket { state: Option<std::net::TcpStream>, } impl TcpSocket { pub fn new() -> Self { Self { state: None } } } ...
use minimq::{Minimq, Property, QoS}; use std::io::{Read, Write}; use embedded_nal::{self, nb, IpAddr, Ipv4Addr, SocketAddr}; #[derive(Copy, Clone, Debug)] struct STACK; pub struct TcpSocket { state: Option<std::net::TcpStream>, } impl TcpSocket { pub fn new() -> Self { Self { state: None } } } ...
impl embedded_nal::TcpClientStack for STACK { type Error = std::io::Error; type TcpSocket = TcpSocket; fn socket(&mut self) -> Result<TcpSocket, Self::Error> { Ok(TcpSocket::new()) } fn connect( &mut self, socket: &mut TcpSocket, remote: SocketAddr, ) -> nb::R...
use std::io::ErrorKind::{TimedOut, WouldBlock}; match e.kind() { WouldBlock | TimedOut => nb::Error::WouldBlock, _ => e.into(), } }
function_block-function_prefix_line
[ { "content": "#[test]\n\npub fn serialize_publish_with_properties() {\n\n let good_publish: [u8; 14] = [\n\n 0x30, // Publish message\n\n 0x0c, // Remaining length (14)\n\n 0x00, 0x03, 0x41, 0x42, 0x43, // Topic: ABC\n\n 0x04, // Properties length - 1 property encoding a string of...
Rust
taskchampion/src/server/local.rs
dbr/taskchampion
3cccdc7e3253901ef4f13112d5bcf847d070a08f
use crate::server::{ AddVersionResult, GetVersionResult, HistorySegment, Server, VersionId, NO_VERSION_ID, }; use crate::utils::Key; use failure::Fallible; use kv::msgpack::Msgpack; use kv::{Bucket, Config, Error, Integer, Serde, Store, ValueBuf}; use serde::{Deserialize, Serialize}; use std::path::Path; use uuid::...
use crate::server::{ AddVersionResult, GetVersionResult, HistorySegment, Server, VersionId, NO_VERSION_ID, }; use crate::utils::Key; use failure::Fallible; use kv::msgpack::Msgpack; use kv::{Bucket, Config, Error, Integer, Serde, Store, ValueBuf}; use serde::{Deserialize, Serialize}; use std::path::Path; use uuid::...
if let AddVersionResult::Ok(_) = server.add_version(parent_version_id, history.clone())? { panic!("should not have accepted the version") } Ok(()) } }
if let AddVersionResult::ExpectedParentVersion(_) = server.add_version(parent_version_id, history.clone())? { panic!("should have accepted the version") }
if_condition
[]
Rust
src/app/va/va_inst.rs
hasebems/Musical_Sound_Generator_Framework_by_Rust
32cf38d46e739f1e693dbf9ea4472e1fad35ccc4
use std::rc::Rc; use std::cell::Cell; use crate::msgf_if; use crate::core::*; use crate::core::msgf_voice::*; use crate::engine::*; use crate::app::va::*; pub struct InstVa { vce_audio: msgf_afrm::AudioFrame, inst_audio: msgf_afrm::AudioFrame, vcevec: Vec<va_voice::VoiceVa>, delay: msgf_delay::Delay,...
use std::rc::Rc; use std::cell::Cell; use crate::msgf_if; use crate::core::*; use crate::core::msgf_voice::*; use crate::engine::*; use crate::app::va::*; pub struct InstVa { vce_audio: msgf_afrm::AudioFrame, inst_audio: msgf_afrm::AudioFrame, vcevec: Vec<va_voice::VoiceVa>, delay: msgf_delay::Delay,...
}; if return_num == max_note { None } else { Some(&mut self.vcevec[return_num]) } } fn _debug(&mut self) { let sz = self.vcevec.len(); println!("Debug!: {}",sz); } }
if self.vcevec[i].note_num() == note_num && sts == self.vcevec[i].status() { return_num = i; break; }
if_condition
[ { "content": "pub fn get_inst(inst_number:usize, vol:u8, pan:u8, exp:u8) -> Box<dyn msgf_inst::Inst> {\n\n if inst_number < 8 {\n\n println!(\"Changed Va: {}\",inst_number);\n\n Box::new(va_inst::InstVa::new(inst_number,vol,pan,exp))\n\n }\n\n else if inst_number < 16 {\n\n println...
Rust
src/editview/src/fonts.rs
Cogitri/gxi
adba6d9b292691ae5c3d90341fd5335c0b27a5cb
use log::debug; use pango::{FontDescription, FontsetExt, Language}; #[derive(Debug, Clone, PartialOrd, PartialEq)] pub struct Font { pub font_height: f64, pub font_width: f64, pub font_ascent: f64, pub font_descent: f64, pub font_desc: FontDescription, } impl Font { pub fn new(pang...
use log::debug; use pango::{FontDescription, FontsetExt, Language}; #[derive(Debug, Clone, PartialOrd, PartialEq)] pub struct Font { pub font_height: f64, pub font_width: f64, pub font_ascent: f64, pub font_descent: f64, pub font_desc: FontDescription, } impl Font { pub fn new(pang...
}
assert_eq!( font, Font { font_ascent: 16.0, font_descent: 5.0, font_height: 21.0, font_width: 10.0, font_desc: FontDescription::from_string("Source Code Pro Bold 12"), } ) }
function_block-function_prefix_line
[ { "content": "/// Generate a new `Settings` object, which we pass to the `EditView` to set its behaviour.\n\npub fn new_settings() -> editview::Settings {\n\n let gschema = gio::Settings::new(\"org.gnome.Tau\");\n\n let interface_font = {\n\n use gtk::SettingsExt;\n\n let gtk_settings = gtk:...
Rust
src/auth/oidc.rs
MatteoJoliveau/apicurio-sync
d530835d987f9ec182306fbacf4f4a18b14e66ea
use std::convert::Infallible; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::ops::Add; use std::sync::Arc; use async_trait::async_trait; use chrono::{DateTime, Duration, Utc}; use http::StatusCode; use openidconnect::{ AuthorizationCode, ClientId, ClientSecret, CsrfToken, IssuerUrl, Nonce, OAuth2TokenRespo...
use std::convert::Infallible; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::ops::Add; use std::sync::Arc; use async_trait::async_trait; use chrono::{DateTime, Duration, Utc}; use http::StatusCode; use openidconnect::{ AuthorizationCode, ClientId, ClientSecret, CsrfToken, IssuerUrl, Nonce, OAuth2TokenRespo...
warp::reply::html(format!( r#" <h1>ERROR</h1> <h2>{}</h2> <p>{}</p> "#, err, msg )), StatusCode::BAD_REQUEST, )); } let token_response = token_response.unwrap(); provider.tokens = Some(TokenSet { access_tok...
RequestTokenError::Parse(inner, _) => inner.to_string(), RequestTokenError::Other(_) => "".to_string(), }; tracing::info!("ERROR: {} {}", err, msg); tx.send(()).await.expect("shutdown::send"); return Ok(warp::reply::with_status(
random
[ { "content": "fn with_auth(req: RequestBuilder, auth: &context::Auth) -> RequestBuilder {\n\n match auth {\n\n Auth::Oidc { access_token, .. } => req.bearer_auth(access_token),\n\n Auth::Basic { username, password } => req.basic_auth(username, password.as_ref()),\n\n Auth::None => req,\n...
Rust
algebra/src/fft/domain/mod.rs
ZencashOfficial/zexe
deaabb1c47d2a01fbd7514dc4ed4e255ebaec890
#[doc(hidden)] pub mod domain_selector; pub use self::domain_selector::*; #[doc(hidden)] pub mod basic_radix_2_domain; pub use self::basic_radix_2_domain::*; #[doc(hidden)] pub mod mixed_radix_2_domain; pub use self::mixed_radix_2_domain::*; #[cfg(all(test, feature = "bls12_381"))] mod test; use crate::PrimeField...
#[doc(hidden)] pub mod domain_selector; pub use self::domain_selector::*; #[doc(hidden)] pub mod basic_radix_2_domain; pub use self::basic_radix_2_domain::*; #[doc(hidden)] pub mod mixed_radix_2_domain; pub use self::mixed_radix_2_domain::*; #[cfg(all(test, feature = "bls12_381"))] mod test; use crate::PrimeField...
ize).unwrap(); let domain_size = domain.size(); assert_eq!(domain_size, domain.elements().collect::<Vec<_>>().len()); } } #[test] fn elements_contents() { for coeffs in 1..18 { let size = 1 << coeffs; let domain = get_best_evaluation_domain::<...
let i = index - other_size; let x = period - 1; Ok(i + (i / x) + 1) } } fn elements(&self) -> Elements<F> { Elements { cur_elem: F::one(), cur_pow: 0, size: self.size() as u64, group_gen: self.group_gen(), ...
random
[ { "content": "pub trait PairingEngine: Sized + 'static + Copy + Debug + Sync + Send + Eq + PartialEq {\n\n /// This is the scalar field of the G1/G2 groups.\n\n type Fr: PrimeField + SquareRootField + Into<<Self::Fr as PrimeField>::BigInt>;\n\n\n\n /// The projective representation of an element in G1....
Rust
src/visualizer/symmetry/symmetry.rs
swaggy/rpi-music-visualizer
e962b2ebe17b815bec5364f6292e6349619ed77d
use audio; use gfx; use gfx::gl; use std::mem; use std::ptr; const NUM_SQUARES: usize = 1; const NUM_VERTICIES_PER_SQUARE: usize = 6; const NUM_ATTRIBUTES_PER_VERTEX: usize = 2; const NUM_FLOATS: usize = NUM_SQUARES * NUM_VERTICIES_PER_SQUARE * NUM_ATTRIBUTES_PER_VERTEX; pub struct SymmetryVisualizer { program_id...
use audio; use gfx; use gfx::gl; use std::mem; use std::ptr; const NUM_SQUARES: usize = 1; const NUM_VERTICIES_PER_SQUARE: usize = 6; const NUM_ATTRIBUTES_PER_VERTEX: usize = 2; const NUM_FLOATS: usize = NUM_SQUARES * NUM_VERTICIES_PER_SQUARE * NUM_ATTRIBUTES_PER_VERTEX; pub struct SymmetryVisualizer { program_id...
fn generate_vertex_data() -> Vec<f32> { let mut vertex_data = Vec::with_capacity(NUM_FLOATS); let add_square = |vertex_data: &mut Vec<f32>, size: f32| { vertex_data.extend_from_slice(&[ -size, -size, -size, size, size, size, -size, -...
function_block-full_function
[ { "content": "pub fn to_amplitude(input: Vec<Complex<f32>>, amplitude_scalar: f32) -> Vec<f32> {\n\n let mut output: Vec<f32> = vec![0.0; input.len()];\n\n\n\n for i in 0..input.len() {\n\n let re = input[i].re;\n\n let im = input[i].im;\n\n output[i] = (re * re + im * im).sqrt() / in...
Rust
src/message.rs
belak/simple-irc-rs
15ba0b64c7d843f28f814109f3ecd1c9fd05f736
use std::collections::BTreeMap; use std::fmt; use std::fmt::Write; use std::option::Option; use std::str::FromStr; use super::error::Error; use crate::escaped::{escape_char, unescape_char}; #[derive(Debug, PartialEq, Default, Clone)] pub struct Prefix { pub nick: String, pub user: Option<String>, pub hos...
use std::collections::BTreeMap; use std::fmt; use std::fmt::Write; use std::option::Option; use std::str::FromStr; use super::error::Error; use crate::escaped::{escape_char, unescape_char}; #[derive(Debug, PartialEq, Default, Clone)] pub struct Prefix { pub nick: String, pub user: Option<String>, pub hos...
} } impl fmt::Display for Prefix { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(&self.nick)?; if let Some(user) = self.user.as_ref() { f.write_char('!')?; f.write_str(&user[..])?; } if let Some(host) = self.host.as_ref() { ...
Ok(Prefix { nick, user: user.and_then(|s| if s == "" { None } else { Some(s.to_string()) }), host: host.and_then(|s| if s == "" { None } else { Some(s.to_string()) }), })
call_expression
[ { "content": "fn parse_complex(bench: &mut Bencher) {\n\n bench.iter(|| \"@a=b;c=d;e=\\\\\\\\ :hello-world PING PONG :EXTRA\".parse::<Message>());\n\n}\n\n\n\nbenchmark_group!(benches, parse_simple, parse_complex);\n\nbenchmark_main!(benches);\n", "file_path": "benches/msg_split.rs", "rank": 1, "...
Rust
src/wallet/transact.rs
AurevoirXavier/onething
856de56bf9d55727080796b2f9cf6f9477a12968
use std::{ u128, fs::File, io::{stdin, stdout, Read, Write}, thread::{self, sleep}, time::Duration, }; use crate::util::{ to_hex, init::{CONF, GET_BALANCE_API, WALLETS}, }; use super::{ format_balance, get_info, get_all_balance, get_premier_wallet, list_wallet, tran...
use std::{ u128, fs::File, io::{stdin, stdout, Read, Write}, thread::{self, sleep}, time::Duration, }; use crate::util::{ to_hex, init::{CONF, GET_BALANCE_API, WALLETS}, }; use super::{ format_balance, get_info, get_all_balance, get_premier_wallet, list_wallet, tran...
f.read_to_string(&mut orders).unwrap(); orders }; let mut handles = vec![]; for orders in orders.lines().map(|line| line.to_owned()).collect::<Vec<String>>().chunks(CONF.transaction_per_thread) { let orders = orders.to_vec(); let handle = thread::spawn(move || { for o...
continue; } let value = u128::from_str_radix(&remain[2..], 16).unwrap() - 0x2386f26fc10000; Transaction::new(&premier_wallet, &value.to_string(), "0x186a0", "") .sign(&wallet, "123456789") .send(); println!("Walle...
random
[ { "content": "pub fn check_balance(from: &str, value: &str, gas_limit: &str) -> bool {\n\n let balance = u128::from_str_radix(&get_info(GET_BALANCE_API, from)[2..], 16).unwrap();\n\n let gas_limit = u128::from_str_radix(&gas_limit[2..], 16).unwrap();\n\n let gas_price = 0x174876e800;\n\n let value =...
Rust
crates/wasi-common/src/virtfs/pipe.rs
willemneal/wasmtime
a9455a8e5188ba70a2831279b5a3968e2c192539
use crate::handle::{Handle, HandleRights}; use crate::wasi::{types, Errno, Result}; use std::any::Any; use std::io::{self, Read, Write}; use std::sync::{Arc, RwLock}; #[derive(Debug)] pub struct ReadPipe<R: Read + Any> { rights: RwLock<HandleRights>, reader: Arc<RwLock<R>>, } impl<R: Read + Any> Clone for R...
use crate::handle::{Handle, HandleRights}; use crate::wasi::{types, Errno, Result}; use std::any::Any; use std::io::{self, Read, Write}; use std::sync::{Arc, RwLock}; #[derive(Debug)] pub struct ReadPipe<R: Read + Any> { rights: RwLock<HandleRights>, reader: Arc<RwLock<R>>, } impl<R: Read + Any> Clone for R...
n } fn get_rights(&self) -> HandleRights { *self.rights.read().unwrap() } fn set_rights(&self, rights: HandleRights) { *self.rights.write().unwrap() = rights; } fn advise( &self, _advice: types::Advice, _offset: types::Filesize, _len: types::Fil...
or<Vec<u8>>> { fn from(r: &[u8]) -> Self { Self::from(r.to_vec()) } } impl From<String> for ReadPipe<io::Cursor<String>> { fn from(r: String) -> Self { Self::new(io::Cursor::new(r)) } } impl From<&str> for ReadPipe<io::Cursor<String>> { fn from(r: &str) -> Self { Self::from...
random
[ { "content": "pub fn build_dependencies<R: Reader<Offset = usize>>(\n\n dwarf: &read::Dwarf<R>,\n\n at: &AddressTransform,\n\n) -> read::Result<Dependencies> {\n\n let mut deps = Dependencies::new();\n\n let mut units = dwarf.units();\n\n while let Some(unit) = units.next()? {\n\n build_un...
Rust
runtime/wasm/src/asc_abi/mod.rs
Tumble17/graph-node
a4315a33652391f453031a5412b6c51ba4ce084c
pub use self::asc_ptr::AscPtr; use crate::error::DeterministicHostError; use graph::prelude::anyhow; use std::convert::TryInto; use std::mem::size_of; pub mod asc_ptr; pub mod class; #[cfg(target_endian = "big")] compile_error!("big-endian targets are currently unsupported"); pub trait AscHeap: Sized { fn...
pub use self::asc_ptr::AscPtr; use crate::error::DeterministicHostError; use graph::prelude::anyhow; use std::convert::TryInto; use std::mem::size_of; pub mod asc_ptr; pub mod class; #[cfg(target_endian = "big")] compile_error!("big-endian targets
: AscPtr<Self>, _heap: &H) -> Result<u32, DeterministicHostError> { Ok(size_of::<Self>() as u32) } } pub trait AscValue: AscType + Copy + Default {} impl AscType for bool { fn to_asc_bytes(&self) -> Result<Vec<u8>, DeterministicHostError> { Ok(vec![*self as u8]) } fn from_asc_bytes(as...
are currently unsupported"); pub trait AscHeap: Sized { fn raw_new(&mut self, bytes: &[u8]) -> Result<u32, DeterministicHostError>; fn get(&self, offset: u32, size: u32) -> Result<Vec<u8>, DeterministicHostError>; fn asc_new<C, T: ?Sized>(&mut self, rust_obj: &T) -> Result<A...
random
[ { "content": "/// Run a GraphQL query against the `STORE`\n\npub fn execute_subgraph_query(query: Query, target: QueryTarget) -> QueryResults {\n\n execute_subgraph_query_with_complexity(query, target, None)\n\n}\n\n\n", "file_path": "store/test-store/src/store.rs", "rank": 0, "score": 148663.683...
Rust
src/handlers.rs
rogusdev/onetime-downloader
9860b8fa61383f6dc836c48dcf928a5008a2979c
use rand::Rng; use bytes::{Bytes}; use actix_web::{web, HttpRequest, HttpResponse, http::header}; use actix_multipart::{Field, Multipart}; use futures::{StreamExt, TryStreamExt}; use crate::models::{CreateLink, OnetimeDownloaderService, OnetimeFile, OnetimeLink}; const API_KEY_HEADER: &'static str = "X-Api-Key"; ...
use rand::Rng; use bytes::{Bytes}; use actix_web::{web, HttpRequest, HttpResponse, http::header}; use actix_multipart::{Field, Multipart}; use futures::{StreamExt, TryStreamExt}; use crate::models::{CreateLink, OnetimeDownloaderService, OnetimeFile, OnetimeLink}; const API_KEY_HEADER: &'static str = "X-Api-Key"; ...
field_filename = Some(String::from_utf8(val).unwrap()); } } } } if (field_filename.is_some() || file_filename.is_some()) && contents.is_some() { let now = service.time_provider.unix_ts_ms(); let filename = field_filename.unwrap_or_else(|| file_filename.unw...
est().body(format!("field value too big! {}", size))) } val.append(&mut data.to_vec()); } Ok(val) } pub async fn add_file ( req: HttpRequest, mut payload: Multipart, service: web::Data<OnetimeDownloaderService>, ) -> Result<HttpResponse, HttpResponse> { println!("add file"); ...
random
[ { "content": "// https://users.rust-lang.org/t/impl-tryinto-as-an-argument-in-a-function-complains-about-the-error-conversion/34004\n\npub fn try_from_vec<T, U: TryFrom<T, Error=MyError>> (items: Vec<T>, name: &'static str) -> Result<Vec<U>, MyError> {\n\n let mut vec = Vec::new();\n\n for item in items....
Rust
tower-lsp/src/service.rs
Hyperion101010/solang-vscode
7dfaf0d8702242739c83117b45610b582af04ee9
use std::error::Error; use std::fmt::{Display, Formatter, Result as FmtResult}; use std::future::Future; use std::pin::Pin; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::task::{Context, Poll}; use futures::compat::Future01CompatExt; use futures::future::{self, TryFutureExt}; use futures...
use std::error::Error; use std::fmt::{Display, Formatter, Result as FmtResult}; use std::future::Future; use std::pin::Pin; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::task::{Context, Poll}; use futures::compat::Future01CompatExt; use futures::future::{self, TryFutureExt}; use futures...
ll(initialize.clone()).await, Ok(Some(ok.into()))); let err = r#"{"jsonrpc":"2.0","error":{"code":-32600,"message":"Invalid request"},"id":1}"#; assert_eq!(service.poll_ready(), Poll::Ready(Ok(()))); assert_eq!(service.call(initialize).await, Ok(Some(err.into()))); } #[tokio::test] ...
let initialize: Incoming = INITIALIZE_REQUEST.parse().unwrap(); let ok = r#"{"jsonrpc":"2.0","result":{"capabilities":{}},"id":1}"#; assert_eq!(service.poll_ready(), Poll::Ready(Ok(()))); assert_eq!(service.ca
function_block-random_span
[ { "content": "/// Compat alternative for `jsonrpc_core::BoxFuture`.\n\ntype BoxFuture<T> = Compat<Pin<Box<dyn Future<Output = Result<T, Error>> + Send>>>;\n\n\n\n/// Routes responses from the language client back to the server.\n\npub type MessageSender = Sender<Output>;\n\n\n\n/// Stream of messages produced b...
Rust
src/lib.rs
Andreas-Edling/triangulator
f425e004d1b2fcaa654299ae09c86fb795fea004
mod circle; mod convex_hull; mod delaunay_inc; mod edge; mod point; mod triangle; mod types; mod utils; pub use circle::Circle; pub use point::Point; pub use triangle::Triangle; use delaunay_inc::DelaunayIncremental; #[derive(Debug, thiserror::Error, PartialEq, Eq)] pub enum TriangulatorError { #[error("Too fe...
mod circle; mod convex_hull; mod delaunay_inc; mod edge; mod point; mod triangle; mod types; mod utils; pub use circle::Circle; pub use point::Point; pub use triangle::Triangle; use delaunay_inc::DelaunayIncremental; #[derive(Debug, thiserror::Error, PartialEq, Eq)] pub enum TriangulatorError { #[error("Too fe...
#[test] fn handles_identical_values() { let points = [ Point::new(0.0, 0.0), Point::new(1.0, 0.0), Point::new(0.5, 1.0), Point::new(0.5, 0.5), Point::new(0.5, 0.5), ]; let res = triangulate(&points); assert!(res.is_ok...
fn returns_three_triangles() { let points = [ Point::new(0.0, 0.0), Point::new(1.0, 0.0), Point::new(0.5, 1.0), Point::new(0.5, 0.5), ]; let res = triangulate(&points); assert!(res.is_ok()); assert_eq!(res.unwrap().len(), 3); ...
function_block-full_function
[ { "content": "fn point_in_triangle(point: &Point, a: &Point, b: &Point, c: &Point) -> bool {\n\n if cross(a, b, c).abs() < f32::EPSILON {\n\n return false;\n\n }\n\n\n\n same_side_of_line(point, a, b, c)\n\n && same_side_of_line(point, b, a, c)\n\n && same_side_of_line(point, c, a,...
Rust
race_result_analysis/src/race_result_analysis.rs
ddboline/garmin_rust
170ab41ba7c53855af753fc0050dee9cb2779f13
use anyhow::Error; use chrono::{NaiveDate, Utc}; use itertools::Itertools; use maplit::hashmap; use ndarray::{array, Array1}; use postgres_query::{query, FromSqlRow}; use rusfun::{curve_fit::Minimizer, func1d::Func1D}; use stack_string::StackString; use std::collections::HashMap; use garmin_lib::{ common::{garmin_...
use anyhow::Error; use chrono::{NaiveDate, Utc}; use itertools::Itertools; use maplit::hashmap; use ndarray::{array, Array1}; use postgres_query::{query, FromSqlRow}; use rusfun::{curve_fit::Minimizer, func1d::Func1D}; use stack_string::StackString; use std::collections::HashMap; use garmin_lib::{ common::{garmin_...
e {"".into()}; let flag = if is_demo { result.race_flag.to_string() } else { format!( r#"<button type="button" id="race_flag_{id}" onclick="flipRaceResultFlag({id});">{flag}</button>"#, flag=result.race_flag, id=result.id ...
</tbody> </table>"#, entries ); let race_results = self.data.iter().sorted_by(|x, y| x.race_date.cmp(&y.race_date)).rev().map(|result| { let distance = f64::from(result.race_distance) / METERS_PER_MILE; let time = print_h_m_s(result.race_time, true).unw...
random
[ { "content": "pub fn print_h_m_s(second: f64, do_hours: bool) -> Result<StackString, Error> {\n\n let hours = (second / 3600.0) as i32;\n\n let minutes = (second / 60.0) as i32 - hours * 60;\n\n let seconds = second as i32 - minutes * 60 - hours * 3600;\n\n if (hours > 0) | ((hours == 0) & do_hours)...
Rust
07_system_fw/src/types.rs
lazear/types-and-programming-languages
0787493713b41639878db206e76d82fa8f29a77a
use std::convert::TryFrom; use std::fmt; #[derive(Clone, Debug, PartialEq, PartialOrd)] pub enum Type { Unit, Nat, Bool, Var(usize), Record(Vec<TyField>), Product(Vec<Type>), Projection(Box<Type>, usize), Arrow(Box<Type>, Box<Type>), Universal(Box<TyKind>, Box<Type>), Existentia...
use std::convert::TryFrom; use std::fmt; #[derive(Clone, Debug, PartialEq, PartialOrd)] pub enum Type { Unit, Nat, Bool, Var(usize), Record(Vec<TyField>), Product(Vec<Type>), Projection(Box<Type>, usize), Arrow(Box<Type>, Box<Type>), Universal(Box<TyKind>, Box<Type>), Existentia...
fn visit(&mut self, ty: &mut Type) { match ty { Type::Var(v) if *v == self.cutoff => { Shift::new(self.cutoff as isize).visit(&mut self.ty); *ty = self.ty.clone(); } _ => self.walk(ty), } } }
ersal(&mut self, _: &mut TyKind, ty: &mut Type) { self.cutoff += 1; self.visit(ty); self.cutoff -= 1; } fn visit_existential(&mut self, _: &mut TyKind, ty: &mut Type) { self.cutoff += 1; self.visit(ty); self.cutoff -= 1; } fn visit_abs(&mut self, _: &mut...
random
[ { "content": "pub fn subst(mut s: Type, mut t: Type) -> Type {\n\n Shift::new(1).visit(&mut s);\n\n Subst::new(s).visit(&mut t);\n\n Shift::new(-1).visit(&mut t);\n\n t\n\n}\n\n\n", "file_path": "06_system_f/src/types/mod.rs", "rank": 0, "score": 285996.36236996215 }, { "content"...
Rust
src/sources/band.rs
prin-r/my_delphi
a792fe0a8617302d53f1ccd59979c80ef126444e
use hyper::{ client::{Client, HttpConnector}, header, Body, Request, }; use base64; use bytes::buf::ext::BufExt; use hyper_rustls::HttpsConnector; use obi::OBIDecode; use serde::de; use serde::de::*; use serde::{Deserialize, Serialize}; use std::str::FromStr; pub const BASE_URI: &str = "http://guanyu-devnet.b...
use hyper::{ client::{Client, HttpConnector}, header, Body, Request, }; use base64; use bytes::buf::ext::BufExt; use hyper_rustls::HttpsConnector; use obi::OBIDecode; use serde::de; use serde::de::*; use serde::{Deserialize, Serialize}; use std::str::FromStr; pub const BASE_URI: &str = "http://guanyu-devnet.b...
pub async fn get_orcle_script(&self) -> Result<OracleScript, String> { let mut request = Request::builder() .method("GET") .uri(&format!( "{}/oracle/oracle_scripts/{}", BASE_URI, self.oracle_script_id )) .body(Body::empty()) ...
4, calldata: String, min_count: u64, ask_count: u64) -> Self { Self { http_client: Client::builder().build(HttpsConnector::new()), oracle_script_id: oracle_script_id, calldata: calldata, min_count: min_count, ask_count: ask_count, } }
function_block-function_prefixed
[ { "content": "/// Obtain a read-only (multi-reader) lock on the application configuration.\n\n///\n\n/// Panics if the application configuration has not been loaded.\n\npub fn app_config() -> config::Reader<DelphiApp> {\n\n config::Reader::new(&APPLICATION)\n\n}\n\n\n\n/// Delphi Application\n\n#[derive(Debu...
Rust
tests/it/compute/comparison.rs
sd2k/arrow2
6ccb1542467024683b61f7ec4bb0ae67caebfbb2
use arrow2::array::*; use arrow2::compute::comparison::{self, boolean::*}; use arrow2::datatypes::{DataType::*, IntervalUnit}; use arrow2::datatypes::{IntegerType, TimeUnit}; use arrow2::scalar::new_scalar; #[test] fn consistency() { use arrow2::compute::comparison::*; let datatypes = vec![ Null, ...
use arrow2::array::*; use arrow2::compute::comparison::{self, boolean::*}; use arrow2::datatypes::{DataType::*, IntervalUnit}; use arrow2::datatypes::{IntegerType, TimeUnit}; use arrow2::scalar::new_scalar; #[test] fn consistency() { use arrow2::compute::comparison::*; let datatypes = vec![ Null, ...
}
Utf8Array::<i32>::from_iter([Some("a"), None, None]); let out = comparison::utf8::neq_and_validity(&a, &b); check_mask(&out, &[false, false, true]); let out = comparison::utf8::neq_scalar_and_validity(&a, "a"); check_mask(&out, &[false, true, true]); let a = U...
function_block-function_prefixed
[ { "content": "/// Perform `left <= right` operation on an array and a scalar value.\n\n/// Null values are less than non-null values.\n\npub fn lt_eq_scalar(lhs: &BooleanArray, rhs: bool) -> BooleanArray {\n\n if rhs {\n\n let all_ones = !0;\n\n compare_op_scalar(lhs, rhs, |_, _| all_ones)\n\n ...
Rust
src/util/descriptor.rs
stevenroose/bwt
5fca1781402668c867fff59c939c6248197c7df4
use std::str::FromStr; use bitcoin::secp256k1::{self, Secp256k1}; use bitcoin::{Address, Network}; use miniscript::descriptor::{Descriptor, DescriptorPublicKey, DescriptorTrait, Wildcard}; use miniscript::{ForEachKey, TranslatePk2}; use crate::error::{Error, OptionExt, Result}; use crate::util::xpub::{xpub_matches_ne...
use std::str::FromStr; use bitcoin::secp256k1::{self, Secp256k1}; use bitcoin::{Address, Network}; use miniscript::descriptor::{Descriptor, DescriptorPublicKey, DescriptorTrait, Wildcard}; use miniscript::{ForEachKey, TranslatePk2}; use crate::error::{Error, OptionExt, Result}; use crate::util::xpub::{xpub_matches_ne...
} pub trait DescriptorExt: Sized { fn to_string_no_checksum(&self) -> String; fn checksum(&self) -> Checksum; fn parse_canonical(s: &str) -> Result<Self>; } impl DescriptorExt for ExtendedDescriptor { fn to_string_no_checksum(&self) -> String { self.to_string().splitn(2, '#').n...
pub fn extract(desc: &ExtendedDescriptor, network: Network) -> Result<Vec<DescKeyInfo>> { let mut keys_info = vec![]; let is_valid = desc.for_each_key(|fe| { match fe.as_key() { DescriptorPublicKey::XPub(desc_xpub) => { ...
function_block-full_function
[ { "content": "pub fn fmt_error_chain(err: &Error) -> String {\n\n err.chain()\n\n .map(|e| e.to_string())\n\n .collect::<Vec<String>>()\n\n .join(\": \")\n\n}\n", "file_path": "src/error.rs", "rank": 1, "score": 209093.9023795075 }, { "content": "// Handle errors prod...
Rust
2017/day23/src/main.rs
mour/advent-of-code
664c7838bf3ea269dfcf67fea1db70d0e5c3f1b9
#![feature(iterator_step_by)] extern crate regex; extern crate primal; #[macro_use] extern crate lazy_static; use regex::Regex; use std::io; use std::io::prelude::*; use std::collections::HashMap; use std::str::FromStr; use std::env; lazy_static! { static ref INSTR_RE: Regex = Regex::new(r"^(?P<instr>set|su...
#![feature(iterator_step_by)] extern crate regex; extern crate primal; #[macro_use] extern crate lazy_static; use regex::Regex; use std::io; use std::io::prelude::*; use std::collections::HashMap; use std::str::FromStr; use std::env; lazy_static! { static ref INSTR_RE: Regex = Regex::new(r"^(?P<instr>set|su...
cify the part of the puzzle."); } } #[cfg(test)] mod tests { use super::Computer; use std::collections::HashMap; #[test] fn part_a_test() { let input_str = include_str!("../input.txt"); let program = input_str.parse().expect("parse error"); let mut computer = Computer::ne...
&Value::Reg('d'))? = val_c; } { *self.get_reg_mut(&Value::Reg('f'))? = f; } { *self.get_reg_mut(&Value::Reg('h'))? = h; } pc += 1; } ...
random
[ { "content": "#[derive(Debug, PartialEq, Eq)]\n\nstruct Prerequisites(BTreeMap<char, HashSet<char>>);\n\n\n\nimpl FromStr for Prerequisites {\n\n type Err = AocError;\n\n\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n\n let mut out = BTreeMap::new();\n\n\n\n for line in s.lines() {\...
Rust
games/src/tanks.rs
rlane/picosystem-rs
fe37feb195e531096456c7fb1545f601d81dffca
use log::info; use micromath::{vector::Vector, F32Ext}; use picosystem::{ display::{Display, HEIGHT, WIDTH}, hardware, time, }; use embedded_graphics::mono_font::{ascii::FONT_10X20, MonoTextStyle}; use embedded_graphics::pixelcolor::Rgb565; use embedded_graphics::prelude::*; use embedded_graphics::primitives::...
use log::info; use micromath::{vector::Vector, F32Ext}; use picosystem::{ display::{Display, HEIGHT, WIDTH}, hardware, time, }; use embedded_graphics::mono_font::{ascii::FONT_10X20, MonoTextStyle}; use embedded_graphics::pixelcolor::Rgb565; use embedded_graphics::prelude::*; use embedded_graphics::primitives::...
fn fire_shot( hw: &mut hardware::Hardware, terrain: &mut Terrain, tank: &Tank, other: &Tank, ) -> bool { use micromath::vector::F32x2; let mut p = F32x2 { x: tank.position.x as f32, y: tank.position.y as f32, }; let angle = if tank.index == 0 { tank.angle } el...
function_block-full_function
[ { "content": "pub fn framebuffer() -> &'static mut [u16; WIDTH * HEIGHT] {\n\n unsafe { &mut FRAMEBUFFER }\n\n}\n\n\n\npub type RealDisplay =\n\n ST7789<SPIInterfaceNoCS<Spi<hal::spi::Enabled, pac::SPI0, 8>, DynPin>, DynPin>;\n\n\n\npub struct Display {\n\n st7789: RealDisplay,\n\n backlight_pin: Dy...
Rust
src/pwm.rs
rust-idf/rust-idf-hal
1fdd0274e5a88823533e7aa327dddc1986040397
use crate::gpio::*; use idf_sys::{ error::*, pwm::* }; const MAX_PWM_CHANNELS : usize = 8; #[derive(Copy, Clone)] struct PwmChannel { pin: PinId, duty: u32, } #[derive(Copy, Clone)] pub enum PwmInitializationError { TooManyChannels, TooShortPeriod, DutyExceedsPeriod, PeriodNotSet, } ...
use crate::gpio::*; use idf_sys::{ error::*, pwm::* }; const MAX_PWM_CHANNELS : usize = 8; #[derive(Copy, Clone)] struct PwmChannel { pin: PinId, duty: u32, } #[derive(Copy, Clone)] pub enum PwmInitializationError { TooManyChannels, TooShortPeriod, DutyExceedsPeriod, PeriodNotSet, } ...
pub fn set_period(mut self, period: u32) -> Result<Self, PwmInitializationError> { if period < 10 { Err(PwmInitializationError::TooShortPeriod) } else { self.period = Some(period); Ok(self) } } pub fn initialize(self) -> Result<Pwm, (PwmInitiali...
self.channels_count += 1; Ok(self) } else { Err(PwmInitializationError::TooManyChannels) } }
function_block-function_prefix_line
[ { "content": "pub fn set_event_loop<F>(loop_handler: F)\n\n where F: FnMut(SystemEvent) + Send + 'static\n\n{\n\n unsafe {\n\n let closure_ptr = Box::into_raw(Box::new(loop_handler));\n\n\n\n esp_event_loop_init(Some(event_loop_wrapper::<F>), closure_ptr as *mut xtensa_void);\n\n }\n\n}",...
Rust
src/router/request_matcher/header.rs
ptondereau/libredirectionio
fb48a34078393eda9d5ccf23ae1721e61be81124
use crate::http::Request; use crate::router::request_matcher::{PathAndQueryMatcher, RequestMatcher}; use crate::router::trace::{TraceInfo, TraceInfoHeaderCondition}; use crate::router::{Route, RouteData, RouteHeaderKind, Trace}; use regex::Regex; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; use ...
use crate::http::Request; use crate::router::request_matcher::{PathAndQueryMatcher, RequestMatcher}; use crate::router::trace::{TraceInfo, TraceInfoHeaderCondition}; use crate::router::{Route, RouteData, RouteHeaderKind, Trace}; use regex::Regex; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; use ...
fn cache(&mut self, limit: u64, level: u64) -> u64 { let mut new_limit = limit; for matcher in self.condition_groups.values_mut() { new_limit = matcher.cache(new_limit, level); } self.any_header.cache(new_limit, level) } fn len(&self) -> usize { self....
fn trace(&self, request: &Request) -> Vec<Trace<T>> { let mut traces = self.any_header.trace(request); let mut execute_conditions = BTreeMap::new(); for (conditions, matcher) in &self.condition_groups { let mut matched = true; let mut executed = true; let mut...
function_block-full_function
[ { "content": "pub trait RequestMatcher<T: RouteData>: Debug + Send + Sync {\n\n fn insert(&mut self, route: Route<T>);\n\n\n\n fn remove(&mut self, id: &str) -> bool;\n\n\n\n fn match_request(&self, request: &Request) -> Vec<&Route<T>>;\n\n\n\n fn trace(&self, request: &Request) -> Vec<Trace<T>>;\n\...
Rust
partial_ref_derive/src/lib.rs
jix/partial_ref
9d98d2d9ed7508fbb0fe8d7bcf4d8d3debdbb93a
#![recursion_limit = "128"] extern crate proc_macro; use std::collections::HashSet; use crate::proc_macro::TokenStream; use proc_macro2::{Span, TokenTree}; use quote::{quote, ToTokens}; use syn::{ parse_macro_input, parse_quote, parse_str, Attribute, Data, DeriveInput, Lifetime, LifetimeDef, Lit, Member, Me...
#![recursion_limit = "128"] extern crate proc_macro; use std::collections::HashSet; use crate::proc_macro::TokenStream; use proc_macro2::{Span, TokenTree}; use quote::{quote, ToTokens}; use syn::{ parse_macro_input, parse_quote, parse_str, Attribute, Data, DeriveInput, Lifetime, LifetimeDef, Lit, Member, Me...
split_mut_type = quote!( ::partial_ref::Mut< ::partial_ref::Nested<ContainingPart, #part>, #split_mut_type > ); } for (_, part) in typed_parts.iter() { const_type = quote!(::partial_ref::Const<#part, #const_type>); mut_type = quote...
function_block-function_prefix_line
[ { "content": "pub fn swap_a_and_b<T>(mut partial_ref: partial!(T, mut PartA, mut PartB))\n\nwhere\n\n T: PartialRefTarget,\n\n T: HasPart<PartA>,\n\n T: HasPart<PartB>,\n\n{\n\n split_borrow!(a, b = &(mut PartA) partial_ref);\n\n\n\n std::mem::swap(a.part_mut(PartA), b.part_mut(PartB))\n\n}\n\n\n...
Rust
src/main.rs
maximeborges/pico-rs-rmii
f450f67d6676554191df6f8c63cff62ac38dc832
#![no_std] #![no_main] use cortex_m_rt::entry; use defmt::*; use defmt_rtt as _; use embedded_hal::digital::v2::OutputPin; use embedded_time::rate::*; use panic_probe as _; use rp2040_hal as hal; mod pio; use crate::pio::{init_eth, EthPins}; use hal::{ clocks::*, pac, pll::{common_configs::PLL_USB_48MHZ,...
#![no_std] #![no_main] use cortex_m_rt::entry; use defmt::*; use defmt_rtt as _; use embedded_hal::digital::v2::OutputPin; use embedded_time::rate::*; use panic_probe as _; use rp2040_hal as hal; mod pio; use crate::pio::{init_eth, EthPins}; use hal::{ clocks::*, pac, pll::{common_configs::PLL_USB_48MHZ,...
#[link_section = ".boot2"] #[used] pub static BOOT2: [u8; 256] = rp2040_boot2::BOOT_LOADER_W25Q080;
s( xosc: pac::XOSC, pll_sys: pac::PLL_SYS, pll_usb: pac::PLL_USB, clocks: pac::CLOCKS, resets: &mut pac::RESETS, watchdog: pac::WATCHDOG, ) -> ClocksManager { let xosc_crystal_freq = 12_000_000u32; let xosc = setup_xosc_blocking(xosc, xosc_crystal_freq.Hz()).unwrap_or_else(|_| { ...
function_block-function_prefixed
[ { "content": "pub fn init_eth(mut pins: EthPins, pio0: pac::PIO0, dma: pac::DMA, resets: &mut pac::RESETS) {\n\n let rx_d0_index = pins.rx_d0.id().num;\n\n let tx_d0_index = pins.tx_d0.id().num;\n\n\n\n pins = pins.setup_pins(TargetPio::Pio0);\n\n\n\n setup_dma(&dma);\n\n\n\n let mdio = Mdio::ini...
Rust
src/tile.rs
pauljxtan/toitoi
bcce8ce2605782f95353fe33cba45395f6c18829
use itertools::Itertools; use std::fmt; #[derive(Clone, Copy, Eq, PartialEq, Hash, Ord, PartialOrd)] enum Suit { Man, Pin, Sou, Hon, } #[derive(Clone, Copy, Eq, PartialEq, Hash, Ord, PartialOrd)] pub struct Tile { suit: Suit, number: u8, } impl Tile { pub fn number(&self) -> u8 { self.n...
use itertools::Itertools; use std::fmt; #[derive(Clone, Copy, Eq, PartialEq, Hash, Ord, PartialOrd)] enum Suit { Man, Pin, Sou, Hon, } #[derive(Clone, Copy, Eq, PartialEq, Hash, Ord, PartialOrd)] pub struct Tile { suit: Suit, number: u8, } impl Tile { pub fn number(&self) -> u8 { self.n...
#[test] fn test_tile_next() { assert_eq!(t("1m").next(), t("2m")); assert_eq!(t("3p").next(), t("4p")); assert_eq!(t("5s").next(), t("6s")); assert_eq!(t("1z").next(), t("2z")); assert_eq!(t("6z").next(), t("7z")); } #[test] fn test_tile_prev() { ass...
al); assert_eq!(t("1m").cmp(&t("2m")), Ordering::Less); assert_eq!(t("2m").cmp(&t("1p")), Ordering::Less); assert_eq!(t("1z").cmp(&t("9s")), Ordering::Greater); assert_eq!(t("5z").cmp(&t("4z")), Ordering::Greater); }
function_block-function_prefixed
[ { "content": "/// Scores all winning hand combinations.\n\n///\n\n/// # Example\n\n///\n\n/// ```rust\n\n/// use toitoi::{\n\n/// score::score,\n\n/// tile::{tile_from_string, tiles_from_string},\n\n/// types::{Call, FuReason, HanReason, HandContext, Limit, Points, Yaku},\n\n/// };\n\n///\n\n/// let...
Rust
src/game/car/drive_to_destination.rs
izhevskoye/oligarchy
721b018823f58918cefbd1d1c4dfdc99efe27749
use std::collections::HashSet; use bevy::prelude::*; use bevy_ecs_tilemap::prelude::*; use rand::{thread_rng, Rng}; use crate::game::{ assets::{BlockedForBuilding, CanDriveOver, Direction, Occupied, Position, RequiresUpdate}, car::{Car, Waypoints}, construction::UnderConstruction, setup::{BUILDING_LAY...
use std::collections::HashSet; use bevy::prelude::*; use bevy_ecs_tilemap::prelude::*; use rand::{thread_rng, Rng}; use crate::game::{ assets::{BlockedForBuilding, CanDriveOver, Direction, Occupied, Position, RequiresUpdate}, car::{Car, Waypoints}, construction::UnderConstruction, setup::{BUILDING_LAY...
map_query: MapQuery, ) { let mut car_positions: HashSet<UVec2> = car_query .iter_mut() .map(|(_, _, position)| position.position) .collect(); for (car_entity, mut car, mut position) in car_query.iter_mut() { let mut waypoint = match waypoint_query.get_mut(car_entity) { ...
function_block-function_prefix_line
[ { "content": "pub fn teardown(mut commands: Commands, query: Query<Entity, With<Text>>) {\n\n for entity in query.iter() {\n\n commands.entity(entity).despawn_recursive();\n\n }\n\n}\n\n\n", "file_path": "src/game/setup/title.rs", "rank": 0, "score": 210125.22385270492 }, { "con...
Rust
gdnative/src/godot_type.rs
dkaste/godot-rust
0871443f4bcba81370d93a8f0534b91d618b4516
use super::*; pub trait GodotType: Sized { fn to_variant(&self) -> Variant; fn from_variant(variant: &Variant) -> Option<Self>; fn from_sys_variant(variant: &sys::godot_variant) -> Option<Self> { Self::from_variant(Variant::cast_ref(variant)) } } impl GodotType for () { fn to_variant(&sel...
use super::*; pub trait GodotType: Sized { fn to_variant(&self) -> Variant; fn from_variant(variant: &Variant) -> Option<Self>; fn from_sys_variant(variant: &sys::godot_variant) -> Option<Self> { Self::from_variant(Variant::cast_ref(variant)) } } impl GodotType for () { fn to_variant(&sel...
fn from_variant(variant: &Variant) -> Option<Self> { unsafe { let api = get_api(); if (api.godot_variant_get_type)(&variant.0) == sys::godot_variant_type::GODOT_VARIANT_TYPE_REAL { Some((api.godot_variant_as_real)(&variant.0) as Self) } else { ...
fn to_variant(&self) -> Variant { unsafe { let mut ret = sys::godot_variant::default(); (get_api().godot_variant_new_real)(&mut ret, f64::from(*self)); Variant(ret) } }
function_block-full_function
[ { "content": "#[inline]\n\n#[doc(hidden)]\n\npub fn get_api() -> &'static GodotApi {\n\n unsafe { GODOT_API.as_ref().expect(\"API not bound\") }\n\n}\n\n\n\n#[derive(Copy, Clone, Debug, PartialEq, Eq)]\n\n#[repr(u32)]\n\npub enum GodotError {\n\n Failed = sys::godot_error::GODOT_FAILED as u32,\n\n Unav...
Rust
backend/comments-rs-memdb/src/lib.rs
reenigneEsrever92/comment-rs
07bb5965f780e62bb92f7ae2e44f44b9bff2d93b
use std::{ future::Future, pin::Pin, sync::Mutex, task::{Context, Poll}, }; use comments_rs_core_backend::{ data::{Comment, Thread, User}, error::StoreError, traits::{CommentStore, StoreResult, ThreadStore, UserStore}, }; #[derive(Default)] struct CommentDb { users: Vec<User>, thre...
use std::{ future::Future, pin::Pin, sync::Mutex, task::{Context, Poll}, }; use comments_rs_core_backend::{ data::{Comment, Thread, User}, error::StoreError, traits::{CommentStore, StoreResult, ThreadStore, UserStore}, }; #[derive(Default)] struct CommentDb { users: Vec<User>, thre...
fn find_thread_by_hash( &self, hash: &str, ) -> StoreResult<Option<Thread>> { let data = self.data.lock().unwrap(); Box::pin(ImmediateFuture { result: Ok(data .threads .iter() .find(|thread| thread.hash == hash) ...
mut self, hash: &str, ) -> StoreResult<Option<Thread>> { let data = self.data.get_mut().unwrap(); let index = data.threads.iter().position(|thread| thread.hash == hash); match index { Some(index) => Box::pin(ImmediateFuture { result: Ok(Some(data.threads...
function_block-function_prefix_line
[ { "content": "#[function_component(Thread)]\n\nfn thread(thread: &ThreadProps) -> Html {\n\n html! {\n\n <div>\n\n <h1>{ &thread.data.name }</h1>\n\n { for thread.comments.iter().map(|comment|\n\n html! {\n\n <Comment data = {comment.clone()} />\...
Rust
src/functions/string.rs
JmPotato/dbgen
651eb4c2e59ed8f906ce5445db253e55432e4edc
use super::{args_1, args_3, args_4, Arguments, Function}; use crate::{ bytes::ByteString, error::Error, eval::{CompileContext, C}, span::{Span, SpanExt, S}, value::Value, }; use std::{convert::TryInto, isize, ops::Range}; fn sql_start_length_to_range(start: isize, length: isize) -> Range<usize> {...
use super::{args_1, args_3, args_4, Arguments, Function}; use crate::{ bytes::ByteString, error::Error, eval::{CompileContext, C}, span::{Span, SpanExt, S}, value::Value, }; use std::{convert::TryInto, isize, ops::Range}; fn sql_start_length_to_range(start: isize, length: isize) -> Range<usize> {...
} #[derive(Debug)] pub struct Concat; impl Function for Concat { fn compile(&self, _: &CompileContext, span: Span, args: Arguments) -> Result<C, S<Error>> { match Value::sql_concat(args.iter().map(|arg| &arg.inner)) { Ok(result) => Ok(C::Constant(result)), Err(e) => Err(e.span(spa...
ength.unwrap_or_else(|| self.0.length_of(&placing) as isize); let range = self.0.parse_sql_range(&input, start, length); input.splice(range, placing); Ok(C::Constant(input.into())) }
function_block-function_prefixed
[ { "content": "pub fn ensure_seed(matches: &mut Matches<'_>) {\n\n matches.entry(\"seed\").or_insert_with(|| {\n\n let mut buf = [0u8; 32];\n\n OsRng.fill_bytes(&mut buf);\n\n Match::Str(HEXLOWER_PERMISSIVE.encode(&buf))\n\n });\n\n}\n", "file_path": "dbdbgen/src/cli.rs", "rank...
Rust
src/main.rs
mvertescher/example-serial-terminal
29dd2424e33742b699f454926fefb386405ba69f
use std::convert::TryFrom; use std::path::PathBuf; use std::{io, str}; use bytes::{BufMut, BytesMut}; use futures::stream::StreamExt; use serialport::{FlowControl, Parity, StopBits}; use structopt::clap::AppSettings; use structopt::StructOpt; use strum::{EnumString, EnumVariantNames}; use tokio_serial::DataBits; use...
use std::convert::TryFrom; use std::path::PathBuf; use std::{io, str}; use bytes::{BufMut, BytesMut}; use futures::stream::StreamExt; use serialport::{FlowControl, Parity, StopBits}; use structopt::clap::AppSettings; use structopt::StructOpt; use strum::{EnumString, EnumVariantNames}; use tokio_serial::DataBits; use...
, }; } Ok(None) } } struct SerialWriteCodec(Eol); impl Encoder<String> for SerialWriteCodec { type Error = LinesCodecError; fn encode(&mut self, line: String, buf: &mut BytesMut) -> Result<(), Self::Error> { let eol = self.0.bytes(); buf.reserve(line.len() + e...
Err(LinesCodecError::Io(io::Error::new( io::ErrorKind::Other, "Invalid String", )))
call_expression
[ { "content": "# `serial-terminal-rs`\n\n\n\n[![Build Status](https://travis-ci.com/mvertescher/serial-terminal-rs.svg?branch=master)](https://travis-ci.com/mvertescher/serial-terminal-rs)\n\n[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)\n\n[...
Rust
src/ahb_secure_ctrl/sec_ctrl_ram4_slave_rule.rs
geky/lpc55s6x-pac
766a1eec50a670a5872aa1a8c7637a9d5b9d6478
#[doc = "Reader of register SEC_CTRL_RAM4_SLAVE_RULE"] pub type R = crate::R<u32, super::SEC_CTRL_RAM4_SLAVE_RULE>; #[doc = "Writer for register SEC_CTRL_RAM4_SLAVE_RULE"] pub type W = crate::W<u32, super::SEC_CTRL_RAM4_SLAVE_RULE>; #[doc = "Register SEC_CTRL_RAM4_SLAVE_RULE `reset()`'s with value 0"] impl crate::Reset...
#[doc = "Reader of register SEC_CTRL_RAM4_SLAVE_RULE"] pub type R = crate::R<u32, super::SEC_CTRL_RAM4_SLAVE_RULE>; #[doc = "Writer for register SEC_CTRL_RAM4_SLAVE_RULE"] pub type W = crate::W<u32, super::SEC_CTRL_RAM4_SLAVE_RULE>; #[doc = "Register SEC_CTRL_RAM4_SLAVE_RULE `reset()`'s with value 0"] impl crate::Reset...
[inline(always)] pub fn ram4_rule(&mut self) -> RAM4_RULE_W { RAM4_RULE_W { w: self } } }
= "Checks if the value of the field is `ENUM_S_NP`"] #[inline(always)] pub fn is_enum_s_np(&self) -> bool { *self == RAM4_RULE_A::ENUM_S_NP } #[doc = "Checks if the value of the field is `ENUM_S_P`"] #[inline(always)] pub fn is_enum_s_p(&self) -> bool { *self == RAM4_RULE_A::ENUM...
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
src/zones/mod.rs
tindzk/rustdns
79830c6872fab6ed3bf0df4e7cb1a91248763bff
use crate::zones::preprocessor::preprocess; use crate::zones::parser::Rule; use crate::zones::parser::ZoneParser; use crate::Class; use crate::Resource; use pest_consume::Parser; use std::str::FromStr; use std::time::Duration; use strum_macros::Display; mod parser; mod parser_tests; mod preprocessor; mod process; #...
use crate::zones::preprocessor::preprocess; use crate::zones::parser::Rule; use crate::zones::parser::ZoneParser; use crate::Class; use crate::Resource; use pest_consume::Parser; use std::str::FromStr; use std::time::Duration; use strum_macros::Display; mod parser; mod parser_tests; mod preprocessor; mod process; #...
File { origin, entries } } } impl FromStr for File { type Err = pest_consume::Error<Rule>; fn from_str(input_str: &str) -> Result<Self, Self::Err> { let input_str = preprocess(input_str).unwrap(); ...
if let Some(domain) = origin { if let Some(domain) = domain.strip_suffix('.') { origin = Some(domain.to_owned()) } else { panic!("TODO Origin wasn't a absolute domain"); } }
if_condition
[ { "content": "#[test]\n\npub fn test_encode() {\n\n for test in TESTS {\n\n assert_eq!(encode(test.0).unwrap(), test.1);\n\n }\n\n}\n", "file_path": "old_src/punycode.rs", "rank": 0, "score": 87430.92558889286 }, { "content": "#[derive(Parser)]\n\n#[grammar = \"zones/preprocesso...
Rust
sos21-use-case/src/list_form_answers.rs
sohosai/sos21-backend
f1883844b0e5c68d6b3f9d159c9268142abc81b4
use crate::error::{UseCaseError, UseCaseResult}; use crate::model::{form::FormId, form_answer::FormAnswer}; use anyhow::Context; use sos21_domain::context::{FormAnswerRepository, FormRepository, Login}; use sos21_domain::model::permissions::Permissions; #[derive(Debug, Clone)] pub enum Error { FormNotFound, I...
use crate::error::{UseCaseError, UseCaseResult}; use crate::model::{form::FormId, form_answer::FormAnswer}; use anyhow::Context; use sos21_domain::context::{FormAnswerRepository, FormRepository, Login}; use sos21_domain::model::permissions::Permissions; #[derive(Debug, Clone)] pub enum Error { FormNotFound, I...
#[tokio::test] async fn test_general() { let user = test::model::new_general_user(); let (app, form_id, _) = prepare_app(user).await; assert!(matches!( list_form_answers::run(&app, form_id).await, Err(UseCaseError::UseCase( list_form_answer...
Set::new(); expected.insert(FormAnswerId::from_entity(form1_answer1.id())); expected.insert(FormAnswerId::from_entity(form1_answer2.id())); let app = test::build_mock_app() .users(vec![login_user.clone(), operator]) .forms(vec![form1, form2]) .projects(vec![p...
function_block-function_prefixed
[ { "content": "pub fn to_check_answer_error(err: form::item::CheckAnswerError) -> CheckAnswerError {\n\n match err.kind() {\n\n form::item::CheckAnswerErrorKind::MismatchedItemsLength => {\n\n CheckAnswerError::MismatchedItemsLength\n\n }\n\n form::item::CheckAnswerErrorKind::M...
Rust
api/src/models/user_program_record.rs
stefansu28/gdlk
e31ed41dd86d9591099a754812c5d33ae224816b
use std::cmp; use crate::{error::ResponseResult, schema::user_program_records}; use chrono::{DateTime, Utc}; use diesel::{ dsl, expression::bound::Bound, query_builder::InsertStatement, sql_types, ExpressionMethods, Identifiable, Insertable, PgConnection, QueryDsl, Queryable, RunQueryDsl, }; use uuid::Uuid...
use std::cmp; use crate::{error::ResponseResult, schema::user_program_records}; use chrono::{DateTime, Utc}; use diesel::{ dsl, expression::bound::Bound, query_builder::InsertStatement, sql_types, ExpressionMethods, Identifiable, Insertable, PgConnection, QueryDsl, Queryable, RunQueryDsl, }; use uuid::Uuid...
} #[derive(Clone, Debug, Insertable)] #[table_name = "user_program_records"] pub struct NewUserProgramRecord<'a> { pub user_id: Uuid, pub program_spec_id: Uuid, pub source_code: &'a str, pub cpu_cycles: i32, pub instructions: i32, pub registers_used: i32, pub stacks_used: i32, } impl NewU...
columns::cpu_cycles, user_program_records::columns::instructions, user_program_records::columns::registers_used, user_program_records::columns::stacks_used, )) .get_results(conn)?; let reduced: Option<UserProgr...
function_block-function_prefixed
[ { "content": "/// Converts a Juniper (GraphQL) ID to a UUID. If the given string is not a\n\n/// valid UUID, then just return the nil UUID (all zeroes). This is useful in\n\n/// the API because we want to handle malformed UUIDs the same way we handle\n\n/// UUIDs that aren't in the database.\n\npub fn gql_id_to...
Rust
src/search/cli.rs
nickwb/fgr
14d23ebda8002b0a25823f1e5208e22faa97e5d0
use clap::{App, Arg}; use std::io::Write; use std::{env, fmt::Arguments}; use std::{io, path::PathBuf}; use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor}; pub struct InvokeOptions { search_root: PathBuf, follow_symlinks: bool, show_all: bool, paranoid: bool, verbose: bool, ...
use clap::{App, Arg}; use std::io::Write; use std::{env, fmt::Arguments}; use std::{io, path::PathBuf}; use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor}; pub struct InvokeOptions { search_root: PathBuf, follow_symlinks: bool, show_all: bool, paranoid: bool, verbose: bool, ...
pub struct MessageOutput { is_verbose: bool, stderr: StandardStream, } impl MessageOutput { pub fn new(opts: &InvokeOptions) -> Self { Self { is_verbose: opts.verbose(), stderr: StandardStream::stderr(ColorChoice::Auto), } } pub fn log_info(&mut self, mess...
r() { Ok(path) => Ok(path), Err(error) => Err(format!("Could not get current directory => {}", error)), }, Some(path_str) => match PathBuf::from(path_str).canonicalize() { Ok(path) => { if path.is_dir() { Ok(path) } ...
function_block-function_prefixed
[ { "content": "pub fn find_git_repositories(opts: &InvokeOptions) -> io::Result<()> {\n\n let output = &RefCell::new(MessageOutput::new(opts));\n\n\n\n let walk = WalkDir::new(opts.search_root())\n\n .follow_links(opts.follow_symlinks())\n\n .min_depth(0)\n\n .max_depth(opts.max_depth(...
Rust
parser/src/format/projection.rs
estuary/connectors
e0dd46c891cad7fce6553439a37b3c42d5e31248
use crate::config::ParseConfig; use caseless::Caseless; use doc::inference::{Exists, Shape}; use doc::{Pointer, Schema, SchemaIndexBuilder}; use json::schema::build::Error as SchemaBuildError; use json::schema::index::Error as SchemaIndexError; use json::schema::types; use serde_json::Value; use std::collections::BTre...
use crate::config::ParseConfig; use caseless::Caseless; use doc::inference::{Exists, Shape}; use doc::{Pointer, Schema, SchemaIndexBuilder}; use json::schema::build::Error as SchemaBuildError; use json::schema::index::Error as SchemaIndexError; use json::schema::types; use serde_json::Value; use std::collections::BTre...
let expected: &[(&[&str], Projection)] = &[ ( &[ "fieldA", "BeeLoc", "BEELOC", "fielda", "FIELDA", "locationa", "/locationa", ...
pes::Set>, must_exist: bool, ptr: &str) -> Projection { Projection { possible_types: ty, must_exist, target_location: Pointer::from_str(ptr), } }
function_block-function_prefixed
[ { "content": "pub fn build_elastic_schema(schema_json: &[u8]) -> Result<ESFieldType, Error> {\n\n build_elastic_schema_with_overrides(schema_json, &[])\n\n}\n\n\n", "file_path": "materialize-elasticsearch/schemabuilder/src/elastic_search_schema_builder.rs", "rank": 0, "score": 409868.50653248356 ...
Rust
astar_lib/src/lib.rs
ThePerkinrex/astar
51ca488c75cfcadd5880ec5d710f5024e9f02dc6
use std::{collections::HashMap, usize}; pub struct Graph<T>(Vec<GraphNode<T>>); impl<T> Graph<T> { pub fn new() -> Self { Self(Default::default()) } pub fn add_node(&mut self, data: T) -> usize { self.add_node_with_children(data, Vec::new()) } pub fn add_node_with_children(&mut s...
use std::{collections::HashMap, usize}; pub struct Graph<T>(Vec<GraphNode<T>>); impl<T> Graph<T> { pub fn new() -> Self { Self(Default::default()) } pub fn add_node(&mut self, data: T) -> usize { self.add_node_with_children(data, Vec::new()) } pub fn add_node_with_children(&mut s...
}
let mut index = None; for i in 0..self.elements.len() { let e = &self.elements[i]; if f(&e.0, &e.1) { index = Some(i); break } } index.map(|i| self.elements.remove(i)) }
function_block-function_prefix_line
[ { "content": "fn main() {\n\n println!(\"Hello, world!\");\n\n let mut g = Graph::new();\n\n let start = g.add_node('S');\n\n g.add_child(start, 7, 'A');\n\n let b = g.add_child(start, 5, 'B');\n\n let c = g.add_child(start, 2, 'C');\n\n let end = g.add_child(b, 2, 'E');\n\n g.add_childr...
Rust
arcon/src/buffer/event/mod.rs
arxra/arcon
bfaa73394f9a1d0261bfd4e6eda5335e9aba9e42
use crate::error::*; use arcon_allocator::{Alloc, AllocId, Allocator}; use crossbeam_utils::CachePadded; use std::sync::{ atomic::{AtomicBool, Ordering}, Arc, Mutex, }; #[derive(Debug)] pub struct EventBuffer<T> { ptr: *mut T, allocator: Arc<Mutex<Allocator>>, id: AllocId, ...
use crate::error::*; use arcon_allocator::{Alloc, AllocId, Allocator}; use crossbeam_utils::CachePadded; use std::sync::{ atomic::{AtomicBool, Ordering}, Arc, Mutex, }; #[derive(Debug)] pub struct EventBuffer<T> { ptr: *mut T, allocator: Arc<Mutex<Allocator>>, id: AllocId, ...
} #[inline] pub fn as_ptr(&self) -> *const T { self.buffer.as_ptr() } #[inline] pub fn reader(&self) -> BufferReader<T> { BufferReader { buffer: self.buffer.clone(), len: self.len, } } pub fn copy_from_writer(&mut self, o...
if let Some(v) = (*self.buffer).push(value, self.len) { Some(v) } else { self.len += 1; None }
if_condition
[]
Rust
src/sinks/kafka/sink.rs
f1shl3gs/vertex
8dc1e7e2291f80460a3baae2026aa61491ca0ec1
use std::time::Duration; use buffers::Acker; use event::encoding::{EncodingConfig, StandardEncodings}; use event::Event; use futures::{stream::BoxStream, StreamExt}; use log_schema::log_schema; use rdkafka::consumer::{BaseConsumer, Consumer}; use rdkafka::error::KafkaError; use rdkafka::producer::FutureProducer; use r...
use std::time::Duration; use buffers::Acker; use event::encoding::{EncodingConfig, StandardEncodings}; use event::Event; use futures::{stream::BoxStream, StreamExt}; use log_schema::log_schema; use rdkafka::consumer::{BaseConsumer, Consumer}; use rdkafka::error::KafkaError; use rdkafka::producer::FutureProducer; use r...
sink.run().await } } pub async fn health_check(config: KafkaSinkConfig) -> crate::Result<()> { trace!(message = "Health check started",); let client = config.to_rdkafka(KafkaRole::Consumer).unwrap(); let topic = match Template::try_from(config.topic) .context(TopicTemplate)? ....
let sink = input .filter_map(|event| futures_util::future::ready(request_builder.build_request(event))) .into_driver(service, self.acker);
assignment_statement
[ { "content": "pub fn encode_log(mut event: Event, encoding: &EncodingConfig<Encoding>) -> Option<Bytes> {\n\n encoding.apply_rules(&mut event);\n\n let log = event.into_log();\n\n\n\n let b = match encoding.codec() {\n\n Encoding::Json => serde_json::to_vec(&log),\n\n Encoding::Text => {\...
Rust
tor-circmgr/src/mgr/streams.rs
spring-epfl/arti-tweaks
834d3c1855974dc69885e189b4ad6f385924b840
use futures::stream::{Fuse, FusedStream, Stream, StreamExt}; use futures::task::{Context, Poll}; use pin_project::pin_project; use std::pin::Pin; #[derive(Debug, Clone, Eq, PartialEq)] pub(super) enum Source { Left, Right, } #[pin_project] pub(super) struct SelectBiased<S, T> { ...
use futures::stream::{Fuse, FusedStream, Stream, StreamExt}; use futures::task::{Context, Poll}; use pin_project::pin_project; use std::pin::Pin; #[derive(Debug, Clone, Eq, PartialEq)] pub(super) enum Source { Left, Right, } #[pin_project] pub(super) struct SelectBiased<S, T> { ...
}
async fn multiplex() { use futures::SinkExt; use Source::{Left as L, Right as R}; let (mut snd_l, rcv_l) = futures::channel::mpsc::channel(5); let (mut snd_r, rcv_r) = futures::channel::mpsc::channel(5); let mut s = select_biased(rcv_l, rcv_r); snd_l.send(1_usize).await...
function_block-full_function
[ { "content": "// Try connecting to ourself and sending a little data.\n\n//\n\n// NOTE: requires Ipv4 localhost.\n\nfn self_connect<R: Runtime>(runtime: R) -> IoResult<()> {\n\n let localhost = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0);\n\n let rt1 = runtime.clone();\n\n\n\n let listener = runtime.bloc...
Rust
prototype/collection/tensor/sparse/mod.rs
gitter-badger/tinychain
9ed5ed7f0194032ee0c71e236be4bf2a5ba9e384
use std::pin::Pin; use async_trait::async_trait; use futures::future::{self, TryFutureExt}; use futures::stream::{self, Stream, StreamExt, TryStreamExt}; use crate::class::Instance; use crate::collection::Collection; use crate::error; use crate::handler::*; use crate::scalar::value::number::*; use crate::scalar::{Met...
use std::pin::Pin; use async_trait::async_trait; use futures::future::{self, TryFutureExt}; use futures::stream::{self, Stream, StreamExt, TryStreamExt}; use crate::class::Instance; use crate::collection::Collection; use crate::error; use crate::handler::*; use crate::scalar::value::number::*; use crate::scalar::{Met...
f::Reduce> { let accessor = SparseReduce::new(self.clone(), axis, SparseTensor::product_all)?; Ok(SparseTensor { accessor }) } fn product_all(&self, txn: Txn) -> TCBoxTryFuture<Number> { Box::pin(async move { if self.all(&txn).await? { from_sparse(self.clone(...
write_value_at(txn_id, coord, value.clone()))) .try_buffer_unordered(2) .try_fold((), |_, _| future::ready(Ok(()))) .await } } async fn write_value_at(&self, txn_id: TxnId, coord: Coord, value: Number) -> TCResult<()> { self.accessor.write_value(t...
random
[ { "content": "fn unwrap_row(mut row: Vec<Value>) -> TCResult<(Coord, Number)> {\n\n let coord = unwrap_coord(&row[0..row.len() - 1])?;\n\n if let Some(value) = row.pop() {\n\n Ok((coord, value.try_into()?))\n\n } else {\n\n Err(error::internal(ERR_CORRUPT))\n\n }\n\n}\n\n\n", "file...
Rust
tests/integration.rs
m-cat/over
0a4d6ddaec531a77692a7ddf8213f9774d83fd67
#![allow(clippy::cognitive_complexity)] extern crate num_bigint; extern crate num_rational; extern crate num_traits; #[macro_use] extern crate over; mod errors; use num_traits::ToPrimitive; use over::{ obj::{Obj, Pair}, types::Type, value::Value, OverResult, ReferenceType, }; #[cfg(test)] use pretty_...
#![allow(clippy::cognitive_complexity)] extern crate num_bigint; extern crate num_rational; extern crate num_traits; #[macro_use] extern crate over; mod errors; use num_traits::ToPrimitive; use over::{ obj::{Obj, Pair}, types::Type, value::Value, OverResult, ReferenceType, }; #[cfg(test)] use pretty_...
#[test] fn any_type() -> OverResult<()> { let obj = Obj::from_file("tests/test_files/any_type.over")?; let arr1 = obj.get("arr1").unwrap(); let arr2 = arr![arr![arr![]], arr![arr![2]], arr![arr![]]]; assert_eq!(arr1.get_type(), Type::Arr(Box::new(arr2.inner_type()))); assert_eq!(arr1, arr2); ...
fn operations() -> OverResult<()> { let obj = Obj::from_file("tests/test_files/operations.over")?; assert_eq!(obj.get("mod1").unwrap(), int!(5)); assert_eq!(obj.get("mod2").unwrap(), int!(0)); assert_eq!(obj.get("arr1").unwrap(), arr![3, 4]); assert_eq!(obj.get("arr2").unwrap(), arr![3, 4]); a...
function_block-full_function
[]
Rust
src/extensions.rs
rusuly/mysql_cdc
06963a0f91aff3d8be2341008a2bdc03340fe1b8
use crate::constants::auth_plugin_names::AuthPlugin; use crate::constants::NULL_TERMINATOR; use crate::errors::Error; use crate::responses::error_packet::ErrorPacket; use crate::responses::response_type::ResponseType; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use sha1::Sha1; use sha2::{Digest, Sha256}...
use crate::constants::auth_plugin_names::AuthPlugin; use crate::constants::NULL_TERMINATOR; use crate::errors::Error; use crate::responses::error_packet::ErrorPacket; use crate::responses::response_type::ResponseType; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use sha1::Sha1; use sha2::{Digest, Sha256}...
pub fn read_bitmap_little_endian( cursor: &mut Cursor<&[u8]>, bits_number: usize, ) -> Result<Vec<bool>, io::Error> { let mut result = vec![false; bits_number]; let bytes_number = (bits_number + 7) / 8; for i in 0..bytes_number { let value = cursor.read_u8()?; for y in 0..8 { ...
pub fn read_len_enc_num(cursor: &mut Cursor<&[u8]>) -> Result<usize, Error> { let first_byte = cursor.read_u8()?; if first_byte < 0xFB { Ok(first_byte as usize) } else if first_byte == 0xFB { Err(Error::String( "Length encoded integer cannot be NULL.".to_string(), )) ...
function_block-full_function
[ { "content": "fn parse_string_array(cursor: &mut Cursor<&[u8]>) -> Result<Vec<String>, Error> {\n\n let mut result = Vec::new();\n\n while cursor.position() < cursor.get_ref().len() as u64 {\n\n let value = read_len_enc_str(cursor)?;\n\n result.push(value);\n\n }\n\n Ok(result)\n\n}\n\...
Rust
synapse_auto_compressor/src/state_saving.rs
QwertyNetworks-com/rust-synapse-compress-state
32e43da3e81fa8699f5d90d552ed34d7a6780e22
use anyhow::{bail, Result}; use log::trace; use synapse_compress_state::Level; use openssl::ssl::{SslConnector, SslMethod, SslVerifyMode}; use postgres::{fallible_iterator::FallibleIterator, types::ToSql, Client}; use postgres_openssl::MakeTlsConnector; pub fn connect_to_database(db_url: &str) -> Result<Client> { ...
use anyhow::{bail, Result}; use log::trace; use synapse_compress_state::Level; use openssl::ssl::{SslConnector, SslMethod, SslVerifyMode}; use postgres::{fallible_iterator::FallibleIterator, types::ToSql, Client}; use postgres_openssl::MakeTlsConnector; pub fn connect_to_database(db_url: &str) -> Result<Client> { ...
pub fn write_room_compressor_state( client: &mut Client, room_id: &str, level_info: &[Level], last_compressed: i64, ) -> Result<()> { let mut write_transaction = client.transaction()?; for (level_num, level) in level_info.iter().enumerate() { let level...
level_info.push(Level::restore(max_size, current_length, current_head)); prev_seen = level_num; } if level_info.is_empty() { return Ok(None); } Ok(Some((last_compressed.unwrap(), level_info))) }
function_block-function_prefix_line
[ { "content": "/// Finds the state_groups that are at the head of each compressor level\n\n/// NOTE this does not also retrieve their predecessors\n\n///\n\n/// # Arguments\n\n///\n\n/// * `client' - A Postgres client to make requests with\n\n/// * `levels' - The levels who's heads are being requested\n\nf...
Rust
src/iter/tournament_matches.rs
vityafx/toornament-rs
dab7fd41793809e9f43e3fe614b6ac69b7705608
use crate::*; use iter::games::GamesIter; pub struct TournamentMatchesIter<'a> { client: &'a Toornament, tournament_id: TournamentId, with_games: bool, } impl<'a> TournamentMatchesIter<'a> { pub fn new(client: &'a Toornament, tournament_id: TournamentId) -> TournamentMatchesIter { ...
use crate::*; use iter::games::GamesIter; pub struct TournamentMatchesIter<'a> { client: &'a Toornament, tournament_id: TournamentId, with_games: bool, } impl<'a> TournamentMatchesIter<'a> { pub fn new(client: &'a Toornament, tournament_id: TournamentId) -> TournamentMatchesIter { ...
}
pub fn update(mut self) -> Result<Match> { let matches = self.client.matches( self.tournament_id.clone(), Some(self.match_id.clone()), self.with_games, )?; let original = match matches.0.first() { Some(m) => m.to_owned(), None => { ...
function_block-full_function
[ { "content": "fn match_filter(f: MatchFilter) -> String {\n\n let mut out = Vec::new();\n\n if let Some(f) = f.featured {\n\n out.push(format!(\"featured={}\", if f { 1 } else { 0 }));\n\n }\n\n if let Some(r) = f.has_result {\n\n out.push(format!(\"has_result={}\", if r { 1 } else { 0...
Rust
src/git.rs
rask/wppr
b4fa94247a0271c1a65df8da0991c674b31b137f
use std::{ path::PathBuf, process::Command }; use config::GitConfig; pub struct Git { bin: String, config: GitConfig, working_directory: PathBuf } pub type GitResult = Result<bool, String>; impl Git { pub fn new(bin: String, cfg: GitConfig, cwd: PathBuf) -> Self { Git { ...
use std::{ path::PathBuf, process::Command }; use config::GitConfig; pub struct Git { bin: String, config: GitConfig, working_directory: PathBuf } pub type GitResult = Result<bool, String>; impl Git { pub fn new(bin: String, cfg: GitConfig, cwd: PathBuf) -> Self { Git { ...
} pub fn has_uncommited_changes(&self) -> GitResult { let mut cmd = self.get_base_cmd(); cmd.arg("status"); let output = cmd.output().expect("Error when trying to run git command: `git status`"); match output.status.success() { false => Err(format!("Could not ...
match output.status.success() { true => { self.set_repo_git_config() }, false => { Err(format!("Could not initialize new git repository: `{}`", String::from_utf8_lossy(&output.stderr))) } }
function_block-random_span
[ { "content": "/// Runs upgrades and gitifications on managed WordPress plugins.\n\npub fn run(config: RuntimeConfig) -> Result<bool, String> {\n\n let plugins: Vec<Plugin> = get_managed_plugins(&config);\n\n\n\n if plugins.len() < 1 {\n\n println!(\"Configuration has no plugins defined\");\n\n ...
Rust
packages/bindings-test/src/subspaces/query.rs
desmos-labs/desmos-bindings
121831e36ef287b30949101ab12038355901a1b8
#[cfg(test)] mod tests { use crate::chain_communication::DesmosCli; use crate::consts::{TEST_SUBSPACE, TEST_SUBSPACE_USER_GROUP, USER1_ADDRESS}; use cosmwasm_std::Addr; use desmos_bindings::subspaces::query::SubspacesQuery; use desmos_bindings::subspaces::query_types::{ QuerySubspaceResponse...
#[cfg(test)] mod tests { use crate::chain_communication::DesmosCli; use crate::consts::{TEST_SUBSPACE, TEST_SUBSPACE_USER_GROUP, USER1_ADDRESS}; use cosmwasm_std::Addr; use desmos_bindings::subspaces::query::SubspacesQuery; use desmos_bindings::subspaces::query_types::{ QuerySubspaceResponse...
}
let response: QueryUserPermissionsResponse = desmos_cli.wasm_query(&contract_address, &query).to_object(); assert_eq!(31, response.permissions); }
function_block-function_prefix_line
[ { "content": "/// Functions that mocks the subspaces query responses.\n\npub fn mock_subspaces_query_response(query: &SubspacesQuery) -> ContractResult<Binary> {\n\n let response = match query {\n\n SubspacesQuery::Subspaces { .. } => {\n\n let subspace = MockSubspacesQueries::get_mock_subs...
Rust
day-07/src/main.rs
justahero/advent-of-code-2020
97e44ff2547e837f28f536f22897529045f8f003
use anyhow::anyhow; use std::collections::HashMap; use petgraph::{Direction, EdgeDirection, graph::Graph, graph::NodeIndex, visit::Bfs}; type BagGraph = Graph<Bag, i32>; #[derive(Debug, Clone)] struct Bag { pub color: String, pub contents: Vec<(i32, String)>, } impl Bag { pub fn new(color: String, conte...
use anyhow::anyhow; use std::collections::HashMap; use petgraph::{Direction, EdgeDirection, graph::Graph, graph::NodeIndex, visit::Bfs}; type BagGraph = Graph<Bag, i32>; #[derive(Debug, Clone)] struct Bag { pub color: String, pub contents: Vec<(i32, String)>, } impl Bag { pub fn new(color: String, conte...
#[test] fn test_count_bag_colors_example() { let lines = rules(r#" shiny gold bags contain 2 dark red bags. dark red bags contain 2 dark orange bags. dark orange bags contain 2 dark yellow bags. dark yellow bags contain 2 dark green bags. dar...
fn test_count_bag_colors_nested() { let lines = rules(r#" light red bags contain 1 bright white bag. bright white bags contain 3 dark orange bags, 4 dotted black bags. dark orange bags contain 1 muted yellow bag, 2 vibrant plum bags. muted yellow bags contain 2 sh...
function_block-full_function
[ { "content": "/// Parses all rules and messages\n\n/// For now return all rules and the messages as tuple\n\nfn parse(content: &str) -> anyhow::Result<(HashMap<u64, Rule>, Vec<String>)> {\n\n let mut rules = HashMap::new();\n\n let mut messages = Vec::new();\n\n\n\n content\n\n .lines()\n\n ...
Rust
egui-demo/src/main.rs
Ar37-rs/demos
b77283496f4076863cc16c059f1e1721932d3ea1
use egui_backend::{ egui, fltk::{enums::*, prelude::*, *}, gl, DpiScaling, }; use fltk_egui as egui_backend; use std::rc::Rc; use std::{cell::RefCell, time::Instant}; const SCREEN_WIDTH: u32 = 800; const SCREEN_HEIGHT: u32 = 600; fn main() { let a = app::App::default().with_scheme(app::Scheme::Gtk); ...
use egui_backend::{ egui, fltk::{enums::*, prelude::*, *}, gl, DpiScaling, }; use fltk_egui as egui_backend; use std::rc::Rc; use std::{cell::RefCell, time::Instant}; const SCREEN_WIDTH: u32 = 800; const SCREEN_HEI
age += 1; } ui.label(format!("Hello '{}', age {}", name, age)); ui.separator(); if ui .button("Quit?") .on_hover_cursor(egui::CursorIcon::PointingHand) .clicked() { quit = true; }...
GHT: u32 = 600; fn main() { let a = app::App::default().with_scheme(app::Scheme::Gtk); app::get_system_colors(); app::set_font_size(20); let mut main_win = window::Window::new(100, 100, SCREEN_WIDTH as _, SCREEN_HEIGHT as _, None); let mut glut_win = window::GlWindow::new(5, 5, main_win.w() - 200, ...
random
[ { "content": "pub fn get_proc_address(win: &window::GlWindow, name: &str) -> *mut c_void {\n\n win.get_proc_address(name) as _\n\n}\n\n\n", "file_path": "libmpv/src/main.rs", "rank": 7, "score": 27188.836802598013 }, { "content": "# egui-demo\n\n\n\nUse fltk as a backend for egui using th...
Rust
src/components/radio.rs
veeso/tui-realm-stdlib
1501393e8b2c0574dcae75a19dbfe4749c125601
/** * MIT License * * termscp - Copyright (c) 2021 Christian Visintin * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights ...
/** * MIT License * * termscp - Copyright (c) 2021 Christian Visintin * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights ...
pub fn value(mut self, i: usize) -> Self { self.attr( Attribute::Value, AttrValue::Payload(PropPayload::One(PropValue::Usize(i))), ); self } fn is_rewind(&self) -> bool { self.props .get_or(Attribute::Rewind, AttrValue::Flag(fal...
pub fn choices<S: AsRef<str>>(mut self, choices: &[S]) -> Self { self.attr( Attribute::Content, AttrValue::Payload(PropPayload::Vec( choices .iter() .map(|x| PropValue::Str(x.as_ref().to_string())) .collect(), ...
function_block-full_function
[ { "content": "/// ### use_or_default_styles\n\n///\n\n/// Returns the styles to be used; in case in span are default, use props'.\n\n/// The values returned are `(foreground, background, modifiers)`\n\npub fn use_or_default_styles(props: &Props, span: &TextSpan) -> (Color, Color, Modifier) {\n\n (\n\n ...
Rust
src/common/resp_execution.rs
y-projects/undermoon
d592f1c63080d3b3294fd6be798bb9291014bf4d
use crate::common::utils::pretty_print_bytes; use crate::protocol::{ BinSafeStr, OptionalMulti, RedisClient, RedisClientError, RedisClientFactory, Resp, RespVec, }; use atomic_option::AtomicOption; use futures::channel::oneshot; use futures::{select, Future, FutureExt}; use std::pin::Pin; use std::str; use std::syn...
use crate::common::utils::pretty_print_bytes; use crate::protocol::{ BinSafeStr, OptionalMulti, RedisClient, RedisClientError, RedisClientFactory, Resp, RespVec, }; use atomic_option::AtomicOption; use futures::channel::oneshot; use futures::{select, Future, FutureExt}; use std::pin::Pin; use std::str; use std::syn...
e()); let res = keep_sending_cmd( &mut client, OptionalMulti::Single(vec![]), interval, retry_handle_func, ) .await; assert!(res.is_err()); assert_eq!(counter.count.load(Ordering::SeqCst), 3); } #[tokio::test] async fn ...
error!( "failed to send commands {:?} {:?}. Try again.", err, debug_cmd ); } } tokio::time::sleep(interval).await; } } pub async fn keep_connecting_and_sending_cmd<F: RedisClientFactory, Func>( client_factory: Arc<F>, addr...
random
[ { "content": "pub fn resp_to_buf(buf: &mut Vec<u8>, resp: &RespVec) -> io::Result<usize> {\n\n encode_resp(buf, resp)\n\n}\n\n\n", "file_path": "src/protocol/encoder.rs", "rank": 1, "score": 283247.8273549658 }, { "content": "pub fn parse_indexed_resp(buf: &mut BytesMut) -> Result<Indexed...
Rust
src/rawdata.rs
deepmesa/criterion-charts-tsx
3ca000c916d31455332807530e626d3729a96318
use std::collections::BTreeMap; use std::collections::BTreeSet; use crate::infomap::SeriesInfoMap; use crate::timeunit::TimeUnit; use crate::tsxdata::MeanTimeData; use crate::tsxdata::TotalTimeData; use crate::tsxdata::TsxData; use crate::FnName; use crate::GroupName; use crate::IterCount; use crate::Measure; use crat...
use std::collections::BTreeMap; use std::collections::BTreeSet; use crate::infomap::SeriesInfoMap; use crate::timeunit::TimeUnit; use crate::tsxdata::MeanTimeData; use crate::tsxdata::TotalTimeData; use crate::tsxdata::TsxData; use crate::FnName; use crate::GroupName; use crate::IterCount; use crate::Measure; use crat...
pub fn insert( &mut self, function: FnName, measurement: Measure, iter_count: IterCount, time_unit: TimeUnit, ) { let function_key = function.to_ascii_lowercase(); match self.fn_map.get_mut(&function_key) { None => { let mut c_...
nData { fn_map: BTreeMap::<FnName, CriterionDataSet>::new(), fn_names: BTreeSet::<FnName>::new(), } }
function_block-function_prefixed
[ { "content": "struct TsxYDataPoint(Measure, YIndex);\n\n\n\npub struct TsxDataSet {\n\n points: BTreeMap<IterCount, Vec<TsxYDataPoint>>,\n\n uv_analysis: BTreeMap<YIndex, UvAnalysis>,\n\n bv_analysis: BTreeMap<YIndex, BvAnalysis>,\n\n time_unit: Option<TimeUnit>,\n\n trendlines: bool,\n\n}\n\n\n\...
Rust
kernel/device_manager/src/lib.rs
ZetaNumbers/Theseus
21da16cffe3e516e2bc710c66d8f7584da80c186
#![no_std] #![feature(trait_alias)] #[macro_use] extern crate log; extern crate spin; extern crate event_types; extern crate e1000; extern crate memory; extern crate apic; extern crate acpi; extern crate keyboard; extern crate pci; extern crate mouse; extern crate storage_manager; extern crate network_manager; extern ...
#![no_std] #![feature(trait_alias)] #[macro_use] extern crate log; extern crate spin; extern crate event_types; extern crate e1000; extern crate memory; extern crate apic; extern crate acpi; extern crate keyboard; extern crate pci; extern crate mouse; extern crate storage_manager; extern crate network_manager; extern ...
pub struct FatFsAdapter<IO>(IO); impl<IO> FatFsAdapter<IO> { pub fn new(io: IO) -> FatFsAdapter<IO> { FatFsAdapter(io) } } impl<IO> fatfs::IoBase for FatFsAdapter<IO> { type Error = FatFsIoErrorAdapter; } impl<IO> fatfs::Read for FatFsAdapter<IO> where IO: bare_io::Read { fn read(&mut self, buf: &mut [u8...
let ixgbe_interface = EthernetNetworkInterface::new_ipv4_interface( ixgbe_nic_ref, DEFAULT_LOCAL_IP, &DEFAULT_GATEWAY_IP )?; add_to_network_interfaces(ixgbe_interface); } if network_manager::NETWORK_INTERFACES.lock().is_empty() { warn!("Note: n...
function_block-function_prefix_line
[ { "content": "/// Allocates memory for the NIC registers\n\n/// \n\n/// # Arguments \n\n/// * `dev`: reference to pci device \n\n/// * `mem_base`: starting physical address of the device's memory mapped registers\n\npub fn allocate_device_register_memory(dev: &PciDevice, mem_base: PhysicalAddress) -> Result<Map...
Rust
gstreamer-base/src/base_parse.rs
JohnBox/gstreamer-rs
ed6fadf35160df3fd597c78c75278c68ebe59078
use crate::BaseParse; use crate::BaseParseFrame; use glib::prelude::*; use glib::translate::*; use gst::FormattedValue; use std::convert::TryFrom; use std::mem; pub trait BaseParseExtManual: 'static { #[doc(alias = "get_sink_pad")] fn sink_pad(&self) -> gst::Pad; #[doc(alias = "get_src_pad")] fn src_...
use crate::BaseParse; use crate::BaseParseFrame; use glib::prelude::*; use glib::translate::*; use gst::FormattedValue; use std::convert::TryFrom; use std::mem; pub trait BaseParseExtManual: 'static { #[doc(alias = "get_sink_pad")] fn sink_pad(&self) -> gst::Pad; #[doc(alias = "get_src_pad")] fn src_...
} else { None } } } fn finish_frame( &self, frame: BaseParseFrame, size: u32, ) -> Result<gst::FlowSuccess, gst::FlowError> { unsafe { try_from_glib(ffi::gst_base_parse_finish_frame( self.as_ref().t...
Some(gst::GenericFormattedValue::new( dest_format, dest_val.assume_init(), ))
call_expression
[ { "content": "pub trait PluginFeatureExtManual: Sized + 'static {\n\n #[doc(alias = \"get_rank\")]\n\n #[doc(alias = \"gst_plugin_feature_get_rank\")]\n\n fn rank(&self) -> Rank;\n\n #[doc(alias = \"gst_plugin_feature_set_rank\")]\n\n fn set_rank(&self, rank: Rank);\n\n #[doc(alias = \"gst_plu...
Rust
src/embedded_flash/syscall.rs
epita-cs2/OpenSK
eb65c4f07f747694f9e96726acee1a65badb8e03
use alloc::vec::Vec; use libtock_core::syscalls; use persistent_store::{Storage, StorageError, StorageIndex, StorageResult}; const DRIVER_NUMBER: usize = 0x50003; mod command_nr { pub const GET_INFO: usize = 1; pub mod get_info_nr { pub const WORD_SIZE: usize = 0; pub const PAGE_SIZE: usize ...
use alloc::vec::Vec; use libtock_core::syscalls; use persistent_store::{Storage, StorageError, StorageIndex, StorageResult}; const DRIVER_NUMBER: usize = 0x50003; mod command_nr { pub const GET_INFO: usize = 1; pub mod get_info_nr { pub const WORD_SIZE: usize = 0; pub const PAGE_SIZE: usize ...
fn is_word_aligned(&self, x: usize) -> bool { x & (self.word_size - 1) == 0 } fn is_page_aligned(&self, x: usize) -> bool { x & (self.page_size - 1) == 0 } } impl Storage for SyscallStorage { fn word_size(&self) -> usize { self.word_size } fn page_size(&self) -> ...
syscall.page_size.is_power_of_two() || !syscall.is_word_aligned(syscall.page_size) { return Err(StorageError::CustomError); } for i in 0..memop(memop_nr::STORAGE_CNT, 0)? { let storage_ptr = memop(memop_nr::STORAGE_PTR, i)?; let max_storage_len = m...
function_block-function_prefix_line
[ { "content": "pub fn fill_buffer(buf: &mut [u8]) -> bool {\n\n let buf_len = buf.len();\n\n\n\n let result = syscalls::allow(DRIVER_NUMBER, allow_nr::SHARE_BUFFER, buf);\n\n if result.is_err() {\n\n return false;\n\n }\n\n\n\n let is_filled = Cell::new(false);\n\n let mut is_filled_alar...