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 |
|---|---|---|---|---|
session_data.rs | use super::{
configuration::{self, CoreConfig, SessionConfig},
core_data::{CoreData, CoreHandle},
};
use crate::cmd::dap_server::{
debug_adapter::{
dap::adapter::DebugAdapter, dap::dap_types::Source, protocol::ProtocolAdapter,
},
DebuggerError,
};
use anyhow::{anyhow, Result};
use probe_rs::... |
if let Some(info) = list.first() {
Probe::open(info).map_err(DebuggerError::DebugProbe)
} else {
return Err(DebuggerError::Other(anyhow!(
"No probes found. Please check your USB connections."
)));
... | {
return Err(DebuggerError::Other(anyhow!(
"Found multiple ({}) probes",
list.len()
)));
} | conditional_block |
session_data.rs | use super::{
configuration::{self, CoreConfig, SessionConfig},
core_data::{CoreData, CoreHandle},
};
use crate::cmd::dap_server::{
debug_adapter::{
dap::adapter::DebugAdapter, dap::dap_types::Source, protocol::ProtocolAdapter,
},
DebuggerError,
};
use anyhow::{anyhow, Result};
use probe_rs::... | {
let debug_info = if let Some(binary_path) = &core_configuration.program_binary {
DebugInfo::from_file(binary_path).map_err(|error| DebuggerError::Other(anyhow!(error)))?
} else {
return Err(anyhow!(
"Please provide a valid `program_binary` for debug core: {:?}",
core_co... | identifier_body | |
session_data.rs | use super::{
configuration::{self, CoreConfig, SessionConfig},
core_data::{CoreData, CoreHandle},
};
use crate::cmd::dap_server::{
debug_adapter::{
dap::adapter::DebugAdapter, dap::dap_types::Source, protocol::ProtocolAdapter,
},
DebuggerError,
};
use anyhow::{anyhow, Result};
use probe_rs::... | {
pub(crate) breakpoint_type: BreakpointType,
pub(crate) address: u64,
}
/// SessionData is designed to be similar to [probe_rs::Session], in as much that it provides handles to the [CoreHandle] instances for each of the available [probe_rs::Core] involved in the debug session.
/// To get access to the [CoreH... | ActiveBreakpoint | identifier_name |
render.rs | //! HTML generation
//!
use crate::{Result, TomlMap};
use chrono::DateTime;
use handlebars::Handlebars;
use serde_json::Value as JsonValue;
use std::collections::HashMap;
use toml::value::Value as TomlValue;
/// Html to insert before and after diff chunks
pub struct DiffStyle {
/// Html to insert before a span of ... | .iter()
.map(json_value_to_string)
.collect::<Vec<String>>()
.join(",");
out.write(&csv)?;
Ok(())
},
),
);
//
// format-date: strftime-like function to reformat date
hb.registe... | {
use handlebars::{Context, Helper, HelperResult, Output, RenderContext, RenderError};
// "join-csv" turns array of values into comma-separated list
// Converts each value using to_string()
hb.register_helper(
"join-csv",
Box::new(
|h: &Helper,
_r: &Handlebars,
... | identifier_body |
render.rs | //! HTML generation
//!
use crate::{Result, TomlMap};
use chrono::DateTime;
use handlebars::Handlebars;
use serde_json::Value as JsonValue;
use std::collections::HashMap;
use toml::value::Value as TomlValue;
/// Html to insert before and after diff chunks
pub struct DiffStyle {
/// Html to insert before a span of ... | /// Test template processor
#[test]
fn test_html_page() {
use crate::render::Renderer;
const TEST_TEMPLATE: &str = "<html><body><h1>{{title}}</h1>{{content}}</body></html>";
let mut map = TomlMap::new();
map.insert("title".into(), "Abc".into());
// simulate processing
let expected = TEST_TEMPL... | let mut r2 = Renderer::init(&RenderConfig::default()).expect("ok");
r2.set("x".into(), toml::Value::from("xyz"));
assert!(true);
}
| random_line_split |
render.rs | //! HTML generation
//!
use crate::{Result, TomlMap};
use chrono::DateTime;
use handlebars::Handlebars;
use serde_json::Value as JsonValue;
use std::collections::HashMap;
use toml::value::Value as TomlValue;
/// Html to insert before and after diff chunks
pub struct DiffStyle {
/// Html to insert before a span of ... | () -> Self {
// unwrap ok because only error condition occurs with templates, and default has none.
Self::init(&RenderConfig::default()).unwrap()
}
}
impl<'gen> Renderer<'gen> {
/// Initialize handlebars template processor.
pub fn init(config: &RenderConfig) -> Result<Self> {
let mu... | default | identifier_name |
output.rs | //
//! Copyright 2020 Alibaba Group Holding Limited.
//!
//! 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 ... |
}
pub fn give_entire_iterator<I: IntoIterator<Item = D>>(&mut self, iter: I) -> IOResult<bool> {
let mut count = 0;
for datum in iter.into_iter() {
count += 1;
self.push(datum)?;
}
Ok(self.update_capacity(count))
}
///
pub fn give_batch(&mut... | {
for item in iter {
self.push(item)?;
}
Ok(true)
} | conditional_block |
output.rs | //
//! Copyright 2020 Alibaba Group Holding Limited.
//!
//! 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 ... | } | Session::new(&mut self.inner, matched, self.batch_size, ca)
} | random_line_split |
output.rs | //
//! Copyright 2020 Alibaba Group Holding Limited.
//!
//! 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 ... |
#[inline]
fn is_closed(&self) -> bool {
self.poisoned
}
}
impl<D: Data> OutputHandle<D> {
pub fn new(output: WrappedTee<DataSet<D>>, batch: usize, port: Port, delta: OutputDelta) -> Self {
OutputHandle {
port,
delta,
inner: output,
capac... | {
if !self.poisoned {
trace!("Worker[{}], output[{:?}] is closing ...", self.inner.worker, self.port);
self.poisoned = true;
self.inner.close()?;
}
Ok(())
} | identifier_body |
output.rs | //
//! Copyright 2020 Alibaba Group Holding Limited.
//!
//! 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 ... | (&mut self) -> &mut dyn Any {
self
}
fn as_any_ref(&self) -> &dyn Any {
self
}
}
impl<D: Data> TaggedOutput for OutputHandle<D> {
#[inline]
fn set_output_capacity(&mut self, capacity: usize) {
self.capacity.replace(capacity);
}
#[inline]
fn has_capacity(&self) ... | as_any_mut | identifier_name |
main.rs | use clap::*;
use gre::*;
use isosurface::{marching_cubes::MarchingCubes, source::Source};
use kiss3d::nalgebra::{Perspective3, Point3, Rotation3, Vector3};
use rand::prelude::*;
use std::f32::consts::PI;
use std::ops::{Add, Mul, Sub};
use svg::node::element::path::Data;
use svg::node::element::*;
#[derive(Parser)]
#[c... | fn add(self, v: Vector3<f32>) -> Self::Output {
Tri {
v1: self.v1 + v,
v2: self.v2 + v,
v3: self.v3 + v,
}
}
}
impl Mul<Tri> for f32 {
type Output = Tri;
fn mul(self, tri: Tri) -> Self::Output {
Tri {
v1: self * tri.v1,
v2: self * tri.v2,
v3: self * tri.v3,
... | }
impl Add<Vector3<f32>> for Tri {
type Output = Tri;
| random_line_split |
main.rs | use clap::*;
use gre::*;
use isosurface::{marching_cubes::MarchingCubes, source::Source};
use kiss3d::nalgebra::{Perspective3, Point3, Rotation3, Vector3};
use rand::prelude::*;
use std::f32::consts::PI;
use std::ops::{Add, Mul, Sub};
use svg::node::element::path::Data;
use svg::node::element::*;
#[derive(Parser)]
#[c... |
}
route.push((x, y));
route
}
| {
break;
} | conditional_block |
main.rs | use clap::*;
use gre::*;
use isosurface::{marching_cubes::MarchingCubes, source::Source};
use kiss3d::nalgebra::{Perspective3, Point3, Rotation3, Vector3};
use rand::prelude::*;
use std::f32::consts::PI;
use std::ops::{Add, Mul, Sub};
use svg::node::element::path::Data;
use svg::node::element::*;
#[derive(Parser)]
#[c... |
fn is_inside_polygons(p: (f64, f64), polygons: &Vec<Vec<(f64, f64)>>) -> bool {
for polygon in polygons {
if is_inside_a_polygon(p, polygon) {
return true;
}
}
false
}
fn main() {
let opts: Opts = Opts::parse();
let groups = art(&opts);
let mut document = base_document("yellow", opts.width,... | {
let mut inside = false;
let mut j = polygon.len() - 1;
for i in 0..polygon.len() {
let pi = polygon[i];
let pj = polygon[j];
if (pi.1 > p.1) != (pj.1 > p.1)
&& p.0 < (pj.0 - pi.0) * (p.1 - pi.1) / (pj.1 - pi.1) + pi.0
{
inside = !inside;
}
j = i;
}
inside
} | identifier_body |
main.rs | use clap::*;
use gre::*;
use isosurface::{marching_cubes::MarchingCubes, source::Source};
use kiss3d::nalgebra::{Perspective3, Point3, Rotation3, Vector3};
use rand::prelude::*;
use std::f32::consts::PI;
use std::ops::{Add, Mul, Sub};
use svg::node::element::path::Data;
use svg::node::element::*;
#[derive(Parser)]
#[c... | (precision: f64, width: f64, height: f64) -> Self {
let wi = (width / precision).ceil() as usize;
let hi = (height / precision).ceil() as usize;
let counters = vec![0; wi * hi];
Passage {
precision,
width,
height,
counters,
}
}
fn index(self: &Self, (x, y): (f64, f64)) -... | new | identifier_name |
gossip.rs | #![allow(clippy::arithmetic_side_effects)]
#[macro_use]
extern crate log;
use {
rayon::iter::*,
solana_gossip::{
cluster_info::{ClusterInfo, Node},
contact_info::{LegacyContactInfo as ContactInfo, Protocol},
crds::Cursor,
gossip_service::GossipService,
},
solana_perf::pa... |
sleep(Duration::from_secs(1));
}
exit.store(true, Ordering::Relaxed);
for (_, dr, _) in listen {
dr.join().unwrap();
}
assert!(done);
}
/// retransmit messages to a list of nodes
fn retransmit_to(
peers: &[&ContactInfo],
data: &[u8],
socket: &UdpSocket,
forwarded: b... | {
trace!("not converged {} {} {}", i, total + num, num * num);
} | conditional_block |
gossip.rs | #![allow(clippy::arithmetic_side_effects)]
#[macro_use]
extern crate log;
use {
rayon::iter::*,
solana_gossip::{
cluster_info::{ClusterInfo, Node},
contact_info::{LegacyContactInfo as ContactInfo, Protocol},
crds::Cursor,
gossip_service::GossipService,
},
solana_perf::pa... | 10_000,
&vote_keypairs,
vec![100; vote_keypairs.len()],
);
let bank0 = Bank::new_for_tests(&genesis_config_info.genesis_config);
let bank_forks = Arc::new(RwLock::new(BankForks::new(bank0)));
let nodes: Vec<_> = vote_keypairs
.into_iter()
.map(|keypairs| {
... |
let vote_keypairs: Vec<_> = (0..num_nodes)
.map(|_| ValidatorVoteKeypairs::new_rand())
.collect();
let genesis_config_info = create_genesis_config_with_vote_accounts( | random_line_split |
gossip.rs | #![allow(clippy::arithmetic_side_effects)]
#[macro_use]
extern crate log;
use {
rayon::iter::*,
solana_gossip::{
cluster_info::{ClusterInfo, Node},
contact_info::{LegacyContactInfo as ContactInfo, Protocol},
crds::Cursor,
gossip_service::GossipService,
},
solana_perf::pa... | () {
solana_logger::setup();
run_gossip_topo(50, |listen| {
let num = listen.len();
for n in 0..num {
let y = n % listen.len();
let x = (n + 1) % listen.len();
let yv = &listen[y].0;
let mut d = yv.lookup_contact_info(&yv.id(), |ci| ci.clone()).unw... | gossip_ring | identifier_name |
gossip.rs | #![allow(clippy::arithmetic_side_effects)]
#[macro_use]
extern crate log;
use {
rayon::iter::*,
solana_gossip::{
cluster_info::{ClusterInfo, Node},
contact_info::{LegacyContactInfo as ContactInfo, Protocol},
crds::Cursor,
gossip_service::GossipService,
},
solana_perf::pa... | test_node.sockets.tvu.pop().unwrap(),
)
}
/// Test that the network converges.
/// Run until every node in the network has a full ContactInfo set.
/// Check that nodes stop sending updates after all the ContactInfo has been shared.
/// tests that actually use this function are below
fn run_gossip_topo<F>(... | {
let mut test_node = Node::new_localhost_with_pubkey(&node_keypair.pubkey());
let cluster_info = Arc::new(ClusterInfo::new(
test_node.info.clone(),
node_keypair,
SocketAddrSpace::Unspecified,
));
let gossip_service = GossipService::new(
&cluster_info,
Some(bank_f... | identifier_body |
lib.rs | mod error;
use std::fs::{self, File, OpenOptions};
use std::io::{self, stdin, stdout, Write};
use std::ops::Deref;
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};
use error_chain::bail;
use hex::FromHex;
use lazy_static::lazy_static;
use seckey::SecBytes;
use serde::{Deserialize, Serialize};
us... | skey_file.encrypt(passwd);
skey_file.save(skey_path)?;
pkey_file.save(pkey_path)?;
println!("Generated {} and {}", pkey_path.display(), skey_path.display());
Ok((pkey_file, skey_file))
}
fn prompt_skey(skey_path: &Path, prompt: impl AsRef<str>) -> Result<SecretKeyFile, Error> {
let mu... | let passwd = Passwd::prompt_new()
.chain_err(|| skey_path )?;
let (pkey_file, mut skey_file) = SecretKeyFile::new();
| random_line_split |
lib.rs | mod error;
use std::fs::{self, File, OpenOptions};
use std::io::{self, stdin, stdout, Write};
use std::ops::Deref;
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};
use error_chain::bail;
use hex::FromHex;
use lazy_static::lazy_static;
use seckey::SecBytes;
use serde::{Deserialize, Serialize};
us... |
/// Get a SecretKeyFile from a path. If the file is encrypted, prompt for a password on stdin.
pub fn get_skey(skey_path: &Path) -> Result<SecretKeyFile, Error> {
prompt_skey(skey_path, "Passphrase for")
}
/// Open, decrypt, re-encrypt with a different passphrase from stdin, and save the newly encrypted
/// sec... | {
let mut key_file = SecretKeyFile::open(skey_path)?;
if key_file.is_encrypted() {
let passwd = Passwd::prompt(&format!("{} {}: ", prompt.as_ref(), skey_path.display()))
.chain_err(|| skey_path )?;
key_file.decrypt(passwd)
.chain_err(|| skey_path )?;
}
Ok(key... | identifier_body |
lib.rs | mod error;
use std::fs::{self, File, OpenOptions};
use std::io::{self, stdin, stdout, Write};
use std::ops::Deref;
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};
use error_chain::bail;
use hex::FromHex;
use lazy_static::lazy_static;
use seckey::SecBytes;
use serde::{Deserialize, Serialize};
us... | (&mut self) -> Option<sign::SecretKey> {
match &self.skey {
SKey::Plain(skey) => Some(skey.clone()),
SKey::Cipher(_) => None,
}
}
/// Returns `None` if the secret key is encrypted.
pub fn public_key_file(&self) -> Option<PublicKeyFile> {
Some(PublicKeyFil... | key | identifier_name |
main.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... |
fn read_tls(&self, buf: &mut [u8]) -> isize {
let mut retval = -1;
let result = unsafe {
tls_client_read(self.enclave_id,
&mut retval,
self.tlsclient_id,
buf.as_mut_ptr() as * mut c_void,
... | {
let retval = unsafe {
tls_client_close(self.enclave_id, self.tlsclient_id)
};
if retval != sgx_status_t::SGX_SUCCESS {
println!("[-] ECALL Enclave [tls_client_close] Failed {}!", retval);
}
} | identifier_body |
main.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | (&self) -> bool {
let mut retval = -1;
let result = unsafe {
tls_client_wants_read(self.enclave_id,
&mut retval,
self.tlsclient_id)
};
match result {
sgx_status_t::SGX_SUCCESS => { },
... | wants_read | identifier_name |
main.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... |
if self.is_closed() {
println!("Connection closed");
return false;
}
self.reregister(poll);
true
}
}
impl TlsClient {
fn new(enclave_id: sgx_enclave_id_t, sock: TcpStream, hostname: &str, cert: &str) -> Option<TlsClient> {
println!("[+] TlsCl... | {
self.do_write();
} | conditional_block |
main.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | let result = unsafe {
tls_client_write(self.enclave_id,
&mut retval,
self.tlsclient_id,
buf.as_ptr() as * const c_void,
buf.len() as c_int)
};
match result {
... | }
}
fn write_tls(&self, buf: &[u8]) -> isize {
let mut retval = -1; | random_line_split |
mod.rs | // MIT/Apache2 License
//! This module defines the `Display` object, which acts as a connection to the X11 server, and the
//! `Connection` trait, which the `Display` object abstracts itself over. See the documentation for
//! these objects for more information.
use crate::{
auth_info::AuthInfo,
auto::{
... |
#[cfg(feature = "std")]
impl DisplayConnection {
/// Create a new connection to the X server, given an optional name and authorization information.
#[inline]
pub fn create(name: Option<Cow<'_, str>>, auth_info: Option<AuthInfo>) -> crate::Result<Self> {
let connection = name::NameConnection::connec... | /// A variant of `Display` that uses X11's default connection mechanisms to connect to the server. In
/// most cases, you should be using this over any variant of `Display`.
#[cfg(feature = "std")]
pub type DisplayConnection = Display<name::NameConnection>; | random_line_split |
mod.rs | // MIT/Apache2 License
//! This module defines the `Display` object, which acts as a connection to the X11 server, and the
//! `Connection` trait, which the `Display` object abstracts itself over. See the documentation for
//! these objects for more information.
use crate::{
auth_info::AuthInfo,
auto::{
... | (&mut self) -> crate::Result<Event> {
loop {
match self.event_queue.pop_front() {
Some(event) => break Ok(event),
None => self.wait_async().await?,
}
}
}
/// If there is an event currently in the queue that matches the predicate, returns t... | wait_for_event_async | identifier_name |
server.rs | //
// Copyright (c) Pirmin Kalberer. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
use crate::core::config::ApplicationCfg;
use crate::mvt_service::MvtService;
use crate::runtime_config::{config_from_args, service_from_args};
use crate::st... | .service(
web::resource("/{tileset}/{z}/{x}/{y}.pbf").route(
web::route()
.guard(guard::Any(guard::Get()).or(guard::Head()))
.to(tile_pbf),
),
);
if mvt_viewer {
app = app.service... | random_line_split | |
server.rs | //
// Copyright (c) Pirmin Kalberer. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
use crate::core::config::ApplicationCfg;
use crate::mvt_service::MvtService;
use crate::runtime_config::{config_from_args, service_from_args};
use crate::st... | (
config: web::Data<ApplicationCfg>,
service: web::Data<MvtService>,
params: web::Path<(String, u8, u32, u32)>,
req: HttpRequest,
) -> Result<HttpResponse> {
let params = params.into_inner();
let tileset = params.0;
let z = params.1;
let x = params.2;
let y = params.3;
let gzip =... | tile_pbf | identifier_name |
server.rs | //
// Copyright (c) Pirmin Kalberer. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
use crate::core::config::ApplicationCfg;
use crate::mvt_service::MvtService;
use crate::runtime_config::{config_from_args, service_from_args};
use crate::st... | Some(tile) => {
let mut r = HttpResponse::Ok();
r.content_type("application/x-protobuf");
if gzip {
// data is already gzip compressed
r.insert_header(header::ContentEncoding::Gzip);
}
let cache_max_age = config.webserve... | {
let params = params.into_inner();
let tileset = params.0;
let z = params.1;
let x = params.2;
let y = params.3;
let gzip = req
.headers()
.get(header::ACCEPT_ENCODING)
.and_then(|headerval| {
headerval
.to_str()
.ok()
... | identifier_body |
interaction.rs | use bevy_math::{Mat4, Quat, Vec2, Vec3};
use bevy_utils::Duration;
use serde::{Deserialize, Serialize};
use std::{
collections::HashMap,
ops::{Deref, Mul},
};
// Note: indices follow WebXR convention. OpenXR's palm joint is missing, but it can be retrieved
// using `XrTrackingSource::hands_pose()`.
pub const X... |
/// Returns poses that can be used to render a target ray or cursor. The ray is along -Z. The
/// behavior is vendor-specific. Index 0 corresponds to the left hand, index 1 corresponds to
/// the right hand.
pub fn hand_target_ray(&self) -> [Option<XrPose>; 2] {
self.inner.hands_target_ray()
... | {
self.inner.hands_skeleton_pose()
} | identifier_body |
interaction.rs | use bevy_math::{Mat4, Quat, Vec2, Vec3};
use bevy_utils::Duration;
use serde::{Deserialize, Serialize};
use std::{
collections::HashMap,
ops::{Deref, Mul},
};
// Note: indices follow WebXR convention. OpenXR's palm joint is missing, but it can be retrieved
// using `XrTrackingSource::hands_pose()`.
pub const X... | else {
XrButtonState::Default
}
}
pub fn button_touched(&self, action: &str) -> bool {
if let Some(XrActionState::Button { state,.. }) = self.current_states.get(action) {
*state!= XrButtonState::Default
} else {
false
}
}
pub fn butt... | {
*state
} | conditional_block |
interaction.rs | use bevy_math::{Mat4, Quat, Vec2, Vec3};
use bevy_utils::Duration;
use serde::{Deserialize, Serialize};
use std::{
collections::HashMap,
ops::{Deref, Mul},
};
// Note: indices follow WebXR convention. OpenXR's palm joint is missing, but it can be retrieved
// using `XrTrackingSource::hands_pose()`.
pub const X... | {
pub left_hand: Option<String>,
pub right_hand: Option<String>,
}
| XrProfiles | identifier_name |
interaction.rs | use bevy_math::{Mat4, Quat, Vec2, Vec3};
use bevy_utils::Duration;
use serde::{Deserialize, Serialize};
use std::{
collections::HashMap,
ops::{Deref, Mul},
};
// Note: indices follow WebXR convention. OpenXR's palm joint is missing, but it can be retrieved
// using `XrTrackingSource::hands_pose()`.
pub const X... | }
pub fn binary_value(&self, action: &str) -> bool {
if let Some(XrActionState::Binary(value)) = self.current_states.get(action) {
*value
} else {
self.button_pressed(action)
}
}
pub fn scalar_value(&self, action: &str) -> f32 {
if let Some(XrAct... | pub fn button_just_unpressed(&self, action: &str) -> bool {
self.button_states(action)
.map(|(cur, prev)| cur != XrButtonState::Pressed && prev == XrButtonState::Pressed)
.unwrap_or(false) | random_line_split |
futures.rs | //! A futures executor as an event source
//!
//! Only available with the `executor` cargo feature of `calloop`.
//!
//! This executor is intended for light futures, which will be polled as part of your
//! event loop. Such futures may be waiting for IO, or for some external computation on an
//! other thread for examp... | (&mut self, poll: &mut Poll) -> crate::Result<()> {
self.ping.unregister(poll)?;
Ok(())
}
}
/// An error arising from processing events in an async executor event source.
#[derive(thiserror::Error, Debug)]
pub enum ExecutorError {
/// Error while reading new futures added via [`Scheduler::sched... | unregister | identifier_name |
futures.rs | //! A futures executor as an event source
//!
//! Only available with the `executor` cargo feature of `calloop`.
//!
//! This executor is intended for light futures, which will be polled as part of your
//! event loop. Such futures may be waiting for IO, or for some external computation on an
//! other thread for examp... | ))
}
impl<T> EventSource for Executor<T> {
type Event = T;
type Metadata = ();
type Ret = ();
type Error = ExecutorError;
fn process_events<F>(
&mut self,
readiness: Readiness,
token: Token,
mut callback: F,
) -> Result<PostAction, Self::Error>
where
... | {
let (sender, incoming) = mpsc::channel();
let (wake_up, ping) = make_ping()?;
let state = Rc::new(State {
incoming,
active_tasks: RefCell::new(Some(Slab::new())),
sender: Arc::new(Sender {
sender: Mutex::new(sender),
wake_up,
notified: AtomicBoo... | identifier_body |
futures.rs | //! A futures executor as an event source
//!
//! Only available with the `executor` cargo feature of `calloop`.
//!
//! This executor is intended for light futures, which will be polled as part of your
//! event loop. Such futures may be waiting for IO, or for some external computation on an
//! other thread for examp... | pub struct Executor<T> {
/// Shared state between the executor and the scheduler.
state: Rc<State<T>>,
/// Notifies us when the executor is woken up.
ping: PingSource,
}
/// A scheduler to send futures to an executor
#[derive(Clone, Debug)]
pub struct Scheduler<T> {
/// Shared state between the ex... |
/// A future executor as an event source
#[derive(Debug)] | random_line_split |
futures.rs | //! A futures executor as an event source
//!
//! Only available with the `executor` cargo feature of `calloop`.
//!
//! This executor is intended for light futures, which will be polled as part of your
//! event loop. Such futures may be waiting for IO, or for some external computation on an
//! other thread for examp... |
// If the executor is already awake, don't bother waking it up again.
if self.notified.swap(true, Ordering::SeqCst) {
return;
}
// Wake the executor.
self.wake_up.ping();
}
}
impl<T> Drop for Executor<T> {
fn drop(&mut self) {
let active_tasks = se... | {
// The runnable must be dropped on its origin thread, since the original future might be
// !Send. This channel immediately sends it back to the Executor, which is pinned to the
// origin thread. The executor's Drop implementation will force all of the runnables to be
/... | conditional_block |
path_through.rs |
// This example is another version of `passthrough.rs` that uses the
// path strings instead of the file descriptors with `O_PATH` flag
// for referencing the underlying file entries.
// It has the advantage of being able to use straightforward the
// *standard* filesystem APIs, but also the additional path resolution... | {
use futures::io::AsyncReadExt;
reader.read_to_end(&mut buf).await?;
}
use tokio::io::AsyncReadExt;
let mut buf = &buf[..];
let mut buf = (&mut buf).take(op.size() as u64);
let written = tokio::io::copy(&mut buf, &mut *file).await?;
Ok(R... | let mut buf = Vec::with_capacity(op.size() as usize); | random_line_split |
path_through.rs | // This example is another version of `passthrough.rs` that uses the
// path strings instead of the file descriptors with `O_PATH` flag
// for referencing the underlying file entries.
// It has the advantage of being able to use straightforward the
// *standard* filesystem APIs, but also the additional path resolution
... | (&self, path: &Path) -> Option<Arc<Mutex<INode>>> {
let ino = self.path_to_ino.get(path).copied()?;
self.get(ino)
}
}
struct VacantEntry<'a> {
table: &'a mut INodeTable,
ino: Ino,
}
impl VacantEntry<'_> {
fn insert(mut self, inode: INode) {
let path = inode.path.clone();
... | get_path | identifier_name |
lib.rs | // Copyright 2021-2023 Vector 35 Inc.
//
// 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 agreed to... | {
register(
"DWARF Dump",
"Show embedded DWARF info as a tree structure for you to navigate",
DWARFDump {},
);
true
} | identifier_body | |
lib.rs | // Copyright 2021-2023 Vector 35 Inc.
//
// 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 agreed to... | else {
let attr_string = format!("{:?}", attr.value());
attr_line.push(InstructionTextToken::new(
BnString::new(attr_string),
InstructionTextTokenContents::Text,
));
}
disassembly_lines.push(DisassemblyTextLine::from(attr_line));
}... | {
let value_string = format!("{}", value);
attr_line.push(InstructionTextToken::new(
BnString::new(value_string),
InstructionTextTokenContents::Integer(value as u64),
));
} | conditional_block |
lib.rs | // Copyright 2021-2023 Vector 35 Inc.
//
// 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 agreed to... | // See the License for the specific language governing permissions and
// limitations under the License.
use binaryninja::{
binaryview::{BinaryView, BinaryViewExt},
command::{register, Command},
disassembly::{DisassemblyTextLine, InstructionTextToken, InstructionTextTokenContents},
flowgraph::{BranchTy... | // distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | random_line_split |
lib.rs | // Copyright 2021-2023 Vector 35 Inc.
//
// 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 agreed to... | <R: Reader>(
view: &BinaryView,
dwarf: &Dwarf<R>,
unit: &Unit<R>,
die_node: &DebuggingInformationEntry<R>,
) -> Vec<DisassemblyTextLine> {
let mut disassembly_lines: Vec<DisassemblyTextLine> = Vec::with_capacity(10); // This is an estimate so "most" things won't need to resize
let label_value =... | get_info_string | identifier_name |
mod.rs | use std::{
cell::{Ref, RefCell},
ops::RangeInclusive,
rc::Rc,
};
pub type Time = f32;
use crate::Pose;
/// Aggregate of [`ColumnData`] that can only be added and not deleted.
/// Length of all [`ColumnData`] are equal, making this effectively a 2D table.
pub type DataSet<T = f32> = Vec<ColumnData<T>>;
//... | (timeseries: TimeSeries<T>) -> Self {
Self {
time: timeseries.time,
data: vec![timeseries.data],
}
}
}
impl<T: Clone> TimeTable<T> {
pub fn new(time: Vec<Time>, data: Vec<T>) -> Self {
TimeSeries::new(time, data).into()
}
#[allow(dead_code)]
pub fn g... | from_timeseries | identifier_name |
mod.rs | use std::{
cell::{Ref, RefCell},
ops::RangeInclusive,
rc::Rc,
};
pub type Time = f32;
use crate::Pose;
/// Aggregate of [`ColumnData`] that can only be added and not deleted.
/// Length of all [`ColumnData`] are equal, making this effectively a 2D table.
pub type DataSet<T = f32> = Vec<ColumnData<T>>;
//... |
pub fn get_range_raw(&self, start: Time, end: Time) -> Option<Vec<Time>> {
self.get_range(start, end)
.map(|range| self.vec[range].to_vec())
}
/// Length of the time vector
pub fn len(&self) -> usize {
self.vec.len()
}
}
#[derive(Debug, Default)]
pub struct TimeTable<T... | {
if start < end {
if let Some(start) = self.get_index(start) {
if let Some(end) = self.get_index_under(end) {
return Some(start..=end);
}
}
}
None
} | identifier_body |
mod.rs | use std::{
cell::{Ref, RefCell},
ops::RangeInclusive,
rc::Rc,
};
pub type Time = f32;
use crate::Pose;
/// Aggregate of [`ColumnData`] that can only be added and not deleted.
/// Length of all [`ColumnData`] are equal, making this effectively a 2D table.
pub type DataSet<T = f32> = Vec<ColumnData<T>>;
//... |
}
/// Similar to [`get_index`], but only returns time index that is smaller than the input time.
/// This is useful when making sure the returned time index never exceeds the given time, as
/// in [`get_range`]
///
/// [`get_index`]: Self::get_index
/// [`get_range`]: Self::get_range
f... | {
// unwrap here is ok, since time_changed always ensures cache is not None
Some(self.cache.unwrap().1)
} | conditional_block |
mod.rs | use std::{
cell::{Ref, RefCell},
ops::RangeInclusive,
rc::Rc,
};
pub type Time = f32;
use crate::Pose;
/// Aggregate of [`ColumnData`] that can only be added and not deleted.
/// Length of all [`ColumnData`] are equal, making this effectively a 2D table.
pub type DataSet<T = f32> = Vec<ColumnData<T>>;
//... | // self.cache = Some((time, index));
index
})
} else {
// unwrap here is ok, since time_changed always ensures cache is not None
Some(self.cache.unwrap().1)
}
}
/// Similar to [`get_index`], but only returns time index that is ... | if self.time_changed(time) {
self.vec.iter().position(|&t| t >= time).map(|index| { | random_line_split |
main.rs | // Copyright 2021 The Simlin Authors. All rights reserved.
// Use of this source code is governed by the Apache License,
// Version 2.0, that can be found in the LICENSE file.
use std::fs::File;
use std::io::{BufReader, Write};
use std::rc::Rc;
use pico_args::Arguments;
use simlin_compat::engine::builtins::Loc;
use ... | else {
let results = simulate(&project);
if!args.is_no_output {
results.print_tsv();
}
}
}
| {
if args.reference.is_none() {
eprintln!("missing required argument --reference FILE");
std::process::exit(1);
}
let ref_path = args.reference.unwrap();
let reference = load_csv(&ref_path, b'\t').unwrap();
let results = simulate(&project);
result... | conditional_block |
main.rs | // Copyright 2021 The Simlin Authors. All rights reserved.
// Use of this source code is governed by the Apache License,
// Version 2.0, that can be found in the LICENSE file.
use std::fs::File;
use std::io::{BufReader, Write};
use std::rc::Rc;
use pico_args::Arguments;
use simlin_compat::engine::builtins::Loc;
use ... |
fn main() {
let args = match parse_args() {
Ok(args) => args,
Err(err) => {
eprintln!("error: {}", err);
usage();
}
};
let file_path = args.path.unwrap_or_else(|| "/dev/stdin".to_string());
let file = File::open(&file_path).unwrap();
let mut reader = ... | vm.into_results()
} | random_line_split |
main.rs | // Copyright 2021 The Simlin Authors. All rights reserved.
// Use of this source code is governed by the Apache License,
// Version 2.0, that can be found in the LICENSE file.
use std::fs::File;
use std::io::{BufReader, Write};
use std::rc::Rc;
use pico_args::Arguments;
use simlin_compat::engine::builtins::Loc;
use ... | () ->! {
let argv0 = std::env::args()
.next()
.unwrap_or_else(|| "<mdl>".to_string());
die!(
concat!(
"mdl {}: Simulate system dynamics models.\n\
\n\
USAGE:\n",
" {} [SUBCOMMAND] [OPTION...] PATH\n",
"\n\
OPTIONS:\n",
... | usage | identifier_name |
ui.rs | use std::collections::{HashSet, HashMap, VecDeque};
use std::any::{Any, TypeId};
use std::rc::Rc;
use std::cell::RefCell;
use cassowary::Constraint;
use cassowary::strength::*;
use glutin;
use window::Window;
use app::App;
use widget::{WidgetRef, WidgetBuilder};
use layout::{LimnSolver, LayoutChanged, LayoutVars, Ex... |
pub fn needs_redraw(&self) -> bool {
self.needs_redraw
}
pub(super) fn draw_if_needed(&mut self) {
if self.needs_redraw {
self.draw();
self.needs_redraw = false;
}
}
fn draw(&mut self) {
let window_size = self.window.borrow_mut().size_f32()... | {
self.needs_redraw = true;
} | identifier_body |
ui.rs | use std::collections::{HashSet, HashMap, VecDeque};
use std::any::{Any, TypeId};
use std::rc::Rc;
use std::cell::RefCell;
use cassowary::Constraint;
use cassowary::strength::*;
use glutin;
use window::Window;
use app::App;
use widget::{WidgetRef, WidgetBuilder};
use layout::{LimnSolver, LayoutChanged, LayoutVars, Ex... | (root: WidgetRef) -> Self {
WidgetsDfsPostReverse {
stack: vec![root],
discovered: HashSet::new(),
finished: HashSet::new(),
}
}
}
impl Iterator for WidgetsDfsPostReverse {
type Item = WidgetRef;
fn next(&mut self) -> Option<WidgetRef> {
while let... | new | identifier_name |
ui.rs | use std::collections::{HashSet, HashMap, VecDeque};
use std::any::{Any, TypeId};
use std::rc::Rc;
use std::cell::RefCell;
use cassowary::Constraint;
use cassowary::strength::*;
use glutin;
use window::Window;
use app::App;
use widget::{WidgetRef, WidgetBuilder};
use layout::{LimnSolver, LayoutChanged, LayoutVars, Ex... |
}
None
}
}
// Iterates in reverse of draw order, that is, depth first post order,
// with siblings in reverse of insertion order
struct WidgetsDfsPostReverse {
stack: Vec<WidgetRef>,
discovered: HashSet<WidgetRef>,
finished: HashSet<WidgetRef>,
}
impl WidgetsDfsPostReverse {
fn ne... | {
return Some(widget_ref.clone());
} | conditional_block |
ui.rs | use std::collections::{HashSet, HashMap, VecDeque};
use std::any::{Any, TypeId};
use std::rc::Rc;
use std::cell::RefCell;
use cassowary::Constraint;
use cassowary::strength::*;
use glutin;
use window::Window;
use app::App;
use widget::{WidgetRef, WidgetBuilder};
use layout::{LimnSolver, LayoutChanged, LayoutVars, Ex... | dfs: WidgetsDfsPostReverse,
}
impl WidgetsUnderCursor {
fn new(point: Point, root: WidgetRef) -> Self {
WidgetsUnderCursor {
point: point,
dfs: WidgetsDfsPostReverse::new(root),
}
}
}
impl Iterator for WidgetsUnderCursor {
type Item = WidgetRef;
fn next(&mut ... | }
pub struct WidgetsUnderCursor {
point: Point, | random_line_split |
check.rs | //! Consensus check functions
use std::{collections::HashSet, sync::Arc};
use chrono::{DateTime, Utc};
use zebra_chain::{
amount::{Amount, Error as AmountError, NonNegative},
block::{Block, Hash, Header, Height},
parameters::{Network, NetworkUpgrade},
transaction,
work::{difficulty::ExpandedDiffi... |
/// Returns `Ok(())` if the block subsidy in `block` is valid for `network`
///
/// [3.9]: https://zips.z.cash/protocol/protocol.pdf#subsidyconcepts
pub fn subsidy_is_valid(block: &Block, network: Network) -> Result<(), BlockError> {
let height = block.coinbase_height().ok_or(SubsidyError::NoCoinbase)?;
let c... | {
// # Consensus
//
// > `solution` MUST represent a valid Equihash solution.
//
// https://zips.z.cash/protocol/protocol.pdf#blockheader
header.solution.check(header)
} | identifier_body |
check.rs | //! Consensus check functions
use std::{collections::HashSet, sync::Arc};
use chrono::{DateTime, Utc};
use zebra_chain::{
amount::{Amount, Error as AmountError, NonNegative},
block::{Block, Hash, Header, Height},
parameters::{Network, NetworkUpgrade},
transaction,
work::{difficulty::ExpandedDiffi... | (
block: &Block,
network: Network,
block_miner_fees: Amount<NonNegative>,
) -> Result<(), BlockError> {
let height = block.coinbase_height().ok_or(SubsidyError::NoCoinbase)?;
let coinbase = block.transactions.get(0).ok_or(SubsidyError::NoCoinbase)?;
let transparent_value_balance: Amount = subsi... | miner_fees_are_valid | identifier_name |
check.rs | //! Consensus check functions
use std::{collections::HashSet, sync::Arc};
use chrono::{DateTime, Utc};
use zebra_chain::{
amount::{Amount, Error as AmountError, NonNegative},
block::{Block, Hash, Header, Height},
parameters::{Network, NetworkUpgrade},
transaction,
work::{difficulty::ExpandedDiffi... | //
// https://zips.z.cash/protocol/protocol.pdf#blockheader
header.solution.check(header)
}
/// Returns `Ok(())` if the block subsidy in `block` is valid for `network`
///
/// [3.9]: https://zips.z.cash/protocol/protocol.pdf#subsidyconcepts
pub fn subsidy_is_valid(block: &Block, network: Network) -> Result... | // # Consensus
//
// > `solution` MUST represent a valid Equihash solution. | random_line_split |
check.rs | //! Consensus check functions
use std::{collections::HashSet, sync::Arc};
use chrono::{DateTime, Utc};
use zebra_chain::{
amount::{Amount, Error as AmountError, NonNegative},
block::{Block, Hash, Header, Height},
parameters::{Network, NetworkUpgrade},
transaction,
work::{difficulty::ExpandedDiffi... |
}
/// Returns `Ok(())` if the miner fees consensus rule is valid.
///
/// [7.1.2]: https://zips.z.cash/protocol/protocol.pdf#txnconsensus
pub fn miner_fees_are_valid(
block: &Block,
network: Network,
block_miner_fees: Amount<NonNegative>,
) -> Result<(), BlockError> {
let height = block.coinbase_heigh... | {
// Future halving, with no founders reward or funding streams
Ok(())
} | conditional_block |
alias.rs | err(cx, loc.span, "can not move into a by-reference binding");
}
let root = expr_root(cx, init.expr, false);
let root_var = path_def_id(cx, root.ex);
if is_none(root_var) {
err(cx, loc.span, "a reference binding can't be \
rooted in a temporar... | let ty = ty::node_id_to_type(tcx, pat.id);
for f in fs {
let m = ty::get_field(tcx, ty, f.ident).mt.mut != ast::imm;
walk(tcx, m ? some(contains(ty)) : mut, f.pat, set); | random_line_split | |
alias.rs | let f_may_close =
alt f.node {
ast::expr_path(_) { def_is_local(cx.tcx.def_map.get(f.id)) }
_ { true }
};
if f_may_close {
let i = 0u;
for b in bindings {
let unsfe = vec::len(b.unsafe_tys) > 0u;
alt b.root_var {
some(rid) {... | {
cx.tcx.sess.span_err(sp, err);
} | conditional_block | |
alias.rs | err(*cx, sp, "can not pass a dynamically-sized type by value");
}
}
// Blocks need to obey any restrictions from the enclosing scope, and may
// be called multiple times.
let proto = ty::ty_fn_proto(cx.tcx, fty);
if proto == ast::proto_block {
check_loop(*cx, sc) {|| v.visit_block... | }
fn check_lval(cx: @ctx, dest: @ast::expr, sc: scope, v: vt<scope>) {
alt dest.node {
ast::expr_path(p) {
let def = cx.tcx.def_map.get(dest.id);
let dnum = ast_util::def_id_of_def(def).node;
for b in sc.bs {
if b.root_var == some(dnum) {
let inv = @{reaso... | {
let def = cx.tcx.def_map.get(id);
if !def_is_local(def) { ret; }
let my_defnum = ast_util::def_id_of_def(def).node;
let my_local_id = local_id_of_node(cx, my_defnum);
let var_t = ty::expr_ty(cx.tcx, ex);
for b in sc.bs {
// excludes variables introduced since the alias was made
... | identifier_body |
alias.rs | scope, f: @ast::expr, args: [@ast::expr])
-> [binding] {
let fty = ty::expr_ty(cx.tcx, f);
let arg_ts = ty::ty_fn_args(cx.tcx, fty);
let mut_roots: [{arg: uint, node: node_id}] = [];
let bindings = [];
let i = 0u;
for arg_t: ty::arg in arg_ts {
let arg = args[i];
let root = ... | unsafe_set | identifier_name | |
main.rs | #[macro_use]
extern crate failure;
use nbted::unstable::{data, read, string_read, string_write, write};
use nbted::Result;
use std::env;
use std::fs::File;
use std::io;
use std::io::{BufReader, BufWriter};
use std::path::Path;
use std::process::exit;
use std::process::Command;
use getopts::Options;
use tempdir::Tem... |
/// Main entrypoint for program.
///
/// Returns an integer representing the program's exit status.
fn run_cmdline() -> Result<i32> {
let args: Vec<String> = env::args().collect();
let mut opts = Options::new();
let _: &Options = opts.optflagopt("e", "edit", "edit a NBT file with your $EDITOR.
If [FI... | {
match run_cmdline() {
Ok(ret) => {
exit(ret);
}
Err(e) => {
eprintln!("{}", e.backtrace());
eprintln!("Error: {}", e);
for e in e.iter_chain().skip(1) {
eprintln!(" caused by: {}", e);
}
eprintln!("F... | identifier_body |
main.rs | #[macro_use]
extern crate failure;
use nbted::unstable::{data, read, string_read, string_write, write};
use nbted::Result;
use std::env;
use std::fs::File;
use std::io;
use std::io::{BufReader, BufWriter};
use std::path::Path;
use std::process::exit;
use std::process::Command;
use getopts::Options;
use tempdir::Tem... | Some(x) => {
let mut x = x.to_os_string();
x.push(".txt");
x
}
None => bail!("Error reading file name"),
};
let tmp_path = tmpdir.path().join(tmp);
{
let mut f = File::create(&tmp_path).context("Unable to create temporary file")?;
... | * to the temporary file */
let tmpdir = TempDir::new("nbted").context("Unable to create temporary directory")?;
let tmp = match Path::new(input).file_name() { | random_line_split |
main.rs | #[macro_use]
extern crate failure;
use nbted::unstable::{data, read, string_read, string_write, write};
use nbted::Result;
use std::env;
use std::fs::File;
use std::io;
use std::io::{BufReader, BufWriter};
use std::path::Path;
use std::process::exit;
use std::process::Command;
use getopts::Options;
use tempdir::Tem... | else {
bail!("Internal error: No action selected. (Please report this.)");
}
}
/// When the user wants to edit a specific file in place
///
/// Returns an integer representing the program's exit status.
fn edit(input: &str, output: &str) -> Result<i32> {
/* First we read the NBT data from the input */... | {
edit(&input, &output)
} | conditional_block |
main.rs | #[macro_use]
extern crate failure;
use nbted::unstable::{data, read, string_read, string_write, write};
use nbted::Result;
use std::env;
use std::fs::File;
use std::io;
use std::io::{BufReader, BufWriter};
use std::path::Path;
use std::process::exit;
use std::process::Command;
use getopts::Options;
use tempdir::Tem... | (tmp_path: &Path) -> Result<data::NBTFile> {
let editor = match env::var("VISUAL") {
Ok(x) => x,
Err(_) => match env::var("EDITOR") {
Ok(x) => x,
Err(_) => bail!("Unable to find $EDITOR"),
},
};
let mut cmd = Command::new(editor);
let _: &mut Command = cm... | open_editor | identifier_name |
rtio.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub fn new<'a>(io: &'a mut IoFactory) -> LocalIo<'a> {
LocalIo { factory: io }
}
/// Returns the underlying I/O factory as a trait reference.
#[inline]
pub fn get<'a>(&'a mut self) -> &'a mut IoFactory {
// FIXME(pcwalton): I think this is actually sound? Could borrow check
... | {
match LocalIo::borrow() {
None => Err(io::standard_error(io::IoUnavailable)),
Some(mut io) => f(io.get()),
}
} | identifier_body |
rtio.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | fn id(&self) -> libc::pid_t;
fn kill(&mut self, signal: int) -> IoResult<()>;
fn wait(&mut self) -> ProcessExit;
}
pub trait RtioPipe {
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint>;
fn write(&mut self, buf: &[u8]) -> IoResult<()>;
fn clone(&self) -> ~RtioPipe:Send;
}
pub trait RtioUnix... | fn truncate(&mut self, offset: i64) -> IoResult<()>;
}
pub trait RtioProcess { | random_line_split |
rtio.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
/// Path to file to be opened
pub path: Path,
/// Flags for file access mode (as per open(2))
pub flags: int,
/// File creation mode, ignored unless O_CREAT is passed as part of flags
pub mode: int
}
/// Description of what to do when a file handle is closed
pub enum CloseBehavior {
/// ... | FileOpenConfig | identifier_name |
traffic_signal.rs | use crate::options::TrafficSignalStyle;
use crate::render::{DrawCtx, DrawTurnGroup, BIG_ARROW_THICKNESS};
use crate::ui::UI;
use ezgui::{
Button, Color, Composite, DrawBoth, EventCtx, GeomBatch, GfxCtx, Line, ManagedWidget,
ModalMenu, Outcome, Text,
};
use geom::{Circle, Distance, Duration, Polygon};
use map_mo... | batch.push(
protected_color,
signal.turn_groups[g]
.geom
.make_arrow(BIG_ARROW_THICKNESS * 2.0)
.unwrap(),
);
}
}
... | {
let protected_color = ctx
.cs
.get_def("turn protected by traffic signal", Color::GREEN);
let yield_color = ctx.cs.get_def(
"turn that can yield by traffic signal",
Color::rgba(255, 105, 180, 0.8),
);
let signal = ctx.map.get_traffic_signal(i);
for (id, crosswalk) ... | identifier_body |
traffic_signal.rs | use crate::options::TrafficSignalStyle;
use crate::render::{DrawCtx, DrawTurnGroup, BIG_ARROW_THICKNESS};
use crate::ui::UI;
use ezgui::{
Button, Color, Composite, DrawBoth, EventCtx, GeomBatch, GfxCtx, Line, ManagedWidget,
ModalMenu, Outcome, Text,
};
use geom::{Circle, Distance, Duration, Polygon};
use map_mo... | .iter()
.map(|r| ui.primary.map.get_r(*r).get_name())
.collect::<BTreeSet<_>>();
let len = road_names.len();
// TODO Some kind of reusable TextStyle thing
// TODO Need to wrap this
txt.add(Line("").roboto().size(21).fg(Color::WHITE.alpha(0.54)));
... | .roads | random_line_split |
traffic_signal.rs | use crate::options::TrafficSignalStyle;
use crate::render::{DrawCtx, DrawTurnGroup, BIG_ARROW_THICKNESS};
use crate::ui::UI;
use ezgui::{
Button, Color, Composite, DrawBoth, EventCtx, GeomBatch, GfxCtx, Line, ManagedWidget,
ModalMenu, Outcome, Text,
};
use geom::{Circle, Distance, Duration, Polygon};
use map_mo... |
TurnPriority::Banned => {}
}
}
}
}
if time_left.is_none() {
return;
}
let radius = Distance::meters(0.5);
let box_width = (2.5 * radius).inner_meters();
let box_height = (6.5 * radius).inner_meters();
let center = ctx.map.get... | {
batch.extend(
yield_color,
turn.geom
.make_arrow_outline(
BIG_ARROW_THICKNESS * 2.0,
BIG_ARROW_THICKNESS / 2.0,
... | conditional_block |
traffic_signal.rs | use crate::options::TrafficSignalStyle;
use crate::render::{DrawCtx, DrawTurnGroup, BIG_ARROW_THICKNESS};
use crate::ui::UI;
use ezgui::{
Button, Color, Composite, DrawBoth, EventCtx, GeomBatch, GfxCtx, Line, ManagedWidget,
ModalMenu, Outcome, Text,
};
use geom::{Circle, Distance, Duration, Polygon};
use map_mo... | (&mut self, ctx: &mut EventCtx, ui: &mut UI, menu: &mut ModalMenu) {
if self.current_phase!= 0 && menu.action("select previous phase") {
self.change_phase(self.current_phase - 1, ui, ctx);
}
if self.current_phase!= ui.primary.map.get_traffic_signal(self.i).phases.len() - 1
... | event | identifier_name |
util.rs | // Copyright 2022 TiKV Project Authors. Licensed under Apache-2.0.
use std::{fmt::Write, path::Path, sync::Arc, thread, time::Duration};
use encryption_export::{data_key_manager_from_config, DataKeyManager};
use engine_rocks::{RocksEngine, RocksStatistics};
use engine_test::raft::RaftTestEngine;
use engine_traits::{C... |
let base_tick_interval = cluster.cfg.raft_store.raft_base_tick_interval.0;
if let Some(election_ticks) = election_ticks {
cluster.cfg.raft_store.raft_election_timeout_ticks = election_ticks;
}
let election_ticks = cluster.cfg.raft_store.raft_election_timeout_ticks as u32;
let election_timeo... | {
cluster.cfg.raft_store.raft_base_tick_interval = ReadableDuration::millis(base_tick_ms);
} | conditional_block |
util.rs | // Copyright 2022 TiKV Project Authors. Licensed under Apache-2.0.
use std::{fmt::Write, path::Path, sync::Arc, thread, time::Duration};
use encryption_export::{data_key_manager_from_config, DataKeyManager};
use engine_rocks::{RocksEngine, RocksStatistics};
use engine_test::raft::RaftTestEngine;
use engine_traits::{C... |
election_timeout
}
pub fn wait_for_synced(
cluster: &mut Cluster<ServerCluster<RocksEngine>, RocksEngine>,
node_id: u64,
region_id: u64,
) {
let mut storage = cluster
.sim
.read()
.unwrap()
.storages
.get(&node_id)
.unwrap()
.clone();
let leader... | // check < abnormal < max leader missing duration.
cluster.cfg.raft_store.peer_stale_state_check_interval = ReadableDuration(election_timeout * 3);
cluster.cfg.raft_store.abnormal_leader_missing_duration =
ReadableDuration(election_timeout * 4);
cluster.cfg.raft_store.max_leader_missing_duration... | random_line_split |
util.rs | // Copyright 2022 TiKV Project Authors. Licensed under Apache-2.0.
use std::{fmt::Write, path::Path, sync::Arc, thread, time::Duration};
use encryption_export::{data_key_manager_from_config, DataKeyManager};
use engine_rocks::{RocksEngine, RocksStatistics};
use engine_test::raft::RaftTestEngine;
use engine_traits::{C... | let (k, v) = data_set.choose(&mut rng).unwrap();
assert_eq!(cluster.get_cf(cf, k).unwrap(), *v);
}
// Empty keys means the whole range.
cluster.must_delete_range_cf(cf, b"", b"");
for _ in 0..50 {
let k = &data_set.choose(&mut rng).unwrap().0;
assert!(cluster.get_cf(cf,... | {
let data_set: Vec<_> = (1..500)
.map(|i| {
(
format!("key{:08}", i).into_bytes(),
format!("value{}", i).into_bytes(),
)
})
.collect();
for kvs in data_set.chunks(50) {
let requests = kvs.iter().map(|(k, v)| new_put_cf_cmd(... | identifier_body |
util.rs | // Copyright 2022 TiKV Project Authors. Licensed under Apache-2.0.
use std::{fmt::Write, path::Path, sync::Arc, thread, time::Duration};
use encryption_export::{data_key_manager_from_config, DataKeyManager};
use engine_rocks::{RocksEngine, RocksStatistics};
use engine_test::raft::RaftTestEngine;
use engine_traits::{C... | (config: &mut Config) {
let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
let cfg = &mut config.security.encryption;
cfg.data_encryption_method = EncryptionMethod::Aes128Ctr;
cfg.data_key_rotation_period = ReadableDuration(Duration::from_millis(100));
cfg.master_key = test_util::new_test_fi... | configure_for_encryption | identifier_name |
multiexp.rs | use super::error::{GPUError, GPUResult};
use super::locks;
use super::sources;
use super::utils;
use crate::bls::Engine;
use crate::multicore::Worker;
use crate::multiexp::{multiexp as cpu_multiexp, FullDensity};
use ff::{PrimeField, ScalarEngine};
use groupy::{CurveAffine, CurveProjective};
use log::{error, info};
use... | <G>(
&mut self,
pool: &Worker,
bases: Arc<Vec<G>>,
exps: Arc<Vec<<<G::Engine as ScalarEngine>::Fr as PrimeField>::Repr>>,
skip: usize,
n: usize,
) -> GPUResult<<G as CurveAffine>::Projective>
where
G: CurveAffine,
<G as groupy::CurveAffine>::Engine... | multiexp | identifier_name |
multiexp.rs | use super::error::{GPUError, GPUResult};
use super::locks;
use super::sources;
use super::utils;
use crate::bls::Engine;
use crate::multicore::Worker;
use crate::multiexp::{multiexp as cpu_multiexp, FullDensity};
use ff::{PrimeField, ScalarEngine};
use groupy::{CurveAffine, CurveProjective};
use log::{error, info};
use... |
}
MAX_WINDOW_SIZE
}
fn calc_best_chunk_size(max_window_size: usize, core_count: usize, exp_bits: usize) -> usize {
// Best chunk-size (N) can also be calculated using the same logic as calc_window_size:
// n = e^window_size * window_size * 2 * core_count / exp_bits
(((max_window_size as f64).exp(... | {
return w;
} | conditional_block |
multiexp.rs | use super::error::{GPUError, GPUResult};
use super::locks;
use super::sources;
use super::utils;
use crate::bls::Engine;
use crate::multicore::Worker;
use crate::multiexp::{multiexp as cpu_multiexp, FullDensity};
use ff::{PrimeField, ScalarEngine};
use groupy::{CurveAffine, CurveProjective};
use log::{error, info};
use... | })
.collect();
if kernels.is_empty() {
return Err(GPUError::Simple("No working GPUs found!"));
}
info!(
"Multiexp: {} working device(s) selected. (CPU utilization: {})",
kernels.len(),
get_cpu_utilization()
);
... | }
res.ok() | random_line_split |
multiexp.rs | use super::error::{GPUError, GPUResult};
use super::locks;
use super::sources;
use super::utils;
use crate::bls::Engine;
use crate::multicore::Worker;
use crate::multiexp::{multiexp as cpu_multiexp, FullDensity};
use ff::{PrimeField, ScalarEngine};
use groupy::{CurveAffine, CurveProjective};
use log::{error, info};
use... |
fn exp_size<E: Engine>() -> usize {
std::mem::size_of::<<E::Fr as ff::PrimeField>::Repr>()
}
impl<E> SingleMultiexpKernel<E>
where
E: Engine,
{
pub fn create(d: opencl::Device, priority: bool) -> GPUResult<SingleMultiexpKernel<E>> {
let src = sources::kernel::<E>(d.brand() == opencl::Brand::Nvidi... | {
let aff_size = std::mem::size_of::<E::G1Affine>() + std::mem::size_of::<E::G2Affine>();
let exp_size = exp_size::<E>();
let proj_size = std::mem::size_of::<E::G1>() + std::mem::size_of::<E::G2>();
((((mem as f64) * (1f64 - MEMORY_PADDING)) as usize)
- (2 * core_count * ((1 << MAX_WINDOW_SIZE) ... | identifier_body |
pso.rs | // Copyright 2015 The Gfx-rs Developers.
//
// 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 ag... |
}
impl Error for CreationError {
fn description(&self) -> &str {
"Could not create PSO on device."
}
}
/// Color output configuration of the PSO.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct ColorInfo {
/// Color ... | {
write!(f, "{}", self.description())
} | identifier_body |
pso.rs | // Copyright 2015 The Gfx-rs Developers.
//
// 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 ag... |
self.set_dimensions(dim);
}
fn set_dimensions(&mut self, dim: texture::Dimensions) {
debug_assert!(self.dimensions.map(|d| d == dim).unwrap_or(true));
self.dimensions = Some(dim);
}
/// Get the rendering view (returns values > 0)
pub fn get_view(&self) -> (u16, u16, u16) {... | {
self.stencil = Some(view.clone());
} | conditional_block |
pso.rs | // Copyright 2015 The Gfx-rs Developers.
//
// 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 ag... | <R: Resources> {
/// Array of color target views
pub colors: [Option<R::RenderTargetView>; MAX_COLOR_TARGETS],
/// Depth target view
pub depth: Option<R::DepthStencilView>,
/// Stencil target view
pub stencil: Option<R::DepthStencilView>,
/// Rendering dimensions
pub dimensions: Option<t... | PixelTargetSet | identifier_name |
pso.rs | // Copyright 2015 The Gfx-rs Developers.
//
// 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 ag... | UnorderedViewSlot, SamplerSlot,
Primitive, Resources};
use {format, state as s, texture};
use shade::Usage;
use std::error::Error;
use std::fmt;
/// Maximum number of vertex buffers used in a PSO definition.
pub const MAX_VERTEX_BUFFERS: usize = 4;
/// An offset inside a vertex buffer, in bytes.
pub type Bu... | use {ConstantBufferSlot, ColorSlot, ResourceViewSlot, | random_line_split |
fmt.rs | //! Utilities for formatting and printing `String`s.
//!
//! This module contains the runtime support for the [`format!`] syntax extension.
//! This macro is implemented in the compiler to emit calls to this module in
//! order to format arguments at runtime into strings.
//!
//! # Usage
//!
//! The [`format!`] macro i... | //! [`format!`]:../../std/macro.format.html
//! [`to_string`]:../../std/string/trait.ToString.html
//! [`writeln!`]:../../std/macro.writeln.html
//! [`write_fmt`]:../../std/io/trait.Write.html#method.write_fmt
//! [`std::io::Write`]:../../std/io/trait.Write.html
//! [`print!`]:../../std/macro.print.html
//! [`println!`... | random_line_split | |
fmt.rs | //! Utilities for formatting and printing `String`s.
//!
//! This module contains the runtime support for the [`format!`] syntax extension.
//! This macro is implemented in the compiler to emit calls to this module in
//! order to format arguments at runtime into strings.
//!
//! # Usage
//!
//! The [`format!`] macro i... | rgs.estimated_capacity();
let mut output = string::String::with_capacity(capacity);
output.write_fmt(args).expect("a formatting trait implementation returned an error");
output
}
| identifier_body | |
fmt.rs | //! Utilities for formatting and printing `String`s.
//!
//! This module contains the runtime support for the [`format!`] syntax extension.
//! This macro is implemented in the compiler to emit calls to this module in
//! order to format arguments at runtime into strings.
//!
//! # Usage
//!
//! The [`format!`] macro i... | -> string::String {
let capacity = args.estimated_capacity();
let mut output = string::String::with_capacity(capacity);
output.write_fmt(args).expect("a formatting trait implementation returned an error");
output
}
| <'_>) | identifier_name |
sha_256.rs | //! This module is an implementation of the SHA-256 hashing algorithm
use padding::PaddingScheme;
use padding::merkle_damgard::MDPadding512u32;
// Logical functions used by SHA-256 (function names taken from NIST standard)
fn ch(x: u32, y: u32, z: u32) -> u32 {
(x & y) ^ (!x & z)
}
//
fn maj(x: u32, y: u32, z: u... | (x: u32) -> u32 {
x.rotate_right(17) ^ x.rotate_right(19) ^ (x >> 10)
}
// Constants used by SHA-256
const K: [u32; 64] = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
... | sigma_1 | identifier_name |
sha_256.rs | //! This module is an implementation of the SHA-256 hashing algorithm
use padding::PaddingScheme;
use padding::merkle_damgard::MDPadding512u32;
// Logical functions used by SHA-256 (function names taken from NIST standard)
fn ch(x: u32, y: u32, z: u32) -> u32 {
(x & y) ^ (!x & z)
}
//
fn maj(x: u32, y: u32, z: u... |
//
fn sigma_1(x: u32) -> u32 {
x.rotate_right(17) ^ x.rotate_right(19) ^ (x >> 10)
}
// Constants used by SHA-256
const K: [u32; 64] = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0... | {
x.rotate_right(7) ^ x.rotate_right(18) ^ (x >> 3)
} | identifier_body |
sha_256.rs | //! This module is an implementation of the SHA-256 hashing algorithm
use padding::PaddingScheme;
use padding::merkle_damgard::MDPadding512u32;
// Logical functions used by SHA-256 (function names taken from NIST standard)
fn ch(x: u32, y: u32, z: u32) -> u32 {
(x & y) ^ (!x & z)
}
//
fn maj(x: u32, y: u32, z: u... | g = f;
f = e;
e = d.wrapping_add(t_1);
d = c;
c = b;
b = a;
a = t_1.wrapping_add(t_2);
}
// Update the hash value
hash[0] = hash[0].wrapping_add(a);
hash[1] = hash[1].wrapping_add(b);
hash[2] = h... | .wrapping_add(ch(e, f, g))
.wrapping_add(K[t])
.wrapping_add(w[t]);
let t_2 = capital_sigma_0(a).wrapping_add(maj(a, b, c));
h = g; | random_line_split |
main.1.rs | extern crate brainfuck;
extern crate rand;
#[macro_use]
extern crate log;
extern crate env_logger;
mod context;
use brainfuck::parser;
use context::Context;
use std::time::{Duration, Instant};
use rand::random;
use log::LevelFilter;
use std::sync::mpsc::channel;
use std::thread;
use std::sync::{Arc, Mutex};
/*
f64数组... |
new_pop.push(self.populations[i]);
}
}
let (tx, rx) = channel();
let elite_count = new_pop.len();
let new_pop = Arc::new(Mutex::new(new_pop));
for tid in 0..NUM_THREAD{
let target = self.target.clone();
let child_count... | .NUM_COPIES_ELITE{ | identifier_name |
main.1.rs | extern crate brainfuck;
extern crate rand;
#[macro_use]
extern crate log;
extern crate env_logger;
mod context;
use brainfuck::parser;
use context::Context;
use std::time::{Duration, Instant};
use rand::random;
use log::LevelFilter;
use std::sync::mpsc::channel;
use std::thread;
use std::sync::{Arc, Mutex};
/*
f64数组... | oulette_selection()]);
parents.push(self.populations[self.roulette_selection()]);
}
let tx = tx.clone();
let new_pop_clone = new_pop.clone();
thread::spawn(move || {
let mut childs = vec![];
//println!("{}.start", tid);
... | new_pop.push(self.populations[i]);
}
}
let (tx, rx) = channel();
let elite_count = new_pop.len();
let new_pop = Arc::new(Mutex::new(new_pop));
for tid in 0..NUM_THREAD{
let target = self.target.clone();
let child_count = (POPULATION_S... | identifier_body |
main.1.rs | extern crate brainfuck;
extern crate rand;
#[macro_use]
extern crate log;
extern crate env_logger;
mod context;
use brainfuck::parser;
use context::Context;
use std::time::{Duration, Instant};
use rand::random;
use log::LevelFilter;
use std::sync::mpsc::channel;
use std::thread;
use std::sync::{Arc, Mutex};
/*
f64数组... | self.genes[i] = shift_bit;
shift_bit = temp;
}else{
self.genes[i] = self.genes[self.length-1];
}
}
}else{
... | if i>0{
let temp = self.genes[i]; | random_line_split |
main.1.rs | extern crate brainfuck;
extern crate rand;
#[macro_use]
extern crate log;
extern crate env_logger;
mod context;
use brainfuck::parser;
use context::Context;
use std::time::{Duration, Instant};
use rand::random;
use log::LevelFilter;
use std::sync::mpsc::channel;
use std::thread;
use std::sync::{Arc, Mutex};
/*
f64数组... | selected_pos
}
//下一代
fn epoch(&mut self){
//计算总适应分
self.total_fitness = 0.0;
for p in &mut self.populations{
self.total_fitness += p.fitness;
}
//按照得分排序
self.populations.sort_by(|a, b| b.fitness.partial_cmp(&a.fitness).unwrap());
le... | ness_total > slice{
selected_pos = i;
break;
}
}
| conditional_block |
main.rs | //! Urbit Nock 4K data structures, with basic parsing, and evaluation.
//! <https://urbit.org/docs/learn/arvo/nock/>
#![feature(never_type, exact_size_is_empty)]
use byteorder::{ByteOrder, LittleEndian};
use derive_more::Constructor;
use env_logger;
use log::{debug, error, info, log, trace, warn};
use std::{clone::Clon... | () -> Result<(), Box<dyn std::error::Error>> {
env_logger::try_init()?;
let subject = list(&[cell(atom(11), atom(12)), atom(2), atom(3), atom(4), atom(5)]);
let formula = cell(atom(0), atom(7));
info!("subject: {}", subject);
info!("formula: {}", formula);
let product = nock(subject.clone(), ... | main | identifier_name |
main.rs | //! Urbit Nock 4K data structures, with basic parsing, and evaluation.
//! <https://urbit.org/docs/learn/arvo/nock/>
#![feature(never_type, exact_size_is_empty)]
use byteorder::{ByteOrder, LittleEndian};
use derive_more::Constructor;
use env_logger;
use log::{debug, error, info, log, trace, warn};
use std::{clone::Clon... | // *[a 4 b] -> +*[a b]
3 => Ok(cell(subject, parameter).tar()?.lus()?),
// A formula [5 b c] treats b and c as formulas that become the input to
// another axiomatic operator, =. *[a 5 b c] -> =[*[a b]
// *[a c]]
5 => un... | }
// In formulas [3 b] and [4 b], b is another formula, whose product against
// the subject becomes the input to an axiomatic operator. 3 is ? and 4 is +
// *[a 3 b] -> ?*[a b]
3 => Ok(cell(subject, parameter).tar()?.wut()), | random_line_split |
main.rs | //! Urbit Nock 4K data structures, with basic parsing, and evaluation.
//! <https://urbit.org/docs/learn/arvo/nock/>
#![feature(never_type, exact_size_is_empty)]
use byteorder::{ByteOrder, LittleEndian};
use derive_more::Constructor;
use env_logger;
use log::{debug, error, info, log, trace, warn};
use std::{clone::Clon... | / Returns a reference to the Cell in this Noun, or a Crash if it's an atom.
pub fn try_cell(&self) -> Result<&Cell, Crash> {
match self {
Noun::Cell(cell) => Ok(cell),
Noun::Atom(_) => Err(Crash::from("required cell, had atom")),
}
}
/// `*[subject formula]` nock for... | match self {
Noun::Atom(atom) => Ok(atom),
Noun::Cell(_) => Err(Crash::from("required atom, had cell")),
}
}
// | identifier_body |
symdumper.rs | use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
use std::iter::once;
use std::process::Command;
use std::io::{Error, ErrorKind};
use crate::win32::ModuleInfo;
type HANDLE = usize;
extern {
fn GetCurrentProcess() -> HANDLE;
}
#[allow(non_snake_case)]
#[repr(C)]
struct SrcCodeInfoW {
SizeOfStruct: u3... | SizeOfStruct: std::mem::size_of::<SrcCodeInfoW>() as u32,
Key: 0,
ModBase: 0,
Obj: [0; 261],
FileName: [0; 261],
LineNumber: 0,
Address: 0,
}
}
}
#[allow(non_snake_case)]
#[repr(C)]
struct SymbolInfoW {
SizeOfStruct: u3... | SrcCodeInfoW { | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.