file_name large_stringlengths 4 69 | prefix large_stringlengths 0 26.7k | suffix large_stringlengths 0 24.8k | middle large_stringlengths 0 2.12k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
index.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or | // (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of t... | random_line_split | |
test_result.rs | mod checked {
#[derive(Debug)]
pub enum MathError {
DivisionByZero,
NonPositiveLogarithm,
NegativeSquareRoot,
}
pub type MathResult = Result<f64, MathError>;
pub fn div(x: f64, y: f64) -> MathResult {
if y == 0.0 {
Err(MathError::DivisionByZero)
} els... | Ok(sqrt) => sqrt,
},
},
}
}
fn main() {
println!("{}", op(1.0, 10.0));
} | Ok(ln) => match checked::sqrt(ln) {
Err(why) => panic!("{:?}", why), | random_line_split |
test_result.rs | mod checked {
#[derive(Debug)]
pub enum MathError {
DivisionByZero,
NonPositiveLogarithm,
NegativeSquareRoot,
}
pub type MathResult = Result<f64, MathError>;
pub fn div(x: f64, y: f64) -> MathResult |
pub fn sqrt(x: f64) -> MathResult {
if x < 0.0 {
Err(MathError::NegativeSquareRoot)
} else {
Ok(x.sqrt())
}
}
pub fn ln(x: f64) -> MathResult {
if x <= 0.0 {
Err(MathError::NonPositiveLogarithm)
} else {
Ok(x.ln())
... | {
if y == 0.0 {
Err(MathError::DivisionByZero)
} else {
Ok(x / y)
}
} | identifier_body |
test_result.rs | mod checked {
#[derive(Debug)]
pub enum MathError {
DivisionByZero,
NonPositiveLogarithm,
NegativeSquareRoot,
}
pub type MathResult = Result<f64, MathError>;
pub fn div(x: f64, y: f64) -> MathResult {
if y == 0.0 {
Err(MathError::DivisionByZero)
} els... | () {
println!("{}", op(1.0, 10.0));
}
| main | identifier_name |
client.rs | use hyper::{body::Body, Client};
use opentelemetry::{
global,
sdk::export::trace::stdout,
sdk::trace as sdktrace,
trace::{TraceContextExt, Tracer},
Context, KeyValue,
};
use opentelemetry_aws::XrayPropagator;
use opentelemetry_http::HeaderInjector;
fn init_tracer() -> sdktrace::Tracer |
#[tokio::main]
async fn main() -> std::result::Result<(), Box<dyn std::error::Error + Send + Sync +'static>> {
let _tracer = init_tracer();
let client = Client::new();
let span = global::tracer("example/client").start("say hello");
let cx = Context::current_with_span(span);
let mut req = hyper::... | {
global::set_text_map_propagator(XrayPropagator::new());
// Install stdout exporter pipeline to be able to retrieve the collected spans.
// For the demonstration, use `Sampler::AlwaysOn` sampler to sample all traces. In a production
// application, use `Sampler::ParentBased` or `Sampler::TraceIdRatioB... | identifier_body |
client.rs | use hyper::{body::Body, Client};
use opentelemetry::{
global,
sdk::export::trace::stdout,
sdk::trace as sdktrace,
trace::{TraceContextExt, Tracer},
Context, KeyValue,
};
use opentelemetry_aws::XrayPropagator;
use opentelemetry_http::HeaderInjector;
fn | () -> sdktrace::Tracer {
global::set_text_map_propagator(XrayPropagator::new());
// Install stdout exporter pipeline to be able to retrieve the collected spans.
// For the demonstration, use `Sampler::AlwaysOn` sampler to sample all traces. In a production
// application, use `Sampler::ParentBased` or ... | init_tracer | identifier_name |
client.rs | use hyper::{body::Body, Client};
use opentelemetry::{
global,
sdk::export::trace::stdout,
sdk::trace as sdktrace, | trace::{TraceContextExt, Tracer},
Context, KeyValue,
};
use opentelemetry_aws::XrayPropagator;
use opentelemetry_http::HeaderInjector;
fn init_tracer() -> sdktrace::Tracer {
global::set_text_map_propagator(XrayPropagator::new());
// Install stdout exporter pipeline to be able to retrieve the collected... | random_line_split | |
builder.rs | /* 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 https://mozilla.org/MPL/2.0/. */
//! Helper module to build up a selector safely and efficiently.
//!
//! Our selector representation is designed ... | Component::Class(..) |
Component::AttributeInNoNamespace {.. } |
Component::AttributeInNoNamespaceExists {.. } |
Component::AttributeOther(..) |
Component::FirstChild |
Component::LastChild |
Component::OnlyChild |
Component::Ro... | specificity.id_selectors += 1;
},
| conditional_block |
builder.rs | /* 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 https://mozilla.org/MPL/2.0/. */
//! Helper module to build up a selector safely and efficiently.
//!
//! Our selector representation is designed ... | (iter: slice::Iter<Component<Impl>>) -> Specificity
where
Impl: SelectorImpl,
{
fn simple_selector_specificity<Impl>(
simple_selector: &Component<Impl>,
specificity: &mut Specificity,
) where
Impl: SelectorImpl,
{
match *simple_selector {
Component::Combinator... | x_selector_specificity<Impl> | identifier_name |
builder.rs | /* 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 https://mozilla.org/MPL/2.0/. */
//! Helper module to build up a selector safely and efficiently.
//!
//! Our selector representation is designed ... | //! * We store the top-level compound selectors from right to left, i.e. in
//! matching order.
//! * We store the simple selectors for each combinator from left to right, so
//! that we match the cheaper simple selectors first.
//!
//! Meeting all these constraints without extra memmove traffic during parsing
//! ... | //! as Component instances. | random_line_split |
xrwebglsubimage.rs | /* 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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::XRWebGLSubImageBinding::XRWebGLSubImageBinding::XRWebGLSubImageMetho... |
/// https://immersive-web.github.io/layers/#dom-xrwebglsubimage-imageindex
fn GetImageIndex(&self) -> Option<u32> {
self.image_index
}
/// https://immersive-web.github.io/layers/#dom-xrwebglsubimage-texturewidth
fn TextureWidth(&self) -> u32 {
self.size.width
}
/// https:... | {
self.depth_stencil_texture.as_deref().map(DomRoot::from_ref)
} | identifier_body |
xrwebglsubimage.rs | /* 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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::XRWebGLSubImageBinding::XRWebGLSubImageBinding::XRWebGLSubImageMetho... | (&self) -> u32 {
self.size.width
}
/// https://immersive-web.github.io/layers/#dom-xrwebglsubimage-textureheight
fn TextureHeight(&self) -> u32 {
self.size.height
}
}
| TextureWidth | identifier_name |
xrwebglsubimage.rs | /* 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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::XRWebGLSubImageBinding::XRWebGLSubImageBinding::XRWebGLSubImageMetho... | /// https://immersive-web.github.io/layers/#dom-xrwebglsubimage-texturewidth
fn TextureWidth(&self) -> u32 {
self.size.width
}
/// https://immersive-web.github.io/layers/#dom-xrwebglsubimage-textureheight
fn TextureHeight(&self) -> u32 {
self.size.height
}
} | random_line_split | |
font.rs | // Copyright (c) 2016-2018 Bruce Stenning. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of co... | else {
println!("No char {} found", c);
}
i += 1;
}
}
}
// Output the handle associated with the font's image, for debug purposes
impl fmt::Debug for Font {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self.texture)
}
}
| {
let (il, it, ir, ib) = self.char_coords[&c];
let t = vec![
Vec2 { x: il, y: it },
Vec2 { x: ir, y: it },
Vec2 { x: ir, y: ib },
Vec2 { x: il, y: ib },
];
let i1 = self.thre... | conditional_block |
font.rs | // Copyright (c) 2016-2018 Bruce Stenning. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of co... | Vec2 { x: ir, y: it },
Vec2 { x: ir, y: ib },
Vec2 { x: il, y: ib },
];
let i1 = self.thread_data.add_vertex_st_f2f2(&v[0], &t[0]);
let i2 = self.thread_data.add_vertex_st_f2f2(&v[1], &t[1]);
let... | if self.char_coords.contains_key(&c) {
let (il, it, ir, ib) = self.char_coords[&c];
let t = vec![
Vec2 { x: il, y: it }, | random_line_split |
font.rs | // Copyright (c) 2016-2018 Bruce Stenning. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of co... |
}
| {
write!(f, "{:?}", self.texture)
} | identifier_body |
font.rs | // Copyright (c) 2016-2018 Bruce Stenning. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of co... | (&mut self, renderer: &Box<Renderer>, resource_manager: &Arc<Mutex<Box<ResourceManager>>>) {
if self.shader.check_for_rebuild(
None,
renderer,
resource_manager,
)
{
self.reconfigure_shaders();
}
// Turn off shader warnings until th... | check_for_shader_rebuild | identifier_name |
dns_resolver.rs | //! Replacement of service's DNS resolver
use std::{
io::{self, ErrorKind},
net::SocketAddr,
};
use async_trait::async_trait;
use futures::future;
use log::{debug, trace};
use trust_dns_resolver::proto::{
op::{Message, Query},
rr::{DNSClass, Name, RData, RecordType},
};
use shadowsocks::{config::Mode... | {
let mut vaddr = Vec::new();
for record in res.answers() {
match *record.rdata() {
RData::A(addr) => vaddr.push(SocketAddr::new(addr.into(), port)),
RData::AAAA(addr) => vaddr.push(SocketAddr::new(addr.into(), port)),
ref rdata => {
trace!("skipped rd... | identifier_body | |
dns_resolver.rs | //! Replacement of service's DNS resolver
use std::{
io::{self, ErrorKind},
net::SocketAddr,
};
use async_trait::async_trait;
use futures::future;
use log::{debug, trace};
use trust_dns_resolver::proto::{
op::{Message, Query},
rr::{DNSClass, Name, RData, RecordType},
};
use shadowsocks::{config::Mode... | }
impl DnsResolver {
pub fn new(ns: NameServerAddr) -> DnsResolver {
DnsResolver {
ns,
client_cache: DnsClientCache::new(5),
mode: Mode::UdpOnly,
ipv6_first: false,
connect_opts: ConnectOpts::default(),
attempts: 2,
}
}
... | mode: Mode,
ipv6_first: bool,
connect_opts: ConnectOpts,
attempts: usize, | random_line_split |
dns_resolver.rs | //! Replacement of service's DNS resolver
use std::{
io::{self, ErrorKind},
net::SocketAddr,
};
use async_trait::async_trait;
use futures::future;
use log::{debug, trace};
use trust_dns_resolver::proto::{
op::{Message, Query},
rr::{DNSClass, Name, RData, RecordType},
};
use shadowsocks::{config::Mode... | (ns: NameServerAddr) -> DnsResolver {
DnsResolver {
ns,
client_cache: DnsClientCache::new(5),
mode: Mode::UdpOnly,
ipv6_first: false,
connect_opts: ConnectOpts::default(),
attempts: 2,
}
}
pub fn set_mode(&mut self, mode: M... | new | identifier_name |
runtime.rs | // use std::ffi::CString;
// use std::io;
// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::str::FromStr;
use std::sync::Arc;
use std::time::{Duration, Instant};
use trust_dns_client::op::Query;
use trust_dns_client::rr::{LowerName, Name, RecordType};
use trust_dns_proto::rr::domain::Name as DomainName;
use tr... | let mname = parts
.next()
.and_then(|n| n.parse::<Name>().ok())
.ok_or("invalid mname")?;
let rname = parts
.next()
.and_then(|n| n.parse::<Name>().ok())
.ok_or("invalid rname")?;
let serial = parts
.next()
.and_then(|n| n.parse::<u32>().ok())
... | {
let parse_error = |e| format!("error parsing: {}", e);
let rdata = |data: &str, rtype: RecordType| match rtype {
RecordType::A => Ok(RData::A(data.parse().map_err(parse_error)?)),
RecordType::AAAA => Ok(RData::AAAA(data.parse().map_err(parse_error)?)),
RecordType::CNAME => Ok(RData::CNAME(DomainName::... | identifier_body |
runtime.rs | // use std::ffi::CString;
// use std::io;
// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::str::FromStr;
use std::sync::Arc;
use std::time::{Duration, Instant};
use trust_dns_client::op::Query;
use trust_dns_client::rr::{LowerName, Name, RecordType};
use trust_dns_proto::rr::domain::Name as DomainName;
use tr... | mod test {
use doh_dns::{Dns, DnsHttpsServer};
use std::time::Duration;
#[tokio::test]
async fn doh_servers() {
let cloudflare = (
"cloudflare",
Some(DnsHttpsServer::new(
"cloudflare-dns.com".into(),
"dns-query".into(),
vec![
"1.1.1.1".parse().unwrap(),
... | // }
#[cfg(test)] | random_line_split |
runtime.rs | // use std::ffi::CString;
// use std::io;
// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::str::FromStr;
use std::sync::Arc;
use std::time::{Duration, Instant};
use trust_dns_client::op::Query;
use trust_dns_client::rr::{LowerName, Name, RecordType};
use trust_dns_proto::rr::domain::Name as DomainName;
use tr... | () {
let resolver = Dns::default();
let result = resolver.resolve_txt("blokada.org").await.unwrap();
for txt in result {
println!("txt: '{}'", txt.data);
}
}
}
| test_txt | identifier_name |
platform_x86_64.rs | #[cfg(not(test))]
use alloc::format;
#[cfg(not(test))]
use alloc::prelude::v1::*;
#[cfg(test)]
use std::prelude::v1::*;
use crate::debugshell::{Command, DebugShell};
pub fn builtin_exit_qemu(_sh: &mut DebugShell, _: Vec<String>) -> String { | format!("asked qemu nicely to exit!\n")
}
pub fn builtin_vga_scrollback_data(_sh: &mut DebugShell, _: Vec<String>) -> String {
use x86_64::instructions::interrupts::without_interrupts;
without_interrupts(|| {
use crate::platform::x86_64::vga::VGA_WRITER;
let vga = VGA_WRITER.get();
... | use crate::platform::x86_64::exit_qemu;
unsafe {
exit_qemu();
}
| random_line_split |
platform_x86_64.rs | #[cfg(not(test))]
use alloc::format;
#[cfg(not(test))]
use alloc::prelude::v1::*;
#[cfg(test)]
use std::prelude::v1::*;
use crate::debugshell::{Command, DebugShell};
pub fn builtin_exit_qemu(_sh: &mut DebugShell, _: Vec<String>) -> String {
use crate::platform::x86_64::exit_qemu;
unsafe {
exit_qemu();... |
})
}
pub fn register_platform_builtins(sh: &mut DebugShell) {
sh.commands.push(Command {
name: String::from("vga-scrollback?"),
func: builtin_vga_scrollback_data,
});
sh.commands.push(Command {
name: String::from("exit-qemu!"),
func: builtin_exit_qemu,
});
}
| {
"vga scrollback is not enabled!\n".into()
} | conditional_block |
platform_x86_64.rs | #[cfg(not(test))]
use alloc::format;
#[cfg(not(test))]
use alloc::prelude::v1::*;
#[cfg(test)]
use std::prelude::v1::*;
use crate::debugshell::{Command, DebugShell};
pub fn builtin_exit_qemu(_sh: &mut DebugShell, _: Vec<String>) -> String |
pub fn builtin_vga_scrollback_data(_sh: &mut DebugShell, _: Vec<String>) -> String {
use x86_64::instructions::interrupts::without_interrupts;
without_interrupts(|| {
use crate::platform::x86_64::vga::VGA_WRITER;
let vga = VGA_WRITER.get();
if let Some(ref sb) = vga.scrollback {
... | {
use crate::platform::x86_64::exit_qemu;
unsafe {
exit_qemu();
}
format!("asked qemu nicely to exit!\n")
} | identifier_body |
platform_x86_64.rs | #[cfg(not(test))]
use alloc::format;
#[cfg(not(test))]
use alloc::prelude::v1::*;
#[cfg(test)]
use std::prelude::v1::*;
use crate::debugshell::{Command, DebugShell};
pub fn builtin_exit_qemu(_sh: &mut DebugShell, _: Vec<String>) -> String {
use crate::platform::x86_64::exit_qemu;
unsafe {
exit_qemu();... | (sh: &mut DebugShell) {
sh.commands.push(Command {
name: String::from("vga-scrollback?"),
func: builtin_vga_scrollback_data,
});
sh.commands.push(Command {
name: String::from("exit-qemu!"),
func: builtin_exit_qemu,
});
}
| register_platform_builtins | identifier_name |
one_time_server.rs | //! A very simple HTTP server which responds to only one connection with the plain text "Hello, World!".
#![crate_name = "one_time_server"]
#![allow(unstable)]
extern crate time;
extern crate http;
use std::io::net::ip::{SocketAddr, Ipv4Addr};
use std::io::Writer;
use http::server::{Config, Server, Request, Respons... | Ok(_) => println!("done serving"),
Err(e) => println!("failed to serve: {}", e)
}
} | }
}
fn main() {
match HelloWorldServer.serve_once(true, None) { | random_line_split |
one_time_server.rs | //! A very simple HTTP server which responds to only one connection with the plain text "Hello, World!".
#![crate_name = "one_time_server"]
#![allow(unstable)]
extern crate time;
extern crate http;
use std::io::net::ip::{SocketAddr, Ipv4Addr};
use std::io::Writer;
use http::server::{Config, Server, Request, Respons... |
fn handle_request(&self, _r: Request, w: &mut ResponseWriter) {
w.headers.date = Some(time::now_utc());
w.headers.content_length = Some(14);
w.headers.content_type = Some(MediaType {
type_: String::from_str("text"),
subtype: String::from_str("plain"),
pa... | {
Config { bind_address: SocketAddr { ip: Ipv4Addr(127, 0, 0, 1), port: 8001 } }
} | identifier_body |
one_time_server.rs | //! A very simple HTTP server which responds to only one connection with the plain text "Hello, World!".
#![crate_name = "one_time_server"]
#![allow(unstable)]
extern crate time;
extern crate http;
use std::io::net::ip::{SocketAddr, Ipv4Addr};
use std::io::Writer;
use http::server::{Config, Server, Request, Respons... | () {
match HelloWorldServer.serve_once(true, None) {
Ok(_) => println!("done serving"),
Err(e) => println!("failed to serve: {}", e)
}
}
| main | identifier_name |
server.rs | use rocket;
use rocket::http::RawStr;
use rocket::request::{FromParam, Request};
use rocket::response::{self, NamedFile, Redirect, Responder};
use scheduled_executor::ThreadPoolExecutor;
use cache::Cache;
use config::Config;
use error::*;
use live_consumer::{self, LiveConsumerStore};
use metadata::ClusterId;
use utils... |
pub struct CachedFile {
ttl: usize,
file: NamedFile,
}
impl CachedFile {
pub fn from(file: NamedFile) -> CachedFile {
CachedFile::with_ttl(1800, file)
}
pub fn with_ttl(ttl: usize, file: NamedFile) -> CachedFile {
CachedFile { ttl, file }
}
}
impl<'a> Responder<'a> for Cache... | {
let _ = version; // just ignore version
NamedFile::open(Path::new("resources/web_server/public/").join(file))
.map(CachedFile::from)
.ok()
} | identifier_body |
server.rs | use rocket;
use rocket::http::RawStr;
use rocket::request::{FromParam, Request};
use rocket::response::{self, NamedFile, Redirect, Responder};
use scheduled_executor::ThreadPoolExecutor;
use cache::Cache;
use config::Config;
use error::*;
use live_consumer::{self, LiveConsumerStore};
use metadata::ClusterId;
use utils... | }
pub fn run_server(executor: &ThreadPoolExecutor, cache: Cache, config: &Config) -> Result<()> {
let version = option_env!("CARGO_PKG_VERSION").unwrap_or("?");
info!(
"Starting kafka-view v{}, listening on {}:{}.",
version, config.listen_host, config.listen_port
);
let rocket_env = ro... | "Cache-Control",
format!("max-age={}, must-revalidate", self.ttl),
)
.ok()
} | random_line_split |
server.rs | use rocket;
use rocket::http::RawStr;
use rocket::request::{FromParam, Request};
use rocket::response::{self, NamedFile, Redirect, Responder};
use scheduled_executor::ThreadPoolExecutor;
use cache::Cache;
use config::Config;
use error::*;
use live_consumer::{self, LiveConsumerStore};
use metadata::ClusterId;
use utils... | {
ttl: usize,
file: NamedFile,
}
impl CachedFile {
pub fn from(file: NamedFile) -> CachedFile {
CachedFile::with_ttl(1800, file)
}
pub fn with_ttl(ttl: usize, file: NamedFile) -> CachedFile {
CachedFile { ttl, file }
}
}
impl<'a> Responder<'a> for CachedFile {
fn respond_... | CachedFile | identifier_name |
structure.rs | extern crate rand;
use self::rand::Rng;
// Read files
use std::io::prelude::*;
use std::fs;
use core::renderer::RGB;
use super::Filter;
use core::world::dungeon::map::{self, Measurable, tile, Tile};
///
/// Structure placer
///
/// Generate prefab structures based on files and place them on the grid
///
#[derive(... |
}
impl Filter for Structure {
type Output = Tile;
fn apply(&mut self, grid: &mut map::Grid<Self::Output>) {
self.add_rand_struct(grid);
}
}
| {
Structure {}
} | identifier_body |
structure.rs | extern crate rand;
use self::rand::Rng;
// Read files
use std::io::prelude::*;
use std::fs;
use core::renderer::RGB;
use super::Filter;
use core::world::dungeon::map::{self, Measurable, tile, Tile};
///
/// Structure placer
///
/// Generate prefab structures based on files and place them on the grid
///
#[derive(... | (&mut self, grid: &mut map::Grid<Self::Output>) {
self.add_rand_struct(grid);
}
}
| apply | identifier_name |
structure.rs | extern crate rand;
use self::rand::Rng;
// Read files
use std::io::prelude::*;
use std::fs;
use core::renderer::RGB;
use super::Filter;
use core::world::dungeon::map::{self, Measurable, tile, Tile};
///
/// Structure placer
///
/// Generate prefab structures based on files and place them on the grid
///
#[derive(... | strct = rot90(strct);
}
// Read details of vector
let w = strct.width();
let h = strct.height();
// Read details of map
let total_w = grid.width();
let total_h = grid.height();
// Add to map if possible
let x = rng.gen_range(0, w + 1);
let y = rng.gen_range(0, h + 1);
... | random_line_split | |
promiserejectionevent.rs | /* 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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use crate::dom::bindings::codegen::Bindi... | let promise = init.promise.clone();
let bubbles = EventBubbles::from(init.parent.bubbles);
let cancelable = EventCancelable::from(init.parent.cancelable);
let event = PromiseRejectionEvent::new(
global,
Atom::from(type_),
bubbles,
cancelab... | global: &GlobalScope,
type_: DOMString,
init: RootedTraceableBox<PromiseRejectionEventBinding::PromiseRejectionEventInit>,
) -> Fallible<DomRoot<Self>> {
let reason = init.reason.handle(); | random_line_split |
promiserejectionevent.rs | /* 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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use crate::dom::bindings::codegen::Bindi... |
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.event.IsTrusted()
}
}
| {
self.reason.get()
} | identifier_body |
promiserejectionevent.rs | /* 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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use crate::dom::bindings::codegen::Bindi... | (
global: &GlobalScope,
type_: DOMString,
init: RootedTraceableBox<PromiseRejectionEventBinding::PromiseRejectionEventInit>,
) -> Fallible<DomRoot<Self>> {
let reason = init.reason.handle();
let promise = init.promise.clone();
let bubbles = EventBubbles::from(init.par... | Constructor | identifier_name |
lib.rs | #[derive(Debug, PartialEq)]
pub enum Comparison {
Unequal,
Equal,
Sublist,
Superlist
}
pub fn sublist<T>(first: &[T], second: &[T]) -> Comparison where T: PartialEq {
let (shortest, longest) =
if first.len() < second.len() { (first, second) }
else { (second, first) };
let mut a... | .map(|length| length >= shortest.len()).unwrap_or(false);
}
if!done { Comparison::Unequal }
else if first.len() < second.len() { Comparison::Sublist }
else if shortest.len() == longest.len() { Comparison::Equal }
else { Comparison::Superlist }
} | random_line_split | |
lib.rs |
#[derive(Debug, PartialEq)]
pub enum Comparison {
Unequal,
Equal,
Sublist,
Superlist
}
pub fn sublist<T>(first: &[T], second: &[T]) -> Comparison where T: PartialEq |
position += 1;
done = anchors.first().map(|&start| position - start)
.map(|length| length >= shortest.len()).unwrap_or(false);
}
if!done { Comparison::Unequal }
else if first.len() < second.len() { Comparison::Sublist }
else if shortest.len() == longest.len() { Comparison::... | {
let (shortest, longest) =
if first.len() < second.len() { (first, second) }
else { (second, first) };
let mut anchors = Vec::new();
let mut position = 0;
let mut done = first.len() * second.len() == 0;
while !done && position < longest.len() {
if let Some(start) = anchors.... | identifier_body |
lib.rs |
#[derive(Debug, PartialEq)]
pub enum | {
Unequal,
Equal,
Sublist,
Superlist
}
pub fn sublist<T>(first: &[T], second: &[T]) -> Comparison where T: PartialEq {
let (shortest, longest) =
if first.len() < second.len() { (first, second) }
else { (second, first) };
let mut anchors = Vec::new();
let mut position = 0;
... | Comparison | identifier_name |
grid.rs | /* ===============================================================================
Simulation of the evolution of the animal world.
Grid of world.
14 Feb 2021.
----------------------------------------------------------------------------
Licensed under the terms of the GPL version 3.
http://www.gnu.org/licenses/gpl-3.0.... | (&self, position_in_units: Point) -> (isize, isize) {
let x = (position_in_units.x / Self::CELL_SIZE).floor() as isize;
let y = (position_in_units.y / Self::CELL_SIZE).floor() as isize;
(x, y)
}
fn set_translation(&mut self, new_translation: Vector) {
self.translation = new_translation;
... | project_to_world | identifier_name |
grid.rs | /* ===============================================================================
Simulation of the evolution of the animal world.
Grid of world.
14 Feb 2021.
----------------------------------------------------------------------------
Licensed under the terms of the GPL version 3.
http://www.gnu.org/licenses/gpl-3.0.... | let region = self.visible_region(size);
Point::new(
position.x / self.scaling + region.x,
position.y / self.scaling + region.y,
)
}
fn project_to_world(&self, position_in_units: Point) -> (isize, isize) {
let x = (position_in_units.x / Self::CELL_SIZE).floor() as isize;... | fn project(&self, position: Point, size: Size) -> Point { | random_line_split |
grid.rs | /* ===============================================================================
Simulation of the evolution of the animal world.
Grid of world.
14 Feb 2021.
----------------------------------------------------------------------------
Licensed under the terms of the GPL version 3.
http://www.gnu.org/licenses/gpl-3.0.... | for column in columns {
// There must be a special border when crossing the edge of the world, skipping for optimization
if column!= 0 {
frame.fill_rectangle(
Point::new(column as f32, rows_start),
Size::new(width, tot... | {
// Draw the inner grid
let width = 2.0 / Self::CELL_SIZE;
let color = Color::from_rgb8(70, 74, 83);
frame.translate(Vector::new(-width / 2.0, -width / 2.0));
// Draw horizontal lines
for row in rows {
// There must be a special bor... | conditional_block |
grid.rs | /* ===============================================================================
Simulation of the evolution of the animal world.
Grid of world.
14 Feb 2021.
----------------------------------------------------------------------------
Licensed under the terms of the GPL version 3.
http://www.gnu.org/licenses/gpl-3.0.... |
fn project(&self, position: Point, size: Size) -> Point {
let region = self.visible_region(size);
Point::new(
position.x / self.scaling + region.x,
position.y / self.scaling + region.y,
)
}
fn project_to_world(&self, position_in_units: Point) -> (isize, isize) {
le... | {
let width = size.width / self.scaling;
let height = size.height / self.scaling;
Region {
x: -self.translation.x,
y: -self.translation.y,
width,
height,
}
} | identifier_body |
restrict-type-argument.rs | fn | <T: Send>(val: T) {}
fn use_impl_sync(val: impl Sync) {
is_send(val); //~ ERROR `impl Sync` cannot be sent between threads safely
}
fn use_where<S>(val: S) where S: Sync {
is_send(val); //~ ERROR `S` cannot be sent between threads safely
}
fn use_bound<S: Sync>(val: S) {
is_send(val); //~ ERROR `S` canno... | is_send | identifier_name |
restrict-type-argument.rs | fn is_send<T: Send>(val: T) {}
fn use_impl_sync(val: impl Sync) {
is_send(val); //~ ERROR `impl Sync` cannot be sent between threads safely
}
| is_send(val); //~ ERROR `S` cannot be sent between threads safely
}
fn use_bound_2<
S // Make sure we can synthezise a correct suggestion span for this case
:
Sync
>(val: S) {
is_send(val); //~ ERROR `S` cannot be sent between threads safely
}
fn use_bound_and_where<S: Sync>(val: S) where S: std::... | fn use_where<S>(val: S) where S: Sync {
is_send(val); //~ ERROR `S` cannot be sent between threads safely
}
fn use_bound<S: Sync>(val: S) { | random_line_split |
restrict-type-argument.rs | fn is_send<T: Send>(val: T) |
fn use_impl_sync(val: impl Sync) {
is_send(val); //~ ERROR `impl Sync` cannot be sent between threads safely
}
fn use_where<S>(val: S) where S: Sync {
is_send(val); //~ ERROR `S` cannot be sent between threads safely
}
fn use_bound<S: Sync>(val: S) {
is_send(val); //~ ERROR `S` cannot be sent between th... | {} | identifier_body |
glyph.rs | u8 = 0x2;
fn break_flag_to_enum(flag: u8) -> BreakType {
if (flag & BREAK_TYPE_NORMAL)!= 0 {
BreakType::Normal
} else if (flag & BREAK_TYPE_HYPHEN)!= 0 {
BreakType::Hyphen
} else {
BreakType::None
}
}
fn break_enum_to_flag(e: BreakType) -> u8 {
match e {
BreakType:... | entry = entry.set_char_is_space()
}
self.entry_buffer[i.to_usize()] = entry;
}
pub fn add_glyphs_for_char_index(&mut self, i: CharIndex, data_for_glyphs: &[GlyphData]) {
assert!(i < self.char_len());
assert!(data_for_glyphs.len() > 0);
let glyph_count = dat... | random_line_split | |
glyph.rs | 8 = 0x2;
fn break_flag_to_enum(flag: u8) -> BreakType {
if (flag & BREAK_TYPE_NORMAL)!= 0 {
BreakType::Normal
} else if (flag & BREAK_TYPE_HYPHEN)!= 0 {
BreakType::Hyphen
} else {
BreakType::None
}
}
fn break_enum_to_flag(e: BreakType) -> u8 {
match e {
BreakType::N... | (&self, rang: &Range<CharIndex>) -> Au {
self.iter_glyphs_for_char | advance_for_char_range | identifier_name |
glyph.rs | 0 {
BreakType::Normal
} else if (flag & BREAK_TYPE_HYPHEN)!= 0 {
BreakType::Hyphen
} else {
BreakType::None
}
}
fn break_enum_to_flag(e: BreakType) -> u8 {
match e {
BreakType::None => BREAK_TYPE_NONE,
BreakType::Normal => BREAK_TYPE_NORMAL,
BreakType:... | {
self.iter_glyphs_for_char_range(rang)
.fold(Au(0), |advance, (_, glyph)| advance + glyph.advance())
} | identifier_body | |
glyph.rs | bool {
self.has_flag(FLAG_IS_SIMPLE_GLYPH)
}
#[inline(always)]
fn has_flag(&self, flag: u32) -> bool {
(self.value & flag)!= 0
}
#[inline(always)]
fn adapt_character_flags_of_entry(&self, other: GlyphEntry) -> GlyphEntry {
GlyphEntry { value: self.value | other.value }... | {
// No more glyphs for current character. Try to get another.
self.glyph_range = None;
self.next()
} | conditional_block | |
args.rs | use super::abi::usercalls::{alloc, raw::ByteBuffer};
use crate::ffi::OsString;
use crate::fmt;
use crate::slice;
use crate::sync::atomic::{AtomicUsize, Ordering};
use crate::sys::os_str::Buf;
use crate::sys_common::FromInner;
#[cfg_attr(test, linkage = "available_externally")]
#[export_name = "_ZN16__rust_internals3st... |
}
pub fn args() -> Args {
let args = unsafe { (ARGS.load(Ordering::Relaxed) as *const ArgsStore).as_ref() };
if let Some(args) = args { Args(args.iter()) } else { Args([].iter()) }
}
pub struct Args(slice::Iter<'static, OsString>);
impl fmt::Debug for Args {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> ... | {
let args = unsafe { alloc::User::<[ByteBuffer]>::from_raw_parts(argv as _, argc as _) };
let args = args
.iter()
.map(|a| OsString::from_inner(Buf { inner: a.copy_user_buffer() }))
.collect::<ArgsStore>();
ARGS.store(Box::into_raw(Box::new(args)) as _, Order... | conditional_block |
args.rs | use super::abi::usercalls::{alloc, raw::ByteBuffer};
use crate::ffi::OsString;
use crate::fmt;
use crate::slice;
use crate::sync::atomic::{AtomicUsize, Ordering};
use crate::sys::os_str::Buf;
use crate::sys_common::FromInner;
#[cfg_attr(test, linkage = "available_externally")]
#[export_name = "_ZN16__rust_internals3st... |
pub struct Args(slice::Iter<'static, OsString>);
impl fmt::Debug for Args {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.as_slice().fmt(f)
}
}
impl Iterator for Args {
type Item = OsString;
fn next(&mut self) -> Option<OsString> {
self.0.next().cloned()
}
... | {
let args = unsafe { (ARGS.load(Ordering::Relaxed) as *const ArgsStore).as_ref() };
if let Some(args) = args { Args(args.iter()) } else { Args([].iter()) }
} | identifier_body |
args.rs | use super::abi::usercalls::{alloc, raw::ByteBuffer};
use crate::ffi::OsString;
use crate::fmt;
use crate::slice;
use crate::sync::atomic::{AtomicUsize, Ordering};
use crate::sys::os_str::Buf;
use crate::sys_common::FromInner;
#[cfg_attr(test, linkage = "available_externally")]
#[export_name = "_ZN16__rust_internals3st... | #[cfg_attr(test, allow(dead_code))]
pub unsafe fn init(argc: isize, argv: *const *const u8) {
if argc!= 0 {
let args = unsafe { alloc::User::<[ByteBuffer]>::from_raw_parts(argv as _, argc as _) };
let args = args
.iter()
.map(|a| OsString::from_inner(Buf { inner: a.copy_user_bu... | random_line_split | |
args.rs | use super::abi::usercalls::{alloc, raw::ByteBuffer};
use crate::ffi::OsString;
use crate::fmt;
use crate::slice;
use crate::sync::atomic::{AtomicUsize, Ordering};
use crate::sys::os_str::Buf;
use crate::sys_common::FromInner;
#[cfg_attr(test, linkage = "available_externally")]
#[export_name = "_ZN16__rust_internals3st... | (argc: isize, argv: *const *const u8) {
if argc!= 0 {
let args = unsafe { alloc::User::<[ByteBuffer]>::from_raw_parts(argv as _, argc as _) };
let args = args
.iter()
.map(|a| OsString::from_inner(Buf { inner: a.copy_user_buffer() }))
.collect::<ArgsStore>();
... | init | identifier_name |
client.rs | // Copyright (c) 2016 P.Y. Laligand
use hyper::Client as HttpClient;
use serde_json::{self, Map, Value};
use std::io::Read;
use super::clip::Clip;
use super::error::XboxError;
use super::xuid::Xuid;
/// Header definition for the API key.
header! { (XAuth, "X-AUTH") => [String] }
/// Interface to the xboxapi.com API... | .and_then(|json| { json.as_u64().ok_or(XboxError::from("Unexpected id format")) })
.map(|value| { Xuid(value) })
}
/// Builds a clip object from its JSON representation.
fn create_clip(json: &mut Map<String, Value>) -> Result<Clip, XboxError> {
let get_value = |key: &str| -> R... | pub fn get_xuid(&self, gamertag: &String) -> Result<Xuid, XboxError> {
let path = format!("xuid/{}", gamertag);
self.send_request(&path) | random_line_split |
client.rs | // Copyright (c) 2016 P.Y. Laligand
use hyper::Client as HttpClient;
use serde_json::{self, Map, Value};
use std::io::Read;
use super::clip::Clip;
use super::error::XboxError;
use super::xuid::Xuid;
/// Header definition for the API key.
header! { (XAuth, "X-AUTH") => [String] }
/// Interface to the xboxapi.com API... |
/// Returns the list of available clips for the given user.
pub fn get_clips(&self, xuid: &Xuid) -> Result<Vec<Clip>, XboxError> {
let path = format!("{}/game-clips", xuid);
let mut json = try!(self.send_request(&path));
let json_string = json.to_string();
let clips = try!(json... | {
let get_value = |key: &str| -> Result<String, XboxError> {
json.get(key)
.and_then(|value| { value.as_str() })
.map(|string| { string.to_owned() })
.ok_or(XboxError::new(format!("Could not get key {}", key)))
};
let id = try!(get_valu... | identifier_body |
client.rs | // Copyright (c) 2016 P.Y. Laligand
use hyper::Client as HttpClient;
use serde_json::{self, Map, Value};
use std::io::Read;
use super::clip::Clip;
use super::error::XboxError;
use super::xuid::Xuid;
/// Header definition for the API key.
header! { (XAuth, "X-AUTH") => [String] }
/// Interface to the xboxapi.com API... | {
/// The API key to authenticate with the service.
api_key: String,
}
/// Base URL for API calls.
const BASE_URL: &'static str = "https://xboxapi.com/v2";
impl Client {
/// Creates a new instance with the given API key.
pub fn new(api_key: String) -> Client {
Client {api_key: api_key}
... | Client | identifier_name |
replay.rs | const REPLAY_BUFFER_SIZE: usize = 256;
const EMPTY_ENTRY: u64 = 0xFFFFFFFFFFFFFFFF;
pub struct ReplayProtection {
most_recent_sequence: u64,
received_packet: [u64; REPLAY_BUFFER_SIZE]
}
impl Clone for ReplayProtection {
fn clone(&self) -> ReplayProtection {
ReplayProtection {
most_rece... | () -> ReplayProtection {
ReplayProtection {
most_recent_sequence: 0,
received_packet: [EMPTY_ENTRY; REPLAY_BUFFER_SIZE]
}
}
pub fn packet_already_received(&mut self, sequence: u64) -> bool {
if sequence & (1 << 63) == (1 << 63) {
return false;
... | new | identifier_name |
replay.rs | const REPLAY_BUFFER_SIZE: usize = 256;
const EMPTY_ENTRY: u64 = 0xFFFFFFFFFFFFFFFF;
pub struct ReplayProtection {
most_recent_sequence: u64,
received_packet: [u64; REPLAY_BUFFER_SIZE]
}
impl Clone for ReplayProtection {
fn clone(&self) -> ReplayProtection {
ReplayProtection {
most_rece... | pub fn packet_already_received(&mut self, sequence: u64) -> bool {
if sequence & (1 << 63) == (1 << 63) {
return false;
}
if sequence + (REPLAY_BUFFER_SIZE as u64) <= self.most_recent_sequence {
return true
}
if sequence > self.most_recent_se... | random_line_split | |
replay.rs | const REPLAY_BUFFER_SIZE: usize = 256;
const EMPTY_ENTRY: u64 = 0xFFFFFFFFFFFFFFFF;
pub struct ReplayProtection {
most_recent_sequence: u64,
received_packet: [u64; REPLAY_BUFFER_SIZE]
}
impl Clone for ReplayProtection {
fn clone(&self) -> ReplayProtection {
ReplayProtection {
most_rece... |
if sequence > self.most_recent_sequence {
self.most_recent_sequence = sequence;
}
let index = sequence as usize % REPLAY_BUFFER_SIZE;
if self.received_packet[index] == EMPTY_ENTRY {
self.received_packet[index] = sequence;
return false
... | {
return true
} | conditional_block |
replay.rs | const REPLAY_BUFFER_SIZE: usize = 256;
const EMPTY_ENTRY: u64 = 0xFFFFFFFFFFFFFFFF;
pub struct ReplayProtection {
most_recent_sequence: u64,
received_packet: [u64; REPLAY_BUFFER_SIZE]
}
impl Clone for ReplayProtection {
fn clone(&self) -> ReplayProtection |
}
impl ReplayProtection {
pub fn new() -> ReplayProtection {
ReplayProtection {
most_recent_sequence: 0,
received_packet: [EMPTY_ENTRY; REPLAY_BUFFER_SIZE]
}
}
pub fn packet_already_received(&mut self, sequence: u64) -> bool {
if sequence & (1 << 63) == (1 ... | {
ReplayProtection {
most_recent_sequence: self.most_recent_sequence,
received_packet: self.received_packet
}
} | identifier_body |
draw.rs | use std::f32::consts::FRAC_PI_2 as QUARTER_TAU;
use glium::texture::{Texture2d, Texture2dDataSource};
use glium::Display;
use glium::Surface as SurfaceTrait;
use ui::{BB, Px};
use ui::color::Color;
use ui::render::{Renderer, Surface, Buffer, XYAndUV};
use ui::text::{FontFace, FontFaces};
pub use glium::glutin::Mouse... |
pub fn line(&mut self, from: [Px; 2], to: [Px; 2], width: Px, color: Color) {
self.with_surface(|this| this.renderer.colored(&mut this.surface, color, |buffer| {
buffer.line(from, to, width);
}));
}
pub fn fill(&mut self, bb: BB<Px>, color: Color/*, corner_radius: Px*/) {
... | {
self.surface.finish().unwrap();
} | identifier_body |
draw.rs | use std::f32::consts::FRAC_PI_2 as QUARTER_TAU;
use glium::texture::{Texture2d, Texture2dDataSource};
use glium::Display;
use glium::Surface as SurfaceTrait;
use ui::{BB, Px};
use ui::color::Color;
use ui::render::{Renderer, Surface, Buffer, XYAndUV};
use ui::text::{FontFace, FontFaces};
pub use glium::glutin::Mouse... | self.overlay_drawing = false;
self.overlay_requested = false;
}
}
pub fn draw_overlay<F, T>(&mut self, f: F) -> T where F: FnOnce(&mut DrawCx) -> T {
assert!(!self.inside_overlay);
self.inside_overlay = true;
let r = f(self);
self.inside_overlay =... | x.draw(self); | random_line_split |
draw.rs | use std::f32::consts::FRAC_PI_2 as QUARTER_TAU;
use glium::texture::{Texture2d, Texture2dDataSource};
use glium::Display;
use glium::Surface as SurfaceTrait;
use ui::{BB, Px};
use ui::color::Color;
use ui::render::{Renderer, Surface, Buffer, XYAndUV};
use ui::text::{FontFace, FontFaces};
pub use glium::glutin::Mouse... | (&mut self, cursor: MouseCursor) {
self.with_surface(|this| this.cursor = cursor);
}
pub fn clear(&mut self, color: Color) {
self.renderer.clear(&mut self.surface, color);
}
// TODO make DrawCx linear to ensure this method gets called.
pub fn finish(self) {
self.surface.fin... | cursor | identifier_name |
draw.rs | use std::f32::consts::FRAC_PI_2 as QUARTER_TAU;
use glium::texture::{Texture2d, Texture2dDataSource};
use glium::Display;
use glium::Surface as SurfaceTrait;
use ui::{BB, Px};
use ui::color::Color;
use ui::render::{Renderer, Surface, Buffer, XYAndUV};
use ui::text::{FontFace, FontFaces};
pub use glium::glutin::Mouse... |
}));
}
pub fn border(&mut self, bb: BB<Px>, color: Color, border_size: Px, corner_radius: Px) {
self.with_surface(|this| this.renderer.colored(&mut this.surface, color, |buffer| {
if corner_radius == 0.0 {
buffer.rect_border(bb, border_size);
} else {
... | {
let resolution = (QUARTER_TAU * corner_radius).ceil() as u32;
buffer.rect_round(bb, resolution, corner_radius);
} | conditional_block |
lib.rs | // This file is part of Grust, GObject introspection bindings for Rust
//
// Copyright (C) 2013-2015 Mikhail Zabaluev <mikhail.zabaluev@gmail.com>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Softwa... | // Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#![crate_name = "grust"]
#![crate_type = "li... | // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | random_line_split |
lib.rs | //
// Copyright 2015 Richard W. Branson
// Copyright 2015 The Rust Project Developers.
//
// See LICENSE file at top level directory.
//
extern crate libc;
use std::error::Error;
use std::io;
use std::fmt;
use libc::{c_void, c_int};
use std::ops::Drop;
use std::ptr;
use self::MemoryMapKind::*;
use self::MapOption::*;... | ,
MapNonStandardFlags(..) => {}
}
}
let flProtect = match (executable, readable, writable) {
(false, false, false) if handle.is_none() => libc::PAGE_NOACCESS,
(false, true, false) => libc::PAGE_READONLY,
(false, true, true) => libc::PAGE_R... | { offset = offset_; } | conditional_block |
lib.rs | //
// Copyright 2015 Richard W. Branson
// Copyright 2015 The Rust Project Developers.
//
// See LICENSE file at top level directory.
//
extern crate libc;
use std::error::Error;
use std::io;
use std::fmt;
use libc::{c_void, c_int};
use std::ops::Drop;
use std::ptr;
use self::MemoryMapKind::*;
use self::MapOption::*;... | () -> usize {
unsafe { libc::sysconf(libc::_SC_PAGESIZE) as usize }
}
#[cfg(windows)]
fn page_size() -> usize {
unsafe {
let mut info = mem::zeroed();
libc::GetSystemInfo(&mut info);
return info.dwPageSize as usize;
}
}
/// A memory mapped file or chunk of memory. This is a very sy... | page_size | identifier_name |
lib.rs | //
// Copyright 2015 Richard W. Branson
// Copyright 2015 The Rust Project Developers.
//
// See LICENSE file at top level directory.
//
extern crate libc;
use std::error::Error;
use std::io;
use std::fmt;
use libc::{c_void, c_int};
use std::ops::Drop;
use std::ptr;
use self::MemoryMapKind::*;
use self::MapOption::*;... | },
MapOffset(offset_) => { offset = offset_ as off_t; },
MapNonStandardFlags(f) => { custom_flags = true; flags = f },
}
}
if fd == -1 &&!custom_flags { flags |= libc::MAP_ANON; }
let r = unsafe {
libc::mmap(addr as *mut c_... | MapFd(fd_) => {
flags |= libc::MAP_FILE;
fd = fd_; | random_line_split |
time_zone.rs | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use glib_sys;
use translate::*;
use GString;
use TimeType;
glib_wrapper! {
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TimeZone(Shared<glib_sys::GTimeZ... | (seconds: i32) -> TimeZone {
unsafe { from_glib_full(glib_sys::g_time_zone_new_offset(seconds)) }
}
pub fn new_utc() -> TimeZone {
unsafe { from_glib_full(glib_sys::g_time_zone_new_utc()) }
}
pub fn find_interval(&self, type_: TimeType, time_: i64) -> i32 {
unsafe {
... | new_offset | identifier_name |
time_zone.rs |
use glib_sys;
use translate::*;
use GString;
use TimeType;
glib_wrapper! {
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TimeZone(Shared<glib_sys::GTimeZone>);
match fn {
ref => |ptr| glib_sys::g_time_zone_ref(ptr),
unref => |ptr| glib_sys::g_time_zone_unref(ptr),
... | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT | random_line_split | |
time_zone.rs | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use glib_sys;
use translate::*;
use GString;
use TimeType;
glib_wrapper! {
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TimeZone(Shared<glib_sys::GTimeZ... |
#[cfg(any(feature = "v2_58", feature = "dox"))]
pub fn get_identifier(&self) -> GString {
unsafe { from_glib_none(glib_sys::g_time_zone_get_identifier(self.to_glib_none().0)) }
}
pub fn get_offset(&self, interval: i32) -> i32 {
unsafe { glib_sys::g_time_zone_get_offset(self.to_glib_no... | {
unsafe {
from_glib_none(glib_sys::g_time_zone_get_abbreviation(
self.to_glib_none().0,
interval,
))
}
} | identifier_body |
kl25z_map.rs | // Copyright 2014 Martin Kojtal (0xc0170)
//
// 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 or a... | (port: u32) -> &'static Port {
unsafe {
&*((BASE_PORTA + (port*0x1000)) as *const Port)
}
}
}
const BASE_MCG : u32 = 0x40064000;
pub struct Mcg {
pub c1 : VolatileRW<u8>,
pub c2 : VolatileRW<u8>,
pub c3 : VolatileRW<u8>,
pub c4 : VolatileRW<u8>,
pub c5 : VolatileRW<... | get | identifier_name |
kl25z_map.rs | // Copyright 2014 Martin Kojtal (0xc0170)
//
// 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 or a... | pub cr : VolatileRW<u8>,
}
impl Osc0 {
pub fn get() -> &'static Osc0 {
unsafe {
&*(BASE_OSC0 as *const Osc0)
}
}
}
const BASE_PTA :u32 = 0x400FF000;
pub struct Gpio {
pub pdor : VolatileRW<u32>,
pub psor : VolatileRW<u32>,
pub pcor : VolatileRW<u32>,
pub ptor :... |
const BASE_OSC0 : u32 = 0x40065000;
pub struct Osc0 { | random_line_split |
kl25z_map.rs | // Copyright 2014 Martin Kojtal (0xc0170)
//
// 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 or a... |
}
const BASE_PORTA : u32 = 0x40049000;
pub struct Port {
pub pcr : [VolatileRW<u32>; 32],
pub gpclr : VolatileRW<u32>,
pub gpchr : VolatileRW<u32>,
pub reserved_0 : [u8; 24],
pub isfr : VolatileRW<u32>,
}
impl Port {
pub fn get(port: u32) -> &'static Port {
unsafe {
&*((B... | {
unsafe {
&*(BASE_SIM as *const Sim)
}
} | identifier_body |
utils.rs | //! Shared mathematical utility functions.
/// Cut value to be inside given range
///
/// ```
/// use image::math::utils;
///
/// assert_eq!(utils::clamp(-5, 0, 10), 0);
/// assert_eq!(utils::clamp( 6, 0, 10), 6);
/// assert_eq!(utils::clamp(15, 0, 10), 10);
/// ```
#[inline]
#[deprecated]
pub fn clamp<N>(a: N, min:... |
/// Calculates the width and height an image should be resized to.
/// This preserves aspect ratio, and based on the `fill` parameter
/// will either fill the dimensions to fit inside the smaller constraint
/// (will overflow the specified bounds on one axis to preserve
/// aspect ratio), or will shrink so that both ... | {
if a < min {
return min;
}
if a > max {
return max;
}
a
} | identifier_body |
utils.rs | //! Shared mathematical utility functions.
/// Cut value to be inside given range
///
/// ```
/// use image::math::utils;
///
/// assert_eq!(utils::clamp(-5, 0, 10), 0);
/// assert_eq!(utils::clamp( 6, 0, 10), 6);
/// assert_eq!(utils::clamp(15, 0, 10), 10);
/// ```
#[inline]
#[deprecated]
pub fn clamp<N>(a: N, min:... | else {
u64::from(width) * u64::from(nheight) / u64::from(height)
};
let intermediate = std::cmp::max(1, intermediate);
if use_width {
if intermediate <= u64::from(::std::u32::MAX) {
(nwidth, intermediate as u32)
} else {
(
(u64::from(nwidth) *... | {
u64::from(height) * u64::from(nwidth) / u64::from(width)
} | conditional_block |
utils.rs | //! Shared mathematical utility functions.
/// Cut value to be inside given range
///
/// ```
/// use image::math::utils;
///
/// assert_eq!(utils::clamp(-5, 0, 10), 0);
/// assert_eq!(utils::clamp( 6, 0, 10), 6);
/// assert_eq!(utils::clamp(15, 0, 10), 10);
/// ```
#[inline]
#[deprecated]
pub fn clamp<N>(a: N, min:... | () {
let result = super::resize_dimensions(1, 150, 128, 128, false);
assert!(result.0 > 0);
assert!(result.1 > 0);
}
#[test]
fn resize_handles_overflow() {
let result = super::resize_dimensions(100, ::std::u32::MAX, 200, ::std::u32::MAX, true);
assert!(result.0 == 10... | resize_never_rounds_to_zero | identifier_name |
utils.rs | //! Shared mathematical utility functions.
/// Cut value to be inside given range
///
/// ```
/// use image::math::utils;
///
/// assert_eq!(utils::clamp(-5, 0, 10), 0);
/// assert_eq!(utils::clamp( 6, 0, 10), 6);
/// assert_eq!(utils::clamp(15, 0, 10), 10);
/// ```
#[inline]
#[deprecated]
pub fn clamp<N>(a: N, min:... | /// (will overflow the specified bounds on one axis to preserve
/// aspect ratio), or will shrink so that both dimensions are
/// completely contained with in the given `width` and `height`,
/// with empty space on one axis.
pub(crate) fn resize_dimensions(width: u32, height: u32, nwidth: u32, nheight: u32, fill: bool)... | /// Calculates the width and height an image should be resized to.
/// This preserves aspect ratio, and based on the `fill` parameter
/// will either fill the dimensions to fit inside the smaller constraint | random_line_split |
sendmoremoney.rs | //! Send More Money.
//!
//! https://en.wikipedia.org/wiki/Verbal_arithmetic
extern crate puzzle_solver;
use puzzle_solver::{Puzzle,Solution,VarToken};
fn make_send_more_money() -> (Puzzle, Vec<VarToken>) {
let mut sys = Puzzle::new();
let vars = sys.new_vars_with_candidates_1d(8, &[0,1,2,3,4,5,6,7,8,9]);
... | }
#[test]
fn sendmoremoney_naive() {
let (mut sys, vars) = make_send_more_money();
let dict = sys.solve_unique().expect("solution");
print_send_more_money(&dict, &vars);
verify_send_more_money(&dict, &vars);
println!("sendmoremoney_naive: {} guesses", sys.num_guesses());
}
| {
let carry = [0,1];
let (mut sys, vars) = make_send_more_money();
let (s, e, n, d) = (vars[0], vars[1], vars[2], vars[3]);
let (m, o, r, y) = (vars[4], vars[5], vars[6], vars[7]);
let c1 = sys.new_var_with_candidates(&carry);
let c2 = sys.new_var_with_candidates(&carry);
let c3 = sys.new_v... | identifier_body |
sendmoremoney.rs | //! Send More Money.
//!
//! https://en.wikipedia.org/wiki/Verbal_arithmetic
extern crate puzzle_solver;
use puzzle_solver::{Puzzle,Solution,VarToken};
fn make_send_more_money() -> (Puzzle, Vec<VarToken>) {
let mut sys = Puzzle::new();
let vars = sys.new_vars_with_candidates_1d(8, &[0,1,2,3,4,5,6,7,8,9]);
... | }
#[test]
fn sendmoremoney_naive() {
let (mut sys, vars) = make_send_more_money();
let dict = sys.solve_unique().expect("solution");
print_send_more_money(&dict, &vars);
verify_send_more_money(&dict, &vars);
println!("sendmoremoney_naive: {} guesses", sys.num_guesses());
} | println!("sendmoremoney_carry: {} guesses", sys.num_guesses()); | random_line_split |
sendmoremoney.rs | //! Send More Money.
//!
//! https://en.wikipedia.org/wiki/Verbal_arithmetic
extern crate puzzle_solver;
use puzzle_solver::{Puzzle,Solution,VarToken};
fn | () -> (Puzzle, Vec<VarToken>) {
let mut sys = Puzzle::new();
let vars = sys.new_vars_with_candidates_1d(8, &[0,1,2,3,4,5,6,7,8,9]);
let (s, e, n, d) = (vars[0], vars[1], vars[2], vars[3]);
let (m, o, r, y) = (vars[4], vars[5], vars[6], vars[7]);
sys.remove_candidates(s, &[0]);
sys.remove_candid... | make_send_more_money | identifier_name |
cargo.rs | #![allow(unstable)]
extern crate "rustc-serialize" as rustc_serialize;
extern crate cargo;
#[macro_use] extern crate log;
use std::collections::BTreeSet;
use std::os;
use std::io;
use std::io::fs::{self, PathExtensions};
use std::io::process::{Command,InheritFd,ExitStatus,ExitSignal};
use cargo::{execute_main_withou... | println!(" {}", command);
};
return Ok(None)
}
let (mut args, command) = match flags.arg_command.as_slice() {
"" | "help" if flags.arg_args.len() == 0 => {
shell.set_verbose(true);
let args = &[os::args()[0].clone(), "-h".to_string()];
... | for command in list_commands().into_iter() { | random_line_split |
cargo.rs | #![allow(unstable)]
extern crate "rustc-serialize" as rustc_serialize;
extern crate cargo;
#[macro_use] extern crate log;
use std::collections::BTreeSet;
use std::os;
use std::io;
use std::io::fs::{self, PathExtensions};
use std::io::process::{Command,InheritFd,ExitStatus,ExitSignal};
use cargo::{execute_main_withou... | {
let mut dirs = vec![];
match os::self_exe_path() {
Some(path) => {
dirs.push(path.join("../lib/cargo"));
dirs.push(path);
},
None => {}
};
match std::os::getenv("PATH") {
Some(val) => {
for dir in os::split_paths(val).iter() {
... | identifier_body | |
cargo.rs | #![allow(unstable)]
extern crate "rustc-serialize" as rustc_serialize;
extern crate cargo;
#[macro_use] extern crate log;
use std::collections::BTreeSet;
use std::os;
use std::io;
use std::io::fs::{self, PathExtensions};
use std::io::process::{Command,InheritFd,ExitStatus,ExitSignal};
use cargo::{execute_main_withou... | (cmd: &str, args: &[String], shell: &mut MultiShell) {
let command = match find_command(cmd) {
Some(command) => command,
None => {
let msg = match find_closest(cmd) {
Some(closest) => format!("No such subcommand\n\n\tDid you mean `{}`?\n", closest),
None =... | execute_subcommand | identifier_name |
setup.rs | // This file is part of rust-web/twig
//
// For the copyright and license information, please view the LICENSE
// file that was distributed with this source code.
//! Stores the Twig configuration.
use std::path::Path;
use std::rc::Rc;
use extension;
use extension::api::Extension;
use engine::{Engine, options, Option... |
/// An absolute path where to store the compiled templates (optional)
pub fn set_cache(mut self, cache: Option<&Path>) -> Self {
self.opt.cache = cache.map(|reference| reference.to_owned());
self
}
/// Whether to reload the template if the original source changed (optional).
/// ... | {
self.opt.autoescape = autoescape;
self
} | identifier_body |
setup.rs | // This file is part of rust-web/twig
//
// For the copyright and license information, please view the LICENSE
// file that was distributed with this source code.
//! Stores the Twig configuration.
use std::path::Path;
use std::rc::Rc;
use extension;
use extension::api::Extension;
use engine::{Engine, options, Option... | (mut self, auto_reload: Option<bool>) -> Self {
self.opt.auto_reload = auto_reload;
self
}
/// A flag that indicates whether optimizations are applied
pub fn set_optimizations(mut self, optimizations: options::Optimizations) -> Self {
self.opt.optimizations = optimizations;
... | set_auto_reload | identifier_name |
setup.rs | // This file is part of rust-web/twig
//
// For the copyright and license information, please view the LICENSE
// file that was distributed with this source code.
//! Stores the Twig configuration.
use std::path::Path;
use std::rc::Rc;
use extension;
use extension::api::Extension;
use engine::{Engine, options, Option... | // }
} | random_line_split | |
bbox.rs | //! Bounding boxes that know their coordinate space.
use crate::coord_units::CoordUnits;
use crate::rect::Rect;
use crate::transform::Transform;
#[derive(Debug, Default, Copy, Clone)]
pub struct BoundingBox {
transform: Transform,
pub rect: Option<Rect>, // without stroke
pub ink_rect: Option<Rect>, /... | r1: Option<Rect>,
r2: Option<Rect>,
transform: &Transform,
clip: bool,
) -> Option<Rect> {
match (r1, r2, clip) {
(r1, None, _) => r1,
(None, Some(r2), _) => Some(transform.transform_rect(&r2)),
(Some(r1), Some(r2), true) => transform
.transform_rect(&r2)
... | }
fn combine_rects( | random_line_split |
bbox.rs | //! Bounding boxes that know their coordinate space.
use crate::coord_units::CoordUnits;
use crate::rect::Rect;
use crate::transform::Transform;
#[derive(Debug, Default, Copy, Clone)]
pub struct BoundingBox {
transform: Transform,
pub rect: Option<Rect>, // without stroke
pub ink_rect: Option<Rect>, /... | (mut self) {
self.rect = None;
self.ink_rect = None;
}
fn combine(&mut self, src: &BoundingBox, clip: bool) {
if src.rect.is_none() && src.ink_rect.is_none() {
return;
}
// this will panic!() if it's not invertible... should we check on our own?
let ... | clear | identifier_name |
bbox.rs | //! Bounding boxes that know their coordinate space.
use crate::coord_units::CoordUnits;
use crate::rect::Rect;
use crate::transform::Transform;
#[derive(Debug, Default, Copy, Clone)]
pub struct BoundingBox {
transform: Transform,
pub rect: Option<Rect>, // without stroke
pub ink_rect: Option<Rect>, /... |
pub fn with_ink_rect(self, ink_rect: Rect) -> BoundingBox {
BoundingBox {
ink_rect: Some(ink_rect),
..self
}
}
pub fn clear(mut self) {
self.rect = None;
self.ink_rect = None;
}
fn combine(&mut self, src: &BoundingBox, clip: bool) {
... | {
BoundingBox {
rect: Some(rect),
..self
}
} | identifier_body |
links.rs | use std::collections::HashMap;
use core::PackageSet;
use util::{CargoResult, human};
// Validate that there are no duplicated native libraries among packages and
// that all packages with `links` also have a build script.
pub fn | (deps: &PackageSet) -> CargoResult<()> {
let mut map = HashMap::new();
for dep in deps.iter() {
let lib = match dep.manifest().links() {
Some(lib) => lib,
None => continue,
};
match map.get(&lib) {
Some(previous) => {
return Err(human(... | validate | identifier_name |
links.rs | use std::collections::HashMap;
use core::PackageSet;
use util::{CargoResult, human};
// Validate that there are no duplicated native libraries among packages and
// that all packages with `links` also have a build script.
pub fn validate(deps: &PackageSet) -> CargoResult<()> {
let mut map = HashMap::new();
f... | } | random_line_split | |
links.rs | use std::collections::HashMap;
use core::PackageSet;
use util::{CargoResult, human};
// Validate that there are no duplicated native libraries among packages and
// that all packages with `links` also have a build script.
pub fn validate(deps: &PackageSet) -> CargoResult<()> | `{}` but does not have a custom build \
script", dep.package_id(), lib)))
}
map.insert(lib, dep.package_id());
}
Ok(())
}
| {
let mut map = HashMap::new();
for dep in deps.iter() {
let lib = match dep.manifest().links() {
Some(lib) => lib,
None => continue,
};
match map.get(&lib) {
Some(previous) => {
return Err(human(format!("native library `{}` is being l... | identifier_body |
writebatch.rs | use utils::{tmpdir};
use leveldb::database::{Database};
use leveldb::options::{Options,ReadOptions,WriteOptions};
use leveldb::database::kv::{KV};
use leveldb::database::batch::{Batch,Writebatch,WritebatchIterator};
#[test]
fn test_writebatch() {
let mut opts = Options::new();
opts.create_if_missing = true;
... | {
put: i32,
deleted: i32,
}
impl WritebatchIterator for Iter {
type K = i32;
fn put(&mut self,
_key: i32,
_value: &[u8]) {
self.put = self.put + 1;
}
fn deleted(&mut self,
_key: i32) {
self.deleted = self.deleted + 1;
}
}
#[test]
fn t... | Iter | identifier_name |
writebatch.rs | use utils::{tmpdir};
use leveldb::database::{Database};
use leveldb::options::{Options,ReadOptions,WriteOptions};
use leveldb::database::kv::{KV};
use leveldb::database::batch::{Batch,Writebatch,WritebatchIterator};
#[test]
fn test_writebatch() {
let mut opts = Options::new();
opts.create_if_missing = true;
... |
}
let read_opts2 = ReadOptions::new();
let res2 = database.get(read_opts2, 1);
match res2 {
Ok(data) => { assert!(data.is_none()) },
Err(_) => { panic!("failed reading data") }
}
}
struct Iter {
put: i32,
deleted: i32,
}
impl WritebatchIterator for Iter {
type K = i32... | { panic!("failed reading data") } | conditional_block |
writebatch.rs | use utils::{tmpdir};
use leveldb::database::{Database};
use leveldb::options::{Options,ReadOptions,WriteOptions};
use leveldb::database::kv::{KV};
use leveldb::database::batch::{Batch,Writebatch,WritebatchIterator};
#[test]
fn test_writebatch() {
let mut opts = Options::new();
opts.create_if_missing = true;
... | let data = data.unwrap();
assert_eq!(data, vec!(2));
},
Err(_) => { panic!("failed reading data") }
}
let read_opts2 = ReadOptions::new();
let res2 = database.get(read_opts2, 1);
match res2 {
Ok(data) => { assert!(data.is_none()) },
Err(_) => { pa... | Ok(data) => {
assert!(data.is_some()); | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.