text stringlengths 8 4.13M |
|---|
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors
//
// 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
//
// Unl... |
#![warn(missing_docs)]
use std::error::Error;
use auto_impl::auto_impl;
use slotmap::Key;
use super::ops::DelayType;
use super::{Color, GraphNodeId, GraphSubgraphId};
/// Trait for writing textual representations of graphs, i.e. mermaid or dot graphs.
#[auto_impl(&mut, Box)]
pub trait GraphWrite {
/// Error typ... |
use std::fs::File;
use std::io::Read;
fn main() {
let mut file = File::open("d06-input").expect("file not found");
let mut input = String::new();
file.read_to_string(&mut input).expect("something went wrong reading file");
let mut sum = 0;
let data: Vec<String> = input.split("\n\n").map(|s| s.to_string()).colle... |
use std::borrow::Cow;
use std::io;
use futures::{future, FutureExt};
use futures::future::{lazy, Future};
use futures::channel::mpsc::unbounded;
use futures::channel::oneshot::{channel, Receiver};
use tokio::runtime::current_thread::Handle;
use tokio_timer::{timer::Timer, clock::Clock};
use tokio_net::driver::Reactor... |
use std::env;
use std::process;
pub struct Options {
pub input : String,
pub output : String,
//pub weight : String,
pub tolerate : String,
pub matrix : String,
pub colorize : String,
}
impl Options {
pub fn new() -> Options
{
let argv : Vec<String> = env::args().collect();
let argc : usize = ar... |
// Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
use super::{
rescue, CYCLE_LENGTH as HASH_CYCLE_LEN, SIG_CYCLE_LENGTH as SIG_CYCLE_LEN, TRACE_WIDTH,
};
use crate::utils::{are_equal, ... |
//TODO: make a build script that builds out each of these for the given platform
//TODO: create a launcher system
#[cfg(feature = "dx11")]
pub extern crate gfx_backend_dx11 as back;
#[cfg(feature = "dx12")]
pub extern crate gfx_backend_dx12 as back;
//TODO: make webgl work
#[cfg(any(feature = "gl", feature = "wgl"))... |
fn century(year: u32) -> u32 {
return ((year - 1) / 100) + 1
}
|
macro_rules! fourcc_code {
($a:expr, $b:expr, $c:expr, $d:expr) => {
(($a as u32) |
(($b as u32) << 8) |
(($c as u32) << 16) |
(($d as u32) << 24)) as u32
};
}
#[derive(Debug)]
#[repr(u32)]
pub enum Format {
RGB888 = fourcc_code!('R', 'G', '2', '4'),
XRGB88... |
#[derive(Debug)]
struct Person<'a> {
name: &'a str
}
fn make_person<'a>(name: &'a str) -> Person<'a> {
Person {name}
}
fn make_static_str() -> &'static str {
"hello"
}
fn make_ref_str<'a>() -> &'a str {
"hello"
}
fn modify_string(s: &mut String) {
s.push_str(" world");
}
#[cfg(test)]
mod test {... |
#[doc = "Reader of register HWCFGR2"]
pub type R = crate::R<u32, super::HWCFGR2>;
#[doc = "Reader of field `CFG1`"]
pub type CFG1_R = crate::R<u8, u8>;
#[doc = "Reader of field `CFG2`"]
pub type CFG2_R = crate::R<u8, u8>;
impl R {
#[doc = "Bits 0:3 - CFG1"]
#[inline(always)]
pub fn cfg1(&self) -> CFG1_R {
... |
use std::error::Error;
use std::fs::read_to_string;
use std::path::PathBuf;
use structopt::StructOpt;
use crate::model::*;
use crate::PROJECT_TEMP_FILE;
mod common;
mod change_column;
mod change_tags;
#[derive(StructOpt, Debug)]
pub struct CommitMsg {
file: PathBuf,
}
pub fn commit_msg(args: CommitMsg) -> Result... |
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
/// Objects that can be cast to another object in a saturating way.
///
/// = Remarks
///
/// This is used to cast be... |
use std::collections::{HashMap, HashSet, VecDeque};
use std::io;
use ckb_logger::{debug, warn};
use futures::{
prelude::*,
sync::mpsc::{channel, Receiver, Sender},
Async, Poll, Stream,
};
use p2p::{
bytes::Bytes,
context::{ProtocolContext, ProtocolContextMutRef},
multiaddr::Multiaddr,
trait... |
// This file is part of Substrate.
// Copyright (C) 2017-2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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
//
// ht... |
pub mod clock;
pub mod pwm;
pub mod sercom;
pub mod timer;
pub mod trng;
#[cfg(feature="unproven")]
pub mod adc;
|
/**
* File format: (Version \n\0\0\1)
* Magic number:
* "BKTree: " + "0000\n"
* Checksum: "SHA256: " + hex sha-256 of the remainder of the file following this newline + "\n---\n"
* CBOR encoded header as a map:
* "Created-On": ISO-8601 timestamp
* "Node-Format": "8 bits distance, 8 bits ch... |
extern crate stream_cipher;
extern crate block_cipher_trait;
extern crate salsa20_family;
use block_cipher_trait::generic_array::GenericArray;
use salsa20_family::Salsa20;
use stream_cipher::NewStreamCipher;
use stream_cipher::StreamCipher;
use stream_cipher::SyncStreamCipherSeek;
#[cfg(test)]
const KEY_BYTES: usize ... |
use std::net::SocketAddr;
use hydroflow::hydroflow_syntax;
use hydroflow::util::{UdpSink, UdpStream};
use crate::helpers::parse_command;
use crate::protocol::KVSMessage;
use crate::GraphType;
pub(crate) async fn run_client(
outbound: UdpSink,
inbound: UdpStream,
server_addr: SocketAddr,
graph: Option... |
#[macro_export]
macro_rules! not_nan {
( $l:expr ) => {
ordered_float::NotNan::new($l).unwrap()
};
}
|
#[doc = "Register `CSR17` reader"]
pub type R = crate::R<CSR17_SPEC>;
#[doc = "Register `CSR17` writer"]
pub type W = crate::W<CSR17_SPEC>;
#[doc = "Field `CSR17` reader - CSR17"]
pub type CSR17_R = crate::FieldReader<u32>;
#[doc = "Field `CSR17` writer - CSR17"]
pub type CSR17_W<'a, REG, const O: u8> = crate::FieldWri... |
use crate::{
gui::{BuildContext, UiMessage, UiNode},
scene::{EditorScene, Selection},
send_sync_message,
sidebar::{
base::BaseSection, camera::CameraSection, decal::DecalSection, light::LightSection,
lod::LodGroupEditor, mesh::MeshSection, particle::ParticleSystemSection,
physics... |
pub mod svg_movie;
|
//! This example shows how to add an IP address to the given link, with minimal error handling.
//! You need to be root run this example.
use std::env;
use std::thread::spawn;
use futures::{Future, Stream};
use ipnetwork::IpNetwork;
use tokio_core::reactor::Core;
use netlink_packet_route::link::nlas::LinkNla;
use rt... |
pub mod gameobjects;
pub mod components;
pub mod rendering; |
use serde::{Serialize, Deserialize};
use super::location::Location;
use chrono::{DateTime, Local};
/// returned by the mvg api
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ConnectionList{
pub connection_list: Vec<Connection>
}
/// Desciption of one time-dependant connect... |
use crate::data::channel;
use std::convert::TryFrom;
use std::fmt::{self, Display};
use std::str::FromStr;
/// A wildcard Channel specifier.
///
/// This type represents a value suitable for use with [wildcard subscribe]
/// feature.
///
/// Currently you can have up to three levels deep with your channel segment
/// ... |
//! This file contains the types necessary to collect various types of stats.
use crate::loom::sync::atomic::{AtomicU64, Ordering::Relaxed};
/// This type contains methods to retrieve stats from a Tokio runtime.
#[derive(Debug)]
pub struct RuntimeStats {
workers: Box<[WorkerStats]>,
}
/// This type contains metho... |
use super::error::Error;
use super::header::Header;
use super::types;
use num_traits::FromPrimitive;
use std::io::Read;
#[derive(Default, Debug, Clone)]
pub struct SegmentHeader {
pub phtype: types::SegmentType,
pub flags: types::SegmentFlags,
pub offset: u64,
pub vaddr: u64,
pub paddr: u64,
p... |
use memlib::logger::MinimalLogger;
use memlib::memory;
use log::*;
use std::error::Error;
mod config;
mod hacks;
mod sdk;
pub const PROCESS_NAME: &str = "csgo.exe";
pub const CHEAT_TICKRATE: u64 = 1;
const LOG_LEVEL: LevelFilter = LevelFilter::Debug;
fn run() -> Result<(), Box<dyn Error>> {
MinimalLogger::init... |
pub fn collatz(n: u64) -> Option<u64> {
match n {
0 => None,
1 => Some(0),
n if n%2 == 0 => collatz(n/2).map(|x| x+1),
_ => collatz(3*n+1).map(|x| x+1)
}
}
|
use x86_64::VirtAddr;
use x86_64::structures::gdt::{GlobalDescriptorTable, Descriptor, SegmentSelector};
use x86_64::structures::tss::TaskStateSegment;
pub const DOUBLE_FAULT_IST_INDEX: u16 = 0;
#[no_mangle]
pub static mut TSS: TaskStateSegment = TaskStateSegment::new();
#[allow(unused)] const GDT_DPL0: u64 = 0 << 4... |
#![feature(option_result_contains)]
// #![allow(dead_code)]
#![allow(unused_imports)]
#[macro_use]
extern crate io_error;
extern crate strum;
extern crate strum_macros;
extern crate fixed;
extern crate log;
pub mod methods;
pub mod operators;
pub mod pddl_parser;
#[cfg(test)]
mod tests {
#[test]
fn it_works... |
#![allow(unused_imports)]
#![allow(dead_code)]
extern crate rand;
use std::io::{self, BufRead, BufReader, Read, Write};
use std::net::{TcpListener, TcpStream, ToSocketAddrs};
use std::str;
use std::{thread, time};
use rand::prelude::*;
pub const SOH: char = '\u{01}';
fn create_fix_message() -> String {
let mut ... |
use std::error::Error as StdError;
use std::marker;
use std::result::Result as StdResult;
use crate::{Result, Error};
/// Lazily decode the data bytes, it can be used to avoid CPU intensive decoding
/// before making sure we really need to decode it (e.g. based on the key).
#[derive(Default)]
pub struct LazyDecode<C>... |
// Copied from nom master:
// https://github.com/Geal/nom/blob/a38188f333c29d00c32a3082bec5491d2eefa33f/src/sequence.rs#L591-L687
// Will be released in nom 2.0.
#![cfg(feature = "parsing")]
#[macro_export]
#[doc(hidden)]
macro_rules! do_parse (
($i:expr, $($rest:tt)*) => (
{
do_parse_impl!($i, 0usize, $(... |
use crate::base::{ArchivedRkyvRequest, ErrorCode, RkyvGenericResponse};
use crate::storage::local::FileStorage;
pub fn commit_write(
request: &ArchivedRkyvRequest,
file_storage: &FileStorage,
) -> Result<RkyvGenericResponse, ErrorCode> {
match request {
ArchivedRkyvRequest::Fsync { inode } => file_... |
use crate::config::{Config, ThemeSetting};
use crate::display_action::DisplayAction;
use crate::models::Manager;
use crate::models::Window;
use crate::models::Workspace;
use crate::DisplayEvent;
#[cfg(test)]
mod mock_display_server;
pub mod xlib_display_server;
use std::sync::Arc;
#[cfg(test)]
pub use self::mock_displ... |
use super::util;
use super::mapping;
use super::controls;
use super::rendering;
use super::ai;
use super::player_actions;
use super::equipment::{ Equipment, Slot };
use super::data::{
Object,
Fighter,
DeathCallback,
Game,
Tcod,
MessageLog,
PlayerAction,
Item,
};
use tcod::input::{self, E... |
mod cli;
fn main() -> std::io::Result<()> {
let project = cli::Project::new();
project.build_structure()?;
Ok(())
}
|
mod event;
mod flags;
mod key;
pub use self::event::*;
pub use self::flags::*;
pub use self::key::*;
|
use sys;
pub struct ConstraintSolver {
solver: Box<sys::btSequentialImpulseConstraintSolver>,
}
impl ConstraintSolver {
pub fn new() -> Self {
ConstraintSolver {
solver: Box::new(unsafe { sys::btSequentialImpulseConstraintSolver::new() }),
}
}
pub fn as_ptr(&self) -> *mut ... |
mod cluster_client;
mod node_client;
mod peer_client;
mod tcp_client;
pub use cluster_client::RemoteRaftGroups;
pub use node_client::NodeClient;
pub use peer_client::PeerClient;
pub use peer_client::TcpPeerClient;
|
use std::collections::HashMap;
use std::fs;
pub fn run(filename: &str) {
let protein = fs::read_to_string(filename).expect("Something went wrong reading the file");
let protein = protein.trim();
let table: HashMap<char, &str> = [
('A', "71.03711"),
('C', "103.00919"),
('D', "115.026... |
pub use crate::apex::blackboard::abstraction::*;
pub use crate::apex::buffer::abstraction::*;
pub use crate::apex::error::abstraction::*;
pub use crate::apex::event::abstraction::*;
pub use crate::apex::file_system::abstraction::*;
pub use crate::apex::interrupt::abstraction::*;
pub use crate::apex::limits;
pub use cra... |
pub mod operations;
pub mod op_types;
mod imagemagick_commands; |
/*===============================================================================================*/
// Copyright 2016 Kyle Finlay
//
// 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
//
// ... |
/*
* BitTorrent bencode decoder demo (Rust)
*
* Copyright (c) 2021 Project Nayuki. (MIT License)
* https://www.nayuki.io/page/bittorrent-bencode-format-tools
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"),... |
#[doc = "Register `CCR` reader"]
pub type R = crate::R<CCR_SPEC>;
#[doc = "Register `CCR` writer"]
pub type W = crate::W<CCR_SPEC>;
#[doc = "Field `CKMODE` reader - ADC clock mode These bits are set and cleared by software to define the ADC clock scheme (which is common to both master and slave ADCs): In all synchronou... |
use std::sync::Arc;
use chrono::Utc;
use eyre::Report;
use hashbrown::HashMap;
use rosu_v2::prelude::Beatmapset;
use twilight_model::channel::Message;
use crate::{
commands::osu::MapsetEntry, core::Context, custom_client::OsuTrackerMapsetEntry,
embeds::OsuTrackerMapsetsEmbed, BotResult,
};
use super::{Pages,... |
use std::str::FromStr;
use std::time::Duration as StdDuration;
use nom::{
branch::alt,
bytes::complete::tag,
character::complete::digit1,
combinator::{all_consuming, map_res, opt},
error::{Error, ErrorKind, ParseError},
number::complete::float,
sequence::{preceded, separated_pair, terminate... |
pub mod opaque;
pub mod password;
pub mod ssh_key;
pub mod x509;
|
//! Input tokenizer
use std;
use std::borrow::ToOwned;
use std::rc::Rc;
use parser::tokens::{Token, SourceLocation, dummy_source};
use parser::util::{SharedString, rcstr, rcstring};
// --- Lexer: Error -------------------------------------------------------------
const SYMBOL_CHARS: &'static str = "+-*/%\\=<... |
use wasm_bindgen::prelude::*;
use crate::{active_tab, goto_page};
#[wasm_bindgen]
pub async fn quadcopter() {
// Set active tab.
active_tab("");
// Go to the page.
goto_page(
"/projects/quadcopter",
"/api/projects/quadcopter/quadcopter.html?ver=HoXPgcmMerc",
"Quadcopter",
... |
use std::io;
use std::io::BufRead;
mod ledger;
use ledger::account::Account;
use ledger::title::Title;
#[derive(Debug)]
struct Transaction {
title: Title,
accounts: Vec<Account>,
}
struct ErrorMsg<'a> {
line_no: i32,
message: &'a str,
}
fn parse<'a>(source: impl BufRead) -> Result<Vec<Transaction>, ... |
use crate::common::*;
/// A module, the top-level type produced by the parser. So-named because
/// although at present, all justfiles consist of a single module, in the future
/// we will likely have multi-module and multi-file justfiles.
///
/// Not all successful parses result in valid justfiles, so additional
/// ... |
extern crate pkg_config;
use std::env;
use std::process;
fn main() {
if let Ok(info) = pkg_config::find_library("openssl") {
let paths = env::join_paths(info.include_paths).unwrap();
println!("cargo:include={}", paths.to_str().unwrap());
process::exit(0);
}
process::exit(1);
}
|
pub type Entity = usize; |
#[derive(Debug)]
pub enum Signal {
Dot,
Dash,
ShortGap,
LongGap,
}
pub fn signals_to_char(signals: &[Signal]) -> Option<char> {
use Signal::*;
match signals {
&[Dot, Dash] => Some('a'),
&[Dash, Dot, Dot, Dot] => Some('b'),
_ => None,
}
}
pub struct SignalProcessor ... |
use std::cmp::{max, min};
/// Solves the Day 05 Part 1 puzzle with respect to the given input.
pub fn part_1(input: String) {
let mut vents: Vec<Vent> = Vec::new();
for line in input.lines() {
let mut segments = line.split(" -> ");
let mut beg = segments.next().unwrap().split(",");
le... |
#![feature(generic_associated_types)]
use crystalorb::{client::stage::Stage, Config, TweeningMethod};
use test_env_log::test;
mod common;
use common::MockClientServer;
#[test]
fn when_server_and_client_clocks_desync_then_client_should_resync_quickly() {
const UPDATE_COUNT: usize = 200;
const TIMESTEP_SECOND... |
#[macro_use]
extern crate nom;
pub mod lexer;
pub mod ast;
pub mod parser; |
use std::fmt::{self, Display, Formatter};
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
pub struct Position {
line: usize,
col: usize,
}
impl Position {
fn to(self, other: Position) -> Span {
Span {
from: self,
to: other,
}
}
}
impl Display for Position... |
fn main() {
println!("Hello world!");
another_function();
another_function2(5);
}
fn another_function() {
println!("ANother function");
}
fn another_function2(x:i32){
println!("The value of x = {}",x);
}
|
#![macro_use]
use std::ops::*;
use std::cmp::*;
use num::*;
/// Returns true when 2 values subtracted are smaller than eps.
#[inline]
pub fn nearly_equal_eps<T>(a: T, b: T, eps: T) -> bool
where T: Sub<Output = T> + Signed + PartialOrd
{
let diff = abs(a - b);
diff < eps
}
/// Returns true, when a and b ... |
use std::net::Ipv4Addr;
use std::env;
use stremio_addon_sdk::server::{serve_http, ServerOptions};
mod manifest;
use manifest::get_manifest;
mod handlers;
use handlers::build;
#[tokio::main]
async fn main() {
// get the Manifest, which is declared in manifest.rs
let manifest = get_manifest();
// get the ... |
use particle::collide::absorb::Absorber;
use particle::collide::collide::Collider;
use std::marker::PhantomData;
pub trait TokenLike: Ord + Clone {}
impl TokenLike for () {}
impl<T> TokenLike for T
where T: Ord + Clone
{
}
impl<'a, C: 'a, D: 'a, B: 'a> IntoIterator for &'a SackType<C, D, B>
where B: SackBac... |
use crate::generate::src::{quotable_to_src, quote, Src, ToSrc};
use crate::grammar::ParseNodeShape;
use crate::grammar::{Grammar, MatchesEmpty, Rule, RuleWithNamedFields};
use crate::scannerless::Pat as SPat;
use ordermap::{Entry, OrderMap, OrderSet};
use std::borrow::Cow;
use std::cell::RefCell;
use std::fmt::Write a... |
use super::{Measure, Measurements};
use sightglass_data::Phase;
/// For users that may want to record measurements on their own, this mechanism allows the tool to
/// be used without the overhead of any measurement activity. TODO document example using `perf` and
/// `start`/`end` (how to reference `NoopMeasure::start... |
use std::fs::File;
use std::io::Read;
use scan_fmt::*;
use std::collections::HashMap;
fn main() {
let mut file = File::open("input").unwrap();
let mut buf = String::new();
file.read_to_string(&mut buf).unwrap();
let lines = buf.lines();
let edges: Vec<(char,char)> = lines.map(|line| {
let ... |
use crate::sys::unix::net::{new_ip_socket, socket_addr};
use crate::sys::unix::{SourceFd, TcpStream};
use crate::{event, Interest, Registry, Token};
use std::fmt;
use std::io;
use std::mem::size_of;
use std::net::{self, SocketAddr};
use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
pub struct TcpListener... |
/*
Copyright (c) 2023 Uber Technologies, Inc.
<p>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
<p>http://www.apache.org/licenses/LICENSE-2.0
<p>Unless required by applicable law or agreed to... |
//! This example demonstrates using the [attribute macro](https://doc.rust-lang.org/reference/procedural-macros.html#attribute-macros)
//! [`inline`] to expand struct fields to individual columns in a [`Table`] display.
//!
//! * Note that without inlining a struct or enum field, those objects
//! must implement the [`... |
pub mod adjacent;
pub mod hash;
pub mod rect;
|
use file;
pub fn run() {
let inputs = file::read_inputs("Day2.txt");
let lines = read_values(&inputs);
part1(&lines);
part2(&lines);
part2_recursive(&lines);
part1(&read_values(&"5 1 9 5\n7 5 3\n2 4 6 8"));
part2(&read_values(&"5 9 2 8\n9 4 7 3\n3 8 6 5"));
}
fn read_values(inputs: &str)... |
use std::fmt;
use std::ops::{Deref, DerefMut};
use std::iter::FromIterator;
use std::cell::{RefCell, Ref, RefMut};
use std::ptr;
use std::mem;
use std::ffi::{CStr, CString};
use std::any::TypeId;
use std::marker::PhantomData;
use std::collections::{HashMap, VecDeque};
use std::collections::hash_map::Entry as HashMapEnt... |
// This module attempts to implement the Generalized Policy Iteration
// (GPI) algorithm as an abstract concept, allowing clients to
// "plug in" different policy evaluation/improvement algorithms.
use std::collections::HashMap;
use rand::Rng;
use game::{State, Action, Deck, Reward, MIN_SUM, MAX_SUM, MIN_CARD, MAX_C... |
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::difficulty;
use crate::difficulty::{difficult_to_target, target_to_difficulty};
use anyhow::{Error, Result};
use argon2::{self, Config};
use byteorder::{ByteOrder, LittleEndian, ReadBytesExt, WriteBytesExt};
use config::N... |
//! Extract author information for book clusters.
use std::path::PathBuf;
use crate::arrow::polars::nonnull_schema;
use crate::arrow::writer::open_parquet_writer;
use crate::ids::codes::*;
use crate::prelude::*;
use polars::prelude::*;
static GRAPH_NODE_FILE: &str = "book-links/cluster-graph-nodes.parquet";
#[derive... |
mod atlas_rect;
use vulkano::command_buffer::SubpassContents;
use gristmill::asset::image::{Image, TileAtlasImage};
use gristmill::renderer::{LoadContext, RenderContext, scene};
use gristmill::geometry2d::*;
use super::{Entity, World};
use atlas_rect::{Texture, TileAtlasTexture, AtlasRectPipeline};
#[derive(Clone)]... |
/// If `profile` feature is enabled, records high-level profiling information to `profile.csv`.
/// Recording is done via a thread-local buffer and dedicated file writing thread, in an attempt to
/// mitigate overhead.
///
#[macro_export(local_inner_macros)]
macro_rules! profile {
($name: expr) => {
#[cfg(f... |
use nix::errno::Errno;
use nix::unistd::Pid;
use nix::sys::ptrace;
use core::ffi::c_void;
#[derive(Clone)]
#[derive(Copy)]
#[derive(Debug)]
pub struct breakpoint {
saved_data: u8,
pub addr: usize,
pub enabled: bool,
pub pid: Pid,
}
impl breakpoint {
pub fn New(proc: Pid, target_addr: usize) -> breakpoint {
bre... |
#[doc = "Register `VLCR` reader"]
pub type R = crate::R<VLCR_SPEC>;
#[doc = "Register `VLCR` writer"]
pub type W = crate::W<VLCR_SPEC>;
#[doc = "Field `HLINE` reader - Horizontal line duration"]
pub type HLINE_R = crate::FieldReader<u16>;
#[doc = "Field `HLINE` writer - Horizontal line duration"]
pub type HLINE_W<'a, R... |
trait Bob {
fn is_shouting(&self) -> bool;
fn is_silent(&self) -> bool;
}
impl Bob for str {
fn is_shouting(&self) -> bool {
self.chars().all(|c| (!c.is_alphabetic() || c.is_uppercase()))
}
fn is_silent(&self) -> bool {
self.chars().all(|c| !c.is_whitespace())
}
}
pub fn repl... |
pub fn solve_v1() -> i32 {
let data = super::load_file("day2.txt");
let mut count = 0;
for line in data.split("\n") {
let parts: Vec<&str> = line.split(" ").map(|s| s.trim()).collect();
assert_eq!(parts.len(), 3, "Invalid input file");
let limits: Vec<i32> = parts[0]
.s... |
pub mod ast;
use self::ast::{Assertion, Atom, Clause, Const, Term, Var};
use lalrpop_util::lalrpop_mod;
use std::collections::HashMap;
use std::fmt::{Display, Formatter};
use std::io::Write;
lalrpop_mod!(pub parser);
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Environment(HashMap<Var, Term>);
pub type Knowledg... |
use clap::{crate_version, App, Arg};
use nix::sched::{clone, CloneFlags};
use nix::sys::signal::Signal;
use nix::sys::wait::waitpid;
use nix::unistd::execvp;
use std::ffi::{CStr, CString};
use std::process;
fn child_func(args: &[&CStr]) -> isize {
execvp(&args[0], &args).expect("exec() failed");
0
}
const STA... |
fn merge(in1: &[i32], in2: &[i32], out: &mut [i32]) {
let (left, right) = out.split_at_mut(in1.len());
left.clone_from_slice(in1);
right.clone_from_slice(in2);
}
// least significant digit radix sort
fn radix_sort(data: &mut [i32]) {
for bit in 0..31 {
// types of small and big is Vec<i32>.
... |
#[doc = "Register `RCC_AXIDIVR` reader"]
pub type R = crate::R<RCC_AXIDIVR_SPEC>;
#[doc = "Register `RCC_AXIDIVR` writer"]
pub type W = crate::W<RCC_AXIDIVR_SPEC>;
#[doc = "Field `AXIDIV` reader - AXIDIV"]
pub type AXIDIV_R = crate::FieldReader;
#[doc = "Field `AXIDIV` writer - AXIDIV"]
pub type AXIDIV_W<'a, REG, const... |
// Generated from vec_mask.rs.tera template. Edit the template, not the generated file.
#[cfg(not(target_arch = "spirv"))]
use core::fmt;
use core::ops::*;
/// A 3-dimensional `u32` vector mask.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
#[repr(C, align(16))]
pub struct BVec3A {
pub x: u32,
pub y: u32,
p... |
//! Graphics helpers
use crate::graphics::bitmap::{BitmapMode, PalletMode};
use crate::graphics::colour::{self, Colour};
/// The colours of a rainbow
const RAINBOW: [Colour; 6] = [
colour::R,
colour::O,
colour::Y,
colour::G,
colour::B,
colour::V,
];
/// Draw a rainbow with the given `thicknes... |
use game_state;
use std::str;
pub fn get_rook_moves(state: &game_state::GameState, piece_coord: Vec<u8>) -> Vec<String> {
let mut can_move_here = true;
let mut allowed_rook_moves: Vec<String> = Vec::new();
//down
let down = (0i8,1i8);
//up
let up = (0i8,-1i8);
//left
let left = (-1i8... |
use std::fs::File;
use std::io::prelude::*;
use std::env;
use std::process;
use std::str;
use std::collections::HashMap;
fn load_file(file_path: &str) -> String {
let mut contents = String::new();
let mut f = File::open(file_path).expect("Unable to open file");
f.read_to_string(&mut contents).expect("ca... |
use cgmath::prelude::ElementWise;
use cgmath::{dot, Array, EuclideanSpace, InnerSpace, Point3, Vector3};
use rand::Rng;
use crate::light::{Color, Light, Ray};
pub type Triangle = [Point3<f64>; 3];
pub struct Plane {
pub id: f64,
pub vertices: Triangle,
pub color: Color,
pub normal: Vector3<f64>,
}
fn is_poi... |
use anyhow::{Error, Result};
use hyper::{Body, Response, StatusCode};
use std::fmt::Display;
use url::Url;
#[derive(Debug)]
pub struct HttpError {
pub status_code: StatusCode,
pub request_url: Url,
pub body: Option<Body>,
}
impl Display for HttpError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) ->... |
use std::path::PathBuf;
#[derive(Clone)]
pub struct Project {
pub directory: PathBuf,
}
|
use log::{LevelFilter, Log, Metadata, Record};
#[allow(dead_code)]
struct Logger {
pub filter: Option<String>,
}
impl Log for Logger {
fn enabled(&self, _: &Metadata) -> bool {
true
}
fn log(&self, record: &Record) {
eprintln!(
"[{}] {}",
record
... |
#[doc = "Register `FDCAN_NBTP` reader"]
pub type R = crate::R<FDCAN_NBTP_SPEC>;
#[doc = "Register `FDCAN_NBTP` writer"]
pub type W = crate::W<FDCAN_NBTP_SPEC>;
#[doc = "Field `TSEG2` reader - Nominal Time segment after sample point"]
pub type TSEG2_R = crate::FieldReader;
#[doc = "Field `TSEG2` writer - Nominal Time se... |
use super::super::prelude::{
HMODULE
};
pub type Module = HMODULE; |
fn main() {}
#[cfg(test)]
mod tests {
#[test]
fn you_can_assert_eq() { assert_eq!(2, 2); }
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.