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 |
|---|---|---|---|---|
elf.rs | use std::convert::TryInto;
use std::ffi::CStr;
use std::mem;
use std::ptr;
use std::slice;
use failure::{bail, format_err, Error, Fail, ResultExt};
use goblin::elf::{
header::{EM_BPF, ET_REL},
section_header::{SectionHeader, SHT_PROGBITS, SHT_REL},
sym::{Sym, STB_GLOBAL},
};
use ebpf_core::{
ffi, prog... | (
&self,
programs: &mut [Program],
maps: &[Map],
maps_idx: Option<usize>,
text_idx: Option<usize>,
) -> Result<(), Error> {
for (idx, sec) in &self.obj.shdr_relocs {
if let Some(prog) = programs.iter_mut().find(|prog| prog.idx == *idx) {
tr... | relocate_programs | identifier_name |
elf.rs | use std::convert::TryInto;
use std::ffi::CStr;
use std::mem;
use std::ptr;
use std::slice;
use failure::{bail, format_err, Error, Fail, ResultExt};
use goblin::elf::{
header::{EM_BPF, ET_REL},
section_header::{SectionHeader, SHT_PROGBITS, SHT_REL},
sym::{Sym, STB_GLOBAL},
};
use ebpf_core::{
ffi, prog... | debug!(
"{:?} kernel program #{} @ section `{}` with {} insns",
ty,
idx,
name,
insns.len()
);
programs.push((name, ty, attach, idx, insns.t... | random_line_split | |
elf.rs | use std::convert::TryInto;
use std::ffi::CStr;
use std::mem;
use std::ptr;
use std::slice;
use failure::{bail, format_err, Error, Fail, ResultExt};
use goblin::elf::{
header::{EM_BPF, ET_REL},
section_header::{SectionHeader, SHT_PROGBITS, SHT_REL},
sym::{Sym, STB_GLOBAL},
};
use ebpf_core::{
ffi, prog... |
BPF_VERSION_SEC if sec.sh_type == SHT_PROGBITS => {
version = Some(u32::from_ne_bytes(section_data()?.try_into()?));
debug!("kernel version: {:x}", version.as_ref().unwrap());
}
BPF_MAPS_SEC => {
debug!("`{}` s... | {
license = Some(
CStr::from_bytes_with_nul(section_data()?)?
.to_str()?
.to_owned(),
);
debug!("kernel license: {}", license.as_ref().unwrap());
} | conditional_block |
list.rs | // 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 in the LICENSE-APACHE file or at:
// https://www.apache.org/licenses/LICENSE-2.0
//! A row or column with run-time adjustable contents
use ... |
Some(self.id())
}
fn draw(&self, draw_handle: &mut dyn DrawHandle, mgr: &event::ManagerState, disabled: bool) {
let disabled = disabled || self.is_disabled();
let solver = layout::RowPositionSolver::new(self.direction);
solver.for_children(&self.widgets, draw_handle.get_clip_r... | {
return child.find_id(coord);
} | conditional_block |
list.rs | // 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 in the LICENSE-APACHE file or at:
// https://www.apache.org/licenses/LICENSE-2.0
//! A row or column with run-time adjustable contents
use ... | (&mut self, index: usize) -> Option<&mut dyn WidgetConfig> {
self.widgets.get_mut(index).map(|w| w.as_widget_mut())
}
}
impl<D: Directional, W: Widget> Layout for List<D, W> {
fn size_rules(&mut self, size_handle: &mut dyn SizeHandle, axis: AxisInfo) -> SizeRules {
let dim = (self.direction, se... | get_child_mut | identifier_name |
list.rs | // 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 in the LICENSE-APACHE file or at:
// https://www.apache.org/licenses/LICENSE-2.0
//! A row or column with run-time adjustable contents
use ... | self.list = &self.list[1..];
Some(item)
} else {
None
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let len = self.len();
(len, Some(len))
}
}
impl<'a, W: Widget> ExactSizeIterator for ListIter<'a, W> {
fn len(&self) -> usize {
... | impl<'a, W: Widget> Iterator for ListIter<'a, W> {
type Item = &'a W;
fn next(&mut self) -> Option<Self::Item> {
if !self.list.is_empty() {
let item = &self.list[0]; | random_line_split |
list.rs | // 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 in the LICENSE-APACHE file or at:
// https://www.apache.org/licenses/LICENSE-2.0
//! A row or column with run-time adjustable contents
use ... |
/// Reserves capacity for at least `additional` more elements to be inserted
/// into the list. See documentation of [`Vec::reserve`].
pub fn reserve(&mut self, additional: usize) {
self.widgets.reserve(additional);
}
/// Remove all child widgets
///
/// Triggers a [reconfigure ac... | {
self.widgets.capacity()
} | identifier_body |
lib.rs | // This file is part of Substrate.
// Copyright (C) 2022 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://... |
}
/// Waste at most the remaining ref time weight of `meter`.
///
/// Tries to come as close to the limit as possible.
pub(crate) fn waste_at_most_ref_time(meter: &mut WeightMeter) {
let Ok(n) = Self::calculate_ref_time_iters(&meter) else { return };
meter.consume(T::WeightInfo::waste_ref_time_iter(n)... | {
Err(())
} | conditional_block |
lib.rs | // This file is part of Substrate.
// Copyright (C) 2022 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://... |
/// Set how much of the remaining `proof_size` weight should be consumed by `on_idle`.
///
/// `1.0` means that all remaining `proof_size` will be consumed. The PoV benchmarking
/// results that are used here are likely an over-estimation. 100% intended consumption will
/// therefore translate to less than ... | {
T::AdminOrigin::ensure_origin_or_root(origin)?;
ensure!(compute <= RESOURCE_HARD_LIMIT, Error::<T>::InsaneLimit);
Compute::<T>::set(compute);
Self::deposit_event(Event::ComputationLimitSet { compute });
Ok(())
} | identifier_body |
lib.rs | // This file is part of Substrate.
// Copyright (C) 2022 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://... | }
Self::deposit_event(Event::PalletInitialized { reinit: witness_count.is_some() });
TrashDataCount::<T>::set(new_count);
Ok(())
}
/// Set how much of the remaining `ref_time` weight should be consumed by `on_idle`.
///
/// Only callable by Root or `AdminOrigin`.
#[pallet::call_index(1)]
pub f... | (new_count..current_count).for_each(TrashData::<T>::remove); | random_line_split |
lib.rs | // This file is part of Substrate.
// Copyright (C) 2022 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://... | (origin: OriginFor<T>, storage: FixedU64) -> DispatchResult {
T::AdminOrigin::ensure_origin_or_root(origin)?;
ensure!(storage <= RESOURCE_HARD_LIMIT, Error::<T>::InsaneLimit);
Storage::<T>::set(storage);
Self::deposit_event(Event::StorageLimitSet { storage });
Ok(())
}
}
impl<T: Config> Pallet<T> ... | set_storage | identifier_name |
freelist.rs | use types::{txid_t, pgid_t};
use page::{Page, get_page_header_size, merge_pgids, merge_pgids_raw, FREELIST_PAGE_FLAG};
use std::rc::Rc;
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::mem;
use std::slice;
// FreeList represents a list of all pages that are available for allocation.
// It als... | else {
let pgid_ptr = &p.ptr as *const usize as *const pgid_t;
self.ids.reserve(count - idx);
let mut pgids_slice = unsafe {
slice::from_raw_parts(pgid_ptr.offset(idx as isize), count)
};
self.ids.append(&mut pgids_slice.to_vec());
... | {
self.ids.clear();
} | conditional_block |
freelist.rs | use types::{txid_t, pgid_t};
use page::{Page, get_page_header_size, merge_pgids, merge_pgids_raw, FREELIST_PAGE_FLAG};
use std::rc::Rc;
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::mem;
use std::slice;
// FreeList represents a list of all pages that are available for allocation.
// It als... | } else {
p.count = 0xFFFF;
let mut pgid_ptr = &mut p.ptr as *mut usize as *mut pgid_t;
unsafe {*pgid_ptr = lenids as u64;}
/*
let mut dst = unsafe {
Vec::from_raw_parts(pgid_ptr.offset(1), 0, lenids)
};
*/
... | {
// Combine the old free pgids and pgids waiting on an open transaction.
// Update the header flag.
p.flags |= FREELIST_PAGE_FLAG;
// The page.count can only hold up to 64k elementes so if we overflow that
// number then we handle it by putting the size in the first element.
... | identifier_body |
freelist.rs | use types::{txid_t, pgid_t};
use page::{Page, get_page_header_size, merge_pgids, merge_pgids_raw, FREELIST_PAGE_FLAG};
use std::rc::Rc;
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::mem;
use std::slice;
// FreeList represents a list of all pages that are available for allocation.
// It als... | () {
// Create a page.
let mut buf: [u8; 4096] = [0; 4096];
let page: *mut Page = buf.as_mut_ptr() as *mut Page;
unsafe {
(*page).flags = FREELIST_PAGE_FLAG;
(*page).count = 2;
}
// Insert 2 page ids
let ids_ptr: *mut pgid_t = unsafe {
... | freelist_read | identifier_name |
freelist.rs | use types::{txid_t, pgid_t};
use page::{Page, get_page_header_size, merge_pgids, merge_pgids_raw, FREELIST_PAGE_FLAG};
use std::rc::Rc;
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::mem;
use std::slice;
// FreeList represents a list of all pages that are available for allocation.
// It als... | // writes the page ids onto a freelist page. All free and pending ids are
// saved to disk since in the event of a program crash, all pending ids will
// become free.
pub fn write(&self, p: &mut Page) {
// Combine the old free pgids and pgids waiting on an open transaction.
// Update th... | }
| random_line_split |
13.1.rs | // --- Day 13: Packet Scanners ---
// You need to cross a vast firewall. The firewall consists of several layers, each with a security scanner that moves back and forth across the layer. To succeed, you must not be detected by a scanner.
// By studying the firewall briefly, you are able to record (in your puzzle in... | (f: File) -> Scanners {
let buf = BufReader::new(f);
let mut scanners = HashMap::new();
let mut max_depth = 0;
let mut max_range = 0;
for line in buf.lines() {
let split = line.expect("io error")
.split(": ")
.map(|s| s.parse::<i32>().expect("parse int err"))
... | get_scanners | identifier_name |
13.1.rs | // --- Day 13: Packet Scanners ---
// You need to cross a vast firewall. The firewall consists of several layers, each with a security scanner that moves back and forth across the layer. To succeed, you must not be detected by a scanner.
// By studying the firewall briefly, you are able to record (in your puzzle in... | // 0 1 2 3 4 5 6
// [ ] ( )...... [ ]... [ ]
// [S] [S] [S] [S]
// [ ] [ ] [ ]
// [ ] [ ]
// 0 1 2 3 4 5 6
// [ ] (S)...... [ ]... [ ]
// [ ] [ ] [ ] [ ]
// [S] [S] [S]
// [ ] [ ]
// P... | // [ ] [ ]
// Picosecond 1:
| random_line_split |
13.1.rs | // --- Day 13: Packet Scanners ---
// You need to cross a vast firewall. The firewall consists of several layers, each with a security scanner that moves back and forth across the layer. To succeed, you must not be detected by a scanner.
// By studying the firewall briefly, you are able to record (in your puzzle in... |
let mi = r - 1; /* max index of the scanner range */
let unique_positions = r * 2 - 2; /* how many different states the scanner can be in. Whenever the scanner is at an end, it can only be turning around. Whenever a scanner is in a middle position, it could be going back or forward*/
... | {
return Some(0);
} | conditional_block |
13.1.rs | // --- Day 13: Packet Scanners ---
// You need to cross a vast firewall. The firewall consists of several layers, each with a security scanner that moves back and forth across the layer. To succeed, you must not be detected by a scanner.
// By studying the firewall briefly, you are able to record (in your puzzle in... |
fn main() {
let fname = "src/13/data";
// let fname = "src/13/testdata";
let f = File::open(fname).expect(&format!("Couldn't open {}", fname));
let scanners = get_scanners(f);
println!(
"Advent 13-1: severity {} at offset 0.",
severity(&0, &scanners)
);
let m... | {
let mut d: i32 = 0;
while d <= scanners.max_depth {
let scanner_time = d + offset;
if scanners.collides(&d, &scanner_time) {
return true;
}
d += 1;
}
false
} | identifier_body |
lib.rs | //! `pdf_derive` provides a proc macro to derive the Object trait from the `pdf` crate.
//! # Usage
//! There are several ways to derive Object on a struct or enum:
//! ## 1. Struct from PDF Dictionary
//!
//! A lot of dictionary types defined in the PDF 1.7 reference have a finite amount of possible
//! fields. Each o... | else {
match *value {
Lit::Str(ref value, _) => attrs.checks.push((String::from(ident.as_ref()), value.clone())),
_ => panic!("Other checks must have RHS String."),
}
... | {
match *value {
Lit::Str(ref value, _) => {
if value.ends_with("?") {
attrs.type_name = Some(value[.. value.len()-1].to_string());
... | conditional_block |
lib.rs | //! `pdf_derive` provides a proc macro to derive the Object trait from the `pdf` crate.
//! # Usage
//! There are several ways to derive Object on a struct or enum:
//! ## 1. Struct from PDF Dictionary
//!
//! A lot of dictionary types defined in the PDF 1.7 reference have a finite amount of possible
//! fields. Each o... |
/// Accepts Name to construct enum
fn impl_object_for_enum(ast: &DeriveInput, variants: &Vec<Variant>) -> quote::Tokens {
let id = &ast.ident;
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
let ser_code: Vec<_> = variants.iter().map(|var| {
quote! {
#id... | {
let attrs = GlobalAttrs::from_ast(&ast);
if attrs.is_stream {
match ast.body {
Body::Struct(ref data) => impl_object_for_stream(ast, data.fields()),
Body::Enum(_) => panic!("Enum can't be a PDF stream"),
}
} else {
match ast.body {
Body::Struct(r... | identifier_body |
lib.rs | //! `pdf_derive` provides a proc macro to derive the Object trait from the `pdf` crate.
//! # Usage
//! There are several ways to derive Object on a struct or enum:
//! ## 1. Struct from PDF Dictionary
//!
//! A lot of dictionary types defined in the PDF 1.7 reference have a finite amount of possible
//! fields. Each o... | match ast.body {
Body::Struct(ref data) => impl_object_for_stream(ast, data.fields()),
Body::Enum(_) => panic!("Enum can't be a PDF stream"),
}
} else {
match ast.body {
Body::Struct(ref data) => impl_object_for_struct(ast, data.fields()),
Body... | random_line_split | |
lib.rs | //! `pdf_derive` provides a proc macro to derive the Object trait from the `pdf` crate.
//! # Usage
//! There are several ways to derive Object on a struct or enum:
//! ## 1. Struct from PDF Dictionary
//!
//! A lot of dictionary types defined in the PDF 1.7 reference have a finite amount of possible
//! fields. Each o... | (ast: &DeriveInput, fields: &[Field]) -> quote::Tokens {
let name = &ast.ident;
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
let attrs = GlobalAttrs::from_ast(&ast);
let parts: Vec<_> = fields.iter()
.map(|field| {
let (key, default, skip) = field_attrs(fie... | impl_object_for_struct | identifier_name |
main.rs | error::UrlParseSnafu {
url: &config.targets_base_url,
})?,
)
.transport(transport)
.load()
.context(error::MetadataSnafu)
}
fn applicable_updates<'a>(
manifest: &'a Manifest,
variant: &str,
ignore_waves: bool,
seed: u32,
) -> Vec<&'a Update> {
let mut updates: Vec<&... | .arg("-r")
.status()
.context(error::RebootFailureSnafu)
{
// Kill the signal handling thread
signals_handle.close();
return Err(err);
}
Ok(())
}
/// Our underlying HTTP client, reqwest, supports proxies by reading the `HTTPS_PROXY` and `NO_PROXY`
/// environmen... | random_line_split | |
main.rs | ::UrlParseSnafu {
url: &config.targets_base_url,
})?,
)
.transport(transport)
.load()
.context(error::MetadataSnafu)
}
fn applicable_updates<'a>(
manifest: &'a Manifest,
variant: &str,
ignore_waves: bool,
seed: u32,
) -> Vec<&'a Update> {
let mut updates: Vec<&Updat... | () -> Result<()> {
let mut gpt_state = State::load().context(error::PartitionTableReadSnafu)?;
gpt_state.cancel_upgrade();
gpt_state.write().context(error::PartitionTableWriteSnafu)?;
Ok(())
}
fn set_common_query_params(
query_params: &mut QueryParams,
current_version: &Version,
config: &Co... | revert_update_flags | identifier_name |
main.rs | ::UrlParseSnafu {
url: &config.targets_base_url,
})?,
)
.transport(transport)
.load()
.context(error::MetadataSnafu)
}
fn applicable_updates<'a>(
manifest: &'a Manifest,
variant: &str,
ignore_waves: bool,
seed: u32,
) -> Vec<&'a Update> {
let mut updates: Vec<&Updat... | update_required(
&manifest,
| {
// A manifest with a single update whose version exceeds the max version.
// update in manifest has
// - version: 1.25.0
// - max_version: 1.20.0
let path = "tests/data/regret.json";
let manifest: Manifest = serde_json::from_reader(File::open(path).unwrap()).unwrap();
... | identifier_body |
Python3_original.rs | #[derive(Clone)]
#[allow(non_camel_case_types)]
pub struct Python3_original {
support_level: SupportLevel,
data: DataHolder,
code: String,
imports: String,
interpreter: String,
main_file_path: String,
plugin_root: String,
cache_dir: String,
venv: Option<String>,
}
impl Python3_origin... | (&self, line: &str, code: &str) -> bool {
info!(
"checking for python module usage: line {} in code {}",
line, code
);
if line.contains('*') {
return true;
}
if line.contains(" as ") {
if let Some(name) = line.split(' ').last() {
... | module_used | identifier_name |
Python3_original.rs | #[derive(Clone)]
#[allow(non_camel_case_types)]
pub struct Python3_original {
support_level: SupportLevel,
data: DataHolder,
code: String,
imports: String,
interpreter: String,
main_file_path: String,
plugin_root: String,
cache_dir: String,
venv: Option<String>,
}
impl Python3_origin... |
}
}
impl Interpreter for Python3_original {
fn new_with_level(data: DataHolder, level: SupportLevel) -> Box<Python3_original> {
//create a subfolder in the cache folder
let rwd = data.work_dir.clone() + "/python3_original";
let mut builder = DirBuilder::new();
builder.recursive... | {
if let Some(venv_array_config) = Python3_original::get_interpreter_option(&self.get_data(), "venv") {
if let Some(actual_vec_of_venv) = venv_array_config.as_array() {
for possible_venv in actual_vec_of_venv.iter() {
if let Some(possible_venv_str)... | conditional_block |
Python3_original.rs | #[derive(Clone)]
#[allow(non_camel_case_types)]
pub struct Python3_original {
support_level: SupportLevel,
data: DataHolder,
code: String,
imports: String,
interpreter: String,
main_file_path: String,
plugin_root: String,
cache_dir: String,
venv: Option<String>,
}
impl Python3_origin... | self.code = self.data.current_line.clone();
} else {
self.code = String::from("");
}
Ok(())
}
fn add_boilerplate(&mut self) -> Result<(), SniprunError> {
if!self.imports.is_empty() {
let mut indented_imports = String::new();
for im... | } else if !self.data.current_line.replace(" ", "").is_empty()
&& self.get_current_level() >= SupportLevel::Line
{ | random_line_split |
Python3_original.rs | #[derive(Clone)]
#[allow(non_camel_case_types)]
pub struct Python3_original {
support_level: SupportLevel,
data: DataHolder,
code: String,
imports: String,
interpreter: String,
main_file_path: String,
plugin_root: String,
cache_dir: String,
venv: Option<String>,
}
impl Python3_origin... |
fn get_name() -> String {
String::from("Python3_original")
}
fn behave_repl_like_default() -> bool {
false
}
fn has_repl_capability() -> bool {
true
}
fn default_for_filetype() -> bool {
true
}
fn get_supported_languages() -> Vec<String> {
... | {
// All cli arguments are sendable to python
// Though they will be ignored in REPL mode
Ok(())
} | identifier_body |
frameworks.rs | // stripped mac core foundation + metal layer only whats needed
#![allow(non_camel_case_types)]
#![allow(non_upper_case_globals)]
#![allow(non_snake_case)]
pub use {
std::{
ffi::c_void,
os::raw::c_ulong,
ptr::NonNull,
},
crate::{
makepad_platform::{
os::app... | {
pub protocol: MIDIProtocolID,
pub numPackets: u32,
pub packet: [MIDIEventPacket; 1usize],
}
#[repr(C, packed(4))]
#[derive(Copy, Clone)]
pub struct MIDIEventPacket {
pub timeStamp: MIDITimeStamp,
pub wordCount: u32,
pub words: [u32; 64usize],
}
#[link(name = "CoreMidi", kind = "framework")]... | MIDIEventList | identifier_name |
frameworks.rs | // stripped mac core foundation + metal layer only whats needed
#![allow(non_camel_case_types)]
#![allow(non_upper_case_globals)]
#![allow(non_snake_case)]
pub use {
std::{
ffi::c_void,
os::raw::c_ulong,
ptr::NonNull,
},
crate::{
makepad_platform::{
os::app... |
pub const kAudioUnitManufacturer_Apple: u32 = 1634758764;
#[repr(C)] pub struct OpaqueAudioComponent([u8; 0]);
pub type CAudioComponent = *mut OpaqueAudioComponent;
#[repr(C)] pub struct ComponentInstanceRecord([u8; 0]);
pub type CAudioComponentInstance = *mut ComponentInstanceRecord;
pub type CAudioUnit = CAudioCo... | }
};
// CORE AUDIO | random_line_split |
lib.rs | // This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.a... | (s: &str) -> Result<Self, Self::Err> {
bytes::from_hex(s).map(Bytes)
}
}
/// Stores the encoded `RuntimeMetadata` for the native side as opaque type.
#[derive(Encode, Decode, PartialEq, TypeInfo)]
pub struct OpaqueMetadata(Vec<u8>);
impl OpaqueMetadata {
/// Creates a new instance with the given metadata blob.
p... | from_str | identifier_name |
lib.rs | // This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.a... | #[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use sp_runtime_interface::pass_by::{PassByEnum, PassByInner};
use sp_std::{ops::Deref, prelude::*};
pub use sp_debug_derive::RuntimeDebug;
#[cfg(feature = "serde")]
pub use impl_serde::serialize as bytes;
#[cfg(feature = "full_crypto")]
pub mod hashing;
... | #[cfg(feature = "serde")]
pub use serde; | random_line_split |
lib.rs | // This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.a... |
}
impl codec::WrapperTypeEncode for Bytes {}
impl codec::WrapperTypeDecode for Bytes {
type Wrapped = Vec<u8>;
}
#[cfg(feature = "std")]
impl sp_std::str::FromStr for Bytes {
type Err = bytes::FromHexError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
bytes::from_hex(s).map(Bytes)
}
}
/// Stores the en... | {
&self.0[..]
} | identifier_body |
api.rs | //! This API contains all you will need to interface your
//! your bot algorithm with the GTPv2 protocol.
//! Your main task will be to implement the GoBot trait.
use std::str::FromStr;
use std::vec::Vec;
/// Contains all the possible errors your bot
/// may return to the library.
/// Be careful, any callback returni... | fn komi(&mut self, komi: f32) -> ();
/// Sets the board size.
/// Returns `Err(InvalidBoardSize)` if the size is not supported.
/// The protocol cannot handle board sizes > 25x25.
fn boardsize(&mut self, size: usize) -> Result<(), GTPError>;
/// Plays the provided move on the board.
/// Re... | /// Clears the board, can never fail.
fn clear_board(&mut self) -> ();
/// Sets the komi, can never fail, must accept absurd values. | random_line_split |
api.rs | //! This API contains all you will need to interface your
//! your bot algorithm with the GTPv2 protocol.
//! Your main task will be to implement the GoBot trait.
use std::str::FromStr;
use std::vec::Vec;
/// Contains all the possible errors your bot
/// may return to the library.
/// Be careful, any callback returni... | // eliminate 'I'
let number = u8::from_str(&text[1..]);
let mut y: u8 = 0;
match number {
Ok(num) => y = num,
_ => (),
}
if y == 0 || y > 25 {
return None;
}
Some(Vertex{x: x, y: y})
}
/// Returns a tuple of coordinates... |
x -= 1;
} | conditional_block |
api.rs | //! This API contains all you will need to interface your
//! your bot algorithm with the GTPv2 protocol.
//! Your main task will be to implement the GoBot trait.
use std::str::FromStr;
use std::vec::Vec;
/// Contains all the possible errors your bot
/// may return to the library.
/// Be careful, any callback returni... | (&self, status: StoneStatus) -> Result<Vec<Vertex>, GTPError> {
Err(GTPError::NotImplemented)
}
/// Computes the bot's calculation of the final score.
/// If it is a draw, float value must be 0 and colour is not important.
/// Can fail with èErr(CannotScore)`.
fn final_score(&self) -> Resul... | final_status_list | identifier_name |
my.rs | use std::{io, iter};
use std::collections::{HashSet, HashMap};
use std::iter::FromIterator;
use std::ops::RangeFull;
use paths_builder::Path;
macro_rules! parse_input {
($x:expr, $t:ident) => ($x.trim().parse::<$t>().unwrap())
}
#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy, PartialOrd, Ord)]
pub struct Pt {
... | {
pub moves: Vec<(i8, i8)>, // (dx, dy)
pub nowater: Vec<Pt>, // (x, y) sorted
pub noobstacles: Vec<Pt>, // (x, y) sorted
pub xmin: i32,
pub xmax: i32,
pub ymin: i32,
pub ymax: i32,
}
#[derive(Debug)]
pub struct Paths {
pub paths: HashMap... | Path | identifier_name |
my.rs | use std::{io, iter};
use std::collections::{HashSet, HashMap};
use std::iter::FromIterator;
use std::ops::RangeFull;
use paths_builder::Path;
macro_rules! parse_input {
($x:expr, $t:ident) => ($x.trim().parse::<$t>().unwrap())
}
#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy, PartialOrd, Ord)]
pub struct Pt {
... | pub struct Paths {
pub paths: HashMap<usize, HashMap<(i32, i32), Vec<Path>>>,
}
}
struct BallPaths {
count: usize,
ball: usize,
paths: Vec<(paths_builder::Path,usize)>
}
struct Main {
width : usize,
height: usize,
field : Vec<u8>,
holes : Vec<Pt>,
balls : Vec<(Pt, u8)>,... | pub ymax: i32,
}
#[derive(Debug)] | random_line_split |
my.rs | use std::{io, iter};
use std::collections::{HashSet, HashMap};
use std::iter::FromIterator;
use std::ops::RangeFull;
use paths_builder::Path;
macro_rules! parse_input {
($x:expr, $t:ident) => ($x.trim().parse::<$t>().unwrap())
}
#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy, PartialOrd, Ord)]
pub struct Pt {
... |
for pt in path.noobstacles.iter().chain(path.nowater.iter()) {
if used_points.contains(pt) {
continue 'outer;
}
}
if is_leaf {
let mut s : Vec<(usize, Path)> = Vec::new();
s.push((paths.ball, path.cl... | {
continue;
} | conditional_block |
lib.rs | // Copyright 2013-2014 The gl-rs developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// 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... | (&self) -> Option<::syntax::util::small_vector::SmallVector<::std::gc::Gc<Item>>> {
Some(::syntax::util::small_vector::SmallVector::many(self.content.clone()))
}
}
// handler for generate_gl_bindings!
fn macro_handler(ecx: &mut ExtCtxt, span: Span, token_tree: &[TokenTree]) -> Box<MacResult+'static> {
... | make_items | identifier_name |
lib.rs | // Copyright 2013-2014 The gl-rs developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// 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... | Path::new(ecx.codemap().span_to_filename(span)).display().to_string(), content);
// getting all the items defined by the bindings
let mut items = Vec::new();
loop {
match parser.parse_item_with_outer_attributes() {
None => break,
Some(i) => items.push(i)
}
... | return DummyResult::any(span)
}
};
let mut parser = ::syntax::parse::new_parser_from_source_str(ecx.parse_sess(), ecx.cfg(), | random_line_split |
lib.rs | // Copyright 2013-2014 The gl-rs developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// 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... | }
};
let filter = Some(Filter {
extensions: extensions,
profile: profile,
version: version,
api: api,
});
// generating the registry of all bindings
let reg = {
use std::io::BufReader;
use std::task;
let result = task::try(proc() {
... | {
// getting the arguments from the macro
let (api, profile, version, generator, extensions) = match parse_macro_arguments(ecx, span.clone(), token_tree) {
Some(t) => t,
None => return DummyResult::any(span)
};
let (ns, source) = match api.as_slice() {
"gl" => (Gl, khronos_api:... | identifier_body |
lib.rs | #![deny(warnings)]
pub mod corgi;
pub mod dict;
#[cfg(test)]
pub mod tests;
use crate::corgi::{decode, encode, Corgi, CorgiDTO, CorgiId, CorgiKey, Rarity};
use crate::dict::Dict;
use near_env::near_envlog;
use near_sdk::{
borsh::{self, BorshDeserialize, BorshSerialize},
collections::UnorderedMap,
env,
... | let mut it = bids.into_iter();
let signer = env::predecessor_account_id();
if signer == owner.clone() {
if let Some((bidder, (price, _timestamp))) = it.next() {
end_auction(it, bidder, price);
} else {
self.auctions.remove(&key);
... | let (key, mut bids, auction_ends) = self.get_auction(&token_id);
let corgi = {
let corgi = self.corgis.get(&key);
assert!(corgi.is_some());
corgi.unwrap()
};
let owner = corgi.owner.clone();
let end_auction = |it, bidder, price| {
i... | identifier_body |
lib.rs | #![deny(warnings)]
pub mod corgi;
pub mod dict;
#[cfg(test)]
pub mod tests;
use crate::corgi::{decode, encode, Corgi, CorgiDTO, CorgiId, CorgiKey, Rarity};
use crate::dict::Dict;
use near_env::near_envlog;
use near_sdk::{
borsh::{self, BorshDeserialize, BorshSerialize},
collections::UnorderedMap,
env,
... | }
fn get_collection_key(prefix: &str, mut key: String) -> Vec<u8> {
key.insert_str(0, prefix);
key.as_bytes().to_vec()
} | random_line_split | |
lib.rs | #![deny(warnings)]
pub mod corgi;
pub mod dict;
#[cfg(test)]
pub mod tests;
use crate::corgi::{decode, encode, Corgi, CorgiDTO, CorgiId, CorgiKey, Rarity};
use crate::dict::Dict;
use near_env::near_envlog;
use near_sdk::{
borsh::{self, BorshDeserialize, BorshSerialize},
collections::UnorderedMap,
env,
... | -> Self {
env::log(format!("init v{}", env!("CARGO_PKG_VERSION")).as_bytes());
Self {
corgis: Dict::new(CORGIS.to_vec()),
corgis_by_owner: UnorderedMap::new(CORGIS_BY_OWNER.to_vec()),
auctions: UnorderedMap::new(AUCTIONS.to_vec()),
}
}
}
#[near_bindgen]
... | fault() | identifier_name |
main.rs | use std::fs::File;
use std::io::{BufReader, BufWriter};
use std::collections::HashMap;
use std::fmt::Display;
use std::fmt;
use std::hash::Hash;
use std::io::Write;
use clap::{App, AppSettings, Arg, ArgMatches};
use conllx::io::{Reader, ReadSentence};
use conllx::token::Token;
use failure::{Error};
use itertools::Iter... |
impl<V> Confusion<V> where V: ToString {
fn write_accuracies(&self, mut w: impl Write) -> Result<(), Error> {
for (idx, item) in self.numberer.idx2val.iter().map(V::to_string).enumerate() {
let row = &self.confusion[idx];
let correct = row[idx];
let total = row.iter().s... | } | random_line_split |
main.rs | use std::fs::File;
use std::io::{BufReader, BufWriter};
use std::collections::HashMap;
use std::fmt::Display;
use std::fmt;
use std::hash::Hash;
use std::io::Write;
use clap::{App, AppSettings, Arg, ArgMatches};
use conllx::io::{Reader, ReadSentence};
use conllx::token::Token;
use failure::{Error};
use itertools::Iter... |
Ok(())
}
static DEFAULT_CLAP_SETTINGS: &[AppSettings] = &[
AppSettings::DontCollapseArgsInUsage,
AppSettings::UnifiedHelpMessage,
];
// Argument constants
static VALIDATION: &str = "VALIDATION";
static PREDICTION: &str = "PREDICTION";
static DEPREL_CONFUSION: &str = "deprel_confusion";
static DEPREL_ACCU... | {
let out = File::create(file_name).unwrap();
let mut writer = BufWriter::new(out);
distance_confusion.write_accuracies(&mut writer).unwrap();
} | conditional_block |
main.rs | use std::fs::File;
use std::io::{BufReader, BufWriter};
use std::collections::HashMap;
use std::fmt::Display;
use std::fmt;
use std::hash::Hash;
use std::io::Write;
use clap::{App, AppSettings, Arg, ArgMatches};
use conllx::io::{Reader, ReadSentence};
use conllx::token::Token;
use failure::{Error};
use itertools::Iter... | <V>{
val2idx: HashMap<V, usize>,
idx2val: Vec<V>,
}
impl<V> Numberer<V> where V: Clone + Hash + Eq {
pub fn new() -> Self {
Numberer {
val2idx: HashMap::new(),
idx2val: Vec::new(),
}
}
fn number<S>(&mut self, val: S) -> usize where S: Into<V> {
let v... | Numberer | identifier_name |
main.rs | use std::fs::File;
use std::io::{BufReader, BufWriter};
use std::collections::HashMap;
use std::fmt::Display;
use std::fmt;
use std::hash::Hash;
use std::io::Write;
use clap::{App, AppSettings, Arg, ArgMatches};
use conllx::io::{Reader, ReadSentence};
use conllx::token::Token;
use failure::{Error};
use itertools::Iter... |
fn number<S>(&mut self, val: S) -> usize where S: Into<V> {
let val = val.into();
if let Some(idx) = self.val2idx.get(&val) {
*idx
} else {
let n_vals = self.val2idx.len();
self.val2idx.insert(val.clone(), n_vals);
self.idx2val.push(val);
... | {
Numberer {
val2idx: HashMap::new(),
idx2val: Vec::new(),
}
} | identifier_body |
session.rs | remote_ptr::{RemotePtr, Void},
session::{
address_space::{
address_space::{AddressSpaceSharedPtr, Mapping},
memory_range::MemoryRangeKey,
MappingFlags,
},
diversion_session::DiversionSession,
record_session::RecordSession,
replay_sessio... | {
let start = m.map.start();
let data_size: usize;
let num_byes_addr =
RemotePtr::<u32>::cast(remote_ptr_field!(start, syscallbuf_hdr, num_rec_bytes));
if read_val_mem(
clone_leader,
remote_ptr_field!(start, syscallbuf_hdr, locked),
None,
) != 0u8
{
// The... | identifier_body | |
session.rs | number_for_munmap, syscall_number_for_openat,
SupportedArch,
},
log::LogDebug,
preload_interface::syscallbuf_hdr,
rd::RD_RESERVED_ROOT_DIR_FD,
remote_ptr::{RemotePtr, Void},
session::{
address_space::{
address_space::{AddressSpaceSharedPtr, Mapping},
memor... | else if m.local_addr.is_some() {
ed_assert_eq!(
clone_leader,
m.map.start(),
AddressSpace::preload_thread_locals_start()
);
} else if m.recorded_map.flags().contains(M... | {
group
.captured_memory
.push((m.map.start(), capture_syscallbuf(&m, &**clone_leader)));
} | conditional_block |
session.rs | number_for_munmap, syscall_number_for_openat,
SupportedArch,
},
log::LogDebug,
preload_interface::syscallbuf_hdr,
rd::RD_RESERVED_ROOT_DIR_FD,
remote_ptr::{RemotePtr, Void},
session::{
address_space::{
address_space::{AddressSpaceSharedPtr, Mapping},
memor... | (&self, vmuid: AddressSpaceUid) -> Option<AddressSpaceSharedPtr> {
self.finish_initializing();
// If the weak ptr was found, we _must_ be able to upgrade it!;
self.vm_map().get(&vmuid).map(|a| a.upgrade().unwrap())
}
/// Return a copy of `tg` with the same mappings.
/// NOTE: Called... | find_address_space | identifier_name |
session.rs | _number_for_munmap, syscall_number_for_openat,
SupportedArch,
},
log::LogDebug,
preload_interface::syscallbuf_hdr,
rd::RD_RESERVED_ROOT_DIR_FD,
remote_ptr::{RemotePtr, Void},
session::{
address_space::{
address_space::{AddressSpaceSharedPtr, Mapping},
memo... | for k in shared_maps_to_clone {
remap_shared_mmap(&mut remote, emu_fs, dest_emu_fs, k);
}
for t in vm.task_set().iter() {
if Rc::ptr_eq(&group_leader, &t) {
continue;
}
... | shared_maps_to_clone.push(k);
}
}
// Do this in a separate loop to avoid iteration invalidation issues | random_line_split |
validation_host.rs | // Copyright 2019-2020 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.
// Polkadot 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... | (&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "ValidationHostMemory")
}
}
impl std::ops::Deref for ValidationHostMemory {
type Target = SharedMem;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl std::ops::DerefMut for ValidationHostMemory {
fn deref_mut(&mut self) -> &mut Self::Ta... | fmt | identifier_name |
validation_host.rs | // Copyright 2019-2020 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.
// Polkadot 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... | if validation_code.len() > MAX_CODE_MEM {
return Err(ValidationError::InvalidCandidate(InvalidCandidate::CodeTooLarge(validation_code.len())));
}
// First, check if need to spawn the child process
self.start_worker(binary, args)?;
let memory = self.memory.as_mut()
.expect("memory is always `Some` after ... | validation_code: &[u8],
params: ValidationParams,
binary: &PathBuf,
args: &[&str],
) -> Result<ValidationResult, ValidationError> { | random_line_split |
validation_host.rs | // Copyright 2019-2020 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.
// Polkadot 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... |
}
{
debug!("{} Reading results", self.id);
let data: &[u8] = &**memory.wlock_as_slice(0)
.map_err(|e| ValidationError::Internal(e.into()))?;
let (header_buf, _) = data.split_at(MAX_VALIDATION_RESULT_HEADER_MEM);
let mut header_buf: &[u8] = header_buf;
let header = ValidationResultHeader::decode... | {} | conditional_block |
log_file.rs | use std::collections::{HashMap, HashSet};
use std::fmt;
use std::ffi::CString;
use std::io::{Result, Error, ErrorKind};
use std::os::unix::ffi::OsStrExt;
use std::path::{Path, PathBuf};
use libc;
use log::{error, info, warn};
use crate::{Data, ArcDataSlice};
use super::*;
pub(super) struct LogFile {
file_path: ... | (&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "CRL Sweeper File: {}", self.file_path.as_path().display())
}
}
#[cfg(target_os="linux")]
fn open_synchronous_fd(path: &CString) -> libc::c_int {
const O_DIRECT: libc::c_int = 0x4000;
const O_DSYNC: libc::c_int = 4000;
unsafe {
... | fmt | identifier_name |
log_file.rs | use std::collections::{HashMap, HashSet};
use std::fmt;
use std::ffi::CString;
use std::io::{Result, Error, ErrorKind};
use std::os::unix::ffi::OsStrExt;
use std::path::{Path, PathBuf};
use libc;
use log::{error, info, warn};
use crate::{Data, ArcDataSlice};
use super::*;
pub(super) struct LogFile {
file_path: ... |
impl Drop for LogFile {
fn drop(&mut self) {
unsafe {
libc::close(self.fd);
}
}
}
impl fmt::Display for LogFile {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "CRL Sweeper File: {}", self.file_path.as_path().display())
}
}
#[cfg(target_os="li... | fd: libc::c_int,
pub len: usize,
pub max_size: usize,
pub file_uuid: uuid::Uuid
} | random_line_split |
log_file.rs | use std::collections::{HashMap, HashSet};
use std::fmt;
use std::ffi::CString;
use std::io::{Result, Error, ErrorKind};
use std::os::unix::ffi::OsStrExt;
use std::path::{Path, PathBuf};
use libc;
use log::{error, info, warn};
use crate::{Data, ArcDataSlice};
use super::*;
pub(super) struct LogFile {
file_path: ... |
file_id = entry.previous_entry_location.file_id;
entry_block_offset = entry.previous_entry_location.offset as usize;
}
let get_data = |file_location: &FileLocation| -> Result<ArcData> {
let d = files[file_location.file_id.0 as usize].0.read(file_location.offset as ... | {
break; // Cannot have an offset of 0 (first 16 bytes of the file are the UUID)
} | conditional_block |
log_file.rs | use std::collections::{HashMap, HashSet};
use std::fmt;
use std::ffi::CString;
use std::io::{Result, Error, ErrorKind};
use std::os::unix::ffi::OsStrExt;
use std::path::{Path, PathBuf};
use libc;
use log::{error, info, warn};
use crate::{Data, ArcDataSlice};
use super::*;
pub(super) struct LogFile {
file_path: ... |
fn seek(fd: libc::c_int, offset: i64, whence: libc::c_int) -> Result<usize> {
unsafe {
let sz = libc::lseek(fd, offset, whence);
if sz < 0 {
Err(Error::last_os_error())
} else {
Ok(sz as usize)
}
}
}
fn find_last_valid_entry(
fd: libc::c_int,
f... | {
let p: *const u8 = &s[0];
unsafe {
if libc::write(fd, p as *const libc::c_void, s.len()) < 0 {
return Err(Error::last_os_error());
}
libc::fsync(fd);
}
Ok(())
} | identifier_body |
symm_icon.rs | // Symmetric Icons
#![allow(dead_code)]
use array2d::*;
// lambda, alpha, beta, gamma, omega, symmetry, scale
const PRESETS: [[f32; 7]; 36] = [
[1.56, -1., 0.1, -0.82, -0.3, 3., 1.7], [-1.806, 1.806, 0., 1.5, 0., 7., 1.1],
[2.4, -2.5, -0.9, 0.9, 0., 3., 1.5], [-2.7, 5., 1.5, 1., 0., 4., 1.],
[-2.... |
fn make_color(r : u32, g : u32, b : u32) -> u32 { (b << 16) | (g << 8) | r | 0xff00_0000 }
fn make_colora(a : u32, r : u32, g : u32, b : u32) -> u32 { (a << 24) | (b << 16) | (g << 8) | r }
fn get_rainbow(x : u32, y : u32) -> u32 {
match x {
0 => Self::make_color(0, y, 255),
... | {
self.lambda = lambda;
self.alpha = alpha;
self.beta = beta;
self.gamma = gamma;
self.omega = omega;
self.symmetry = if symmetry < 1. { 1 } else { symmetry as u32 };
self.scale = if scale == 0. {1.} else { scale };
self.reset();
} | identifier_body |
symm_icon.rs | // Symmetric Icons
#![allow(dead_code)]
use array2d::*;
// lambda, alpha, beta, gamma, omega, symmetry, scale
const PRESETS: [[f32; 7]; 36] = [
[1.56, -1., 0.1, -0.82, -0.3, 3., 1.7], [-1.806, 1.806, 0., 1.5, 0., 7., 1.1],
[2.4, -2.5, -0.9, 0.9, 0., 3., 1.5], [-2.7, 5., 1.5, 1., 0., 4., 1.],
[-2.... | self.iter = 0;
self.color_list = vec![];
self.reset();
}
pub fn set_preset(&mut self, i : usize) {
let p = PRESETS[i % PRESETS.len()];
self.lambda = p[0];
self.alpha = p[1];
self.beta = p[2];
self.gamma = p[3];
self.omega = p[4];
self.symmetry = p[5] as u32;
... | self.image = Array2D::filled_with(0_u32, w, h);
self.icon = Array2D::filled_with(0_u32, w, h); | random_line_split |
symm_icon.rs | // Symmetric Icons
#![allow(dead_code)]
use array2d::*;
// lambda, alpha, beta, gamma, omega, symmetry, scale
const PRESETS: [[f32; 7]; 36] = [
[1.56, -1., 0.1, -0.82, -0.3, 3., 1.7], [-1.806, 1.806, 0., 1.5, 0., 7., 1.1],
[2.4, -2.5, -0.9, 0.9, 0., 3., 1.5], [-2.7, 5., 1.5, 1., 0., 4., 1.],
[-2.... |
}
fn set_point(&mut self, x : usize, y : usize) {
let icon = self.icon[(x,y)];
let color = self.get_color(icon);
self.image[(x,y)] = color;
self.icon[(x,y)] += 1;
if icon >= 12288 { self.icon[(x,y)] = 8192 }
}
pub fn generate(&mut self, mod_disp : u32) -> bool ... | {
self.color_list[(col * self.speed) as usize]
} | conditional_block |
symm_icon.rs | // Symmetric Icons
#![allow(dead_code)]
use array2d::*;
// lambda, alpha, beta, gamma, omega, symmetry, scale
const PRESETS: [[f32; 7]; 36] = [
[1.56, -1., 0.1, -0.82, -0.3, 3., 1.7], [-1.806, 1.806, 0., 1.5, 0., 7., 1.1],
[2.4, -2.5, -0.9, 0.9, 0., 3., 1.5], [-2.7, 5., 1.5, 1., 0., 4., 1.],
[-2.... | (&mut self) {
self.speed = DEFAULT_SPEED;
self.apcx = self.w as f32 / 2.;
self.apcy = self.h as f32 / 2.;
self.rad = if self.apcx > self.apcy {self.apcy} else {self.apcx};
self.k = 0;
self.x = 0.01;
self.y = 0.003;
self.iter = 0;
self.icon = Arra... | reset | identifier_name |
component.rs | use crate::code::CodeObject;
use crate::signatures::SignatureCollection;
use crate::{Engine, Module, ResourcesRequired};
use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use std::fs;
use std::mem;
use std::path::Path;
use std::ptr::NonNull;
use std::sync::Arc;
use wasmtime_environ::component::{... | (engine: &Engine, path: impl AsRef<Path>) -> Result<Component> {
let code = engine.load_code_file(path.as_ref(), ObjectKind::Component)?;
Component::from_parts(engine, code, None)
}
/// Performs the compilation phase for a component, translating and
/// validating the provided wasm binary t... | deserialize_file | identifier_name |
component.rs | use crate::code::CodeObject;
use crate::signatures::SignatureCollection;
use crate::{Engine, Module, ResourcesRequired};
use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use std::fs;
use std::mem;
use std::path::Path;
use std::ptr::NonNull;
use std::sync::Arc;
use wasmtime_environ::component::{... |
/// Compiles a new WebAssembly component from the in-memory wasm image
/// provided.
//
// FIXME: need to write more docs here.
#[cfg(any(feature = "cranelift", feature = "winch"))]
#[cfg_attr(nightlydoc, doc(cfg(any(feature = "cranelift", feature = "winch"))))]
pub fn from_binary(engine: ... | {
match Self::new(
engine,
&fs::read(&file).with_context(|| "failed to read input file")?,
) {
Ok(m) => Ok(m),
Err(e) => {
cfg_if::cfg_if! {
if #[cfg(feature = "wat")] {
let mut e = e.downcast::<w... | identifier_body |
component.rs | use crate::code::CodeObject;
use crate::signatures::SignatureCollection;
use crate::{Engine, Module, ResourcesRequired};
use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use std::fs;
use std::mem;
use std::path::Path;
use std::ptr::NonNull;
use std::sync::Arc;
use wasmtime_environ::component::{... | }
pub(crate) fn runtime_info(&self) -> Arc<dyn ComponentRuntimeInfo> {
self.inner.clone()
}
/// Creates a new `VMFuncRef` with all fields filled out for the destructor
/// specified.
///
/// The `dtor`'s own `VMFuncRef` won't have `wasm_call` filled out but this
/// component m... | pub fn serialize(&self) -> Result<Vec<u8>> {
Ok(self.code_object().code_memory().mmap().to_vec()) | random_line_split |
annotate.rs | extern crate chrono;
extern crate id3;
extern crate mp3_duration;
extern crate regex;
extern crate reqwest;
use std::{
fs::{
read_dir,
rename,
},
io::{
Read,
},
iter::{
repeat_with,
},
path::{
Path,
PathBuf,
},
time::{
Duration... | (
album_full: &AlbumFull,
client_with_token: &ClientWithToken,
) -> Result<Vec<TrackData>, SimpleError> {
let mut tracks = Vec::new();
let mut paging = album_full.tracks.clone();
while let Some(next_url) = paging.next {
tracks.append(&mut paging.items);
paging = get_with_retry(
... | get_tracks_data | identifier_name |
annotate.rs | extern crate chrono;
extern crate id3;
extern crate mp3_duration;
extern crate regex;
extern crate reqwest;
use std::{
fs::{
read_dir,
rename,
},
io::{
Read,
},
iter::{
repeat_with,
},
path::{
Path,
PathBuf,
},
time::{
Duration... | }
fn annotate_tags(
tags: &mut Tag,
file: &PathBuf,
track_data: TrackData,
album_image: &Vec<u8>,
) -> String {
lazy_static! {
static ref INVALID_FILE_CHRS: Regex = Regex::new(r"[^\w\s.\(\)]+").unwrap();
}
let mut new_name = format!(
"{} {}.mp3",
norm_track_numb... | tags.album().expect("error in writing tags"),
tags.artist().expect("error in writing tags"),
),
data: image.clone(),
}); | random_line_split |
annotate.rs | extern crate chrono;
extern crate id3;
extern crate mp3_duration;
extern crate regex;
extern crate reqwest;
use std::{
fs::{
read_dir,
rename,
},
io::{
Read,
},
iter::{
repeat_with,
},
path::{
Path,
PathBuf,
},
time::{
Duration... |
if album_full.release_date_precision == "month" {
let date = NaiveDate::parse_from_str(
&album_full.release_date[..],
"%Y-%m",
)?;
year = date.year();
month = Some(date.month() as u8);
}
else if album_full.release_d... | {
let date = NaiveDate::parse_from_str(
&album_full.release_date[..],
"%Y",
)?;
year = date.year();
} | conditional_block |
annotate.rs | extern crate chrono;
extern crate id3;
extern crate mp3_duration;
extern crate regex;
extern crate reqwest;
use std::{
fs::{
read_dir,
rename,
},
io::{
Read,
},
iter::{
repeat_with,
},
path::{
Path,
PathBuf,
},
time::{
Duration... |
fn expected_time(
file: &PathBuf,
track_data: &TrackData,
) -> bool {
let actual_duration = mp3_duration::from_path(file.as_path()).expect(
&format!("error measuring {}", file.display())[..],
);
let expected_duration = Duration::from_millis(
track_data.expected_duration_ms as u64,
... | {
if track_number < 10 {
return format!("0{}", track_number);
}
track_number.to_string()
} | identifier_body |
terminal.rs | use std::{
io::{self, Write},
ops::Range,
cmp::min,
iter::Peekable
};
use crate::{
iface::{TerminalPlugin, FormatLike},
config
};
use smallvec::{smallvec, SmallVec};
use terminfo::{expand, Database, capability as cap};
// pub const CORNER_SW: char = '╗';
const CORNER_SE: char = '╔';
const COR... | t_split_idx == 0 {
last_char_idx
} else {
last_split_idx
}
}
impl Terminal {
fn writer<W>(&self, out: W) -> TermWriter<W>
where W: Write
{
TermWriter {
terminal: self,
out
}
}
fn calculate_layout(&self) -> Vec<LineLayout> {
... | _split_idx = idx;
}
}
if las | conditional_block |
terminal.rs | use std::{
io::{self, Write},
ops::Range,
cmp::min,
iter::Peekable
};
use crate::{
iface::{TerminalPlugin, FormatLike},
config
};
use smallvec::{smallvec, SmallVec};
use terminfo::{expand, Database, capability as cap};
// pub const CORNER_SW: char = '╗';
const CORNER_SE: char = '╔';
const COR... | t<(), io::Error> {
self.out.flush()
}
fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> {
self.out.write(buf)
}
}
#[derive(Debug)]
struct TextSegment {
text: String,
fmt: FormatLike,
pre_calculated_length: usize,
}
impl TextSegment {
pub fn new(text: impl Into<S... | Resul | identifier_name |
terminal.rs | use std::{
io::{self, Write},
ops::Range,
cmp::min,
iter::Peekable
};
use crate::{
iface::{TerminalPlugin, FormatLike},
config
};
use smallvec::{smallvec, SmallVec};
use terminfo::{expand, Database, capability as cap};
// pub const CORNER_SW: char = '╗';
const CORNER_SE: char = '╔';
const COR... | )]
pub struct Terminal {
column_count: usize,
text_segments: SmallVec<[SmallVec<[TextSegment; 2]>; 2]>,
error_segments: Vec<(&'static str, String)>,
terminfo: Database,
}
impl TerminalPlugin for Terminal {
fn new(column_count: usize) -> Self {
let terminfo = Database::from_env().unwrap();... | rmatLike::*;
match fmt {
Text => color::TEXT_WHITE,
PrimaryText => color::JUNGLE_GREEN,
Lines => color::LIGHT_GRAY,
SoftWarning => color::ORANGE,
HardWarning => color::SIGNALING_RED,
Error => color::RED,
ExplicitOk => color::BRIGHT_GREEN,
Hidden => co... | identifier_body |
terminal.rs | use std::{
io::{self, Write},
ops::Range,
cmp::min,
iter::Peekable
};
use crate::{
iface::{TerminalPlugin, FormatLike},
config
};
use smallvec::{smallvec, SmallVec};
use terminfo::{expand, Database, capability as cap};
// pub const CORNER_SW: char = '╗';
const CORNER_SE: char = '╔';
const COR... | self.add_text_segment(text, fmt_args);
}
fn flush_to_stdout(&self, prompt_ending: &str) {
//TODO split into multiple functions
// - one for outputting text segments
// - one for outputting error segments
let layout = self.calculate_layout();
let stdout = io::st... | }
} | random_line_split |
mock.rs | // This file is part of the SORA network and Polkaswap app.
// Copyright (c) 2020, 2021, Polka Biome Ltd. All rights reserved.
// SPDX-License-Identifier: BSD-4-Clause
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
... |
pub fn liquidity_provider_c() -> AccountId {
AccountId32::from([6u8; 32])
}
pub const DEX_A_ID: DEXId = common::DEXId::Polkaswap;
parameter_types! {
pub GetBaseAssetId: AssetId = common::XOR.into();
pub GetIncentiveAssetId: AssetId = common::PSWAP.into();
pub const PoolTokenAId: AssetId = common::As... | {
AccountId32::from([5u8; 32])
} | identifier_body |
mock.rs | // This file is part of the SORA network and Polkaswap app.
// Copyright (c) 2020, 2021, Polka Biome Ltd. All rights reserved.
// SPDX-License-Identifier: BSD-4-Clause
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
... | (accounts: Vec<(AccountId, AssetId, Balance)>) -> Self {
let permissioned_account_id = GetPswapDistributionAccountId::get();
Self {
endowed_accounts: accounts,
endowed_assets: vec control.
///
... | (&self,
set: bool, item_indexes: &[u32]) -> WinResult<()>
{
let mut lvi = LVITEM::default();
lvi.stateMask = co::LVIS::SELECTED;
if set { lvi.state = co::LVIS::SELECTED; }
for idx in item_indexes.iter() {
self.hwnd().SendMessage(lvm::SetItemState {
index: Some(*idx),
lvitem: &lvi,
}... | set_selected | identifier_name |
list_view_items.rs | use std::cell::Cell;
use std::ptr::NonNull;
use crate::aliases::WinResult;
use crate::co;
use crate::handles::HWND;
use crate::msg::lvm;
use crate::structs::{LVFINDINFO, LVHITTESTINFO, LVITEM, RECT};
use crate::various::WString;
/// Exposes item methods of a [`ListView`](crate::gui::ListView) control.
///
... | // Static method because it's also used by ListViewColumns.
// https://forums.codeguru.com/showthread.php?351972-Getting-listView-item-text-length
const BLOCK: usize = 64; // arbitrary
let mut buf_sz = BLOCK;
let mut buf = buf;
loop {
let mut lvi = LVITEM::default();
lvi.iSubItem = column... | {
| random_line_split |
lib.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
//! Library to build `Custom_tag` OCaml values.
use std::ffi::CStr;
use std::ffi::CString;
use std::mem::MaybeUninit;
use std::ops::Der... | // a CustomBlockOcamlRep<T> created by T::to_ocamlrep. Such a pointer
// would be aligned and valid.
let custom_block_ptr = value as *mut CustomBlockOcamlRep<T>;
let custom_block = unsafe { custom_block_ptr.as_mut().unwrap() };
// The `Rc` will be dropped here, and its reference... | // Safety: We trust here that CustomOperations structs containing this
// `drop_value` instance will only ever be referenced by custom blocks
// matching the layout of `CustomBlockOcamlRep`. If that's so, then this
// function should only be invoked by the OCaml runtime on a pointer to | random_line_split |
lib.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
//! Library to build `Custom_tag` OCaml values.
use std::ffi::CStr;
use std::ffi::CString;
use std::mem::MaybeUninit;
use std::ops::Der... | <T: CamlSerialize>(value: usize) {
let _: usize = catch_unwind(|| {
// Safety: We trust here that CustomOperations structs containing this
// `drop_value` instance will only ever be referenced by custom blocks
// matching the layout of `CustomBlockOcamlRep`. If that's so, then this
/... | drop_value | identifier_name |
lib.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
//! Library to build `Custom_tag` OCaml values.
use std::ffi::CStr;
use std::ffi::CString;
use std::mem::MaybeUninit;
use std::ops::Der... |
}
| {
assert_eq!(
align_of::<CustomBlockOcamlRep<u8>>(),
align_of::<Value<'_>>()
);
} | identifier_body |
lib.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
//! Library to build `Custom_tag` OCaml values.
use std::ffi::CStr;
use std::ffi::CString;
use std::mem::MaybeUninit;
use std::ops::Der... |
let value_ptr = value.to_bits() as *const CustomBlockOcamlRep<T>;
// Safety: `value_ptr` is guaranteed to be aligned to
// `align_of::<Value>()`, and our use of `expect_block_size` guarantees
// that the pointer is valid for reads of `CUSTOM_BLOCK_SIZE_IN_WORDS *
// `size_of::<Value>()` bytes. Si... | {
return Err(FromError::UnexpectedCustomOps {
expected: ops as *const _ as usize,
actual: block[0].to_bits(),
});
} | conditional_block |
test.rs | // Code that generates a test runner to run all the tests in a crate
#![allow(dead_code)]
#![allow(unused_imports)]
use HasTestSignature::*;
use std::iter;
use std::slice;
use std::mem;
use std::vec;
use log::debug;
use smallvec::{smallvec, SmallVec};
use syntax_pos::{DUMMY_SP, NO_EXPANSION, Span, SourceFile, ByteP... |
fn get_test_runner(sd: &errors::Handler, krate: &ast::Crate) -> Option<ast::Path> {
let test_attr = attr::find_by_name(&krate.attrs, "test_runner")?;
test_attr.meta_item_list().map(|meta_list| {
if meta_list.len()!= 1 {
sd.span_fatal(test_attr.span,
"#![test_runner(..)] acc... | {
attr::contains_name(&i.attrs, "rustc_test_marker")
} | identifier_body |
test.rs | // Code that generates a test runner to run all the tests in a crate
#![allow(dead_code)]
#![allow(unused_imports)]
use HasTestSignature::*;
use std::iter;
use std::slice;
use std::mem;
use std::vec;
use log::debug;
use smallvec::{smallvec, SmallVec};
use syntax_pos::{DUMMY_SP, NO_EXPANSION, Span, SourceFile, ByteP... | fn flat_map_item(&mut self, i: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
self.depth += 1;
let item = noop_flat_map_item(i, self).expect_one("noop did something");
self.depth -= 1;
// Remove any #[main] or #[start] from the AST so it doesn't
// clash with the one we're g... |
impl MutVisitor for EntryPointCleaner { | random_line_split |
test.rs | // Code that generates a test runner to run all the tests in a crate
#![allow(dead_code)]
#![allow(unused_imports)]
use HasTestSignature::*;
use std::iter;
use std::slice;
use std::mem;
use std::vec;
use log::debug;
use smallvec::{smallvec, SmallVec};
use syntax_pos::{DUMMY_SP, NO_EXPANSION, Span, SourceFile, ByteP... | (&mut self, i: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
let ident = i.ident;
if ident.name!= keywords::Invalid.name() {
self.cx.path.push(ident);
}
debug!("current path: {}", path_name_i(&self.cx.path));
let mut item = i.into_inner();
if is_test_case(&i... | flat_map_item | identifier_name |
dac.rs | //! Stabilizer DAC management interface
//!
//! # Design
//!
//! Stabilizer DACs are connected to the MCU via a simplex, SPI-compatible interface. Each DAC
//! accepts a 16-bit output code.
//!
//! In order to maximize CPU processing time, the DAC code updates are offloaded to hardware using
//! a timer compare channel... | (value: u16) -> Self {
Self(value)
}
}
macro_rules! dac_output {
($name:ident, $index:literal, $data_stream:ident,
$spi:ident, $trigger_channel:ident, $dma_req:ident) => {
/// $spi is used as a type for indicating a DMA transfer into the SPI TX FIFO
struct $spi {
spi: h... | from | identifier_name |
dac.rs | //! Stabilizer DAC management interface
//!
//! # Design
//!
//! Stabilizer DACs are connected to the MCU via a simplex, SPI-compatible interface. Each DAC
//! accepts a 16-bit output code.
//!
//! In order to maximize CPU processing time, the DAC code updates are offloaded to hardware using
//! a timer compare channel... |
}
macro_rules! dac_output {
($name:ident, $index:literal, $data_stream:ident,
$spi:ident, $trigger_channel:ident, $dma_req:ident) => {
/// $spi is used as a type for indicating a DMA transfer into the SPI TX FIFO
struct $spi {
spi: hal::spi::Spi<hal::stm32::$spi, hal::spi::Disable... | {
Self(value)
} | identifier_body |
dac.rs | //! Stabilizer DAC management interface
//!
//! # Design
//!
//! Stabilizer DACs are connected to the MCU via a simplex, SPI-compatible interface. Each DAC
//! accepts a 16-bit output code.
//!
//! In order to maximize CPU processing time, the DAC code updates are offloaded to hardware using
//! a timer compare channel... |
}
}
impl From<DacCode> for f32 {
fn from(code: DacCode) -> f32 {
i16::from(code) as f32 * DacCode::VOLT_PER_LSB
}
}
impl From<DacCode> for i16 {
fn from(code: DacCode) -> i16 {
(code.0 as i16).wrapping_sub(i16::MIN)
}
}
impl From<i16> for DacCode {
/// Encode signed 16-bit va... | {
Ok(DacCode::from(code as i16))
} | conditional_block |
dac.rs | //! Stabilizer DAC management interface
//!
//! # Design
//!
//! Stabilizer DACs are connected to the MCU via a simplex, SPI-compatible interface. Each DAC
//! accepts a 16-bit output code.
//!
//! In order to maximize CPU processing time, the DAC code updates are offloaded to hardware using
//! a timer compare channel... | ///
/// # Args
/// * `spi` - The SPI interface used to communicate with the ADC.
/// * `stream` - The DMA stream used to write DAC codes over SPI.
/// * `trigger_channel` - The sampling timer output compare channel for update triggers.
pub fn new(
... | >,
}
impl $name {
/// Construct the DAC output channel. | random_line_split |
storage.rs | use regex::Regex;
use std::collections::HashMap;
use std::path::Path;
use std::sync::Mutex;
use log::{error, info};
use r2d2_sqlite::SqliteConnectionManager;
use rusqlite::params;
use rusqlite_migration::{Migrations, M};
use super::errors::Error;
pub type DatabaseConnection = r2d2::PooledConnection<SqliteConnectionM... |
// Rooms
pub const PENDING_TOKEN_EXPIRATION: i64 = 10 * 60;
pub const TOKEN_EXPIRATION: i64 = 7 * 24 * 60 * 60;
pub const FILE_EXPIRATION: i64 = 15 * 24 * 60 * 60;
lazy_static::lazy_static! {
static ref POOLS: Mutex<HashMap<String, DatabaseConnectionPool>> = Mutex::new(HashMap::new());
}
pub fn pool_by_room_i... | {
let main_table_cmd = "CREATE TABLE IF NOT EXISTS main (
id TEXT PRIMARY KEY,
name TEXT,
image_id TEXT
)";
conn.execute(&main_table_cmd, params![]).expect("Couldn't create main table.");
} | identifier_body |
storage.rs | use regex::Regex;
use std::collections::HashMap;
use std::path::Path;
use std::sync::Mutex;
use log::{error, info};
use r2d2_sqlite::SqliteConnectionManager;
use rusqlite::params;
use rusqlite_migration::{Migrations, M};
use super::errors::Error;
pub type DatabaseConnection = r2d2::PooledConnection<SqliteConnectionM... | Ok(_) => (),
Err(e) => return error!("Couldn't prune pending tokens due to error: {}.", e),
};
}
info!("Pruned pending tokens.");
}
fn get_expired_file_ids(
pool: &DatabaseConnectionPool, file_expiration: i64,
) -> Result<Vec<String>, ()> {
let now = chrono::Utc::now().t... | };
let stmt = "DELETE FROM pending_tokens WHERE timestamp < (?1)";
let now = chrono::Utc::now().timestamp();
let expiration = now - PENDING_TOKEN_EXPIRATION;
match conn.execute(&stmt, params![expiration]) { | random_line_split |
storage.rs | use regex::Regex;
use std::collections::HashMap;
use std::path::Path;
use std::sync::Mutex;
use log::{error, info};
use r2d2_sqlite::SqliteConnectionManager;
use rusqlite::params;
use rusqlite_migration::{Migrations, M};
use super::errors::Error;
pub type DatabaseConnection = r2d2::PooledConnection<SqliteConnectionM... | (conn: &DatabaseConnection) {
let main_table_cmd = "CREATE TABLE IF NOT EXISTS main (
id TEXT PRIMARY KEY,
name TEXT,
image_id TEXT
)";
conn.execute(&main_table_cmd, params![]).expect("Couldn't create main table.");
}
// Rooms
pub const PENDING_TOKEN_EXPIRATION: i64 = 10 * 60;
pub ... | create_main_tables_if_needed | identifier_name |
decode.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use crate::unescape::unescape;
use std::borrow::Cow;
use std::convert::TryFrom;
use thiserror::Error;
use xmlparser::{ElementEnd, Token, Tokenizer};
pub type Depth = usize;
// in general, these errors... | <'a> {
pub prefix: &'a str,
pub local: &'a str,
}
impl Name<'_> {
/// Check if a given name matches a tag name composed of `prefix:local` or just `local`
pub fn matches(&self, tag_name: &str) -> bool {
let split = tag_name.find(':');
match split {
None => tag_name == self.lo... | Name | identifier_name |
decode.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use crate::unescape::unescape;
use std::borrow::Cow;
use std::convert::TryFrom;
use thiserror::Error;
use xmlparser::{ElementEnd, Token, Tokenizer};
pub type Depth = usize;
// in general, these errors... |
/// Prefix component of this elements name (or empty string)
/// ```xml
/// <foo:bar>
/// ^^^
/// ```
pub fn prefix(&self) -> &str {
self.name.prefix
}
/// Returns true of `el` at `depth` is a match for this `start_el`
fn end_el(&self, el: ElementEnd, depth: Depth) -> boo... | {
self.name.local
} | identifier_body |
decode.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use crate::unescape::unescape;
use std::borrow::Cow;
use std::convert::TryFrom;
use thiserror::Error;
use xmlparser::{ElementEnd, Token, Tokenizer};
pub type Depth = usize;
// in general, these errors... | /// <Nested /> <-- next call returns this
/// <MoreNested>hello</MoreNested> <-- then this:
/// </A>
/// <B/> <-- second call to next_tag returns this
/// </Response>
/// ```
pub fn next_start_element<'a>(&'a mut self) -> Option<StartEl<'inp>> {
next_start_element(sel... | random_line_split | |
channel_router.rs | // Copyright 2019 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | else {
self.tasks.insert(from, vec![to]);
}
}
fn into_tasks(mut self, src: &ChannelLayout) -> Vec<Task> {
self.tasks
.drain()
.map(|(k, v)| {
let net = match src[k] {
ChannelState::Net(i) => i,
_ => unrea... | {
k.push(to);
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.