text stringlengths 8 4.13M |
|---|
extern crate rayon;
use rayon::prelude::*;
fn sum_of_square(input: &[i32]) -> i32 {
input.par_iter()
.map(|&i|i * i)
.sum()
}
fn main() {
let mut v = vec![3,4,2,6,4];
let sum = sum_of_square(&v);
println!("the sum of square:{}",sum);
}
|
// Copyright (c) 2021 Ant Group
//
// SPDX-License-Identifier: Apache-2.0
//
//! Because Tokio has removed UnixIncoming since version 0.3,
//! we define the UnixIncoming and implement the Stream for UnixIncoming.
use std::io;
use std::os::unix::io::{AsRawFd, RawFd};
use std::pin::Pin;
use std::task::{Context, Poll};
... |
extern crate ocl;
extern crate log;
use std::result::Result;
use ocl::{Buffer, MemFlags, ProQue,Error};
use log::info;
static MULTIPLY_SRC: &str = include_str!("kernel/multiply.cl");
pub struct MultiplyKernel
{
proque: ProQue,
source_buffer: Buffer<f32>,
pub result_buffer: Buffer<f32>
}
impl MultiplyKer... |
use ckb_chain_spec::consensus::Consensus;
use ckb_core::block::Block;
use ckb_core::extras::BlockExt;
use ckb_core::header::{BlockNumber, Header};
use ckb_core::transaction::{Capacity, ProposalShortId, Transaction};
use ckb_core::uncle::UncleBlock;
use numext_fixed_hash::H256;
use numext_fixed_uint::U256;
pub trait Ch... |
#[derive(Serialize, Deserialize, Debug, Default, Clone, Copy, PartialEq)]
pub struct IndexValuesMetadata {
/// max value on the "right" side key -> value, key -> value ..
pub max_value_id: u32,
pub avg_join_size: f32,
pub num_values: u64,
pub num_ids: u32,
}
impl IndexValuesMetadata {
pub fn ne... |
use std::fs;
//use std::collections::HashMap;
#[derive(Debug, Clone)]
pub struct MemoryGame {
turns: Vec::<usize>,
}
impl MemoryGame {
pub fn new(starting: &Vec<usize>) -> MemoryGame {
let mut turns = Vec::<usize>::new();
starting.iter().for_each(|&s| turns.push(s));
MemoryGame { turn... |
use bevy::prelude::*;
use crate::{player, asset_loader, theater_outside, GameState, level_collision, cutscene, AppState, follow_text::FollowTextEvent, get_colors, Kid};
use bevy::render::pipeline::PrimitiveTopology;
use serde::Deserialize;
use bevy::reflect::{TypeUuid};
use bevy::render::mesh::Indices;
#[derive(Defaul... |
use std::iter::FromIterator;
use map::{
RadixMap,
Matches as MapMatches,
Keys as MapKeys,
};
use key::Key;
/// A set based on a [Radix tree](https://en.wikipedia.org/wiki/Radix_tree).
///
/// See [`RadixMap`](../map/struct.RadixMap.html) for an in-depth explanation of the workings of this
/// struct, as ... |
extern crate rand;
extern crate ecdh_wrapper;
extern crate snow;
extern crate byteorder;
use std::str;
use std::net::TcpListener;
use std::net::TcpStream;
use std::io::Read;
use std::io::Write;
use byteorder::{ByteOrder, BigEndian};
use rand::os::OsRng;
use snow::Builder;
use snow::params::NoiseParams;
use ecdh_wr... |
use spair::prelude::*;
pub struct Spinner;
impl<C: Component> spair::Render<C> for Spinner {
fn render(self, nodes: spair::Nodes<C>) {
nodes.div(|d| {
d.static_attributes()
.class("loading_spinner_container")
.nodes()
.div(|d| d.static_attributes()... |
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use cosmwasm_std::{CanonicalAddr, StdResult, Storage};
use cosmwasm_storage::{
singleton, singleton_read, Singleton,
};
static KEY_CONFIG: &[u8] = b"config";
#[derive(Default, Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct C... |
use crate::common::*;
#[derive(Debug, PartialEq)]
pub(crate) struct Settings<'src> {
pub(crate) dotenv_load: Option<bool>,
pub(crate) export: bool,
pub(crate) positional_arguments: bool,
pub(crate) shell: Option<setting::Shell<'src>>,
}
impl<'src> Settings<'src> {
pub(c... |
use actix_web::{
HttpResponse,
};
use super::super::{
service,
response,
};
pub fn index() -> HttpResponse {
let (domain_develop_trends, domain_develop_popularities) = &service::develop::index();
response::develop_index::response(domain_develop_trends, domain_develop_popularities)
} |
pub mod graphql;
mod misc;
pub mod ws {
use crate::misc::ExtractUserAgent;
use axum::ws::{Message, WebSocket};
pub async fn sub_(mut socket: WebSocket, ExtractUserAgent(user_agent): ExtractUserAgent) {
println!("`{:?}` connected", user_agent);
if let Some(msg) = socket.recv().await {
... |
//! Tests auto-converted from "sass-spec/spec/non_conformant/errors/import"
#[allow(unused)]
use super::rsass;
mod file;
mod miss;
mod url;
|
use std::io;
fn main() {
println!("Entering a number");
let mut input1 = String::new();
io::stdin().read_line(&mut input1).expect("failed to read from stdin");
let trim = input1.trim();
let fact = match trim.parse::<u32>() {
Ok(fact) => fact,
Err(_) => 0,
};
println!("Th... |
//! This example demonstrates usage of [`ron_to_table::to_string`].
fn main() {
let scene = ron::from_str(
r#"
Scene(
materials: {
"metal": (reflectivity: 1.0),
"plastic": (reflectivity: 0.5),
},
entities: [
(name: ... |
//! Module containing definitions for BGP
use crate::{AsId, Prefix, RouterId};
/// Bgo Route
/// The following attributes are omitted
/// - ORIGIN: assumed to be always set to IGP
/// - ATOMIC_AGGREGATE: not used
/// - AGGREGATOR: not used
#[derive(Debug, Clone)]
pub struct BgpRoute {
pub prefix: Prefix,
pub ... |
extern crate kernel32;
extern crate user32;
extern crate winapi;
mod utils;
use utils::*;
use winapi::*;
use user32::*;
use kernel32::*;
use std::ptr::{null, null_mut};
use std::mem;
//ALTERNATIVE TO CALLING AN EXTERNAL FUNCTION
/*#[link(name = "d2d1")]
extern "system" {
pub fn D2D1CreateFactory(
factor... |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_lambda::model::Runtime;
use aws_sdk_lambda::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
st... |
use crate::{IntoSlice, IntoSliceFrom, IntoSliceTo, OwningSlice, OwningSliceFrom, OwningSliceTo};
macro_rules! sanity {
($buf:expr) => {{
assert_eq!(*$buf.into_slice(0u8, 0), []);
assert_eq!(*$buf.into_slice(0u8, 1), [0]);
assert_eq!(*$buf.into_slice(0u8, 2), [0, 1]);
assert_eq!(*$bu... |
use crate::atomicmin::AtomicMin;
use crate::Deadline;
use crate::PngError;
use crate::PngResult;
pub use cloudflare_zlib::is_supported;
use cloudflare_zlib::*;
impl From<ZError> for PngError {
fn from(err: ZError) -> Self {
match err {
ZError::DeflatedDataTooLarge(n) => PngError::DeflatedDataTo... |
use crate::dinfo;
use pollster::block_on;
use winit::event::{Event, VirtualKeyCode};
use winit::window::Window;
use winit_input_helper::WinitInputHelper;
use crate::config::GlobalConfig;
use crate::NOW;
/// Global constant resources
/// Different worlds will share these
pub struct Resources {
//
// GLOBAL
... |
//! Request specific implementations
use serde::{Deserialize, Serialize};
#[derive(Debug, PartialEq, Deserialize, Serialize)]
/// The new page request
pub struct CreateStepPage {
/// describe the number of steps to complete
pub steps: u64,
}
#[derive(Debug, PartialEq, Deserialize, Serialize)]
/// Update steps... |
pub mod editors;
pub mod paths;
use std::io;
use crate::unity;
use thiserror::Error;
//
#[derive(Error, Debug)]
pub enum UvmHubError {
#[error("unity hub config: '{0}' is missing")]
ConfigNotFound(String),
#[error("Unity Hub config directory missing")]
ConfigDirectoryNotFound,
#[error("failed... |
use std::collections::HashMap;
use serde::ser::{SerializeStruct, Error};
use serde::Serialize;
use crate::{Element, Uuid, Number};
use crate::Value;
use crate::error::TychoError;
use crate::serde::ser::TychoSerializer;
use crate::serde::ser::seq::{SeqSerializer, SeqSerializerType};
use crate::types::ident::ValueIdent... |
#![allow(dead_code)]
#![feature(rustc_private)] // decl_storage extra genesis bug
#![cfg_attr(not(feature = "std"), no_std)]
use frame_support::{decl_error, decl_event, decl_module, decl_storage, dispatch, Parameter};
use rstd::prelude::*;
use sp_arithmetic::traits::{CheckedAdd, One, SimpleArithmetic};
use sp_runtime:... |
extern crate rand;
extern crate num_bigint;
use num_bigint::{BigInt, RandBigInt};
fn modpow(b: &BigInt, e: &BigInt, m: &BigInt) -> BigInt {
b.modpow(&e, &m)
}
pub fn signature(h: &BigInt) -> bool {
let p = BigInt::parse_bytes(b"255211775190703847597530955573826158579", 10).unwrap();
let q = BigInt::parse... |
/// Tiny crate to verify message signature and format
use anyhow::Result as Fallible;
use anyhow::{format_err, Context};
use bytes::buf::BufExt;
use bytes::Bytes;
use serde::Deserialize;
use serde_json;
use std::fs::{read_dir, File};
use pgp::composed::message::Message;
use pgp::composed::signed_key::SignedPublicKey;
... |
//! Shortest Job First
use std::cmp::Reverse;
use keyed_priority_queue::KeyedPriorityQueue;
use crate::scheduling::{Os, PId, Scheduler};
/// Process which have the shortest burst time are scheduled first.
/// If two processes have the same bust time then FCFS is used to break the tie.
/// It is a non-preemptive sche... |
fn main() {
print_number(34);
print_sum(32, 35);
add_one(45);
// without type inference
let f: fn(i32) -> i32 = plus_one;
let six = f(5);
print_number(six);
}
fn print_number(x: i32) {
println!("x is: {}", x);
}
fn print_sum(x: i32, y: i32) {
println!("sum is: {}", x+y);
}
fn a... |
use wasm_bindgen;
use wasm_bindgen::prelude::*;
use console_error_panic_hook;
use virtual_dom_rs::prelude::*;
use web_sys;
use web_sys::Element;
use isomorphic_app;
use isomorphic_app::App;
use isomorphic_app::VirtualNode;
#[wasm_bindgen]
pub struct Client {
app: App,
dom_updater: DomUpdater,
}
// Expose g... |
#[doc = "Reader of register INTR_CAUSE_MED"]
pub type R = crate::R<u32, super::INTR_CAUSE_MED>;
#[doc = "Reader of field `SOF_INTR`"]
pub type SOF_INTR_R = crate::R<bool, bool>;
#[doc = "Reader of field `BUS_RESET_INTR`"]
pub type BUS_RESET_INTR_R = crate::R<bool, bool>;
#[doc = "Reader of field `EP0_INTR`"]
pub type E... |
mod list;
mod read;
pub use self::list::run as list;
pub use self::read::run as read;
|
fn print_h()
{
println!("hello");
}
fn main() {
let mut y=0;
let mut z=0;
let x=y+z;
println!("{}",x);
let z=print_h();
z;
}
|
use std::iter::FromIterator;
fn parse_input2(inp: &str) -> Vec<u8> {
inp.trim()
.chars()
.map(|c| {
if (c as u32) < 256 {
c as u8
} else {
panic!{"Only expecting ascii symbols"}
}
})
.collect()
}
fn parse_input1(in... |
#[doc = "Register `GTPR` reader"]
pub type R = crate::R<GTPR_SPEC>;
#[doc = "Register `GTPR` writer"]
pub type W = crate::W<GTPR_SPEC>;
#[doc = "Field `PSC` reader - Prescaler value"]
pub type PSC_R = crate::FieldReader;
#[doc = "Field `PSC` writer - Prescaler value"]
pub type PSC_W<'a, REG, const O: u8> = crate::Field... |
use super::context::Context;
use super::graph::HandoffData;
/// Represents a compiled subgraph. Used internally by [Dataflow] to erase the input/output [Handoff] types.
pub(crate) trait Subgraph {
// TODO: pass in some scheduling info?
fn run(&mut self, context: &mut Context, handoffs: &mut Vec<HandoffData>);
... |
use crate::bus::Bus;
use crate::devnode;
use crate::devtree::DeviceIdent;
use crate::driver::Driver;
use std::thread::{spawn, JoinHandle};
use twz::device::{BusType, Device, DEVICE_ID_SERIAL};
pub struct Instance {
writethread: Option<JoinHandle<()>>,
readthread: Option<JoinHandle<()>>,
nodes: Vec<devnode::DeviceNo... |
use tokio::stream::StreamExt;
use tokio_util::codec::{Framed, BytesCodec};
use futures::sink::SinkExt;
use tokio::net::TcpListener;
#[tokio::main]
async fn main() -> std::io::Result<()> {
let mut listener = TcpListener::bind("127.0.0.1:6142").await?;
println!("Listening on port 6142 ..");
loop {
l... |
pub mod chain;
pub mod block; |
use crate::block_status::BlockStatus;
use crate::relayer::compact_block_verifier::CompactBlockVerifier;
use crate::relayer::error::{Error, Ignored, Internal, Misbehavior};
use crate::relayer::{ReconstructionError, Relayer};
use ckb_logger::{self, debug_target, warn};
use ckb_network::{CKBProtocolContext, PeerIndex};
us... |
#![cfg_attr(not(feature = "std"), no_std)]
#![forbid(unsafe_code)]
//! An efficient and customizable parser for the
//! [`.cnf` (Conjunctive Normal Form)][cnf-format]
//! file format used by [SAT solvers][sat-solving].
//!
//! [sat-solving]: https://en.wikipedia.org/wiki/Boolean_satisfiability_problem
//! [cnf-format]... |
mod compare;
mod store;
use core::fmt;
use core::marker::PhantomData;
use core::mem::ManuallyDrop;
use core::ptr;
use core::sync::atomic::Ordering;
use conquer_pointer::{AtomicMarkedPtr, MarkedNonNull, MarkedPtr, Null};
use crate::traits::{Protect, Reclaim};
use crate::{Maybe, NotEqual, Owned, Protected, Unlinked, U... |
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate riirc;
fn main() {
env_logger::Builder::from_default_env()
.default_format_timestamp(false)
.init();
// TODO use structopt or something like that for this
let mut args = ::std::env::args();
if let Some(next) = args.n... |
use lazy_static::lazy_static;
use scan_fmt::scan_fmt;
use std::str::FromStr;
type Registers = [usize; 6];
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
enum Opcode {
Addr,
Addi,
Mulr,
Muli,
Banr,
Bani,
Borr,
Bori,
Setr,
Seti,
Gtir,
Gtri,
Gtrr,
Eqir,
Eqri,
... |
#[doc = "Register `RGSR` reader"]
pub type R = crate::R<RGSR_SPEC>;
#[doc = "Field `OF` reader - Trigger event overrun flag The flag is set when a trigger event occurs on DMA request generator channel x, while the DMA request generator counter value is lower than GNBREQ. The flag is cleared by writing 1 to the correspo... |
// This file is part of rdma-core. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/rdma-core/master/COPYRIGHT. No part of rdma-core, including this file, may be copied, modified, propagated, or distributed ... |
//! Deals with configuring the I/O APIC.
use super::super::memory::map_page_at;
use super::IRQ_INTERRUPT_NUMS;
use core::fmt;
use memory::{PhysicalAddress, VirtualAddress, NO_CACHE, READABLE, WRITABLE};
use x86_64::instructions::port::outb;
/// The physical base address of the memory mapped I/O APIC.
const IO_APIC_BA... |
use serde::Deserialize;
use serde::Serialize;
#[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize)]
pub struct Timestamp {
pub epoch: u32,
pub unix: u32,
pub human: String,
}
|
#[doc = "Register `EXTI_HWCFGR4` reader"]
pub type R = crate::R<EXTI_HWCFGR4_SPEC>;
#[doc = "Field `EVENT_TRG` reader - EVENT_TRG"]
pub type EVENT_TRG_R = crate::FieldReader<u32>;
impl R {
#[doc = "Bits 0:31 - EVENT_TRG"]
#[inline(always)]
pub fn event_trg(&self) -> EVENT_TRG_R {
EVENT_TRG_R::new(se... |
use tokio::signal;
pub(crate) fn raise_fd_limit() {
match std::panic::catch_unwind(fdlimit::raise_fd_limit) {
Ok(Some(limit)) => {
tracing::debug!("Increase file limit from soft to hard (limit is {limit})")
}
Ok(None) => tracing::debug!("Failed to increase file limit"),
... |
use glium::texture::Texture2d;
use glium::Display;
use image::{ImageBuffer, Rgb};
use support;
use noise::{Perlin, Seedable};
use noise::utils::*;
use nalgebra::clamp;
use scarlet::colors::hslcolor::HSLColor;
use scarlet::color::{RGBColor, Color};
use scarlet::illuminants::Illuminant;
// Really bad code
pub fn gen_pla... |
use crate::{command::Command, define_node_command, get_set_swap, scene::commands::SceneContext};
use rg3d::{
core::pool::Handle,
scene::{base::LevelOfDetail, base::LodGroup, graph::Graph, node::Node},
};
#[derive(Debug)]
pub struct AddLodGroupLevelCommand {
handle: Handle<Node>,
level: LevelOfDetail,
}... |
use crate::{
cmd::multisig::Artifact,
cmd::*,
keypair::{Network, PublicKey},
result::Result,
traits::{ToJson, TxnEnvelope},
};
use helium_api::vars;
use std::{convert::TryInto, str::FromStr};
#[derive(Debug, StructOpt)]
/// Commands for chain variables
pub enum Cmd {
Current(Current),
Creat... |
use log::{debug, error, info, trace, warn};
use edocore::math::vector::{UVector3};
use crate::utils::rle_array::RLEArray;
pub struct VoxelGrid {
//pub voxels: [[[u8; 512]; 512]; 512]
pub voxels: RLEArray<u8>,
pub size: UVector3,
}
impl VoxelGrid {
pub fn new(size: UVector3) -> VoxelGrid {
let... |
use std::convert::TryFrom;
use crate::{Element, Number, Value};
macro_rules! number_to {
($id: ident, $type: ty) => {
impl TryFrom<Number> for $type {
type Error = ();
fn try_from(value: Number) -> Result<Self, Self::Error> {
if let Number::$id(x) = value { return ... |
/**
*
* If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
* Find the sum of all the multiples of 3 or 5 below 1000.
*/
pub fn execute() {
let sequence = 0..1000_i32;
let value : i32 = sequence
.filter(|v| v % 3 == 0 ||... |
use super::Filter;
pub trait WrapSealed<F: Filter> {
type Wrapped: Filter;
fn wrap(&self, filter: F) -> Self::Wrapped;
}
impl<'a, T, F> WrapSealed<F> for &'a T
where
T: WrapSealed<F>,
F: Filter,
{
type Wrapped = T::Wrapped;
fn wrap(&self, filter: F) -> Self::Wrapped {
(*self).wrap(fil... |
use std::collections::HashMap;
use regex::Regex;
pub mod input_files
{
fn build_regex(s : &str) -> regex::Regex
{
regex::Regex::new(s).unwrap()
}
fn build_regex_ci(s : &str) -> regex::Regex
{
regex::Regex::new(&format!("(?i){s}")[..]).unwrap()
}
pub struct Lvo
{
... |
extern crate cfg_if;
extern crate wasm_bindgen;
extern crate chip8;
mod utils;
use cfg_if::cfg_if;
use wasm_bindgen::prelude::*;
use chip8::cpu::Cpu;
cfg_if! {
// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
if #[cfg(feature = "wee_alloc")] {
extern crate w... |
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(not(feature = "std"))]
mod std {
pub use core::*;
}
use std::any::{Any as StdAny, TypeId, type_name};
use std::fmt::{self, Debug, Display};
#[cfg(feature = "std")]
use std::{error::Error, rc::Rc, sync::Arc};
// ++++++++++++++++++++ Any ++++++++++++++++++++
pub t... |
extern crate reqwest;
mod token;
mod track;
mod track_types;
use reqwest::{
Client,
};
fn main(
) {
let client = Client::new();
let token = token::retrieve_access_token(&client)
.expect("Error in access token")
.access_token;
let track_info = track::get_track(&client, &token[..]... |
use diesel::prelude::*;
use super::db_connection::*;
use crate::db::models::AuthInfoEntity;
use crate::db::models::AuthInfo;
use crate::schema::auth_infos::dsl::*;
pub fn fetch_auth_info_by_user_id(database_url: &String, uid: i32) -> Option<AuthInfoEntity> {
use crate::schema::auth_infos::dsl::*;
let connection ... |
pub(crate) mod dir;
pub(crate) mod fadvise;
pub(crate) mod file;
use crate::dir::SeekLoc;
use std::io::Result;
impl SeekLoc {
pub unsafe fn from_raw(loc: i64) -> Result<Self> {
let loc = loc.into();
Ok(Self(loc))
}
}
|
use srt::SrtSocketBuilder;
use futures::try_join;
#[tokio::test]
async fn rendezvous() {
let a = SrtSocketBuilder::new_rendezvous("127.0.0.1:5000")
.local_port(5001)
.connect();
let b = SrtSocketBuilder::new_rendezvous("127.0.0.1:5001")
.local_port(5000)
.connect();
let _... |
use std::sync::Arc;
use std::path::Path;
use super::TaskResult;
use worker::state::State;
use worker::graph::TaskRef;
use worker::data::{Data, DataBuilder};
use futures::{future, Future};
/// Task that merge all input blobs and merge them into one blob
pub fn task_concat(_state: &mut State, task_ref: TaskRef) -> Task... |
use ifstructs::ifreq;
use mio::{unix::SourceFd, Events, Interest, Poll, Token};
use nix::libc;
use pnet::packet::ipv4::Ipv4Packet;
use std::{
fs::{File, OpenOptions},
io::{self, prelude::*},
net::{Ipv4Addr, SocketAddr, UdpSocket},
os::unix::io::{AsRawFd, RawFd},
};
const TUNSETIFF: libc::c_ulong = 0x40... |
// Copyright (c) 2018 The rust-bitcoin developers
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, m... |
use libc::{c_char, c_int};
use std::ffi::CStr;
#[no_mangle]
pub extern "C" fn solve(line: *const c_char, solution: *mut c_int) -> c_int {
if line.is_null() || solution.is_null() {
return 1;
}
let c_str = unsafe { CStr::from_ptr(line) };
let r_str = match c_str.to_str() {
Ok(s) => s,
Err(e) => {
... |
//! This example is a quick and dirty example of
//! what someone might want to do with a JS token stream.
//! Essentially this is reading in the file and writing it out
//! with no comments. It successfully stripped all of the comments
//! out of a webpack output file though it cannot handle object literals
//! very w... |
// use rayon::prelude::*;
fn elevation_at(i: usize, w: usize, h: usize, elv: &[u8]) -> [f32; 4] {
let row = i / w;
let col = i % w;
if row == 0 || row == h - 1 || col == 0 || col == w - 1 {
return [0.0, 0.0, 0.0, 0.0];
}
return [
(elv[i] as f32) / 16.0,
(elv[i + w + (i / w % 2)] as f32) / 16.0,... |
use std::fmt::{self,Debug};
use std::io::{Write, Read};
use std::collections::{HashSet, HashMap};
use std::fs::File;
use std::cmp::Ordering::{Less, Equal, Greater};
extern crate select;
#[macro_use] extern crate serde_json;
use select::predicate::{Predicate, Attr, Class as HTMLClass, Name, And};
const NBSP:char = '\u... |
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::MyWorld;
use cucumber::{Steps, StepsBuilder};
use starcoin_config::{ChainNetwork, NodeConfig, StarcoinOpt};
use std::path::PathBuf;
use std::sync::Arc;
pub fn steps() -> Steps<MyWorld> {
let mut builder: StepsBuilder<... |
pub fn image(grid: &[Vec<u8>], iteration: u8) {
let mut imgbuf = image::RgbImage::new(129, 129);
for (i, line) in grid.iter().enumerate() {
for (j, val) in line.iter().enumerate() {
imgbuf.put_pixel(j as u32, i as u32, image::Rgb([*val, *val, *val]));
}
}
imgbuf.save(&format!... |
use super::Mesh;
pub struct Update<'a> {
pub mesh: Option<Mesh>,
pub swap_desc: Option<&'a wgpu::SwapChainDescriptor>,
}
impl<'a> Default for Update<'a> {
fn default() -> Self {
Update {
mesh: None,
swap_desc: None,
}
}
}
|
extern crate reversi;
use reversi::game::*;
use reversi::cpu;
fn main() {
let cpu_setting = cpu::Setting::new(5, 5, 50, 20, 1, 7, 50);
let setting = Setting {
black : PlayerType::Human,
white : PlayerType::Computer(cpu_setting),
boardsize : (8, 8),
};
start(&setting, true)... |
#![feature(proc_macro, wasm_custom_section, wasm_import_module)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_namespace = Math)]
fn random() -> f64;
#[wasm_bindgen(js_namespace = console)]
fn log(msg: &str);
#[wasm_bindgen(js_namespace ... |
//vim: tw=80
use std::pin::Pin;
use std::task::Poll;
use futures::{Future, FutureExt, TryFutureExt, StreamExt, future, stream};
use futures::channel::oneshot;
#[cfg(feature = "tokio")]
use std::rc::Rc;
use tokio;
use tokio::runtime::current_thread;
use futures_locks::*;
// When an exclusively owned but not yet polle... |
// Primitive str = Immutable fixed-length string somewhere in memory
// String = Growable, heap-allocated data structure - Use when you need to modify or own string data
pub fn run() {
// hello is not change. This string has the fixed length
let hello = "I am going to School in the morning ";
println!("{}", he... |
use std::{any::{Any, TypeId}, collections::HashMap, fmt::Debug, rc::Rc};
use serde::*;
use uuid::Uuid;
use std::fmt;
use crate::element::*;
use crate::entity::*;
use crate::deserialize_context::*;
#[derive(Debug)]
pub enum SceneSerdeError {
CycleError(String),
MissingElementError(String),
SerdeError(serde... |
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::collections::HashMap;
fn calculate_len(object_dependency_len : &mut Vec<i32>, object_dependency : &Vec<i32>, idx : usize) {
let mut i = idx as i32;
let mut stack : Vec<i32> = Vec::new();
while object_dependency[i as usize] >= 0 {
stack.... |
use super::Result;
use crate::model::Wishlist;
pub trait WishlistService: Send + Sync {
fn get_last_wishlist(&self) -> Result<Wishlist>;
}
|
use Renderable;
use context::Context;
use filters;
use error::Result;
pub struct Template {
pub elements: Vec<Box<Renderable>>,
}
impl Renderable for Template {
fn render(&self, context: &mut Context) -> Result<Option<String>> {
maybe_add_default_filters(context);
maybe_add_extra_filters(cont... |
// ===============================================================================
// Authors: AFRL/RQQA
// Organization: Air Force Research Laboratory, Aerospace Systems Directorate, Power and Control Division
//
// Copyright (c) 2017 Government of the United State of America, as represented by
// the Secretary of th... |
use super::{Object, TaggedValue};
impl std::fmt::Debug for Object {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", self)
}
}
impl std::fmt::Display for Object {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
use TaggedValue::*;
ma... |
use std::fmt;
use crate::translations::translations::both_translation;
use crate::Language;
/// Enum representing the possible observed values of IP protocol version.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IpVersion {
/// Internet Protocol version 4
IPv4,
/// Internet Protocol version 6
... |
#![ allow (unused_parens) ]
use cairo;
use gio;
use glib;
use gtk;
use gio::prelude::*;
use gtk::prelude::*;
use gtk::traits::SettingsExt;
use std::cell::RefCell;
use std::env;
use std::io;
use std::rc::Rc;
use std::time::Duration;
use nono::*;
const BORDER_SIZE: f64 = 20.0;
const CELL_SIZE: f64 = 20.0;
const THIC... |
#[cfg(all(unix, not(target_os = "macos")))]
mod common;
#[cfg(all(unix, not(target_os = "macos")))]
mod tests {
const TEST_PLATFORM: &str = "unix";
use super::common::*;
use serial_test::serial;
use webbrowser::Browser;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial]
... |
//! Transaction fees.
use std::collections::HashMap;
use exonum::crypto::PublicKey;
use exonum::storage::{Fork, Snapshot};
use currency::assets;
use currency::assets::{AssetBundle, MetaAsset, TradeAsset};
use currency::configuration::Configuration;
use currency::error::Error;
use currency::wallet;
use currency::wall... |
#![feature(inclusive_range_syntax)]
fn score_byte(c: u8) -> Option<u64> {
let c = if b'A' <= c && c <= b'Z' {
c - b'A' + b'a'
} else {
c
};
match c {
b'e' => Some(5),
b'a' | b't' => Some(4),
b'h' | b'i' | b'n' | b'o' | b'r' | b's' | b' ' => Some(3),
b'b'... |
use std::env;
use std::fs;
fn elem(x : i32, y : i32) -> char
{
let map = [['0', '0', '1', '0', '0'],
['0', '2', '3', '4', '0'],
['5', '6', '7', '8', '9'],
['0', 'A', 'B', 'C', '0'],
['0', '0', 'D', '0', '0']];
map[y as usize][x as usize]
}
fn main() ... |
#[test]
fn test_parse_pull_request_response() {}
|
//! Error facilities
use std::fmt;
/// Core error type for all errors possible from tame-gcs
#[derive(thiserror::Error, Debug, PartialEq)]
pub enum Error {
#[error("Expected {min}-{max} characters, found {len}")]
InvalidCharacterCount { len: usize, min: usize, max: usize },
#[error("Expected {min}-{max} b... |
// #![feature(rustc_private)]
#[macro_use]
extern crate actix_web;
mod badge_routes;
mod utils;
use actix_files::Files;
use actix_web::{
http::{header, StatusCode},
middleware, web, App, HttpResponse, HttpServer, Responder,
};
use badgeland::Badge;
use dotenv::dotenv;
use env_logger::Env;
use listenfd::Liste... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - SysTick control and status register"]
pub csr: CSR,
#[doc = "0x04 - SysTick reload value register"]
pub rvr: RVR,
#[doc = "0x08 - SysTick current value register"]
pub cvr: CVR,
#[doc = "0x0c - SysTick calibratio... |
#![feature(test)]
extern crate scalable_bloom_filter;
extern crate test;
use scalable_bloom_filter::ScalableBloomFilter;
use test::Bencher;
#[bench]
fn insert_n1000_p01(b: &mut Bencher) {
let mut filter = ScalableBloomFilter::new(1000, 0.1);
let mut i = 0;
b.iter(|| {
filter.insert(&i);
i ... |
extern crate native;
extern crate termkey;
#[start]
fn start(argc: int, argv: *const *const u8) -> int {
native::start(argc, argv, main)
}
fn main()
{
let mouse = 0i; // TODO parse arg -m, default 1000
let mouse_proto = 0i; // TODO parse arg -p (no default)
let format = termkey::c::TERMKEY_FORMAT_VIM... |
std_prelude!();
use crate::prelude::*;
#[test]
fn true_accept() {
use crate::preds::True;
assert_eq!(True::pet(()).expect("Must be Some(..)").value(), ());
assert_eq!(True::petref(&()).expect("Must be Some(..)").value(), &());
}
#[test]
fn false_reject() {
use crate::preds::False;
assert_eq!(Fal... |
mod graphql;
mod ops;
use crate::infrastructure::{config, graphql as gql, repositories};
use actix_web::{dev::Server, http, middleware, web, App, HttpServer};
pub fn run(
listener: std::net::TcpListener,
config: config::Settings,
db_pool: repositories::PostgresPool,
) -> std::result::Result<Server, std::i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.