content stringlengths 12 12.8k | id int64 0 359 |
|---|---|
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);
... | 200 |
fn default_handler(irqn: i16) {
panic!("Unhandled exception (IRQn = {})", irqn);
} | 201 |
pub fn number(n: i64) -> Value {
Rc::new(RefCell::new(V {
val: Value_::Number(n),
computed: true,
}))
} | 202 |
fn init_finds_parent_project() {
let project = project("init_finds_parent_project").build();
project
.cargo_fuzz()
.current_dir(project.root().join("src"))
.arg("init")
.assert()
.success();
assert!(project.fuzz_dir().is_dir());
assert!(project.fuzz_cargo_toml().i... | 203 |
fn build_dev() {
let project = project("build_dev").with_fuzz().build();
// Create some targets.
project
.cargo_fuzz()
.arg("add")
.arg("build_dev_a")
.assert()
.success();
project
.cargo_fuzz()
.arg("add")
.arg("build_dev_b")
.ass... | 204 |
fn main() {
if env::args().len() != 2 {
panic!("Incorrect number of arguments provided\n");
}
let input = BufReader::new(File::open(env::args().nth(1).unwrap()).unwrap());
let mut cols: Vec<BTreeMap<char, i32>> = vec![];
for line in input.lines() {
for (i, c) in line.unwrap().char... | 205 |
pub fn star2(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 mut max_guard_asleep_per_minute = vec![(0, None); 60];
for &guard... | 206 |
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!("... | 207 |
fn is_aligned(value: usize, alignment: usize) -> bool {
(value & (alignment - 1)) == 0
} | 208 |
pub fn test_nop() {
let buffer = fs::read("tests/programs/nop").unwrap().into();
let result = run::<u32, SparseMemory<u32>>(&buffer, &vec!["nop".into()]);
assert!(result.is_ok());
assert_eq!(result.unwrap(), 0);
} | 209 |
pub fn parse(raw: &str) -> Option<game::Game> {
let game_raw: GameRaw = serde_json::from_str(raw).ok()?;
let even_initial_timelines = game_raw
.timelines
.iter()
.any(|tl| tl.index == -0.5 || tl.index == 0.5);
let min_timeline = game_raw.timelines
.iter()
.map(|tl| ... | 210 |
fn desearlizer_client(req: &mut reqwest::Response) -> Result<Client, 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 s... | 211 |
pub fn retype_task(source: CAddr, target: CAddr) {
system_call(SystemCall::RetypeTask {
request: (source, target),
});
} | 212 |
pub fn task_set_cpool(target: CAddr, cpool: CAddr) {
system_call(SystemCall::TaskSetCPool {
request: (target, cpool),
});
} | 213 |
fn create_mesh_buffer_verts(
chunk: &Chunk,
device: &wgpu::Device,
queue: &wgpu::Queue,
) -> MeshBufferVerts {
// Calculate total length of buffer e.g. a full chunk of different voxels. This way a new buffer only has to be created when the voxel capacity is changed.
let verts = Mesh::verts(chunk);
... | 214 |
fn part2(rules: &Vec<PasswordRule>) -> usize {
rules
.iter()
.filter(|rule| {
let first = if let Some(c) = rule.password.chars().nth(rule.min - 1) {
c == rule.letter
} else {
false
};
let second = if let Some(c) = rule.... | 215 |
fn main() {
let re_top = Regex::new(r" {4}|\[([A-Z])\]").unwrap();
let re_action = Regex::new(r"move (\d+) from (\d+) to (\d+)").unwrap();
let mut stacks: Vec<Vec<char>> = Vec::new();
let mut input = io::stdin().lock().lines()
.flat_map(|l| l.ok());
for line in &mut input {
if line... | 216 |
fn rc_test() {
use std::rc::Rc;
let s: Rc<String> = Rc::new("shirataki".to_string());
let t: Rc<String> = s.clone();
let u: Rc<String> = s.clone();
assert!(s.contains("shira"));
assert_eq!(t.find("taki"), Some(5));
println!("{} are quite chewy, almost bouncy, but lack flavor", u);
// ... | 217 |
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());
... | 218 |
fn build_stripping_dead_code() {
let project = project("build_strip").with_fuzz().build();
// Create some targets.
project
.cargo_fuzz()
.arg("add")
.arg("build_strip_a")
.assert()
.success();
project
.cargo_fuzz()
.arg("build")
.arg("--s... | 219 |
pub fn task_set_top_page_table(target: CAddr, table: CAddr) {
system_call(SystemCall::TaskSetTopPageTable {
request: (target, table),
});
} | 220 |
fn app() -> App<
impl ServiceFactory<
ServiceRequest,
Response = ServiceResponse<impl MessageBody>,
Config = (),
InitError = (),
Error = Error,
>,
> {
App::new()
} | 221 |
pub fn set_working_folder(working_folder: String) -> Result<(), ()> {
unsafe {
WORKING_FOLDER = working_folder;
}
Ok(())
} | 222 |
fn set_privilege(handle: HANDLE, name: &str) -> Result<(), std::io::Error> {
let mut luid: LUID = LUID {
LowPart: 0,
HighPart: 0,
};
let name: U16CString = name.try_into().unwrap();
let r = unsafe {LookupPrivilegeValueW(std::ptr::null(),name.as_ptr(), &mut luid )};
if r == 0 {
... | 223 |
pub fn get_home() -> Result<String, ()> {
match dirs::home_dir() {
None => Ok(String::new()),
Some(path) => Ok(path.to_str().unwrap().to_string()),
}
} | 224 |
fn input(user_message: &str) -> io::Result<String> {
use std::io::Write;
print!("{}", user_message);
io::stdout().flush()?;
let mut buffer: String = String::new();
io::stdin().read_line(&mut buffer)?;
Ok(buffer.trim_right().to_owned())
} | 225 |
fn get_versions(repo: &Repository) -> Result<Vec<VersionTag>, Box<dyn std::error::Error>> {
let tags = repo
.tag_names(None)?
.into_iter()
.filter_map(|v| v)
.map(|v| v.to_owned())
.collect::<Vec<_>>();
let mut versions = tags
.iter()
.filter_map(|tag| {
... | 226 |
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_milli... | 227 |
pub fn solve(input: &str) -> Option<Box<usize>> {
let sum_of_counts = input
.trim_end()
.split("\n\n")
.map(|group| group.chars().filter(|ch| *ch != '\n').collect::<HashSet<_>>().len())
.sum();
Some(Box::new(sum_of_counts))
} | 228 |
fn channel_take_nonpayload(target: CAddr) -> ChannelMessage {
let result = system_call(SystemCall::ChannelTake {
request: target,
response: None
});
match result {
SystemCall::ChannelTake {
response, ..
} => {
return response.unwrap()
},
... | 229 |
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_... | 230 |
pub fn get_driver(url: &str) -> MigrateResult<Box<Driver>> {
// Mysql driver does not allow to connect using a url so we need to parse it
let mut parser = UrlParser::new();
parser.scheme_type_mapper(db_scheme_type_mapper);
let parsed = parser.parse(url).unwrap();
match parsed.scheme.as_ref() {
... | 231 |
fn main() {
let mut build = cc::Build::new();
build.include("Vulkan-Headers/include");
build.include("VulkanMemoryAllocator/include");
build.file("vma.cpp");
let target = env::var("TARGET").unwrap();
if target.contains("darwin") {
build
.flag("-std=c++17")
.flag... | 232 |
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()
} | 233 |
fn list_migration_directories_with_an_empty_migrations_folder_works(api: TestApi) {
let migrations_directory = api.create_migrations_directory();
api.list_migration_directories(&migrations_directory)
.send()
.assert_listed_directories(&[]);
} | 234 |
fn print_expression(prefix: &str, exp: &IRExpression) {
let next_prefix = format!("{} ", prefix);
match exp {
&IRExpression::Value(ref value) => {
println!("{}Value: '{:?}'", prefix, value);
}
&IRExpression::Variable(ref name) => {
println!("{}Variable: '{:?}'", ... | 235 |
pub fn write_file(path: PathBuf, content: String) -> Result<(), String> {
fs::write(path, content).map_err(|e| e.to_string())
} | 236 |
pub(crate) fn run(args: &ArgMatches) -> AppResult<()> {
let tap_info = create_tap()?;
let data_sock = create_data_sock()?;
let is_auto = args.is_present("auto");
// init peers from args
let init_peers = match args.value_of("peers") {
Some(peers_str) => parse_peers_str(peers_str)?,
N... | 237 |
fn broker(table: &mut Table, ntransfers: u32) {
let mut rng = thread_rng();
let mut ract = Range::new(0, 100);
let mut ramt = Range::new(0, 1000);
let mut nstale = 0;
for _ in 0..ntransfers {
let a1 = ract.sample(&mut rng);
let mut a2 = ract.sample(&mut rng);
while a2 == a1 {
a2 = ract.sam... | 238 |
fn mailmap_from_repo(repo: &git2::Repository) -> Result<Mailmap, Box<dyn std::error::Error>> {
let file = String::from_utf8(
repo.revparse_single("master")?
.peel_to_commit()?
.tree()?
.get_name(".mailmap")
.unwrap()
.to_object(&repo)?
... | 239 |
fn build_serverprefix(s: ~str) -> Result<IRCToken, ~str> {
Ok(PrefixT(Prefix {nick: s, user: ~"", host: ~""}))
} | 240 |
pub fn pretty_print(ir: &std::collections::HashMap<String, IRFunction>) {
for (_, func) in ir {
println!("Function-'{}':", func.name);
println!(" Arguments:");
for param in func.parameters.iter() {
println!(" {}: {:?}", param.name, param.param_type);
}
for sta... | 241 |
pub fn acrn_is_file(path: &str) -> bool {
fs::metadata(path)
.map(|metadata| metadata.is_file())
.unwrap_or(false)
} | 242 |
async fn main() -> tide::Result<()> {
let contents = get_config("~/data/british-english").await?;
let mut app = tide::new();
app.at("/orders/shoes").post(order_shoes);
app.listen("127.0.0.1:8080").await?;
Ok(())
} | 243 |
fn main() {
// let name = String::from("rust");
let mut client = Client::new();
// now loop forever getting tasks every now and then
let duration = (&client.interval * 1000.0) as u64;
let sleep_duration = time::Duration::from_millis(duration);
let (channel_out, channel_in) = unbounded();
... | 244 |
fn run_no_crash() {
let project = project("run_no_crash")
.with_fuzz()
.fuzz_target(
"no_crash",
r#"
#![no_main]
use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: &[u8]| {
#[cfg(fuzzing_repro)]
... | 245 |
fn debug_check_layout(layout: Layout) {
debug_assert!(layout.size() <= LARGEST_POWER_OF_TWO);
debug_assert!(layout.size() > 0);
} | 246 |
fn main() {
println!("Common letters in the box ids: {}",
match find_common_id() {
Some(s) => s,
None => "NA".to_string()
});
} | 247 |
fn openssl_dir() -> Result<String, FrumError> {
#[cfg(target_os = "macos")]
return Ok(String::from_utf8_lossy(
&Command::new("brew")
.arg("--prefix")
.arg("openssl")
.output()
.map_err(FrumError::IoError)?
.stdout,
)
.trim()
.to_str... | 248 |
fn initialize(lines: &Vec<String>) -> Vec<Day> {
let regex = Regex::new(r"(\d\d-\d\d) ((?:23|00):\d\d)\] (Guard #(\d*)|wakes|falls)").expect("Building Regex failed");
let mut events = lines.iter().map(|l| GuardEvent::from_line(l, ®ex)).collect::<Vec<GuardEvent>>();
events.sort_by(|GuardEvent {date: date1... | 249 |
pub fn debug_log(msg: impl AsRef<str>) {
let msg = msg.as_ref();
eprintln!("{} - {}", Local::now().format("%Y%m%d %H:%M:%S"), msg);
} | 250 |
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 ... | 251 |
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... | 252 |
fn
test_option
(
)
-
>
Result
<
(
)
>
{
let
db
=
checked_memory_handle
(
)
?
;
let
s
=
Some
(
"
hello
world
!
"
)
;
let
b
=
Some
(
vec
!
[
1u8
2
3
4
]
)
;
db
.
execute
(
"
INSERT
INTO
foo
(
t
)
VALUES
(
?
1
)
"
[
&
s
]
)
?
;
db
.
execute
(
"
INSERT
INTO
foo
(
b
)
VALUES
(
?
1
)
"
[
&
b
]
)
?
;
let
mut
stmt
=
db
.
prepa... | 253 |
fn main() {
let input1 = vec![1,2,5];
let sol = Solution::coin_change(input1, 11);
println!("Result: {}, Expected: 3", sol);
} | 254 |
fn print_fixed_acc(inss: &[Instruction], op: Operation, pc: usize) -> bool {
let mut fixed_inss = inss.to_vec();
fixed_inss[pc].op = op;
match Evaluator::new(&mut fixed_inss).eval_until_loop() {
(final_pc, final_acc, _) if final_pc == fixed_inss.len() => {
println!("{}", final_acc);
... | 255 |
fn list() {
let project = project("add").with_fuzz().build();
// Create some targets.
project.cargo_fuzz().arg("add").arg("c").assert().success();
project.cargo_fuzz().arg("add").arg("b").assert().success();
project.cargo_fuzz().arg("add").arg("a").assert().success();
// Make sure that we can ... | 256 |
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();
... | 257 |
fn main() {
let argv = os::args();
let size = from_str::<uint>(argv[1]).unwrap();
// println!("{}",size);
let align = from_str::<uint>(argv[2]).unwrap();
// println!("{}", align);
let aligned = align_to(size,align);
println!("{} by {} = {}", size, align, aligned);
// print_uint(*argv[1]);
} | 258 |
pub fn retype_raw_page_free(source: CAddr) -> CAddr {
let result = system_call(SystemCall::RetypeRawPageFree {
request: source,
response: None
});
match result {
SystemCall::RetypeRawPageFree {
response, ..
} => { return response.unwrap(); },
_ => panic!()... | 259 |
fn active_entity(entity: Entity, world: &World) -> bool {
return world.masks[entity] & VOXEL_PASS_MASK == VOXEL_PASS_MASK;
} | 260 |
fn run_with_different_fuzz_dir() {
let (fuzz_dir, mut project_builder) = project_with_fuzz_dir(
"project_likes_to_move_it",
Some("dir_likes_to_move_it_move_it"),
);
let project = project_builder
.with_fuzz()
.fuzz_target(
"you_like_to_move_it",
r#"
... | 261 |
fn buf_to_state(buf: &[u8]) -> Result<Engine, serde_json::Error> {
serde_json::from_slice(buf)
} | 262 |
pub fn debug_time<T>(label: impl AsRef<str>, cb: impl FnOnce() -> T) -> T {
let label = label.as_ref();
let t0 = std::time::Instant::now();
debug_log(format!("Starting {}...", label));
let ret = cb();
debug_log(format!("Finished {}: {:?}", label, t0.elapsed()));
return ret;
} | 263 |
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... | 264 |
async fn main() {
let start_url = std::env::args()
.skip(1)
.next()
.unwrap_or(START_URL.to_string());
let store = MemoryStore::new();
let mut agent = Agent::new(curiosity(), store.clone(), CachedHttp::default());
agent
.investigate(NamedNode::new(start_url).unwrap())
... | 265 |
fn
test_string
(
)
-
>
Result
<
(
)
>
{
let
db
=
checked_memory_handle
(
)
?
;
let
s
=
"
hello
world
!
"
;
db
.
execute
(
"
INSERT
INTO
foo
(
t
)
VALUES
(
?
1
)
"
[
s
.
to_owned
(
)
]
)
?
;
let
from
:
String
=
db
.
one_column
(
"
SELECT
t
FROM
foo
"
)
?
;
assert_eq
!
(
from
s
)
;
Ok
(
(
)
)
} | 266 |
pub fn merge_sort<T: PartialOrd + Debug>(mut v: Vec<T>) -> Vec<T> {
// sort the left half
// sort the right half O(n*ln(n))
// bring the sorted half together O(n)
if v.len() <= 1 {
return v;
}
let mut res = Vec::with_capacity(v.len());
let b = v.split_off(v.len()/2);
let a = merg... | 267 |
pub fn day09_1(s : String) -> u32{
let mut running_total = 0;
let mut scope = 0;
let mut in_garbage = false;
let mut prev_cancel = false;
for c in s.chars(){
if in_garbage {
if c == '>' && !prev_cancel {
in_garbage = false;
prev_cancel = false;
... | 268 |
pub fn print(buffer: [u8; 32], size: usize) {
let _ = system_call(SystemCall::Print {
request: (buffer, size)
});
} | 269 |
pub fn task_set_stack_pointer(target: CAddr, ptr: u64) {
system_call(SystemCall::TaskSetStackPointer {
request: (target, ptr),
});
} | 270 |
pub fn test_outofcycles_in_syscall() {
let buffer = fs::read("tests/programs/syscall64").unwrap().into();
let core_machine = DefaultCoreMachine::<u64, SparseMemory<u64>>::new(ISA_IMC, VERSION0, 20);
let mut machine = DefaultMachineBuilder::new(core_machine)
.instruction_cycle_func(Box::new(constant_... | 271 |
fn criterion_benchmark(c: &mut Criterion) {
let mut group = c.benchmark_group("fyrstikker");
group.sampling_mode(SamplingMode::Flat).sample_size(10);
group.bench_function("fyrstikker 40", |b| {
b.iter(|| fyrstikk_tal_kombinasjonar(40))
});
group.bench_function("fyrstikker 2000", |b| {
... | 272 |
fn get_command(stream: &mut TcpStream, buf: &mut[u8]) -> Result<Task, Error> {
let buf_sz = stream.read(buf).expect("failed to read from stream");
let buf_usize = buf_sz as usize;
let v = match serde_json::from_slice::<Task>(&buf[..buf_usize]){
Ok(v) => v,
Err(e) => return Err(e)
};
... | 273 |
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_ano... | 274 |
fn get_largest_register_value(registers: &HashMap<&str, i32>) -> i32 {
*registers
.iter()
.map(|(_, v)| v)
.max()
.unwrap_or(&0)
} | 275 |
fn git(args: &[&str]) -> Result<String, Box<dyn std::error::Error>> {
let mut cmd = Command::new("git");
cmd.args(args);
cmd.stdout(Stdio::piped());
let out = cmd.spawn();
let mut out = match out {
Ok(v) => v,
Err(err) => {
panic!("Failed to spawn command `{:?}`: {:?}", c... | 276 |
pub fn data_type<'a>() -> Parser<'a, char, DataType> {
ident().convert(|v| DataType::match_data_type(&v))
} | 277 |
fn
test_str
(
)
-
>
Result
<
(
)
>
{
let
db
=
checked_memory_handle
(
)
?
;
let
s
=
"
hello
world
!
"
;
db
.
execute
(
"
INSERT
INTO
foo
(
t
)
VALUES
(
?
1
)
"
[
&
s
]
)
?
;
let
from
:
String
=
db
.
one_column
(
"
SELECT
t
FROM
foo
"
)
?
;
assert_eq
!
(
from
s
)
;
Ok
(
(
)
)
} | 278 |
fn main() {
let nhits = 20;
let ntrials = 2000;
let nnanos = 60 * 1000 * 1000 * 1000;
let ntransfers = 1000;
let nbrokers = 8;
let tolerance = 0.05;
let ops = (ntransfers * nbrokers) as f64;
let million = (1000 * 1000) as f64;
let mut sum = 0.0;
let mut hits = 0;
let mut trial = 0;
let limit ... | 279 |
pub fn write_board(board_name: String, contents: String) -> Result<(), String> {
let mut configurator = Configurator::new();
unsafe {
configurator.set_working_folder(WORKING_FOLDER.clone());
}
configurator.write_board(board_name, contents)
} | 280 |
fn create_tap() -> AppResult<TapInfo> {
// create tap
inner_create_tap("tap0")
} | 281 |
fn print_node(prefix: &str, node: &IRNode) {
let next_prefix = get_next_prefix(prefix);
match node {
&IRNode::Assignment(ref name, ref exp) => {
println!("{}Assignment-'{}':", prefix, name);
print_expression(&next_prefix, exp);
}
&IRNode::DeclareVariable(ref name,... | 282 |
pub fn task_set_instruction_pointer(target: CAddr, ptr: u64) {
system_call(SystemCall::TaskSetInstructionPointer {
request: (target, ptr),
});
} | 283 |
fn extract_archive_into<P: AsRef<Path>>(
path: P,
response: reqwest::blocking::Response,
) -> Result<(), FrumError> {
#[cfg(unix)]
let extractor = archive::tar_xz::TarXz::new(response);
#[cfg(windows)]
let extractor = archive::zip::Zip::new(response);
extractor
.extract_into(path)
... | 284 |
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... | 285 |
fn main() {
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
console_log::init_with_level(log::Level::Warn).expect("could not initialize logger");
let fighter_bytes = include_bytes!("subaction_data.bin");
let subaction = bincode::deserialize(fighter_bytes).unwrap();
wasm_bindgen_futu... | 286 |
fn handle_trame(trame: Trame) -> Option<Trame> {
match (
trame.id,
trame.cmd,
&trame.data[0..trame.data_length as usize],
) {
(0...5, 0x0, [0x55]) => Some(trame!(trame.id, 0x00, [0xAA])),
(_, _, _) => None,
}
} | 287 |
fn soda(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_class::<Soda>()?;
Ok(())
} | 288 |
pub fn add_history(history_type: HistoryType, history_path: String) -> Result<(), &'static str> {
let path_buf = Path::new(&history_path);
if !(path_buf.is_dir() || path_buf.is_file()) {
return Err("Not a validate dir or file path.");
}
let mut configurator = Configurator::new();
configurato... | 289 |
fn part1(rules: &Vec<PasswordRule>) -> usize {
rules
.iter()
.filter(|rule| (rule.min..=rule.max).contains(&rule.password.matches(rule.letter).count()))
.count()
} | 290 |
fn decode_ppm_image(cursor: &mut Cursor<Vec<u8>>) -> Result<Image, Box<std::error::Error>> {
let mut image = Image {
width : 0,
height: 0,
pixels: vec![]
};
// read header
let mut c: [u8; 2] = [0; 2];
cursor.read(&mut c)?;
match &c {
b"P6" => { },
_ ... | 291 |
fn extract_ext_info(
info: &HandshakeControlInfo,
) -> Result<Option<&SrtControlPacket>, ConnectError> {
match &info.info {
HandshakeVsInfo::V5(hs) => Ok(hs.ext_hs.as_ref()),
_ => Err(UnsupportedProtocolVersion(4)),
}
} | 292 |
async fn client<R: tokio::io::AsyncRead + std::marker::Unpin>(url: &str, input_read: R) -> Result<!, String> {
let (read, write) = TcpStream::connect(url).await.map_err(|e| e.to_string())?
.into_split();
let read_comp = TcpOp::<ResponseLatRepr>::new(read)
.comp_null();
// .comp_debug("... | 293 |
pub fn task_set_active(target: CAddr) {
system_call(SystemCall::TaskSetActive {
request: target
});
} | 294 |
fn state_from_snapshot<F>(
snapshot: ::fidl::InterfacePtr<PageSnapshot_Client>,
key: Vec<u8>,
done: F,
) where
F: Send + FnOnce(Result<Option<Engine>, ()>) + 'static,
{
assert_eq!(PageSnapshot_Metadata::VERSION, snapshot.version);
let mut snapshot_proxy = PageSnapshot_new_Proxy(snapshot.inner);
... | 295 |
fn get_submodules(
repo: &Repository,
at: &Commit,
) -> Result<Vec<Submodule>, Box<dyn std::error::Error>> {
let submodule_cfg = modules_file(&repo, &at)?;
let submodule_cfg = Config::parse(&submodule_cfg)?;
let mut path_to_url = HashMap::new();
let entries = submodule_cfg.entries(None)?;
fo... | 296 |
pub fn var(v: Var) -> Value {
Rc::new(RefCell::new(V {
val: Value_::Var(v),
computed: false,
}))
} | 297 |
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!("initial... | 298 |
fn parseFromFile(file: &File) {
let mut reader = BufReader::new(file);
let mut buf = String::from("");
let line_index = 0;
let mut models: Vec<Model> = Vec::new();
let mut lights: Vec<Model> = Vec::new();
while (reader.read_line(&mut buf) != 0) {
if lien_index == 0 {
... | 299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.