content
stringlengths 12
392k
| id
int64 0
1.08k
|
|---|---|
fn main() -> Result<()> {
let args = Args::parse();
let Args {
aspect_ratio,
image_width,
image_height,
samples_per_pixel,
outfile,
max_depth,
} = args;
let (stats_tx, stats_rx) = unbounded();
let (render_tx, render_rx) = bounded(1024);
let look_from = Point3::new(13.0, 2.0, 3.0);
let look_at = Point3::new(0.0, 0.0, 0.0);
// Camera
let camera = Camera::new(
look_from,
look_at,
Vec3::new(0.0, 1.0, 0.0),
20.0,
aspect_ratio,
0.1,
10.0,
);
// World
let world = World::get_world(true);
let color_handle = thread::spawn(move || {
pixels::pixel_loop(
&camera,
&world,
image_width,
image_height,
samples_per_pixel,
max_depth,
stats_tx,
render_tx,
)
});
let stats_handle = thread::spawn(move || {
stats::stats_loop(
stats_rx,
((image_width as f32 * image_height as f32 * 11.3) as usize + 24) as usize,
)
});
let render_handle = thread::spawn(move || render::render_loop(&outfile, render_rx));
let color_io_result = color_handle.join().unwrap();
let stats_io_result = stats_handle.join().unwrap();
let render_io_result = render_handle.join().unwrap();
color_io_result?;
stats_io_result?;
render_io_result?;
Ok(())
}
| 600
|
fn test_where() {
let module = make_module(
indoc! {r#"
-- taken from http://learnyouahaskell.com/syntax-in-functions#pattern-matching
str_imc w h =
if bmi <= 18.5 then "You're underweight, you emo, you!"
elif bmi <= 25.0 then "You're supposedly normal. Pffft, I bet you're ugly!"
elif bmi <= 30.0 then "You're fat! Lose some weight, fatty!"
else "You're a whale, congratulations!"
where
bmi = w / h ^ 2
"#},
default_sym_table(),
);
assert!(module.is_ok());
let module = module.unwrap();
let decls = module.get_decls();
assert_eq!(
decls[0].get_type(),
Some(FuncType::new_func_type(
Some(vec![BasicType::int(), BasicType::int()]),
BasicType::static_str(),
))
);
}
| 601
|
fn parse_file(file_name: &str) -> Vec<Instruction> {
let f = File::open(file_name).expect("Could not open the specified file.");
let reader = BufReader::new(f);
reader
.lines()
.map(|lr| lr.expect("Could not read a line."))
.map(|l| parse_instruction(&l))
.collect()
}
| 602
|
fn number_vectorizer(card_digits: &String) {
let mut card_number: [u32; 16] = [0; 16];
let mut index = 0;
for digit in card_digits.chars() {
card_number[index] = digit.to_digit(10).expect("Non number on credit card");
index += 1;
}
credit_checksum(&mut card_number);
}
| 603
|
fn main() {
let input = "49276d206b696c6c696e6720796f757220627261696e20\
6c696b65206120706f69736f6e6f7573206d757368726f6f6d";
println!("{}", encoding::hexstr_to_base64str(input));
}
| 604
|
pub extern "x86-interrupt" fn not_use_0() { CommonInterruptHandler(42); }
| 605
|
fn part_2() {
let re = Regex::new(r".*=(-?\d+)\.+(-?\d+).*=(-?\d+)\.+(-?\d+).*=(-?\d+)\.+(-?\d+)").unwrap();
let mut cubiods: Vec<Cuboid> = Vec::new();
for l in include_str!("input.txt").split("\n") {
let t: Vec<_> = re
.captures(l)
.unwrap()
.iter()
.skip(1)
.map(|x| x.unwrap().as_str().parse::<i64>().unwrap())
.collect();
let new_c = Cuboid::new(t[0], t[1], t[2], t[3], t[4], t[5]);
cubiods.iter_mut().for_each(|x| x.substraction(&new_c));
if l.contains("on") {
cubiods.push(new_c);
}
}
let s = cubiods.iter().map(|x| x.volume() as u128).sum::<u128>();
println!("{}", s);
}
| 606
|
pub fn test_op_rvc_slli_crash_32() {
let buffer = fs::read("tests/programs/op_rvc_slli_crash_32")
.unwrap()
.into();
let result = run::<u32, SparseMemory<u32>>(&buffer, &vec!["op_rvc_slli_crash_32".into()]);
assert!(result.is_ok());
}
| 607
|
fn make_field(doc: &Option<String>, ident: &syn::Ident, ty: syn::Type) -> syn::Field {
let mut attrs = Vec::new();
if let Some(doc) = doc {
let doc = syn::LitStr::new(&markdown::sanitize(&doc), Span::call_site());
use syn::parse::Parser;
attrs = syn::Attribute::parse_outer
.parse2(quote! {
#[doc=#doc]
})
.expect("failed to parse doc string");
}
syn::Field {
attrs,
vis: syn::parse_quote! {pub},
ident: Some(ident.clone()),
colon_token: Some(syn::parse_quote! {:}),
ty: parse_quote! {::std::option::Option<#ty>},
}
}
| 608
|
fn main() {
println!("Common letters in the box ids: {}",
match find_common_id() {
Some(s) => s,
None => "NA".to_string()
});
}
| 609
|
pub
fn
fetch_update
<
F
>
(
&
self
mut
f
:
F
)
-
>
Result
<
T
T
>
where
F
:
FnMut
(
T
)
-
>
Option
<
T
>
{
let
mut
prev
=
self
.
load
(
)
;
while
let
Some
(
next
)
=
f
(
prev
)
{
match
self
.
compare_exchange
(
prev
next
)
{
x
Ok
(
_
)
=
>
return
x
Err
(
next_prev
)
=
>
prev
=
next_prev
}
}
Err
(
prev
)
}
| 610
|
fn item_query() {
let dir = TestDir::new("sit", "query");
dir.cmd()
.arg("init")
.expect_success();
dir.create_file(".sit/reducers/test.js",r#"
module.exports = function(state, record) {
return Object.assign(state, {value: "hello"});
}
"#);
let id = String::from_utf8(dir.cmd().arg("item").expect_success().stdout).unwrap();
// create a record
Repository::open(dir.path(".sit")).unwrap().item(id.trim()).unwrap().new_record(vec![("test", &b""[..])].into_iter(), true).unwrap();
let output = String::from_utf8(dir.cmd().args(&["reduce", id.trim(), "-q", "join(' ', ['item', id, value])"]).expect_success().stdout).unwrap();
assert_eq!(output.trim(), format!("item {} hello", id.trim()));
}
| 611
|
pub fn task_set_instruction_pointer(target: CAddr, ptr: u64) {
system_call(SystemCall::TaskSetInstructionPointer {
request: (target, ptr),
});
}
| 612
|
pub unsafe fn mmap_trimmed_anonymous(size: usize) -> io::Result<Ptr> {
let aligned_size = alignment_size(size);
let desired = size;
let ptr = mmap_without_fd(size)?;
let addr = ptr as usize;
let padding_start= addr + (BLOCK_SIZE - PAGE_SIZE);
let aligned_addr = padding_start & BLOCK_MASK;
let lower_size = aligned_addr - addr;
if lower_size > 0 {
debug_assert!(munmap(ptr, lower_size) >= 0);
}
let higher_size = aligned_size - (desired + lower_size);
if higher_size > 0 {
let high_pos = aligned_addr + desired;
debug_assert!(munmap(high_pos as Ptr, higher_size) >= 0 );
}
Ok(aligned_addr as Ptr)
}
| 613
|
pub fn causet_partitioner_result_free(result: Box<CausetPartitionerResult>) {
}
| 614
|
pub
const
fn
new
(
val
:
T
)
-
>
AtomicCell
<
T
>
{
AtomicCell
{
value
:
UnsafeCell
:
:
new
(
MaybeUninit
:
:
new
(
val
)
)
}
}
pub
fn
into_inner
(
self
)
-
>
T
{
let
this
=
ManuallyDrop
:
:
new
(
self
)
;
unsafe
{
this
.
as_ptr
(
)
.
read
(
)
}
}
pub
const
fn
is_lock_free
(
)
-
>
bool
{
atomic_is_lock_free
:
:
<
T
>
(
)
}
pub
fn
store
(
&
self
val
:
T
)
{
if
mem
:
:
needs_drop
:
:
<
T
>
(
)
{
drop
(
self
.
swap
(
val
)
)
;
}
else
{
unsafe
{
atomic_store
(
self
.
as_ptr
(
)
val
)
;
}
}
}
pub
fn
swap
(
&
self
val
:
T
)
-
>
T
{
unsafe
{
atomic_swap
(
self
.
as_ptr
(
)
val
)
}
}
#
[
inline
]
pub
fn
as_ptr
(
&
self
)
-
>
*
mut
T
{
self
.
value
.
get
(
)
.
cast
:
:
<
T
>
(
)
}
}
impl
<
T
:
Default
>
AtomicCell
<
T
>
{
pub
fn
take
(
&
self
)
-
>
T
{
self
.
swap
(
Default
:
:
default
(
)
)
}
}
impl
<
T
:
Copy
>
AtomicCell
<
T
>
{
pub
fn
load
(
&
self
)
-
>
T
{
unsafe
{
atomic_load
(
self
.
as_ptr
(
)
)
}
}
}
| 615
|
async fn retrieve_pairs() {
let exchange = init().await;
let pairs = exchange.refresh_market_info().await.unwrap();
println!("{:?}", pairs);
}
| 616
|
fn main() {
// ใใฟใผใณ
// ใใฟใผใณใซใฏไธใค่ฝใจใ็ฉดใใใใพใใ
// ๆฐใใๆ็ธใๅฐๅ
ฅใใไปใฎๆงๆใจๅๆงใใใฟใผใณใฏใทใฃใใผใคใณใฐใใใพใใไพใใฐ๏ผ
let x = 'x';
let c = 'c';
match c {
x => println!("x: {} c: {}", x, c), // ๅ
ใฎxใใทใฃใใผใคใณใฐใใใฆใๅฅใฎxใจใใฆๅไฝใใฆใใใ
}
println!("x: {}", x);
// x => ใฏๅคใใใฟใผใณใซใใใใใใใใใใฎ่
ๅ
ใงๆๅนใช x ใจใใๅๅใฎๆ็ธใๅฐๅ
ฅใใพใใ
// ๆขใซ x ใจใใๆ็ธใๅญๅจใใฆใใใฎใงใๆฐใใซๅฐๅ
ฅใใ x ใฏใใใฎๅคใ x ใใทใฃใใผใคใณใฐใใพใใ
// ่คๅผใใฟใผใณ
let x2 = 1;
match x2 {
1 | 2 => println!("one or two"),
3 => println!("three"),
_ => println!("anything"),
}
// ๅ้
ๆ็ธ
let origin = Point { x: 0, y: 0 };
match origin {
Point { x, y } => println!("({},{})", x, y),
}
// ๅคใซๅฅใฎๅๅใไปใใใใจใใฏใ : ใไฝฟใใใจใใงใใพใใ
let origin2 = Point { x: 0, y: 0 };
match origin2 {
Point { x: x1, y: y1 } => println!("({},{})", x1, y1),
}
// ๅคใฎไธ้จใซใ ใ่ๅณใใใๅ ดๅใฏใๅคใฎใในใฆใซๅๅใไปใใๅฟ
่ฆใฏใใใพใใใ
let origin = Point { x: 0, y: 0 };
match origin {
Point { x, .. } => println!("x is {}", x),
}
// ๆๅใฎใกใณใใ ใใงใชใใใฉใฎใกใณใใซๅฏพใใฆใใใฎ็จฎใฎใใใใ่กใใใจใใงใใพใใ
let origin = Point { x: 0, y: 0 };
match origin {
Point { y, .. } => println!("y is {}", y),
}
// ๆ็ธใฎ็ก่ฆ
let some_value: Result<i32, &'static str> = Err("There was an error");
match some_value {
Ok(value) => println!("got a value: {}", value),
Err(_) => println!("an error occurred"),
}
// ใใใงใฏใใฟใใซใฎๆๅใจๆๅพใฎ่ฆ็ด ใซ x ใจ z ใๆ็ธใใพใใ
fn coordinate() -> (i32, i32, i32) {
// generate and return some sort of triple tuple
// 3่ฆ็ด ใฎใฟใใซใ็ๆใใฆ่ฟใ
(1, 2, 3)
}
let (x, _, z) = coordinate();
// ๅๆงใซ .. ใงใใฟใผใณๅ
ใฎ่คๆฐใฎๅคใ็ก่ฆใใใใจใใงใใพใใ
enum OptionalTuple {
Value(i32, i32, i32),
Missing,
}
let x = OptionalTuple::Value(5, -2, 3);
match x {
OptionalTuple::Value(..) => println!("Got a tuple!"),
OptionalTuple::Missing => println!("No such luck."),
}
// ref ใจ ref mut
// ๅ็
ง ใๅๅพใใใใจใใฏ ref ใญใผใฏใผใใไฝฟใใพใใใใ
let x3 = 5;
match x3 {
ref r => println!("Got a reference to {}", r),
}
// ใใฅใผใฟใใซใชๅ็
งใๅฟ
่ฆใชๅ ดๅใฏใๅๆงใซ ref mut ใไฝฟใใพใใ
let mut x = 5;
match x {
ref mut mr => {
*mr += 1;
println!("Got a mutable reference to {}", mr);
},
}
println!("x = {}", x); // ๅคใๆธใๆใใฃใฆใใใ
// ็ฏๅฒ
let x = 1;
match x {
1 ... 5 => println!("one through five"),
_ => println!("anything"),
}
// ็ฏๅฒใฏๅคใใฎๅ ดๅใๆดๆฐใ char ๅใงไฝฟใใใพใ๏ผ
let x = '๐
';
match x {
'a' ... 'j' => println!("early letter"),
'k' ... 'z' => println!("late letter"),
_ => println!("something else"),
}
// ๆ็ธ
let x = 1;
match x {
e @ 1 ... 5 => println!("got a range element {}", e),
_ => println!("anything"),
}
// ๅ
ๅดใฎ name ใฎๅคใธใฎๅ็
งใซ a ใๆ็ธใใพใใ
#[derive(Debug)]
struct Person {
name: Option<String>,
}
let name = "Steve".to_string();
let mut x: Option<Person> = Some(Person { name: Some(name) });
match x {
Some(Person { name: ref a @ Some(_), .. }) => println!("{:?}", a),
_ => {}
}
// @ ใ | ใจ็ตใฟๅใใใฆไฝฟใๅ ดๅใฏใใใใใใฎใใฟใผใณใงๅใๅๅใๆ็ธใใใใใใซใใๅฟ
่ฆใใใใพใ๏ผ
let x = 5;
match x {
e @ 1 ... 5 | e @ 8 ... 10 => println!("got a range element {}", e),
_ => println!("anything"),
}
// ใฌใผใ
// if ใไฝฟใใใจใงใใใใฌใผใใๅฐๅ
ฅใใใใจใใงใใพใ๏ผ
enum OptionalInt {
Value(i32),
Missing,
}
let x = OptionalInt::Value(5);
match x {
OptionalInt::Value(i) if i > 5 => println!("Got an int bigger than five!"),
OptionalInt::Value(..) => println!("Got an int!"),
OptionalInt::Missing => println!("No such luck."),
}
// ่คๅผใใฟใผใณใง if ใไฝฟใใจใ if ใฏ | ใฎไธกๅดใซ้ฉ็จใใใพใ๏ผ
let x = 4;
let y = false;
match x {
4 | 5 if y => println!("yes"),
_ => println!("no"),
}
// ใคใกใผใธ๏ผ (4 | 5) if y => ...
// ๆททใใฆใใใ
// ใใใใใใจใซๅฟใใฆใใใใใๆททใใฆใใใใใใใใจใใงใใพใ๏ผ
// match x {
// Foo { x: Some(ref name), y: None } => { println!("foo"); },
// }
// ใใฟใผใณใฏใจใฆใๅผทๅใงใใไธๆใซไฝฟใใพใใใใ
}
| 617
|
pub extern "x86-interrupt" fn FPU_error() { CommonExceptionHandler(16); }
| 618
|
pub fn data_type<'a>() -> Parser<'a, char, DataType> {
ident().convert(|v| DataType::match_data_type(&v))
}
| 619
|
fn do_extract_comment_blocks(text: &str, allow_blocks_with_empty_lines: bool) -> Vec<Vec<String>> {
let mut res = Vec::new();
let prefix = "// ";
let lines = text.lines().map(str::trim_start);
let mut block = vec![];
for line in lines {
if line == "//" && allow_blocks_with_empty_lines {
block.push(String::new());
continue;
}
let is_comment = line.starts_with(prefix);
if is_comment {
block.push(line[prefix.len()..].to_string());
} else if !block.is_empty() {
res.push(mem::replace(&mut block, Vec::new()));
}
}
if !block.is_empty() {
res.push(mem::replace(&mut block, Vec::new()))
}
res
}
| 620
|
fn inc_9() {
run_test(&Instruction { mnemonic: Mnemonic::INC, operand1: Some(Direct(CL)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[254, 193], OperandSize::Qword)
}
| 621
|
fn main() -> ! {
let (mut leds, rcc, tim6) = aux9_tasks::init();
// Power on the TIM6 timer
rcc.apb1enr.modify(|_, w| w.tim6en().set_bit());
// SR, the status register.
// EGR, the event generation register.
// CNT, the counter register.
// PSC, the prescaler register.
// ARR, the autoreload register.
// CR1 Control Register 1
// OPM Select one pulse mode
// CEN Counter Enable - Keep the counter disabled for now
tim6.cr1.write(|w| w.opm().set_bit().cen().clear_bit());
// Configure the prescaler to have the counter operate at 1 KHz
// PSC Pre-scaler
// Remember that the frequency of the counter is apb1 / (psc + 1) and that apb1 is 8 MHz.
// APB1_CLOCK = 8 MHz
// 8 MHz / (7999 + 1) = 1 KHz
// The counter (CNT) will increase on every millisecond
tim6.psc.write(|w| w.psc().bits(7999));
let cycle_ms = 200;
let mut seq_idx = 0;
let led_tasks: [i32; 8] = [1, 2, 4, 8, 16, 32, 64, 128];
loop {
// Set the timer to go off in half of `cycle_ms` ticks
// 1 tick = 1 ms
tim6.arr.write(|w| w.arr().bits(cycle_ms / 2));
// CEN: Enable the counter
tim6.cr1.modify(|_, w| w.cen().set_bit());
for led_idx in 0..8 {
if ((seq_idx / led_tasks[led_idx]) % 2) == 0 {
leds[led_idx].on();
} else {
leds[led_idx].off();
}
}
// Update LED sequence index
seq_idx = seq_idx + 1;
if seq_idx == led_tasks[7] * 2 {
seq_idx = 0;
}
// Wait until the alarm goes off (until the update event occurs)
// SR, Status Register
// UIF, Update Interrupt Flag
while !tim6.sr.read().uif().bit_is_set() {}
// Clear the update event flag
tim6.sr.modify(|_, w| w.uif().clear_bit());
}
}
| 622
|
pub fn read_lines(filename: Box<&Path>) -> io::Result<io::Lines<io::BufReader<File>>> {
let file = File::open(*filename)?;
Ok(io::BufReader::new(file).lines())
}
| 623
|
pub fn assign(lhs_node: Node, token: Token, rhs_node: Node) -> Node {
match lhs_node {
Node::LVasgn(var_str, mut nodes) => {
nodes.push(rhs_node);
return Node::LVasgn(var_str, nodes);
},
_ => { panic!("node::assign UNIMPL"); }
}
}
| 624
|
async fn order_book() {
let exchange = init().await;
let req = OrderBookRequest {
market_pair: "eth_btc".to_string(),
};
let resp = exchange.order_book(&req).await.unwrap();
println!("{:?}", resp);
}
| 625
|
fn loadResFromMesh(model: &mut Model, meshFilePath: &str) {}
| 626
|
fn a_table_should_reject_a_stale_write() {
let mut table = HashMapOfTreeMap::new();
table.write(0, &[Row { k: 0, v: 1 }]);
assert_eq!(table.write(0, &[Row { k: 0, v: 2 }]), WriteResult::Stale { cond: 0, max: 1 });
let mut vs = [Value::default(); 1];
table.read (1, &[0], &mut vs);
assert_eq!(vs, [Value { v: 1, t: 1 }]);
}
| 627
|
async fn run_manpage(_args: Args) -> Result<()> {
info!(version=%env!("CARGO_PKG_VERSION"), "constructing manpage");
let man = Man::new(Args::command().long_version(None));
let mut buffer: Vec<u8> = Default::default();
man.render(&mut buffer).into_diagnostic()?;
if std::io::stdout().is_terminal() && which::which("man").is_ok() {
let mut child = Command::new("man")
.arg("-l")
.arg("-")
.stdin(Stdio::piped())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.group()
.kill_on_drop(true)
.spawn()
.into_diagnostic()?;
child
.inner()
.stdin
.as_mut()
.unwrap()
.write_all(&buffer)
.await
.into_diagnostic()?;
if let Some(code) = child
.wait()
.await
.into_diagnostic()?
.code()
.and_then(|code| if code == 0 { None } else { Some(code) })
{
return Err(miette::miette!("Exited with status code {}", code));
}
} else {
std::io::stdout()
.lock()
.write_all(&buffer)
.into_diagnostic()?;
}
Ok(())
}
| 628
|
pub fn get_home() -> Result<String, ()> {
match dirs::home_dir() {
None => Ok(String::new()),
Some(path) => Ok(path.to_str().unwrap().to_string()),
}
}
| 629
|
pub fn exe_phdrs() -> (*const c_void, usize) {
imp::process::exe_phdrs()
}
| 630
|
pub fn format_pbs_duration(duration: &Duration) -> String {
format_duration(duration)
}
| 631
|
fn create_tap() -> AppResult<TapInfo> {
// create tap
inner_create_tap("tap0")
}
| 632
|
fn parse_bag_name(input: &str) -> IResult<&str, &str> {
let input = skip_whitespace(input);
let (input, name) = recognize(tuple((alpha1, space1, alpha1)))(input)?;
let input = skip_whitespace(input);
let (input, _) = tag("bag")(input)?;
let (input, _) = opt(char('s'))(input)?;
let input = skip_whitespace(input);
Ok((input, name))
}
| 633
|
fn run_with_crash() {
let project = project("run_with_crash")
.with_fuzz()
.fuzz_target(
"yes_crash",
r#"
#![no_main]
use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: &[u8]| {
run_with_crash::fail_fuzzing(data);
});
"#,
)
.build();
project
.cargo_fuzz()
.arg("run")
.arg("yes_crash")
.arg("--")
.arg("-runs=1000")
.env("RUST_BACKTRACE", "1")
.assert()
.stderr(
predicate::str::contains("panicked at 'I'm afraid of number 7'")
.and(predicate::str::contains("ERROR: libFuzzer: deadly signal"))
.and(predicate::str::contains("run_with_crash::fail_fuzzing"))
.and(predicate::str::contains(
"โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ\n\
\n\
Failing input:\n\
\n\
\tfuzz/artifacts/yes_crash/crash-"
))
.and(predicate::str::contains("Output of `std::fmt::Debug`:"))
.and(predicate::str::contains(
"Reproduce with:\n\
\n\
\tcargo fuzz run yes_crash fuzz/artifacts/yes_crash/crash-"
))
.and(predicate::str::contains(
"Minimize test case with:\n\
\n\
\tcargo fuzz tmin yes_crash fuzz/artifacts/yes_crash/crash-"
)),
)
.failure();
}
| 634
|
pub fn reply(message: &str) -> &str {
match message.trim() {
x if x.is_empty() => "Fine. Be that way!",
x if x.ends_with("?") => match x {
x if is_uppercase(x) => "Calm down, I know what I'm doing!",
_ => "Sure.",
},
x if is_uppercase(x) => "Whoa, chill out!",
_ => "Whatever.",
}
}
| 635
|
pub fn causet_partitioner_scan_column_as_float(
context: Box<CausetPartitionerContext>,
column_name: &[u8],
column_value: &[u8],
) -> Box<CausetPartitionerContext> {
context
}
| 636
|
pub fn causet_partitioner_scan_column(
context: Box<CausetPartitionerContext>,
column_name: &[u8],
column_value: &[u8],
) -> Box<CausetPartitionerContext> {
context
}
| 637
|
fn add(value: i32) -> i32 {
value + 1
}
| 638
|
async fn main() -> std::io::Result<()> {
// ----------------------------------------------------------------------------- tracing & logging
// configure tracing subscriber
configure_tracing();
// log http events from actix
LogTracer::init().expect("failed to enable http request logging");
// ----------------------------------------------------------------------------- config & pg
let config = get_config().expect("failed to read settings");
let addr = format!("{}:{}", config.app.host, config.app.port);
// configure sqlx connection
let mut conn_options = config.database.conn_opts();
// the line below makes sqlx logs appear as debug, not as info
let conn_options_w_logging = conn_options.log_statements(Debug); //must be a separate var
// get a connection pool
let pg_pool = PgPoolOptions::new()
.connect_timeout(std::time::Duration::from_secs(60)) //on purpose setting longer to avoid sqlx PoolTimedOut
.connect_with(conn_options_w_logging.to_owned())
.await
.expect("failed to connect to Postgres");
// ----------------------------------------------------------------------------- run
let arc_pool = Arc::new(pg_pool);
let arc_config = Arc::new(config);
schedule_tweet_refresh(arc_pool.clone(), arc_config.clone()).await;
run_server(&addr, arc_pool.clone(), arc_config.clone())?.await
}
| 639
|
async fn run_watchexec(args: Args) -> Result<()> {
info!(version=%env!("CARGO_PKG_VERSION"), "constructing Watchexec from CLI");
let init = config::init(&args);
let state = state::State::new()?;
let mut runtime = config::runtime(&args, &state)?;
runtime.filterer(filterer::globset(&args).await?);
info!("initialising Watchexec runtime");
let wx = Watchexec::new(init, runtime)?;
if !args.postpone {
debug!("kicking off with empty event");
wx.send_event(Event::default(), Priority::Urgent).await?;
}
info!("running main loop");
wx.main().await.into_diagnostic()??;
info!("done with main loop");
Ok(())
}
| 640
|
fn inc_6() {
run_test(&Instruction { mnemonic: Mnemonic::INC, operand1: Some(IndirectDisplaced(BX, 5189, Some(OperandSize::Byte), None)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[254, 135, 69, 20], OperandSize::Word)
}
| 641
|
fn get_build_type() -> String {
match env::var("PROFILE").unwrap().as_str() {
"release" => String::from("Release"),
_ => String::from("Debug"),
}
}
| 642
|
pub fn fuzzy_match(choice: &str, pattern: &str) -> Option<i64> {
if pattern.is_empty() {
return Some(0);
}
let scores = build_graph(choice, pattern)?;
let last_row = &scores[scores.len() - 1];
let (_, &MatchingStatus { final_score, .. }) = last_row
.iter()
.enumerate()
.max_by_key(|&(_, x)| x.final_score)
.expect("fuzzy_indices failed to iterate over last_row");
Some(final_score)
}
| 643
|
fn abstract_node(alpha: &RcNode, t: &RcTerm, subst: Subst) {
let bindings = subst
.iter()
.map(|(n, t)| (n.clone(), Rc::clone(t)))
.collect();
let let_term = Term::mk_let(Rc::clone(t), bindings);
replace_subtree(alpha, &let_term);
}
| 644
|
fn load_data() -> Vec<Vec<u8>> {
let f = File::open(DATA_PATH).unwrap();
let f = BufReader::new(f);
let l: Vec<String> = f.lines().collect::<Result<Vec<_>, _>>().unwrap();
let l: Vec<Vec<u8>> = l.into_iter().map(|x| x.from_base64().unwrap()).collect();
l
}
| 645
|
pub fn with_projects<F>(dir:StorageDir, search_terms:&[&str], f:F) -> Result<()>
where F:Fn(&Project)->Result<()>
{
trace!("with_projects({:?})", search_terms);
let luigi = try!(setup_luigi());
let projects = try!(luigi.search_projects_any(dir, search_terms));
if projects.is_empty() {
return Err(format!("Nothing found for {:?}", search_terms).into())
}
for project in &projects{
try!(f(project));
}
Ok(())
}
| 646
|
fn run_predicate_script(
header: fuzzers::HeaderC,
) -> Result<Output, Box<dyn Error>> {
let dir = Builder::new().prefix("bindgen_prop").tempdir()?;
let header_path = dir.path().join("prop_test.h");
let mut header_file = File::create(&header_path)?;
header_file.write_all(header.to_string().as_bytes())?;
header_file.sync_all()?;
let header_path_string = header_path
.into_os_string()
.into_string()
.map_err(|_| "error converting path into String")?;
let mut predicate_script_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
predicate_script_path.push("../../csmith-fuzzing/predicate.py");
let predicate_script_path_string = predicate_script_path
.into_os_string()
.into_string()
.map_err(|_| "error converting path into String")?;
// Copy generated temp files to output_path directory for inspection.
// If `None`, output path not specified, don't copy.
if let Some(ref path) = CONTEXT.lock().unwrap().output_path {
Command::new("cp")
.arg("-a")
.arg(dir.path().to_str().unwrap())
.arg(path)
.output()?;
}
Ok(Command::new(predicate_script_path_string)
.arg(&header_path_string)
.output()?)
}
| 647
|
fn test_let_2() {
let module = make_module(
indoc! {r#"
a = let a = 10 in let a = a * 1.0 in let a = a // 2 in a
b = let a = 10 in let a = a * 1.0 in let a = a / 2 in a
"#},
default_sym_table(),
);
assert!(module.is_ok());
let module = module.unwrap();
let decls = module.get_decls();
assert_eq!(decls[0].get_type(), Some(BasicType::int()));
assert_eq!(decls[1].get_type(), Some(BasicType::float()));
}
| 648
|
pub fn init(
title: &str,
set_min_window_size: bool,
) -> Result<(EventsLoop, GlWindow, Rc<gl::Gl>), Error> {
let events_loop = EventsLoop::new();
let window = WindowBuilder::new().with_title(title);
// 3.3 just because that's what <https://learnopengl.com> uses
let context = ContextBuilder::new()
.with_gl(GlRequest::Specific(Api::OpenGl, (3, 3)))
.with_vsync(true);
// `unwrap` rather than floating the errors upstream since we can't go further
// if we can't create a gl window anyway and because it does not implement
// `Sync`.
let gl_window = GlWindow::new(window, context, &events_loop).unwrap();
// We set the minimum size to 720p physical for ease of testing
if set_min_window_size {
let min_dims = LogicalSize::new(
f64::from(MIN_WINDOW_WIDTH) / gl_window.get_hidpi_factor(),
f64::from(MIN_WINDOW_HEIGHT) / gl_window.get_hidpi_factor(),
);
gl_window.set_inner_size(min_dims);
gl_window.set_min_dimensions(Some(min_dims));
}
unsafe {
gl_window.make_current()?;
}
let gl_unchecked;
unsafe {
gl_unchecked = gl::GlFns::load_with(|symbol| gl_window.get_proc_address(symbol) as *const _);
}
let gl = gl::ErrorCheckingGl::wrap(gl_unchecked);
// enable blending (for fonts)
gl.enable(gl::BLEND);
gl.blend_func(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA);
// all the image data we pass to OpenGL is tightly packed
gl.pixel_store_i(gl::UNPACK_ALIGNMENT, 1);
Ok((events_loop, gl_window, gl))
}
| 649
|
fn is_rollup_commit(commit: &Commit) -> bool {
let summary = commit.summary().unwrap_or("");
summary.starts_with("Rollup merge of #")
}
| 650
|
pub fn channel_take<T: Any + Clone>(target: CAddr) -> T {
let (result, payload) = system_call_take_payload(SystemCall::ChannelTake {
request: target,
response: None
});
match result {
SystemCall::ChannelTake {
request: _,
response: Some(ChannelMessage::Payload),
} => {
return payload;
},
_ => panic!(),
};
}
| 651
|
fn count(nums: &[i64], from: usize, memo: &mut HashMap<usize, i64>) -> i64 {
if let Some(n) = memo.get(&from) {
return *n;
} else if from >= nums.len() {
return 0;
}
let cur = nums[from];
let (a, b, c) = (from + 1, from + 2, from + 3);
let mut sum = count(nums, a, memo); // 1 X X
if b < nums.len() && nums[b] - cur <= 3 {
sum += count(nums, b, memo); // 0 1 X
}
if c < nums.len() && nums[c] - cur <= 3 {
sum += count(nums, c, memo); // 0 0 1
}
memo.insert(from, sum);
sum
}
| 652
|
fn move_node_data_to_coords(nodes: &HashMap<String, Node>, node: &Node, target: &String, used_list_data: Vec<String>) -> (usize, String, HashMap<String, Node>) {
let mut scan_list: Vec<(String, HashMap<String, Node>)> = vec![(node.coords.clone(), nodes.clone())];
let mut used_list: HashSet<String> = HashSet::new();
for n in used_list_data {
used_list.insert(n);
}
let mut count = 1;
let mut result_state: HashMap<String, Node> = HashMap::new();
let mut last_move = String::new();
'main: loop {
let mut temp_list: Vec<(String, HashMap<String, Node>)> = Vec::new();
let mut any_found = false;
for &(ref coords, ref state) in &scan_list {
let node = state.get(coords).unwrap();
let neighbours = node.get_neighbours();
for c in neighbours {
let mut new_state = state.clone();
let mut new_stuff = {
let neighbour = new_state.get(&c).unwrap();
let node = new_state.get(coords).unwrap();
// move on if node already scanned, or if either node can't fit the data
if used_list.contains(&c) || neighbour.used > node.size || node.used > neighbour.size {
continue
}
(neighbour.clone(), node.clone())
};
let neighbour_used = new_stuff.0.used;
let neighbour_coords = new_stuff.0.coords.clone();
new_stuff.0.used = new_stuff.1.used;
new_stuff.1.used = neighbour_used;
new_state.insert(new_stuff.0.coords.clone(), new_stuff.0);
new_state.insert(new_stuff.1.coords.clone(), new_stuff.1);
if neighbour_coords == *target {
result_state = new_state;
last_move = coords.clone();
break 'main
}
temp_list.push((neighbour_coords.clone(), new_state));
any_found = true;
used_list.insert(c.clone());
}
}
count += 1;
scan_list = temp_list.clone();
if !any_found {
println!("Ran out of options");
break
}
}
(count, last_move, result_state)
}
| 653
|
pub fn flip_ref_opt_to_opt_ref<T> (r: Ref<Option<T>>) -> Option<Ref<T>> {
match r.deref() {
Some(_) => Some(Ref::map(r, |o| o.as_ref().unwrap())),
None => None
}
}
| 654
|
fn bindgen_prop(header: fuzzers::HeaderC) -> TestResult {
match run_predicate_script(header) {
Ok(o) => TestResult::from_bool(o.status.success()),
Err(e) => {
println!("{:?}", e);
TestResult::from_bool(false)
}
}
}
| 655
|
pub fn fixed_vector(receiver: Receiver<u128>) -> Result<()> {
// This is used to store all numbers that haven't been solved yet.
// -> For instance, if the task for 10 completes, but 7, 8 and 9 haven't yet, these will be
// added to the backlog.
// In theory, there should never be more than `threadpool_count` elements in the backlog.
let mut backlog: Vec<u128> = vec![EMPTY_SLOT; THREAD_COUNT];
let mut highest_number = DEFAULT_MAX_PROVEN_NUMBER - BATCH_SIZE;
// The highest number that's connected in the sequence of natural numbers from `(0..number)`.
let mut highest_sequential_number = DEFAULT_MAX_PROVEN_NUMBER;
let mut counter = 0;
let start = Instant::now();
loop {
let next_number = receiver.recv()?;
if next_number > highest_number {
// Add all missing numbers that haven't been returned yet.
let mut backlog_slot_iter = 0..THREAD_COUNT;
// Add all missing numbers that haven't been returned yet.
let mut missing = highest_number + BATCH_SIZE;
while missing < next_number {
// Scan the vector for free slots (slots with 0)
// By using a stateful-vector, we only do a single scan for multiple missing
// elements.
while let Some(slot) = backlog_slot_iter.next() {
let value = backlog[slot];
if value == 0 {
backlog[slot] = missing;
break;
}
}
missing += BATCH_SIZE;
}
// Set the new number as the highest number.
highest_number = next_number;
} else {
// The number must be in the backlog.
let mut found_in_backlog = false;
for i in 0..backlog.len() {
if backlog[i] == next_number {
backlog[i] = 0;
found_in_backlog = true;
break;
}
}
if !found_in_backlog {
panic!(
"Couldn't find number {} in backlog {:?}",
next_number, backlog
);
}
}
// We only print stuff every X iterations, as printing is super slow.
// We also only update the highest_sequential_number during this interval.
if counter % (REPORTING_SIZE / BATCH_SIZE) == 0 {
// Find the smallest number in our backlog.
// That number minus 1 is our last succesfully calculated value.
backlog.sort();
for i in backlog.iter() {
if i == &0 {
continue;
}
highest_sequential_number = i - 1;
}
println!(
"Batch : {}, Time: {}ms, Max number: {}, Channel size: {}, Backlog size: {}",
counter,
start.elapsed().as_millis().to_formatted_string(&Locale::en),
highest_sequential_number.to_formatted_string(&Locale::en),
receiver.len(),
backlog.len()
);
}
counter += 1;
}
}
| 656
|
pub fn nth(n: u32) -> u32 {
let mut primes: Vec<u32> = vec![2, 3, 5];
let i = n as usize;
let mut nn = 5;
while i + 1 >= primes.len() {
nn += 2;
if !primes.iter().any(|x| nn % x == 0) {
primes.push(nn);
}
}
primes[i]
}
| 657
|
pub fn list_dir() {
if let Ok(entries) = fs::read_dir(".") {
for entry in entries {
println!("entry:{:?}", entry);
if let Ok(entry) = entry {
println!("path:{:?}", entry.path());
println!("file_name:{:?}", entry.file_name());
println!("file_type:{:?}", entry.file_type());
}
}
}
}
| 658
|
fn die(err: impl Error) -> ! {
println!("{}", err);
std::process::exit(1);
}
| 659
|
pub unsafe fn set_thread_area(u_info: &mut UserDesc) -> io::Result<()> {
imp::syscalls::tls::set_thread_area(u_info)
}
| 660
|
pub fn ref_and_then_mut<'r, T, U: 'static, F: FnOnce (&mut T) -> Option<&mut U>> (mut r: RefMut<'r, T>, f: F) -> Option<RefMut<'r, U>> {
match f(r.deref_mut()) {
Some(u) => {
// SAFETY: we're discarding the compile-time managed borrow in the reference,
// in favor of the runtime-managed borrow in the Ref
let u = unsafe { std::mem::transmute::<&mut U, &'static mut U>(u) };
Some(RefMut::map(r, move |_| u))
}
None => None
}
}
| 661
|
fn main() {
let mut args = env::args();
if args.len() >= 2 {
args.next();
let path = args.next().unwrap();
let mut debug_mode = false;
if let Some(s) = args.next() {
debug_mode = s == "-d";
if s == "-a" {
assemble(path).unwrap();
return;
}
}
run(path, debug_mode).unwrap();
} else {
let path = console_input();
run(path, false).unwrap();
}
}
| 662
|
pub fn test_trace() {
let buffer = fs::read("tests/programs/trace64").unwrap().into();
let result = run::<u64, SparseMemory<u64>>(&buffer, &vec!["trace64".into()]);
assert!(result.is_err());
assert_eq!(result.err(), Some(Error::MemWriteOnExecutablePage));
}
| 663
|
fn fist_2() {
run_test(&Instruction { mnemonic: Mnemonic::FIST, operand1: Some(Indirect(EAX, Some(OperandSize::Dword), None)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[219, 16], OperandSize::Dword)
}
| 664
|
pub fn mean(set: &[f32]) -> f32 {
set.iter().sum::<f32>() / (set.len() as f32)
}
| 665
|
fn save_history(cmd: String) {
let timestamp = chrono::Local::now().format("%s").to_string();
match cmd.as_str() {
"" => (),
_ => {
let mut file = OpenOptions::new()
.create(true).append(true)
.open(get_histfile_path()).unwrap();
file.write((timestamp + ";" + cmd.as_str() + "\n").as_bytes()).unwrap();
}
}
}
| 666
|
fn parseModelInfo(reader: &mut BufReader<&File>, buf: &mut String, models: &mut Vec<Model>, basePath: &str) -> Model {
//Firstly, read the meshId and materialId;
reader.read_line(buf);
let mut split_info = buf.split(" ");
if len(split_info) != 2 {}
let meshId: i32 = split_info.next().unwrap().parse().unwrap();
let materidId = split_info.next().unwrap().parse().unwrap();
let meshFilePath = basePath + "/meshes/" + meshId + "_mesh.obj";
let materialPath = basePath + "/materials/" + materidId + "/" + materidId;
//Then, read the position info;
split_info = buf.split(" ");
let mut modelInfo: Vec<Vec3f> = Vec::new();
let mut infoIndex = 0;
while infoIndex < 3 {
reader.read_line(buf);
let mut split_info = buf.split(" ");
modelInfo.push(Vec3f {
x: split_info.next().unwrap().parse().unwrap(),
y: split_info.next().unwrap().parse().unwrap(),
z: split_info.next().unwrap().parse().unwrap(),
});
infoIndex += 1;
}
loadImageFromMaterial(model, materidId);
models.push(Model {
meshId,
materidId: 0,
position: Vec3f {
x: modelInfo.get(0).unwrap().x,
y: modelInfo.get(0).unwrap().y,
z: modelInfo.get(0).unwrap().z,
},
rotation: Vec3f {
x: modelInfo.get(1).unwrap().x,
y: modelInfo.get(1).unwrap().y,
z: modelInfo.get(1).unwrap().z,
},
scaling: Vec3f {
x: modelInfo.get(2).unwrap().x,
y: modelInfo.get(2).unwrap().y,
z: modelInfo.get(2).unwrap().z,
},
}
);
//Finally, we only need to read an empty line to finish the model parsing process
reader.read_line(buf);
}
| 667
|
pub async fn new_quic_link(
sender: LinkSender,
receiver: LinkReceiver,
endpoint: Endpoint,
) -> Result<(QuicSender, QuicReceiver, ConnectionId), Error> {
let scid = ConnectionId::new();
let mut config = sender.router().new_quiche_config().await?;
config.set_application_protos(b"\x10overnet.link/0.2")?;
config.set_initial_max_data(0);
config.set_initial_max_stream_data_bidi_local(0);
config.set_initial_max_stream_data_bidi_remote(0);
config.set_initial_max_stream_data_uni(0);
config.set_initial_max_streams_bidi(0);
config.set_initial_max_streams_uni(0);
config.set_max_send_udp_payload_size(16384);
config.set_max_recv_udp_payload_size(16384);
const DGRAM_QUEUE_SIZE: usize = 1024 * 1024;
config.enable_dgram(true, DGRAM_QUEUE_SIZE, DGRAM_QUEUE_SIZE);
let quic = match endpoint {
Endpoint::Client => AsyncConnection::connect(
None,
&quiche::ConnectionId::from_ref(&scid.to_array()),
receiver
.peer_node_id()
.map(|x| x.to_ipv6_repr())
.unwrap_or_else(|| "127.0.0.1:65535".parse().unwrap()),
&mut config,
)?,
Endpoint::Server => AsyncConnection::accept(
&quiche::ConnectionId::from_ref(&scid.to_array()),
receiver
.peer_node_id()
.map(|x| x.to_ipv6_repr())
.unwrap_or_else(|| "127.0.0.1:65535".parse().unwrap()),
&mut config,
)?,
};
Ok((
QuicSender { quic: quic.clone() },
QuicReceiver {
_task: Task::spawn(log_errors(
run_link(sender, receiver, quic.clone()),
"QUIC link failed",
)),
quic,
},
scid,
))
}
| 668
|
pub fn acrn_read_dir(path: &str, recursive: bool) -> Result<Vec<DirEntry>, String> {
read_dir(path, recursive).map_err(|e| e.to_string())
}
| 669
|
pub fn check_hex_range(addr: u16) -> bool {
return if addr < 0x0000 || addr > 0xFFFF {
false
} else {
true
};
}
| 670
|
pub fn var(v: Var) -> Value {
Rc::new(RefCell::new(V {
val: Value_::Var(v),
computed: false,
}))
}
| 671
|
pub fn unarchive_projects(year:i32, search_terms:&[&str]) -> Result<Vec<PathBuf>> {
let luigi = try!(setup_luigi_with_git());
Ok(try!( luigi.unarchive_projects(year, search_terms) ))
}
| 672
|
pub fn calculate() {
println!("calculate grade");
}
| 673
|
pub fn test_memory_load_bytes() {
let mut rng = thread_rng();
assert_memory_load_bytes_all(&mut rng, RISCV_MAX_MEMORY, 1024 * 5, 0);
assert_memory_load_bytes_all(&mut rng, RISCV_MAX_MEMORY, 1024 * 5, 2);
assert_memory_load_bytes_all(&mut rng, RISCV_MAX_MEMORY, 1024 * 5, 1024 * 6);
assert_memory_load_bytes_all(&mut rng, RISCV_MAX_MEMORY, 0, 0);
}
| 674
|
fn array_test() {
let lazy_caterer: [u32; 6] = [1, 2, 4, 7, 11, 16];
let taxonomy = ["Animalia", "arthropoda", "Insecta"];
assert_eq!(lazy_caterer[3], 7);
assert_eq!(taxonomy.len(), 3);
let mut sieve = [true; 10000];
for i in 2..100 {
if sieve[i] {
let mut j = i * i;
while j < 10000 {
sieve[j] = false;
j += i;
}
}
}
assert!(sieve[211]);
assert!(!sieve[9876]);
let mut chaos = [3, 5, 4, 1, 2];
chaos.sort();
assert_eq!(chaos, [1, 2, 3, 4, 5]);
}
| 675
|
pub extern "x86-interrupt" fn mouse() { CommonInterruptHandler(44); }
| 676
|
fn build_package(
current_dir: &Path,
installed_dir: &Path,
configure_opts: &[String],
) -> Result<(), FrumError> {
debug!("./configure {}", configure_opts.join(" "));
let mut command = Command::new("sh");
command
.arg("configure")
.arg(format!("--prefix={}", installed_dir.to_str().unwrap()))
.args(configure_opts);
// Provide a default value for --with-openssl-dir
if !configure_opts
.iter()
.any(|opt| opt.starts_with("--with-openssl-dir"))
{
command.arg(format!("--with-openssl-dir={}", openssl_dir()?));
}
let configure = command
.current_dir(¤t_dir)
.output()
.map_err(FrumError::IoError)?;
if !configure.status.success() {
return Err(FrumError::CantBuildRuby {
stderr: format!(
"configure failed: {}",
String::from_utf8_lossy(&configure.stderr).to_string()
),
});
};
debug!("make -j {}", num_cpus::get().to_string());
let make = Command::new("make")
.arg("-j")
.arg(num_cpus::get().to_string())
.current_dir(¤t_dir)
.output()
.map_err(FrumError::IoError)?;
if !make.status.success() {
return Err(FrumError::CantBuildRuby {
stderr: format!(
"make failed: {}",
String::from_utf8_lossy(&make.stderr).to_string()
),
});
};
debug!("make install");
let make_install = Command::new("make")
.arg("install")
.current_dir(¤t_dir)
.output()
.map_err(FrumError::IoError)?;
if !make_install.status.success() {
return Err(FrumError::CantBuildRuby {
stderr: format!(
"make install: {}",
String::from_utf8_lossy(&make_install.stderr).to_string()
),
});
};
Ok(())
}
| 677
|
fn test_region_area() {
let ll = (0.0, 0.0).into_pt();
let ur = (2.0, 2.0).into_pt();
let r = Region::from_points(&ll, &ur);
assert_eq!(r.get_area(), 4.0);
}
| 678
|
fn get_largest_register_value(registers: &HashMap<&str, i32>) -> i32 {
*registers
.iter()
.map(|(_, v)| v)
.max()
.unwrap_or(&0)
}
| 679
|
pub
fn
fetch_and
(
&
self
val
:
bool
)
-
>
bool
{
let
a
=
unsafe
{
&
*
(
self
.
as_ptr
(
)
as
*
const
AtomicBool
)
}
;
a
.
fetch_and
(
val
Ordering
:
:
AcqRel
)
}
| 680
|
fn desearlizer_task(req: &mut reqwest::Response) -> Result<Task, Error> {
let mut buffer = String::new();
match req.read_to_string(&mut buffer) {
Ok(_) => (),
Err(e) => println!("error : {}", e.to_string())
};
println!("buffer before serializaztion: {}", buffer);
let v = match serde_json::from_str::<Task>(&buffer){
Ok(v) => v,
Err(e) => return Err(e)
};
Ok(v)
}
| 681
|
pub fn causet_partitioner_context_new() -> Box<CausetPartitionerContext> {
Box::new(CausetPartitionerContext {
prev_user_soliton_id: Vec::new(),
current_user_soliton_id: Vec::new(),
current_output_file_size: 0,
})
}
| 682
|
pub fn solve2(input: &str) -> Option<Box<usize>> {
let sum_of_counts = input
.trim_end()
.split("\n\n")
.map(|group| {
let answers_per_person = group
.split_ascii_whitespace()
.map(|person| person.chars().collect::<HashSet<_>>())
.collect::<Vec<_>>();
answers_per_person
.iter()
.fold(answers_per_person[0].clone(), |all_yes, persons_answers| {
all_yes.intersection(persons_answers).cloned().collect()
})
.len()
})
.sum();
Some(Box::new(sum_of_counts))
}
| 683
|
pub fn challenge_8() {
let mut file = File::open("data/8.txt").unwrap();
let mut all_file = String::new();
file.read_to_string(&mut all_file).unwrap();
let mut best_guess = ("", 0);
for line in all_file.lines() {
let data = hex::decode(line).unwrap();
let nb_rep = crypto::number_repetition(&data, 16);
if nb_rep > best_guess.1 {
best_guess = (line, nb_rep);
}
}
println!("{} {}", best_guess.0, best_guess.1);
}
| 684
|
pub fn setup_luigi() -> Result<Storage<Project>> {
trace!("setup_luigi()");
let working = try!(::CONFIG.get_str("dirs/working").ok_or("Faulty config: dirs/working does not contain a value"));
let archive = try!(::CONFIG.get_str("dirs/archive").ok_or("Faulty config: dirs/archive does not contain a value"));
let templates = try!(::CONFIG.get_str("dirs/templates").ok_or("Faulty config: dirs/templates does not contain a value"));
let storage = try!(Storage::new(util::get_storage_path(), working, archive, templates));
Ok(storage)
}
| 685
|
pub fn test_jump0() {
let buffer = fs::read("tests/programs/jump0_64").unwrap().into();
let result = run::<u64, SparseMemory<u64>>(&buffer, &vec!["jump0_64".into()]);
assert!(result.is_err());
assert_eq!(result.err(), Some(Error::MemWriteOnExecutablePage));
}
| 686
|
fn test_env_var() {
// Sets a new environment variable to check the correct value retrieval from Gura
let env_var_name = "env_var_value";
let env_value = "using_env_var";
env::set_var(env_var_name, env_value);
let parsed_data = parse(&format!("test: ${}", env_var_name)).unwrap();
assert_eq!(parsed_data, object! {test: env_value});
env::remove_var(env_var_name);
}
| 687
|
pub fn startup_tls_info() -> StartupTlsInfo {
imp::thread::tls::startup_tls_info()
}
| 688
|
pub fn star1(lines: &Vec<String>) -> String {
let days = initialize(lines);
let mut guard_map = HashMap::new();
for day in days {
guard_map.entry(day.guard_id)
.or_insert(vec![])
.push(day);
}
let (&sleepiest_guard_id, sleepiest_guard_days) = guard_map.iter()
.max_by_key(|(_, v)| v.iter()
.map(|day| 60 - day.minutes_awake)
.sum::<i32>()
).unwrap();
let mut sleepiest_guard_awake_by_minutes = vec![0; 60];
for day in sleepiest_guard_days {
// println!("Day: {:?}", day);
for minute in 0..60 {
sleepiest_guard_awake_by_minutes[minute] += i32::from(day.minutes[minute]);
}
}
let (max_minute, _) = sleepiest_guard_awake_by_minutes.iter().enumerate().min_by_key(|(_, times)| *times).unwrap();
println!("Min minute: {}, max guard: {}", max_minute, sleepiest_guard_id);
(sleepiest_guard_id * max_minute as i32).to_string()
}
| 689
|
pub fn sne_op(inputs: OpInputs) -> EmulatorResult<()> {
// SNE compares the A-value to the B-value. If the result of the
// comparison is not equal, the instruction after the next instruction
// (PC + 2) is queued (skipping the next instruction). Otherwise, the
// next instruction is queued (PC + 1).
let a = inputs.regs.a;
let b = inputs.regs.b;
let is_not_equal = match inputs.regs.current.instr.modifier {
Modifier::A => a.a_field != b.a_field,
Modifier::B => a.b_field != b.b_field,
Modifier::AB => a.a_field != b.b_field,
Modifier::BA => a.b_field != b.a_field,
Modifier::F => a.a_field != b.a_field || a.b_field != b.b_field,
Modifier::X => a.a_field != b.b_field || a.b_field != b.a_field,
Modifier::I => {
a.instr != b.instr
|| a.a_field != b.a_field
|| a.b_field != b.b_field
}
};
// Increment PC twice if the condition holds, otherwise increment once
let amt = if is_not_equal { 2 } else { 1 };
inputs.pq.push_back(
offset(inputs.regs.current.idx, amt, inputs.core_size)?,
inputs.warrior_id,
)?;
Ok(())
}
| 690
|
pub fn hex_to_uint256(hex: &str) -> Option<Uint256> {
if hex.len() != 64 { return None; }
let mut out = [0u64; 4];
let mut b: u64 = 0;
for (idx, c) in hex.as_bytes().iter().enumerate() {
b <<= 4;
match *c {
b'A'..=b'F' => b |= (c - b'A' + 10) as u64,
b'a'..=b'f' => b |= (c - b'a' + 10) as u64,
b'0'..=b'9' => b |= (c - b'0') as u64,
_ => return None,
}
if idx % 16 == 15 {
out[3 - (idx / 16)] = b;
b = 0;
}
}
Some(Uint256::from(&out[..]))
}
| 691
|
pub extern "x86-interrupt" fn machine_check() { CommonExceptionHandler(18); }
| 692
|
pub fn ldp_op(inputs: OpInputs) -> EmulatorResult<()> {
// Reads a value from the PSPACE, writing it into core memory
//
// LDP and STP are not defined in any ICWS standard. This implementation
// is based on pMARS's behavior.
//
// The source index uses one of the fields from the A instruction, taken
// modulo pspace size. This is not the field that MOV would use as a
// source index, but rather the field that MOV would use as the source
// value. Each location in PSPACE stores a single field, so the multi-
// field modifiers of (X, F, I) are not meaningful. They are defined to
// operate identically to B.
//
// Similar to source index, the destination is the same destination that
// be written to by a MOV instruction using the same modifier. Again,
// X, F, and I are not meaningful, and behave like B.
//
// Further PSPACE notes:
//
// It is expected that the PSPACE is not cleared between rounds in a
// battle, so a warrior may use information from one round to pick a
// strategy in the next round.
//
// Multiple warriors can the same PSPACE. Hypothetically, this could
// be used in multi-warrior hills where multiple warriors with the same
// author could have an advantage with communication.
//
// The value at index 0 is not shared between warriors with the same pin,
// and it does not retain it's value between rounds. Instead it's initial
// value indicates the outcome of the previous round in this battle.
//
// The pspace address space is typically smaller than the core size, and
// almost always a factor of the core size. By convention, it's 1/16 the
// size of the full core. It's not required for the size to be a factor,
// however if this isn't the case, simple assumptions break.
//
// For example the pspace locations x and x+1 will usually be adjacent
// (modulo pspace size) except when pspace is not a factor of coresize
// and x+1 = coresize = 0.
// In general: (x % coresize) % pspace size != (x % pspace size) % coresize
//
// Queue PC + 1
inputs.pq.push_back(
offset(inputs.regs.current.idx, 1, inputs.core_size)?,
inputs.warrior_id,
)?;
let a = inputs.regs.a;
let b = inputs.regs.b;
let source_index = match inputs.regs.current.instr.modifier {
Modifier::A | Modifier::AB => a.a_field,
Modifier::B
| Modifier::BA
| Modifier::F
| Modifier::X
| Modifier::I => a.b_field,
};
let value = inputs.pspace.read(source_index, inputs.warrior_id)?;
match inputs.regs.current.instr.modifier {
Modifier::A | Modifier::BA => {
let target = inputs.core_get_mut(b.idx)?;
target.a_field = value;
}
Modifier::B
| Modifier::AB
| Modifier::F
| Modifier::X
| Modifier::I => {
let target = inputs.core_get_mut(b.idx)?;
target.b_field = value;
}
};
Ok(())
}
| 693
|
fn map_params(tok: IRCToken) -> Result<IRCToken, ~str> {
// Sequence(~[Sequence(~[Sequence(~[Ignored, Unparsed(~"##codelab")])]), Sequence(~[Sequence(~[Ignored, Unparsed(~":"), Unparsed(~"hi")])])])
match tok {
Sequence(args) => Ok(Params(args.map(|arg| {
match arg.clone() {
Sequence([Sequence([Ignored, Unparsed(param)])]) => param,
Sequence([Sequence([Ignored, Unparsed(~":"), Unparsed(param)])]) => param,
_ => ~""
}
}))),
_ => Err(~"Malformed parameters")
}
}
| 694
|
pub fn write_uint8(buf: &mut Vec<u8>, u: u8) -> usize {
buf.push(u);
1
}
| 695
|
pub fn main() {
Opt::from_args();
let options = SkimOptionsBuilder::default()
.multi(true)
.bind(vec!["ctrl-k:kill-line"])
.build()
.unwrap();
let re = Regex::new(URL_REGEX).unwrap();
let mut buffer = String::new();
io::stdin().read_to_string(&mut buffer).unwrap();
let lines = buffer.split("\n");
let mut split_lines = false;
let mut split_line_buffer: Vec<&str> = Vec::new();
let mut merged_lines: Vec<String> = Vec::new();
for line in lines {
if line.len() == 0 {
continue
}
if line.ends_with(LINE_SPLITTER) {
let mergable = line.get(0..line.len() - 1).unwrap_or("");
split_line_buffer.push(mergable);
split_lines = true;
continue;
}
if split_lines {
split_lines = false;
split_line_buffer.push(line);
let merged_line = &split_line_buffer.join("");
merged_lines.push(merged_line.to_string());
split_line_buffer = Vec::new();
} else {
merged_lines.push(line.to_string());
}
}
let mut matches: HashMap<String, u8> = HashMap::new();
let mut match_index = 1;
for line in merged_lines {
let sanitized = line.replace("=3D", "=");
for capture in re.captures_iter(&sanitized) {
let url_match = capture.get(1).unwrap().as_str();
if matches.contains_key(url_match) {
continue;
}
matches.insert(url_match.to_string(), match_index);
match_index += 1;
}
}
let mut ordered_items: Vec<_> = matches.into_iter().collect();
ordered_items.sort_by(|a, b| a.1.cmp(&b.1));
let item_list: Vec<_> = ordered_items.iter().map(|item| item.0.as_str()).collect();
let items = item_list.join("\n");
let item_reader = SkimItemReader::default();
let items = item_reader.of_bufread(Cursor::new(items));
let output = Skim::run_with(&options, Some(items)).unwrap();
if output.is_abort {
return;
}
for item in output.selected_items.iter() {
let url = item.clone();
Command::new("firefox")
.arg(url.output().as_ref())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.unwrap();
}
}
| 696
|
fn err_list() -> Receiver<i32, u32> {
let (tx, rx) = channel();
tx.send(Ok(1))
.and_then(|tx| tx.send(Ok(2)))
.and_then(|tx| tx.send(Err(3)))
.forget();
return rx
}
| 697
|
pub fn task_set_active(target: CAddr) {
system_call(SystemCall::TaskSetActive {
request: target
});
}
| 698
|
fn parse_statement(input: &str) -> IResult<&str, (&str, Vec<(usize, &str)>)> {
let (input, bag_name) = parse_bag_name(input)?;
let input = skip_whitespace(input);
let (input, _) = tag("contain")(input)?;
let input = skip_whitespace(input);
let (input, list) = alt((parse_bag_list, map(tag("no other bags"), |_| Vec::new())))(input)?;
let (input, _) = char('.')(input)?;
let input = skip_whitespace(input);
Ok((input, (bag_name, list)))
}
| 699
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.