content
stringlengths 12
392k
| id
int64 0
1.08k
|
|---|---|
pub fn read_file(file_name: &str) -> Result<Vec<u8>> {
let mut file = File::open(file_name)?;
let mut data: Vec<u8> = Vec::new();
file.read_to_end(&mut data)?;
Ok(data)
}
| 900
|
pub fn list_data(cache: &Cache, key: usize) {
for reference in vec![1, 2, 3] {
if /*let*/ Some(reference) = cache.data.get(key) {
unimplemented!()
}
}
}
| 901
|
fn lz_string_raw() {
compression_tests(
|s| lz_str::compress(s).into(),
|s| lz_str::decompress(&s.0).map(ByteString::from),
false,
);
}
| 902
|
fn process_instructions(instructions: &Vec<Instruction>) -> (HashMap<&str, i32>, i32) {
let mut registers: HashMap<&str, i32> = HashMap::new();
let mut max = 0;
for instruction in instructions {
let current = *registers.entry(&instruction.condition.register).or_insert(0);
let condition_satisfied = match instruction.condition.operator {
Operator::LessThan => current < instruction.condition.value,
Operator::LessThanOrEqual => current <= instruction.condition.value,
Operator::GreaterThan => current > instruction.condition.value,
Operator::GreaterThanOrEqual => current >= instruction.condition.value,
Operator::Equal => current == instruction.condition.value,
Operator::NotEqual => current != instruction.condition.value,
};
if !condition_satisfied {
continue;
}
let delta = match instruction.increase {
true => instruction.value,
false => -1 * instruction.value,
};
let entry = registers.entry(&instruction.register).or_insert(0);
*entry += delta;
let new_value = *entry;
if new_value > max {
max = new_value;
}
}
(registers, max)
}
| 903
|
fn enums_are_preserved_when_generating_data_model_from_a_schema() {
let ref_data_model = Datamodel {
models: vec![],
enums: vec![dml::Enum {
name: "Enum".to_string(),
database_name: None,
documentation: None,
commented_out: false,
values: vec![
datamodel::dml::EnumValue {
name: "a".to_string(),
documentation: None,
database_name: None,
commented_out: false,
},
datamodel::dml::EnumValue {
name: "b".to_string(),
documentation: None,
database_name: None,
commented_out: false,
},
],
}],
};
let enum_values = vec!["a".to_string(), "b".to_string()];
let schema = SqlSchema {
tables: vec![],
enums: vec![Enum {
name: "Enum".to_string(),
values: enum_values,
}],
sequences: vec![],
};
let introspection_result = calculate_datamodel(&schema, &SqlFamily::Postgres).expect("calculate data model");
assert_eq!(introspection_result.data_model, ref_data_model);
}
| 904
|
fn de_timeline(raw: TimelineRaw, even: bool) -> game::Timeline {
let mut res = game::Timeline::new(
de_l(raw.index, even),
raw.width,
raw.height,
raw.begins_at,
raw.emerges_from.map(|x| de_l(x, even)),
);
let index = de_l(raw.index, even);
let begins_at = raw.begins_at;
let width = raw.width;
let height = raw.height;
res.states = raw
.states
.into_iter()
.enumerate()
.map(|(i, b)| de_board(b, begins_at + i as isize, index, width, height))
.collect();
res
}
| 905
|
pub fn projects_to_csv(projects:&[Project]) -> Result<String>{
let mut string = String::new();
let splitter = ";";
try!(writeln!(&mut string, "{}", [ "Rnum", "Bezeichnung", "Datum", "Rechnungsdatum", "Betreuer", "Verantwortlich", "Bezahlt am", "Betrag", "Canceled"].join(splitter)));
for project in projects{
try!(writeln!(&mut string, "{}", [
project.get("InvoiceNumber").unwrap_or_else(|| String::from(r#""""#)),
project.get("Name").unwrap_or_else(|| String::from(r#""""#)),
project.get("event/dates/0/begin").unwrap_or_else(|| String::from(r#""""#)),
project.get("invoice/date").unwrap_or_else(|| String::from(r#""""#)),
project.get("Caterers").unwrap_or_else(|| String::from(r#""""#)),
project.get("Responsible").unwrap_or_else(|| String::from(r#""""#)),
project.get("invoice/payed_date").unwrap_or_else(|| String::from(r#""""#)),
project.get("Final").unwrap_or_else(|| String::from(r#""""#)),
project.canceled_string().to_owned()
].join(splitter)));
}
Ok(string)
}
| 906
|
extern "C" fn gatt_svr_chr_access_heart_rate(
_conn_handle: u16,
_attr_handle: u16,
ctxt: *mut ble_gatt_access_ctxt,
_arg: *mut ::core::ffi::c_void,
) -> i32 {
/* Sensor location, set to "Chest" */
const BODY_SENS_LOC: u8 = 0x01;
let uuid: u16 = unsafe { ble_uuid_u16((*(*ctxt).__bindgen_anon_1.chr).uuid) };
if uuid == GATT_HRS_BODY_SENSOR_LOC_UUID {
let rc: i32 = unsafe {
os_mbuf_append(
(*ctxt).om,
&BODY_SENS_LOC as *const u8 as *const c_void,
size_of::<u8>() as u16,
)
};
return if rc == 0 {
0
} else {
BLE_ATT_ERR_INSUFFICIENT_RES as i32
};
}
return BLE_ATT_ERR_UNLIKELY as i32;
}
| 907
|
fn primary_key_is_preserved_when_generating_data_model_from_a_schema() {
let ref_data_model = Datamodel {
models: vec![
// Model with auto-incrementing primary key
Model {
database_name: None,
name: "Table1".to_string(),
documentation: None,
is_embedded: false,
is_commented_out: false,
fields: vec![Field::ScalarField(ScalarField {
name: "primary".to_string(),
arity: FieldArity::Required,
field_type: FieldType::Base(ScalarType::Int, None),
database_name: None,
default_value: Some(DMLDefault::Expression(ValueGenerator::new_autoincrement())),
is_unique: false,
is_id: true,
documentation: None,
is_generated: false,
is_updated_at: false,
is_commented_out: false,
})],
is_generated: false,
indices: vec![],
id_fields: vec![],
},
// Model with non-auto-incrementing primary key
Model {
database_name: None,
name: "Table2".to_string(),
documentation: None,
is_embedded: false,
is_commented_out: false,
fields: vec![Field::ScalarField(ScalarField {
name: "primary".to_string(),
arity: FieldArity::Required,
field_type: FieldType::Base(ScalarType::Int, None),
database_name: None,
default_value: None,
is_unique: false,
is_id: true,
documentation: None,
is_generated: false,
is_updated_at: false,
is_commented_out: false,
})],
is_generated: false,
indices: vec![],
id_fields: vec![],
},
// Model with primary key seeded by sequence
Model {
database_name: None,
name: "Table3".to_string(),
documentation: None,
is_embedded: false,
is_commented_out: false,
fields: vec![Field::ScalarField(ScalarField {
name: "primary".to_string(),
arity: FieldArity::Required,
field_type: FieldType::Base(ScalarType::Int, None),
database_name: None,
default_value: Some(DMLDefault::Expression(ValueGenerator::new_autoincrement())),
is_unique: false,
is_id: true,
documentation: None,
is_generated: false,
is_updated_at: false,
is_commented_out: false,
})],
is_generated: false,
indices: vec![],
id_fields: vec![],
},
],
enums: vec![],
};
let schema = SqlSchema {
tables: vec![
Table {
name: "Table1".to_string(),
columns: vec![Column {
name: "primary".to_string(),
tpe: ColumnType {
data_type: "integer".to_string(),
full_data_type: "integer".to_string(),
character_maximum_length: None,
family: ColumnTypeFamily::Int,
arity: ColumnArity::Required,
},
default: None,
auto_increment: true,
}],
indices: vec![],
primary_key: Some(PrimaryKey {
columns: vec!["primary".to_string()],
sequence: None,
constraint_name: None,
}),
foreign_keys: vec![],
},
Table {
name: "Table2".to_string(),
columns: vec![Column {
name: "primary".to_string(),
tpe: ColumnType {
data_type: "integer".to_string(),
full_data_type: "integer".to_string(),
character_maximum_length: None,
family: ColumnTypeFamily::Int,
arity: ColumnArity::Required,
},
default: None,
auto_increment: false,
}],
indices: vec![],
primary_key: Some(PrimaryKey {
columns: vec!["primary".to_string()],
sequence: None,
constraint_name: None,
}),
foreign_keys: vec![],
},
Table {
name: "Table3".to_string(),
columns: vec![Column {
name: "primary".to_string(),
tpe: ColumnType {
data_type: "integer".to_string(),
full_data_type: "integer".to_string(),
character_maximum_length: None,
family: ColumnTypeFamily::Int,
arity: ColumnArity::Required,
},
default: None,
auto_increment: true,
}],
indices: vec![],
primary_key: Some(PrimaryKey {
columns: vec!["primary".to_string()],
sequence: Some(Sequence {
name: "sequence".to_string(),
initial_value: 1,
allocation_size: 1,
}),
constraint_name: None,
}),
foreign_keys: vec![],
},
],
enums: vec![],
sequences: vec![],
};
let introspection_result = calculate_datamodel(&schema, &SqlFamily::Postgres).expect("calculate data model");
assert_eq!(introspection_result.data_model, ref_data_model);
}
| 908
|
pub fn default_panic_handler(info: &PanicInfo) -> ! {
println!("[failed]\n");
println!("Error: {}\n", info);
fail();
crate::halt();
}
| 909
|
fn main() {
// creating instance of Food struct
let pizza = Food{
restaurant : "Pizza Hut".to_string(),
item : String::from("Chicken Fajita"),
size : 9,
price : 800,
available : true
};
// mutable struct
let mut karahi = Food{
available : true,
restaurant : String::from("BBQ tonight"),
// taking field value from another instance
price : pizza.price,
item : "Chicken Ginger".to_string(),
size : 1
};
let biryani = Food{
restaurant: String::from("Student Biryani"),
item: String::from("Beef Biryani"),
..karahi // Creating Instances From Other Instances With Struct Update Syntax
};
println!("Karahi: {:#?}", karahi);
karahi.price = 1100; // mutable struct value is changed
println!("Karahi {} price is {}", karahi.item, karahi.price);
println!("Biryani: {:#?}", biryani);
println!("{} price is {}", biryani.item, karahi.price);
println!("Struct with functions...");
func_struct(pizza); // here pizza moved to func_struct scope
// println!("{:#?}", pizza); // error borrowing moved value
println!("Struct in function return...");
println!("{:#?}", struct_in_fn());
let username = String::from("anasahmed700");
let email = String::from("anasahmed700@gmail.com");
println!("User details: {:#?}", build_user(email, username));
let white = Rgb(255, 255, 255);
let origin = Point(0, 0, 0);
println!("RGB Color values: {:?} Coordinates: {:?}", white, origin)
}
| 910
|
pub fn parse_mapping(input: &str) -> IResult<&str, BTreeMap<String, BTreeMap<String, usize>>> {
let mut mappings = BTreeMap::new();
for line in input.lines().map(str::trim) {
if line.is_empty() {
continue
}
let (input, (bag_name, list)) = parse_statement(line)?;
if !input.is_empty() {
return Err(nom::Err::Failure(nom::error::Error::new(input, nom::error::ErrorKind::LengthValue)))
}
let mut mapping = BTreeMap::new();
mapping.extend(list.iter().map(|(a, b)| (b.to_string(), *a)));
mappings.insert(bag_name.to_string(), mapping);
}
Ok(("", mappings))
}
| 911
|
pub
fn
compare_and_swap
(
&
self
current
:
T
new
:
T
)
-
>
T
{
match
self
.
compare_exchange
(
current
new
)
{
Ok
(
v
)
=
>
v
Err
(
v
)
=
>
v
}
}
| 912
|
async fn process_command(
ctx: Arc<Context>,
command: InteractionCommand,
cmd: InteractionCommandKind,
) -> Result<ProcessResult> {
match cmd {
InteractionCommandKind::Chat(cmd) => {
match pre_process_command(&ctx, &command, cmd).await? {
Some(result) => return Ok(result),
None => {
if cmd.flags.defer() {
command.defer(&ctx, cmd.flags.ephemeral()).await?;
}
(cmd.exec)(ctx, command).await?;
}
}
}
InteractionCommandKind::Message(cmd) => {
if cmd.flags.defer() {
command.defer(&ctx, cmd.flags.ephemeral()).await?;
}
(cmd.exec)(ctx, command).await?;
}
}
Ok(ProcessResult::Success)
}
| 913
|
fn inc_3() {
run_test(&Instruction { mnemonic: Mnemonic::INC, operand1: Some(Direct(EBX)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 67], OperandSize::Word)
}
| 914
|
fn align_address(ptr: *const u8, align: usize) -> usize {
let addr = ptr as usize;
if addr % align != 0 {
align - addr % align
} else {
0
}
}
| 915
|
pub fn assert_unary_arguments<D: Display>(name: D, actual: usize) -> Result<()> {
if actual != 1 {
return Err(ErrorCode::NumberArgumentsNotMatch(format!(
"{} expect to have single arguments, but got {}",
name, actual
)));
}
Ok(())
}
| 916
|
pub fn acrn_is_file(path: &str) -> bool {
fs::metadata(path)
.map(|metadata| metadata.is_file())
.unwrap_or(false)
}
| 917
|
pub(crate) fn ident<'a, E>(i: &'a str) -> nom::IResult<&'a str, Ident, E>
where
E: ParseError<&'a str>,
{
let mut chars = i.chars();
if let Some(f) = chars.next() {
if f.is_alphabetic() || f == '_' {
let mut idx = 1;
for c in chars {
if !(c.is_alphanumeric() || c == '_') {
break;
}
idx += 1;
}
let id = &i[..idx];
if is_reserved(id) {
Err(nom::Err::Error(E::from_error_kind(i, ErrorKind::Satisfy)))
} else {
Ok((&i[idx..], Ident::from_str_unchecked(id)))
}
} else {
Err(nom::Err::Error(E::from_error_kind(i, ErrorKind::Satisfy)))
}
} else {
Err(nom::Err::Error(E::from_error_kind(i, ErrorKind::Eof)))
}
}
| 918
|
fn env_var<K: AsRef<std::ffi::OsStr>>(key: K) -> String {
env::var(&key).expect(&format!("Unable to find env var {:?}", key.as_ref()))
}
| 919
|
fn test(){
}
| 920
|
pub fn write_map_len<W>(wr: &mut W, len: u32) -> Result<Marker, ValueWriteError>
where W: Write
{
if len < 16 {
let marker = Marker::FixMap(len as u8);
try!(write_fixval(wr, marker));
Ok(marker)
} else if len < 65536 {
try!(write_marker(wr, Marker::Map16));
write_data_u16(wr, len as u16).and(Ok(Marker::Map16))
} else {
try!(write_marker(wr, Marker::Map32));
write_data_u32(wr, len).and(Ok(Marker::Map32))
}
}
| 921
|
async fn run_completions(shell: ShellCompletion) -> Result<()> {
info!(version=%env!("CARGO_PKG_VERSION"), "constructing completions");
fn generate(generator: impl Generator) {
let mut cmd = Args::command();
clap_complete::generate(generator, &mut cmd, "watchexec", &mut std::io::stdout());
}
match shell {
ShellCompletion::Bash => generate(Shell::Bash),
ShellCompletion::Elvish => generate(Shell::Elvish),
ShellCompletion::Fish => generate(Shell::Fish),
ShellCompletion::Nu => generate(clap_complete_nushell::Nushell),
ShellCompletion::Powershell => generate(Shell::PowerShell),
ShellCompletion::Zsh => generate(Shell::Zsh),
}
Ok(())
}
| 922
|
fn draw_head<Message, B>(
renderer: &mut Renderer<B>,
head: &Element<'_, Message, Renderer<B>>,
layout: Layout<'_>,
cursor_position: Point,
viewport: &Rectangle,
style: &Style,
) -> (Primitive, mouse::Interaction)
where
B: Backend + backend::Text,
{
let mut head_children = layout.children();
let head_background = Primitive::Quad {
bounds: layout.bounds(),
background: style.head_background,
border_radius: style.border_radius,
border_width: 0.0,
border_color: Color::TRANSPARENT,
};
let (head, head_mouse_interaction) = head.draw(
renderer,
&Defaults {
text: defaults::Text {
color: style.head_text_color,
},
},
head_children
.next()
.expect("Graphics: Layout should have a head content layout"),
cursor_position,
viewport,
);
let (close, close_mouse_interaction) = head_children.next().map_or(
(Primitive::None, mouse::Interaction::default()),
|close_layout| {
let close_bounds = close_layout.bounds();
let is_mouse_over_close = close_bounds.contains(cursor_position);
(
Primitive::Text {
content: super::icons::Icon::X.into(),
font: super::icons::ICON_FONT,
size: close_layout.bounds().height
+ if is_mouse_over_close { 5.0 } else { 0.0 },
bounds: Rectangle {
x: close_bounds.center_x(),
y: close_bounds.center_y(),
..close_bounds
},
color: style.close_color,
horizontal_alignment: HorizontalAlignment::Center,
vertical_alignment: VerticalAlignment::Center,
},
if is_mouse_over_close {
mouse::Interaction::Pointer
} else {
mouse::Interaction::default()
},
)
},
);
(
Primitive::Group {
primitives: vec![head_background, head, close],
},
head_mouse_interaction.max(close_mouse_interaction),
)
}
| 923
|
fn
test_mismatched_types
(
)
-
>
Result
<
(
)
>
{
fn
is_invalid_column_type
(
err
:
Error
)
-
>
bool
{
matches
!
(
err
Error
:
:
InvalidColumnType
(
.
.
)
)
}
let
db
=
checked_memory_handle
(
)
?
;
db
.
execute
(
"
INSERT
INTO
foo
(
b
t
i
f
)
VALUES
(
X
'
0102
'
'
text
'
1
1
.
5
)
"
[
]
)
?
;
let
mut
stmt
=
db
.
prepare
(
"
SELECT
b
t
i
f
n
FROM
foo
"
)
?
;
let
mut
rows
=
stmt
.
query
(
[
]
)
?
;
let
row
=
rows
.
next
(
)
?
.
unwrap
(
)
;
assert_eq
!
(
vec
!
[
1
2
]
row
.
get
:
:
<
_
Vec
<
u8
>
>
(
0
)
?
)
;
assert_eq
!
(
"
text
"
row
.
get
:
:
<
_
String
>
(
1
)
?
)
;
assert_eq
!
(
1
row
.
get
:
:
<
_
c_int
>
(
2
)
?
)
;
assert
!
(
(
1
.
5
-
row
.
get
:
:
<
_
c_double
>
(
3
)
?
)
.
abs
(
)
<
f64
:
:
EPSILON
)
;
assert_eq
!
(
row
.
get
:
:
<
_
Option
<
c_int
>
>
(
4
)
?
None
)
;
assert_eq
!
(
row
.
get
:
:
<
_
Option
<
c_double
>
>
(
4
)
?
None
)
;
assert_eq
!
(
row
.
get
:
:
<
_
Option
<
String
>
>
(
4
)
?
None
)
;
assert
!
(
is_invalid_column_type
(
row
.
get
:
:
<
_
c_int
>
(
0
)
.
unwrap_err
(
)
)
)
;
assert
!
(
is_invalid_column_type
(
row
.
get
:
:
<
_
c_int
>
(
0
)
.
unwrap_err
(
)
)
)
;
assert
!
(
is_invalid_column_type
(
row
.
get
:
:
<
_
i64
>
(
0
)
.
err
(
)
.
unwrap
(
)
)
)
;
assert
!
(
is_invalid_column_type
(
row
.
get
:
:
<
_
c_double
>
(
0
)
.
unwrap_err
(
)
)
)
;
assert
!
(
is_invalid_column_type
(
row
.
get
:
:
<
_
String
>
(
0
)
.
unwrap_err
(
)
)
)
;
#
[
cfg
(
feature
=
"
time
"
)
]
assert
!
(
is_invalid_column_type
(
row
.
get
:
:
<
_
time
:
:
OffsetDateTime
>
(
0
)
.
unwrap_err
(
)
)
)
;
assert
!
(
is_invalid_column_type
(
row
.
get
:
:
<
_
Option
<
c_int
>
>
(
0
)
.
unwrap_err
(
)
)
)
;
assert
!
(
is_invalid_column_type
(
row
.
get
:
:
<
_
c_int
>
(
1
)
.
unwrap_err
(
)
)
)
;
assert
!
(
is_invalid_column_type
(
row
.
get
:
:
<
_
i64
>
(
1
)
.
err
(
)
.
unwrap
(
)
)
)
;
assert
!
(
is_invalid_column_type
(
row
.
get
:
:
<
_
c_double
>
(
1
)
.
unwrap_err
(
)
)
)
;
assert
!
(
is_invalid_column_type
(
row
.
get
:
:
<
_
Vec
<
u8
>
>
(
1
)
.
unwrap_err
(
)
)
)
;
assert
!
(
is_invalid_column_type
(
row
.
get
:
:
<
_
Option
<
c_int
>
>
(
1
)
.
unwrap_err
(
)
)
)
;
assert
!
(
is_invalid_column_type
(
row
.
get
:
:
<
_
String
>
(
2
)
.
unwrap_err
(
)
)
)
;
assert
!
(
is_invalid_column_type
(
row
.
get
:
:
<
_
Vec
<
u8
>
>
(
2
)
.
unwrap_err
(
)
)
)
;
assert
!
(
is_invalid_column_type
(
row
.
get
:
:
<
_
Option
<
String
>
>
(
2
)
.
unwrap_err
(
)
)
)
;
assert
!
(
is_invalid_column_type
(
row
.
get
:
:
<
_
c_int
>
(
3
)
.
unwrap_err
(
)
)
)
;
assert
!
(
is_invalid_column_type
(
row
.
get
:
:
<
_
i64
>
(
3
)
.
err
(
)
.
unwrap
(
)
)
)
;
assert
!
(
is_invalid_column_type
(
row
.
get
:
:
<
_
String
>
(
3
)
.
unwrap_err
(
)
)
)
;
assert
!
(
is_invalid_column_type
(
row
.
get
:
:
<
_
Vec
<
u8
>
>
(
3
)
.
unwrap_err
(
)
)
)
;
assert
!
(
is_invalid_column_type
(
row
.
get
:
:
<
_
Option
<
c_int
>
>
(
3
)
.
unwrap_err
(
)
)
)
;
assert
!
(
is_invalid_column_type
(
row
.
get
:
:
<
_
c_int
>
(
4
)
.
unwrap_err
(
)
)
)
;
assert
!
(
is_invalid_column_type
(
row
.
get
:
:
<
_
i64
>
(
4
)
.
err
(
)
.
unwrap
(
)
)
)
;
assert
!
(
is_invalid_column_type
(
row
.
get
:
:
<
_
c_double
>
(
4
)
.
unwrap_err
(
)
)
)
;
assert
!
(
is_invalid_column_type
(
row
.
get
:
:
<
_
String
>
(
4
)
.
unwrap_err
(
)
)
)
;
assert
!
(
is_invalid_column_type
(
row
.
get
:
:
<
_
Vec
<
u8
>
>
(
4
)
.
unwrap_err
(
)
)
)
;
#
[
cfg
(
feature
=
"
time
"
)
]
assert
!
(
is_invalid_column_type
(
row
.
get
:
:
<
_
time
:
:
OffsetDateTime
>
(
4
)
.
unwrap_err
(
)
)
)
;
Ok
(
(
)
)
}
| 924
|
fn run_a_few_inputs() {
let corpus = Path::new("fuzz").join("corpus").join("run_few");
let project = project("run_a_few_inputs")
.with_fuzz()
.fuzz_target(
"run_few",
r#"
#![no_main]
use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: &[u8]| {
assert!(data.len() != 4);
});
"#,
)
.file(corpus.join("pass-0"), "")
.file(corpus.join("pass-1"), "1")
.file(corpus.join("pass-2"), "12")
.file(corpus.join("pass-3"), "123")
.file(corpus.join("fail"), "fail")
.build();
project
.cargo_fuzz()
.arg("run")
.arg("run_few")
.arg(corpus.join("pass-0"))
.arg(corpus.join("pass-1"))
.arg(corpus.join("pass-2"))
.arg(corpus.join("pass-3"))
.assert()
.stderr(
predicate::str::contains("Running 4 inputs 1 time(s) each.").and(
predicate::str::contains("Running: fuzz/corpus/run_few/pass"),
),
)
.success();
}
| 925
|
fn build_unparsed(s: ~str) -> Result<IRCToken, ~str> {
Ok(Unparsed(s))
}
| 926
|
fn KeyboardHandler(vector: u8){
let mut buffer = b"[INT: , ]".clone();
static mut keyboard_count: u8 = 0;
buffer[5] = vector / 10 + '0' as u8;
buffer[6] = vector % 10 + '0' as u8;
unsafe {
buffer[8] = keyboard_count + '0' as u8;
keyboard_count = (keyboard_count + 1) % 10;
}
print_string(0, 0, &buffer);
if IsOutputBufferFull() {
let temp = GetKeyboardScanCode();
ConvertScanCodeAndPutQueue(temp);
}
SendEOI((vector - pic::PIC_IRQSTARTVECTOR) as u16 );
}
| 927
|
fn up_to_release(
repo: &Repository,
reviewers: &Reviewers,
mailmap: &Mailmap,
to: &VersionTag,
) -> Result<AuthorMap, Box<dyn std::error::Error>> {
let to_commit = repo.find_commit(to.commit).map_err(|e| {
ErrorContext(
format!(
"find_commit: repo={}, commit={}",
repo.path().display(),
to.commit
),
Box::new(e),
)
})?;
let modules = get_submodules(&repo, &to_commit)?;
let mut author_map = build_author_map(&repo, &reviewers, &mailmap, "", &to.raw_tag)
.map_err(|e| ErrorContext(format!("Up to {}", to), e))?;
for module in &modules {
if let Ok(path) = update_repo(&module.repository) {
let subrepo = Repository::open(&path)?;
let submap = build_author_map(
&subrepo,
&reviewers,
&mailmap,
"",
&module.commit.to_string(),
)?;
author_map.extend(submap);
}
}
Ok(author_map)
}
| 928
|
fn listing_a_single_migration_name_should_work(api: TestApi) {
let dm = api.datamodel_with_provider(
r#"
model Cat {
id Int @id
name String
}
"#,
);
let migrations_directory = api.create_migrations_directory();
api.create_migration("init", &dm, &migrations_directory).send_sync();
api.apply_migrations(&migrations_directory)
.send_sync()
.assert_applied_migrations(&["init"]);
api.list_migration_directories(&migrations_directory)
.send()
.assert_listed_directories(&["init"]);
}
| 929
|
pub fn test_mulw64() {
let buffer = fs::read("tests/programs/mulw64").unwrap().into();
let result = run::<u64, SparseMemory<u64>>(&buffer, &vec!["mulw64".into()]);
assert!(result.is_ok());
}
| 930
|
fn func_struct(data: Food){
println!("restaurant => {}", data.restaurant);
println!("item => {}", data.item);
println!("price => {}", data.price);
}
| 931
|
fn adapters() {
assert_done(|| list().map(|a| a + 1).collect(), Ok(vec![2, 3, 4]));
assert_done(|| err_list().map_err(|a| a + 1).collect(), Err(4));
assert_done(|| list().fold(0, |a, b| finished::<i32, u32>(a + b)), Ok(6));
assert_done(|| err_list().fold(0, |a, b| finished::<i32, u32>(a + b)), Err(3));
assert_done(|| list().filter(|a| *a % 2 == 0).collect(), Ok(vec![2]));
assert_done(|| list().and_then(|a| Ok(a + 1)).collect(), Ok(vec![2, 3, 4]));
assert_done(|| list().then(|a| a.map(|e| e + 1)).collect(), Ok(vec![2, 3, 4]));
assert_done(|| list().and_then(|a| failed::<i32, u32>(a as u32)).collect(),
Err(1));
assert_done(|| err_list().or_else(|a| {
finished::<i32, u32>(a as i32)
}).collect(), Ok(vec![1, 2, 3]));
assert_done(|| list().map(|_| list()).flatten().collect(),
Ok(vec![1, 2, 3, 1, 2, 3, 1, 2, 3]));
// assert_eq!(list().map(|i| finished::<_, u32>(i)).flatten().collect(),
// Ok(vec![1, 2, 3]));
assert_done(|| list().skip_while(|e| Ok(*e % 2 == 1)).collect(),
Ok(vec![2, 3]));
assert_done(|| list().take(2).collect(), Ok(vec![1, 2]));
assert_done(|| list().skip(2).collect(), Ok(vec![3]));
}
| 932
|
pub async fn client_async<'a, R, S>(
request: R,
stream: S,
) -> Result<(WebSocketStream<TokioAdapter<S>>, Response), Error>
where
R: IntoClientRequest + Unpin,
S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin,
{
client_async_with_config(request, stream, None).await
}
| 933
|
fn bindgen_test_layout_Bar() {
const UNINIT: ::std::mem::MaybeUninit<Bar> = ::std::mem::MaybeUninit::uninit();
let ptr = UNINIT.as_ptr();
assert_eq!(
::std::mem::size_of::<Bar>(),
48usize,
concat!("Size of: ", stringify!(Bar)),
);
assert_eq!(
::std::mem::align_of::<Bar>(),
8usize,
concat!("Alignment of ", stringify!(Bar)),
);
assert_eq!(
unsafe { ::std::ptr::addr_of!((*ptr).baz1) as usize - ptr as usize },
0usize,
concat!("Offset of field: ", stringify!(Bar), "::", stringify!(baz1)),
);
assert_eq!(
unsafe { ::std::ptr::addr_of!((*ptr).baz2) as usize - ptr as usize },
4usize,
concat!("Offset of field: ", stringify!(Bar), "::", stringify!(baz2)),
);
assert_eq!(
unsafe { ::std::ptr::addr_of!((*ptr).baz3) as usize - ptr as usize },
8usize,
concat!("Offset of field: ", stringify!(Bar), "::", stringify!(baz3)),
);
assert_eq!(
unsafe { ::std::ptr::addr_of!((*ptr).baz4) as usize - ptr as usize },
12usize,
concat!("Offset of field: ", stringify!(Bar), "::", stringify!(baz4)),
);
assert_eq!(
unsafe { ::std::ptr::addr_of!((*ptr).baz_ptr1) as usize - ptr as usize },
16usize,
concat!("Offset of field: ", stringify!(Bar), "::", stringify!(baz_ptr1)),
);
assert_eq!(
unsafe { ::std::ptr::addr_of!((*ptr).baz_ptr2) as usize - ptr as usize },
24usize,
concat!("Offset of field: ", stringify!(Bar), "::", stringify!(baz_ptr2)),
);
assert_eq!(
unsafe { ::std::ptr::addr_of!((*ptr).baz_ptr3) as usize - ptr as usize },
32usize,
concat!("Offset of field: ", stringify!(Bar), "::", stringify!(baz_ptr3)),
);
assert_eq!(
unsafe { ::std::ptr::addr_of!((*ptr).baz_ptr4) as usize - ptr as usize },
40usize,
concat!("Offset of field: ", stringify!(Bar), "::", stringify!(baz_ptr4)),
);
}
| 934
|
pub fn get_remaining_timelimit(ctx: &PbsContext, job_id: &str) -> anyhow::Result<Duration> {
let result = Command::new(&ctx.qstat_path)
.args(&["-f", "-F", "json", job_id])
.output()?;
if !result.status.success() {
anyhow::bail!(
"qstat command exited with {}: {}\n{}",
result.status,
String::from_utf8_lossy(&result.stderr),
String::from_utf8_lossy(&result.stdout)
);
}
let output = String::from_utf8_lossy(&result.stdout).into_owned();
log::debug!("qstat output: {}", output.trim());
parse_pbs_job_remaining_time(job_id, output.as_str())
}
| 935
|
fn main() {
let cli = CliArgs::from_args();
let args = Args::from(cli);
actix::System::builder()
.build()
.block_on(async move { args.process().await });
}
| 936
|
pub fn causet_partitioner_context_free(context: Box<CausetPartitionerContext>) {
//println!("causet_partitioner_context_free");
println!("causet_partitioner_context_free");
}
| 937
|
fn archive(version: &Version) -> String {
format!("ruby-{}.zip", version)
}
| 938
|
fn test_invalid_variable_2() {
let parsed_data = parse(&"$invalid: false");
assert!(parsed_data
.unwrap_err()
.downcast_ref::<ParseError>()
.is_some());
}
| 939
|
fn archive(version: &Version) -> String {
format!("ruby-{}.tar.xz", version)
}
| 940
|
fn main() {
let mut prod_env = "".to_string();
let ws_server_thread = thread::Builder::new().name("ws_server".to_string()).spawn(move || {
println!("Starting websocket server..");
listen("127.0.0.1:3012", |out| { Server { out: out } }).unwrap()
}).unwrap();
thread::sleep(time::Duration::from_millis(1000));
match env::var("PROD_ENV".to_string()) {
Ok(val) => prod_env = val,
Err(e) => println!("Operating in dev mode due to: {}", e),
}
if prod_env != "" {
let app_router_thread = thread::Builder::new().name("app_router".to_string()).spawn(move || {
let mut app_router = Nickel::new();
println!("Starting app router..");
app_router.mount("/controller/", StaticFilesHandler::new("app/controller/"));
app_router.mount("/display/", StaticFilesHandler::new("app/display/"));
app_router.listen("127.0.0.1:6767").unwrap();
}).unwrap();
let _ = app_router_thread.join();
}
let _ = ws_server_thread.join();
println!("Server closing down..");
}
| 941
|
pub
fn
fetch_or
(
&
self
val
:
bool
)
-
>
bool
{
let
a
=
unsafe
{
&
*
(
self
.
as_ptr
(
)
as
*
const
AtomicBool
)
}
;
a
.
fetch_or
(
val
Ordering
:
:
AcqRel
)
}
| 942
|
fn solve_1(input: &str) -> usize {
let mut length = 0;
let mut result = input.to_owned();
loop {
result = reduce(&result);
let reduced_length = result.len();
if reduced_length == length {
break;
}
length = reduced_length;
}
length
}
| 943
|
fn ownership_test() {
let mut v = Vec::new();
for i in 101..106 {
v.push(i.to_string());
}
let fifth = v.pop().unwrap();
assert_eq!(fifth, "105");
let second = v.swap_remove(1);
assert_eq!(second, "102");
let third = std::mem::replace(&mut v[2], "substitute".to_string());
assert_eq!(third, "103");
assert_eq!(v, vec!["101", "104", "substitute"]);
struct Person {
name: Option<String>,
birth: Option<i32>,
};
let mut composers = Vec::new();
composers.push(Person {
name: Some("Palestrina".to_string()),
birth: Some(1525),
});
// let first_name = composers[0].name // error
let first_name = std::mem::replace(&mut composers[0].name, None);
assert_eq!(first_name, Some("Palestrina".to_string()));
assert_eq!(composers[0].name, None);
let birth = composers[0].birth.take();
assert_eq!(birth, Some(1525));
assert_eq!(composers[0].birth, None);
}
| 944
|
extern "C" fn telemetry_thread_fn() {
let _ = MAIN_SENDER.send(GlobalEvent::Info);
CHARLIE_LEDS.lock().unwrap().set_led(0, true);
loop {
CHARLIE_LEDS.lock().unwrap().next();
delay(Duration::from_ms(1)).unwrap();
}
}
| 945
|
fn current_manifest_path() -> ManifestResult {
let locate_result = Command::new("cargo").arg("locate-project").output();
let output = match locate_result {
Ok(out) => out,
Err(e) => {
print!("Failure: {:?}", e);
panic!("Cargo failure to target project via locate-project")
}
};
if !output.status.success() {
return Err(ManifestLoadError::CargoLoadFailure);
}
#[derive(Deserialize)]
struct Data {
root: String,
}
let stdout = String::from_utf8(output.stdout).unwrap();
let decoded: Data = serde_json::from_str(&stdout).unwrap();
let path = Path::new(&decoded.root).to_owned();
// debug!("manifest: {:?}", path);
Ok(path)
}
| 946
|
pub extern "x86-interrupt" fn hdd1() { CommonInterruptHandler(46); }
| 947
|
fn binary_encoding_compatibility_tests_optional() {
eprintln!("base64");
let base64_decompressed = "During tattooing, ink is injected into the skin, initiating an immune response, and cells called \"macrophages\" move into the area and \"eat up\" the ink. The macrophages carry some of the ink to the body\'s lymph nodes, but some that are filled with ink stay put, embedded in the skin. That\'s what makes the tattoo visible under the skin. Dalhousie Uiversity\'s Alec Falkenham is developing a topical cream that works by targeting the macrophages that have remained at the site of the tattoo. New macrophages move in to consume the previously pigment-filled macrophages and then migrate to the lymph nodes, eventually taking all the dye with them. \"When comparing it to laser-based tattoo removal, in which you see the burns, the scarring, the blisters, in this case, we\'ve designed a drug that doesn\'t really have much off-target effect,\" he said. \"We\'re not targeting any of the normal skin cells, so you won\'t see a lot of inflammation. In fact, based on the process that we\'re actually using, we don\'t think there will be any inflammation at all and it would actually be anti-inflammatory.";
let base64_compressed = "CIVwTglgdg5gBAFwIYIQezdGAaO0DWeAznlAFYCmAxghQCanqIAWFcR+0u0ECEKWOEih4AtqJBQ2YCkQAOaKEQq5hDKhQA2mklSTb6cAESikVMGjnMkMWUbii0ANzbQmCVkJlIhUBkYoUOBA5ew9XKHwAOjgAFU9Tc0trW10kMDAAT3Y0UTY0ADMWCMJ3TwAjNDpMgHISTUzRKzgoKtlccpAEHLyWIPS2AogDBgB3XmZSQiJkbLku3ApRcvo6Q2hi9k4oGPiUOrhR627TfFlN5FQMOCcIIghyzTZJNbBNjmgY4H1mNBB7tgAVQgLjA9wQtRIAEEnlQ4AAxfRnKDWUTEOBrFyaSyCHzoOQQPSaODmQJojxBUZoMD4EjlbLIMC2PiwTaJCxWGznCndawuOAyUzQQxBcLsXj5Ipiy7oNAxAByFFGDjMHJS50c/I2TCoiiIIF6YrkMlufyIDTgBJgeSgCAAtEMRiqkpzUr4GOERKIIDAwCg2GU2A0mpNWmsiIsXLaQPoLchtvBY5tqmxxh5iqIYkYAOqsES6prpQS8RBoOCaJDKMB28qVwwy66C5z6bgiI6EyaZP7sCgBirgJS4MVEPQZLBDiqaO60MGtlh3El13CjCg1fnhn1SBg+OhgEDwHkYtCyKA1brebTZPlsCRUSaFAp2xnMuAUAoFagIbD2TxEJAQOgs2zVcZBaNBumfCgWUTKBskKTZWjAUxiQ+fMtB0XAiDLLsQEORQzx7NgfGxbp4OgAoK3EARFBiABJEQCjML84FrZQGEUTZjTQDQiBIQ8VxqUCmJjS9gnuWBlzYOh8Ig5gCGKUDxm0FiiNg0gKKQKi+A4/plLUPBuipEBNG3GgRItFZfD4O1yMo0x0CyKIgA";
test_enc_bin_compat(
lz_str::compress_to_base64,
&base64_decompressed.encode_utf16().collect::<Vec<u16>>(),
base64_compressed.to_string(),
);
eprintln!("uriEncoding");
let uri_encoding_decompressed = "During tattooing, ink is injected into the skin, initiating an immune response, and cells called \"macrophages\" move into the area and \"eat up\" the ink. The macrophages carry some of the ink to the body\'s lymph nodes, but some that are filled with ink stay put, embedded in the skin. That\'s what makes the tattoo visible under the skin. Dalhousie Uiversity\'s Alec Falkenham is developing a topical cream that works by targeting the macrophages that have remained at the site of the tattoo. New macrophages move in to consume the previously pigment-filled macrophages and then migrate to the lymph nodes, eventually taking all the dye with them. \"When comparing it to laser-based tattoo removal, in which you see the burns, the scarring, the blisters, in this case, we\'ve designed a drug that doesn\'t really have much off-target effect,\" he said. \"We\'re not targeting any of the normal skin cells, so you won\'t see a lot of inflammation. In fact, based on the process that we\'re actually using, we don\'t think there will be any inflammation at all and it would actually be anti-inflammatory.";
let uri_encoding_compressed = "CIVwTglgdg5gBAFwIYIQezdGAaO0DWeAznlAFYCmAxghQCanqIAWFcR+0u0ECEKWOEih4AtqJBQ2YCkQAOaKEQq5hDKhQA2mklSTb6cAESikVMGjnMkMWUbii0ANzbQmCVkJlIhUBkYoUOBA5ew9XKHwAOjgAFU9Tc0trW10kMDAAT3Y0UTY0ADMWCMJ3TwAjNDpMgHISTUzRKzgoKtlccpAEHLyWIPS2AogDBgB3XmZSQiJkbLku3ApRcvo6Q2hi9k4oGPiUOrhR627TfFlN5FQMOCcIIghyzTZJNbBNjmgY4H1mNBB7tgAVQgLjA9wQtRIAEEnlQ4AAxfRnKDWUTEOBrFyaSyCHzoOQQPSaODmQJojxBUZoMD4EjlbLIMC2PiwTaJCxWGznCndawuOAyUzQQxBcLsXj5Ipiy7oNAxAByFFGDjMHJS50c-I2TCoiiIIF6YrkMlufyIDTgBJgeSgCAAtEMRiqkpzUr4GOERKIIDAwCg2GU2A0mpNWmsiIsXLaQPoLchtvBY5tqmxxh5iqIYkYAOqsES6prpQS8RBoOCaJDKMB28qVwwy66C5z6bgiI6EyaZP7sCgBirgJS4MVEPQZLBDiqaO60MGtlh3El13CjCg1fnhn1SBg+OhgEDwHkYtCyKA1brebTZPlsCRUSaFAp2xnMuAUAoFagIbD2TxEJAQOgs2zVcZBaNBumfCgWUTKBskKTZWjAUxiQ+fMtB0XAiDLLsQEORQzx7NgfGxbp4OgAoK3EARFBiABJEQCjML84FrZQGEUTZjTQDQiBIQ8VxqUCmJjS9gnuWBlzYOh8Ig5gCGKUDxm0FiiNg0gKKQKi+A4-plLUPBuipEBNG3GgRItFZfD4O1yMo0x0CyKIgA";
test_enc_bin_compat(
lz_str::compress_to_encoded_uri_component,
&uri_encoding_decompressed
.encode_utf16()
.collect::<Vec<u16>>(),
uri_encoding_compressed.into(),
);
eprintln!("UInt8Array");
let uint8_array_decompressed = "During tattooing, ink is injected into the skin, initiating an immune response, and cells called \"macrophages\" move into the area and \"eat up\" the ink. The macrophages carry some of the ink to the body\'s lymph nodes, but some that are filled with ink stay put, embedded in the skin. That\'s what makes the tattoo visible under the skin. Dalhousie Uiversity\'s Alec Falkenham is developing a topical cream that works by targeting the macrophages that have remained at the site of the tattoo. New macrophages move in to consume the previously pigment-filled macrophages and then migrate to the lymph nodes, eventually taking all the dye with them. \"When comparing it to laser-based tattoo removal, in which you see the burns, the scarring, the blisters, in this case, we\'ve designed a drug that doesn\'t really have much off-target effect,\" he said. \"We\'re not targeting any of the normal skin cells, so you won\'t see a lot of inflammation. In fact, based on the process that we\'re actually using, we don\'t think there will be any inflammation at all and it would actually be anti-inflammatory.";
let uint8_array_compressed = &[
8, 133, 112, 78, 9, 96, 118, 14, 96, 4, 1, 112, 33, 130, 16, 123, 55, 70, 1, 163, 180, 13,
103, 128, 206, 121, 64, 21, 128, 166, 3, 24, 33, 64, 38, 167, 168, 128, 22, 21, 196, 126,
210, 237, 4, 8, 66, 150, 56, 72, 161, 224, 11, 106, 36, 20, 54, 96, 41, 16, 0, 230, 138,
17, 10, 185, 132, 50, 161, 64, 13, 166, 146, 84, 147, 111, 167, 0, 17, 40, 164, 84, 193,
163, 156, 201, 12, 89, 70, 226, 139, 64, 13, 205, 180, 38, 9, 89, 9, 148, 136, 84, 6, 70,
40, 80, 224, 64, 229, 236, 61, 92, 161, 240, 0, 232, 224, 0, 85, 61, 77, 205, 45, 173, 109,
116, 144, 192, 192, 1, 61, 216, 209, 68, 216, 208, 0, 204, 88, 35, 9, 221, 60, 0, 140, 208,
233, 50, 1, 200, 73, 53, 51, 68, 172, 224, 160, 171, 101, 113, 202, 64, 16, 114, 242, 88,
131, 210, 216, 10, 32, 12, 24, 1, 221, 121, 153, 73, 8, 137, 145, 178, 228, 187, 112, 41,
69, 203, 232, 233, 13, 161, 139, 217, 56, 160, 99, 226, 80, 234, 225, 71, 173, 187, 77,
241, 101, 55, 145, 80, 48, 224, 156, 32, 136, 33, 203, 52, 217, 36, 214, 193, 54, 57, 160,
99, 129, 245, 152, 208, 65, 238, 216, 0, 85, 8, 11, 140, 15, 112, 66, 212, 72, 0, 65, 39,
149, 14, 0, 3, 23, 209, 156, 160, 214, 81, 49, 14, 6, 177, 114, 105, 44, 130, 31, 58, 14,
65, 3, 210, 104, 224, 230, 64, 154, 35, 196, 21, 25, 160, 192, 248, 18, 57, 91, 44, 131, 2,
216, 248, 176, 77, 162, 66, 197, 97, 179, 156, 41, 221, 107, 11, 142, 3, 37, 51, 65, 12,
65, 112, 187, 23, 143, 146, 41, 139, 46, 232, 52, 12, 64, 7, 33, 69, 24, 56, 204, 28, 148,
185, 209, 207, 200, 217, 48, 168, 138, 34, 8, 23, 166, 43, 144, 201, 110, 127, 34, 3, 78,
0, 73, 129, 228, 160, 8, 0, 45, 16, 196, 98, 170, 74, 115, 82, 190, 6, 56, 68, 74, 32, 128,
192, 192, 40, 54, 25, 77, 128, 210, 106, 77, 90, 107, 34, 34, 197, 203, 105, 3, 232, 45,
200, 109, 188, 22, 57, 182, 169, 177, 198, 30, 98, 168, 134, 36, 96, 3, 170, 176, 68, 186,
166, 186, 80, 75, 196, 65, 160, 224, 154, 36, 50, 140, 7, 111, 42, 87, 12, 50, 235, 160,
185, 207, 166, 224, 136, 142, 132, 201, 166, 79, 238, 192, 160, 6, 42, 224, 37, 46, 12, 84,
67, 208, 100, 176, 67, 138, 166, 142, 235, 67, 6, 182, 88, 119, 18, 93, 119, 10, 48, 160,
213, 249, 225, 159, 84, 129, 131, 227, 161, 128, 64, 240, 30, 70, 45, 11, 34, 128, 213,
186, 222, 109, 54, 79, 150, 192, 145, 81, 38, 133, 2, 157, 177, 156, 203, 128, 80, 10, 5,
106, 2, 27, 15, 100, 241, 16, 144, 16, 58, 11, 54, 205, 87, 25, 5, 163, 65, 186, 103, 194,
129, 101, 19, 40, 27, 36, 41, 54, 86, 140, 5, 49, 137, 15, 159, 50, 208, 116, 92, 8, 131,
44, 187, 16, 16, 228, 80, 207, 30, 205, 129, 241, 177, 110, 158, 14, 128, 10, 10, 220, 64,
17, 20, 24, 128, 4, 145, 16, 10, 51, 11, 243, 129, 107, 101, 1, 132, 81, 54, 99, 77, 0,
208, 136, 18, 16, 241, 92, 106, 80, 41, 137, 141, 47, 96, 158, 229, 129, 151, 54, 14, 135,
194, 32, 230, 0, 134, 41, 64, 241, 155, 65, 98, 136, 216, 52, 128, 162, 144, 42, 47, 128,
227, 250, 101, 45, 67, 193, 186, 42, 68, 4, 209, 183, 26, 4, 72, 180, 86, 95, 15, 131, 181,
200, 202, 52, 199, 64, 178, 40, 136, 0, 0,
];
test_enc_bin_compat(
lz_str::compress_to_uint8_array,
&uint8_array_decompressed
.encode_utf16()
.collect::<Vec<u16>>(),
uint8_array_compressed.to_vec(),
);
eprintln!("UTF16");
let utf16_decompressed = "During tattooing, ink is injected into the skin, initiating an immune response, and cells called \"macrophages\" move into the area and \"eat up\" the ink. The macrophages carry some of the ink to the body\'s lymph nodes, but some that are filled with ink stay put, embedded in the skin. That\'s what makes the tattoo visible under the skin. Dalhousie Uiversity\'s Alec Falkenham is developing a topical cream that works by targeting the macrophages that have remained at the site of the tattoo. New macrophages move in to consume the previously pigment-filled macrophages and then migrate to the lymph nodes, eventually taking all the dye with them. \"When comparing it to laser-based tattoo removal, in which you see the burns, the scarring, the blisters, in this case, we\'ve designed a drug that doesn\'t really have much off-target effect,\" he said. \"We\'re not targeting any of the normal skin cells, so you won\'t see a lot of inflammation. In fact, based on the process that we\'re actually using, we don\'t think there will be any inflammation at all and it would actually be anti-inflammatory.";
let utf16_compressed = "\u{0462}\u{5C33}\u{414C}\u{0780}\u{7320}\u{1025}\u{6063}\u{0230}\u{3DBB}\u{51A0}\u{3496}\u{40F6}\u{3C26}\u{3A05}K\u{00C6}\u{01AC}\u{0870}\u{04F4}\u{7AA8}\u{00D0}\u{5731}\u{7DC5}\u{6D24}\u{0441}\u{25AE}\u{0934}\u{1E20}\u{5B71}\u{1070}\u{6CE0}\u{2930}\u{0093}\u{22A4}\u{2177}\u{1863}\u{152A}V\u{4D44}\u{54B3}\u{37F3}\u{4024}\u{2534}\u{456C}\u{0D3C}\u{7344}\u{18D2}\u{4702}\u{45C0}\u{0393}\u{36A4}\u{60B5}\u{486C}\u{5241}\u{282C}\u{4648}\u{2890}\u{1059}\u{3DA7}\u{55EA}\u{0FA0}\u{03C3}\u{4020}\u{555D}\u{2706}\u{4B8B}\u{2DCE}\u{492C}\u{0620}\u{0517}\u{31C2}\u{44F8}\u{6820}\u{3336}\u{0481}\u{1DF3}\u{6024}\u{3363}\u{5284}\u{01E8}\u{24BA}\u{4CF1}\u{15BC}\u{0A2A}\u{5B4B}\u{4749}@\u{7312}\u{2C61}\u{74D6}\u{0164}\u{00E1}\u{402E}\u{7606}\u{32B2}\u{08A9}\u{48F9}\u{394E}\u{6E25}\u{147C}\u{5F67}\u{2456}\u{4337}\u{5958}\u{5051}\u{78B4}\u{1D7C}\u{149A}\u{6DFA}\u{37E5}\u{4A8F}\u{1170}\u{1890}\u{2728}\u{1124}\u{1CD3}\u{26E9}\u{137B}\u{028C}\u{39C0}\u{31E0}\u{7D86}\u{1A28}\u{1F0D}\u{4022}\u{5440}\u{1738}\u{0F90}\u{218A}\u{1220}\u{0844}\u{7970}\u{7020}\u{0C7F}\u{2359}\u{20F6}\u{28B8}\u{43A1}\u{564E}\u{26B2}\u{6430}\u{7D08}\u{1CA2}\u{03F2}\u{3490}\u{39B0}\u{1364}\u{3C61}\u{28ED}\u{0323}\u{7044}\u{397B}\u{1661}\u{40D6}\u{1F36}\u{04FA}\u{1236}\u{15A6}\u{6758}\u{29FD}\u{35A5}\u{63A0}\u{64C6}\u{3430}\u{622B}\u{430C}\u{2F3F}\u{1249}\u{45B7}\u{3A2D}\u{01A8}\u{0092}\u{0A48}\u{6103}\u{1859}\u{14D9}\u{6907}\u{7256}\u{2635}\u{08C2}\u{1060}\u{5EB8}\u{5741}\u{498E}\u{3FB1}\u{00F3}\u{4029}\u{183E}\u{2520}\u{2020}\u{5A41}\u{4482}\u{5545}\u{1CF4}\u{57E0}\u{63A4}\u{2271}\u{0223}\u{01A0}\u{2856}\u{0CC6}\u{6054}\u{4D69}\u{55C6}\u{5931}\u{0B37}\u{16F2}\u{0408}\u{1704}\u{1B8F}\u{02E7}\u{1B8A}\u{4DAE}\u{1899}\u{4571}\u{0644}\u{3021}\u{6ACC}\u{08B7}\u{2A8B}\u{52A2}\u{2F31}\u{0361}\u{60BA}\u{1239}\u{2321}\u{6E05}\u{2590}\u{61B7}\u{2EA2}\u{73BF}\u{2700}\u{4467}\u{2152}\u{34E9}\u{7F0C}\u{0520}\u{18CB}\u{406A}\u{2E2C}\u{2A41}\u{7439}\u{1628}\u{38CA}\u{3497}\u{2D2C}\u{0D8C}\u{5897}\u{094E}\u{5DE2}\u{4634}\u{0D7F}\u{4F2C}\u{7D72}\u{0327}\u{63C1}\u{4040}\u{3C27}\u{48E5}\u{50D2}\u{1426}\u{570B}\u{3CFA}\u{366F}\u{4B80}\u{2474}\u{24F0}\u{5049}\u{6DAC}\u{734E}\u{00C0}\u{0A25}\u{3521}\u{06E3}\u{6CBE}\u{1129}\u{00A1}\u{684C}\u{6DBA}\u{5739}\u{02F1}\u{508E}\u{4D18}\u{2836}\u{28B9}\u{208C}\u{4872}\u{3676}\u{4622}\u{4C82}\u{2213}\u{734D}\u{03C2}\u{7042}\u{0679}\u{3B30}\u{0892}\u{1453}\u{63F9}\u{583F}\u{0DAB}\u{3A98}\u{1D20}\u{0A2A}\u{6E40}\u{0465}\u{0330}i\u{08A0}\u{28EC}\u{1807}\u{018B}\u{32A0}\u{6134}\u{26EC}\u{34F0}\u{06A4}\u{2068}\u{2202}\u{5C8A}\u{2834}\u{6283}\u{260C}\u{0A0E}\u{2C2C}\u{5CF8}\u{1D2F}\u{4240}\u{7320}\u{21AA}\u{283E}\u{19D4}\u{0B34}\u{2380}\u{6921}\u{22B0}\u{1537}\u{6058}\u{7F6C}\u{52F4}\u{1E2D}\u{68C9}\u{0829}\u{51D7}\u{0D22}\u{124D}\u{0AEB}\u{7118}\u{1DCE}\u{2348}\u{69AE}\u{40D2}\u{1464}\u{0020}\u{0020}";
test_enc_bin_compat(
lz_str::compress_to_utf16,
&utf16_decompressed.encode_utf16().collect::<Vec<u16>>(),
utf16_compressed.into(),
);
}
| 948
|
fn index(data: web::Json<PackageData>) -> String {
let result = ethernet_header(&data.data[..]);
let (rest, eth_header) = if result.is_ok() {
let (r, eh) = result.unwrap();
(r, Some(eh))
} else {
(&data.data[..], None)
};
if eth_header.is_some() {
let result = ipv4_header(rest);
let (rest, ip_header) = if result.is_ok() {
let (r, ipv4_header) = result.unwrap();
(r, Some(ipv4_header))
} else {
(&data.data[..], None)
};
let response = Resp {
ethernet_header: eth_header,
ip_header,
rest,
};
serde_json::to_string(&response).unwrap()
} else {
let response = Resp {
ethernet_header: None,
ip_header: None,
rest,
};
serde_json::to_string(&response).unwrap()
}
}
| 949
|
fn calculate_triangle_buffer_hash(triangles: &[TriangleDefinition]) -> u64 {
let mut hasher = FxHasher::default();
triangles.hash(&mut hasher);
hasher.finish()
}
| 950
|
pub fn grammar() -> ParseContext<IRCToken> {
let mut ctx = ParseContext::new();
/*
message = [ ":" prefix SPACE ] command [ params ] crlf
prefix = servername / ( nickname [ [ "!" user ] "@" host ] )
command = 1*letter / 3digit
params = *14( SPACE middle ) [ SPACE ":" trailing ]
=/ 14( SPACE middle ) [ SPACE [ ":" ] trailing ]
nospcrlfcl = %x01-09 / %x0B-0C / %x0E-1F / %x21-39 / %x3B-FF
; any octet except NUL, CR, LF, " " and ":"
middle = nospcrlfcl *( ":" / nospcrlfcl )
trailing = *( ":" / " " / nospcrlfcl )
SPACE = %x20 ; space character
crlf = %x0D %x0A ; "carriage return" "linefeed"
*/
ctx.rule("message", ~Map(~LessThan(1, ~Literal(":") * ~Rule("prefix") * ~Rule("SPACE")) * ~Rule("command") * ~LessThan(1, ~Rule("params")), map_message));
ctx.rule("prefix", ~Map(~Rule("nickname") * ~LessThan(1, ~LessThan(1, ~Literal("!") * ~Rule("user")) * ~Literal("@") * ~Rule("host")), map_prefix) + ~Build(~Rule("servername"), build_serverprefix));
ctx.rule("command", ~Build(~MoreThan(1, ~Rule("letter")) + ~Exactly(3, ~Rule("digit")), build_unparsed));
ctx.rule("params", ~Map(~More(~Rule("SPACE") * ~Rule("middle")) * ~LessThan(1, ~Rule("SPACE") * ~Literal(":") * ~Rule("trailing"))
+ ~More(~Rule("SPACE") * ~Rule("middle")) * ~LessThan(1, ~Rule("SPACE") * ~LessThan(1, ~Literal(":")) * ~Rule("trailing")), map_params));
ctx.rule("nospcrlfcl", ~Diff(~Chars(1), ~Set("\x00\r\n :".iter().collect())));
ctx.rule("middle", ~Build(~Rule("nospcrlfcl") * ~More(~Literal(":") + ~Rule("nospcrlfcl")), build_unparsed));
ctx.rule("trailing", ~Build(~More(~Literal(":") + ~Literal(" ") + ~Rule("nospcrlfcl")), build_unparsed));
ctx.rule("SPACE", ~Map(~Literal(" "), map_ignored));
ctx.rule("crlf", ~Literal("\r\n"));
/*
target = nickname / server
msgtarget = msgto *( "," msgto )
msgto = channel / ( user [ "%" host ] "@" servername )
msgto =/ ( user "%" host ) / targetmask
msgto =/ nickname / ( nickname "!" user "@" host )
channel = ( "#" / "+" / ( "!" channelid ) / "&" ) chanstring
[ ":" chanstring ]
servername = hostname
host = hostname / hostaddr
hostname = shortname *( "." shortname )
shortname = ( letter / digit ) *( letter / digit / "-" )
*( letter / digit )
; as specified in RFC 1123 [HNAME]
hostaddr = ip4addr / ip6addr
ip4addr = 1*3digit "." 1*3digit "." 1*3digit "." 1*3digit
ip6addr = 1*hexdigit 7( ":" 1*hexdigit )
ip6addr =/ "0:0:0:0:0:" ( "0" / "FFFF" ) ":" ip4addr
nickname = ( letter / special ) *8( letter / digit / special / "-" )
targetmask = ( "$" / "#" ) mask
; see details on allowed masks in section 3.3.1
chanstring = %x01-07 / %x08-09 / %x0B-0C / %x0E-1F / %x21-2B
chanstring =/ %x2D-39 / %x3B-FF
; any octet except NUL, BELL, CR, LF, " ", "," and ":"
channelid = 5( %x41-5A / digit ) ; 5( A-Z / 0-9 )
*/
ctx.rule("servername", ~Rule("hostname"));
ctx.rule("host", ~Build(~Rule("hostname") + ~Rule("hostaddr"), build_unparsed));
ctx.rule("hostname", ~Rule("shortname") * ~More(~Literal(".") * ~Rule("shortname")));
ctx.rule("shortname", (~Rule("letter") + ~Rule("digit")) * ~More(~Rule("letter") + ~Rule("digit") + ~Literal("-")));
ctx.rule("hostaddr", ~Rule("ip4addr") + ~Rule("ip6addr"));
ctx.rule("ip4addr", ~Exactly(3, ~Rule("digit")) * ~Exactly(3, ~Exactly(3, ~Literal(".") * ~Rule("digit"))));
ctx.rule("ip6addr", ~Rule("hexdigit") * ~Exactly(7, ~Literal(":") * ~Rule("hexdigit"))
+ ~Literal("0:0:0:0:0:") * (~Literal("0") + ~Literal("FFFF")) * ~Literal(":") * ~Rule("ip4addr"));
ctx.rule("nickname", ~Build((~Rule("letter") + ~Rule("special")) * ~More(~Rule("letter") + ~Rule("digit") + ~Rule("special") + ~Literal("-")), build_unparsed));
/*
user = 1*( %x01-09 / %x0B-0C / %x0E-1F / %x21-3F / %x41-FF )
; any octet except NUL, CR, LF, " " and "@"
key = 1*23( %x01-05 / %x07-08 / %x0C / %x0E-1F / %x21-7F )
; any 7-bit US_ASCII character,
; except NUL, CR, LF, FF, h/v TABs, and " "
letter = %x41-5A / %x61-7A ; A-Z / a-z
digit = %x30-39 ; 0-9
hexdigit = digit / "A" / "B" / "C" / "D" / "E" / "F"
special = %x5B-60 / %x7B-7D
; "[", "]", "\", "`", "_", "^", "{", "|", "}"
*/
ctx.rule("user", ~Build(~MoreThan(1, ~Diff(~Chars(1), ~Set("\x00\r\n @".iter().collect()))), build_unparsed));
ctx.rule("letter", ~Range('a','z') + ~Range('A','Z'));
ctx.rule("digit", ~Range('0','9'));
ctx.rule("hexdigit", ~Rule("digit") + ~Range('A','F'));
ctx.rule("special", ~Set("[]\\`_^{|}".iter().collect()));
ctx
}
| 951
|
fn state_to_buf(state: &Engine) -> Vec<u8> {
serde_json::to_vec(state).unwrap()
}
| 952
|
fn execute(cmd: String, args: Vec<String>) -> Result<ExitStatus, Error> {
spawn(&cmd, &args, Stdio::inherit(), Stdio::inherit())
.map(|mut c| c.wait())?
}
| 953
|
fn disable_metrics_tracing_integration() {
std::env::set_var("DISABLE_INTERNAL_METRICS_TRACING_INTEGRATION", "true");
}
| 954
|
pub fn test_flat_crash_64() {
let buffer = fs::read("tests/programs/flat_crash_64").unwrap().into();
let core_machine =
DefaultCoreMachine::<u64, FlatMemory<u64>>::new(ISA_IMC, VERSION0, u64::max_value());
let mut machine = DefaultMachineBuilder::new(core_machine).build();
let result = machine.load_program(&buffer, &vec!["flat_crash_64".into()]);
assert_eq!(result.err(), Some(Error::MemOutOfBound));
}
| 955
|
fn perform_arithmetic(
lhs: CoreAddr,
rhs: CoreAddr,
inputs: &OpInputs,
) -> Option<EmulatorResult<CoreAddr>> {
// Performs an math modulo coresize, returning None only if division by zero
match inputs.regs.current.instr.opcode {
Opcode::Add => Some(offset(lhs, i64::from(rhs), inputs.core_size)),
Opcode::Sub => {
// offset() deals with negatives correctly
Some(offset(
lhs,
0_i64.checked_sub(i64::from(rhs))?,
inputs.core_size,
))
}
Opcode::Mul => {
let product = u64::from(lhs).checked_mul(u64::from(rhs));
let normalized = product
.and_then(|p| p.checked_rem(u64::from(inputs.core_size)))
.and_then(|e| u32::try_from(e).ok());
Some(normalized.ok_or(EmulatorError::InternalError(
"Impossible overflow when multiplying field values",
)))
}
Opcode::Div => (rhs != 0).then(|| {
lhs.checked_div(rhs).ok_or(EmulatorError::InternalError(
"Impossible division by zero",
))
}),
Opcode::Mod => (rhs != 0).then(|| {
lhs.checked_rem(rhs).ok_or(EmulatorError::InternalError(
"Impossible division by zero",
))
}),
_ => Some(Err(EmulatorError::InternalError(
"fn arithmetic_op should only be called with Add, Sub, Mul, Div, \
or Mod",
))),
}
}
| 956
|
pub fn djn_op(inputs: OpInputs) -> EmulatorResult<()> {
// DJN decrements the B-value and the B-target, then tests the B-value to
// determine if it is zero. If the decremented B-value is not zero, the
// sum of the program counter and the A-pointer is queued. Otherwise, the
// next instruction is queued (PC + 1). DJN.I functions as DJN.F would,
// i.e. it decrements both both A/B-numbers of the B-value and the
// B-target, and jumps if both A/B-numbers of the B-value are non-zero.
let a = inputs.regs.a;
let b = inputs.regs.b;
let size = inputs.core_size;
let decrement = |x| offset(x, -1, size);
let next_pc = offset(inputs.regs.current.idx, 1, inputs.core_size)?;
let war_id = inputs.warrior_id;
let modifier = inputs.regs.current.instr.modifier;
let Some(b_target) = inputs.core.get_mut(b.idx as usize) else {
return Err(EmulatorError::InternalError(
"attempt to write to invalid core index",
))
};
match modifier {
Modifier::A | Modifier::BA => {
// B value is the A-number of the B instruction
// decrement b target
let b_target_a = b_target.a_field;
let b_target_a = decrement(b_target_a)?;
b_target.a_field = b_target_a;
let non_zero = decrement(b.a_field)? != 0;
if non_zero {
inputs.pq.push_back(a.idx, war_id)?;
} else {
inputs.pq.push_back(next_pc, war_id)?;
}
}
Modifier::B | Modifier::AB => {
// B value is the B-number of the B instruction
// decrement b target
let b_target_b = b_target.b_field;
let b_target_b = decrement(b_target_b)?;
b_target.b_field = b_target_b;
let non_zero = decrement(b.b_field)? != 0;
if non_zero {
inputs.pq.push_back(a.idx, war_id)?;
} else {
inputs.pq.push_back(next_pc, war_id)?;
}
}
Modifier::F | Modifier::X | Modifier::I => {
// B value is the A and B numbers of the B instruction
// decrement b target
let b_target_a = b_target.a_field;
let b_target_a = decrement(b_target_a)?;
let b_target_b = b_target.b_field;
let b_target_b = decrement(b_target_b)?;
b_target.a_field = b_target_a;
b_target.b_field = b_target_b;
let non_zero =
decrement(b.a_field)? != 0 || decrement(b.b_field)? != 0;
if non_zero {
inputs.pq.push_back(a.idx, war_id)?;
} else {
inputs.pq.push_back(next_pc, war_id)?;
}
}
};
Ok(())
}
| 957
|
pub fn min_increment_for_unique(a: Vec<i32>) -> i32 {
let mut A = a;
A.sort_unstable();
let mut n = -1i32;
let mut ans = 0i32;
for &x in A.iter() {
if n < x {
n = x;
} else {
ans += n - x + 1;
n += 1;
}
}
ans
}
| 958
|
fn no_item() {
let dir = TestDir::new("sit", "no_item");
dir.cmd()
.arg("init")
.expect_success();
dir.cmd().args(&["reduce", "some-item"]).expect_failure();
}
| 959
|
fn test_deauthentication_packet() {
// Receiver address: Siemens_41:bd:6e (00:01:e3:41:bd:6e)
// Destination address: Siemens_41:bd:6e (00:01:e3:41:bd:6e)
// Transmitter address: NokiaDan_3d:aa:57 (00:16:bc:3d:aa:57)
// Source address: NokiaDan_3d:aa:57 (00:16:bc:3d:aa:57)
// BSS Id: Siemens_41:bd:6e (00:01:e3:41:bd:6e)
test_test_item(TestItem {
bytes: &DEAUTHENTICATION_PACKET,
subtype: Some(FrameSubtype::Management(
ManagementSubtype::Deauthentication,
)),
ds_status: Some(DSStatus::NotLeavingDSOrADHOC),
duration_id: Some(DurationID::Duration(258)),
receiver_address: "00:01:e3:41:bd:6e".parse().unwrap(),
destination_address: Some("00:01:e3:41:bd:6e".parse().unwrap()),
transmitter_address: Some("00:16:bc:3d:aa:57".parse().unwrap()),
source_address: Some("00:16:bc:3d:aa:57".parse().unwrap()),
bssid_address: Some("00:01:e3:41:bd:6e".parse().unwrap()),
fragment_number: Some(0),
sequence_number: Some(72),
..Default::default()
});
let frame = Frame::new(&DEAUTHENTICATION_PACKET[..]);
match match frame.next_layer().unwrap() {
FrameLayer::Management(ref management_frame) => management_frame.next_layer().unwrap(),
_ => unreachable!("not management"),
} {
ManagementFrameLayer::Deauthentication(ref deauthentication_frame) => {
// Reason code: Deauthenticated because sending STA is leaving (or has left) IBSS or ESS (0x0003)
assert_eq!(
deauthentication_frame.reason_code(),
ReasonCode::STALeavingIBSSOrESS,
"reason_code"
);
}
_ => unreachable!("not deauthentication"),
}
}
| 960
|
fn assert_memory_load_bytes_all<R: Rng>(
rng: &mut R,
max_memory: usize,
buf_size: usize,
addr: u64,
) {
assert_memory_load_bytes(
rng,
&mut SparseMemory::<u64>::new_with_memory(max_memory),
buf_size,
addr,
);
assert_memory_load_bytes(
rng,
&mut FlatMemory::<u64>::new_with_memory(max_memory),
buf_size,
addr,
);
assert_memory_load_bytes(
rng,
&mut WXorXMemory::new(FlatMemory::<u64>::new_with_memory(max_memory)),
buf_size,
addr,
);
#[cfg(has_asm)]
assert_memory_load_bytes(
rng,
&mut AsmCoreMachine::new(ISA_IMC, VERSION0, 200_000),
buf_size,
addr,
);
}
| 961
|
fn lz_string_uint8_array() {
compression_tests(
|s| {
lz_str::compress_to_uint8_array(s)
.into_iter()
.map(u16::from)
.collect::<Vec<u16>>()
.into()
},
|s| {
lz_str::decompress_from_uint8_array(
&s.0.into_iter().map(|el| el as u8).collect::<Vec<u8>>(),
)
.map(ByteString::from)
},
true,
);
}
| 962
|
const fn null_ble_gatt_svc_def() -> ble_gatt_svc_def {
return ble_gatt_svc_def {
type_: BLE_GATT_SVC_TYPE_END as u8,
uuid: ptr::null(),
includes: ptr::null_mut(),
characteristics: ptr::null(),
};
}
| 963
|
pub fn get_main_keyboard_shortcuts(config: &AxessConfiguration) -> Vec<KeyboardShortcut> {
let mut s = vec![
KeyboardShortcut {
key: KeyboardShortcutKey::Key(Keys::Enter),
command_description: "Select the preset or scene".into(),
command: ShortcutCommand::SelectPresetOrScene
}
];
if config.keyboard_shortcuts_axe_edit {
s.push(KeyboardShortcut {
key: KeyboardShortcutKey::CtrlKey(Keys::PageUp),
command_description: "Preset Up".into(),
command: ShortcutCommand::UiPayload(UiPayload::DeviceState(DeviceState::DeltaPreset { delta: 1 }))
});
s.push(KeyboardShortcut {
key: KeyboardShortcutKey::CtrlKey(Keys::PageDown),
command_description: "Preset Down".into(),
command: ShortcutCommand::UiPayload(UiPayload::DeviceState(DeviceState::DeltaPreset { delta: -1 }))
});
for i in 0..8 {
let key = Keys::from_primitive(Keys::Number1.to_primitive() + i);
if let Some(key) = key {
s.push(KeyboardShortcut {
key: KeyboardShortcutKey::CtrlKey(key),
command_description: format!("Select Scene {}", i + 1).into(),
command: ShortcutCommand::UiPayload(UiPayload::DeviceState(DeviceState::SetScene { scene: i }))
});
}
}
}
if config.keyboard_shortcuts_presets_and_scenes_function_keys {
for i in 0..8 {
let key = Keys::from_primitive(Keys::Fn1.to_primitive() + i);
if let Some(key) = key {
s.push(KeyboardShortcut {
key: KeyboardShortcutKey::Key(key),
command_description: format!("Select Scene {}", i + 1).into(),
command: ShortcutCommand::UiPayload(UiPayload::DeviceState(DeviceState::SetScene { scene: i }))
});
}
}
s.push(KeyboardShortcut {
key: KeyboardShortcutKey::Key(Keys::Fn11),
command_description: "Preset Down".into(),
command: ShortcutCommand::UiPayload(UiPayload::DeviceState(DeviceState::DeltaPreset { delta: -1 }))
});
s.push(KeyboardShortcut {
key: KeyboardShortcutKey::Key(Keys::Fn12),
command_description: "Preset Up".into(),
command: ShortcutCommand::UiPayload(UiPayload::DeviceState(DeviceState::DeltaPreset { delta: 1 }))
});
}
s
}
| 964
|
fn test_file() {
use std::env;
let mut dir = env::temp_dir();
dir.push("t_rex_test");
let basepath = format!("{}", &dir.display());
fs::remove_dir_all(&basepath);
let cache = Filecache { basepath: basepath };
assert_eq!(cache.dir("tileset", 1, 2, 0), format!("{}/{}", cache.basepath, "tileset/0/1"));
let pbf = format!("{}/{}", cache.basepath, "tileset/0/1/2.pbf");
assert_eq!(cache.path("tileset", 1, 2, 0), pbf);
// Cache miss
assert!(cache.lookup("tileset", 1, 2, 0, |_| Ok(())).is_err());
// Write into cache
let res = cache.store("tileset", 1, 2, 0, |f| {
f.write_all("0123456789".as_bytes())
});
assert_eq!(res.ok(), Some(()));
assert!(Path::new(&pbf).exists());
// Cache hit
assert!(cache.lookup("tileset", 1, 2, 0, |_| Ok(())).is_ok());
// Read from cache
let mut s = String::new();
cache.lookup("tileset", 1, 2, 0, |f| {
f.read_to_string(&mut s).map(|_| ())
});
assert_eq!(&s, "0123456789");
}
| 965
|
pub fn force_reset() -> Result<(), ()> {
let mut configurator = Configurator::new();
configurator.force_reset();
Ok(())
}
| 966
|
async fn http_lookup(url: &Url) -> Result<Graph, Berr> {
let resp = reqwest::get(url.as_str()).await?;
if !resp.status().is_success() {
return Err("unsucsessful GET".into());
}
let content_type = resp
.headers()
.get(CONTENT_TYPE)
.ok_or("no content-type header in response")?
.to_str()?
.to_string();
let bytes = resp.bytes().await?;
into_rdf(&bytes, &content_type).map_err(Into::into)
}
| 967
|
fn main() {
println!("Hello, Fizz Buzz!");
const NUMBER: i32 = 35;
let fizz_buzz_result = fizz_buzz(NUMBER);
println!("Fizz Buzz for number {} is: {:?}", NUMBER, fizz_buzz_result);
}
| 968
|
pub extern "x86-interrupt" fn keyboard() { KeyboardHandler(33); }
| 969
|
unsafe
fn
atomic_store
<
T
>
(
dst
:
*
mut
T
val
:
T
)
{
atomic
!
{
T
a
{
a
=
&
*
(
dst
as
*
const
_
as
*
const
_
)
;
a
.
store
(
mem
:
:
transmute_copy
(
&
val
)
Ordering
:
:
Release
)
;
mem
:
:
forget
(
val
)
;
}
{
let
_guard
=
lock
(
dst
as
usize
)
.
write
(
)
;
ptr
:
:
write
(
dst
val
)
;
}
}
}
| 970
|
extern fn QScroller_scrollerPropertiesChanged_signal_connect_cb_box_0(rsfptr_raw:*mut Box<Fn(QScrollerProperties)>, arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = QScrollerProperties::inheritFrom(arg0 as u64);
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
| 971
|
pub fn acrn_remove_file(path: &str) -> Result<(), String> {
fs::remove_file(path).map_err(|e| e.to_string())
}
| 972
|
fn item_named_user_query() {
let dir = TestDir::new("sit", "named_user_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 cfg = r#"{"items": {"queries": {"q1": "join(' ', ['item', id, value])"}}}"#;
user_config(&dir, cfg);
let output = String::from_utf8(dir.cmd()
.env("HOME", dir.path(".").to_str().unwrap())
.env("USERPROFILE", dir.path(".").to_str().unwrap())
.args(&["reduce", id.trim(), "-Q", "q1"]).expect_success().stdout).unwrap();
assert_eq!(output.trim(), format!("item {} hello", id.trim()));
}
| 973
|
fn main() -> ! {
let mut robot = init_peripherals(
stm32f446::Peripherals::take().unwrap(),
cortex_m::Peripherals::take().unwrap(),
);
init_servo(&mut robot);
let mut reader = TrameReader::new();
loop {
let b = block!(robot.pc_rx.read()).unwrap();
reader.step(b);
if let Some(trame) = reader.pop_trame() {
asm::bkpt();
}
/*
let mess = servos[0x05].stat();
for b in mess {
block!(robot.servo_tx.write(b)).unwrap();
}
robot.delay.delay_ms(70 as u16);
*/
/*
if let Ok(byte) = pc_rx.read() {
reader.step(byte);
}
if let Some(trame) = reader.pop_trame() {
if let Some(sent) = handle_trame(trame) {
let (arr, size): ([u8; 15], usize) = sent.into();
for b in arr[0..size].iter() {
block!(pc_tx.write(*b)).unwrap();
}
}
}*/
}
}
| 974
|
const
fn
atomic_is_lock_free
<
T
>
(
)
-
>
bool
{
let
is_lock_free
=
can_transmute
:
:
<
T
AtomicUnit
>
(
)
|
can_transmute
:
:
<
T
atomic
:
:
AtomicU8
>
(
)
|
can_transmute
:
:
<
T
atomic
:
:
AtomicU16
>
(
)
|
can_transmute
:
:
<
T
atomic
:
:
AtomicU32
>
(
)
;
#
[
cfg
(
not
(
crossbeam_no_atomic_64
)
)
]
let
is_lock_free
=
is_lock_free
|
can_transmute
:
:
<
T
atomic
:
:
AtomicU64
>
(
)
;
is_lock_free
}
| 975
|
pub fn validate_file(args: &Vec<String>) -> Result<Box<&Path>, KataError> {
if args.len() < 2 {
Err(KataError::new("Not enough arguments! Missing filename."))
} else {
let file_name = Path::new(&args[1]);
if file_name.exists() {
Ok(Box::new(file_name))
} else {
Err(KataError::new("Path does not exist!"))
}
}
}
| 976
|
pub(crate) fn assignment_with_rescue_modifier(i: Input) -> NodeResult {
map(
tuple((
left_hand_side,
no_lt,
char('='),
ws0,
operator_expression,
no_lt,
tag("rescue"),
ws0,
operator_expression,
)),
|_| Node::Placeholder,
)(i)
}
| 977
|
pub extern "x86-interrupt" fn serial_2() { CommonInterruptHandler(35); }
| 978
|
fn figure1b_pct_with_many_tasks() {
// Spawn 18 busy threads, each taking 5 steps, plus 2 main threads with 10 steps, so k=110
// n=50, k=110, d=2, so probability of finding the bug in one iteration is at least 1/(20*110)
// So probability of hitting the bug in 16_000 iterations = 1 - (1 - 1/2200)^16_000 > 99.9%
let scheduler = PctScheduler::new(2, 16_000);
let runner = Runner::new(scheduler, Default::default());
runner.run(|| {
figure1b(20);
});
}
| 979
|
pub fn init(title: &str) -> System {
let title = match title.rfind('/') {
Some(idx) => title.split_at(idx + 1).1,
None => title,
};
let events_loop = glutin::EventsLoop::new();
let builder = glutin::WindowBuilder::new()
.with_title(title.to_owned())
.with_dimensions(glutin::dpi::LogicalSize::new(1024f64, 768f64));
let mut imgui = Context::create();
imgui.set_ini_filename(None);
let mut platform = WinitPlatform::init(&mut imgui);
let hidpi_factor = platform.hidpi_factor();
let font_size = (13.0 * hidpi_factor) as f32;
imgui.fonts().add_font(&[
FontSource::DefaultFontData {
config: Some(FontConfig {
size_pixels: font_size,
..FontConfig::default()
}),
},
FontSource::TtfData {
data: include_bytes!("../../../resources/mplus-1p-regular.ttf"),
size_pixels: font_size,
config: Some(FontConfig {
rasterizer_multiply: 1.75,
glyph_ranges: FontGlyphRanges::japanese(),
..FontConfig::default()
}),
},
]);
imgui.io_mut().font_global_scale = (1.0 / hidpi_factor) as f32;
let render_sys = RenderSystem::init(&mut imgui, builder, &events_loop);
platform.attach_window(imgui.io_mut(), render_sys.window(), HiDpiMode::Rounded);
System {
events_loop,
imgui,
platform,
render_sys,
font_size,
}
}
| 980
|
async fn init() -> Result<Args> {
let mut log_on = false;
#[cfg(feature = "dev-console")]
match console_subscriber::try_init() {
Ok(_) => {
warn!("dev-console enabled");
log_on = true;
}
Err(e) => {
eprintln!("Failed to initialise tokio console, falling back to normal logging\n{e}")
}
}
if !log_on && var("RUST_LOG").is_ok() {
match tracing_subscriber::fmt::try_init() {
Ok(_) => {
warn!(RUST_LOG=%var("RUST_LOG").unwrap(), "logging configured from RUST_LOG");
log_on = true;
}
Err(e) => eprintln!("Failed to initialise logging with RUST_LOG, falling back\n{e}"),
}
}
let args = args::get_args();
let verbosity = args.verbose.unwrap_or(0);
if log_on {
warn!("ignoring logging options from args");
} else if verbosity > 0 {
let log_file = if let Some(file) = &args.log_file {
let is_dir = metadata(&file).await.map_or(false, |info| info.is_dir());
let path = if is_dir {
let filename = format!(
"watchexec.{}.log",
chrono::Utc::now().format("%Y-%m-%dT%H-%M-%SZ")
);
file.join(filename)
} else {
file.to_owned()
};
// TODO: use tracing-appender instead
Some(File::create(path).into_diagnostic()?)
} else {
None
};
let mut builder = tracing_subscriber::fmt().with_env_filter(match verbosity {
0 => unreachable!("checked by if earlier"),
1 => "warn",
2 => "info",
3 => "debug",
_ => "trace",
});
if verbosity > 2 {
use tracing_subscriber::fmt::format::FmtSpan;
builder = builder.with_span_events(FmtSpan::NEW | FmtSpan::CLOSE);
}
match if let Some(writer) = log_file {
builder.json().with_writer(Mutex::new(writer)).try_init()
} else if verbosity > 3 {
builder.pretty().try_init()
} else {
builder.try_init()
} {
Ok(_) => info!("logging initialised"),
Err(e) => eprintln!("Failed to initialise logging, continuing with none\n{e}"),
}
}
Ok(args)
}
| 981
|
pub fn write_value<W>(wr: &mut W, val: &Value) -> Result<(), Error>
where W: Write
{
match val {
&Value::Nil => try!(write_nil(wr)),
&Value::Boolean(val) => try!(write_bool(wr, val)),
// TODO: Replace with generic write_int(...).
&Value::Integer(Integer::U64(val)) => {
try!(write_uint(wr, val));
}
&Value::Integer(Integer::I64(val)) => {
try!(write_sint(wr, val));
}
// TODO: Replace with generic write_float(...).
&Value::Float(Float::F32(val)) => try!(write_f32(wr, val)),
&Value::Float(Float::F64(val)) => try!(write_f64(wr, val)),
&Value::String(ref val) => {
try!(write_str(wr, &val));
}
&Value::Binary(ref val) => {
try!(write_bin(wr, &val));
}
&Value::Array(ref val) => {
try!(write_array_len(wr, val.len() as u32));
for item in val {
try!(write_value(wr, item));
}
}
&Value::Map(ref val) => {
try!(write_map_len(wr, val.len() as u32));
for &(ref key, ref val) in val {
try!(write_value(wr, key));
try!(write_value(wr, val));
}
}
&Value::Ext(ty, ref data) => {
try!(write_ext_meta(wr, data.len() as u32, ty));
try!(wr.write_all(data).map_err(|err| ValueWriteError::InvalidDataWrite(WriteError(err))));
}
}
Ok(())
}
| 982
|
fn main_loop(main_sender: MailSender<GlobalEvent>, main_receiver: MailReceiver<GlobalEvent>) -> ! {
let state = GlobalState::new();
let mut store = Store::new(
state,
|state| {
let mut charlie_leds = CHARLIE_LEDS.lock().unwrap();
charlie_leds.set_leds([
state.s_led[0],
state.s_led[1],
state.s_led[2],
state.s_led[3],
state.s_led[4],
state.s_led[5],
state.s_led[6],
state.s_led[7],
state.run_led,
]);
},
);
// TODO maybe fuse first call with Store::new?
store.force_update();
store.handle_events(main_sender, main_receiver);
}
| 983
|
pub fn do_souper_harvest(func: &ir::Function, out: &mut mpsc::Sender<String>) {
let mut allocs = Allocs::default();
// Iterate over each instruction in each block and try and harvest a
// left-hand side from its result.
for block in func.layout.blocks() {
let mut option_inst = func.layout.first_inst(block);
while let Some(inst) = option_inst {
let results = func.dfg.inst_results(inst);
if results.len() == 1 {
let val = results[0];
let ty = func.dfg.value_type(val);
if ty.is_int() && ty.lane_count() == 1 {
harvest_candidate_lhs(&mut allocs, func, val, out);
}
}
option_inst = func.layout.next_inst(inst);
}
}
}
| 984
|
pub fn challenge_5() {
let input = "Burning 'em, if you ain't quick and nimble\nI go crazy when I hear a cymbal";
let out = crypto::xor_repeating(&input.as_bytes().to_vec(), &"ICE".as_bytes().to_vec());
let out_str = hex::encode(out);
println!("{}", out_str);
}
| 985
|
pub fn brackets_are_balanced(string: &str) -> bool {
let mut brackets = vec![];
for char in string.chars() {
match char {
'(' => brackets.push(char),
'[' => brackets.push(char),
'{' => brackets.push(char),
'}' => {
if brackets.len() == 0 {
return false;
}
let top = brackets.last().unwrap();
if *top == '{' {
brackets.pop();
} else {
return false;
}
}
']' => {
if brackets.len() == 0 {
return false;
}
let top = brackets.last().unwrap();
if *top == '[' {
brackets.pop();
} else {
return false;
}
}
')' => {
if brackets.len() == 0 {
return false;
}
let top = brackets.last().unwrap();
if *top == '(' {
brackets.pop();
} else {
return false;
}
}
_ => (),
}
}
brackets.len() == 0
}
| 986
|
fn app_installer_dir(settings: &Settings) -> crate::Result<PathBuf> {
let arch = match settings.binary_arch() {
"x86" => "x86",
"x86_64" => "x64",
target => {
return Err(crate::Error::ArchError(format!(
"Unsupported architecture: {}",
target
)))
}
};
let package_base_name = format!(
"{}_{}_{}",
settings.main_binary_name().replace(".exe", ""),
settings.version_string(),
arch
);
Ok(
settings
.project_out_directory()
.to_path_buf()
.join(format!("bundle/msi/{}.msi", package_base_name)),
)
}
| 987
|
async fn server(url: &str) -> Result<!, String> {
let server = TcpServer::bind(url).await.map_err(|e| e.to_string())?;
let (op_reads, op_writes) = TcpServerOp::<RequestLatRepr>::new(server.clone())
// .debug("ingress")
.morphism_closure(|item| item.flatten_keyed::<tag::VEC>())
.morphism(Switch)
// .debug("split")
.switch();
type ReadsLatRepr = MapUnionRepr<tag::HASH_MAP, String, SetUnionRepr<tag::HASH_SET, SocketAddr>>;
let op_reads = op_reads
// .debug("read")
.lattice_default::<ReadsLatRepr>();
type WritesLatRepr = MapUnionRepr<tag::HASH_MAP, String, ValueLatRepr>;
let op_writes = op_writes
// .debug("write")
.lattice_default::<WritesLatRepr>();
let binary_func = HashPartitioned::<String, _>::new(
TableProduct::<_, _, _, MapUnionRepr<tag::VEC, _, _>>::new());
let comp = BinaryOp::new(op_reads, op_writes, binary_func)
.morphism_closure(|item| item.transpose::<tag::VEC, tag::VEC>())
.comp_tcp_server::<ResponseLatRepr, _>(server);
comp
.run()
.await
.map_err(|e| format!("TcpComp error: {:?}", e))?;
}
| 988
|
pub fn collect_events(events_loop: &mut EventsLoop) -> Vec<Event> {
let mut events = Vec::<Event>::new();
events_loop.poll_events(|event| events.push(event));
events
}
| 989
|
pub async fn client_async_tls_with_config<R, S>(
request: R,
stream: S,
config: Option<WebSocketConfig>,
) -> Result<(WebSocketStream<ClientStream<S>>, Response), Error>
where
R: IntoClientRequest + Unpin,
S: 'static + tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin,
AutoStream<S>: Unpin,
{
client_async_tls_with_connector_and_config(request, stream, None, config).await
}
| 990
|
pub fn test_memory_store_empty_bytes() {
assert_memory_store_empty_bytes(&mut FlatMemory::<u64>::default());
assert_memory_store_empty_bytes(&mut SparseMemory::<u64>::default());
assert_memory_store_empty_bytes(&mut WXorXMemory::<FlatMemory<u64>>::default());
#[cfg(has_asm)]
assert_memory_store_empty_bytes(&mut AsmCoreMachine::new(ISA_IMC, VERSION0, 200_000));
}
| 991
|
fn default_or(key: &str, default_value: f64, ctx: &mut Context) -> Decimal {
let property = ctx.widget().clone_or_default(key);
match Decimal::from_f64(property) {
Some(val) => val,
None => Decimal::from_f64(default_value).unwrap(),
}
}
| 992
|
fn a_table_should_read_0_for_any_key() {
let mut table = HashMapOfTreeMap::new();
let mut vs = [Value::default(); 1];
table.read (0, &[0], &mut vs);
match vs {
[Value { v: 0, t: 0}] => (),
_ => assert!(false)
}
}
| 993
|
fn list() -> Receiver<i32, u32> {
let (tx, rx) = channel();
tx.send(Ok(1))
.and_then(|tx| tx.send(Ok(2)))
.and_then(|tx| tx.send(Ok(3)))
.forget();
return rx
}
| 994
|
pub fn write_u64<W>(wr: &mut W, val: u64) -> Result<(), ValueWriteError>
where W: Write
{
try!(write_marker(wr, Marker::U64));
write_data_u64(wr, val)
}
| 995
|
pub extern fn pktproc_process(thread_id: u64, packets: *mut *mut libc::c_void, count: u32) {
CONTEXT.with(|ref context| {
if let Some(ref ctx) = *context.borrow() {
assert_eq!(ctx.thread_id, thread_id);
let pkts: &mut [&mut Packet] = unsafe {
mem::transmute(slice::from_raw_parts_mut(packets, count as usize))
};
for p in pkts {
let mut result = -1i32;
{
let ethh = EthernetPacket::from_packet(p);
if ethh.dst_mac[0] & 0x01 == 0 { // if unicast address
ethh.dst_mac = ethh.src_mac;
ethh.src_mac = ctx.installed_ports[p.port as usize].mac_addr;
result = p.port as i32
}
}
(*p).result = result;
}
};
});
}
| 996
|
pub fn string_compose(parts: Node) -> Node {
if is_collapse_string_parts(&parts) {}
// TODO DUMMY
if let Node::Str(string_value) = parts { return Node::Str(string_value); }
if let Node::Nodes(str_nodes) = parts {
if let Node::Str(str_value) = (*str_nodes.get(0).unwrap()).clone() {
return Node::Str(str_value);
}
}
panic!("string_compose UNIMPL");
}
| 997
|
fn main() {
aoc_main(part1, part2);
}
| 998
|
pub fn bubble_sort<T: PartialOrd + Debug>(v: &mut [T]) {
for p in 0..v.len() {
// println!("{:?}", v);
let mut sorted = true;
for i in 0..(v.len()-1) - p{
if v[i] > v[i+1] {
v.swap(i, i+1);
sorted = false;
}
}
if sorted {
return;
}
}
}
| 999
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.