text stringlengths 8 4.13M |
|---|
extern crate bencode;
use self::bencode::Bencode;
use self::bencode::util::ByteString;
use std::{convert, io};
#[macro_export]
macro_rules! get_field_with_default {
($m:expr, $field:expr, $default:expr) => (
match $m.get(&ByteString::from_str($field)) {
Some(a) => try!(FromBencode::from_bencod... |
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
use crate::{
block::{self, BlockId},
color_system,
dicebot::{self, bcdice},
idb,
model::{self, modeless::ModelessId},
random_id::U128Id,
renderer::Renderer,
resource::{Data, ResourceId},
skyway, udonarium, Color,
};
use kagura::prelude::*;
use std::{
collections::{HashMap, HashSe... |
use iron::prelude::*;
use serde_json::Value;
use common::http::*;
use common::utils::*;
use common::utils::is_admin as check_is_admin;
use services::user::{get_username, get_user, get_user_id};
use services::topic::*;
use services::topic::create_topic as service_create_topic;
use services::topic::delete_topic as servi... |
extern crate bytes;
extern crate mio;
extern crate eventual;
extern crate eventual_io;
use mio::tcp;
use eventual::Async;
use eventual_io as eio;
pub fn main() {
// Create the socket
let reactor = eio::Reactor::start().unwrap();
let r = reactor.clone();
// Create a server socket
let srv = tcp::li... |
use std::{marker::PhantomData, ops::Bound};
use chrono::serde::ts_seconds;
use chrono::{DateTime, Utc};
use sqlx::postgres::{types::PgRange, PgConnection};
use svc_agent::AgentId;
use uuid::Uuid;
use serde_derive::{Deserialize, Serialize};
use serde_json::Value as JsonValue;
pub type BoundedDateTimeTuple = (Bound<Da... |
extern crate peroxide;
use peroxide::*;
fn main() {
let a: Matrix = MATLAB::new("1 2; 3 4");
a.print();
let b: Matrix = PYTHON::new(vec![c!(1, 2), c!(3, 4)]);
b.print();
let c: Matrix = R::new(c!(1, 2, 3, 4), 2, 2, Row);
c.print();
let d: Matrix = Matrix::from_index(|x, y| (x * 3 + y + 1... |
// Copyright (c) 2019 - 2020 ESRLabs
//
// 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 ... |
#![feature(rc_unique)]
pub mod first;
pub mod second;
pub mod third;
pub mod fourth;
|
pub(crate) mod table_constraint_kind;
pub(crate) mod table_constraints;
pub(crate) mod table_name;
|
use std::f32;
use std::ops::Add;
use std::ops::Div;
use std::ops::Mul;
use std::ops::Sub;
#[derive(Copy, Clone)]
pub struct Vec3 {
pub e: [f32; 3],
}
impl Vec3 {
pub fn new() -> Vec3 {
Vec3 {
e: [0f32, 0f32, 0f32],
}
}
pub fn from_scalar(t: f32) -> Vec3 {
Vec3 { e:... |
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
// Defining methods
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
// Associated fun... |
#![no_std]
#![no_main]
#![feature(custom_test_frameworks)]
#![test_runner(bentos::test_runner)]
#![reexport_test_harness_main = "test_main"]
extern crate alloc;
use core::panic::PanicInfo;
use alloc::{boxed::Box,vec,vec::Vec,rc::Rc};
use bentos::{print,println};
use bootloader::{BootInfo,entry_point};
entry_point!(k... |
use std::io::Cursor;
use byteorder::{LittleEndian, ReadBytesExt};
use failure::{ensure, format_err, Error};
use log::debug;
use crate::model::{
owned::{ComplexEntry, Entry, EntryHeader, SimpleEntry, TableTypeBuf},
TableType,
};
pub use self::configuration::{ConfigurationWrapper, Region};
mod configuration;
... |
// q0035_search_insert_position
struct Solution;
impl Solution {
pub fn search_insert(nums: Vec<i32>, target: i32) -> i32 {
match nums.binary_search(&target) {
Ok(n) => n as i32,
Err(n) => n as i32,
}
}
}
#[cfg(test)]
mod tests {
use super::Solution;
#[test]
... |
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FeatureProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub state: Option<String>,
}... |
fn challenge1() -> usize {
// Parse input into our own arrival time at the bus station and all
// the IDs of the buses currently in service.
let (arrival_time, bus_ids) = {
let input = aoc20::read_input_to_string("day13");
let arrival_time: usize = input
.lines()
.nt... |
#[doc = "Register `DR_01` reader"]
pub type R = crate::R<DR_01_SPEC>;
#[doc = "Field `PE` reader - Parity Error bit"]
pub type PE_R = crate::BitReader;
#[doc = "Field `V` reader - Validity bit"]
pub type V_R = crate::BitReader;
#[doc = "Field `U` reader - User bit"]
pub type U_R = crate::BitReader;
#[doc = "Field `C` r... |
///! Contains a mutation operator based on ruin and recreate principle.
use super::*;
use crate::construction::heuristics::finalize_insertion_ctx;
use std::sync::Arc;
/// A mutation operator based on ruin and recreate principle.
pub struct RuinAndRecreate {
ruin: Arc<dyn Ruin + Send + Sync>,
recreate: Arc<dyn ... |
use std::char;
fn main() {
let input = 327901;
println!("{}", part1(input));
println!("{}", part2(&[3, 2, 7, 9, 0, 1]));
}
fn part1(input: usize) -> String {
let recipes = generate_recipes(input + 10);
let last_ten = &recipes[input..input + 10];
last_ten
.iter()
.map(|&x| char::... |
use super::super::drawable::*;
use super::image::{Image, ImageIterator, ImageType};
use crate::coord::{Coord, ToUnsigned};
use crate::pixelcolor::PixelColor;
/// # 16 bits per pixel images
///
/// Every two bytes define the color for each pixel.
///
/// You can convert an image to 16BPP for inclusion with `include_byt... |
use std::io::{stdin, Read, StdinLock};
use std::str::FromStr;
#[allow(dead_code)]
struct Scanner<'a> {
cin: StdinLock<'a>,
}
#[allow(dead_code)]
impl<'a> Scanner<'a> {
fn new(cin: StdinLock<'a>) -> Scanner<'a> {
Scanner { cin: cin }
}
fn read<T: FromStr>(&mut self) -> Option<T> {
let t... |
use surf::http::Method;
use crate::framework::endpoint::Endpoint;
/// Delete Key-Value Pairs in Bulk
/// Deletes multiple key-value pairs from Workers KV at once.
/// A 404 is returned if a delete action is for a namespace ID the account doesn't have.
/// https://api.cloudflare.com/#workers-kv-namespace-delete-multip... |
use crate::{
hitable::HitRecord,
ray::Ray,
utils::{
random_in_unit_sphere,
reflect,
refract,
schlick,
},
};
use vec3D::Vec3D;
pub trait Scatter {
fn scatter(&self, ray_in: &Ray, rec: &HitRecord, attenuation: &mut Vec3D, scattered: &mut Ray) -> bool;
}
#[derive(Clon... |
#![allow(dead_code)]
#![feature(libc)]
extern crate libc;
extern crate rsnl;
pub mod socket;
pub mod message;
pub mod controller;
|
use std::collections::VecDeque;
use thiserror::Error;
use super::hir::Expr;
use super::*;
use super::Radix;
/// RecoverableResult is a type that represents a Result that can be recovered from.
///
/// See the [`Recover`] trait for more information.
///
/// [`Recover`]: trait.Recover.html
pub type RecoverableResult<T... |
//! Modal and ModalContainer
//!
//! A widget represent modal widget
use druid::{
lens::{self, LensExt},
BoxConstraints, Command, Data, Env, Event, EventCtx, LayoutCtx, LifeCycle, LifeCycleCtx,
PaintCtx, Point, Rect, Size, UpdateCtx, Widget, WidgetPod,
};
pub trait Modal {
fn is_closed(&self) -> Optio... |
use log::{info, debug};
use std::sync::{Arc, RwLock};
use failure;
use failure::{Error, Fail};
use failure_derive;
use portaudio;
use hero_studio_core::midi::bus::{BusAddress, MidiBus};
use hero_studio_core::{config::Config, config::Audio as AudioConfig, studio::Studio, time::BarsTime};
mod midi;
use crate::midi:... |
#[macro_use]
extern crate bencher;
extern crate directories;
use bencher::Bencher;
use bencher::black_box;
use directories::BaseDirs;
use directories::ProjectDirs;
use directories::UserDirs;
fn base_dirs(b: &mut Bencher) {
b.iter(|| {
let _ = black_box(BaseDirs::new());
});
}
fn user_dirs(b: &mut Ben... |
#![feature(used)]
#![no_std]
extern crate cortex_m_semihosting;
#[cfg(not(feature = "use_semihosting"))]
extern crate panic_abort;
#[cfg(feature = "use_semihosting")]
extern crate panic_semihosting;
extern crate cortex_m;
extern crate cortex_m_rt;
extern crate atsamd21_hal;
extern crate metro_m0;
use metro_m0::clo... |
use serde::Deserialize;
use super::{Activity, Character, Media, Staff, Studio, User};
use crate::models::AiringSchedule;
pub type AniListID = u64;
#[derive(Clone, Debug, Deserialize)]
pub struct FuzzyDate {
year: u32,
month: u32,
day: u32,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "cam... |
#[cfg(test)]
#[path = "../../tests/unit/checker/capacity_test.rs"]
mod capacity_test;
use super::*;
use crate::utils::combine_error_results;
use std::iter::once;
use vrp_core::models::common::{Load, MultiDimLoad};
/// Checks that vehicle load is assigned correctly. The following rules are checked:
/// * max vehicle's... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - ICACHE control register"]
pub cr: CR,
#[doc = "0x04 - ICACHE status register"]
pub sr: SR,
#[doc = "0x08 - ICACHE interrupt enable register"]
pub ier: IER,
#[doc = "0x0c - ICACHE flag clear register"]
pub fc... |
use brawllib_rs::wiird;
use brawllib_rs::wiird::{WiiRDBlock, WiiRDCode};
use getopts::Options;
use std::env;
use std::path::PathBuf;
fn print_usage(program: &str, opts: Options) {
let brief = format!("Usage: {} [options]", program);
print!("{}", opts.usage(&brief));
}
fn main() {
let args: Vec<String> =... |
use itertools::join;
use core::fmt::Debug;
#[derive(Debug, PartialEq, Eq)]
pub struct Entry {
pub num: i32,
pub c: char,
}
pub type Dict = Vec<Entry>;
type BitString = Vec<i32>;
trait Justify {
fn ljust(&self, filler: char, len: usize) -> String;
fn rjust(&self, filler: char, len: usize) -> String;
... |
use std::fmt;
use iced::Color;
use serde::{Deserialize, Serialize};
use crate::gui::styles::custom_themes::{dracula, gruvbox, nord, solarized};
use crate::gui::styles::types::palette::Palette;
/// Custom style with any relevant metadata
pub struct CustomPalette {
/// Color scheme's palette
pub(crate) palette... |
use super::{Blocks, Chunk};
use crate::internal_data_structure::raw_bit_vector::RawBitVector;
impl super::Chunk {
/// Constructor.
pub fn new(value: u64, length: u16, rbv: &RawBitVector, i_chunk: u64) -> Chunk {
let blocks = Blocks::new(rbv, i_chunk, length);
Chunk {
value,
... |
fn main() {
let v1 = vec![1, 2, 3];
let v1_iter = v1.iter();
let v2: Vec<_> = v1_iter.map(|x| x + 1).collect();
println!("{:?}", v2);
}
|
use crate::error::{NiaServerError, NiaServerResult};
use crate::protocol::{
NiaConvertable, NiaGetDefinedModifiersRequest, NiaModifierDescription,
Serializable,
};
use std::sync::MutexGuard;
use nia_interpreter_core::NiaInterpreterCommand;
use nia_interpreter_core::NiaInterpreterCommandResult;
use nia_interpre... |
/// LeetCode Monthly Challenge problem for April 6th, 2021.
pub struct Solution {}
impl Solution {
/// Given an array length n where arr[i] = 2 * i + 1, returns the minimum
/// operations to make all elements equal.
///
/// At each operation two indices are chosen, x and y. Then 1 is subtracted
//... |
extern crate peroxide;
use peroxide::*;
use Number::F;
const S: [f64; 7] = [
0.038, 0.194, 0.425, 0.626, 1.253, 2.500, 3.740
];
fn main() {
let y = ml_matrix("0.05; 0.127; 0.094; 0.2122; 0.2729; 0.2665; 0.3317");
let beta_init = vec!(0.9, 0.2);
let mut beta = beta_init.to_matrix();
let mut j = j... |
use std::{
collections::{BTreeMap, BTreeSet}, mem,
};
use webidl;
use super::Result;
#[derive(Default)]
pub(crate) struct FirstPassRecord<'a> {
pub(crate) interfaces: BTreeSet<String>,
pub(crate) dictionaries: BTreeSet<String>,
pub(crate) enums: BTreeSet<String>,
pub(crate) mixins: BTreeMap<Strin... |
#[doc = "Register `CFR` writer"]
pub type W = crate::W<CFR_SPEC>;
#[doc = "Field `CEOCF` writer - Clear End of Conversion Flag"]
pub type CEOCF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CHPDF` writer - Clear Header Parsing Done Flag"]
pub type CHPDF_W<'a, REG, const O: u8> = crate::BitWrit... |
// build.rs
use grpc_build::build;
fn main() {
build("./protos", "src/protogen", true, true, true).unwrap();
}
|
use ad_hoc_sys as sys;
use std::str::from_utf8_unchecked_mut;
use std::slice::from_raw_parts_mut;
use std::mem::transmute;
use std::ptr::copy_nonoverlapping;
use crate::org::company as host;
use host::Client as packs;
#[repr(C)]
pub struct Meta0(pub u16, u32, u32, u32, pub u32, pub Option<unsafe extern "C" fn(pack: ... |
#[doc = "Reader of register SAI_ACR1"]
pub type R = crate::R<u32, super::SAI_ACR1>;
#[doc = "Writer for register SAI_ACR1"]
pub type W = crate::W<u32, super::SAI_ACR1>;
#[doc = "Register SAI_ACR1 `reset()`'s with value 0x40"]
impl crate::ResetValue for super::SAI_ACR1 {
type Type = u32;
#[inline(always)]
fn... |
use std::fmt::Display;
use chrono::{DateTime, Utc};
pub enum DebugMessageType {
Log=0,
Warning=1,
Error=2,
}
pub struct DebugMessage {
pub message: String,
pub time: DateTime<Utc>,
pub msg_type: DebugMessageType
}
impl Display for DebugMessage {
fn fmt(&self, f: &mut std::fmt::Formatter<'... |
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use anyhow::{bail, Result};
use scs::SCSCodec;
use starcoin_types::account_address::AccountAddress;
use std::fs::OpenOptions;
use std::path::Path;
use std::{
fs,
fs::File,
io::{Read, Write},
path::PathBuf,
};
use wal... |
//! TODO:Describe what is different from audio
// TODO: Defines distance from A4. i8 looks like a good option so not sure if a
// custom struct is required.
// TODO: Technically this can be any type capable of adding +1/-1.
type Pitch = i8;
// TODO:
pub struct PitchSystem<T> {
// TODO: concert pitch, pitch standa... |
use kvs::Command;
use kvs::Result;
use serde_json;
use std::io::{BufReader, BufWriter, Read, Write};
use std::net::TcpStream;
use std::process::exit;
use structopt::StructOpt;
#[derive(StructOpt, Debug)]
struct ClientOpt {
#[structopt(subcommand)]
cmd: Command,
#[structopt(long, default_value = "127.0.0.1... |
use std::io::{self, Read};
use std::sync::mpsc::{Sender, Receiver, channel};
use std::collections::HashMap;
use std::thread;
use std::time::Duration;
#[derive(Debug, Clone, Copy)]
struct Ridx(char);
#[derive(Debug, Clone, Copy)]
enum Operand {
Register(Ridx),
Constant(i64),
}
#[derive(Debug, Clone, Copy)]
e... |
fn is_rotation(s1: &str, s2: &str) -> bool {
let mut s1s1 = s1.to_owned().clone();
s1s1.push_str(s1);
s1s1.contains(s2)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_1() {
assert!(is_rotation("totem", "temto"));
}
#[test]
fn test_2() {
assert!(!is_rotation... |
fn main() {
use std::mem;
let color = "green";
let print = || println!("`color`: {}", color);
// call the closure using the borrow (&color)
print();
let _reborrow = &color;
print();
let _color_moved = color;
let mut count = 0;
let mut inc = || {
count += 1;
println!("`count`: {}", cou... |
use chrono::{Local, NaiveDateTime};
use diesel::prelude::*;
use std::collections::HashMap;
use uuid::Uuid;
use crate::core::schema::transaction;
use crate::core::{
generate_uuid, Account, DbConnection, Money, Product, ServiceError, ServiceResult,
};
/// Represent a transaction
#[derive(Debug, Queryable, Insertabl... |
#[macro_use] extern crate itertools;
fn main() {
let args: Vec<String> = std::env::args().collect();
let filename = &args[1];
println!("{}", filename);
let contents = std::fs::read_to_string(filename).expect("file not found");
// let values = contents.split('\n').filter(|x| !x.is_empty()).map(|x... |
use crate::view_models;
pub struct PostProcessEffectMetaData
{
pub name: view_models::PostProcessEffects,
pub running_time: f32,
pub max_running_time: f32,
} |
// #[macro_use] extern crate quicli;
#[macro_use] extern crate failure;
#[macro_use] extern crate structopt;
mod error;
mod input;
mod output;
use error::{Error, ErrorKind, Result};
// main!(|args: input::RdisOpt, log_level: verbosity| {
// println!("{}", "Hello");
// });
fn main() -> Result<()> {
Ok(())
}
|
use parse::ParseError;
use rand::{Rand, Rng};
use std::fmt;
use std::str::FromStr;
/// A network name to identify nodes.
#[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct Name(pub u64);
impl Rand for Name {
fn rand<R: Rng>(rng: &mut R) -> Self {
Name(rng.gen())
}
}
impl fmt::Deb... |
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
use near_sdk::collections::LookupMap;
use near_sdk::serde_json::{self, json};
use near_sdk::wee_alloc::WeeAlloc;
use near_sdk::{env, near_bindgen, AccountId};
use near_sdk::{Promise, PromiseOrValue, PromiseResult};
#[global_allocator]
static ALLOC: WeeAlloc... |
use crate::MyApp;
use seed::{*, prelude::*};
use crate::traits::component_trait::Component;
use crate::messages::Msg;
//Header
pub struct HeaderComponent;
impl Component<MyApp, Msg> for HeaderComponent {
fn view(_model: &MyApp) -> Node<Msg> {
div![
id!("header"),
"Todo App"
... |
use anyhow::Context;
use rusqlite::Transaction;
pub(crate) fn migrate(transaction: &Transaction<'_>) -> anyhow::Result<()> {
// Add new columns to the blocks table
transaction
.execute_batch(
r"ALTER TABLE starknet_blocks ADD COLUMN gas_price BLOB NOT NULL
DEFAULT X'000000000000... |
use crate::features::syntax::StatementFeature;
use crate::parse::visitor::tests::assert_stmt_feature;
#[test]
fn labelled() {
assert_stmt_feature("label: while(true);", StatementFeature::LabelledStatement);
}
|
fn main() {
let x: i32 = 5;
print_number(x);
let x1: i32 = 10;
let x2: i32 = 11;
print_sum(x1, x2);
print_number(add_one(x1));
}
fn print_number(x: i32){
println!("The number is {}",x)
}
fn print_sum(x: i32, y: i32){
print_number(x+y)
}
fn add_one(x: i32) -> i32 {
x+1 // using a ... |
use k8s_openapi::apiextensions_apiserver::pkg::apis::apiextensions::v1::CustomResourceDefinition;
use kube::{
api::{Api, Patch, PatchParams},
core::crd::merge_crds,
runtime::wait::{await_condition, conditions},
Client, CustomResource, CustomResourceExt, ResourceExt,
};
use schemars::JsonSchema;
use serd... |
use std::fmt;
use std::marker::PhantomData;
use approx::ApproxEq;
use alga::general::{Real, SubsetOf};
use alga::linear::Rotation;
use core::{Scalar, OwnedSquareMatrix};
use core::dimension::{DimName, DimNameSum, DimNameAdd, U1};
use core::storage::{Storage, OwnedStorage};
use core::allocator::{Allocator, OwnedAlloca... |
use crate::*;
use serenity::{
framework::standard::{
macros::{command, group, help},
Args, CommandGroup, CommandResult, HelpOptions, *,
},
model::channel::Message,
model::id::UserId,
prelude::*,
};
use std::collections::HashSet;
mk_group!(General, ping, say);
cmd_ctx_msg!(ping, ctx... |
//! An API to easily print a two dimensional array to stdout.
//! # Example
//! ```rust
//! use grid_printer::GridPrinter;
//!
//! let cars = vec![
//! vec!["Make", "Model", "Color", "Year", "Price", ],
//! vec!["Ford", "Pinto", "Green", "1978", "$750.00", ],
//! vec!["Toyota", "Tacoma", "Red", "2006", "$15... |
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, RwLock};
use std::thread;
use std::thread::spawn;
use std::time::Duration;
pub enum Priority {
Readers,
Writers,
Equal,
}
pub struct ReadersWriters {
readers_count: AtomicUsize,
writers_count: AtomicUsize,
priorit... |
//rand kütüphanesini ekliyoruz
use rand::Rng;
//std kütüphanesi diğer dillerdekiyle aynı
use std::io::Write;
fn main(){
//rand kütüphanesinin gen fonksiyonuyla 32 tane u8 tipinde değer üretiyoruz
let random_bytes = rand::thread_rng().gen::<[u8; 32]>();
println!("Yazılacak bytelar:");
println!("{:?}"... |
use crate::{
metadata::Metadata,
module::{PubSubImpl, PubSubService},
};
use anyhow::Result;
use jsonrpc_core::{futures as futures01, MetaIoHandler};
use jsonrpc_pubsub::Session;
// use starcoin_crypto::hash::HashValue;
use futures::{compat::Stream01CompatExt, StreamExt};
use starcoin_rpc_api::pubsub::StarcoinP... |
#[doc = "Register `OR` reader"]
pub type R = crate::R<OR_SPEC>;
#[doc = "Register `OR` writer"]
pub type W = crate::W<OR_SPEC>;
#[doc = "Field `IN1` reader - IN1"]
pub type IN1_R = crate::BitReader;
#[doc = "Field `IN1` writer - IN1"]
pub type IN1_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `... |
#[doc = "Register `EXTICR1` reader"]
pub type R = crate::R<EXTICR1_SPEC>;
#[doc = "Register `EXTICR1` writer"]
pub type W = crate::W<EXTICR1_SPEC>;
#[doc = "Field `EXTI0` reader - EXTI 0 configuration bits"]
pub type EXTI0_R = crate::FieldReader<EXTI0_A>;
#[doc = "EXTI 0 configuration bits\n\nValue on reset: 0"]
#[deri... |
use matrices::Matrix4;
use tuples::Tuple;
pub struct Ray {
pub origin: Tuple,
pub direction: Tuple,
}
impl Ray {
pub fn new(origin: Tuple, direction: Tuple) -> Self {
Ray { origin, direction }
}
pub fn position(&self, t: f32) -> Tuple {
self.origin + self.direction * t
}
... |
use std::fs;
fn find_sum_of_two(numbers: &[i32], sum: i32) -> Option<(i32, i32)> {
if numbers.len() <= 1 { return None; }
let n1 = numbers[0];
for n2 in &numbers[1..] {
if n1 + n2 == sum { return Some((n1, *n2)) };
}
find_sum_of_two(&numbers[1..], sum)
}
fn find_sum_of_three(numbers: &[... |
pub mod manage_packets;
pub mod types;
|
#![feature(
associated_type_defaults,
const_fn,
macro_at_most_once_rep,
nll,
rust_2018_preview,
slice_patterns,
specialization,
try_from,
underscore_imports,
use_extern_macros,
)]
#![warn(rust_2018_idioms)]
#![cfg_attr(feature = "cargo-clippy", warn(clippy))]
pub mod aggregate;... |
use std::ops::{Index, IndexMut, Deref};
use num_traits::{Float, Zero};
use totsu_core::solver::SliceLike;
use totsu_core::{LinAlgEx, MatType, MatOp};
//
/// Matrix builder
///
/// <script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
/// <script id="MathJax-script" async src="https://... |
use std::io;
use std::sync::mpsc;
use std::thread;
use termion::event::Key;
use termion::input::TermRead;
pub enum Event<I> {
Input(I),
}
pub struct Events {
rx: mpsc::Receiver<Event<Key>>,
}
impl Events {
pub fn new() -> Events {
let (tx, rx) = mpsc::channel();
let _input_handle = {
... |
// SPDX-License-Identifier: Apache-2.0
pub enum BlockCipherAlgorithm {
Aes128Cbc,
}
impl BlockCipherAlgorithm {
pub fn name(&self) -> &str {
match self {
BlockCipherAlgorithm::Aes128Cbc => "aes-128-cbc",
}
}
pub fn key_len(&self) -> usize {
match self {
... |
table! {
languages (id) {
id -> Integer,
language -> Text,
}
}
table! {
words (id) {
id -> Integer,
word -> Text,
word_pattern -> Text,
language_id -> Integer,
}
}
joinable!(words -> languages (language_id));
allow_tables_to_appear_in_same_query!(
l... |
use mpi::topology::Rank;
use super::session::SessionState;
pub unsafe trait RankSelect {
fn get_rank(state: &SessionState) -> Rank;
}
pub struct ZeroRank;
unsafe impl RankSelect for ZeroRank {
fn get_rank(_: &SessionState) -> Rank {
0
}
}
unsafe impl<K: 'static> RankSelect for c... |
println!("the sum is {}", 80.3 + 34.8);
println!("the sum is {}", 80.3 + 34.9);
println!("{}", (23. - 6.) % 5. + 20. * 30. / (3. + 4.));
// println!("{}", 2.7 + 1);
println!("{}", 2.7 + 1.);
println!("{} {}", -12 % 10, -1.2 % 1.);
|
use std::fmt::{Show, Formatter, Result};
use token::*;
pub type Ident = String;
#[deriving(PartialEq)]
pub struct Expr {
pub node : Expr_
}
impl Show for Expr {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "{}", self.node)
}
}
#[deriving(PartialEq)]
pub struct Stmt {
pub node : St... |
use std::io::stdin;
use diesel::prelude::*;
use sl_lib::models::*;
use sl_lib::*;
use console::Style;
pub fn publish_or_unpublish() {
let green = Style::new().green();
let yellow = Style::new().yellow();
let cyan = Style::new().cyan();
let bold = Style::new().bold();
use schema::posts::dsl::*;
... |
pub enum OsuKeyboardError {
InitializationFailed,
}
pub fn report(error: OsuKeyboardError) -> ! {
let error_handle = match error {
_ => || {},
};
loop {
(error_handle)();
arduino_uno::delay_ms(1000_u16)
}
}
// fn stutter_blink(led: &mut PB5<Output>, times: usize) {
// ... |
use {neon::prelude::*, solana_program::pubkey::Pubkey, std::str::FromStr};
fn to_vec(cx: &mut FunctionContext, list: &Handle<JsValue>) -> NeonResult<Vec<String>> {
if list.is_a::<JsArray, _>(cx) {
let list = list.downcast::<JsArray, _>(cx).unwrap();
let len = list.len(cx) as usize;
let mut ... |
//
// Rust windows (イテレーションの方)
// https://qiita.com/hystcs/items/d33e77084277cdba8052
//
// Rust By Example の タプル
// https://doc.rust-jp.rs/rust-by-example-ja/primitives/tuples.html
//
fn naruhodo(chars: &[char]) -> char {
(chars
.windows(2)
.map(|w| (w[0] as u8, w[1] as u8))
.find(|&w| w.0 ... |
use crate::error::{Error, Result, TypeError};
use crate::parsing::{parse, Sexpr as PS, SpannedSexpr};
use crate::scm::Scm;
use crate::source::{Source, SourceLocation};
use crate::symbol::Symbol;
use crate::syntactic_closure::SyntacticClosure;
use std::fmt::Debug;
use std::rc::Rc;
#[derive(Debug, Clone)]
pub struct Tra... |
use std::convert::AsRef;
use xml::Element;
use ::{ElementUtils, NS, ViaXml};
/// [The Atom Syndication Format § The "atom:generator" Element]
/// (https://tools.ietf.org/html/rfc4287#section-4.2.4)
#[derive(Default)]
pub struct Generator {
pub name: String,
pub uri: Option<String>,
pub version: Option<S... |
//! ECS input bundle
use std::hash::Hash;
use std::path::Path;
use serde::Serialize;
use serde::de::DeserializeOwned;
use winit::Event;
use app::ApplicationBuilder;
use config::Config;
use ecs::ECSBundle;
use ecs::input::{Bindings, InputEvent, InputHandler, InputSystem};
use error::Result;
use shrev::EventHandler;
... |
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ListNode {
pub val: i32,
pub next: Option<Box<ListNode>>,
}
impl ListNode {
#[inline]
pub fn new(val: i32) -> Self {
ListNode { next: None, val }
}
pub fn from_array(array: &[i32]) -> Self {
ListNode::from(array)
}
pub ... |
mod ast;
mod parsing;
mod tags;
mod tokens;
use ast::{
Expression,
visitor::{ExpressionVisitor, JsonExpressionVisitor}};
use parsing::parse;
use tokens::process_str;
use std::collections::VecDeque;
fn main() {
let mut tokens = process_str("{\"foo\": \"bar\", \"baz\": -123, \"bing\": 5}");
let mut resu... |
#[doc = "Register `NSOBKCFGR` reader"]
pub type R = crate::R<NSOBKCFGR_SPEC>;
#[doc = "Register `NSOBKCFGR` writer"]
pub type W = crate::W<NSOBKCFGR_SPEC>;
#[doc = "Field `LOCK` reader - OBKCFGR lock option configuration bit This bit locks the FLASH_NSOBKCFGR register. The correct write sequence to FLASH_NSOBKKEYR regi... |
use hdk::{
self,
error::ZomeApiResult,
entry_definition::ValidatingEntryType,
holochain_core_types::{
dna::entry_types::Sharing,
entry::Entry,
},
holochain_json_api::{
json::JsonString,
error::JsonError,
},
holochain_persistence_api::cas::content::Address,... |
// Copyright 2018 Jeffery Xiao, 2019 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable l... |
use std::fs;
use cbc_mode;
fn main() {
let key = "YELLOW SUBMARINE";
let iv = "\x00\x00\x00";
let encypted_text = fs::read_to_string("encrypted_data.txt").expect("Unable to read file");
let decrypted_text = cbc_mode::decrypt_string(
&encypted_text,
key,
iv
);
println!(... |
#[test]
fn test_fd_sync() {
assert_wasi_output!(
"../../wasitests/fd_sync.wasm",
"fd_sync",
vec![],
vec![(
".".to_string(),
::std::path::PathBuf::from("wasitests/test_fs/temp")
),],
vec![],
"../../wasitests/fd_sync.out"
);
}
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under both the MIT license found in the
* LICENSE-MIT file in the root directory of this source tree and the Apache
* License, Version 2.0 found in the LICENSE-APACHE file in the root directory
* of this source tree.
*/
use f... |
use serde_repr::Deserialize_repr;
#[derive(Debug, Deserialize_repr)]
#[repr(u8)]
pub enum Composite {
Above = 1,
Below = 2,
}
impl Default for Composite {
fn default() -> Self {
Self::Above
}
}
|
use std::fs;
#[derive(Debug)]
pub struct Cartridge {
data: Vec<u8>,
gbcFlag: u8,
cartType: CartridgeType,
ramType: RamType,
romSize: u8,
ram: Option<Vec<u8>>,
}
#[derive(Debug)]
enum CartridgeType {
Rom = 0x00,
Mbc1 = 0x01,
Mbc1Ram = 0x02,
Mbc1RamBattery = 0x03,
}
#[derive(D... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.