lang
stringclasses 10
values | seed
stringlengths 5
2.12k
|
---|---|
rust |
impl PartialEq for IndexValuePair {
fn eq(&self, other: &Self) -> bool {
self.value == other.value
} |
rust | /// "iat": 1328550785
/// }
/// ```
#[derive(Debug, Serialize)]
pub struct Claims {
iss: String,
scope: String,
aud: String,
exp: u64,
iat: u64,
}
impl Claims { |
rust | //!
//! ### Mutations
//!
//! GraphQL mutations provide a way to update or create state in the Core.
//!
//! Similarly to queries, mutations have access to a context object and can
//! manipulate windows, menus or global state.
//!
//! ```rust
//! use juniper::{graphql_object, EmptySubscription, EmptyMutation, FieldResult, GraphQLObject, RootNode};
//! use tauri_plugin_graphql::Context as GraphQLContext;
//! use tauri::Manager;
//! use std::sync::Mutex;
//!
//! #[derive(Debug, Default)] |
rust | pub fn srt(self, scale: Vector, rotate: Rotation, translate: Vector)
-> Self
{
self.s(scale).r(rotate).t(translate)
}
/// Rotate Quaternion (axis, angle), then translate.
#[inline(always)]
pub fn rt(self, rotate: Rotation, translate: Vector) -> Self {
self.r(rotate).t(translate)
} |
rust | if !simplified_bindings.contains_key(&var) {
if let Some(value) = bindings.get(&var) {
let (simplified, mut symbols) = simplify_var(&bindings, &var, value);
simplified_bindings.insert(var.clone(), simplified);
referenced_vars.extend(symbols.drain());
} |
rust | }
fn apply(&mut self, value: &dyn Reflect) {
if let ReflectRef::Map(map_value) = value.reflect_ref() {
for (key, value) in map_value.iter() {
if let Some(v) = Map::get_mut(self, key) {
v.apply(value)
}
}
} else {
panic!("Attempted to apply a non-map type to a map type.");
}
}
fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>> { |
rust | if slice.iter().map(|x| x.position).all_equal() {
slice.iter_mut().for_each(|x| x.destroyed = true);
}
}
destroyed.extend(particles.iter().filter(|x| x.destroyed).cloned());
particles.retain(|x| !x.destroyed);
}
|
rust | }
Dir::Horiz
}
// Polygon and Path elements always horizontal, at least for now
Shape::Poly { .. } | Shape::Path { .. } => Dir::Horiz,
}
}
/// Shift coordinates by the (x,y) values specified in `pt`
pub fn shift(&mut self, pt: &Point) {
match *self {
Shape::Rect {
ref mut p0,
ref mut p1, |
rust | ///
/// See: [List
/// OnCalls](https://developer.pagerduty.com/api-reference/b3A6Mjc0ODE2Mw-list-all-of-the-on-calls)
pub fn all<Q>(client: &Client, page_size: usize, params: &'static Q) -> Stream<OnCall>
where
Q: Serialize + ?Sized + std::marker::Sync,
{
client.get_stream("oncalls", "/oncalls", page_size, params)
}
#[cfg(test)]
mod test {
use crate::{models, oncalls, Client, StreamExt, NO_QUERY};
use futures::TryStreamExt;
use tokio::test; |
rust | assert_eq!(format!("{:?}", Dataspace::new(3, true).unwrap()),
"<HDF5 dataspace: (3,)>");
assert_eq!(format!("{}", Dataspace::new((1, 2), true).unwrap()),
"<HDF5 dataspace: (1, 2)>");
assert_eq!(format!("{:?}", Dataspace::new((1, 2), true).unwrap()),
"<HDF5 dataspace: (1, 2)>");
}
#[test]
pub fn test_dataspace() {
silence_errors();
assert_err!(Dataspace::new(H5S_UNLIMITED as usize, true), |
rust | objects: vec![
Box::new(floor),
Box::new(left),
Box::new(middle),
Box::new(right),
],
// The light source is white, shining from above and to the left |
rust | }
}
impl<'s, T> System<'s> for Pausable<T>
where
T: System<'s>, |
rust | fn bin_or_assign(&mut self, bin: JsSyntaxKind, assign: JsSyntaxKind) -> JsSyntaxKind {
if let Some(b'=') = self.next_byte() {
self.next_byte();
assign
} else {
bin
}
}
#[inline] |
rust | // mesh_all::normal::mesh_six::mesh_six,
// mesh_all::normal::mesh_seven::mesh_seven,
// mesh_all::normal::mesh_eight::mesh_eight,
// mesh_all::normal::mesh_nine::mesh_nine,
// mesh_all::normal::mesh_ten::mesh_ten,
// mesh_all::normal::mesh_eleven::mesh_eleven,
// mesh_all::normal::mesh_twenty::mesh_twenty,
// ////////// |
rust | pub fn is_stored(attrs: Raw) -> bool {
if (attrs & UNDEFS) != 0 {
return false;
}
if (attrs & DATA) != 0 {
return (attrs & ACCESSOR) == 0;
}
if (attrs & ACCESSOR) != 0 {
return (attrs & WRITABLE) == 0;
}
false
}
pub fn remove_undefs(attrs: Raw) -> Raw {
attrs & !(UNDEFS) |
rust | mod statistics;
pub use about::*;
pub use connections::*;
pub use installation::*;
pub use logs::*;
pub use settings::*; |
rust | ))
.unwrap();
let mut dec2 = get_decoder(&format!(
"{}/../testfiles/yuv444p8_output.y4m",
env!("CARGO_MANIFEST_DIR")
))
.unwrap();
let result = calculate_video_msssim(&mut dec1, &mut dec2, None, |_| ()).unwrap();
assert_metric_eq(18.8897, result.y);
assert_metric_eq(17.6092, result.u);
assert_metric_eq(19.2732, result.v); |
rust | //
// #[test]
// fn spawn_kill_dead_stream() {
// use std::thread;
// use std::time::Duration;
// use futures::future::Either;
// use futures::sync::oneshot;
//
// // a future which never returns anything (forever accepting incoming
// // connections), but dropping it leads to observable side effects
// // (like closing listening sockets, releasing limited resources,
// // ...)
// #[derive(Debug)]
// struct Dead {
// // when dropped you should get Err(oneshot::Canceled) on the |
rust | /// Drop a `Vec<T>` where `T: Drop`. This triggers a call to `drop_in_place::<[T]>`, which uses a
/// few operations that aren't seen in other drop glues.
struct S(i32);
impl Drop for S {
fn drop(&mut self) {
// No-op
} |
rust | .subcommand(
clap::SubCommand::with_name("copy")
.about("deploy by copying files to a local directory (implies build)"),
)
.subcommand(
clap::SubCommand::with_name("upload")
.about("deploy by uploading files to a remote server (implies build)"),
),
)
}
|
rust | pub name: String,
pub description: Option<String>,
pub directory: Option<String>,
pub repository: Option<String>,
pub commit: Option<String>,
pub version: Option<String>,
pub leftwm_versions: Option<String>,
pub current: Option<bool>,
pub dependencies: Option<Vec<DependencyL>>,
#[serde(skip)] |
rust | fn change_by_pointer() {
let mut storage = Storage::new();
storage.create(4 as i32);
let ptr = {
let item = storage.iter().next().unwrap();
storage.pin(&item)
};
assert_eq!(storage[&ptr], 4); |
rust |
let out_dir = std::env::var("AMQ_PROTOCOL_CODEGEN_DIR")
.or(std::env::var("OUT_DIR"))
.expect("OUT_DIR is not defined");
let out_file =
std::env::var("AMQ_PROTOCOL_CODEGEN_FILE").unwrap_or_else(|_| "protocol".to_string());
let template = include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/templates/protocol.rs"
));
CodeGenerator::simple_codegen(&out_dir, &out_file, "protocol", template, "protocol"); |
rust | pub struct LongFiParser {}
impl LongFiParser {
pub fn new() -> LongFiParser {
LongFiParser {}
}
pub fn parse(&mut self, pkt: &messages::RadioRxPacket) -> Option<LongFiResponse> {
if let Some(req) = lfc::parse(pkt) { |
rust | let hdr = pcap_pkthdr {
ts: timeval {
tv_sec: 0,
tv_usec: 0,
},
caplen: packet.len() as u32,
len: orig_len,
};
let data = packet.as_ptr();
unsafe {
pcap_offline_filter(
(&mut self.0) as *mut bpf_program, |
rust | pub adapter: A,
/// Value retrieved from cache.
pub result: CachedValue<T>,
}
/// Required `Debug` implementation to use `instrument` macro.
impl<A, T> fmt::Debug for CachePolledStale<A, T>
where
A: RuntimeAdapter,
T: CacheableResponse,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("CachePolledStale")
} |
rust |
fn is_valid_identifier(c: &char) -> bool {
c.is_alphabetic() || c.is_numeric() || *c == '_'
}
fn is_valid_numeric(c: &char) -> bool {
c.is_numeric() || *c == '.'
}
#[cfg(test)]
mod tests {
use super::*; |
rust | fn arg_closure() {
with(|&_x| ())
//~^ ERROR cannot move out of dereference of & pointer
}
fn let_pat() {
let &_x = &~"hi";
//~^ ERROR cannot move out of dereference of & pointer
}
pub fn main() {}
|
rust |
fn res_list(&self) -> Result<Box<dyn Iterator<Item = String>>, ResourceError> {
let iter: Vec<String> = self.includes.iter()
.map(|(name, _)| (*name).to_string())
.collect() |
rust | }
pub fn health(_: &HttpRequest<AppState>) -> impl Responder {
"OK".to_string()
}
pub fn json_error_handler(err: error::JsonPayloadError, _: &HttpRequest<AppState>) -> Error {
error::InternalError::from_response(
"",
HttpResponse::BadRequest() |
rust | }
pub fn set_char(&mut self, x: usize, y: usize, glyph: char) {
self.cells[x + y * self.width].glyph = glyph;
}
pub fn set_fg(&mut self, x: usize, y: usize, color: Color) {
self.cells[x + y * self.width].foreground = color;
}
pub fn set_bg(&mut self, x: usize, y: usize, color: Color) {
self.cells[x + y * self.width].background = color;
}
|
rust | use serde::{Deserialize, Serialize};
use super::Position;
#[derive(Debug, Serialize, Deserialize)]
pub struct Teleportation {
pub position: Position,
pub teleport: Position,
}
|
rust |
impl PartialEq for KVPair {
fn eq(&self, other: &Self) -> bool {
self.0.eq(&other.0)
}
}
impl Eq for KVPair {}
impl Ord for KVPair {
fn cmp(&self, other: &Self) -> Ordering {
self.0.cmp(&other.0)
} |
rust | } else {
construct_youtube_search_url(&query[3..])
}
}
pub fn construct_youtube_profile_url(profile: &str) -> String {
format!("https://youtube.com/c/{}", profile)
}
|
rust | #[derive(Serialize, Deserialize, Debug, Clone)]
pub struct SubSlotBundle {
pub challenge_chain: ChallengeChainSubSlot,
pub infused_challenge_chain: Option<InfusedChallengeChainSubSlot>,
pub reward_chain: RewardChainSubSlot,
pub proofs: SubSlotProofs,
} |
rust | best_effort: bool,
) -> Result<Self::Balance, DispatchError> {
Ok(amount)
}
fn transfer_held(
asset: Self::AssetId,
source: &AccountId,
dest: &AccountId, |
rust | fn get_memory_usage(&self) -> usize {
mem::size_of::<Vec<T>>() + self.capacity() * mem::size_of::<T>()
}
}
impl MemoryUsage for LargeBlock {
fn get_memory_usage(&self) -> usize {
mem::size_of::<u64>() * 2
}
}
impl MemoryUsage for LastBlock { |
rust | macro_rules! exprloc {
() => {
if let Some(value) = self.exprloc_value() {
return AttributeValue::Exprloc(value);
}
};
}
macro_rules! flag { |
rust | to: b,
};
let border = Line { point: point(0.0, y_max), vector: vector(1.0, 0.0) };
let l = Line { point: p, vector: dir };
let border_intersection = l.intersection(&border).unwrap(); |
rust | // their DER encoding to what we'll do with them. We don't
// overwrite existing elements, which mean User settings
// trump Admin trump System, as desired.
let mut all_certs = HashMap::new();
for domain in &[Domain::User, Domain::Admin, Domain::System] {
let ts = TrustSettings::new(*domain);
let iter = ts
.iter()
.map_err(|err| Error::new(ErrorKind::Other, err))?;
for cert in iter {
let der = cert.to_der(); |
rust | pub fn get_moves<P: AsRef<Path>>(moves: P) -> Moves {
let moves = moves.as_ref();
read_dir(moves)
.unwrap_or_else(|err| {
panic!( |
rust | impl<'a> SoundSomething<'a> {
pub fn new(sound: &'a dyn SoundPressure<'a>) -> Self {
Self { sound }
}
pub fn read(&self) -> u8 {
// self.sound.enable();
// self.sound.disable();
unimplemented!()
} |
rust | }
}
impl Plugin for Colortest {
fn record_geometry(&self, _command_buffer: CommandBuffer) {
}
fn record_transparent(&self, _command_buffer: CommandBuffer) {
} |
rust |
Ok(())
}
/// Generate a unique, stable package name from the metadata.
fn make_hashed_name(dep: &PackageMetadata<'_>) -> String {
// Use a fixed seed to ensure stable hashes.
let mut hasher = XxHash64::default(); |
rust | }
}
for (file_path, content) in self.file_manager.files.iter() {
parse(
content,
file_path.clone(),
&mut program,
&mut self.location_info,
)?;
}
let mut resolver = Resolver::new();
let mut ir_program = resolver.resolve(&program)?;
|
rust | extern crate chrono;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate chef_api;
extern crate failure;
pub mod models;
|
rust | }
}
}
#[proc_macro_derive(DropStructMacro)]
pub fn drop_struct_macro_derive(input: TokenStream) -> TokenStream {
let ast: syn::DeriveInput = syn::parse(input).unwrap(); |
rust |
pub trait ResultOps<T, E> {
fn bi_map<A, B, D: FnOnce(E) -> B, F: FnOnce(T) -> A>(self, l: D, r: F) -> Result<A, B>;
}
impl<T, E> ResultOps<T, E> for Result<T, E> {
fn bi_map<A, B, D: FnOnce(E) -> B, F: FnOnce(T) -> A>(self, l: D, r: F) -> Result<A, B> {
match self {
Ok(t) => Ok(r(t)),
Err(e) => Err(l(e)),
}
}
} |
rust | };
let config_d = statecs::Config {
unchecked_entity_delete: false,
component_bookkeeping: true,
.. config_a
};
let config_e = statecs::Config {
ecs_ctx_hash_collections: true,
ecs_action_hash_collections: true,
.. config_a
};
let config_f = statecs::Config { unchecked_entity_delete: false, .. config_a }; |
rust |
let mut off = off;
let mut len = len;
let mut cb: i32 = 0;
match self.cache.borrow().as_ref() {
Some(cache) => {
if self.pos.get() >= cache.pos {
let bytes_available_in_cache =
cache.pos as usize + cache.uncompressed_data.len() - self.pos.get() as usize;
if bytes_available_in_cache > 0 { |
rust | pub async fn wait_for_quorum<C: Store + Sync + Send>(
config: &C,
experiment: &Experiment,
) -> Result<(), Error> {
wait_for_quorum_helper(config, experiment, RETRY_DELAY, RETRY_ATTEMPTS).await
}
#[cfg(test)]
mod test {
use super::*;
use crate::{
config::{factory::from_string, tests::inmem_stores},
experiment::Experiment,
net::tests::addrs, |
rust | let (client, db) = init_db(
&config.database.database_url.clone(),
&config.database.database_name.clone(),
).map_err(|e| e.to_string())?;
// Check theme for scss and compile it.
//
// Throw error as string to Result.
let mut sass = Sass::new(
config.clone(),
theme_config.clone()
).map_err(|e| e.to_string())?; |
rust | if let Some(ref draw) = self.steep_streets {
g.redraw(draw);
}
}
}
fn update_panel(&mut self, ctx: &mut EventCtx, app: &App) {
self.panel = Panel::new_builder(Widget::col(vec![
make_zoom_controls(ctx).align_right().padding_right(16),
self.make_legend(ctx, app)
.padding(16)
.bg(ctx.style().panel_bg), |
rust | A connection from ground to the 10K resistor, to the light defined resistor, to 5V. Additionally the Analog port 5 of the arduino needs to be connected between the 10K and light defined resistor.
!*/
#![no_std]
#![no_main]
use arduino_hal::prelude::*;
use panic_halt as _;
use arduino_hal::adc;
#[arduino_hal::entry]
fn main() -> ! {
let dp = arduino_hal::Peripherals::take().unwrap(); |
rust | /// (if you want to prepend or append, for instance).
///
/// This function is unsafe as it mutates the global state but cannot guarantee
/// thread-safety. It needs to be externally synchronized with calls to access
/// the global state.
pub unsafe fn set_search_path<P>(level: ConfigLevel, path: P) -> Result<(), Error>
where
P: IntoCString,
{
crate::init();
call::c_try(raw::git_libgit2_opts(
raw::GIT_OPT_SET_SEARCH_PATH as libc::c_int,
level as libc::c_int, |
rust | // impl Type {
// pub fn apply(self, to: impl Into<Box<Type>>) -> Self {
// Type::Application(Box::new(self), to.into())
// }
// pub fn kind(&self) -> &Kind {
// match self {
// Type::Var(v) => &v.kind,
// Type::Constructor(c) => &c.kind,
// Type::Application(l, _) => {
// match l.kind() {
// Kind::Arrow(_, kind) => &*kind,
// _ => unreachable!(),
// }
// } |
rust | use std::path::PathBuf;
use structopt::StructOpt;
#[derive(StructOpt)]
pub struct Cli {
pub r#type: String, |
rust | pub async fn start(self: &Arc<Model>) {
// Normally the Discovered event is dispatched when an instance is added as a child, but
// since the root isn't anyone's child we need to dispatch it here.
{
let mut actions = self.root.lock_actions().await;
// This returns a Future that does not need to be polled.
let _ = actions.register_no_wait(&self.root, DiscoverAction::new());
}
// In debug mode, we don't start the component root. It must be started manually from
// the lifecycle controller.
if !self.context.runtime_config().debug {
if let Err(e) = self.start_instance(&AbsoluteMoniker::root(), &StartReason::Root).await |
rust | resources.insert(viewport);
resources.insert(DebugDrawResource::new());
resources.insert(EditorDrawResource::new());
use minimum_winit::input::WinitKeyboardKey;
use skulpin::winit::event::VirtualKeyCode;
let keybinds = minimum::resources::editor::Keybinds { |
rust | }
}
v[j] = v[v.len()-1];
v.truncate(j+1);
}
pub fn arrayvec_dedup<A: Array>(v: &mut ArrayVec<A>)
where A::Item: Copy + PartialEq {
arrayvec_dedup_by(v, |&a, &b| a == b); |
rust | fn multiple_of_any(min: u64, max: u64, multiple_predicates: &[u64]) -> u64 {
(min..max)
.filter(|n| multiple_predicates.iter().any(|p| n % p == 0))
.sum()
}
fn main() {
println!("{}", multiple_of_any(0, 1000, &[3, 5]))
}
|
rust | }
pub fn with_title(mut self, title: &'a str) -> Self {
self.title = Some(title);
self
}
pub fn with_icon(mut self, icon: Icon<'a>) -> Self {
self.icon = Some(icon);
self
}
fn title(&self) -> &'a str { |
rust | let submission = ::pgx::utils::sql_entity_graph::PostgresHashEntity {
name: stringify!(#name),
file: file!(),
line: line!(),
full_path: core::any::type_name::<#name>(),
module_path: module_path!(),
id: TypeId::of::<#name>(),
to_sql_config: #to_sql_config,
};
::pgx::utils::sql_entity_graph::SqlGraphEntity::Hash(submission)
} |
rust | }
}
/// Matrix-vector product of the diagonal matrix and the given vector
/// # Panics
/// operation panics if the matrix and vector dimensions are incorrect for a product
/// (unit weights never panic)
#[allow(non_snake_case)]
impl<ScalarType> Mul<DVector<ScalarType>> for &Weights<ScalarType>
where
ScalarType: ClosedMul + Scalar + ComplexField,
{
type Output = DVector<ScalarType>;
|
rust | try_parse(lexer, f).map(Some).or(Ok(None))
}
fn many<T, F>(lexer: &mut Lexer, f: F) -> ParseResult<Vec<T>>
where F: Fn(&mut Lexer) -> ParseResult<T>
{
let mut vals = Vec::new();
while let Ok(v) = f(lexer) {
vals.push(v);
}
Ok(vals)
}
|
rust | let rights = get_rights(&file)?;
let handle = unsafe { RawOsHandle::from_raw_fd(file.into_raw_fd()) };
Ok(Self::new(rights, handle))
}
}
fn get_rights(file: &File) -> io::Result<HandleRights> {
use yanix::{fcntl, file::OFlag}; |
rust | (&Method::Get, "/pubkey.pem") => {
let mut path = {
let config = match self.config.read() {
Ok(c) => c,
Err(e) => {
warn!("Failed to get read lock: {:?}", e);
return internal_server_error();
}
};
config.key_path.clone()
};
path.push("ecpubkey.pem");
read_file(&path)
} |
rust | use crate::models::database::Static;
use crate::database::DB_POOL;
use diesel::prelude::*;
pub fn get_statics_for_page(route: &str, page: &str) -> Vec<Static> {
use crate::schema::pages;
use crate::schema::statics;
let connection = &*DB_POOL.get().unwrap();
} |
rust | // your code
}
fn variance(town: &str, strng: &str) -> f64 {
3.0
// your code
}
#[cfg(test)]
mod tests {
use super::*; |
rust | ///
pub fn member_name(&self) -> &Option<Identifier> {
&self.member_name
}
///
/// Returns `true` if this `ShapeID` has a member name component, else `false`.
///
pub fn is_member(&self) -> bool {
self.member_name.is_some()
} |
rust |
fn get_version() -> (u32, u32, u32, u32) {
// let mut v1 = 0;
// let mut v2 = 0;
// let mut v3 = 0;
// let mut v4 = 0;
// unsafe {
// let fill_version: unsafe extern "cdecl" fn(
// param_1: *mut libc::c_uint,
// param_2: *mut libc::c_uint,
// param_3: *mut libc::c_uint,
// param_4: *mut libc::c_uint,
// ) = std::mem::transmute(0x00d31380 as *const ());
// (fill_version)(&mut v1, &mut v2, &mut v3, &mut v4); |
rust |
pub type Result<T, E = Error> = std::result::Result<T, E>;
#[derive(Clone, Debug, Error, PartialEq)]
pub enum Error {
#[error("{}: {:?}", msg::ERR_ARG_NOT_CONVERTIBLE_TO_UTF_8, 0)]
ArgNotConvertibleToUtf8(std::ffi::OsString), |
rust | pub fn private_key(&self) -> Option<String> {
self.private_key.clone()
}
pub fn certificate(&self) -> Option<String> {
self.certificate.clone()
}
pub fn ca_file(&self) -> Option<String> {
self.ca_file.clone()
} |
rust | }
#[derive(Deserialize, Debug, PartialEq, Clone)]
struct Cluster {
name: String,
cluster: ClusterInfo,
}
#[derive(Deserialize, Debug, PartialEq, Clone)] |
rust | use types::Phase;
const ARG_PHASE: &str = "phase";
#[no_mangle]
pub extern "C" fn call() {
let known_phase: Phase = runtime::get_named_arg(ARG_PHASE);
let get_phase = runtime::get_phase();
assert_eq!(
get_phase, known_phase, |
rust | // Default value = "30 seconds"
default_test_warning_time_limit: "10 millis",
console_output: integra8_serde_formatter::SerdeFormatter,
// Console output parameters will be documented once
// the design is finalized
//console_output_ansi_mode: Auto, |
rust |
mod inject_component;
mod inject_provided;
pub use inject_component::Inject;
pub use inject_provided::InjectProvided; |
rust | "Boise" => 43.6, -116.2, 808.;
"Springfield" => 39.78, -89.65, 190.;
"Indianapolis" => 39.77, -86.15, 238.;
"Des Moines" => 41.58, -93.62, 276.;
"Topeka" => 39.05, -95.68, 289.;
"Frankfort" => 38.18, -84.85, 243.; |
rust | pub trait Editor {
}
|
rust | falcon_member_cid: Option<String>,
}
impl Credentials {
pub fn from_env() -> Result<Self, CredentialsError> { |
rust | use common::bevy::utils::HashMap;
use common::bevy_networking_turbulence::{
ConnectionHandle, NetworkEvent, NetworkResource, NetworkingPlugin,
};
use common::events::*;
use common::game::{validate_player_command, GameInfo, Movable, PlayerControllable, Location};
use common::get_random;
use common::protocol::{ClientIdentification, NetworkSync};
use std::net::SocketAddr;
use std::time::Duration;
|
rust | pub struct Message {
pub payload: [usize; IPC_MAX_ARGS],
pub payload_len: usize,
pub need_reply: bool,
pub cap_transfer: Option<CapSlot>, |
rust | let (statements, reference, write_back) = if im == InputModifier::In {
(vec![], load, WriteBack::Fail)
} else {
let init = if im == InputModifier::InOut {
Some(hir::Initializer::Expression(load))
} else {
None
};
let id = try!(allocate_local("tex", ty.clone(), context)); |
rust | }
}
}
}
}
}
}
fn print_legend() {
let mut t = term::stdout().unwrap();
t.fg(term::color::BRIGHT_GREEN).unwrap();
write!(t, " Legend ").unwrap();
t.fg(term::color::BRIGHT_CYAN).unwrap();
write!(t, "QoS 0 ").unwrap(); |
rust | use graphics::Color;
use sfml_types::Vector2f;
use csfml_graphics_sys as ffi;
/// Define a point with color and texture coordinates
///
/// A vertex is an improved point.
/// |
rust | extern crate rand;
extern crate rayon;
pub mod shape;
pub mod canvas;
pub mod color; |
rust | const COPY_SIZE: usize = 512;
while src.len() >= COPY_SIZE {
#[allow(clippy::ptr_offset_with_cast)]
let (src_word, src_rem) = array_refs![src, COPY_SIZE; ..;];
#[allow(clippy::ptr_offset_with_cast)]
let (dst_word, dst_rem) = mut_array_refs![dst, COPY_SIZE; ..;];
*dst_word = *src_word; |
rust | #[hdk_extern]
fn must_get_valid_element(header_hash: HeaderHash) -> ExternResult<Element> {
hdk::prelude::must_get_valid_element(header_hash)
}
|
rust | let _addr = server::new(|| {
App::with_state(AppState {
foo: "bar".to_string(),
}).middleware(middleware::Logger::default())
.resource("/", |r| {
r.method(http::Method::GET).with(index);
})
.resource("/post1", |r| {
r.method(http::Method::POST).with(handle_post_1)
})
.resource("/post2", |r| {
r.method(http::Method::POST).with(handle_post_2)
}) |
rust | #[derive(FromForm, Debug)]
struct TokenForm {
grant_type: String,
code: String,
redirect_uri: String,
client_id: String,
client_secret: String,
}
#[derive(Serialize)]
struct AuthResponse {
token_type: String, |
rust | self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _STARTW<'a> {
w: &'a mut W,
}
impl<'a> _STARTW<'a> { |
rust | <main>
<Switch<Route> render={Switch::render(switch)} />
</main>
<footer class="footer">
<div class="content has-text-centered"> |
rust | line_numbers: HashSet<LineNumber>,
delims: BreakableDelims,
}
impl BreakableEntry { |
rust | let result = toyyyymm.eval(&columns, block.num_rows())?;
assert_eq!(result.len(), 4);
assert_eq!(result.data_type(), DataType::UInt32);
let actual_ref = result
.to_array()?
.u32()?
.inner()
.values()
.as_slice()
.to_vec();
assert_eq!(vec![197001u32, 197001u32, 197001u32, 197001u32], actual_ref);
}
|
rust | assert_eq!(deunicode("മലയാലമ്"), "mlyaalm");
assert_eq!(deunicode("げんまい茶"), "genmaiCha");
assert_eq!(deunicode("🦄☣"), "unicorn biohazard");
assert_eq!(deunicode("🦄 ☣"), "unicorn biohazard");
assert_eq!(deunicode(" spaces "), " spaces ");
assert_eq!(deunicode(" two spaces "), " two spaces ");
assert_eq!(deunicode(&[std::char::from_u32(849).unwrap()].iter().collect::<String>()), "[?]");
assert_eq!(deunicode_with_tofu(&[std::char::from_u32(849).unwrap()].iter().collect::<String>(), "tofu"), "tofu");
} |
rust | err!(int: "{} is not a number", int);
return quote!();
}
}
} else {
err!(expr_lit: "Enum variant must be an integer.");
return quote!();
}
} |
rust | <gh_stars>100-1000
pub struct SparseSdf {
pub data: Vec<u8>,
}
impl SparseSdf {
pub fn add_node() {}
}
|
rust |
fn is_file(&self) -> bool {
self.entry.is_file()
}
fn is_hidden(&self) -> bool {
// Roots are never hidden; we always want to show them since the user gave them to us
// explicitly.
// Roots can also have the name ".", so they would appear to be hidden in that case unless
// we handle it differently.
false |
rust | //--------------------------------------------------------------
// M-2
for name in &names {
println!("{}", name);
}
//--------------------------------------------------------------
// M-3
// If this line doesn't exist, then it throws error like 'can't be used' as already used before in `for-range`
let names: Vec<&str> = vec!["Abhi", "Sam", "McLaren", "Gary"];
let mut iterator = (&names).into_iter();
while let Some(name) = iterator.next() {
println!("{}", name);
} |
rust | use crate::SITE_NAME;
use db::models::*;
use diesel::pg::PgConnection;
pub fn invite_user_to_organization_email(
config: &Config,
invite: &OrganizationInvite,
org: &Organization,
recipient_name: &str,
conn: &PgConnection,
) -> Result<(), ApiError> {
let invite_link_accept = format!(
"{}/invites/accept?token={}",
config.front_end_url.clone(),
invite.security_token.expect("Security token is not set") |
Subsets and Splits