text stringlengths 8 4.13M |
|---|
// functions1.rs
// Make me compile! Execute `rustlings hint functions1` for hints :)
// I AM DONE
fn call_me(a: i32, b:i32) -> i32 {
if a > b {
return a;
} else {
return b;
}
}
fn main() {
call_me(10,20);
}
|
use num::Signed;
use std::convert::TryFrom;
use std::ops::{Add, Sub};
use std::result::Result;
macro_rules! impl_value {
($self: ident) => {
impl<S: Copy + Signed + Sized> AsValue<S> for $self<S> {
fn value(&self) -> S {
self.0
}
}
};
}
macro_rules! zero... |
use bitbuffer::{BitRead, BitWrite, BitWriteStream, LittleEndian};
use crate::{Parse, ParserState, Result, Stream};
use self::consolecmd::ConsoleCmdPacket;
use self::datatable::DataTablePacket;
use self::message::MessagePacket;
use self::stop::StopPacket;
use self::stringtable::StringTablePacket;
use self::synctick::S... |
use super::{Cartridge, Mapper, Mirror, serialize::*};
pub struct Nrom {
cart: Cartridge,
chr_ram: Vec<u8>,
}
impl Nrom {
pub fn new(cart: Cartridge) -> Self {
Nrom{
cart: cart,
chr_ram: vec![0; 0x2000],
}
}
}
impl Mapper for Nrom {
fn read(&self, address: u... |
use std::env; //args()
use std::io::Write; //writeln!()
use std::process; //exit()
use std::net::TcpListener; //TcpListener::*()
use std::str::from_utf8; //from_utf8()
use std::string::String; //as_bytes()
//Uses u8 buffer array, noting that ASCII and utf8 share the same memory alignm... |
/*!
```rudra-poc
[target]
crate = "abi_stable"
version = "0.9.0"
indexed_version = "0.8.3"
[report]
issue_url = "https://github.com/rodrimati1992/abi_stable_crates/issues/44"
issue_date = 2020-12-21
rustsec_url = "https://github.com/RustSec/advisory-db/pull/609"
rustsec_id = "RUSTSEC-2020-0105"
[[bugs]]
analyzer = "U... |
pub use self::greetings::*;
pub use self::farewells::*;
pub mod greetings;
pub mod farewells;
|
pub mod node;
pub mod rpc;
pub mod test;
pub mod types;
pub mod prelude {
pub use super::rpc::RpcExtension;
pub use super::test::*;
}
|
use crate::protocol::error::ProtocolError;
#[derive(Debug, Clone, Copy)]
pub enum Speed {
S4 = 1,
S5 = 2,
S6 = 3,
S7 = 4,
S8 = 5,
}
impl Default for Speed {
fn default() -> Self {
Self::S4
}
}
impl Speed {
pub fn from_raw(raw: u8) -> Result<Self, ProtocolError> {
let i... |
pub enum TokenType {
// Single-character tokens.
LeftParen,
RightParen,
LeftBrace,
RightBrace,
Comma,
Dot,
Minus,
Plus,
SemiColon,
Slash,
Star,
// One or two character tokens.
Bang,
BangEqual,
Equal,
EqualEqual,
Greater,
GreaterEqual,
Less,
LessEqual,
// Literals.
Identif... |
use tokio_postgres::{Client, Statement, types::Type, IsolationLevel};
use crate::queries::errors::Result;
use crate::api::app_state::AppDatabase;
pub struct Query {
pub update_bucket: Statement,
pub acquire_token_from_bucket: Statement,
}
impl Query {
pub async fn new(client: &Client) -> Self {
le... |
pub mod manage_chart_data;
pub mod types;
|
use im::{HashMap, HashSet};
use rustc_session::Session;
use crate::rustspec::*;
use crate::util::check_vec;
use std::{
ops::Add,
sync::atomic::{AtomicUsize, Ordering},
};
use crate::name_resolution::{FnKey, FnValue, TopLevelContext};
pub static ID_COUNTER: AtomicUsize = AtomicUsize::new(0);
fn fresh_hacspec... |
use std::collections::BTreeSet;
use serde::{Serialize, Deserialize};
use super::{Column, Task, Id};
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Project {
id: Id,
name: String,
description: String,
columns: Vec<Column>,
tasks: Vec<Task>,
}
impl Project {
pub fn new<I: AsRef<str>>... |
use clap::{value_t, App, Arg, SubCommand};
use rusqlite::Connection;
mod error;
mod item;
mod salvage;
mod utils;
use crate::error::NumeneraError;
use crate::utils::roll_dice;
fn main() -> Result<(), NumeneraError> {
let conn = Connection::open("./numenera.db")?;
let matches = App::new("Numenera Helper")
... |
tag thing { a; b; c; }
iter foo() -> int { put 10; }
fn main() {
let x = true;
alt a {
a. { x = true; for each i: int in foo() { } }
b. { x = false; }
c. { x = false; }
}
}
|
// -*- rust -*-
iter two() -> int { put 0; put 1; }
iter range(start: int, stop: int) -> int {
let i: int = start;
while i < stop { put i; i += 1; }
}
fn main() {
let a: [mutable int] = [mutable -1, -1, -1, -1, -1, -1, -1, -1];
let p: int = 0;
for each i: int in two() {
for each j: int ... |
extern crate regex;
use colored::*;
use regex::Regex;
use std::cmp::Ordering;
use std::env;
use std::fs;
use std::process::Command;
fn fetch_problem_url() -> Option<String> {
let args: Vec<String> = env::args().collect();
if args.len() == 2 {
return Some(args[1].to_string());
}
println!("Incor... |
extern crate hoge;
use hoge::hoge;
//mod hoge;
struct TimeBomb {
s: &'static str
}
impl Drop for TimeBomb {
fn drop(&mut self) {
println!("dropped {}", self.s)
}
}
trait Seq<T> {
fn length(&self) -> uint;
}
impl<T> Seq<T> for Vec<T> {
fn length(&self) -> uint {
self.len()
}
}... |
#[doc = "Register `DMACRXIWTR` reader"]
pub type R = crate::R<DMACRXIWTR_SPEC>;
#[doc = "Register `DMACRXIWTR` writer"]
pub type W = crate::W<DMACRXIWTR_SPEC>;
#[doc = "Field `RWT` reader - Receive Interrupt Watchdog Timer Count This field indicates the number of system clock cycles, multiplied by factor indicated in R... |
use std::{convert::TryFrom, fmt::Debug, ops::Deref};
use time::{
error::ComponentRange, format_description::well_known::Iso8601, Date as _Date, OffsetDateTime,
PrimitiveDateTime, Time,
};
use crate::Error;
use librespot_protocol as protocol;
use protocol::metadata::Date as DateMessage;
impl From<ComponentRa... |
use std::fs::{File};
use std::io::{BufRead, BufReader};
use std::vec::{Vec};
use std::collections::{HashMap};
type Coord = (usize, usize);
type AstList = Vec<Coord>;
fn parse_program(inp: &str) -> AstList {
let f = BufReader::new(File::open(inp).unwrap());
return f.lines()
.enumerate()
.map(... |
extern crate proc_macro;
use proc_macro::{TokenStream};
use syn::{
parse_macro_input,
ItemImpl,
ImplItem,
Visibility,
Signature,
Path,
FnArg,
Pat,
PatIdent,
Ident,
};
use syn::spanned::Spanned;
use syn::parse::Error;
use quote::{quote, ToTokens};
/// Make `pub` methods in the a... |
use std::{
convert::{TryFrom, TryInto},
fmt::Debug,
ops::{Deref, DerefMut},
};
use crate::{
audio::file::AudioFiles,
availability::Availabilities,
content_rating::ContentRatings,
image::Images,
request::RequestResult,
restriction::Restrictions,
util::{impl_deref_wrapped, impl_tr... |
use super::{DataClass, DataIdDefinition};
use ::ErrorKind;
use ::std::marker::PhantomData;
pub type DataIdSimpleType = f32;
pub(crate) static DATAID_DEFINITION : DataIdDefinition<DataIdSimpleType, DataIdType> =
DataIdDefinition {
data_id: 28,
class: DataClass::SensorAndInformationalData,
r... |
use std::ops::{Add,Sub};
use std::convert::TryInto;
pub type pLcpKar<T> = Vec<T>;
impl <T> pLcp<T> for pLcpKar<T>
where T:Copy +
Add<Output = T> +
Sub<Output = T> +
PartialOrd +
From<u8> +
Into<usize>
{
fn compute(t: String, sa: Vec<T>) -> Result... |
use std::io;
fn main() {
println!("Welcome to the temperature convertor!");
let temperature_unit = loop {
println!("Input \"F\" to convert from Fahrenheit or \"C\" to convert from Celsius.");
let mut temperature_unit = String::new();
io::stdin()
.read_line(&mut temperatur... |
use nom::*;
use nom::types::CompleteStr;
use ::ast::{StringlyTyped, StringlyTypedInner};
fn is_quote(c: char) -> bool {
match c as char {
'\'' | '"' => true,
_ => false
}
}
named!{stringly_typed <CompleteStr, (StringlyTyped<&str>)>, alt!(double_quote | single_quote)}
named!{double_quote <Com... |
// use chrono::Local;
// extern crate serde_json;
use serde::{Deserialize, Serialize};
use serde_json::Result;
#[derive(Serialize, Deserialize, Debug)]
pub struct Task {
name: String,
created: String,
description: String,
log_time: i64,
}
use thiserror::Error;
#[derive(Error, Debug)]
pub enum TaskEr... |
use std::ops::Mul;
pub const BLACK: Color = Color::new(0, 0, 0);
pub const WHITE: Color = Color::new(255, 255, 255);
pub const RED: Color = Color::new(255, 0, 0);
pub const GREEN: Color = Color::new(0, 255, 0);
pub const BLUE: Color = Color::new(0, 0, 255);
#[derive(Copy, Clone)]
pub struct Color {
pub red: u8,
... |
use std::sync::Arc;
use chrono::{DateTime, Utc};
use common::result::Result;
use crate::domain::interaction::{InteractionRepository, Like, Reading, Review, View};
use crate::domain::publication::{PublicationId, Statistics};
use crate::domain::reader::ReaderId;
pub struct StatisticsService {
interaction_repo: Ar... |
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
extern crate serde_yaml;
extern crate toml;
/// # Deserialization of the JSON in the readable TOML and YAML formats
///
/// The module deserializes the json file into the `Request` object.
/// The `Request` object can be printed in YA... |
use std::num::sqrt;
use std::ptr::null;
use pancurses::Window;
enum NodeDirection {
PathRight,
PathLeft,
PathDown,
PathUp,
}
pub struct Node {
x: i32,
y: i32,
hcost: i32,
gcost: i32,
fcost: i32,
flag: Option<NodeDirection>,
parent: Arc<Node>,
}
impl Node {
pub fn new(x... |
//! The top-level documentation resides on the [project README](https://github.com/tomhoule/graphql-client) at the moment.
//!
//! The main interface to this library is the custom derive that generates modules from a GraphQL query and schema. See the docs for the [`GraphQLQuery`] trait for a full example.
#![deny(warn... |
#[doc = "Logging"];
export console_on, console_off;
#[nolink]
native mod rustrt {
fn rust_log_console_on();
fn rust_log_console_off();
}
#[doc = "Turns on logging to stdout globally"]
fn console_on() {
rustrt::rust_log_console_on();
}
#[doc(
brief =
"Turns off logging to stdout globally",
de... |
extern crate pest;
#[macro_use]
extern crate pest_derive;
#[macro_use]
extern crate lazy_static;
extern crate regex;
pub mod mm_parser;
extern crate mockall;
pub mod io {
use std::fs;
pub struct FileIO {
}
use mockall::automock;
#[automock]
pub trait IO {
fn slurp(&self, filename: &... |
use diesel::Queryable;
use uuid::Uuid;
#[derive(Debug, PartialEq, Eq)]
pub struct UserId(Uuid);
impl Into<Uuid> for UserId {
fn into(self) -> Uuid {
self.0
}
}
impl Queryable<diesel::sql_types::Uuid, diesel::pg::Pg> for UserId {
type Row = Uuid;
fn build(row: Self::Row) -> Self {
Use... |
#[test]
fn wrap_nodes_with_content_sizing_overflowing_margin() {
let layout = stretch::node::Node::new(
stretch::style::Style {
flex_direction: stretch::style::FlexDirection::Column,
size: stretch::geometry::Size {
width: stretch::style::Dimension::Points(500f32),
... |
use log::info;
use rocket::{http::Status, post, State};
use rocket_contrib::{
json,
json::{Json, JsonValue},
};
use rustflake::Snowflake;
use serde::{Deserialize, Serialize};
use std::process::Command;
use std::sync::{mpsc, mpsc::RecvTimeoutError};
use std::thread;
use std::time::Duration;
use crate::docker::D... |
use std::convert::TryInto;
use std::env;
use std::num::Wrapping;
const REPLACEMENT_TABLE: [[u8; 16]; 8] = [
[4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3],
[14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9],
[5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11],
[7, 13, 10, 1, 0, 8, 9, 15... |
use crate::tentacle::LogLine;
use futures::Async::*;
use futures::{Poll, Stream};
use log::*;
use std::fmt;
use std::fmt::Display;
use std::vec::Vec;
#[derive(Debug)]
pub enum LogStreamError {
DefaultError(String),
}
impl Display for LogStreamError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
... |
mod restore_structure;
mod parse_commands;
use crate::restore_structure::{Restore};
use crate::parse_commands::ParseCommand;
use cassandra_restore_keyspace::show_err_msg;
fn main() {
match ParseCommand::new() {
Ok(config) => {
let restore = Restore::new(config);
restore.run()
... |
use getopts;
use getopts::Options;
use std::env;
use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::io::{BufReader, BufWriter};
use std::process;
fn main() {
let args: Vec<String> = env::args().collect();
let mut opts = Options::new();
opts.optflag("h", "help", "print this help menu");
... |
fn main() {
let mut x = 5;
println!("The value of x is {}", x);
x = 6;
println!("The value of x is {}", x);
const MAX_POINTS: u32 = 100_000;
println!("Constant variable {}", MAX_POINTS);
let x = 7; // shadowing
println!("The value of x is {}", x);
let spaces = " ";
let spaces ... |
use crate::uwu::uwuify;
use crate::ResultExt;
use serenity::{
async_trait,
model::{
gateway::Ready,
interactions::{Interaction, InteractionResponseType},
},
prelude::*,
};
pub struct Handler;
impl Handler {
async fn handle_uwuify(&self, ctx: Context, interaction: Interaction) {
... |
use regex::Regex;
use std::str::FromStr as StrFromStr;
use strum_macros::EnumString;
use crate::util;
pub fn solve() {
let input_file = "input-day-19.txt";
println!("Day 19 answers");
print!(" first puzzle: ");
let (answer_p1, _answer_p2) = solve_both_file(input_file);
println!("{}", answer_p1);
... |
use std::collections::HashMap;
use std::sync::mpsc;
use std::cmp;
use intcode;
#[macro_use]
extern crate itertools;
fn main() {
let start_time = std::time::Instant::now();
let program = intcode::load_program("day11/input.txt").unwrap_or_else(|err| {
println!("Could not load input file!\n{:?}", err);
... |
// verification-helper: PROBLEM https://onlinejudge.u-aizu.ac.jp/problems/1009
fn main() {
loop {
let mut line = String::new();
if std::io::stdin().read_line(&mut line)
.map(|bytes| bytes == 0)
.unwrap_or(false)
{
break;
}
let nums = line
... |
// TODO: Needs improvement
pub fn count_smaller(nums: Vec<i32>) -> Vec<i32> {
let n = nums.len();
let mut result = vec![0; n];
for i in 0..n {
for j in i + 1..n {
if nums[i] > nums[j] {
result[i] += 1;
}
}
}
result
} |
use portmidi::types::MidiEvent;
use std::fmt;
const NUM_SLIDERS: usize = 8;
#[derive(Debug, PartialEq)]
pub enum Korg {
S, M, R,
Knob, Slider,
TrackLeft, TrackRight,
Cycle,
Set, MarkerLeft, MarkerRight,
Rewind, FastForward, Stop, Play, Record,
}
// A more readable representation of a midi event
pub s... |
#[doc = "Register `CR` reader"]
pub type R = crate::R<CR_SPEC>;
#[doc = "Register `CR` writer"]
pub type W = crate::W<CR_SPEC>;
#[doc = "Field `HSION` reader - Internal high-speed clock enable"]
pub type HSION_R = crate::BitReader<HSION_A>;
#[doc = "Internal high-speed clock enable\n\nValue on reset: 1"]
#[derive(Clone... |
mod support;
use cubik::server::ServerContainer;
use cubik::player::{Player, PlayerControlType};
use cubik::quadoctree::{QuadOctreeNode, BoundingBox};
use support::msg::AppMessage;
use std::time::{Instant, Duration};
use std::thread::sleep;
use std::collections::HashMap;
use crate::support::constants::APP_ID;
use cubi... |
mod parser;
mod scanner;
pub mod syntax_error;
mod tokens;
use ast::*;
use front::parser::Parser;
use front::syntax_error::SyntaxError;
use front::tokens::Token;
pub fn parse(filename: &str, input: &str) -> Result<Vec<Node>, Vec<SyntaxError>> {
let mut p = Parser::new(filename, input);
let mut values = Vec::n... |
#[doc = "Register `APBRSTR1` reader"]
pub type R = crate::R<APBRSTR1_SPEC>;
#[doc = "Register `APBRSTR1` writer"]
pub type W = crate::W<APBRSTR1_SPEC>;
#[doc = "Field `TIM3RST` reader - TIM3 timer reset"]
pub type TIM3RST_R = crate::BitReader;
#[doc = "Field `TIM3RST` writer - TIM3 timer reset"]
pub type TIM3RST_W<'a, ... |
//! This crate is responsible of providing [FFI] interface for `SVM`.
//!
//! [FFI]: https://doc.rust-lang.org/nomicon/ffi.html
#![deny(missing_docs)]
#![deny(unused)]
#![deny(dead_code)]
#![deny(unreachable_code)]
#![feature(vec_into_raw_parts)]
mod address;
mod byte_array;
mod macros;
mod r#ref;
mod state;
pub mod... |
use crate::core::shared_access_signature::{format_date, format_form, sign, SasProtocol, SasToken};
use chrono::{DateTime, Utc};
use std::{fmt, marker::PhantomData};
const SERVICE_SAS_VERSION: &str = "2020-06-12";
pub enum BlobSignedResource {
Blob, // b
BlobVersion, // bv
BlobSnapshot, // bs
... |
//! This module deals with configuration data including the management of the list of secrets
#![allow(clippy::filter_map)]
use crate::image::CONF_LINE_IDENTIFIER__CONTROL;
use crate::image::CONF_LINE_IDENTIFIER__IMAGE;
use rand::Rng;
use thiserror::Error;
//use serde::Deserialize;
use serde_derive::Deserialize;
/// ... |
use std::{env, fmt, ops::Deref};
const DEFAULT_CONSUL_ADDR: &str = "http://127.0.0.1:8500";
/// Simple wrapper around a type to keep it from being printed. The wrapped value
/// can still be printed if you wish by accessing it directly with .0
pub struct Secret<T>(pub T);
impl<T> fmt::Debug for Secret<T> {
fn fmt... |
use crate::lib::builders::BuildConfig;
use crate::lib::environment::Environment;
use crate::lib::error::DfxResult;
use crate::lib::models::canister::CanisterPool;
use crate::lib::models::canister_id_store::CanisterIdStore;
use crate::lib::provider::create_agent_environment;
use clap::Clap;
/// Builds all or specific ... |
/*
* Rustの所有権(ムーブ)。
* CreatedAt: 2019-06-01
*/
fn main() {
let a = String::from("Hello Ownership !!"); // ヒープ領域の確保
let b = a; // ムーブ(ヒープ領域の所有権がポインタ変数`a`から`b`へ移った。所有できるのは必ず1つのポインタ変数のみ)
println!("b = {}", b);
// println!("a = {}", a); // error[E0382]: use of moved value: `a`
}
|
extern crate iron;
extern crate router;
use std::env;
use iron::{Iron, Request, Response, IronResult};
use router::Router;
use iron::status;
// Serves a string to the user. Try accessing "/".
fn hello(_: &mut Request) -> IronResult<Response> {
let resp = Response::with((status::Ok, "Hello world!"));
Ok(resp)... |
//! Provide animation time signals.
//!
//! Each time signal is in milliseconds, and starts from 0. Any live
//! animation time signals will be updated each frame, and are strictly
//! increasing.
//!
//! For example, this will show a progress bar that takes 10 seconds to
//! fill:
//!
//! ```no_run
//! # use silkenweb... |
use std::{
io::{self, stdin, Write},
process,
};
use crate::preloader::ADDR;
use crate::compiler::npm_install;
use colored::*;
use once_cell::sync::Lazy;
use std::sync::Mutex;
pub static VERBOSE: Lazy<Mutex<bool>> = Lazy::new(|| Mutex::new(false));
pub fn log(text: String, verbose: bool) {
if !verbose {... |
use clap::{App, Arg};
use rustbg::extitem::ExtItem;
use rustbg::search::Search;
use rustbg::Config;
use std::fs::File;
use std::io::BufReader;
use std::io::{self, BufRead, Write};
use std::sync::RwLock;
const UAGENT: &str = "RarSpyder/1.0 (Linux x86_64;) Rust/1.44.0-nightly";
const MIRROR: &str = "rarbgproxied.org";
... |
use super::RingBufferStream;
use ds::RingSlice;
use ds::Slice;
use protocol::{Protocol, RequestId};
use std::sync::Arc;
pub(crate) struct Item {
data: ResponseData,
done: Option<(usize, Arc<RingBufferStream>)>,
}
pub struct ResponseData {
data: RingSlice,
req_id: RequestId,
seq: usize, // respons... |
#[doc = "Register `APB1RSTR1` reader"]
pub type R = crate::R<APB1RSTR1_SPEC>;
#[doc = "Register `APB1RSTR1` writer"]
pub type W = crate::W<APB1RSTR1_SPEC>;
#[doc = "Field `TIM2RST` reader - TIM2 timer reset"]
pub type TIM2RST_R = crate::BitReader<TIM2RST_A>;
#[doc = "TIM2 timer reset\n\nValue on reset: 0"]
#[derive(Clo... |
#[doc = "Register `PLLI2SCFGR` reader"]
pub type R = crate::R<PLLI2SCFGR_SPEC>;
#[doc = "Register `PLLI2SCFGR` writer"]
pub type W = crate::W<PLLI2SCFGR_SPEC>;
#[doc = "Field `PLLI2SM` reader - Division factor for audio PLL (PLLI2S) input clock"]
pub type PLLI2SM_R = crate::FieldReader;
#[doc = "Field `PLLI2SM` writer ... |
use apllodb_sql_parser::apllodb_ast;
use apllodb_shared_components::ApllodbResult;
use apllodb_storage_engine_interface::AlterTableAction;
use super::AstTranslator;
impl AstTranslator {
pub fn alter_table_action(
ast_alter_table_action: apllodb_ast::Action,
) -> ApllodbResult<AlterTableAction> {
... |
fn main() {
let (a, b, c) = {
let mut line = String::new();
std::io::stdin().read_line(&mut line).unwrap();
let mut ws = line.trim_end().split_whitespace();
let n1: u64 = ws.next().unwrap().parse().unwrap();
let n2: u64 = ws.next().unwrap().parse().unwrap();
let n3: u... |
use json::JsonValue;
use regex::Regex;
use super::{match_json_slice, try_to_match_filters, SelectionLens, SelectionLensParser};
struct Sequence {
matchers: Vec<Box<dyn SelectionLens>>,
}
impl SelectionLens for Sequence {
fn select<'a>(&self, input: Option<&'a JsonValue>) -> Option<&'a JsonValue> {
ma... |
use std::{net::TcpStream, io::{Read, Write}, path};
use crate::server::request::Request;
use crate::server::file_manager::{get_file, get_mime_type, DEFAULT_PATH};
use std::sync::Arc;
const BAD_REQUEST: &'static[u8] = b"HTTP/1.1 400 BAD REQUEST";
const NOT_FOUND: &'static[u8] = b"HTTP/1.1 404 NOT FOUND";
const OK_REQUE... |
use crate::components::container::NavLinks;
use crate::components::container::COPYRIGHT_YEARS;
use crate::templates::docs::generation::{DocsManifest, DocsVersionStatus};
use perseus::{link, t};
use sycamore::context::use_context;
use sycamore::prelude::Template as SycamoreTemplate;
use sycamore::prelude::*;
use sycamor... |
#[doc = "Register `SR` reader"]
pub type R = crate::R<SR_SPEC>;
#[doc = "Field `XDCNT` reader - data counter - When the I3C is acting as controller: number of targets detected on the bus - When the I3C is acting as target: number of transmitted bytes - Whatever the I3C is acting as controller or target: number of data ... |
use crate::common::*;
pub fn run() -> Result<(), i32> {
#[cfg(windows)]
ansi_term::enable_ansi_support().ok();
env_logger::Builder::from_env(
env_logger::Env::new()
.filter("JUST_LOG")
.write_style("JUST_LOG_STYLE"),
)
.init();
let app = Config::app();
info!("Parsing command line argum... |
/// Binary Preference-based measure
fn bpref(rel: &Vec<bool>) -> f64 {
let count_relevant = rel.iter().filter(|x| **x).count();
if count_relevant == 0 {
return 0.0;
}
let mut i = rel.len() - 1;
while !rel[i] {
i -= 1;
}
let count_non_relevant = rel[0..i].iter().filter(|x| !*... |
use crate::num::simd::SimdScalar;
use crate::num::simd::{
f32s, f64s, i128s, i16s, i32s, i64s, i8s, isizes, u128s, u16s, u32s, u64s, u8s, usizes,
};
pub trait Scalar: sealed::Ops {
const ZERO: Self;
const ONE: Self;
type Simd: SimdScalar<Single = Self>;
fn into_real<R: Real>(self) -> R;
fn cl... |
use std::env;
use std::fs;
use std::path::Path;
const MATRIX_SIZE:usize =1000;
enum LightMode{
Switch,
Dimmer,
}
enum Ops{
On,
Off,
Toggle,
}
fn read_instructions(filename:&str)->String{
let fpath = Path::new(filename);
let abspath = env::current_dir()
.unwrap()
.into... |
extern crate intrepion_x_fizz_buzz;
#[test]
fn test_one_is_one() {
assert_eq!("1", intrepion_x_fizz_buzz::fizz_buzz(1));
}
#[test]
fn test_two_is_two() {
assert_eq!("2", intrepion_x_fizz_buzz::fizz_buzz(2));
}
#[test]
fn test_three_is_fizz() {
assert_eq!("Fizz", intrepion_x_fizz_buzz::fizz_buzz(3));
}
#[test]... |
pub mod collision;
pub type CollisionWorld = ncollide2d::world::CollisionWorld<f32, hecs::Entity>;
pub type PhysHandle = ncollide2d::pipeline::CollisionObjectSlabHandle;
pub use ncollide2d::{pipeline::CollisionGroups, shape::Cuboid};
use crate::Game;
use glsp::FromVal;
/// Collision Group Constants
#[derive(serde::D... |
// Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::error::Error;
use std::fmt;
use serde::Deserialize;
use serde::Serialize;
/// Returned by a failed integrity-check on a slab,... |
use std::ops::AddAssign;
#[derive(Debug)]
pub enum Opcode {
Load(u8),
LoadConst(u8),
LoadImmediate(i8),
Store(u8),
Add, Sub, Mul, Div,
Print
}
#[derive(Debug)]
pub struct Chunk {
pub code: Vec<Opcode>,
pub constants: Vec<i64>
}
impl Chunk{
pub fn new() -> Chunk{
Chunk{code:v... |
#[doc = "Register `GPIOJ_SIDR` reader"]
pub type R = crate::R<GPIOJ_SIDR_SPEC>;
#[doc = "Field `SIDR` reader - SIDR"]
pub type SIDR_R = crate::FieldReader<u32>;
impl R {
#[doc = "Bits 0:31 - SIDR"]
#[inline(always)]
pub fn sidr(&self) -> SIDR_R {
SIDR_R::new(self.bits)
}
}
#[doc = "GPIO size ide... |
fn main() {
let nums: Vec<i32> = Vec::new();
let mut nums = vec![1,2,3];
nums.push(4);
nums.remove(2);
for num in &nums {
println!("{}",num);
}
enum Value {
Int(i32),
Float(f32)
};
let random = vec![Value::Int(3), Value::Float(4.56)];
for val in &ran... |
#[macro_use]
extern crate clap;
#[macro_use]
extern crate log;
use std::env;
use std::path::*;
use std::process;
use clap::App;
use log::{LogRecord, LogLevel, LogLevelFilter};
use env_logger::LogBuilder;
use console::style;
mod config;
mod build;
mod erl;
fn handle_command(bin_path: PathBuf) {
let yaml = load_y... |
use colored::Colorize;
use regex::Regex;
use std::process::{Command, Stdio};
use std::thread;
const URL: &str = "https://google.com"; // Here you put the url
fn threads() {
const NTHREADS: u32 = 1; // number of threads
let mut children = vec![];
for _i in 0..NTHREADS {
children.push(thread::spawn... |
use crate::rdata::*;
/// The enumeration that represents implemented types of DNS resource records data
#[derive(Debug, PartialEq)]
pub enum RData<'a> {
A(A),
AAAA(Aaaa),
CNAME(Cname<'a>),
MX(Mx<'a>),
NS(Ns<'a>),
PTR(Ptr<'a>),
SOA(Soa<'a>),
SRV(Srv<'a>),
TXT(Txt<'a>),
OPT(&'a [u... |
use super::orientation::{Orientation, Rotation, MatingSide};
pub fn invert_side(width: u32, side: u32) -> u32 {
(0..width).fold(0, |total, n|
(total << 1) + ((side >> n) & 1)
)
}
#[derive(Debug)]
pub struct Tile {
pub label: u32,
pub data: Vec<bool>,
pub width: u32,
pub sides: [u32; 4]... |
/// Various representations of a variable name.
///
/// Note that the use of the cached! macro is safe here because this structure is
/// immutable after initialization.
pub struct ScalarName {
/// Any string representation of the variable
pub canonical: String
}
/// Naively cache the first return value of the... |
// This file was generated by gir (https://github.com/gtk-rs/gir @ fbb95f4)
// from gir-files (https://github.com/gtk-rs/gir-files @ 77d1f70)
// DO NOT EDIT
use Cancellable;
use Error;
use File;
use IOStream;
use Icon;
use InputStream;
use Resource;
use ResourceLookupFlags;
use ffi;
use glib;
use glib::object::IsA;
us... |
//! The `parser` module contains types and functions useful for parsing Parallisp.
use nom;
use nom::{digit, IResult, multispace, space};
use std::convert::From;
use std::error::Error;
use std::{fmt, i64, iter, num, string};
use std::iter::FromIterator;
use std::str::FromStr;
use super::Expr;
/// `ParseError`s are er... |
use header::{self, HdrVal};
use headers::parse::CommaDelimited;
use std::fmt;
/// A value to represent an encoding used in `Transfer-Encoding`
/// or `Accept-Encoding` header.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Encoding<T> {
kind: Kind<T>,
}
/// Represents one or more encodings
#[derive(Clone, Deb... |
// 有一幅以二维整数数组表示的图画,每一个整数表示该图画的像素值大小,数值在 0 到 65535 之间。
// 给你一个坐标 (sr, sc) 表示图像渲染开始的像素值(行 ,列)和一个新的颜色值 newColor,让你重新上色这幅图像。
// 为了完成上色工作,从初始坐标开始,记录初始坐标的上下左右四个方向上像素值与初始坐标相同的相连像素点,接着再记录这四个方向上符合条件的像素点与他们对应四个方向上像素值与初始坐标相同的相连像素点,……,重复该过程。将所有有记录的像素点的颜色值改为新的颜色值。
// 最后返回经过上色渲染后的图像。
//
// ## 示例 1:
//
// 输入:
// image = [[1,1,1],[1,1... |
extern crate ggez;
extern crate nalgebra;
extern crate rand;
extern crate hsluv;
use ggez::*;
use ggez::event::{self, Keycode, Mod, MouseButton, MouseState};
use ggez::graphics::{DrawParam, DrawMode, Mesh, Rect, Point2, Vector2, Matrix4};
use nalgebra::{Real};
use std::fs::File;
mod entities;
mod star_system_gen;
u... |
/// AnnotatedTagObject contains meta information of the tag object
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct AnnotatedTagObject {
pub sha: Option<String>,
#[serde(rename = "type")]
pub type_: Option<String>,
pub url: Option<String>,
}
impl AnnotatedTagObject {
/// Create ... |
#[doc = "Register `OR` reader"]
pub type R = crate::R<OR_SPEC>;
#[doc = "Register `OR` writer"]
pub type W = crate::W<OR_SPEC>;
#[doc = "Field `OR_` reader - Option register bit 1"]
pub type OR__R = crate::FieldReader<OR__A>;
#[doc = "Option register bit 1\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, ... |
use std::io::Write;
use crossterm::{
cursor::{self},
style::{self, Colorize, StyledContent},
QueueableCommand, Result,
};
#[derive(Clone, Copy, Debug)]
pub enum GameContent {
SnakeHead(usize),
SnakeBody(usize),
Food,
Border,
Empty,
Character(char),
CharacterOnBorder(char),
}
f... |
pub fn run() {
let groups: Vec<&str> = include_str!("input.txt").split("\n\n").collect();
let mut some = 0;
let mut all = 0;
for g in groups.iter() {
let a = count_answers_in_group(g);
some += a.0;
all += a.1;
}
println!("Day06 - Part 1: {}", some);
println!("Day06 ... |
use lazy_static::lazy_static;
use regex::Regex;
use serde::{Deserialize, Serialize};
lazy_static! {
/// Check if a wikipedia anchor links to an external resource.
static ref EXT_LINK : Regex = Regex::new("^[A-Za-z]+:").unwrap();
}
/// Wikipedia anchor, representing a link between pages, optionally with a
/// ... |
use super::*;
use super::{Highlight, Select};
use std::sync::atomic::Ordering;
use std::sync::Arc;
use tokio::sync::RwLock;
#[derive(Clone)]
pub enum FocusedWidget<'a> {
DownloadTable(Arc<RwLock<DownloadTable<'a>>>),
FileTable(Arc<RwLock<FileTable<'a>>>),
MessageList(Arc<RwLock<MessageList<'a>>>),
}
/* ... |
use std::marker::PhantomData;
use super::Pusherator;
pub struct ForEach<Func, In> {
func: Func,
_marker: PhantomData<fn(In)>,
}
impl<Func, In> Pusherator for ForEach<Func, In>
where
Func: FnMut(In),
{
type Item = In;
fn give(&mut self, item: Self::Item) {
(self.func)(item)
}
}
impl<Fun... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.