kionite231

joined 2 years ago
MODERATOR OF
[–] kionite231 7 points 2 weeks ago (3 children)

It happens all the time when I go to university. I often catch a delusion like you said "that person doesn't wanna harm me since it doesn't benefit them" however It's hard to catch that "people doesn't mocking me and laughing at me" whenever I see a person laughing I think that they are laughing at me and it makes me uncomfortable. It's very hard to "catch" this kind of things. also I think that people are judging me like saying "oh he is a terrible person because xyz" which is infuriating.

[–] kionite231 2 points 2 weeks ago (1 children)

I don't have a beefy machine to play game on, so installing Bazzite is useless for me.

[–] kionite231 1 points 2 weeks ago (1 children)

I don't have their number so I can't send a message right now. However I will be going to the hospital after 20 days so then I can tell him about this.

[–] kionite231 4 points 3 weeks ago (1 children)

I didn't mention that I am also afraid of water and I don't shave my beard. Is it also symptoms of schizophrenia? Should I tell this to my psychiatrist?

[–] kionite231 4 points 3 weeks ago

I made the community on my home instance but feel free to make a new one on your instance too!

[–] kionite231 2 points 3 weeks ago (3 children)

You are right, I am still afraid of water that's why I don't take a bath frequently, I am also afraid of shaving my beard. However I haven't told this to my psychiatrist since I thought it was irrelevant. Please tell me if these are also symptoms of schizophrenia.

[–] kionite231 4 points 3 weeks ago

Thanks, I will make a post there!

[–] kionite231 4 points 3 weeks ago (4 children)

just made a new post in the schizophrenia community. [email protected]

https://lemmy.ca/post/38888819

[–] kionite231 1 points 3 weeks ago

You are correct, maybe 1 week is not that much time, I should try to use it for at least a month.

[–] kionite231 2 points 3 weeks ago

Thank you for the link!

[–] kionite231 1 points 3 weeks ago (1 children)

Yeah, I am trying to learn Linux(also BSDs) by using and tweaking them, I don't know if this is the right way to learn it.

[–] kionite231 1 points 3 weeks ago (3 children)

I mean to know/learn about it ( sorry bad english )

 

the code I have written isn't very idiomatic or efficient. I am still new to Rust so I am learning things. I am amazed that I can write a pastebin in just 60 lines of Rust code. It's awesome. I am thinking about deploying it on my server.

any suggestions would be appreciated :)

code:

use axum::{extract::Path, routing::get, Router};
use std::fs::{read_to_string, File};
use std::io::prelude::*;
use std::net::{TcpListener, TcpStream};
use std::str;

const MAX_FILE_SIZE: usize = 1024 * 1024 * 10;
static mut FILE_COUNT: usize = 0;

fn handle_client(stream: &mut TcpStream) -> std::io::Result<()> {
    let mut buf = vec![0; 1024];
    unsafe {
        let file_name = FILE_COUNT.to_string();
        FILE_COUNT += 1;
        let mut file = File::create(file_name)?;
        let mut size: usize = 0;
        loop {
            let read_data = stream.read(&mut buf).unwrap();
            size += read_data;
            if size >= MAX_FILE_SIZE {
                return Ok(())
            }
            if read_data == 0 {
                return Ok(());
            }
            stream.write_all(&buf[..read_data]).unwrap();
            write!(file, "{}", str::from_utf8(&buf[..read_data]).unwrap())?;
        }
    }
}

async fn upload_handle() -> std::io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:8080")?;

    // accept connections and process them serially
    for stream in listener.incoming() {
        handle_client(&mut stream?)?;
    }

    Ok(())
}

async fn handle(Path(id): Path<String>) -> String {
    if let Ok(content) = read_to_string(id) {
        return content;
    }
    return String::from("ERROR: File not found");
}

#[tokio::main]
async fn main() {
    tokio::spawn(upload_handle());

    let app = Router::new()
        .route("/", get(|| async { "Paste something in pastebin!" }))
        .route("/{id}", get(handle));

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

4
submitted 2 months ago* (last edited 2 months ago) by kionite231 to c/[email protected]
 

Hello,

I am trying to solve the day 7 using Rust and this is what I came up with so far:

use std::fs;

fn calculate(answer: &i32, numbers: &mut Vec<i32>) -> bool {
    if numbers.len() >= 2 {
	let tmp1 = numbers[0];
	let tmp2 = numbers[1];
	numbers.remove(0);
	numbers.remove(0);

	numbers.insert(0, tmp1 * tmp2);

	if calculate(answer, numbers) == true {
	    return true;
	} else {
	    numbers.remove(0);
	    numbers.insert(0, tmp1 + tmp2);
	    if calculate(answer, numbers) == true {
		return true;
	    } else {
		return false;
	    }
	}
    } else {
	if *answer == numbers[0] {
	    println!("> {} true", numbers[0]);
	    return true;
	} else {
	    println!("> {} false", numbers[0]);
	    return false;
	}
    }
}

fn main() {
    let contents = fs::read_to_string("sample.txt")
        .expect("Should have been able to read the file");

    for line in contents.lines() {
	let tmp = line.split(":").collect::<Vec<&str>>();
	let answer = tmp[0].to_string().parse::<i32>().unwrap();
	println!("{:?}", answer);
	let numbers_str = tmp[1].split(" ");
	let mut numbers: Vec<i32> = Vec::new();
	for num in numbers_str {
	    if num.len() == 0 {
		continue;
	    }
	    numbers.push(num.parse::<i32>().unwrap());
	}
	println!("{:?}", numbers);
	if calculate(&answer, &mut numbers) == true {
	    println!("it's true");
	}
    }
}

I don't know why the recursion is not working. any help would be appreciated.

 
use std::fs;

fn update_guard_loc(map: &mut Vec<Vec<char>>, guard_loc: &mut (i32, i32)) {
    match map[guard_loc.0 as usize][guard_loc.1 as usize] {
	'^' => {
	    if map[(guard_loc.0 - 1) as usize][guard_loc.1 as usize] == '#' {
		map[guard_loc.0 as usize][guard_loc.1 as usize] = '>'
	    } else {
		map[guard_loc.0 as usize][guard_loc.1 as usize] = 'X';
		guard_loc.0 -= 1;
		map[guard_loc.0 as usize][guard_loc.1 as usize] = '^';
	    }
	},
	'>' => {
	    if map[guard_loc.0 as usize][(guard_loc.1 + 1) as usize] == '#' {
		map[guard_loc.0 as usize][guard_loc.1 as usize] = 'v'
	    } else {
		map[guard_loc.0 as usize][guard_loc.1 as usize] = 'X';
		guard_loc.1 += 1;
		map[guard_loc.0 as usize][guard_loc.1 as usize] = '>';
	    }
	},
	'v' => {
	    if map[(guard_loc.0 + 1) as usize][guard_loc.1 as usize] == '#' {
		map[guard_loc.0 as usize][guard_loc.1 as usize] = '<'
	    } else {
		map[guard_loc.0 as usize][guard_loc.1 as usize] = 'X';
		guard_loc.0 += 1;
		map[guard_loc.0 as usize][guard_loc.1 as usize] = 'v';
	    }
	},
	'<' => {
	    if map[guard_loc.0 as usize][(guard_loc.1 - 1) as usize] == '#' {
		map[guard_loc.0 as usize][guard_loc.1 as usize] = '^'
	    } else {
		map[guard_loc.0 as usize][guard_loc.1 as usize] = 'X';
		guard_loc.1 -= 1;
		map[guard_loc.0 as usize][guard_loc.1 as usize] = '<';
	    }
	},

	_ => println!("unreachable"),
    }
}

fn main() {
    let contents = fs::read_to_string("input.txt").expect("Should have able to read the file");
    let mut map: Vec<Vec<char>> = Vec::new();
    let lines = contents.split("\n").collect::<Vec<&str>>();
    for line in lines {
	if line.len() == 0 {
	    // ignore empty line
	    break;
	}
	map.push(line.chars().collect::<Vec<char>>());
    }
    // Getting the first location of guard
    let mut height: i32 = 0;
    let mut width: i32 = 0;
    let mut guard_loc: (i32, i32) = (0, 0);
    for (i, lines) in map.iter().enumerate() {
	for (j, chr) in lines.iter().enumerate() {
	    if *chr == '^' {
		guard_loc.0 = i as i32;
		guard_loc.1 = j as i32;
	    }
	    height = (i + 1) as i32;
	    width = (j + 1) as i32;
	}
    }
    loop {
	update_guard_loc(&mut map, &mut guard_loc);
	match map[guard_loc.0 as usize][guard_loc.1 as usize] {
	    '^' => {
		if guard_loc.0 - 1 < 0 {
		    break;
		}
	    },
	    'v' => {
		if guard_loc.0 + 1 > height - 1 {
		    break;
		}
	    },
	    '>' => {
		if guard_loc.1 + 1 > width - 1 {
		    break;
		}
	    },
	    '<' => {
		if guard_loc.1 - 1 < 0 {
		    break;
		}
	    },
	    _ => println!("ureachable"),
	}
    }

    for line in map.iter() {
	println!("{:?}", line);
    }

    let mut count = 0;
    for line in map.iter() {
	for c in line.iter() {
	    if *c == 'X' {
		count += 1;
	    }
	}
    }
    println!("count: {}", count + 1);
}

 
use std::fs;
use std::collections::HashMap;

fn reorder_pages<'a>(rules_hash_map: HashMap<&str, Vec<&str>>, page_numbers: &'a str) -> Vec<&'a str>{
    let mut tmp = page_numbers.split(",").collect::<Vec<&str>>();
    for i in 0..tmp.len()-1 {
        for j in i+1..tmp.len() {
            match rules_hash_map.get(&tmp[i]) {
                Some(vec) => {
                    if !vec.contains(&tmp[j]) {
			if let Some(v2) = rules_hash_map.get(&tmp[j]) {
			    if v2.contains(&tmp[i]) {
				// swap two elements
				let t = tmp[i];
				tmp[i] = tmp[j];
				tmp[j] = t;
			    }
			}

                    }
                }
                None => {
		    if let Some(v2) = rules_hash_map.get(&tmp[j]) {
			if v2.contains(&tmp[i]) {
			    // swap two elements
			    let t = tmp[i];
			    tmp[i] = tmp[j];
			    tmp[j] = t;
			}
		    }
                }
            }
        }
    }
    return tmp;
}

fn main() {
    let contents = fs::read_to_string("input.txt")
        .expect("Should have been able to read the file");
    let parts = contents.split("\n\n").collect::<Vec<&str>>();
    let rules = parts[0];
    let page_numbers = parts[1];
    let mut rules_hash_map: HashMap<&str, Vec<&str>> = HashMap::new();

    for rule in rules.split("\n") {
        let tmp = rule.split("|").collect::<Vec<&str>>();
        rules_hash_map.entry(tmp[0]).and_modify(|vec| vec.push(tmp[1])).or_insert(vec![tmp[1]]);
    }

    let mut answer = 0;
    for page_numbers_line in page_numbers.split("\n").collect::<Vec<&str>>() {
        if page_numbers_line.len() == 0 {
            break;
        }
	let none_reordered_pages = page_numbers_line.split(",").collect::<Vec<&str>>();
        let reordered_pages = reorder_pages(rules_hash_map.clone(), page_numbers_line);
	let doesnt_matching = none_reordered_pages.iter().zip(&reordered_pages).filter(|&(a, b)| a != b).count();
	if doesnt_matching > 0 {
	    //println!("reorder_pages: {:?}", reordered_pages);
	   // println!("number of doesn't match: {:?}", doesnt_matching);
	    answer += reordered_pages[reordered_pages.len() / 2].parse::<i32>().unwrap();
	}


    }

    println!("answer: {answer}");
}

 
use std::fs;
use std::collections::HashMap;

fn count_correct(rules_hash_map: HashMap<&str, Vec<&str>>, page_numbers: &str) -> bool{
        let tmp = page_numbers.split(",").collect::<Vec<&str>>();
        for i in 0..tmp.len()-1 {
            for j in i+1..tmp.len() {
                match rules_hash_map.get(&tmp[i]) {
                    Some(vec) => {
                        if !vec.contains(&tmp[j]) {
                            return false;
                        }
                    }
                    None => {
                        return false;
                    }
                }
            }
        }
    

    return true;
}

fn main() {
    let contents = fs::read_to_string("input.txt")
        .expect("Should have been able to read the file");
    let parts = contents.split("\n\n").collect::<Vec<&str>>();
    let rules = parts[0];
    let page_numbers = parts[1];
    let mut rules_hash_map: HashMap<&str, Vec<&str>> = HashMap::new();

    for rule in rules.split("\n") {
        let tmp = rule.split("|").collect::<Vec<&str>>();
        rules_hash_map.entry(tmp[0]).and_modify(|vec| vec.push(tmp[1])).or_insert(vec![tmp[1]]);
    }

    let mut count = 0;
    let mut answer = 0;
    for page_numbers_line in page_numbers.split("\n").collect::<Vec<&str>>() {
        if page_numbers_line.len() == 0 {
            break;
        }
        let ok = count_correct(rules_hash_map.clone(), page_numbers_line);
        if ok {
            let tmp = page_numbers_line.split(",").collect::<Vec<&str>>();
            answer += tmp[tmp.len()/2].parse::<i32>().expect("parsing error");
            count += 1;
        }
    }

    println!("true_count: {count}");
    println!("answer: {answer}");
}

any suggestions would be appreciated :)

 

Hello,

some time ago I shared a Guess game that I made from scratch and this time I thought to do something different so I decided to make a Guess game over IRC.

It's pretty basic but I learned a lot about destructing Enum, unwrap and if let syntax.

I would appreciate any suggestion :)

here is the source code:

use futures::prelude::*;
use irc::client::prelude::*;

use rand::Rng;

#[tokio::main]
async fn main() -> irc::error::Result<()> {
    let config = Config {
        nickname: Some("beep_boop".to_owned()),
        server: Some("irc.libera.chat".to_owned()),
        channels: vec!["#test".to_owned()],
        ..Default::default()
    };

    let mut client = Client::from_config(config).await?;
    client.identify()?;

    let mut stream = client.stream()?;
    let mut secret_number = rand::thread_rng().gen_range(0..101);
    let mut attempts = 0;

    while let Some(message) = stream.next().await.transpose()? {
        print!("{}", message);

        match message.command {
            Command::PRIVMSG(channel, message) => {
                if let Some(command) = message.get(0..6) {
                    if command == "!guess" {
                        let parts = message.split(' ').collect::<Vec<_>>();
                        if let Some(part2) = parts.get(1) {
                            if let Ok(num) = part2.to_string().parse::<u32>() {
                                println!("{:?}", num);
                                if num == secret_number {
                                    client.send_privmsg(&channel, format!("You won with {attempts} attempts! generating next number")).unwrap();
                                    secret_number = rand::thread_rng().gen_range(0..101);
                                    attempts = 0; // reseting the number of attempts 
                                } else if num > secret_number {
                                    client.send_privmsg(&channel, "too high").unwrap();
                                    attempts += 1;
                                } else {
                                    client.send_privmsg(&channel, "too low").unwrap();
                                    attempts += 1;
                                }
                            }
                        }
                    }
                }
                else {
                    continue;
                }
                if message.contains(client.current_nickname()) {
                    client.send_privmsg(channel, "beep boop").unwrap();
                }
            },
            _ => println!("IRC command not implemented: {message}"),
        }
    }

    Ok(())
}

16
struct in Rust (self.rust)
 

Hello,

I learned about struct in Rust, so I just wanted to share what I have learned.

what is struct in Rust? It's the same as what's in C language. eg,

struct Point {
    x: i32,
    y: i32,
}

that's it this is how we define a struct. we can create all sort of struct with different data types. ( here I have used only i32 but you can use any data type you want)

now Rust also have which we find in OOPs languages like Java. it's called method. here is how we can define methods for a specific struct in Rust.

impl Point {
    fn print_point(&self) {
        println!("x: {} y: {}", self.x, self.y);
    }
}

see it's that easy. tell me if I forgot about something I should include about struct in Rust.

 

hello,

last time I made a fibonacci series generator in Rust and now I have made something different :)

use std::io;

fn main() {
    let mut input: String = String::new();
    let stdin = io::stdin();

    let x = rand::random::<u32>() % 101;
    let mut attempts = 0;

    loop {
        println!("Guess a number from 0 to 100:");
        stdin.read_line(&mut input);
        input = input.to_string().replace("\n", ""); // removing the \n
        let user_input: u32 = input.parse::<u32>().unwrap();
        if x == user_input {
            println!("You won! attempts: {attempts}");
            break;
        }
        else if x < user_input {
            println!("too big");
            attempts += 1;
        }
        else {
            println!("too small");
            attempts += 1;
        }
        input.clear()
    }
}

feel free to give me suggestion :)

 

Hello,

As I said in the previous post that I have started learning Rust and made a simple fibonacci series generator. Today I made a palindrome string checker. it's very basic. I haven't used Enum or Struct in the code since I don't think it's necessary in this simple code.

here is the code:

use std::io;

fn main() {
    let mut input = String::new();
    let stdin = io::stdin();
    stdin.read_line(&mut input).unwrap(); // we want to exit in case it couldn't read from stdin

    input = input.replace("\n", ""); // Removing newline

    let mut is_palindrome: bool = true;
    for i in 0..input.len()/2 {
        let first_char: &str = &input[i..i+1];
        let last_char: &str = &input[input.len()-i-1..input.len()-i];
        if first_char != "\n" {
            if first_char != last_char {
                is_palindrome = false;
            }
        }
    }

    println!("palindrome: {}", is_palindrome);
}
20
Learning Rust (self.rust)
 

Hello,

I have started learning Rust. I have only made a fibonaci series program so far but I would make more complex program as I progress in learning Rust :D

2
Went to another pdoc (self.schizophrenia)
submitted 2 months ago by kionite231 to c/schizophrenia
 

Hello,

I went to another pdoc because the previous one was asking for more money and I don't have money to pay pdoc. So I went to a government funded pdoc and he diagnosed me with Parkinson's disease and schizophrenia. I feel like this pdoc would cure schizophrenia, at least I hope so.

 

Hello,

first I installed Gentoo with glibc and it worked fine, I got sway up and running but after some time I got bored and wanted something new. so I decided to go with Arch with rEFInd bootloader but I couldn't make it work. Arch dropped me into a rescue shell. so I went back to Gentoo but this time with musl and this time I tried Hyprland on Gentoo. there were 133 packages to install for Hyprland, so I went for installing those packages but the build failed probably because using musl. now I thought I just pick that's easy to setup and I went with Debian and it got installed successfully. so yeah, right now I am using Debian after the back and forth between Arch and Gentoo.

sadly I pissed of some Gentoo devs on IRC #gentoo :(

maybe it was my fault I shouldn't have distrohopped when Gentoo was installed succesfully and working fine.

view more: ‹ prev next ›