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
rs/canonical_state/src/test_visitors.rs
3cL1p5e7/ic
2b6011291d900454cedcf86ec41c8c1994fdf7d9
use crate::visitor::{Control, Visitor}; use ic_utils::rle::DebugBlob; use std::fmt; pub(crate) struct NoopVisitor; impl Visitor for NoopVisitor { type Output = (); fn start_subtree(&mut self) -> Result<(), ()> { Ok(()) } fn enter_edge(&mut self, _name: &[u8]) -> Result<Control, ()> { ...
use crate::visitor::{Control, Visitor}; use ic_utils::rle::DebugBlob; use std::fmt; pub(crate) struct NoopVisitor; impl Visitor for NoopVisitor { type Output = (); fn start_subtree(&mut self) -> Result<(), ()> { Ok(()) } fn enter_edge(&mut self, _name: &[u8]) -> Result<Control, ()> { ...
self.trace.push(TraceEntry::VisitNum(num)); self.nested_visitor .visit_num(num) .map_err(|out| (self.trace.clone(), out)) } fn finish(self) -> Self::Output { (self.trace, self.nested_visitor.finish()) } } pub(crate) struct PathVisitor { path: Vec<Vec...
for TraceEntry { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::StartSubtree => write!(f, "start"), Self::EnterEdge(v) => write!(f, "edge {:?}", DebugBlob(&v[..])), Self::EndSubtree => write!(f, "end"), Self::VisitBlob(v) => writ...
random
[]
Rust
rust/pact_mock_server_cli/src/server.rs
tienvx/pact-reference
65a64ff4ee2c0906bcc174b3cab0049981621916
use std::{ net::TcpListener, process, sync::mpsc, thread, time::Duration }; use std::convert::Infallible; use std::net::{IpAddr, SocketAddr}; use futures::channel::oneshot::channel; use hyper::server::Server; use hyper::service::make_service_fn; use log::*; use maplit::*; use serde_json::{self, json, Value};...
use std::{ net::TcpListener, process, sync::mpsc, thread, time::Duration }; use std::convert::Infallible; use std::net::{IpAddr, SocketAddr}; use futures::channel::oneshot::channel; use hyper::server::Server; use hyper::service::make_service_fn; use log::*; use maplit::*; use serde_json::{self, json, Value};...
sert("subpath".to_string(), paths[1].clone()); paths[1] == "verify" } else { true } } Err(_) => false } } else { false } }), render_response: callback(&|context, _| { debug!("mock_server_resource -> render_...
{ guard.start_tls_mock_server(mock_server_id.clone(), pact, get_next_port(options.base_port), &tls_config, config) }) } else { debug!("Starting mock server with id {}", &mock_server_id); guard.start_mock_server(mock_server_id.clone(), pact, get_next_port(...
random
[ { "content": "/// Process a JSON body with embedded matching rules and generators\n\npub fn process_json_value(body: &Value, matching_rules: &mut MatchingRuleCategory, generators: &mut Generators) -> String {\n\n match body {\n\n Value::Object(ref map) => process_object(map, matching_rules, generators, DocP...
Rust
src/okta/models/okta_sign_on_policy_rule_signon_actions.rs
jonathanmorley/okra-rs
4efe9aef5e89eda1f0f28e3696589e98bc703774
#[allow(unused_imports)] use serde_json::Value; #[allow(unused_imports)] use std::borrow::Borrow; #[allow(unused_imports)] use super::*; #[derive(Debug, Default, Serialize, Deserialize, PartialEq)] pub struct r#OktaSignOnPolicyRuleSignonActions { #[serde(rename = "access", skip_serializing_if = "Option::is_none"...
#[allow(unused_imports)] use serde_json::Value; #[allow(unused_imports)] use std::borrow::Borrow; #[allow(unused_imports)] use super::*; #[derive(Debug, Default, Serialize, Deserialize, PartialEq)] pub struct r#OktaSignOnPolicyRuleSignonActions { #[serde(rename = "access", skip_serializing_if = "Option::is_none"...
lf { self.r#remember_device_by_default = Some(r#remember_device_by_default); self } pub fn r#remember_device_by_default(&self) -> Option<&bool> { self.r#remember_device_by_default.as_ref().map(|x| x.borrow()) } pub fn reset_remember_device_by_default(&mut self) { self.r...
vice_by_default = Some(r#remember_device_by_default); } pub fn with_remember_device_by_default(mut self, r#remember_device_by_default: bool) -> Se
random
[ { "content": "fn main() {\n\n openapi_codegen::client(\"openapi.yaml\", \"src/okta\", true).unwrap();\n\n}\n", "file_path": "build.rs", "rank": 0, "score": 52013.637571350664 }, { "content": "pub trait LoginApi {\n\n fn login_default(&self) -> Result<reqwest::Response, Error>;\n\n f...
Rust
examples/sse_chat.rs
kenorld/salvo
5bd71671ef64ea52dbb90adf0b7125092c8c2898
use futures; use futures::StreamExt; use once_cell::sync::Lazy; use salvo::prelude::*; use std::collections::HashMap; use std::sync::{ atomic::{AtomicUsize, Ordering}, Arc, Mutex, }; use tokio::sync::mpsc; use tokio_stream::wrappers::UnboundedReceiverStream; use tracing_subscriber; use tracing_subscriber::fmt::...
use futures; use futures::StreamExt; use once_cell::sync::Lazy; use salvo::prelude::*; use std::collections::HashMap; use std::sync::{ atomic::{AtomicUsize, Ordering}, Arc, Mutex, }; use tokio::sync::mpsc; use tokio_stream::wrappers::UnboundedReceiverStream; use tracing_subscriber; use tracing_subscriber::fmt::...
= data; chat.appendChild(line); } sse.onopen = function() { chat.innerHTML = "<p><em>Connected!</em></p>"; } var user_id; sse.addEventListener("user", function(msg) { user_id = msg.data; }); sse.onmessage = function(msg) { ...
c::unbounded_channel(); let rx = UnboundedReceiverStream::new(rx); tx.send(Message::UserId(my_id)) .unwrap(); ONLINE_USERS.lock().unwrap().insert(my_id, tx); let stream = rx.map(|msg| match msg { Message::UserId(my_id) => Ok::<_, salvo_core::Error>(SseEvent::default...
random
[ { "content": "/// Our state of currently connected users.\n\n///\n\n/// - Key is their id\n\n/// - Value is a sender of `salvo::ws::Message`\n\ntype Users = Arc<RwLock<HashMap<usize, mpsc::UnboundedSender<Result<Message, salvo::Error>>>>>;\n\n\n\n// Keep track of all connected users, key is usize, value\n\n// i...
Rust
src/memory.rs
mdm/ronald
32724df6226b8d63971e3796f1c2fadd3fb93638
use std::collections::HashMap; use std::fs::*; use std::io; use std::cell::RefCell; use std::rc::Rc; pub type MemoryShared = Rc<RefCell<Memory>>; pub trait Read { fn read_byte(&self, address: usize) -> u8; fn read_word(&self, address: usize) -> u16 { let low_byte = self.read_byte(address); l...
use std::collections::HashMap; use std::fs::*; use std::io; use std::cell::RefCell; use std::rc::Rc; pub type MemoryShared = Rc<RefCell<Memory>>; pub trait Read { fn read_byte(&self, address: usize) -> u8; fn read_word(&self, address: usize)
} } pub fn from_file(size: usize, path: &str, offset: usize) -> RAM { let mut ram = RAM::new(size); let rom = read(path).unwrap_or_else(|_| panic!("ROM file \"{}\" could not be read.", path)); for (i, byte) in rom.into_iter().enumerate() { ram.write_by...
-> u16 { let low_byte = self.read_byte(address); let high_byte = self.read_byte(address + 1); u16::from_le_bytes([low_byte, high_byte]) } } pub trait Write { fn write_byte(&mut self, address: usize, value: u8); fn write_word(&mut self, address: usize, value: u16) { let byte...
random
[ { "content": "pub trait System {\n\n fn emulate(&mut self) -> u8;\n\n fn get_screen(&self) -> screen::ScreenShared;\n\n fn get_keyboard(&self) -> keyboard::KeyboardShared;\n\n fn activate_debugger(&mut self);\n\n fn load_disk(&mut self, drive: usize, filename: &str);\n\n}\n\n\n\npub struct CPC464...
Rust
src/models/manga.rs
Egomination/mangapplizer_backend
4b6140b13e3a27797bc2dcf017f8a384ac02b082
use crate::errors::MangapplizerError; use crate::models::{ genre, genre_lists, json_manga, media, relation, series, staff, tag, tag_lists, }; use crate::schema::mangas; use diesel::PgConnection; #[derive( Queryable, QueryableByName, Identifiable, Associations, De...
use crate::errors::MangapplizerError; use crate::models::{ genre, genre_lists, json_manga, media, relation, series, staff, tag, tag_lists, }; use crate::schema::mangas; use diesel::PgConnection; #[derive( Queryable, QueryableByName, Identifiable, Associations, De...
pub fn len(&self) -> usize { self.0.iter().len() } pub fn is_empty(&self) -> bool { self.len() == 0 } } impl<'a> NewManga<'a> { pub fn create( &self, connection: &PgConnection, ) -> Result<Manga, MangapplizerError> { use diesel::RunQueryDsl; d...
ainto_tsquery(search))) } let result = query .select(MANGAS_COLUMNS) .load::<Manga>(connection) .expect("Error Searching Manga"); MangaList(result) }
function_block-function_prefixed
[ { "content": "pub fn establish_connection() -> PgPool {\n\n dotenv().ok();\n\n\n\n let database_url =\n\n env::var(\"DATABASE_URL\").expect(\"DATABASE_URL must be set!\");\n\n init_pool(&database_url).expect(\"Failed to create database connection pool\")\n\n}\n", "file_path": "src/db_connect...
Rust
packages/polar/sample-project/packages/cargo_common/src/tokens.rs
dldjwls3/polar
e8326d92ff8b7e36d517525db435b625a5f79864
use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use crate::contract::Contract; use cosmwasm_std::{Binary, HumanAddr, StdError, StdResult, Uint128}; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct InitHook { pub msg: Binary, pub contract_addr: HumanAddr, pub...
use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use crate::contract::Contract; use cosmwasm_std::{Binary, HumanAddr, StdError, StdResult, Uint128}; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct InitHook { pub msg: Binary, pub contract_addr: HumanAddr, pub...
} if !is_valid_symbol(&self.symbol) { return Err(StdError::generic_err( "Ticker symbol is not in expected format [a-zA-Z\\-]{3,12}", )); } if self.decimals > 18 { return Err(StdError::generic_err("Decimals must not exceed 18")); } ...
date(&self) -> StdResult<()> { if !is_valid_name(&self.name) { return Err(StdError::generic_err( "Name is not in the expected format (3-50 UTF-8 bytes)", ));
function_block-random_span
[ { "content": "pub fn config<S: Storage>(storage: &mut S) -> Singleton<S, State> {\n\n singleton(storage, CONFIG_KEY)\n\n}\n\n\n", "file_path": "examples/hello-world/contracts/src/state.rs", "rank": 0, "score": 170980.77985329565 }, { "content": "pub fn config<S: Storage>(storage: &mut S) ...
Rust
tests/encoding.rs
rapiditynetworks/xero-rs
234eb1c7bab560e7e5f2bed40223ee16f74ff6f4
extern crate bigdecimal; extern crate chrono; extern crate serde_json; extern crate xero; use bigdecimal::BigDecimal; use chrono::NaiveDate; use serde_json as json; use xero::accounting::*; use xero::encoding::XmlSerializable; fn _xml(example: &'static str) -> Option<String> { if example.chars().next() == Some('\...
extern crate bigdecimal; extern crate chrono; extern crate serde_json; extern crate xero; use bigdecimal::BigDecimal; use chrono::NaiveDate; use serde_json as json; use xero::accounting::*; use xero::encoding::XmlSerializable; fn _xml(example: &'static str) -> Option<String> { if example.chars().next() == Some('\...
#[test] fn serialize_invoice_params() { let mut invoice = InvoiceParams::default(); invoice.contact = ContactIdParams{contact_id: "eaa28f49-6028-4b6e-bb12-d8f6278073fc"}; assert_eq!(invoice.to_xml().ok(), _xml(" <Type>ACCREC</Type> <Contact> <ContactID>eaa28f49-6028-4b6e-bb12-d8f6278073fc</ContactID> <...
0.0000, "PaymentType": "ACCRECPAYMENT", "Status": "AUTHORISED", "IsReconciled": true }"#; let payment: Payment = json::from_str(&data).unwrap(); assert_eq!(payment, Payment{ payment_id: String::from("payment-id"), amount: BigDecimal::from(0).with_scale(4), p...
function_block-function_prefixed
[ { "content": "fn main() {\n\n let consumer_key = env::var(\"XERO_CONSUMER_KEY\").expect(\"Environment XERO_CONSUMER_KEY must be provided\");\n\n let private_key = env::var(\"RSA_PRIVATE_KEY_PEM\").expect(\"Environment RSA_PRIVATE_KEY_PEM must be provided\");\n\n let keypair = xero::PKey::from_rsa(xero:...
Rust
northstar/src/runtime/mount.rs
inorick/northstar
03daa69db52b3941baa6fdffdd60600426775f32
use super::{ config::Config, device_mapper as dm, device_mapper::{self}, key::PublicKey, loopdev::LoopControl, state::Npk, }; use crate::{npk, npk::dm_verity::VerityHeader}; use bitflags::_core::str::Utf8Error; use floating_duration::TimeAsFloat; use futures::{future::ready, Future, FutureExt}...
use super::{ config::Config, device_mapper as dm, device_mapper::{self}, key::PublicKey, loopdev::LoopControl, state::Npk, }; use crate::{npk, npk::dm_verity::VerityHeader}; use bitflags::_core::str::Utf8Error; use floating_duration::TimeAsFloat; use futures::{future::ready, Future, FutureExt}...
iled to wait for removal of {}", &path.display()))) .and_then(|r| r) }
}) } pub(super) async fn umount( &self, target: &Path, verity_device: Option<&Path>, ) -> Result<(), Error> { task::block_in_place(|| nix::mount::umount(target).map_err(Error::Os))?; if let Some(verity_device) = verity_device { debug!("Waiting for dm dev...
random
[ { "content": "fn sign_npk(key: &Path, fsimg: &Path, manifest: &Manifest) -> Result<String, Error> {\n\n let fsimg_size = fs::metadata(&fsimg)\n\n .map_err(|e| Error::Io {\n\n context: format!(\"Failed to read file size: '{}'\", &fsimg.display()),\n\n error: e,\n\n })?\n\n ...
Rust
simulation/src/lib.rs
palantir/conjure-rust-runtime
2a37ba33b0b504d4dc779dc66b8bfffe6a8a0026
#![cfg(test)] use crate::harness::Harness; use crate::server::Endpoint; use crate::simulation::{Simulation, SimulationBuilder1, TokioClock}; use rand_pcg::Pcg64; use std::sync::Arc; use tokio::time::Duration; use witchcraft_metrics::Meter; mod harness; mod metrics; mod recorder; mod server; mod simulation; fn main(...
#![cfg(test)] use crate::harness::Harness; use crate::server::Endpoint; use crate::simulation::{Simulation, SimulationBuilder1, TokioClock}; use rand_pcg::Pcg64; use std::sync::Arc; use tokio::time::Duration; use witchcraft_metrics::Meter; mod harness; mod metrics; mod recorder; mod server; mod simulation; fn main(...
fn all_nodes_500(s: SimulationBuilder1) -> Simulation { s.server(|s| { s.name("node1") .handler(|h| h.response(500).response_time(Duration::from_millis(600))) .until(Duration::from_secs(10), "revert badness") .handler(|h| h.response(200).response_time(Duration::from_mil...
h.response(200) .linear_response_time(Duration::from_millis(60), capacity) }) }) .server(|s| { s.name("fast_then_slow_then_fast") .handler(|h| { h.response(200) .linear_response_time(Duration::from_millis(60), capacity) ...
function_block-function_prefix_line
[ { "content": "pub fn active_requests(registry: &MetricRegistry, server: &str) -> Arc<Counter> {\n\n registry.counter(MetricId::new(\"activeRequests\").with_tag(\"server\", server.to_string()))\n\n}\n\n\n", "file_path": "simulation/src/metrics.rs", "rank": 4, "score": 171217.01342981166 }, { ...
Rust
crypto-ws-client/tests/kraken.rs
crypto-crawler/crypto-crawler-rs
e13e5493b530a7211479987c8b9209157ebdbaa2
#[macro_use] mod utils; #[cfg(test)] mod kraken_spot { use crypto_ws_client::{KrakenSpotWSClient, WSClient}; #[tokio::test(flavor = "multi_thread")] async fn subscribe() { gen_test_code!( KrakenSpotWSClient, subscribe, &vec![ ("trade".to_string()...
#[macro_use] mod utils; #[cfg(test)] mod kraken_spot { use crypto_ws_client::{KrakenSpotWSClient, WSClient}; #[tokio::test(flavor = "multi_thread")] async fn subscribe() { gen_test_code!( KrakenSpotWSClient, subscribe, &vec![ ("trade".to_string()...
KrakenFuturesWSClient, subscribe_orderbook, &vec!["FI_XBTUSD_220624".to_string()] ); } }
send, &vec![ r#"{"event":"subscribe","feed":"trade","product_ids":["FI_XBTUSD_220624"]}"# .to_string() ] ); } #[tokio::test(flavor = "multi_thread")] async fn subscribe_trade() { gen_test_code!( KrakenFuture...
random
[ { "content": "fn fetch_symbols(kind: &str) -> Result<Vec<String>> {\n\n let all_markets = fetch_raw_markets(kind)?;\n\n let all_symbols: Vec<String> = all_markets.into_iter().map(|x| x.instrument_name).collect();\n\n Ok(all_symbols)\n\n}\n\n\n\npub(super) fn fetch_inverse_future_symbols() -> Result<Vec...
Rust
src/net/tcp/stream.rs
cssivision/awak
0c0d15b15ef992cea1e0bdfd6585ac2f3584d9cb
use std::io; use std::net::{self, Shutdown, SocketAddr, ToSocketAddrs}; use std::pin::Pin; use std::task::{Context, Poll}; use futures_util::io::{AsyncRead, AsyncWrite, IoSlice, IoSliceMut}; use socket2::{Domain, Protocol, Socket, Type}; use crate::io::Async; #[derive(Debug)] pub struct TcpStream { inner: Async<...
use std::io; use std::net::{self, Shutdown, SocketAddr, ToSocketAddrs}; use std::pin::Pin; use std::task::{Context, Poll}; use futures_util::io::{AsyncRead, AsyncWrite, IoSlice, IoSliceMut}; use socket2::{Domain, Protocol, Socket, Type}; use crate::io::Async; #[derive(Debug)] pub struct TcpStream { inner: Async<...
ite_vectored(cx, bufs) } fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> { Pin::new(&mut self.0).poll_flush(cx) } fn poll_close(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> { Poll::Ready(self.0.shutdown(Shutdown::Write)) }...
t Self>, cx: &mut Context<'_>, bufs: &[IoSlice<'_>], ) -> Poll<io::Result<usize>> { Pin::new(&mut self.0).poll_wr
function_block-random_span
[ { "content": "fn poll_future<T>(cx: &mut Context<'_>, fut: impl Future<Output = T>) -> Poll<T> {\n\n pin_mut!(fut);\n\n fut.poll(cx)\n\n}\n\n\n\npub(crate) struct Timer {\n\n deadline: Instant,\n\n key: usize,\n\n waker: Option<Waker>,\n\n}\n\n\n\nimpl Timer {\n\n pub fn new(deadline: Instant)...
Rust
crates/core/src/tukui_api.rs
mmhand123/ajour
7c06055e06f5980335da1e4717b89bf2428aadd5
use crate::{ addon::Addon, config::Flavor, error::ClientError, network::request_async, utility::{regex_html_tags_to_newline, regex_html_tags_to_space, truncate}, Result, }; use async_std::sync::Arc; use isahc::config::RedirectPolicy; use isahc::prelude::*; use serde::Deserialize; #[derive(Clone...
use crate::{ addon::Addon, config::Flavor, error::ClientError, network::request_async, utility::{regex_html_tags_to_newline, regex_html_tags_to_space, truncate}, Result, }; use async_std::sync::Arc; use isahc::config::RedirectPolicy; use isahc::prelude::*; use serde::Deserialize; #[derive(Clone...
pub async fn fetch_remote_package( shared_client: Arc<HttpClient>, id: &str, flavor: &Flavor, ) -> Result<(String, TukuiPackage)> { let url = api_endpoint(id, flavor); let timeout = Some(30); let mut resp = request_async(&shared_client, &url, vec![], timeout).await?; if resp.status().is_s...
Flavor::Retail | Flavor::RetailPTR | Flavor::RetailBeta => match id { "-1" => "https://www.tukui.org/ui/tukui/changelog".to_owned(), "-2" => "https://www.tukui.org/ui/elvui/changelog".to_owned(), _ => format!("https://www.tukui.org/addons.php?id={}&changelog", id), }, ...
function_block-function_prefix_line
[ { "content": "/// Returns the addon website url.\n\npub fn addon_url(id: &str) -> String {\n\n format!(\"{}{}\", ADDON_URL, id)\n\n}\n\n\n\n#[serde(rename_all = \"camelCase\")]\n\n#[derive(Clone, Debug, Deserialize)]\n\n/// Struct for applying wowi details to an `Addon`.\n\npub struct WowIPackage {\n\n pu...
Rust
src/executors.rs
sambuc/mercator_parser
2566cac17fd55e69a5df3776bdb0aebb723fee4a
use std::collections::{HashMap, HashSet}; use std::rc::Rc; use mercator_db::space; use mercator_db::Core; use mercator_db::CoreQueryParameters; use mercator_db::IterObjects; use mercator_db::IterObjectsBySpaces; use super::expressions::*; use super::symbols::*; fn group_by_space<'s>( list: IterObjectsBySpaces<'s...
use std::collections::{HashMap, HashSet}; use std::rc::Rc; use mercator_db::space; use mercator_db::Core; use mercator_db::CoreQueryParameters; use mercator_db::IterObjects; use mercator_db::IterObjectsBySpaces; use super::expressions::*; use super::symbols::*; fn group_by_space<'s>( list: IterObjectsBySpaces<'s...
fn filter<'b>( &'b self, predicate: &'b Predicate, core_id: &'b str, parameters: &'b CoreQueryParameters<'b>, ) -> mercator_db::ResultSet<'b> { let results = self.execute(core_id, parameters)?; Ok(results .into_iter() .map(move |(space, ...
t = rh.execute(core_id, parameters)?; let union = if rh.predict(parameters.db) < self.predict(parameters.db) { left.append(&mut right); left } else { right.append(&mut left); right }; Ok(union) }
function_block-function_prefixed
[ { "content": "fn main() {\n\n lalrpop::process_root().unwrap();\n\n}\n", "file_path": "build.rs", "rank": 7, "score": 35765.08835520609 }, { "content": "fn main() {\n\n // If RUST_LOG is unset, set it to INFO, otherwise keep it as-is.\n\n if std::env::var(\"RUST_LOG\").is_err() {\n\...
Rust
compiler/src/yul/runtime/functions.rs
lexDAO/fe
0e34e5f192d0e6f8986f0aedc32ee1948adc1bbf
use yultsur::*; pub fn all() -> Vec<yul::Statement> { vec![ avail(), alloc(), alloc_mstoren(), free(), ccopy(), mcopy(), scopy(), mloadn(), sloadn(), cloadn(), mstoren(), sstoren(), dualkeccak256(), ] } pub...
use yultsur::*; pub fn all() -> Vec<yul::Statement> { vec![ avail(), alloc(), alloc_mstoren(), free(), ccopy(), mcopy(), scopy(), mloadn(), sloadn(), cloadn(), mstoren(), sstoren(), dualkeccak256(), ] } pub...
pub fn alloc_mstoren() -> yul::Statement { function_definition! { function alloc_mstoren(val, size) -> ptr { (ptr := alloc(size)) (mstoren(ptr, val, size)) } } } pub fn free() -> yul::Statement { function_definition! { function free(ptr) { (msto...
c() -> yul::Statement { function_definition! { function alloc(size) -> ptr { (ptr := mload(0x00)) (if (eq(ptr, 0x00)) { (ptr := 0x20) }) (mstore(0x00, (add(ptr, size)))) } } }
function_block-function_prefixed
[ { "content": "/// Builds a switch statement that dispatches calls to the contract.\n\npub fn dispatcher(attributes: Vec<FunctionAttributes>) -> Result<yul::Statement, CompileError> {\n\n let arms = attributes\n\n .iter()\n\n .map(|arm| dispatch_arm(arm.to_owned()))\n\n .collect::<Result<...
Rust
demo/faas/code/rust/proxy-wasm/src/dispatcher.rs
LXPWing/layotto
d991eba68fbf6ca4befb1ac45d7dc35147848b68
use std::{ cell::{Cell, RefCell}, collections::HashMap, }; use crate::{ traits::{HttpContext, RootContext}, types::{Action, ContextType, NewHttpContext, NewRootContext}, }; thread_local! { static DISPATCHER: Dispatcher = Dispatcher::new(); } pub fn set_root_context(callback: NewRootContext) { ...
use std::{ cell::{Cell, RefCell}, collections::HashMap, }; use crate::{ traits::{HttpContext, RootContext}, types::{Action, ContextType, NewHttpContext, NewRootContext}, }; thread_local! { static DISPATCHER: Dispatcher = Dispatcher::new(); } pub fn set_root_context(callback: NewRootContext) { ...
cate context_id") } } fn create_http_context(&self, context_id: u32, root_context_id: u32) { let new_context = match self.roots.borrow().get(&root_context_id) { Some(root_context) => match self.new_http_stream.get() { Some(f) => f(context_id, root_context_id), ...
roots: RefCell::new(HashMap::new()), new_http_stream: Cell::new(None), http_streams: RefCell::new(HashMap::new()), } } fn on_create_context(&self, context_id: u32, root_context_id: u32) { if root_context_id == 0 { self.create_root_context(context...
random
[ { "content": "#[no_mangle]\n\npub fn _start() {\n\n dispatcher::set_root_context(|_| -> Box<dyn RootContext> {\n\n Box::new(DefaultRootContext::<ServerHttpContext>::default())\n\n });\n\n}\n\n\n\n#[no_mangle]\n\n#[allow(unused_must_use)]\n\npub extern \"C\" fn proxy_get_id() {\n\n set_buffer(Buf...
Rust
src/mediacontainer.rs
csssuf/plextv-rs
5815f0a1d6c590c6da5da933c2ea2d907137cb78
use music::ApiTrack; use util; #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Deserialize)] pub enum DirectoryType { Unknown, #[serde(rename = "movie")] Movies, #[serde(rename = "artist")] Music, #[serde(rename = "show")] Shows, #[serde(rename = "album")] Album, } impl Default for Directory...
use music::ApiTrack; use util; #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Deserialize)] pub enum DirectoryType { Unknown, #[serde(rename = "movie")] Movies, #[serde(rename = "artist")] Music, #[serde(rename = "show")] Shows, #[serde(rename = "album")] Album, } impl Default for Directory...
b(crate) home: bool, } #[derive(Debug, Clone, Default)] #[derive(Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct DirectoryEntry { pub(crate) key: String, pub(crate) title: String, pub(crate) name: String, #[serde(deserialize_with = "util::deserialize_xml_bool")] pub(crate) secondar...
lCase")] pub(crate) struct MediaContainer { identifier: String, size: u64, #[serde(default, rename = "Server")] pub(crate) servers: Vec<MediaServerEntry>, #[serde(default, rename = "Directory")] pub(crate) directories: Vec<DirectoryEntry>, #[serde(default, rename = "Track")] pub(crate) tr...
random
[ { "content": "use std::fmt;\n\n\n\nuse serde::{de, Deserializer};\n\n\n\nheader! { (XPlexProduct, \"X-Plex-Product\") => [String] }\n\nheader! { (XPlexVersion, \"X-Plex-Version\") => [String] }\n\nheader! { (XPlexClientIdentifier, \"X-Plex-Client-Identifier\") => [String] }\n\nheader! { (XPlexToken, \"X-Plex-To...
Rust
src/main.rs
JoshBrudnak/pong
3a57a51b69e0c044716c74a1da0ebf4e8f098f9e
extern crate clap; extern crate futures; extern crate http; extern crate hyper; extern crate termion; extern crate tokio_core; extern crate tui; use clap::App; use clap::Arg; use futures::{Future, Stream}; use hyper::{Client, Uri}; use std::io; use std::thread::sleep; use std::time::{Duration, Instant}; use termion::r...
extern crate clap; extern crate futures; extern crate http; extern crate hyper; extern crate termion; extern crate tokio_core; extern crate tui; use clap::App; use clap::Arg; use futures::{Future, Stream}; use hyper::{Client, Uri}; use std::io; use std::thread::sleep; use std::time::{Duration, Instant}; use termion::r...
let url = matches .value_of("INPUT") .expect("Url not chosen") .to_string(); ping(url); }
let matches = App::new("pong") .version("0.1.0") .author("Josh Brudnak <jobrud314@gmail.com>") .about("A for pinging a url") .arg( Arg::with_name("INPUT") .value_name("URL") .required(true) .help("The URL to use") ...
assignment_statement
[ { "content": "# pong\n\n\n\nA rewrite of ping using Rust and a more detailed TUI.\n\n\n\n## State\n\n\n\nEarly development, not yet finished implementing.\n", "file_path": "README.md", "rank": 4, "score": 6785.054501519313 } ]
Rust
src/lib.rs
mgr-inz-rafal/swarm
3e5f09d2a43d8df225c34a8c7cdbed9222aff438
#[macro_use] mod macros; mod carrier; mod dispatcher; mod payload; mod position; mod slot; mod tools; use std::hash::Hash; pub use carrier::*; use dispatcher::*; pub use payload::*; pub use slot::*; #[macro_use] extern crate approx; fn _debug_dump_slots(slots: &[Slot<char>]) { for (i, v) in slots.iter().enumer...
#[macro_use] mod macros; mod carrier; mod dispatcher; mod payload; mod position; mod slot; mod tools; use std::hash::Hash; pub use carrier::*; use dispatcher::*; pub use payload::*; pub use slot::*; #[macro_use] extern crate approx; fn _debug_dump_slots(slots: &[Slot<char>]) { for (i, v) in slots.iter().enumer...
pub fn add_carrier(&mut self, carrier: Carrier<T>) -> usize { Swarm::<T>::add_object(&mut self.carriers, carrier) } pub fn add_slot(&mut self, slot: Slot<T>) -> usize { Swarm::<T>::add_obje...
pub fn new() -> Swarm<T> { Swarm { carriers: Vec::new(), slots: Vec::new(), first_tick: true, idle_ticks: 0, tick_counter: 0, dispatcher: Dispatcher::new(), } }
function_block-full_function
[ { "content": "#[test]\n\nfn issue26_high_speed_carrier_not_reaching_target() {\n\n // https://github.com/mgr-inz-rafal/swarm/issues/26\n\n\n\n let mut game = swarm_it::Swarm::new();\n\n\n\n let i = game.add_carrier(Carrier::new(50.0, 50.0));\n\n let mut carrier = game.get_carriers_mut()[i];\n\n c...
Rust
c2rust-transpile/src/rust_ast/traverse.rs
blinklad/c2rust
5df45752c4fb9a933f835d1f44eca49b00cd9c06
use syntax::ast::*; use syntax::ptr; pub trait Traversal: Sized { fn traverse_stmt(&mut self, s: Stmt) -> Stmt { traverse_stmt_def(self, s) } fn traverse_expr(&mut self, s: Expr) -> Expr { traverse_expr_def(self, s) } fn traverse_trait_item(&mut self, ti: TraitItem) -> TraitItem {...
use syntax::ast::*; use syntax::ptr; pub trait Traversal: Sized { fn traverse_stmt(&mut self, s: Stmt) -> Stmt { traverse_stmt_def(self, s) } fn traverse_expr(&mut self, s: Expr) -> Expr { traverse_expr_def(self, s) } fn traverse_trait_item(&mut self, ti: TraitItem) -> TraitItem {...
, iis.traverse(walk)) } ItemKind::Use(u) => ItemKind::Use(u), ItemKind::ExternCrate(u) => ItemKind::ExternCrate(u), ItemKind::GlobalAsm(u) => ItemKind::GlobalAsm(u), ItemKind::Ty(l, r) => ItemKind::Ty(l, r), ItemKind::Enum(l, r) => ItemKind::Enum(l, r), ItemKind::...
bl) => { ExprKind::ForLoop(pat, cond.traverse(walk), block.traverse(walk), lbl) } ExprKind::Loop(block, lbl) => ExprKind::Loop(block.traverse(walk), lbl), ExprKind::Match(cond, arm) => ExprKind::Match(cond.traverse(walk), arm.traverse(walk)), ExprKind::Closure(cap, isasync, m...
random
[ { "content": "pub fn stmts_block(mut stmts: Vec<Stmt>) -> P<Block> {\n\n if stmts.len() == 1 {\n\n if let StmtKind::Expr(ref e) = stmts[0].node {\n\n if let ExprKind::Block(ref b, None) = e.node {\n\n return b.clone();\n\n }\n\n }\n\n }\n\n\n\n if stmt...
Rust
core/specht-core/src/tun/device_unix.rs
zhuhaow/Specht2
00af69abf67caacf44a118dc9552c8f0c432c2d0
use crate::Result; use anyhow::ensure; use futures::ready; use ipnetwork::Ipv4Network; use std::{ io::{self, Read}, mem, os::unix::prelude::{AsRawFd, IntoRawFd, RawFd}, pin::Pin, task::{Context, Poll}, }; use tokio::io::{unix::AsyncFd, AsyncRead, ReadBuf}; use tun::{configure, create, Layer}; pub...
use crate::Result; use anyhow::ensure; use futures::ready; use ipnetwork::Ipv4Network; use std::{ io::{self, Read}, mem, os::unix::prelude::{AsRawFd, IntoRawFd, RawFd}, pin::Pin, task::{Context, Poll}, }; use tokio::io::{unix::AsyncFd, AsyncRead, ReadBuf}; use tun::{configure, create, Layer}; pub...
ze_of_val(&rtmsg) as libc::c_ushort; unsafe { rtmsg.rtm.rtm_pid = libc::getpid(); } let addr_sockaddr: OsSocketAddr = SocketAddr::V4(SocketAddrV4::new(route.ip(), 0)).into(); unsafe { std::ptr::copy_nonoverlapping( addr_sockaddr.as_ptr() as *mut l...
Ok(n as usize) } } } #[cfg(target_os = "macos")] mod route { use crate::Result; use anyhow::{bail, Context}; use ipnetwork::Ipv4Network; use nix::unistd::{close, write}; use os_socketaddr::OsSocketAddr; use scopeguard::guard; use std::{ ffi::CStr, mem, n...
random
[ { "content": "pub fn create_tun_as_raw_handle(_subnet: Ipv4Network) -> Result<RawDeviceHandle> {\n\n bail!(\"Not supported\")\n\n}\n\n\n\npub struct Device {}\n\n\n\nimpl Device {\n\n pub fn new(_subnet: Ipv4Network) -> Result<Self> {\n\n bail!(\"Not supported\");\n\n }\n\n\n\n pub fn from_ra...
Rust
src/main.rs
trigger67/world-data
33f830120eefe721dc974ec01de35d116efceb3c
mod drawing; mod report_generation; mod tools; use chrono::NaiveDate; use std::collections::HashMap; use std::error::Error; use std::fs::File; use std::io::{BufRead, BufReader}; const START_YEAR: i32 = 2016; const END_YEAR: i32 = 2021; const NUMBER_OF_YEARS: i32 = END_YEAR - START_YEAR + 1; const NUMBER_OF_YEARS_USIZE...
mod drawing; mod report_generation; mod tools; use chrono::NaiveDate; use std::collections::HashMap; use std::error::Error; use std::fs::File; use std::io::{BufRead, BufReader}; const START_YEAR: i32 = 2016; const END_YEAR: i32 = 2021; const NUMBER_OF_YEARS: i32 = END_YEAR - START_YEAR + 1; const NUMBER_OF_YEARS_USIZE...
fn compute_data_from_file( filename: String, hashmap_results: &mut HashMap<String, i32>, ) -> Result<&mut HashMap<String, i32>, Box<dyn Error>> { let input = File::open(filename)?; let buffered = BufReader::new(input); for (_idx, line) in buffered.lines().enumerate() { let new_line = line...
i32; NUMBER_OF_YEARS_USIZE] { let mut computed_data: [i32; NUMBER_OF_YEARS_USIZE] = [0; NUMBER_OF_YEARS_USIZE]; for year in START_YEAR..(END_YEAR + 1) { for data_element in results { if data_element.year == year { if data_element.age_group == age_group { ...
function_block-function_prefix_line
[ { "content": "pub fn get_files_from_dir(dir_name: String) -> Result<Vec<String>, Box<dyn Error>> {\n\n let mut file_list: Vec<String> = Vec::new();\n\n\n\n let files = std::fs::read_dir(dir_name).unwrap();\n\n\n\n for file in files {\n\n file_list.push(file.unwrap().path().into_os_string().into_...
Rust
src/analysis/score.rs
alfaevc/rusty-machine
e7cc57fc5e0f384aeb19169336deb5f66655c76a
use libnum::{Zero, One}; use linalg::{BaseMatrix, Matrix}; use learning::toolkit::cost_fn::{CostFunc, MeanSqError}; pub fn accuracy<I1, I2, T>(outputs: I1, targets: I2) -> f64 where T: PartialEq, I1: ExactSizeIterator + Iterator<Item=T>, I2: ExactSizeIterator + Iterator<Item=T> { assert!...
use libnum::{Zero, One}; use linalg::{BaseMatrix, Matrix}; use learning::toolkit::cost_fn::{CostFunc, MeanSqError}; pub fn accuracy<I1, I2, T>(outputs: I1, targets: I2) -> f64 where T: PartialEq, I1: ExactSizeIterator + Iterator<Item=T>, I2: ExactSizeIterator + Iterator<Item=T> { assert!...
pub fn f1<'a, I, T>(outputs: I, targets: I) -> f64 where I: ExactSizeIterator<Item=&'a T>, T: 'a + PartialEq + Zero + One { assert!(outputs.len() == targets.len(), "outputs and targets must have the same length"); let mut tpos = 0.0f64; let mut fpos = 0.0f64; let mut fneg = 0.0f64; ...
pub fn recall<'a, I, T>(outputs: I, targets: I) -> f64 where I: ExactSizeIterator<Item=&'a T>, T: 'a + PartialEq + Zero + One { assert!(outputs.len() == targets.len(), "outputs and targets must have the same length"); let mut tpfn = 0.0f64; let mut tp = 0.0f64; for (ref o, ref t) in outp...
function_block-full_function
[ { "content": "/// Load trees dataset.\n\n///\n\n/// The data set contains a sample of 31 black cherry trees in the\n\n/// Allegheny National Forest, Pennsylvania.\n\n///\n\n/// ## Attribute Information\n\n///\n\n/// ### Data\n\n///\n\n/// ``Matrix<f64>`` contains following columns.\n\n///\n\n/// - diameter (i...
Rust
day07/rust/mr-kaffee/src/main.rs
mr-kaffee/aoc-2020
b2a0d552ebd4ce67dbe6ec0f143564248bc517ba
use std::collections::{BTreeSet, VecDeque, BTreeMap}; use regex::Regex; use std::fs; fn main() { let content = fs::read_to_string("input.txt") .expect("Failed to read from file"); let bags = Bag::parse(&content); let parents = explore_parents(&bags, "shiny gold"); println!("Found {} container...
use std::collections::{BTreeSet, VecDeque, BTreeMap}; use regex::Regex; use std::fs; fn main() { let content = fs::read_to_string("input.txt") .expect("Failed to read from file"); let bags = Bag::parse(&content); let parents = explore_parents(&bags, "shiny gold"); println!("Found {} container...
fn count_children(bags: &BTreeMap<String, Bag>, color: &str) -> i32 { 1 + bags.get(color).expect("Bag not found").contains.iter() .fold(0, |acc, (color, cnt)| acc + cnt * count_children(bags, color)) } #[derive(Debug, PartialEq)] struct Bag { color: String, contains: BTreeMap<String, i32>, }...
fn explore_parents<'a>(bags: &'a BTreeMap<String, Bag>, color: &str) -> BTreeSet<&'a str> { let mut parents: BTreeSet<&str> = BTreeSet::new(); let mut queue: VecDeque<&str> = VecDeque::new(); queue.push_back(color); while let Some(color) = queue.pop_front() { bags.values().filter(|bag| bag...
function_block-full_function
[ { "content": "fn parse(content: &str) -> Vec<u64> {\n\n content.lines().map(|line| line.parse::<u64>().expect(\"Parse error\")).collect()\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n const CONTENT: &str = \"35\n\n20\n\n15\n\n25\n\n47\n\n40\n\n62\n\n55\n\n65\n\n95\n\n102\n\n117\n", ...
Rust
src/lib.rs
laynor/iso_currency
16a1dbbf42a658e9f7a5295fd98fa227851ac161
pub use iso_country::Country; #[cfg(feature = "with-serde")] use serde::{Deserialize, Serialize}; include!(concat!(env!("OUT_DIR"), "/isodata.rs")); #[derive(PartialEq)] pub struct CurrencySymbol { pub symbol: String, pub subunit_symbol: Option<String>, } impl std::fmt::Debug for CurrencySymbol { fn f...
pub use iso_country::Country; #[cfg(feature = "with-serde")] use serde::{Deserialize, Serialize}; include!(concat!(env!("OUT_DIR"), "/isodata.rs")); #[derive(PartialEq)] pub struct CurrencySymbol { pub symbol: String, pub subunit_symbol: Option<String>, } impl std::fmt::Debug for CurrencySymbol { fn f...
} impl std::fmt::Debug for Currency { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{}", self.code()) } } impl std::fmt::Display for Currency { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{}", self.name()) } } #[cfg(test)]...
pub fn new(symbol: &str, subunit_symbol: Option<&str>) -> CurrencySymbol { CurrencySymbol { symbol: symbol.to_owned(), subunit_symbol: match subunit_symbol { Some(v) => Some(v.to_owned()), None => None, }, } }
function_block-full_function
[ { "content": "fn write_enum_impl(file: &mut BufWriter<File>, data: &Vec<IsoData>) {\n\n writeln!(file, \"impl Currency {{\").unwrap();\n\n writeln!(file, \" /// Returns the numeric code of the currency\").unwrap();\n\n writeln!(file, \" ///\").unwrap();\n\n writeln!(file, \" /// This method...
Rust
Kernel/Modules/storage_scsi/lib.rs
ids1024/rust_os
236dfdca5660372ea6d4c3f1eea463dbd2c2945d
#![feature(linkage)] #![no_std] #[macro_use] extern crate kernel; #[allow(unused_imports)] use kernel::prelude::*; use kernel::async; use kernel::metadevs::storage; pub mod proto; pub trait ScsiInterface: Sync + Send + 'static { fn name(&self) -> &str; fn send<'a>(&'a self, command: &[u8], data: &'a [u8]) -> sto...
#![feature(linkage)] #![no_std] #[macro_use] extern crate kernel; #[allow(unused_imports)] use kernel::prelude::*; use kernel::async; use kernel::metadevs::storage; pub mod proto; pub trait ScsiInterface: Sync + Send + 'static { fn name(&self) -> &str; fn send<'a>(&'a self, command: &[u8], data: &'a [u8]) -> sto...
pub fn new_boxed(int: I) -> Result<Box<Self>,storage::IoError> { let (class, removable) = { let mut inq_data = proto::InquiryRsp::new(); try!( Self::recv_cmd(&int, proto::Inquiry::new(inq_data.len() as u16).as_ref(), inq_data.as_mut()) ); log_debug!("Type: {:#x}", inq_data.prehipheral_type()); le...
8]) -> Result<(), storage::IoError> { log_debug!("- cmd=[{:?}]", cmd); match cmd[0] & 0xE0 { 0x00 => assert_eq!(cmd.len(), 6), 0x20 => assert_eq!(cmd.len(), 10), 0x40 => assert_eq!(cmd.len(), 10), 0xA0 => assert_eq!(cmd.len(), 12), 0x80 => assert_eq!(cmd.len(), 16), _ => {}, } let _size = { le...
function_block-function_prefixed
[ { "content": "/// Wait on the provided list of Waiter trait objects\n\n///\n\npub fn wait_on_list(waiters: &mut [&mut dyn Waiter], timeout: Option<u64>) -> Option<usize>\n\n{\n\n\tlog_trace!(\"wait_on_list(waiters = {:?}, timeout = {:?})\", waiters, timeout);\n\n\tif waiters.len() == 0\n\n\t{\n\n\t\tpanic!(\"wa...
Rust
src/platform/bluez/advertising.rs
OtaK/niter
e66b301b2469b7048e0ce254110a8e4df04cceba
use crate::platform::bluez; use crate::spec::ble_appearance::BLEAppearance; #[derive( Debug, Clone, Copy, strum::Display, strum::EnumString, zvariant_derive::Type, serde::Serialize, serde::Deserialize, )] #[strum(serialize_all = "lowercase")] pub enum AdvertisementType { Broadcast, ...
use crate::platform::bluez; use crate::spec::ble_appearance::BLEAppearance; #[derive( Debug, Clone, Copy, strum::Display, strum::EnumString, zvariant_derive::Type, serde::Serialize, serde::Deserialize, )] #[strum(serialize_all = "lowercase")] pub enum AdvertisementType { Broadcast, ...
fn set( &mut self, _property_name: &str, _value: &zvariant::Value, ) -> Option<zbus::fdo::Result<()>> { None } fn call( &self, c: &zbus::Connection, m: &zbus::Message, name: &str, ) -> std::option::Option<zbus::Result<u32>> { m...
f.discoverable()).into(), ); props.insert( "DiscoverableTimeout".to_string(), zvariant::Value::from(self.discoverable_timeout()).into(), ); props.insert( "Includes".to_string(), zvariant::Value::from(bluez::ZvariantableArray::from(self.incl...
function_block-function_prefixed
[ { "content": "pub trait MeshAttentionDelegate: zvariant::Type + 'static {\n\n fn set_timer(&self, element_index: u8, time: u16);\n\n fn get_timer(&self, element_index: u8) -> u16;\n\n}\n\n\n\n#[allow(dead_code)]\n\npub struct MeshAttention<T: MeshAttentionDelegate> {\n\n object_path: String,\n\n ser...
Rust
src/main.rs
neiskip/Rust-queue-worker-with-mysql-as-storage
3ab97fd0837d95dec9327801c57b0d734fac3a6a
mod db; mod error; mod queue; mod mysqljob; use std::{sync::Arc, time::Duration}; pub use error::Error; use futures::{stream, StreamExt}; use mysqljob::MySqlQueue; use queue::{Job, Message, Queue, SendSignInEmail}; use rand::SeedableRng; use rand::{thread_rng, Rng, rngs::StdRng}; use rand::distributions::{Alphanume...
mod db; mod error; mod queue; mod mysqljob; use std::{sync::Arc, time::Duration}; pub use error::Error; use futures::{stream, StreamExt}; use mysqljob::MySqlQueue; use queue::{Job, Message, Queue, SendSignInEmail}; use rand::SeedableRng; use rand::{thread_rng, Rng, rngs::StdRng}; use rand::distributions::{Alphanume...
async fn handle_job(job: Job) -> Result<(), crate::Error> { match job.message { message @ Message::SendSignInEmail{ .. } => { println!("{}", format!("Sending sign in email: {:?}", &message)); }, _ => {} }; Ok(()) }
function_block-full_function
[ { "content": "#[async_trait::async_trait]\n\npub trait Queue: Send + Sync + Debug {\n\n async fn push(&self, job: Message, scheduled_for: Option<chrono::DateTime<chrono::Utc>>) -> Result<(), crate::Error>;\n\n \n\n async fn pull(&self, number_of_jobs: u32) -> Result<Vec<Job>, crate::Error>;\n\n asyn...
Rust
src/tools/clippy/src/main.rs
qy3u/rust
2935d294ff862fdf96578d0cbbdc289e8e7ba81c
#![cfg_attr(feature = "deny-warnings", deny(warnings))] use rustc_tools_util::VersionInfo; use std::env; use std::ffi::OsString; use std::path::PathBuf; use std::process::{self, Command}; const CARGO_CLIPPY_HELP: &str = r#"Checks a package to catch common mistakes and improve your Rust code. Usage: cargo clippy ...
#![cfg_attr(feature = "deny-warnings", deny(warnings))] use rustc_tools_util::VersionInfo; use std::env; use std::ffi::OsString; use std::path::PathBuf; use std::process::{self, Command}; const CARGO_CLIPPY_HELP: &str = r#"Checks a package to catch common mistakes and improve your Rust code. Usage: cargo clippy ...
fn into_std_cmd(self) -> Command { let mut cmd = Command::new("cargo"); cmd.env(self.path_env(), Self::path()) .envs(ClippyCmd::target_dir()) .env("CLIPPY_ARGS", self.clippy_args) .arg(self.cargo_subcommand) .args(&self.args); cmd } } ...
fn target_dir() -> Option<(&'static str, OsString)> { env::var_os("CLIPPY_DOGFOOD") .map(|_| { env::var_os("CARGO_MANIFEST_DIR").map_or_else( || std::ffi::OsString::from("clippy_dogfood"), |d| { std::path::PathBuf::from(...
function_block-full_function
[]
Rust
engine/src/v0/person_behavior.rs
jinpan/covid-simulations
fb0b207c989ff1aca62bf7b2b05d6fc3e3f56be7
use crate::v0::config::ShopperParams; use crate::v0::core::Person; use crate::v0::geometry::{BoundingBox, Position}; use crate::v0::maps::MapElement; use crate::v0::utils::random_bool_vec; use crate::v0::{maps, wasm_view}; use anyhow::Result; use rand::{Rng, RngCore}; use std::f32::consts::PI; use std::iter::Iterator; ...
use crate::v0::config::ShopperParams; use crate::v0::core::Person; use crate::v0::geometry::{BoundingBox, Position}; use crate::v0::maps::MapElement; use crate::v0::utils::random_bool_vec; use crate::v0::{maps, wasm_view}; use anyhow::Result; use rand::{Rng, RngCore}; use std::f32::consts::PI; use std::iter::Iterator; ...
}
fn test_find_path() -> Result<()> { let mut rng = Box::new(ChaCha8Rng::seed_from_u64(10914)); let sg_map = maps::Map::load_from_ascii_str(simple_groceries::MAP_ASCII_STR, 10, 1)?; let household_idx = 19; assert_eq!( sg_map.households[household_idx].bounds, Boundi...
function_block-full_function
[ { "content": "pub fn load(params: &MapParams) -> Result<Map> {\n\n let map_ascii_str = match params.name.as_str() {\n\n \"simple_groceries\" => maps::simple_groceries::MAP_ASCII_STR,\n\n _ => {\n\n return Err(anyhow!(\"unknown map name {}\", params.name));\n\n }\n\n };\n\n\...
Rust
src/main.rs
brickyluke/mc-block-stats
a7580042a001253f9a96805b08b2517e59204f3b
use std::{fs::File, io::Error, ops::Range, path::PathBuf, sync::mpsc::channel}; use fastanvil::{Chunk, JavaChunk, RegionBuffer}; use log::*; use structopt::StructOpt; use threadpool::ThreadPool; use block_count::BlockCount; mod block_count; const IGNORE_BLOCKS: &[&str] = &["minecraft:air", "minecraft:cave_air"]; co...
use std::{fs::File, io::Error, ops::Range, path::PathBuf, sync::mpsc::channel}; use fastanvil::{Chunk, JavaChunk, RegionBuffer}; use log::*; use structopt::StructOpt; use threadpool::ThreadPool; use block_count::BlockCount; mod block_count; const IGNORE_BLOCKS: &[&str] = &["minecraft:air", "minecraft:cave_air"]; co...
fn gather_region_stats( region_file: PathBuf, world_y_coords: Range<isize>, process_all_chunks: bool, ) -> Result<BlockCount, Error> { let world_height = usize::try_from(world_y_coords.end - world_y_coords.start).unwrap(); debug!("World height={}", world_height); let file = File::open(region_...
fn main() { let opt = Opt::from_args(); stderrlog::new() .module(module_path!()) .quiet(opt.quiet) .verbosity(opt.verbose + 1) .timestamp(stderrlog::Timestamp::Millisecond) .init() .unwrap(); let world_y_coords = if opt.high_worlds { -64..320 ...
function_block-full_function
[ { "content": "# Minecraft Block Statistics Analyser\n\n\n\nCounts Minecraft blocks by type and altitude (Y coordinate, height) for a given set of Minecraft region files (`*.mca`).\n\n\n\nPrints resulting statistics in CSV format.\n\n\n\n## Build\n\n\n\nUse standard Cargo commands to build and install the execut...
Rust
src/timeline.rs
ftilde/sparse
2a1e12f61c520b7b22749d01a014775c197f16f2
use matrix_sdk::ruma::api::client::r0::message::get_message_events::{self, Direction}; use matrix_sdk::{ deserialized_responses::RoomEvent, room::{Messages, Room}, ruma::events::{ reaction::ReactionEventContent, AnyRoomEvent, AnySyncMessageEvent, AnySyncRoomEvent, SyncMessageEvent, }, ...
use matrix_sdk::ruma::api::client::r0::message::get_message_events::{self, Direction}; use matrix_sdk::{ deserialized_responses::RoomEvent, room::{Messages, Room}, ruma::events::{ reaction::ReactionEventContent, AnyRoomEvent, AnySyncMessageEvent, AnySyncRoomEvent, SyncMessageEvent, }, ...
Newest, } pub struct MessageQueryResult { query: MessageQuery, events: Messages, }
::Newest, Direction::Backward, client.sync_token().await.unwrap(), t.clone(), ), } }; async move { let mut request = get_message_events::Request::new(&room_id, &from, dir); request.limit = QU...
random
[ { "content": "fn send_read_receipt(c: &Client, rid: &RoomId, eid: Box<EventId>) {\n\n if let Some(room) = c.get_joined_room(rid) {\n\n tokio::spawn(async move {\n\n room.read_receipt(&eid).await.unwrap();\n\n });\n\n } else {\n\n tracing::error!(\"can't send read receipt, n...
Rust
src/main.rs
typedruby/typedruby
0216fe987e1bfc55fce36f8c859d529aa9b8d870
#[macro_use] extern crate clap; #[macro_use] extern crate serde_derive; extern crate crossbeam; extern crate glob; extern crate itertools; extern crate ref_slice; extern crate regex; extern crate serde; extern crate serde_json; extern crate termcolor; extern crate toml; extern crate typed_arena; extern crate vec_map;...
#[macro_use] extern crate clap; #[macro_use] extern crate serde_derive; extern crate crossbeam; extern crate glob; extern crate itertools; extern crate ref_slice; extern crate regex; extern crate serde; extern crate serde_json; extern crate termcolor; extern crate toml; extern crate typed_arena; extern crate vec_map;...
s) => command::strip(&mut reporter, config, files), Command::Server => command::server(&mut reporter), }; process::exit(match success { true => 0, false => 1, }); }
function_block-function_prefixed
[ { "content": "pub fn annotate(reporter: &mut Reporter, config: AnnotateConfig, file: PathBuf) -> bool {\n\n match annotate::apply_annotations(&file, config) {\n\n Ok(()) => true,\n\n Err(err) => {\n\n match err {\n\n AnnotateError::Syntax(diagnostics) => {\n\n ...
Rust
main.rs
malisbad/legends-of-code-and-magic
99707893a3116b330cc8395c28867dd4af07849f
use std::io; macro_rules! parse_input { ($x:expr, $t:ident) => ($x.trim().parse::<$t>().unwrap()) } /** * Auto-generated code below aims at helping you parse * the standard input according to the problem statement. **/ fn main() { let mut drafting: bool = true; let mut turn = 0; loop { ...
use std::io; macro_rules! parse_input { ($x:expr, $t:ident) => ($x.trim().parse::<$t>().unwrap()) } /** * Auto-generated code below aims at helping you parse * the standard input according to the problem statement. **/ fn main() { let mut drafting: bool = true; let mut turn = 0; loop { ...
fn full_face_attack(board: Vec<&card::Card>) -> String { let mut attack_string = String::new(); for card in board { attack_string.push_str(&format!("{};", card.attack(-1))); } return attack_string; } }
fn pure_efficiency_play(player: &player::Player, playable: Vec<&card::Card>) -> String { let mut summon_string = String::new(); let mut current_mana = player.player_mana; while (current_mana >= 0) { for card in &playable { if (current_mana == card.cost) { ...
function_block-full_function
[ { "content": "# Legends of Code and Magic\n\n\n\nLanguage learning exercise for Rust using [Codingame](https://www.codingame.io)'s contest \n\n\"Legends of Code and Magic\" for bot building.\n\n\n\n## Dependencies\n\n\n", "file_path": "README.md", "rank": 11, "score": 5581.473701487713 } ]
Rust
examples/inputs_tour/src/steps/step_h_sliders.rs
songww/iced_audio
11dc01a8a978e9e36bb67748d3da2740e2249f90
use iced::{image, Column, Element, Length, Rectangle, Row, Text}; use iced_audio::{ h_slider, text_marks, tick_marks, FloatRange, FreqRange, HSlider, IntRange, LogDBRange, Normal, }; use crate::{style, Step}; #[derive(Debug, Clone)] pub enum Message { Float(Normal), Int(Normal), DB(Normal), F...
use iced::{image, Column, Element, Length, Rectangle, Row, Text}; use iced_audio::{ h_slider, text_marks, tick_marks, FloatRange, FreqRange, HSlider, IntRange, LogDBRange, Normal, }; use crate::{style, Step}; #[derive(Debug, Clone)] pub enum Message { Float(Normal), Int(Normal), DB(Normal), F...
}
s); let h_slider_int = HSlider::new(&mut self.h_slider_int_state, Message::Int) .tick_marks(&self.int_tick_marks) .text_marks(&self.int_text_marks); let h_slider_db = HSlider::new(&mut self.h_slider_db_state, Message::DB) .tick_ma...
function_block-function_prefixed
[]
Rust
src/role.rs
elsid/CodeSide
2c08f73114cd1e4d29cde61b342d1ef4e052e5cc
use model::{ Tile, Unit, }; use crate::my_strategy::{ Debug as Dbg, Positionable, Rect, Rectangular, Vec2, Vec2i, World, }; #[derive(Debug, Clone)] pub enum Role { Shooter, Miner { plant_mines: usize, planted_mines: usize, }, Pusher, } pub fn get_ro...
use model::{ Tile, Unit, }; use crate::my_strategy::{ Debug as Dbg, Positionable, Rect, Rectangular, Vec2, Vec2i, World, }; #[derive(Debug, Clone)] pub enum Role { Shooter, Miner { plant_mines: usize, planted_mines: usize, }, Pusher, } pub fn get_ro...
} if my_total_score >= world.properties().kill_score * world.properties().team_size { break; } } if max_my_total_score < world.properties().kill_score { #[cfg(all(feature = "enable_debug", feature = "enable_debug_log"))] debug.log(format!("[{}] reject miner 6 ...
.sum::<i32>(); let opponent_explosion_score = collided_teammate_units.iter() .map(|v| { if v.health > world.properties().mine_explosion_params.damage * plant_mines as i32 { 0 } else { world.properties().kill_score ...
random
[ { "content": "pub fn with_unit_position(world: World, unit_id: i32, position: Vec2) -> World {\n\n let mut game = world.game().clone();\n\n let index = game.units.iter().position(|v| v.id == unit_id).unwrap();\n\n game.units[index].position = position.as_model();\n\n World::new(world.config().clone(...
Rust
src/derive/arena.rs
tlaferriere/moore
2e432bf1bf03462024a9f61502295b679da42fca
use heck::SnakeCase; use proc_macro::TokenStream; use proc_macro2::Ident; use quote::{format_ident, quote, ToTokens}; use std::{cell::RefCell, collections::BTreeMap}; use syn::{Generics, Item}; thread_local! { static TYPES: RefCell<Vec<Type>> = Default::default(); } struct Type { name: String, generics:...
use heck::SnakeCase; use proc_macro::TokenStream; use proc_macro2::Ident; use quote::{format_ident, quote, ToTokens}; use std::{cell::RefCell, collections::BTreeMap}; use syn::{Generics, Item}; thread_local! { static TYPES: RefCell<Vec<Type>> = Default::default(); } struct Type { name: String, generics:...
pub(crate) fn mark_arena(_args: TokenStream, input: TokenStream) -> TokenStream { let input = syn::parse_macro_input!(input as Item); let (name, generics) = match &input { Item::Enum(item) => (&item.ident, &item.generics), Item::Struct(item) => (&item.ident, &item.generics), Item::Type...
pub(crate) fn add_node(name: &Ident, generics: &Generics) { let node = Type { name: name.to_string(), generics: generics.to_token_stream().to_string(), }; TYPES.with(|c| c.borrow_mut().push(node)); }
function_block-full_function
[ { "content": "struct VirtualSourceContent(pub String);\n\n\n\nimpl SourceFile for VirtualSourceFile {\n\n fn get_id(&self) -> Source {\n\n self.id\n\n }\n\n\n\n fn get_path(&self) -> RcStr {\n\n self.filename.clone()\n\n }\n\n\n\n fn get_content(&self) -> Rc<dyn SourceContent> {\n\n...
Rust
src/rect.rs
dvdplm/imageproc
de85ccdb510b3eff450d1622aa97fefb66f6d2da
use std::cmp; #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub struct Rect { left: i32, top: i32, width: u32, height: u32, } pub trait Region<T> { fn contains(&self, x: T, y: T) -> bool; } impl Rect { pub fn at(x: i32, y: i32) -> RectPosition { RectPosition ...
use std::cmp; #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub struct Rect { left: i32, top: i32, width: u32, height: u32, } pub trait Region<T> { fn contains(&self, x: T, y: T) -> bool; } impl Rect { pub fn at(x: i32, y: i32) -> RectPosition { RectPosition ...
} } impl Region<i32> for Rect { fn contains(&self, x: i32, y: i32) -> bool { self.left <= x && x <= self.right() && self.top <= y && y <= self.bottom() } } impl Region<f32> for Rect { fn contains(&self, x: f32, y: f32) -> bool { self.left as f32 <= x && x <= self.right() as f3...
Some(Rect { left: left, top: top, width: (right - left) as u32 + 1, height: (bottom - top) as u32 + 1, })
call_expression
[ { "content": "/// Returns the number of distinct Haar-like features for an image of the given dimensions.\n\n/// \n\n/// Includes positive and negative, two and three region, vertical and horizontal features,\n\n/// as well as positive and negative four region features.\n\n///\n\n/// Consider a `k`-region horiz...
Rust
src/lib.rs
richardanaya/eei
7e97d054a41aac1df702c331669a0c28d9d0e787
#![no_std] pub type Address = &'static [u8; 20]; pub type Amount = &'static [u8; 16]; pub type Data = &'static [u8; 32]; pub type Hash = Data; #[repr(C)] pub enum CallResult { Success = 0, Failure = 1, Revert = 2, } extern "C" { pub fn ethereum_useGas(amount: i64); ...
#![no_std] pub type Address = &'static [u8; 20]; pub type Amount = &'static [u8; 16]; pub type Data = &'static [u8; 32]; pub type Hash = Data;
pub fn ethereum_callDelegate( gas_limit: i64, address_ptr: *const Address, data_ptr: *const u8, data_length: i32, ) -> CallResult; pub fn ethereum_callStatic( gas_limit: i64, address_ptr: *const A...
#[repr(C)] pub enum CallResult { Success = 0, Failure = 1, Revert = 2, } extern "C" { pub fn ethereum_useGas(amount: i64); pub fn ethereum_getAddress(address_ptr: *mut Address); pub fn ethereum_getExternalBalance(address_ptr: *...
random
[]
Rust
src/lib.rs
fenhl/gres
f222909bc06c90a0592ac488ef72396886c063a2
#![deny(missing_docs, rust_2018_idioms, unused, unused_crate_dependencies, unused_import_braces, unused_lifetimes, unused_qualifications, warnings)] #![forbid(unsafe_code)] use { std::{ convert::TryFrom, future::Future, }, async_trait::async_trait, }; #[cfg(feature = "async-proto")] use a...
#![deny(missing_docs, rust_2018_idioms, unused, unused_crate_dependencies, unused_import_braces, unused_lifetimes, unused_qualifications, warnings)] #![forbid(unsafe_code)] use { std::{ convert::TryFrom, future::Future, }, async_trait::async_trait, }; #[cfg(feature = "async-proto")] use a...
}
match fut.await { Ok(Ok(x)) => Ok(Ok(x)), Ok(Err(step)) => Err(step), Err(e) => Ok(Err(e)), }
if_condition
[ { "content": "#[derive(Debug)]\n\nstruct State {\n\n num_lines: u16,\n\n current_line: u16,\n\n stdout: Stdout,\n\n}\n\n\n\n/// A command-line progress renderer.\n\n///\n\n/// `Cli` does not implement [`Clone`]. If you need to share it across threads, consider wrapping it inside an [`Arc`](std::sync::A...
Rust
syntaxdot-transformers/src/scalar_weighting.rs
Quadrocompile/syntaxdot
1dbb04d372806dd6b454f056964b770ad142c08e
use std::borrow::Borrow; use syntaxdot_tch_ext::PathExt; use tch::nn::{Init, Linear, Module}; use tch::{Kind, Reduction, Tensor}; use crate::cow::CowTensor; use crate::layers::{Dropout, LayerNorm}; use crate::loss::CrossEntropyLoss; use crate::models::LayerOutput; use crate::module::{FallibleModule, FallibleModuleT...
use std::borrow::Borrow; use syntaxdot_tch_ext::PathExt; use tch::nn::{Init, Linear, Module}; use tch::{Kind, Reduction, Tensor}; use crate::cow::CowTensor; use crate::layers::{Dropout, LayerNorm}; use crate::loss::CrossEntropyLoss; use crate::models::LayerOutput; use crate::module::{FallibleModule, FallibleModuleT...
} pub fn forward(&self, layers: &[LayerOutput], train: bool) -> Result<Tensor, TransformerError> { assert_eq!( self.layer_weights.size()[0], layers.len() as i64, "Expected {} layers, got {}", self.layer_weights.size()[0], layers.len() ...
Ok(ScalarWeight { layer_dropout_prob, layer_weights: vs.var("layer_weights", &[n_layers], Init::Const(0.))?, scale: vs.var("scale", &[], Init::Const(1.))?, })
call_expression
[ { "content": "pub fn count_sentences(mut buf_read: impl BufRead) -> Result<usize> {\n\n let mut n_sents = 0;\n\n\n\n loop {\n\n let buf = buf_read.fill_buf()?;\n\n\n\n if buf.is_empty() {\n\n break;\n\n }\n\n\n\n n_sents += bytecount::count(buf, b'\\n');\n\n\n\n ...
Rust
vga/src/lib.rs
steveeJ/intermezzOS-kernel
2b5a0fabf0ed3b249cb17651abf60e479ef12ad2
#![no_std] #![feature(nll)] use core::fmt; use core::fmt::Write; use core::ptr; mod character; use character::Character; pub use character::Color; const ROWS: usize = 25; const COLS: usize = 80; pub struct Vga<T: AsMut<[u8]>> { slice: T, buffer: [Character; ROWS * COLS], position: usize, foreground...
#![no_std] #![feature(nll)] use core::fmt; use core::fmt::Write; use core::ptr; mod character; use character::Character; pub use character::Color; const ROWS: usize = 25; const COLS: usize = 80; pub struct Vga<T: AsMut<[u8]>> { slice: T, buffer: [Character; ROWS * COLS], position: usize, foreground...
vga.write_str("hello\nworld\n!").unwrap(); vga.flush(); assert_eq!(mock_memory[0], b'h'); assert_eq!(mock_memory[1], 0x02); assert_eq!(mock_memory[2], b'e'); assert_eq!(mock_memory[3], 0x02); assert_eq!(mock_memory[4], b'l'); assert_eq!(mock_memory[5], 0x02...
_eq!(mock_memory[1], 0x02); } #[test] fn write_a_word() { let mut mock_memory = [0u8; ROWS * COLS * 2]; let mut vga = Vga::new(&mut mock_memory[..]); let word = "word"; vga.write_str(word).unwrap(); vga.flush(); assert_eq!(mock_memory[0], b'w'); ass...
random
[ { "content": "#[test]\n\nfn write() {\n\n let mut mock_memory = vec![0u8; 25 * 80 * 2];\n\n let vga = Vga::new(&mut mock_memory);\n\n check_write(vga);\n\n}\n\n\n", "file_path": "vga/tests/vga.rs", "rank": 0, "score": 76323.02781976257 }, { "content": "fn check_write<T: Write>(_: T)...
Rust
core/src/display_object/text.rs
max-dekock/ruffle
82735a78070e74e20659a8bce75b412fd93fed9d
use crate::context::{RenderContext, UpdateContext}; use crate::display_object::{DisplayObjectBase, TDisplayObject}; use crate::prelude::*; use crate::tag_utils::SwfMovie; use crate::transform::Transform; use crate::types::{Degrees, Percent}; use gc_arena::{Collect, GcCell}; use std::sync::Arc; #[derive(Clone, Debug, C...
use crate::context::{RenderContext, UpdateContext}; use crate::display_object::{DisplayObjectBase, TDisplayObject}; use crate::prelude::*; use crate::tag_utils::SwfMovie; use crate::transform::Transform; use crate::types::{Degrees, Percent}; use gc_arena::{Collect, GcCell}; use std::sync::Arc; #[derive(Clone, Debug, C...
} unsafe impl<'gc> gc_arena::Collect for TextData<'gc> { #[inline] fn trace(&self, cc: gc_arena::CollectionContext) { self.base.trace(cc); self.static_data.trace(cc); } } #[allow(dead_code)] #[derive(Debug, Clone)] struct TextStatic { swf: Arc<SwfMovie>, id: CharacterId, bound...
fn hit_test_shape( &self, context: &mut UpdateContext<'_, 'gc, '_>, mut point: (Twips, Twips), ) -> bool { if self.world_bounds().contains(point) { let local_matrix = self.global_to_local_matrix(); let tf = self.0.read(); let mut text_...
function_block-full_function
[ { "content": "/// Converts an SWF color from sRGB space to linear color space.\n\npub fn srgb_to_linear(mut color: swf::Color) -> swf::Color {\n\n fn to_linear_channel(n: u8) -> u8 {\n\n let mut n = f32::from(n) / 255.0;\n\n n = if n <= 0.04045 {\n\n n / 12.92\n\n } else {\n\n...
Rust
src/score.rs
tuomas56/hyphenation
e77f0788edc13f52a9ff094159d7303ac8783486
/*! # Evaluating potential hyphenation opportunities In Knuth–Liang hyphenation, dictionaries identify valid word breaks by searching whole words for sub-word patterns, ultimately producing a *score* that evaluates each interval between letters as a candidate for hyphenation. As an example, consider the word "firkin"...
/*! # Evaluating potential hyphenation opportunities In Knuth–Liang hyphenation, dictionaries identify valid word breaks by searching whole words for sub-word patterns, ultimately producing a *score* that evaluates each interval between letters as a candidate for hyphenation. As an example, consider the word "firkin"...
}
r() { let k = i + index as usize; if k > 1 && k <= hyphenable_length && value > values[k - 2] { values[k - 2] = value; regions[k - 2] = Some(r); } } for &Locus { i...
function_block-function_prefixed
[ { "content": "/// The indices of soft hyphens (U+00AD) within the string, if any. Existing\n\n/// soft hyphens indicate a preferred hyphenation, which can be used without\n\n/// resorting to best-effort hyphenation.\n\npub fn soft_hyphen_indices(word : &str) -> Option<Vec<usize>> {\n\n let shys : Vec<_> = wo...
Rust
src/query/delete.rs
qyihua/sea-query
86a45c122118d11e8e07ba3c599ef3b41e0724c4
use crate::{ backend::QueryBuilder, prepare::*, query::{condition::*, OrderedStatement}, types::*, value::*, Query, QueryStatementBuilder, SelectExpr, SelectStatement, }; #[derive(Debug, Clone)] pub struct DeleteStatement { pub(crate) table: Option<Box<TableRef>>, pub(crate) wherei: Con...
use crate::{ backend::QueryBuilder, prepare::*, query::{condition::*, OrderedStatement}, types::*, value::*, Query, QueryStatementBuilder, SelectExpr, SelectStatement, }; #[derive(Debug, Clone)] pub struct DeleteStatement { pub(crate) table: Option<Box<TableRef>>, pub(crate) wherei: Con...
#[allow(clippy::wrong_self_convention)] pub fn from_table<T>(&mut self, tbl_ref: T) -> &mut Self where T: IntoTableRef, { self.table = Some(Box::new(tbl_ref.into...
wherei: ConditionHolder::new(), orders: Vec::new(), limit: None, returning: Vec::new(), } }
function_block-function_prefix_line
[ { "content": "#[allow(clippy::many_single_char_names)]\n\n#[cfg(feature = \"with-json\")]\n\n#[cfg_attr(docsrs, doc(cfg(feature = \"with-json\")))]\n\npub fn sea_value_to_json_value(value: &Value) -> Json {\n\n use crate::{CommonSqlQueryBuilder, QueryBuilder};\n\n\n\n match value {\n\n Value::Bool(...
Rust
src/sys/pkg/tests/pkg-cache/src/inspect.rs
dreamboy9/fuchsia
4ec0c406a28f193fe6e7376ee7696cca0532d4ba
use { crate::{get_missing_blobs, verify_fetches_succeed, write_blob, TestEnv}, blobfs_ramdisk::BlobfsRamdisk, fidl_fuchsia_io::{DirectoryMarker, FileMarker}, fidl_fuchsia_pkg::{BlobInfo, NeededBlobsMarker}, fidl_fuchsia_pkg_ext::BlobId, fuchsia_async as fasync, fuchsia_inspect::{assert_dat...
use { crate::{get_missing_blobs, verify_fetches_succeed, write_blob, TestEnv}, blobfs_ramdisk::BlobfsRamdisk, fidl_fuchsia_io::{DirectoryMarker, FileMarker}, fidl_fuchsia_pkg::{BlobInfo, NeededBlobsMarker}, fidl_fuchsia_pkg_ext::BlobId, fuchsia_async as fasync, fuchsia_inspect::{assert_dat...
#[fasync::run_singlethreaded(test)] async fn base_blob_count_with_two_base_packages_and_one_shared_blob() { let pkg0 = PackageBuilder::new("a-base-package") .add_resource_at("some-blob", &b"shared-contents"[..]) .build() .await .unwrap(); let pkg1 = PackageBuilder::new("other-b...
async fn base_blob_count_with_one_base_package() { let pkg = PackageBuilder::new("a-base-package") .add_resource_at("some-empty-blob", &[][..]) .build() .await .unwrap(); assert_base_blob_count(&[&pkg], None, 4).await; }
function_block-full_function
[]
Rust
src/side_by_side.rs
kokizzu/difftastic
99a2fffd606ea5c6669622db55c6e361e99d2d3b
use atty::Stream; use colored::{Color, Colorize}; use std::cmp::{max, min}; use std::collections::HashMap; use crate::lines::{ codepoint_len, enforce_exact_length, enforce_max_length, format_line_num, LineGroup, LineNumber, }; use crate::style::apply_colors; use crate::syntax::{aligned_lines, MatchedPos}; const S...
use atty::Stream; use colored::{Color, Colorize}; use std::cmp::{max, min}; use std::collections::HashMap; use crate::lines::{ codepoint_len, enforce_exact_length, enforce_max_length, format_line_num, LineGroup, LineNumber, }; use crate::style::apply_colors; use crate::syntax::{aligned_lines, MatchedPos}; const S...
fn longest_visible_line_lhs(s: &str, groups: &[LineGroup]) -> usize { let lines = split_lines_nonempty(s); let mut longest = 0; for group in groups { if let Some(lhs_lines) = &group.lhs_lines { for line_num in lhs_lines.start.0..lhs_lines.end.0 { let current_len = code...
fn split_lines_nonempty(s: &str) -> Vec<String> { if s == "" { return vec!["".into()]; } let mut lines = vec![]; for line in s.lines() { lines.push(line.into()); } lines }
function_block-full_function
[ { "content": "/// Return the length of `s` in codepoints. This ensures that it's\n\n/// safe to slice `s` at this boundary.\n\npub fn codepoint_len(s: &str) -> usize {\n\n s.chars().count()\n\n}\n\n\n", "file_path": "src/lines.rs", "rank": 1, "score": 159129.58782478957 }, { "content": "/...
Rust
src/sites/reddit.rs
Draphar/redditrip
b833ed9786c902f0a8c56cd08fc2e386097ba5b3
/* * Copyright 2020 Draphar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writi...
/* * Copyright 2020 Draphar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writi...
} pub async fn fetch_image(client: &Client, url: &Uri, output: &Path) -> Result<()> { trace!("fetch({:?}, {:?})", url, output); download(client, url, output).await } pub async fn fetch_gallery( client: &Client, url: &Uri, output: &Path, gallery: &Gallery, ) -> Result<()> { trace!("fetch_...
f { match s { "no-audio" => VRedditMode::NoAudio, "ffmpeg" => VRedditMode::Ffmpeg, other => VRedditMode::Website(other.to_string()), } }
function_block-function_prefixed
[ { "content": "/// Returns the currently supported domains.\n\npub fn supported_domains() -> &'static str {\n\n \"\\\n\ni.redd.it\n\nv.redd.it\n\nreddit.com\n\ni.imgur.com\n\nimgur.com\n\ngfycat.com\n\nthumbs.gfycat.com\n\ngiant.gfycat.com\n\nredgifs.com\n\nthumbs1.redgifs.com\n\ni.pinimg.com\n\ni.postimg.cc\...
Rust
src/tim2/smcr/mod.rs
japaric/stm32f103xx
4c6153d8aa017f2e22d78b47f18ed2c773562d70
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::SMCR { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut ...
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::SMCR { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut ...
#[inline] pub fn msm(&mut self) -> _MSMW { _MSMW { w: self } } #[doc = "Bits 4:6 - Trigger selection"] #[inline] pub fn ts(&mut self) -> _TSW { _TSW { w: self } } #[doc = "Bits 0:2 - Slave mode selection"] #[inline] pub fn sms(&mut self) -> _SMSW { _SMSW { w: ...
8 = 8; ((self.bits >> OFFSET) & MASK as u32) as u8 }; ETFR { bits } } #[doc = "Bit 7 - Master/Slave mode"] #[inline] pub fn msm(&self) -> MSMR { let bits = { const MASK: bool = true; const OFFSET: u8 = 7; ((self.bits >> OFFSET) & MA...
random
[ { "content": "fn main() {\n\n if env::var_os(\"CARGO_FEATURE_RT\").is_some() {\n\n let out = &PathBuf::from(env::var_os(\"OUT_DIR\").unwrap());\n\n File::create(out.join(\"device.x\"))\n\n .unwrap()\n\n .write_all(include_bytes!(\"device.x\"))\n\n .unwrap();\n\n...
Rust
vendor/registry-40351f815f426200/clap/src/completions/powershell.rs
yangzhon/cloud-hypervisor
89fc75d5d35cc0c700a25ddb321143ca15fb70dc
use std::io::Write; use app::parser::Parser; use INTERNAL_ERROR_MSG; pub struct PowerShellGen<'a, 'b> where 'a: 'b { p: &'b Parser<'a, 'b>, } impl<'a, 'b> PowerShellGen<'a, 'b> { pub fn new(p: &'b Parser<'a, 'b>) -> Self { PowerShellGen { p: p } } pub fn generate_to<W: Write>(&self, buf: &mut W) {...
use std::io::Write; use app::parser::Parser; use INTERNAL_ERROR_MSG; pub struct PowerShellGen<'a, 'b> where 'a: 'b { p: &'b Parser<'a, 'b>, } impl<'a, 'b> PowerShellGen<'a, 'b> { pub fn new(p: &'b Parser<'a, 'b>) -> Self { PowerShellGen { p: p } } pub fn generate_to<W: Write>(&self, buf: &mut W) {...
} fn generate_inner<'a, 'b, 'p>(p: &'p Parser<'a, 'b>, previous_command_name: &str, names: &mut Vec<&'p str>) -> (String, String) { debugln!("PowerShellGen::generate_inner;"); let command_name = if previous_command_name.is_empty() { format!("{}_{}", previous_command_name, &p.meta.bin_name.as_ref().exp...
completions = @() switch ($command) {{ {subcommands_cases} }} $completions | ?{{ $_ -like "$wordToComplete*" }} | Sort-Object | %{{ New-Object System.Management.Automation.CompletionResult $_, $_, 'ParameterValue', $_ }} }} }} "#, bin_names =...
function_block-function_prefix_line
[ { "content": "// Returns a byte vector representing the contents of a null terminated C string which\n\n// contains if_name.\n\nfn build_terminated_if_name(if_name: &str) -> Result<Vec<u8>> {\n\n // Convert the string slice to bytes, and shadow the variable,\n\n // since we no longer need the &str version...
Rust
examples/worklet.rs
b-ma/web-audio-api-rs
45dd400d3b89427c6e6f587abc88bcff8f2e2633
use rand::Rng; use web_audio_api::context::{ AudioContext, AudioContextRegistration, AudioParamId, BaseAudioContext, }; use web_audio_api::node::{AudioNode, ChannelConfig}; use web_audio_api::param::{AudioParam, AudioParamDescriptor, AutomationRate}; use web_audio_api::render::{AudioParamValues, AudioProcessor, Au...
use rand::Rng; use web_audio_api::context::{ AudioContext, AudioContextRegistration, AudioParamId, BaseAudioContext, }; use web_audio_api::node::{AudioNode, ChannelConfig}; use web_
{ &self.amplitude } } struct WhiteNoiseProcessor { amplitude: AudioParamId, } impl AudioProcessor for WhiteNoiseProcessor { fn process( &mut self, _inputs: &[AudioRenderQuantum], outputs: &mut [AudioRenderQuantum], params: AudioParamValues, _scope: &RenderSc...
audio_api::param::{AudioParam, AudioParamDescriptor, AutomationRate}; use web_audio_api::render::{AudioParamValues, AudioProcessor, AudioRenderQuantum, RenderScope}; struct WhiteNoiseNode { registration: AudioContextRegistration, channel_config: ChannelConfig, amplitude: AudioParam, } impl ...
random
[ { "content": "#[allow(clippy::module_name_repetitions)]\n\npub trait BaseAudioContext {\n\n /// retrieves the `ConcreteBaseAudioContext` associated with this `AudioContext`\n\n fn base(&self) -> &ConcreteBaseAudioContext;\n\n\n\n /// Decode an [`AudioBuffer`] from a given input stream.\n\n ///\n\n ...
Rust
pallets/dao/src/lib.rs
DNFT-Team/dnft-substrate-node
f51822a2b84d4bcfc3dbcb2d1c9829f4c98582a8
#![cfg_attr(not(feature = "std"), no_std)] use codec::{Decode, Encode}; use frame_support::{ decl_error, decl_event, decl_module, decl_storage, ensure, traits::{Currency, Randomness}, StorageMap, StorageValue, }; use frame_system::ensure_signed; use pallet_randomness_collective_flip as randomness; use sp_i...
#![cfg_attr(not(feature = "std"), no_std)] use codec::{Decode, Encode}; use frame_support::{ decl_error, decl_event, decl_module, decl_storage, ensure, traits::{Currency, Randomness}, StorageMap, StorageValue, }; use frame_system::ensure_signed; use pallet_randomness_collective_flip as randomness; use sp_i...
} impl<T: Config> DAOManager<T::AccountId, BalanceOf<T>> for Module<T> { fn get_dao_account() -> T::AccountId { Self::dao_acc() } fn get_dao_tax() -> BalanceOf<T> { Self::dao_tax() } }
fn _handle_passed_proposal(proposals_id: ProposalId) -> DispatchResult { if let Some(proposal) = Self::proposals(proposals_id.clone()) { if proposal.theme == ProposalTheme::ChangeDAOTax { ensure!(proposal.value_money != None, Error::<T>::ParamERR); <DAOTax<T>>::put(pr...
function_block-full_function
[ { "content": "pub trait Config: frame_system::Config {\n\n type Event: From<Event<Self>> + Into<<Self as frame_system::Config>::Event>;\n\n type Currency: Currency<Self::AccountId>;\n\n}\n\n\n\ndecl_event!(\n\n pub enum Event<T> where\n\n <T as frame_system::Config>::AccountId,\n\n {\n\n\n\n ...
Rust
src/future_ext.rs
katyo/new-tokio-smtp
6f2aa27ebd5914c1da2f0691cd4740780bc82e8b
use futures::{Future, IntoFuture, Poll, Async}; pub trait ResultWithContextExt<Ctx, I, E>: Future<Item=(Ctx, Result<I, E>)> { fn ctx_and_then<FN, B, I2>(self, f: FN) -> CtxAndThen<Self, B, FN> where FN: FnOnce(Ctx, I) -> B, B: IntoFutur...
use futures::{Future, IntoFuture, Poll, Async}; pub trait ResultWithContextExt<Ctx, I, E>: Future<Item=(Ctx, Result<I, E>)> { fn ctx_and_then<FN, B, I2>(self, f: FN) -> CtxAndThen<Self, B, FN> where FN: FnOnce(Ctx, I) -> B, B: IntoFutur...
, item); let mut fut = bval.into_future(); let first_poll_res = fut.poll(); self.state = State::Intermediate(fut); first_poll_res } } pub struct CtxOrElse<P, B, FN> where B: IntoFuture, { state: State<P, B::Future>, map_fn: Option<FN> } impl<P, B, FN, Ctx, I, E, E2> F...
try_ready!(p.poll()) }, State::Intermediate(ref mut im) => { return im.poll(); }, }; let item = match result { Err(err) => return Ok(Async::Ready((ctx, Err(err)))), Ok(item) => item }; let map_fn = self.m...
function_block-random_span
[ { "content": "pub fn check_response(response: Response) -> Result<Response, LogicError> {\n\n if response.is_erroneous() {\n\n Err(LogicError::Code(response))\n\n } else {\n\n Ok(response)\n\n }\n\n}\n\n\n\n/// An error representing that a command was successfully send and the response wa...
Rust
src/compute/arithmetics/decimal/mul.rs
Amdahl-rr/arrow2
9066298b531054ad7c0253827dd421797bf5684c
use crate::{ array::PrimitiveArray, compute::{ arithmetics::{ArrayCheckedMul, ArrayMul, ArraySaturatingMul}, arity::{binary, binary_checked, unary}, utils::{check_same_len, combine_validities}, }, datatypes::DataType, error::{Error, Result}, scalar::{PrimitiveScalar, Sc...
use crate::{ array::PrimitiveArray, compute::{ arithmetics::{ArrayCheckedMul, ArrayMul, ArraySaturatingMul}, arity::{binary, binary_checked, unary}, utils::{check_same_len, combine_validities}, }, datatypes::DataType, error::{Error, Result}, scalar::{PrimitiveScalar, Sc...
match res { res if res.abs() > max => None, _ => Some(res), } } None => None, }; binary_checked(lhs, rhs, lhs.data_type().clone(), op) } impl ArrayMul<PrimitiveArray<i128>> for PrimitiveArray<i128> { fn mul(&self, rhs: &PrimitiveArra...
rhs } else { return PrimitiveArray::<i128>::new_null(lhs.data_type().clone(), lhs.len()); }; let scale = 10i128.pow(scale as u32); let max = max_value(precision); let op = move |a: i128| { let res: i128 = a .checked_mul(rhs) ...
random
[ { "content": "/// Returns the maximum of [`Array`]. The scalar is null when all elements are null.\n\n/// # Error\n\n/// Errors iff the type does not support this operation.\n\npub fn max(array: &dyn Array) -> Result<Box<dyn Scalar>> {\n\n Ok(match array.data_type().to_physical_type() {\n\n PhysicalTy...
Rust
src/queryable/stmt.rs
tonygrue/mysql_async
bde64f9750caa80420d62e5af1500e07dcaa3671
use futures_util::future::Either; use crate::{ connection_like::{ streamless::Streamless, ConnectionLike, ConnectionLikeWrapper, StmtCacheResult, }, error::*, io, prelude::FromRow, queryable::{query_result::QueryResult, BinaryProtocol}, Column, Params, Row, Value::{self}, }; u...
use futures_util::future::Either; use crate::{ connection_like::{ streamless::Streamless, ConnectionLike, ConnectionLikeWrapper, StmtCacheResult, }, error::*, io, prelude::FromRow, queryable::{query_result::QueryResult, BinaryProtocol}, Column, Params, Row, Value::{self}, }; u...
async fn execute_named(self, params: Params) -> Result<QueryResult<Self, BinaryProtocol>> { if self.inner.named_params.is_none() { let error = DriverError::NamedParamsForPositionalQuery.into(); return Err(error); } let positional_params = match params.i...
async fn execute_positional<U>(self, params: U) -> Result<QueryResult<Self, BinaryProtocol>> where U: ::std::ops::Deref<Target = [Value]>, U: IntoIterator<Item = Value>, U: Send + 'static, { if self.inner.num_params as usize != params.len() { Err(DriverError::StmtPara...
function_block-full_function
[ { "content": "pub fn new(stream: Stream, data: Vec<u8>) -> WritePacket {\n\n WritePacket {\n\n data: Some(data),\n\n stream: Some(stream),\n\n }\n\n}\n\n\n\nimpl Future for WritePacket {\n\n type Output = Result<Stream>;\n\n\n\n fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -...
Rust
src/linalg.rs
finalfusion/reductive
5b156bbca55d091cb57bee178abc2ff09b4e1085
use ndarray::{Array1, Array2, ArrayBase, Axis, Data, Ix1, Ix2, NdFloat}; use num_traits::{AsPrimitive, FromPrimitive}; pub trait Covariance<A> { fn covariance(self, observation_axis: Axis) -> Array2<A>; } impl<S, A> Covariance<A> for ArrayBase<S, Ix2> where S: Data<Elem = A>, ...
use ndarray::{Array1, Array2, ArrayBase, Axis, Data, Ix1, Ix2, NdFloat}; use num_traits::{AsPrimitive, FromPrimitive}; pub trait Covariance<A> { fn covariance(self, observation_axis: Axis) -> Array2<A>; } impl<S, A> Covariance<A> for ArrayBase<S, Ix2> where S: Data<Elem = A>, ...
} impl<A, S1> SquaredEuclideanDistance<A, Ix2> for ArrayBase<S1, Ix1> where A: NdFloat, S1: Data<Elem = A>, { type Output = Array1<A>; fn squared_euclidean_distance<S2>(&self, other: ArrayBase<S2, Ix2>) -> Self::Output where S2: Data<Elem = A>, { assert_eq!( self.l...
f); let other_sqn = other.dot(&other); let dp = self.dot(&other); self_sqn + other_sqn - (dp + dp) }
function_block-function_prefixed
[ { "content": "fn squared_euclidean_distance_ix1_ix2(c: &mut Criterion) {\n\n let data1: Array2<f64> = Array2::random((200, 50), Normal::new(1., 0.2).unwrap());\n\n let data2: Array2<f64> = Array2::random((50, 50), Normal::new(1., 0.2).unwrap());\n\n\n\n c.bench_function(\"squared_euclidean_distance_ix1...
Rust
ipld/hamt/src/hash.rs
dignifiedquire/forest
af7ad3a74c62b4712e08f1da38a29dabec5e15d2
use std::hash::Hasher; use std::{mem, slice}; pub trait Hash { fn hash<H: Hasher>(&self, state: &mut H); fn hash_slice<H: Hasher>(data: &[Self], state: &mut H) where Self: Sized, { for piece in data { piece.hash(state); } } } macro_rules! impl_write { ($(...
use std::hash::Hasher; use std::{mem, slice}; pub trait Hash { fn hash<H: Hasher>(&self, state: &mut H); fn hash_slice<H: Hasher>(data: &[Self], state: &mut H) where Self: Sized, { for piece in data { piece.hash(state); } } } macro_rules! impl_write { ($(...
}
fn hash<H: Hasher>(&self, state: &mut H) { if mem::size_of::<Self>() == mem::size_of::<usize>() { state.write_usize(*self as *const () as usize); } else { let (a, b) = unsafe { *(self as *const Self as *const (usize, usize)) }; state.write_us...
function_block-function_prefix_line
[ { "content": "/// Generates blake2b hash with provided size.\n\n///\n\n/// # Example\n\n/// ```\n\n/// use forest_encoding::blake2b_variable;\n\n///\n\n/// let ingest: Vec<u8> = vec![];\n\n/// let hash = blake2b_variable(&ingest, 20);\n\n/// assert_eq!(hash.len(), 20);\n\n/// ```\n\npub fn blake2b_variable(inge...
Rust
src/flash/efusepins.rs
jeandudey/cc13x2-rs
215918099301ec75e9dfad531f5cf46e13077a39
#[doc = "Reader of register EFUSEPINS"] pub type R = crate::R<u32, super::EFUSEPINS>; #[doc = "Writer for register EFUSEPINS"] pub type W = crate::W<u32, super::EFUSEPINS>; #[doc = "Register EFUSEPINS `reset()`'s with value 0"] impl crate::ResetValue for super::EFUSEPINS { type Type = u32; #[inline(always)] ...
#[doc = "Reader of register EFUSEPINS"] pub type R = crate::R<u32, super::EFUSEPINS>; #[doc = "Writer for register EFUSEPINS"] pub type W = crate::W<u32, super::EFUSEPINS>; #[doc = "Register EFUSEPINS `reset()`'s with value 0"] impl crate::ResetValue for super::EFUSEPINS { type Type = u32; #[inline(always)] ...
#[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) &...
<'a> { w: &'a mut W, } impl<'a> EFC_INSTRUCTION_INFO_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) ...
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
common/src/notification.rs
Weasy666/Zor
bea942e07b5b26c4a2bce02ea51bff450d9135f1
use std::borrow::Borrow; use std::str::FromStr; use rocket::{ data::ToByteUnit, form::{self, DataField, FromFormField, ValueField}, request::FromParam }; #[derive(Clone, Debug, PartialEq)] pub enum Notification { Disabled, Enabled, OnMentions, } impl Notification { pub fn to_i16(&self) -> ...
use std::borrow::Borrow; use std::str::FromStr; use rocket::{ data::ToByteUnit, form::{self, DataField, FromFormField, ValueField}, request::FromParam }; #[derive(Clone, Debug, PartialEq)] pub enum Notification { Disabled, Enabled, OnMentions, } impl Notification { pub fn to_i16(&self) -> ...
if !bytes.is_complete() { Err((None, Some(limit)))?; } let bytes = bytes.into_inner(); let bytes = rocket::request::local_cache!(field.request, bytes); let notification = std::str::from_utf8(bytes)?; Ok(notification.parse::<Notification>() ...
Self> { let limit = field.request.limits() .get("notification") .unwrap_or(256.kibibytes()); let bytes = field.data.open(limit).into_bytes().await?;
function_block-random_span
[]
Rust
src/http/module/ngx_http_chunked_filter_module.rs
Funny-Systems-OSS/RUSTENGINE-http-modules
1255d1b4889186212bbf71078eeb6a1328a6f442
use crate::bindings; use crate::core::ngx_core_macro; use crate::core::ngx_module_macro; use crate::core::ngx_string_macro; use std::mem; use std::ptr; #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct ngx_http_chunked_filter_ctx_t { pub free: *mut bindings::ngx_chain_t, pub busy: *mut bindings::ngx_chain_t,...
use crate::bindings; use crate::core::ngx_core_macro; use crate::core::ngx_module_macro; use crate::core::ngx_string_macro; use std::mem; use std::ptr; #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct ngx_http_chunked_filter_ctx_t { pub free: *mut bindings::ngx_chain_t, pub busy: *mut bindings::ngx_chain_t,...
unsafe extern "C" fn ngx_http_chunked_filter_init( _: *mut bindings::ngx_conf_t, ) -> bindings::ngx_int_t { ngx_http_next_header_filter = bindings::ngx_http_top_header_filter; bindings::ngx_http_top_header_filter = Some(ngx_http_chunked_header_filter); ngx_http_next_body_filter = bindings::ngx_http_t...
t; (*b).last = (*b).last.offset(1); *fresh8 = ngx_core_macro::CR; let fresh9 = (*b).last; (*b).last = (*b).last.offset(1); *fresh9 = ngx_core_macro::LF; } i = i.wrapping_add(1) } let fresh10 = (*b).last; (*b).last = (*b).last.offset...
function_block-function_prefixed
[ { "content": "pub fn ngx_memcpy(dst: *mut u8, src: *mut u8, n: usize) -> *mut u8 {\n\n if dst.is_null() || src.is_null() {\n\n panic!(\n\n \"source ({:#?}) or destination ({:#?}) may be null.\",\n\n src, dst,\n\n );\n\n }\n\n return unsafe {\n\n libc::memcpy(\...
Rust
src/core/syntax/action.rs
erwanM974/hibou_ictss_2020
211dfb52287f9fa3a30bb7c0b75afa519c059f9f
/* Copyright 2020 Erwan Mahe (github.com/erwanM974) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in...
/* Copyright 2020 Erwan Mahe (github.com/erwanM974) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in...
} return contents; } } #[derive(Clone, PartialEq, Debug, Eq, Hash)] pub struct ReceptionAction { pub origin_gt_id : Option<usize>, pub ms_id : usize, pub synchronicity : CommunicationSynchronicity, pub recipients : Vec<usize> } impl ReceptionAction { pub fn new(origin_gt_id :...
match target_ref { &EmissionTargetRef::Lifeline(tar_lf_id) => { contents.insert( TraceAction::new(tar_lf_id,TraceActionKind::Reception, self.ms_id) ); }, _ => {} }
if_condition
[ { "content": "pub fn inner_trace_from_pairs(content : &mut Pairs<Rule>,\n\n gen_ctx : &GeneralContext,\n\n unavailable_lifelines : &HashSet<usize>,\n\n trace : &mut Vec<TraceAction>,\n\n lifelines...
Rust
src/shape.rs
d0rianb/Speedy2D
1ad53d2bc885ded10b27584606e35ca050ed7437
/* * Copyright 2021 QuantumBadger * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or ag...
/* * Copyright 2021 QuantumBadger * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or ag...
#[inline] pub const fn top_left(&self) -> &Vector2<T> { &self.top_left } #[inline] pub const fn bottom_right(&self) -> &Vector2<T> { &self.bottom_right } } impl<T: Copy> Rectangle<T> { #[inline] pub fn top_right(&self) -> Vector2<T> { ...
pub fn from_tuples(top_left: (T, T), bottom_right: (T, T)) -> Self { Rectangle { top_left: Vector2::new(top_left.0, top_left.1), bottom_right: Vector2::new(bottom_right.0, bottom_right.1) } }
function_block-function_prefix_line
[ { "content": "#[must_use]\n\nfn obtain_context_if_valid(\n\n state: &RefCell<GLContextManagerState>\n\n) -> Option<GLContextManager>\n\n{\n\n let state = state.borrow_mut();\n\n\n\n if state.is_valid {\n\n Some(GLContextManager {\n\n state: state.weak_ref_to_self.upgrade().unwrap()\n\...
Rust
src/stream/adapters/flatten.rs
KaiJewson/completion
874ed55170a9f63d3e7827ce0fa34a1fcf1b4699
use core::pin::Pin; use core::task::{Context, Poll}; use completion_core::CompletionStream; use futures_core::{ready, Stream}; use pin_project_lite::pin_project; use crate::CompletionStreamExt; use super::Map; pin_project! { #[derive(Debug, Clone)] pub struct FlatMap<S: CompletionStream, U, F> wh...
use core::pin::Pin; use core::task::{Context, Poll}; use completion_core::CompletionStream; use futures_core::{ready, Stream}; use pin_project_lite::pin_project; use crate::CompletionStreamExt; use super::Map; pin_project! { #[derive(Debug, Clone)] pub struct FlatMap<S: CompletionStream, U, F> wh...
} fn size_hint(&self) -> (usize, Option<usize>) { let (_, stream_upper) = self.stream.size_hint(); let (current_lower, current_upper) = self.current.as_ref().map_or((0, Some(0)), U::size_hint); ( current_lower, if stream_upper == Some(0) { ...
if let Some(current) = this.current.as_mut().as_pin_mut() { current.poll_cancel(cx) } else { this.stream.poll_cancel(cx) }
if_condition
[ { "content": "/// Create a stream from a seed value and an async closure.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// use completion::{CompletionStreamExt, completion_async_move, stream};\n\n///\n\n/// let mut stream = stream::unfold(0, |n| completion_async_move! {\n\n/// if n < 3 {\n\n/// let...
Rust
validator-api/src/node_status_api/routes.rs
tommyv1987/nym
938eb2d0f0220a8411b6462b76480223140bc033
use crate::node_status_api::models::{ ErrorResponse, GatewayStatusReport, GatewayUptimeHistory, MixnodeStatusReport, MixnodeUptimeHistory, }; use crate::storage::ValidatorApiStorage; use crate::ValidatorCache; use rocket::http::Status; use rocket::serde::json::Json; use rocket::State; use validator_api_reques...
use crate::node_status_api::models::{ ErrorResponse, GatewayStatusReport, GatewayUptimeHistory, MixnodeStatusReport, MixnodeUptimeHistory, }; use crate::storage::ValidatorApiStorage; use crate::ValidatorCache; use rocket::http::Status; use rocket::serde::json::Json; use rocket::State; use validator_api_reques...
#[get("/mixnode/<identity>/reward-estimation")] pub(crate) async fn get_mixnode_reward_estimation( cache: &State<ValidatorCache>, storage: &State<ValidatorApiStorage>, identity: String, ) -> Result<Json<RewardEstimationResponse>, ErrorResponse> { let (bond, status) = cache.mixnode_details(&identity).a...
pub(crate) async fn get_mixnode_status( cache: &State<ValidatorCache>, identity: String, ) -> Json<MixnodeStatusResponse> { Json(MixnodeStatusResponse { status: cache.mixnode_status(identity).await, }) }
function_block-full_function
[]
Rust
carbide/examples/calculator/calculator_state.rs
HolgerGottChriestensen/conrod
48b80a0c8915b2d478a445f1e5a8e0f396598652
use std::str::FromStr; #[derive(Clone, Debug)] pub struct CalculatorState { left: Option<f64>, right: Option<f64>, result: Option<f64>, current_operation: Operation, old_operation: Operation, string: String, } impl CalculatorState { pub fn new() -> Self { CalculatorState { ...
use std::str::FromStr; #[derive(Clone, Debug)] pub struct CalculatorState { left: Option<f64>, right: Option<f64>, result: Option<f64>, current_operation: Operation, old_operation: Operation, string: String, } impl CalculatorState {
=> "×", Operation::Div => "/", } } }
pub fn new() -> Self { CalculatorState { left: None, right: None, result: None, current_operation: Operation::None, old_operation: Operation::None, string: "".to_string(), } } pub fn get_upper_display(&self) -> String { ...
random
[ { "content": "pub trait Layouter: Debug + DynClone {\n\n fn positioner(&self) -> fn(Position, Dimension, &mut dyn Widget);\n\n}\n\n\n\ndyn_clone::clone_trait_object!(Layouter);\n", "file_path": "carbide_core/src/layout/layouter.rs", "rank": 0, "score": 150663.49840896192 }, { "content": "...
Rust
src/config/test.rs
phamlequang/turtle
b004f87e8b63838344ca5bf706af21eaf3b11dab
use super::*; use std::io::ErrorKind; const CONFIG_FILE: &str = "etc/sample.config.toml"; fn sample_config() -> Config { return Config::load(CONFIG_FILE).expect("cannot load config file"); } #[test] fn test_load_config_ok() { let config = sample_config(); assert!(!config.project.is_empty()); assert!...
use super::*; use std::io::ErrorKind; const CONFIG_FILE: &str = "etc/sample.config.toml"; fn sample_config() -> Config { return Config::load(CONFIG_FILE).expect("cannot load config file"); } #[test] fn test_load_config_ok() { let config = sample_config(); assert!(!config.project.is_empty()); assert!...
#[test] fn test_search_service_not_found() { let config = sample_config(); let name = "unknown"; let found = config.search_service(name); assert!(found.is_none()); } #[test] fn test_search_service_repository_found() { let config = sample_config(); let name = "lotus"; let found = config....
fn test_search_service_found() { let config = sample_config(); let name = "lotus"; let found = config.search_service(name); assert!(found.is_some()); let service = found.unwrap(); assert_eq!(service.name, name); }
function_block-full_function
[ { "content": "pub fn generate_compose_file(file_path: &str, config: &Config) -> io::Result<()> {\n\n let contents = generate_compose_text(config);\n\n return fs::write(file_path, contents);\n\n}\n\n\n", "file_path": "src/docker/mod.rs", "rank": 0, "score": 192645.86774455314 }, { "cont...
Rust
src/main.rs
davisschenk/rasp-leds-v2
3e1b32ea9e8c7fe97426fdb4c4684b33a7ed3457
#[macro_use] extern crate rocket; use rasp_leds_hal::*; use rocket::serde::json::Json; use rocket::State; use serde::Serialize; use std::sync::{Arc, Mutex}; type Result<T> = std::result::Result<T, Json<LedError>>; type StateRunner = State<LedRunner>; #[cfg(feature = "spotify")] type SpotifyClient = State<Arc<Mutex<rs...
#[macro_use] extern crate rocket; use rasp_leds_hal::*; use rocket::serde::json::Json; use rocket::State; use serde::Serialize; use std::sync::{Arc, Mutex}; type Result<T> = std::result::Result<T, Json<LedError>>; type StateRunner = State<LedRunner>; #[cfg(feature = "spotify")] type SpotifyClient = State<Arc<Mutex<rs...
#[launch] async fn rocket() -> _ { env_logger::init(); #[cfg(feature = "simulate")] let runner = LedRunner::new(150, 25); #[cfg(feature = "hardware")] let mut runner = LedRunner::new(300, 18, 255); rocket::build() .manage(runner) .manage(get_spotify()) .mount("/", ro...
ith_config(creds, oauth, config); match spotify.read_token_cache(true) { Ok(Some(new_token)) => { let expired = new_token.is_expired(); *spotify.get_token().lock().unwrap() = Some(new_token); if expired { match...
function_block-function_prefixed
[ { "content": "type Responder<T> = oneshot::Sender<Result<T>>;\n\n\n\npub type HistoryList = VecDeque<History>;\n\n\n\n/// An input to the internal state machine\n", "file_path": "rasp-leds/src/runner.rs", "rank": 5, "score": 78202.44142292325 }, { "content": "#[cfg(feature = \"spotify\")]\n\...
Rust
database/src/string.rs
godlinchong/rsedis
1ff8838362aecbd652729afd376f6a56f9f4189b
use std::io; use std::io::Write; use std::str; use basichll::HLL; use dbutil::normalize_position; use error::OperationError; use rdbutil::constants::*; use rdbutil::{encode_i64, encode_slice_u8, EncodeError}; const HLL_ERROR: f64 = 0.0019; #[derive(PartialEq, Debug, Clone)] pub enum ValueString { Integer(i64), ...
use std::io; use std::io::Write; use std::str; use basichll::HLL; use dbutil::normalize_position; use error::OperationError; use rdbutil::constants::*; use rdbutil::{encode_i64, encode_slice_u8, EncodeError}; const HLL_ERROR: f64 = 0.0019; #[derive(PartialEq, Debug, Clone)] pub enum ValueString { Integer(i64), ...
pub fn pfcount(&self) -> Result<usize, OperationError> { Ok(if self.strlen() == 0 { 0 } else { HLL::from_vec(self.to_vec()).count().round() as usize }) } pub fn pfmerge(&mut self, data: Vec<&ValueString>) -> Result<(), OperationError> { let mut hll ...
pub fn pfadd(&mut self, data: Vec<Vec<u8>>) -> Result<bool, OperationError> { let mut changed = false; let mut hll = if self.strlen() == 0 { HLL::new(HLL_ERROR) } else { HLL::from_vec(self.to_vec()) }; for el in data { changed = hll.insert(&el)...
function_block-full_function
[ { "content": "/// Parses an ASCII representation of a number\n\n///\n\n/// # Examples\n\n/// ```\n\n/// use database::dbutil::vec_to_usize;\n\n///\n\n/// assert_eq!(vec_to_usize(&vec!['2' as u8, '0' as u8, '0' as u8]).unwrap(), 200);\n\n/// assert!(vec_to_usize(&vec!['a' as u8]).is_err());\n\n/// assert!(vec_to...
Rust
atcoder-problems-backend/tests/test_server_e2e_problem_list.rs
polyester-CTRL/AtCoderProblems
054346a74c1667e7f89c151fe0388e4730a195e7
use actix_web::{cookie::Cookie, http::StatusCode, test}; use atcoder_problems_backend::server::middleware::github_auth::{ GithubAuthentication, GithubClient, GithubToken, }; use serde_json::{json, Value}; pub mod utils; const VALID_CODE: &str = "valid-code"; const VALID_TOKEN: &str = "valid-token"; #[actix_web::...
use actix_web::{cookie::Cookie, http::StatusCode, test}; use atcoder_problems_backend::server::middleware::github_auth::{ GithubAuthentication, GithubClient, GithubToken, }; use serde_json::{json, Value}; pub mod utils; const VALID_CODE: &str = "valid-code"; const VALID_TOKEN: &str = "valid-token"; #[actix_web::...
l)) .configure(atcoder_problems_backend::server::config_services), ) .await; let response = test::TestRequest::get() .uri(&format!("/internal-api/authorize?code={}", VALID_CODE)) .send_request(&app) .await; assert_eq!(response.status(), StatusCode::FOUND); let ...
function_block-function_prefixed
[ { "content": "pub fn start_mock_github_api_server(access_token: &str, token: GithubToken) -> MockServer {\n\n let server = MockServer::start();\n\n let token_header = format!(\"token {}\", access_token);\n\n server.mock(|when, then| {\n\n when.method(\"GET\")\n\n .path(\"/user\")\n\n ...
Rust
src/tools/mod.rs
Connum/runebender
c0b212c76a1f3f6985141f61e4bb46465e37256d
mod ellipse; mod knife; mod pen; mod preview; mod rectangle; mod select; pub use ellipse::Ellipse; pub use knife::Knife; pub use pen::Pen; pub use preview::Preview; pub use rectangle::Rectangle; pub use select::Select; use crate::edit_session::EditSession; use crate::mouse::{Mouse, TaggedEvent}; use druid::{Env, Ev...
mod ellipse; mod knife; mod pen; mod preview; mod rectangle; mod select; pub use ellipse::Ellipse; pub use knife::Knife; pub use pen::Pen; pub use preview::Preview; pub use rectangle::Rectangle; pub use select::Select; use crate::edit_session::EditSession; use crate::mouse::{Mouse, TaggedEvent}; use druid::{Env, Ev...
}
pub fn needs_new_undo_group(self, other: EditType) -> bool { match (self, other) { (EditType::NudgeDown, EditType::NudgeDown) => false, (EditType::NudgeUp, EditType::NudgeUp) => false, (EditType::NudgeLeft, EditType::NudgeLeft) => false, (EditType::NudgeRight, Edi...
function_block-full_function
[ { "content": "pub fn configure_env(env: &mut Env) {\n\n env.set(SIDEBAR_BACKGROUND, colors::LIGHT_GREY);\n\n env.set(SIDEBAR_EDGE_STROKE, colors::SIDEBAR_EDGE);\n\n env.set(PLACEHOLDER_GLYPH_COLOR, colors::LIGHT_GREY);\n\n env.set(GLYPH_LIST_STROKE, colors::LIGHT_GREY);\n\n env.set(GLYPH_LIST_BAC...
Rust
src/lib.rs
Sporif/tracing-perf
7f90383a2eaff169d2d42b2acac15d67174d1af6
#![doc = include_str!("../README.md")] #![cfg_attr( feature = "docsrs", cfg_attr(doc, doc = ::document_features::document_features!()) )] #![forbid(unsafe_code)] #![warn(clippy::all, clippy::pedantic, clippy::nursery, clippy::cargo)] use std::fmt; #[cfg(feature = "start-print-order")] use indexmap::IndexMap ...
#![doc = include_str!("../README.md")] #![cfg_attr( feature = "docsrs", cfg_attr(doc, doc = ::document_features::document_features!()) )] #![forbid(unsafe_code)] #![warn(clippy::all, clippy::pedantic, clippy::nursery, clippy::cargo)] use std::fmt; #[cfg(feature = "start-print-order")] use indexmap::IndexMap ...
} macro_rules! _span { ($lvl:expr, $($args:tt)*) => {{ match $lvl { Level::ERROR => ::tracing::span!(Level::ERROR, $($args)*), Level::WARN => ::tracing::span!(Level::WARN, $($args)*), Level::INFO => ::tracing::span!(Level::INFO, $($args)*), Level::DEBUG ...
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut stats: Vec<(&'static str, Duration)> = get_times(&self.times, self.print_order); match self.print_order { #[cfg(feature = "start-print-order")] PrintOrder::Start | PrintOrder::RevStart => {} PrintOrder...
function_block-full_function
[ { "content": "# tracing-perf - Performance and time reporting for [tracing]\n\n\n\nThis crate provides very useful tools for reporting performance metrics\n\nthrough `tracing`, similar to [slog-perf].\n\n\n\n[tracing]: https://github.com/tokio-rs/tracing\n\n[slog-perf]: https://github.com/slog-rs/perf\n\n\n\n##...
Rust
truck-geometry/src/decorators/curve_on_surface.rs
roudy16/truck
b92af7761302a5d16b5e52b15f1be7b6c4dfd460
use crate::*; impl<C, S> PCurve<C, S> { #[inline(always)] pub fn new(curve: C, surface: S) -> PCurve<C, S> { PCurve { curve, surface } } #[inline(always)] pub fn curve(&self) -> &C { &self.curve } #[inline(always)] pub fn surface(&self) -> &S { &self.surface } } impl<C, S> Par...
use crate::*; impl<C, S> PCurve<C, S> { #[inline(always)] pub fn new(curve: C, surface: S) -> PCurve<C, S> { PCurve { curve, surface } } #[inline(always)] pub fn curve(&self) -> &C { &self.curve } #[inline(always)] pub fn surface(&self) -> &S { &self.surface } } impl<C, S> Par...
self.surface.uuder(pt[0], pt[1]) * der[0] * der[0] + self.surface.uvder(pt[0], pt[1]) * der[0] * der[1] * 2.0 + self.surface.vvder(pt[0], pt[1]) * der[1] * der[1] + self.surface.uder(pt[0], pt[1]) * der2[0] + self.surface.vder(pt[0], pt[1]) * der2[1] } } impl...
64) -> Self::Vector { let pt = self.curve.subs(t); let der = self.curve.der(t); let der2 = self.curve.der2(t);
function_block-random_span
[ { "content": "/// Divides the domain into equal parts, examines all the values, and returns `t` such that `curve.subs(t)` is closest to `point`.\n\n/// This method is useful to get an efficient hint of `search_nearest_parameter`.\n\npub fn presearch<C>(curve: &C, point: C::Point, range: (f64, f64), division: us...
Rust
sophia/src/serializer/nq.rs
MattesWhite/sophia_rs
8fd99ece331da47fb21fa22c86a2e8be293d3adb
use super::nt::write_term; use sophia_api::quad::{stream::*, Quad}; use sophia_api::serializer::*; use std::io; #[derive(Clone, Debug, Default)] pub struct NqConfig { ascii: bool, } impl NqConfig { pub fn set_ascii(&mut self, ascii: bool) -> &mut Self { self.ascii = ascii; self } } ...
use super::nt::write_term; use sophia_api::quad::{stream::*, Quad}; use sophia_api::serializer::*; use std::io; #[derive(Clone, Debug, Default)] pub struct NqConfig { ascii: bool, } impl NqConfig { pub fn set_ascii(&mut self, ascii: bool) -> &mut Self { self.ascii = ascii; self } } ...
b(crate) mod test { use super::*; use sophia_api::ns::*; use sophia_term::literal::convert::AsLiteral; use sophia_term::*; #[test] fn dataset() { let me = StaticTerm::new_iri("http://champin.net/#pa").unwrap(); let d = vec![ ( [ me...
w.write_all(b".\n") } .map_err(|e| io::Error::new(io::ErrorKind::Other, e)) }) .map(|_| self) } } impl NqSerializer<Vec<u8>> { #[inline] pub fn new_stringifier() -> Self { NqSerializer::new(Vec::new()) } #[inlin...
random
[ { "content": "pub fn generalized_node_types_quads() -> impl QuadSource {\n\n let v: Vec<([StaticTerm; 3], Option<StaticTerm>)> = vec![\n\n (\n\n [rdf::type_.into(), rdf::type_.into(), rdf::Property.into()],\n\n Some(rdf::type_.into()),\n\n ),\n\n ([*B1, *B2, *B1], S...
Rust
src/states/paused.rs
Noah2610/LD44
fec5924d168c45343bb20b91ee370f15f632ec12
use super::state_prelude::*; use amethyst::ecs::{Join, WriteStorage}; const UI_RON_PATH: &str = "ui/paused.ron"; #[derive(Default)] pub struct Paused { ui_entities: Vec<Entity>, ui_reader_id: Option<ReaderId<UiEvent>>, to_main_menu: bool, } impl Paused { fn handle_keys<'a, 'b>( &mut self, ...
use super::state_prelude::*; use amethyst::ecs::{Join, WriteStorage}; const UI_RON_PATH: &str = "ui/paused.ron"; #[derive(Default)] pub struct Paused { ui_entities: Vec<Entity>, ui_reader_id: Option<ReaderId<UiEvent>>, to_main_menu: bool, } impl Paused { fn handle_keys<'a, 'b>( &mut self, ...
fn ui_ron_path(&self) -> &str { UI_RON_PATH } fn ui_entities(&self) -> &Vec<Entity> { &self.ui_entities } fn ui_entities_mut(&mut self) -> &mut Vec<Entity> { &mut self.ui_entities } fn ui_reader_id(&self) -> &Option<ReaderId<UiEvent>> { &self.ui_reader_id...
ton" => { self.to_main_menu = true; Some(Trans::Pop) } _ => None, } }
function_block-function_prefixed
[ { "content": "#[cfg(not(feature = \"debug\"))]\n\npub fn in_development_mode() -> bool {\n\n false\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 0, "score": 155643.77828316568 }, { "content": "pub fn resources_dir() -> String {\n\n format!(\"{}/{}\", application_root_dir(), RESOURCE...
Rust
src/layer/chain.rs
shuyangsun/mlp-rust
3a7717febbb0b9487a62ff89adf61072767f9283
use crate::utility::counter::CounterEst; use crate::{Dense, MLPFloat, Optimizer, Tensor}; use ndarray::{ArrayD, ArrayViewD}; use std::cell::RefCell; pub struct LayerChain<T> where T: MLPFloat, { is_frozen: bool, layers: Vec<Box<dyn Tensor<T>>>, layer_outputs: RefCell<Vec<ArrayD<T>>>, } pub struct Laye...
use crate::utility::counter::CounterEst; use crate::{Dense, MLPFloat, Optimizer, Tensor}; use ndarray::{ArrayD, ArrayViewD}; use std::cell::RefCell; p
per(input, false, false) } pub fn dense_l2_sum(&self) -> T { let all_sums: Vec<T> = self .layers .iter() .map(|layer| match layer.downcast_ref::<Dense<T>>() { Some(val) => val.weight_view_2d().mapv(|ele| ele * ele).sum(), None => T::ze...
ub struct LayerChain<T> where T: MLPFloat, { is_frozen: bool, layers: Vec<Box<dyn Tensor<T>>>, layer_outputs: RefCell<Vec<ArrayD<T>>>, } pub struct LayerChainFrozen<T> where T: MLPFloat, { layers: Vec<Box<dyn Tensor<T> + Sync>>, } impl<T> LayerChain<T> where T: MLPFloat, { pub fn new()...
random
[ { "content": "pub trait Tensor<T>: Downcast {\n\n fn forward(&self, input: ArrayViewD<T>) -> ArrayD<T>;\n\n fn backward_respect_to_input(\n\n &self,\n\n layer_input: ArrayViewD<T>,\n\n layer_output: ArrayViewD<T>,\n\n ) -> ArrayD<T>;\n\n\n\n fn par_forward(&self, input: ArrayVie...
Rust
Parabel and Bonsai/omikuji_github/src/model/mod.rs
anonymouslorem/library_identification_vulnerability_report
3eb1916b25bcf885640ed19954377edf45f7498a
mod cluster; pub mod eval; pub mod liblinear; pub mod train; use crate::mat_util::*; use crate::{Index, IndexValueVec}; use hashbrown::HashMap; use itertools::Itertools; use log::info; use ordered_float::NotNan; use rayon::prelude::*; use serde::{Deserialize, Serialize}; use std::cmp::Reverse; use std::i...
mod cluster; pub mod eval; pub mod liblinear; pub mod train; use crate::mat_util::*; use crate::{Index, IndexValueVec}; use hashbrown::HashMap; use itertools::Itertools; use log::info; use ordered_float::NotNan; use rayon::prelude::*; use serde::{Deserialize, Serialize}; use std::cmp::Reverse; use std::i...
match self { TreeNode::Branch { ref mut weights, ref mut children, } => { densify(weights, max_sparse_density); children .par_iter_mut() .for_each(|child| child.densify_wei...
fn densify(weights: &mut [Option<Vector>], max_sparse_density: f32) { for w in weights.iter_mut().flatten() { if !w.is_dense() && w.density() > max_sparse_density { w.densify(); } } }
function_block-full_function
[ { "content": "struct model *load_model(const char *model_file_name)\n\n{\n\n\tFILE *fp = fopen(model_file_name,\"r\");\n\n\tif(fp==NULL) return NULL;\n\n\n\n\tlong long i;\n\n\tlong long nr_feature;\n\n\tlong long n;\n\n\tlong long nr_class;\n\n\tdouble bias;\n\n\tmodel *model_ = Malloc(model,1);\n\n\tparameter...
Rust
third_party/libflate/src/huffman.rs
bradyjoestar/rust-sgx-sdk
2e4263693e979c7273bfe844a28ba861b56ce185
use std::prelude::v1::*; use std::cmp; use std::io; use bit; const MAX_BITWIDTH: u8 = 15; #[derive(Debug, Clone, PartialEq, Eq)] pub struct Code { pub width: u8, pub bits: u16, } impl Code { pub fn new(width: u8, bits: u16) -> Self { debug_assert!(width <= MAX_BITWIDTH); Code { width, bi...
use std::prelude::v1::*; use std::cmp; use std::io; use bit; const MAX_BITWIDTH: u8 = 15; #[derive(Debug, Clone, PartialEq, Eq)] pub struct Code { pub width: u8, pub bits: u16, } impl Code { pub fn new(width: u8, bits: u16) -> Self { debug_assert!(width <= MAX_BITWIDTH); Code { width, bi...
fn package(mut nodes: Vec<Node>) -> Vec<Node> { if nodes.len() >= 2 { let new_len = nodes.len() / 2; #[cfg_attr(feature = "cargo-clippy", allow(needless_range_loop))] for i in 0..new_len { nodes[i] = mem::replace(&mut nodes[i * 2], Node::empty()); ...
fn merge(x: Vec<Node>, y: Vec<Node>) -> Vec<Node> { let mut z = Vec::with_capacity(x.len() + y.len()); let mut x = x.into_iter().peekable(); let mut y = y.into_iter().peekable(); loop { let x_weight = x.peek().map(|s| s.weight); let y_weight = y.peek().map(|s| s.w...
function_block-full_function
[ { "content": "/// Copies the entire contents of a reader into a writer.\n\n///\n\n/// This function will continuously read data from `reader` and then\n\n/// write it into `writer` in a streaming fashion until `reader`\n\n/// returns EOF.\n\n///\n\n/// On success, the total number of bytes that were copied from...
Rust
src/type_infer/mod.rs
imlyzh/Cement
c6f3e6fac84953c9d221e9046a8bd5b113432794
pub mod types; use std::sync::Arc; use sexpr_ir::gast::constant::Constant; use crate::{ast::{Ast, Call, Cond, Lets, Pair, Params, callable::{Lambda, Pattern}}, env::Env}; use self::types::{CallableType, Type}; pub trait TypeInfer { fn type_infer(&self, env: Arc<Env<Type>>) -> Type; } impl TypeInfer for Ast { ...
pub mod types; use std::sync::Arc; use sexpr_ir::gast::constant::Constant; use crate::{ast::{Ast, Call, Cond, Lets, Pair, Params, callable::{Lambda, Pattern}}, env::Env}; use self::types::{CallableType, Type}; pub trait TypeInfer { fn type_infer(&self, env: Arc<Env<Type>>) -> Type; } impl TypeInfer for Ast { ...
.iter() .map(|(_, x)|x.type_infer(env.clone())) .collect(); /* else_expr .iter() .for_each(|x| rts.push(x.type_infer(env.clone()))); // */ rts.into_iter().reduce(Type::union).unwrap_or(Type::Nil) } } impl TypeInfer for Let...
) = self; for i in cond_exprs.iter().map(|(x, _)|x) { i.type_infer(env.clone()); } let rts: Vec<Type> = cond_exprs
random
[ { "content": "// partial eval native interface\n\ntype PENI = fn(Vec<Result<Value, Ast>>) -> Result<Value, Ast>;", "file_path": "src/runtime/value.rs", "rank": 1, "score": 109631.67710263134 }, { "content": "fn call_params_parse_from(pair: Pair<Rule>, path: Arc<String>) -> Vec<Ast> {\n\n ...
Rust
research/gaia-x/pegasus/pegasus/src/operator/mod.rs
LI-Mingyu/GraphScope-MY
942060983d3f7f8d3a3377467386e27aba285b33
use std::cell::Cell; use std::time::Instant; use nohash_hasher::IntSet; use pegasus_common::rc::UnsafeRcPtr; use crate::api::meta::OperatorInfo; use crate::api::notification::{CancelScope, EndScope}; use crate::channel_id::ChannelInfo; use crate::communication::input::{new_input, InputProxy}; use crate::communicati...
use std::cell::Cell; use std::time::Instant; use nohash_hasher::IntSet; use pegasus_common::rc::UnsafeRcPtr; use crate::api::meta::OperatorInfo; use crate::api::notification::{CancelScope, EndScope}; use crate::channel_id::ChannelInfo; use crate::communication::input::{new_input, InputProxy}; use crate::communicati...
nd(sig.clone())?; } } outputs[0].notify_end(sig)?; } Ok(()) } else { Ok(()) } } fn on_cancel(&mut self, n: CancelScope, inputs: &[Box<dyn InputProxy>]) -> Result<(), JobExecError> { if !inputs.is_emp...
= self.notify.merge_end(n) { let EndScope { port: _port, tag, weight } = end; let sig = EndSignal::new(tag, weight); if outputs.len() > 1 { for i in 1..outputs.len() { outputs[i].notify_e
function_block-random_span
[ { "content": "pub trait InputEndNotify: Send + 'static {\n\n fn notify(&mut self, end: EndSignal) -> IOResult<()>;\n\n}\n\n\n\nimpl<T: Data> InputEndNotify for GeneralPush<MicroBatch<T>> {\n\n fn notify(&mut self, mut end: EndSignal) -> IOResult<()> {\n\n end.update();\n\n assert_eq!(end.upd...
Rust
examples/funktion.rs
spamviech/kommandozeilen_argumente
15445d0e50e07837d3e1420dad12e1c5baf26cc2
use std::{ ffi::OsString, fmt::{Debug, Display}, num::NonZeroI32, }; use kommandozeilen_argumente::{ crate_name, crate_version, kombiniere, Argumente, Beschreibung, EnumArgument, NonEmpty, ParseArgument, ParseFehler, Sprache, }; #[derive(Debug, Clone)] enum Aufzählung { Eins, Zwei, Dre...
use std::{ ffi::OsString, fmt::{Debug, Display}, num::NonZeroI32, }; use kommandozeilen_argumente::{ crate_name, crate_version, kombiniere, Argumente, Beschreibung, EnumArgument, NonEmpty, ParseArgument, ParseFehler, Sprache, }; #[derive(Debug, Clone)] enum Aufzählung { Eins, Zwei, Dre...
fn main() { let sprache = Sprache::DEUTSCH; let flag = Argumente::flag_bool_mit_sprache( Beschreibung::neu_mit_sprache( "flag", None::<&str>, Some("Eine Flag mit Standard-Einstellungen."), Some(false), sprache, ), sprache, )...
function_block-full_function
[ { "content": "fn write_argument_wert(f: &mut Formatter<'_>, colon: bool, wert: &ArgumentWert) -> fmt::Result {\n\n use ArgumentWert::*;\n\n match wert {\n\n KeinWert => Ok(()),\n\n Unterargument(args) => write_liste(f, if colon { \": (\" } else { \"(\" }, args, \")\"),\n\n Liste(tts) ...
Rust
src/connectivity/network/netstack3/core/src/wire/mod.rs
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
#![allow(clippy::block_in_if_condition_stmt)] macro_rules! debug_err { ($err:expr, $($arg:tt)*) => ( { use ::log::debug; debug!($($arg)*); $err } ) } macro_rules! debug_err_fn { ($err:expr, $($arg:tt)*) => ( ...
#![allow(clippy::block_in_if_condition_stmt)] macro_rules! debug_err { ($err:expr, $($arg:tt)*) => ( { use ::log::debug; debug!($($arg)*); $err } ) } macro_rules! debug_err_fn { ($err:expr, $($arg:tt)*) => ( ...
m_buffer(&mut bv, 2); assert_eq!(mp.unwrap(), &buff[..2]); let mp = MaybeParsed::take_from_buffer(&mut bv, 3); assert_eq!(mp.unwrap_incomplete(), &buff[2..]); } #[test] fn test_maybe_parsed_min_len() { let buff = [1_u8, 2, 3, 4]; let mp = MaybeParsed::new_with_min_le...
} else { MaybeParsed::Incomplete(buff.take_rest_front()) } } pub(crate) fn new_with_min_len(bytes: T, min_len: usize) -> Self where T: ByteSlice, { if bytes.len() >= min_len { MaybeParsed::Complete(bytes) } else...
random
[]
Rust
src/uucore/src/lib/mods/error.rs
arijit79/coreutils
92ccfa86b0b8caf54e5e0e87d8e4c66a36a86e18
use std::{ error::Error, fmt::{Display, Formatter}, sync::atomic::{AtomicI32, Ordering}, }; static EXIT_CODE: AtomicI32 = AtomicI32::new(0); pub fn get_exit_code() -> i32 { EXIT_CODE.load(Ordering::SeqCst) } pub fn set_exit_code(code: i32) { EXIT_CODE.store(code, Ordering::SeqCst); } pub type ...
use std::{ error::Error, fmt::{Display, Formatter}, sync::atomic::{AtomicI32, Ordering}, }; static EXIT_CODE: AtomicI32 = AtomicI32::new(0); pub fn get_exit_code() -> i32 { EXIT_CODE.load(Ordering::SeqCst) } pub fn set_exit_code(code: i32) { EXIT_CODE.store(code, Ordering::SeqCst); } pub type ...
} impl From<UIoError> for UCommonError { fn from(e: UIoError) -> UCommonError { UCommonError::Io(e) } } impl From<UIoError> for UError { fn from(e: UIoError) -> UError { let common: UCommonError = e.into(); common.into() } } #[derive(Debug)] pub enum UCommonError { Io(UIo...
fn map_err_context(self, context: impl FnOnce() -> String) -> UIoError { UIoError { context: (context)(), inner: std::io::Error::new(self, ""), } }
function_block-full_function
[]
Rust
src/server_pool.rs
elpiel/httptest
624c1a261fcb53f879ac7fce042528bb4c858c50
use crate::Server; use once_cell::sync::OnceCell; use std::marker::PhantomData; use std::ops::{Deref, DerefMut}; use std::sync::Mutex; #[derive(Debug)] pub struct ServerPool(OnceCell<InnerPool>, usize); impl ServerPool { pub const fn new(max_servers: usize) -> Self { ServerPool(OnceCel...
use crate::Server; use once_cell::sync::OnceCell; use std::marker::PhantomData; use std::ops::{Deref, DerefMut}; use std::sync::Mutex; #[derive(Debug)] pub struct ServerPool(OnceCell<InnerPool>, usize); impl ServerPool { pub const fn new(max_servers: usize) -> Self { ServerPool(OnceCel...
} impl Drop for InnerPool { fn drop(&mut self) { let servers_created = self.servers_created.lock().expect("poisoned mutex"); for _ in 0..*servers_created { self.servers_rx .recv() .expect("all senders unexpectedly dropped"); } } } #...
let mut servers_created = self.servers_created.lock().expect("poisoned mutex"); if *servers_created < self.servers_tx.capacity().unwrap() { *servers_created += 1; return ServerHandle { servers_tx: self.servers_tx.clone(), server: Some(S...
function_block-function_prefix_line
[ { "content": "/// true if the input matches the regex provided.\n\n///\n\n/// # Example\n\n///\n\n/// ```\n\n/// use httptest::mappers::*;\n\n///\n\n/// // A request matcher that matches a request to path \"/test/foo\" or \"/test/bar\".\n\n/// request::path(matches(\"^/test/(foo|bar)$\"));\n\n/// ```\n\npub fn ...
Rust
src/main.rs
ExcaliburZero/advent_of_code_2021
0ddf6e8c05b6cf2aec4fcf3b19acd81fdf7a52ea
extern crate clap; use clap::{App, Arg, SubCommand}; extern crate advent_of_code_2021; fn main() { let a = App::new("advent_of_code_2021").author("Christopher Wells <cwellsny@gmail.com>"); let days = get_days(); let app = days.iter().map(|d| d.0.clone()).fold(a, |b, day| { b.subcommand( ...
extern crate clap; use clap::{App, Arg, SubCommand}; extern crate advent_of_code_2021; fn main() { let a = App::new("advent_of_code_2021").author("Christopher Wells <cwellsny@gmail.com>"); let days = get_days(); let app = days.iter().map(|d| d.0.clone()).fold(a, |b, day| { b.subcommand( ...
} } } type AdventOfCodeDay = (String, fn(), fn()); fn get_days() -> Vec<AdventOfCodeDay> { vec![ ( "1".to_string(), advent_of_code_2021::one::part_one as fn(), advent_of_code_2021::one::part_two as fn(), ), ( "2".to_string(), ...
match part { "one" => part_one(), "two" => part_two(), p => println!("Unknown part: {}", p), }
if_condition
[ { "content": "pub fn part_two() {\n\n let numbers = read_input();\n\n let answer = count_num_3_sum_increases(&numbers);\n\n\n\n println!(\"{}\", answer);\n\n}\n\n\n", "file_path": "src/one.rs", "rank": 0, "score": 168788.98868894298 }, { "content": "pub fn part_two() {\n\n let st...
Rust
src/formatter/local_time_cacher.rs
SpriteOvO/spdlog-rs
6c06abdec817f2ed719b61a4beb0de6080bced0e
use std::{ cell::{RefCell, RefMut}, time::SystemTime, }; use chrono::prelude::*; use once_cell::sync::Lazy; use crate::sync::*; pub(crate) static LOCAL_TIME_CACHER: Lazy<SpinMutex<LocalTimeCacher>> = Lazy::new(|| SpinMutex::new(LocalTimeCacher::new())); #[derive(Clone)] pub(crate) struct LocalTimeCacher...
use std::{ cell::{RefCell, RefMut}, time::SystemTime, }; use chrono::prelude::*; use once_cell::sync::Lazy; use crate::sync::*; pub(crate) static LOCAL_TIME_CACHER: Lazy<SpinMutex<LocalTimeCacher>> = Lazy::new(|| SpinMutex::new(LocalTimeCacher::new())); #[derive(Clone)] pub(crate) struct LocalTimeCacher...
impl_cache_fields_getter! { year: i32, month: u32, day: u32, hour: u32, minute: u32, } pub(crate) fn second(&self) -> u32 { *self.cached.second.borrow_mut().get_or_insert_with(|| { if !self.cached.is_leap_second { self.cached.loc...
t| { opt.get_or_insert_with(|| { format!( "{}-{:02}-{:02} {:02}:{:02}:{:02}", self.year(), self.month(), self.day(), self.hour(), self.minute(), ...
function_block-function_prefixed
[ { "content": "fn journal_send(args: impl Iterator<Item = impl AsRef<str>>) -> StdResult<(), io::Error> {\n\n let iovecs: Vec<_> = args.map(|a| unsafe { const_iovec::from_str(a) }).collect();\n\n let result = unsafe { ffi::sd_journal_sendv(iovecs.as_ptr(), iovecs.len() as c_int) };\n\n if result == 0 {\...
Rust
diesel/src/query_builder/insert_statement/insert_with_default_for_sqlite.rs
Razican/diesel
2eee07c88749d06fd6627223b5ad87e357ff2946
use super::{BatchInsert, InsertStatement}; use crate::connection::Connection; use crate::insertable::Insertable; use crate::insertable::{CanInsertInSingleQuery, ColumnInsertValue, DefaultableColumnInsertValue}; use crate::prelude::*; use crate::query_builder::returning_clause::NoReturningClause; use crate::query_builde...
use super::{BatchInsert, InsertStatement}; use crate::connection::Connection; use crate::insertable::Insertable; use crate::insertable::{CanInsertInSingleQuery, ColumnInsertValue, DefaultableColumnInsertValue}; use crate::prelude::*; use crate::query_builder::returning_clause::NoReturningClause; use crate::query_builde...
query.execute(conn) } } macro_rules! tuple_impls { ($( $Tuple:tt { $(($idx:tt) -> $T:ident, $ST:ident, $TT:ident,)+ } )+) => { $( impl_contains_defaultable_value!($($T,)*); )* } } macro_rules! impl...
let query = InsertStatement { records: SqliteBatchInsertWrapper(query.records), operator: query.operator, target: query.target, returning: query.returning, };
assignment_statement
[]
Rust
storage-proofs-post/src/rational/compound.rs
suanhang/rust-fil-proofs
ec2ef88a17ffed991b64dc8d96b30c36b275eca0
use std::marker::PhantomData; use anyhow::ensure; use bellperson::bls::{Bls12, Fr}; use bellperson::{Circuit, ConstraintSystem, SynthesisError}; use generic_array::typenum::U2; use storage_proofs_core::{ compound_proof::{CircuitComponent, CompoundProof}, drgraph::graph_height, error::Result, gadgets::p...
use std::marker::PhantomData; use anyhow::ensure; use bellperson::bls::{Bls12, Fr}; use bellperson::{Circuit, ConstraintSystem, SynthesisError}; use generic_array::typenum::U2; use storage_proofs_core::{ compound_proof::{CircuitComponent, CompoundProof}, drgraph::graph_height, error::Result, gadgets::p...
fn circuit( pub_in: &<RationalPoSt<'a, Tree> as ProofScheme<'a>>::PublicInputs, _priv_in: <RationalPoStCircuit<Tree> as CircuitComponent>::ComponentPrivateInputs, vanilla_proof: &<RationalPoSt<'a, Tree> as ProofScheme<'a>>::Proof, _pub_params: &<RationalPoSt<'a, Tree> as ProofSchem...
r>> { let mut inputs = Vec::new(); let por_pub_params = por::PublicParams { leaves: (pub_params.sector_size as usize / NODE_SIZE), private: true, }; ensure!( pub_in.challenges.len() == pub_in.comm_rs.len(), "Missmatch in challenges and co...
function_block-function_prefixed
[ { "content": "pub fn public_params<Tree: 'static + MerkleTreeTrait>(\n\n sector_bytes: PaddedBytesAmount,\n\n partitions: usize,\n\n porep_id: [u8; 32],\n\n api_version: ApiVersion,\n\n) -> Result<stacked::PublicParams<Tree>> {\n\n StackedDrg::<Tree, DefaultPieceHasher>::setup(&setup_params(\n\n ...
Rust
signature/src/lib.rs
Atul9/crush
b546f85af4ca2aa3204988ed57491d9ebe17afc0
use proc_macro2; use syn; use proc_macro2::{TokenStream, Literal, TokenTree}; use syn::{Item, Type, PathArguments, GenericArgument, Attribute}; use quote::{quote, ToTokens, quote_spanned}; use proc_macro2::Ident; use syn::spanned::Spanned; struct TypeData { initialize: TokenStream, mappings: TokenStream, ...
use proc_macro2; use syn; use proc_macro2::{TokenStream, Literal, TokenTree}; use syn::{Item, Type, PathArguments, GenericArgument, Attribute}; use quote::{quote, ToTokens, quote_spanned}; use proc_macro2::Ident; use syn::spanned::Spanned; struct TypeData { initialize: TokenStream, mappings: TokenStream, ...
#[proc_macro_attribute] pub fn signature(_metadata: proc_macro::TokenStream, input: proc_macro::TokenStream) -> proc_macro::TokenStream { match signature_real(TokenStream::from(input)) { Ok(res) | Err(res) => { proc_macro::TokenStream::from(res) } } }
let type_data = type_to_value(&field.ty, name, default_value.clone(), is_unnamed_target)?; let initialize = type_data.initialize; let mappings = type_data.mappings; values.extend(quote! {let mut #name = #initialize; }.into_token_stream()); if is_named_tar...
function_block-function_prefix_line
[ { "content": "fn format_argument(res: &mut String, arg: Option<&Argument>) -> CrushResult<()> {\n\n res.push_str(mandate(arg, \"Missing argument\")?.value.to_string().as_str());\n\n Ok(())\n\n}\n\n\n", "file_path": "src/lib/types/string/format.rs", "rank": 1, "score": 415522.69102745864 }, ...
Rust
artichoke-backend/src/extn/core/string/scan.rs
johnwahba/artichoke
7ef7fa8dda78e8d53c18ab91b7707a6c10f91089
use std::cmp; use std::mem; use crate::convert::{Convert, RustBackedValue, TryConvert}; use crate::extn::core::matchdata::MatchData; use crate::extn::core::regexp::enc::Encoding; use crate::extn::core::regexp::opts::Options; use crate::extn::core::regexp::{syntax, Backend, Regexp}; use crate::sys; use crate::value::{V...
use std::cmp; use std::mem; use crate::convert::{Convert, RustBackedValue, TryConvert}; use crate::extn::core::matchdata::MatchData; use crate::extn::core::regexp::enc::Encoding; use crate::extn::core::regexp::opts::Options; use crate::extn::core::regexp::{syntax, Backend, Regexp}; use crate::sys; use crate::value::{V...
pub fn method(interp: &Artichoke, args: Args, value: Value) -> Result<Value, Error> { let mrb = interp.0.borrow().mrb; let regexp = args.regexp.ok_or(Error::WrongType)?; let s = value.itself().map_err(|_| Error::Fatal)?; let s = unsafe { String::try_convert(&interp, s) }.map_err(|_| Error::WrongType)?; ...
function_block-full_function
[ { "content": "// TODO: Add tests for this parse_pattern, see GH-157.\n\npub fn parse_pattern(pattern: &str, mut opts: Options) -> (String, Options) {\n\n let orig_opts = opts;\n\n let mut chars = pattern.chars();\n\n let mut enabled = true;\n\n let mut pat_buf = String::new();\n\n let mut pointer...
Rust
crates/bevy-physical-sky/src/lib.rs
superdump/minkraft
3356b9a7556ea62aeadd8d98fe15a39376f22994
use bevy::{ core::Byteable, prelude::*, reflect::TypeUuid, render::{ render_graph::{base, AssetRenderResourcesNode, RenderGraph}, renderer::{RenderResource, RenderResources}, shader::ShaderDefs, }, transform::TransformSystem, }; pub mod solar_position; pub use chrono::p...
use bevy::{ core::Byteable, prelude::*, reflect::TypeUuid, render::{ render_graph::{base, AssetRenderResourcesNode, RenderGraph}, renderer::{RenderResource, RenderResources}, shader::ShaderDefs, }, transform::TransformSystem, }; pub mod solar_position; pub use chrono::p...
mie_zenith_length: 1000.0, sun_intensity_factor: 1151.0, sun_intensity_falloff_steepness: 1.22, sun_angular_diameter_degrees: 0.00639, tonemap_weighting: 9.50, update_sun_position, ..Default::default() } } pub fn purple_dusk(update...
b const PHYSICAL_SKY_VERTEX_SHADER: &str = include_str!("../assets/shaders/physical_sky.vert"); pub const PHYSICAL_SKY_FRAGMENT_SHADER: &str = include_str!("../assets/shaders/physical_sky.frag"); const SUN_DISTANCE: f32 = 400000.0; pub struct PhysicalSkyPlugin; impl Plugin for PhysicalSkyPlugin { fn build(&self,...
random
[ { "content": "/// Escapes the capturing of output from tests so it's visible even when the test succeeds.\n\npub fn test_print(message: &str) {\n\n use std::io::Write;\n\n\n\n std::io::stdout()\n\n .lock()\n\n .write_all(message.as_bytes())\n\n .unwrap();\n\n}\n", "file_path": "sr...
Rust
src/analysis/cross_validation.rs
winstonewert/rusty-machine
1bff90b1cbad15b221179366d7b347a1feb76683
use std::cmp; use std::iter::Chain; use std::slice::Iter; use linalg::{BaseMatrix, Matrix}; use learning::{LearningResult, SupModel}; use learning::toolkit::rand_utils::in_place_fisher_yates; pub fn k_fold_validate<M, S>(model: &mut M, inputs: &Matrix<f64>, t...
use std::cmp; use std::iter::Chain; use std::slice::Iter; use linalg::{BaseMatrix, Matrix}; use learning::{LearningResult, SupModel}; use learning::toolkit::rand_utils::in_place_fisher_yates; pub fn k_fold_validate<M, S>(model: &mut M, inputs: &Matrix<f64>, t...
tem = &'a usize; fn next(&mut self) -> Option<&'a usize> { self.0.next() } } impl <'a> ExactSizeIterator for TestIndices<'a> { fn len(&self) -> usize { self.0.len() } } impl<'a> TrainingIndices<'a> { fn new(left: &'a [usize], right: &'a [usize]) -> TrainingIndices<'a> { le...
: Vec<usize> = (0..num_samples).collect(); in_place_fisher_yates(&mut indices); ShuffledIndices(indices) } struct Partition<'a> { train_indices_iter: TrainingIndices<'a>, test_indices_iter: TestIndices<'a> } #[derive(Clone)] struct TestIndices<'a>(Iter<'a, usize>); #[derive(Clone)] struct TrainingInd...
random
[ { "content": "/// Returns the fraction of outputs rows which match their target.\n\npub fn row_accuracy(outputs: &Matrix<f64>, targets: &Matrix<f64>) -> f64 {\n\n accuracy(outputs.row_iter().map(|r| r.raw_slice()),\n\n targets.row_iter().map(|r| r.raw_slice()))\n\n}\n\n\n", "file_path": "src/...
Rust
src/inspector/channel.rs
ry/rusty_v8
c025a918c005957a7410b9e7e7d9913943a3c8ca
use crate::support::int; use crate::support::CxxVTable; use crate::support::FieldOffset; use crate::support::Opaque; use crate::support::RustVTable; use crate::support::UniquePtr; use crate::StringBuffer; extern "C" { fn v8_inspector__V8Inspector__Channel__BASE__CONSTRUCT( buf: &mut std::mem::MaybeUninit<Channel...
use crate::support::int; use crate::support::CxxVTable; use crate::support::FieldOffset; use crate::support::Opaque; use crate::support::RustVTable; use crate::support::UniquePtr; use crate::StringBuffer; extern "C" { fn v8_inspector__V8Inspector__Channel__BASE__CONSTRUCT( buf: &mut std::mem::MaybeUninit<Channel...
}
fn test_channel() { let mut channel = TestChannel::new(); let msg_view = StringView::from(MESSAGE); channel.send_response(999, StringBuffer::create(&msg_view)); assert_eq!(CALL_COUNT.swap(0, SeqCst), 1); channel.send_notification(StringBuffer::create(&msg_view)); assert_eq!(CALL_COUNT.swap(0, Se...
function_block-full_function
[ { "content": "#[allow(unused_variables)]\n\npub trait ClientImpl: AsClient {\n\n fn base(&self) -> &ClientBase;\n\n fn base_mut(&mut self) -> &mut ClientBase;\n\n\n\n fn run_message_loop_on_pause(&mut self, context_group_id: int) {}\n\n fn quit_message_loop_on_pause(&mut self) {}\n\n fn run_if_waiting_for_...
Rust
src/main.rs
dereulenspiegel/fill-helper
2eb5aec4672091b0f339900f94d80b121547bc8f
#![deny(unsafe_code)] #![no_main] #![no_std] mod flow_counter; extern crate panic_semihosting; use cortex_m_semihosting::hprintln; use embedded_graphics::{ fonts::{Font6x8, Text}, pixelcolor::BinaryColor, prelude::*, primitives::Rectangle, style::{PrimitiveStyleBuilder, TextStyleBuilder}, }; use...
#![deny(unsafe_code)] #![no_main] #![no_std] mod flow_counter; extern crate panic_semihosting; use cortex_m_semihosting::hprintln; use embedded_graphics::{ fonts::{Font6x8, Text}, pixelcolor::BinaryColor, prelude::*, primitives::Rectangle, style::{PrimitiveStyleBuilder, TextStyleBuilder}, }; use...
disp.clear(); disp.flush().unwrap(); let now = cx.start; hprintln!("Scheduling tasks").unwrap(); cx.schedule .scan_rotary_encoder(now + ROTARY_ENCODER_PERIOD.cycles()) .unwrap(); cx.schedule .scan_flow_counter(now + FLOW_COU...
match disp.display_on(true) { Ok(_) => (), Err(e) => hprintln!("Failed to call display on {:?}", e).unwrap(), }
if_condition
[ { "content": "# `cortex-m-quickstart`\n\n\n\n> A template for building applications for ARM Cortex-M microcontrollers\n\n\n\nThis project is developed and maintained by the [Cortex-M team][team].\n\n\n\n## Dependencies\n\n\n\nTo build embedded programs using this template you'll need:\n\n\n\n- Rust 1.31, 1.30-b...
Rust
examples/fighting_game/systems/restart_system.rs
TuckerBMorgan/bevy_ggrs
e6034ac00f5865912653847aeed11d0a018fec39
use crate::systems::*; use crate::*; #[derive(Debug, Hash, PartialEq, Eq, Clone, SystemLabel, Component)] pub struct RestartSystem; #[derive(Debug, Clone, Eq, PartialEq, Hash, Reflect, Component)] pub enum RestartSystemStateEnum { Blackout, OpenUp, } impl Default for RestartSystemStateEnum { fn default()...
use crate::systems::*; use crate::*; #[derive(Debug, Hash, PartialEq, Eq, Clone, SystemLabel, Component)] pub struct RestartSystem; #[derive(Debug, Clone, Eq, PartialEq, Hash, Reflect, Component)] pub enum RestartSystemStateEnum { Blackout, OpenUp, } impl Default for RestartSystemStateEnum { fn default()...
= 400.0f32; slides_in_place += 1; } } if slides_in_place == 2 { restart_state.system_state = RestartSystemStateEnum::OpenUp; for (mut transform, mut player_state, mut player_health, mut sprite, _player1) in ...
tureAtlasSprite, &Player1, ), Without<Player2>, >, mut player_2_restart: Query< ( &mut Transform, &mut PlayerState, &mut PlayerHealth, &mut TextureAtlasSprite, &Player2, ), Without<Player1>, >, ...
random
[ { "content": "pub fn player_movement_system(mut query: Query<(&mut Transform, &mut PlayerState)>) {\n\n for (mut transform, mut player_state) in query.iter_mut() {\n\n transform.translation += Vec3::new(\n\n player_state.x_velocity as f32,\n\n player_state.y_velocity as f32,\n\n ...
Rust
mos-core/src/errors.rs
RoyJacobs/mosdev
75c21606aa37addf6a3b20c431de5690ee8aa162
use crate::parser::code_map::{CodeMap, Span, SpanLoc}; use codespan_reporting::diagnostic::{Diagnostic, Severity}; use codespan_reporting::files::{Error, Files}; use itertools::Itertools; use pathdiff::diff_paths; use std::fmt::{Display, Formatter}; use std::ops::Range; pub type CoreResult<T> = Result<T, Diagnostics>;...
use crate::parser::code_map::{CodeMap, Span, SpanLoc}; use codespan_reporting::diagnostic::{Diagnostic, Severity}; use codespan_reporting::files::{Error, Files}; use itertools::Itertools; use pathdiff::diff_paths; use std::fmt::{Display, Formatter}; use std::ops::Range; pub type CoreResult<T> = Result<T, Diagnostics>;...
}
fn files() { let mut codemap = CodeMap::default(); let a = codemap.add_file("a".into(), "1234567890\nabcde".into()); let b = codemap.add_file("b".into(), "ABCDE\nFGHIJKLMNO".into()); let cm = &codemap; assert_eq!(cm.line_index(a.span, 5).unwrap(), 0); assert_eq!(cm.line_...
function_block-full_function
[ { "content": "pub fn format_cpu_details(cpu: &MOS6502, use_color: bool) -> String {\n\n let flags = cpu.get_status_register();\n\n let fmt = |f: char, b: u8| if b != 0 { f } else { '-' };\n\n let flags = vec![\n\n fmt('N', flags & 128),\n\n fmt('V', flags & 64),\n\n '-',\n\n ...
Rust
src/lib.rs
emallson/setlike
eaa13b1d7c2ee42323ea018f6fd15e670230aa00
#[cfg(feature = "bit-set")] use bit_set::BitSet; #[cfg(feature = "hashbrown")] use hashbrown::HashSet as HashBrownSet; use std::collections::{BTreeSet, HashSet}; use std::hash::{BuildHasher, Hash}; #[cfg(test)] #[macro_use] extern crate quickcheck; pub trait Setlike<T: Sized> { fn contains(&self, el: &T) -> b...
#[cfg(feature = "bit-set")] use bit_set::BitSet; #[cfg(feature = "hashbrown")] use hashbrown::HashSet as HashBrownSet; use std::collections::{BTreeSet, HashSet}; use std::hash::{BuildHasher, Hash}; #[cfg(test)] #[macro_use] extern crate quickcheck; pub trait Setlike<T: Sized> { fn contains(&self, el: &T) -> b...
use std::collections::HashSet; ); set_test!( btree_set, BTreeSet<usize>, usize, use std::collections::BTreeSet; ); }
_capacity_and_hasher(k, S::default()) } } impl<T: Sized + Ord> Setlike<T> for BTreeSet<T> { fn len(&self) -> usize { self.len() } fn contains(&self, el: &T) -> bool { self.contains(el) } fn insert(&mut self, el: T) -> bool { self.insert(el) } fn remove(&mut se...
random
[ { "content": "# setlike\n\nA small rust library to describe setlike objects.\n\n\n\n```toml\n\n[dependencies]\n\nsetlike = {version = \"0.1\", git = \"https://github.com/emallson/setlike.git\"}\n\n```\n\n\n\nThe fundamental purpose of this library is to provide a way to abstract over the most basic set operatio...
Rust
benches/lua.rs
parampavar/vector
83bd797ff6a05fb3246a2442a701db3a85e323b5
use std::pin::Pin; use criterion::{criterion_group, BatchSize, Criterion, Throughput}; use futures::{stream, SinkExt, Stream, StreamExt}; use indexmap::IndexMap; use indoc::indoc; use transforms::lua::v2::LuaConfig; use vector::{ config::{TransformConfig, TransformContext}, event::Event, test_util::{collec...
use std::pin::Pin; use criterion::{criterion_group, BatchSize, Criterion, Throughput}; use futures::{stream, SinkExt, Stream, StreamExt}; use indexmap::IndexMap; use indoc::indoc; use transforms::lua::v2::LuaConfig; use vector::{ config::{TransformConfig, TransformContext}, event::Event, test_util::{collec...
}), ]; for (name, transform) in benchmarks { let (tx, rx) = futures::channel::mpsc::channel::<Event>(num_events as usize); let mut rx: Pin<Box<dyn Stream<Item = Event> + Send>> = match transform { Transform::Function(t) => { let mut t = t.clone(); B...
}) }), ("v1", { let source = String::from(indoc! {r#" if event["the_field"] ~= "0" then event = nil end "#}); Transform::event_task(transforms::lua::v1::Lua::new(source, vec![]).unwrap()) }), ...
random
[ { "content": "fn rename_key_flat(c: &mut Criterion) {\n\n let mut group: BenchmarkGroup<WallTime> =\n\n c.benchmark_group(\"vector_core::event::log_event::LogEvent::rename_key_flat\");\n\n group.sampling_mode(SamplingMode::Auto);\n\n\n\n group.bench_function(\"rename_flat_key (key is present)\",...
Rust
datafusion/physical-expr/src/planner.rs
r4ntix/arrow-datafusion
930653415c6303b34f856826ba73717b25b9574c
use crate::{ execution_props::ExecutionProps, expressions::{ self, binary, CaseExpr, Column, DateIntervalExpr, GetIndexedFieldExpr, Literal, }, functions, udf, var_provider::VarType, PhysicalExpr, }; use arrow::{ compute::can_cast_types, datatypes::{DataType, Schema}, }; use da...
use crate::{ execution_props::ExecutionProps, expressions::{ self, binary, CaseExpr, Column, DateIntervalExpr, GetIndexedFieldExpr, Literal, }, functions, udf, var_provider::VarType, PhysicalExpr, }; use arrow::{ compute::can_cast_types, datatypes::{DataType, Schema}, }; use da...
} }) .collect::<Result<Vec<_>>>()?; expressions::in_list(value_expr, list_exprs, negated) } }, other => Err(DataFusionError::NotImplemented(format!( "Physical plan does not support logical expressio...
if can_cast_types( &list_expr_data_type, &value_expr_data_type, ) { expressions::cast( list_expr, input_schema, ...
if_condition
[ { "content": "/// Create an in_list expression\n\npub fn in_list(expr: Expr, list: Vec<Expr>, negated: bool) -> Expr {\n\n Expr::InList {\n\n expr: Box::new(expr),\n\n list,\n\n negated,\n\n }\n\n}\n\n\n", "file_path": "datafusion/expr/src/expr_fn.rs", "rank": 0, "score": ...
Rust
src/application.rs
plyhun/plygui-gtk
01b1c339212b72cb99f72f09a5e13dbcc240c416
use crate::common::{self, *}; use gio::ApplicationFlags; use glib::{self, Continue}; use gtk::Application as GtkApplicationSys; use std::any::TypeId; const DEFAULT_FRAME_SLEEP_MS: u32 = 100; pub struct GtkApplication { app: GtkApplicationSys, name: String, selfptr: *mut Application, sleep: u32, } p...
use crate::common::{self, *}; use gio::ApplicationFlags; use glib::{self, Continue}; use gtk::Application as GtkApplicationSys; use std::any::TypeId; const DEFAULT_FRAME_SLEEP_MS: u32 = 100; pub struct GtkApplication { app: GtkApplicationSys, name: String, selfptr: *mut Application, sleep: u32, } p...
fn exit(&mut self) { let base = &mut unsafe { &mut *self.selfptr }.base; for mut window in base.windows.drain(..) { window.as_any_mut().downcast_mut::<crate::window::Window>().unwrap().inner_mut().inner_mut().inner_mut().inner_mut().close(true); } for mut tray in base.tr...
k, mpsc::TryRecvError::Disconnected => unreachable!(), }, } } glib::usleep(a.inner().sleep as u64); Continue(true) }); } gtk::main() }
function_block-function_prefixed
[ { "content": "pub fn make_menu<T: controls::Member>(menu: GtkMenuShell, mut items: Vec<types::MenuItem>, storage: &mut Vec<callbacks::Action>, item_spawn: fn(id: usize, selfptr: *mut T) -> GtkMenuItem, selfptr: *mut T) {\n\n let mut options = Vec::new();\n\n let mut help = Vec::new();\n\n\n\n let make_...
Rust
editors/xi-term/vendor/clippy_lints/src/shadow.rs
babariviere/nix-local
2080b0deeedc1eeef3d8561a1cfa4666c3cb7df1
use reexport::*; use rustc::lint::*; use rustc::hir::*; use rustc::hir::intravisit::FnKind; use rustc::ty; use syntax::codemap::Span; use utils::{contains_name, higher, in_external_macro, iter_input_pats, snippet, span_lint_and_then}; declare_lint! { pub SHADOW_SAME, Allow, "rebinding a name to itself, e.g...
use reexport::*; use rustc::lint::*; use rustc::hir::*; use rustc::hir::intravisit::FnKind; use rustc::ty; use syntax::codemap::Span; use utils::{contains_name, higher, in_external_macro, iter_input_pats, snippet, span_lint_and_then}; declare_lint! { pub SHADOW_SAME, Allow, "rebinding a name to itself, e.g...
fn check_expr<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, bindings: &mut Vec<(Name, Span)>) { if in_external_macro(cx, expr.span) { return; } match expr.node { ExprUnary(_, ref e) | ExprField(ref e, _) | ExprTupField(ref e, _) | ExprAddrOf(_, ref e) | ExprBox(ref e) => { ...
fn lint_shadow<'a, 'tcx: 'a>( cx: &LateContext<'a, 'tcx>, name: Name, span: Span, pattern_span: Span, init: Option<&'tcx Expr>, prev_span: Span, ) { if let Some(expr) = init { if is_self_shadow(name, expr) { span_lint_and_then( cx, SHADOW_S...
function_block-full_function
[ { "content": "# nix-local\n\nMy local nix repository\n", "file_path": "README.md", "rank": 0, "score": 2934.0904429706256 } ]