Category: Blog

  • hospital-system

    📊 Hospital System Application – EN

    A patient registration and image upload application where patient records can be made and images can be uploaded. Patients can be updated, their pictures can be deleted and listed. With the project, I experienced uploading images to the database with PHP.

    💻 Tech Stack

    • PHP
    • Bootstrap
    • Javascript

    🎨 Features

    • Patient Addition, Deletion, Update and Listing Operations
    • Patient Search
    • Uploading, Deleting and Listing Patient Images

    📷 Screen Shots

    image image image image image image

    Environment Variables

    To run this project you will need to add the following environment variables to your file

    db/config.php > DB_USER

    db/config.php > DB_PASS

    🚀 Run on Your Computer

    Note: You must have PHP and MySQL installed on your computer.

    Note2: You must have an apache server such as XAMPP installed on your computer and you must open Apache Server and MySQL services before the operations.

    1. Clone the project

      git clone https://github.com/sonatipek/hospital-system.git

    2. Go to the project directory

      cd hospital-system

    3. Run the required database script and add the environment variables

      hospital-system/database.sql

    4. Add the project into your apache server folder. For XAMPP;

      xampp/htdocs/hospital-system

    5. Run it on your localhost. Try typing this in your browser bar;

      localhost/hospital-system

    6. That’s all!

    🌟 Feedback

    You can support me with your feedback. If you have any feedback, please contact at sonatsayginipek@gmail.com or sonatipek.com .


    📊 Hastane Sistem Uygulaması – TR

    Hasta kayıtlarının yapıldığı, resimlerinin yüklenilebildiği bir hasta kayıt ve resim yükleme uygulaması. Hastalar güncellenebilir, resimleri silinebilir, listelenebilir. Proje ile PHP ile veritabanına resim yüklemeyi tecrübe ettim.

    💻 Kullanılan Teknolojiler

    • PHP
    • Bootstrap
    • Javascript

    🎨 Özellikler

    • Hasta Ekleme, Silme, Güncelleme ve Listeleme İşlemleri
    • Hasta Arama
    • Hastanın Görüntülerini Yükleme, Silme ve Listeleme İşlemleri

    📷 Ekran Görüntüleri

    image image image image image image

    Ortam Değişkenleri

    Bu projeyi çalıştırmak için aşağıdaki ortam değişkenlerini dosyanıza eklemeniz gerekecek

    db/config.php > DB_USER

    db/config.php > DB_PASS

    🚀 Bilgisayarınızda Çalıştırın

    Not: Bilgisayarınızda PHP ve MySQL kurulu olmalıdır.

    Not2: Bilgisayarınızda XAMPP gibi bir apache server kurulu olmalıdır ve işlemlerden önce Apache Server ve MySQL servislerini açmalısınız.

    1. Projeyi klonlayın

      git clone https://github.com/sonatipek/hospital-system.git

    2. Proje dizinine gidin

      cd hastane-sistemi

    3. Gerekli veritabanı komut dosyasını çalıştırın ve ortam değişkenlerini ekleyin

      hastane-sistemi/veritabani.sql

    4. Projeyi apache sunucu klasörünüze ekleyin. XAMPP için;

      xampp/htdocs/hastane-sistemi

    5. Localhost’unuzda çalıştırın. Tarayıcı çubuğunuza bunu yazmayı deneyin;

    “bash localhost/hastane-sistemi

    
    ## 🌟 Geri bildirim
    Beni geri bildirimlerinizle destekleyebilirsiniz. Herhangi bir geri bildiriminiz varsa, lütfen **sonatsayginipek@gmail.com** veya **sonatipek.com** adresinden iletişime geçin.
    
    
    Visit original content creator repository https://github.com/sonatipek/hospital-system
  • picket


    Picket
    Picket

    Screen color picker for linux with magnifier and custom/user defined formats.

    FeaturesAuthorsLicense

    Main Window

    MainWindow

    Features

    Magnifier

    Magnifier

    CustomFormat

    All the formats are stored in the directory {home}/.picket in the file formats.txt Color Formats consist of two components:

    1. [xxxx] – A unique indetifier
    2. xxxxxx… – The actual string that will be copied to the clipboard

    Example

    [RGB]$r$, $g$, $b$

    output:

    150, 250, 75

    Lines that do not start with a [ character are ignored and can be used like comments

    FormatEditor

    Simple Format Editor

    FormatEditor

    Variables

    Variable Description
    $r$ Red 0-255
    $g$ Green 0-255
    $b$ Blue 0-255
    $a$ Aplha 0-255
    $r_d$ Red as double 0.0 – 1.0
    $g_d$ Green as double 0.0 – 1.0
    $b_d$ Blue as double 0.0 – 1.0
    $a_d$ Alpha as double 0.0 – 1.0
    $r_hex$ Red as hex 00 – FF
    $g_hex$ Green as hex 00 – FF
    $b_hex$ Blue as hex 00 – FF
    $a_hex$ Alpha as hex 00 – FF
    $h$ Hue
    $s$ Saturation in %
    $l$ Lightness in %
    $s_d$ Saturation as double
    $l_d$ Lightness as double
    $c$ Cyan 0-100
    $m$ Magenta 0-100
    $y$ Yellow 0-100
    $k$ Key 0-100
    $c_d$ Cyan as double 0.0 – 1.0
    $m_d$ Magenta as double 0.0 – 1.0
    $y_d$ Yellow as double 0.0 – 1.0
    $k_d$ Key as double 0.0 – 1.0

    Settings

    SettingsWindow

    Useful settings:

    • Start immediate pick – Starts the picking process when the application starts
    • Copy to clipboard after pick – Copies the selected format to clipboard after the pickcing process finished
    • Quit after pick – Quits the application after the picking process finishes

    Shortcuts

    MainWindow

    Key Description
    SPACE or p Starts the picker
    TAB Copies the format to the clipboard
    q Quit. Exit application.
    1...9 Quick format selection

    Picker

    Key Description
    up arrow or w Move up
    down arrow or s Move down
    left arrow or a Move left
    right arrow or d Move right
    e or + Increase magnifier size
    q or - Decrease magnifier size
    ESC Cancel pick

    Packages

    Arch User Repositories https://aur.archlinux.org/packages/picket/

    Manual Install

    Clone the repository to your local machine. git clone https://github.com/rajter/Picket.git
    Change directory to Picket cd Picket
    Create directory “build” mkdir build
    Change directory to build cd build
    Execute cmake for Release build cmake -DCMAKE_BUILD_TYPE=Release ..
    Execute sudo make install to build and install it on your machine.

      git clone https://github.com/rajter/Picket.git
      cd Picket
      mkdir build
      cd build
      cmake -DCMAKE_BUILD_TYPE=Release ..
      sudo make install

    Prerequisites

    • GCC – GNU Compiler
    • Gtkmm Gtkmm – GTK+ wrapper for c++

    Built With

    • mINI – tiny, header only C++ library for manipulating INI files
    • Glade – Glade user interface designer

    Authors

    • Andrija RajterInitial workrajter

    License

    This project is licensed under the MIT License – see the LICENSE file for details

    Visit original content creator repository https://github.com/rajter/picket
  • accownt

    Accownt

    The goal of Accownt is to be a full-featured, standalone account system that’s straightforward for developers and users, easy to maintain, and as customizable as possible without introducing too much complexity.

    Features

    • Email + password login
      • Passwordless login via links sent to emails also available
      • Passwords are hashed with bcrypt
    • Two-Factor Authentication (2FA)
      • Authy, Google Authenticator, etc supported
    • Email verification
      • Plug in your SMTP credentials for Mailgun, Gmail, or anything else
    • Account recovery
    • Account deletion
    • No dependencies other than Node and what npm will install
    • No database needed
    • Standalone server and web client
      • Easy integration into new and existing applications of any stack
    • reCAPTCHA v2 support
    • JSON Web Tokens (JWT)
      • Shared JWT and cookie between Accownt and your app for session authentication
    • Easy theming + light and dark themes

    Install

    As simple as Accownt is, you’ll still need to install, configure, build, and integrate into your app. We’ve made it just about as easy as it could possibly be.

    Note #1: If your system does not yet have Node installed, start with nvm (or nvm for Windows).

    Note #2: You may alternatively download Accownt through npm (see here), however this is not currently the recommended installation method. In the future we’ll likely have a CLI tool available through npm to make configuring, running, and managing Accownt instances easier.

    Step 0: Clone the repo

    git clone https://github.com/xyfir/accownt.git
    cd accownt

    From now on we’ll assume commands are run from accownt/.

    Step 1: Download npm dependencies

    Install npm depencies for each module:

    cd server
    npm install
    cd ../web
    npm install
    cd ../ # back to accownt/

    Step 2: Set environment variables

    The Accownt modules are configured via environment variables which are loaded into the applications via .env files located in each module’s directory.

    To understand the syntax of the .env files, know that they are first loaded via dotenv and then the string values provided by dotenv are parsed by enve.

    Step 2a: Create .env files

    First we’ll create each file by copying the example .env files and then we’ll work our way through populating them with values.

    cp server/example.env server/.env
    cp web/example.env web/.env

    Step 2b: Edit .env files

    Edit the files server/.env and web/.env. Update the config keys with your own values. You can find descriptions for each one under the Accownt -> Env namespaces in the type definitions. Use the appropriate interface for each corresponding file.

    Step 3: Build from source

    cd server
    npm run build
    cd ../web
    npm run build
    cd ../

    Step 4: Start the server

    Now you’ll need to start the server and serve the built files. The simplest way to do this is:

    cd server
    npm run start
    cd ../

    If you’re in production, you’ll probably run the server with pm2 and proxy the server through Nginx or Apache while serving static files through them instead of Node. For you, know that files to be served to the client are located in web/dist with web/dist/index.html serving as the web client’s entry file.

    Step 5: Add Accownt to your app

    This part is largely up to you, so it’s important to understand the flow of data between your app and Accownt:

    1. Your app sends users to Accownt’s login/registration form either by user action or automatically through a forced redirection. All you need to do is get the user to Accownt, everything it needs to know is already in its config.
    2. Accownt will handle everything until there’s a login, at which point it will redirect the user back to your app with the JWT in the URL based on your configuration. The same JWT will also be set as a cookie, so depending on your setup you may be able to and prefer to access this instead.

    To be a bit more specific:

    1. Somewhere in your app you’ll put login and/or registration links that point to the Accownt web client.
    2. If your app utilizes the JWT cookie that Accownt sets then all you need to do is verify the token with each request via jsonwebttoken or the equivalent in your preferred language.
    3. Once the JWT is verified and decoded, you can retrieve the userId and email properties from it to use however you need. Note that userId is a unix timestamp in milliseconds (13 digits!) that corresponds to when the user created their account. Also keep in mind that if your app is receiving a JWT, the user’s email has already been verified.
    4. If the JWT is invalid or expired, redirect them back to the Accownt form or to unauthenticated parts of your app.
    5. Lastly, you’ll need a route somewhere to catch redirections and tokens from Accownt after each successful login. You set this already in your

    There are also some optional steps you can take to improve the user experience:

    1. You can also add a link somewhere that takes authenticated users to Accownt so they can modify their account information, like their password or 2FA.
    2. You can allow users to delete their accounts by configuring the proper environment variables.

    Example

    A working example can be found in Ptorx.

    Contribute

    If you’d like to help work on Accownt, the tutorial above will suffice to get you up and running. Certain things however will make your life easier:

    • Make sure your NODE_ENV variables in the .env files are set to "development".
    • Run the web client’s dev server via npm run start when in web/. Connect to it via the PORT you set in web/.env.
    • Check the scripts in each module’s package.json for helpful scripts.
    Visit original content creator repository https://github.com/xyfir/accownt
  • nft-faucet

    NFT Faucet

    Deploy to GitHub Pages

    It’s a WASM web-application that allows you to mint ERC-721 and ERC-1155 tokens to any specified address from supported networks.

    Demo

    Go to https://darkcodi.github.io/nft-faucet/

    demo

    Deployed contracts

    Used contracts are based on OpenZeppilin contracts, but with one unusual feature – mint method can be called by anyone, not just by an owner.

    ERC-721 ERC-1155
    Ropsten 0x71902F99902339d7ce1F994C12155f4350BCD226 0x80b45421881c0452A6e70148Fc928fA33107cEb3
    Rinkeby 0x9F64932Be34D5D897C4253D17707b50921f372B6 0xf67C575502fc1cE399a3e1895dDf41847185D7bD
    Goerli 0xC3E4214dd442136079dF06bb2529Bae276d37564 0x5807d7be82153F6a302d92199221090E3b78A3C3
    Kovan 0x99ea658e02baDE18c43Af5Fa8c18cfF4f251E311 0xdBDD0377D1799910A4B0a4306F8d812265bF33Cb
    Sepolia 0x9F64932Be34D5D897C4253D17707b50921f372B6 0x1eD60FedfF775D500DDe21A974cd4E92e0047Cc8
    OptimismKovan 0xee52f32f4bbcedc2a1ed1c195936132937f2d371 0xCc0040129f197F63D37ebd77E62a6F96dDcd4e0A
    PolygonMumbai 0xeE8272220A0988279627714144Ff6981E204fbE4 0x23147CdbD963A3D0fec0F25E4604844f477F65d2
    MoonbaseAlpha 0x9F64932Be34D5D897C4253D17707b50921f372B6 0xf67C575502fc1cE399a3e1895dDf41847185D7bD
    ArbitrumRinkeby 0x9F64932Be34D5D897C4253D17707b50921f372B6 0xf67C575502fc1cE399a3e1895dDf41847185D7bD
    AvalancheFuji 0x9F64932Be34D5D897C4253D17707b50921f372B6 0xf67C575502fc1cE399a3e1895dDf41847185D7bD
    BnbChainTestnet 0xe6ee919a81da4dad1e632614ba4fdb8d748eb278 0xa6d787d1ec987a96ba2a8bf4dae79234e4a2125a

    Technology stack

    NOTE: The entire web app works as a static website, hosted on Github Pages. There is NO backend, it runs only in your browser! 🙂

    • Blazor WASM
    • Metamask
    • IPFS (upload provider – Infura, pinning provider – Crust)
    • Solidity smart contracts

    forthebadge forthebadge

    How to run it locally?

    Simply type this command in the root of this repo:

    dotnet run --project NftFaucet
    
    Visit original content creator repository https://github.com/darkcodi/nft-faucet
  • nft-faucet

    NFT Faucet

    Deploy to GitHub Pages

    It’s a WASM web-application that allows you to mint ERC-721 and ERC-1155 tokens to any specified address from supported networks.

    Demo

    Go to https://darkcodi.github.io/nft-faucet/

    demo

    Deployed contracts

    Used contracts are based on OpenZeppilin contracts, but with one unusual feature – mint method can be called by anyone, not just by an owner.

    ERC-721 ERC-1155
    Ropsten 0x71902F99902339d7ce1F994C12155f4350BCD226 0x80b45421881c0452A6e70148Fc928fA33107cEb3
    Rinkeby 0x9F64932Be34D5D897C4253D17707b50921f372B6 0xf67C575502fc1cE399a3e1895dDf41847185D7bD
    Goerli 0xC3E4214dd442136079dF06bb2529Bae276d37564 0x5807d7be82153F6a302d92199221090E3b78A3C3
    Kovan 0x99ea658e02baDE18c43Af5Fa8c18cfF4f251E311 0xdBDD0377D1799910A4B0a4306F8d812265bF33Cb
    Sepolia 0x9F64932Be34D5D897C4253D17707b50921f372B6 0x1eD60FedfF775D500DDe21A974cd4E92e0047Cc8
    OptimismKovan 0xee52f32f4bbcedc2a1ed1c195936132937f2d371 0xCc0040129f197F63D37ebd77E62a6F96dDcd4e0A
    PolygonMumbai 0xeE8272220A0988279627714144Ff6981E204fbE4 0x23147CdbD963A3D0fec0F25E4604844f477F65d2
    MoonbaseAlpha 0x9F64932Be34D5D897C4253D17707b50921f372B6 0xf67C575502fc1cE399a3e1895dDf41847185D7bD
    ArbitrumRinkeby 0x9F64932Be34D5D897C4253D17707b50921f372B6 0xf67C575502fc1cE399a3e1895dDf41847185D7bD
    AvalancheFuji 0x9F64932Be34D5D897C4253D17707b50921f372B6 0xf67C575502fc1cE399a3e1895dDf41847185D7bD
    BnbChainTestnet 0xe6ee919a81da4dad1e632614ba4fdb8d748eb278 0xa6d787d1ec987a96ba2a8bf4dae79234e4a2125a

    Technology stack

    NOTE: The entire web app works as a static website, hosted on Github Pages. There is NO backend, it runs only in your browser! 🙂

    • Blazor WASM
    • Metamask
    • IPFS (upload provider – Infura, pinning provider – Crust)
    • Solidity smart contracts

    forthebadge forthebadge

    How to run it locally?

    Simply type this command in the root of this repo:

    dotnet run --project NftFaucet
    
    Visit original content creator repository https://github.com/darkcodi/nft-faucet
  • bootcamp-desafio-01

    Desafio 01. Conceitos do NodeJS

    Crie uma aplicação do zero utilizando Express.

    Essa aplicação será utilizada para armazenar projetos e suas tarefas.

    Rotas

    • POST /projects: A rota deve receber id e title dentro corpo de cadastrar um novo projeto dentro de um array no seguinte formato: { id: "1", title: 'Novo projeto', tasks: [] };

    • GET /projects: Rota que lista todos projetos e suas tarefas;

    • PUT /projects/:id: A rota deve alterar apenas o título do projeto com o id presente nos parâmetros da rota;

    • DELETE /projects/:id: A rota deve deletar o projeto com o id presente nos parâmetros da rota;

    • POST /projects/:id/tasks: A rota deve receber um campo title e armazenar uma nova tarefa no array de tarefas de um projeto específico escolhido através do id presente nos parâmetros da rota;

    Exemplo

    Se eu chamar a rota POST /projects repassando { id: 1, title: 'Novo projeto' } e a rota POST /projects/1/tasks com { title: 'Nova tarefa' }, meu array de projetos deve ficar assim:

    [
      {
        id: "1",
        title: 'Novo projeto',
        tasks: ['Nova tarefa']
      }
    ]

    Middlewares

    • Crie um middleware que será utilizado em todas rotas que recebem o ID do projeto nos parâmetros da URL que verifica se o projeto com aquele ID existe. Se não existir retorne um erro, caso contrário permita a requisição continuar normalmente;

    • Crie um middleware global chamado em todas requisições que imprime (console.log) uma contagem de quantas requisições foram feitas na aplicação até então;

    Entrega

    Esse desafio não precisa ser entregue e não receberá correção, mas você pode ver o resultado do código do desafio aqui: https://github.com/Rocketseat/bootcamp-gostack-desafio-01

    Após concluir o desafio, adicionar esse código ao seu Github é uma boa forma de demonstrar seus conhecimentos para oportunidades futuras.

    “Sua única limitação é você mesmo”!


    Resolução

    funcionamento

    Visit original content creator repository https://github.com/v1eira/bootcamp-desafio-01
  • slice-base-normalize-slice

    About stdlib…

    We believe in a future in which the web is a preferred environment for numerical computation. To help realize this future, we’ve built stdlib. stdlib is a standard library, with an emphasis on numerical and scientific computation, written in JavaScript (and C) for execution in browsers and in Node.js.

    The library is fully decomposable, being architected in such a way that you can swap out and mix and match APIs and functionality to cater to your exact preferences and use cases.

    When you use stdlib, you can be absolutely certain that you are using the most thorough, rigorous, well-written, studied, documented, tested, measured, and high-quality code out there.

    To join us in bringing numerical computing to the web, get started by checking us out on GitHub, and please consider financially supporting stdlib. We greatly appreciate your continued support!

    normalizeSlice

    NPM version Build Status Coverage Status

    Normalize a Slice object.

    Installation

    npm install @stdlib/slice-base-normalize-slice

    Alternatively,

    • To load the package in a website via a script tag without installation and bundlers, use the ES Module available on the esm branch (see README).
    • If you are using Deno, visit the deno branch (see README for usage intructions).
    • For use in Observable, or in browser/node environments, use the Universal Module Definition (UMD) build available on the umd branch (see README).

    The branches.md file summarizes the available branches and displays a diagram illustrating their relationships.

    To view installation and usage instructions specific to each branch build, be sure to explicitly navigate to the respective README files on each branch, as linked to above.

    Usage

    var normalizeSlice = require( '@stdlib/slice-base-normalize-slice' );

    normalizeSlice( slice, len, strict )

    Normalizes a Slice object, where len specifies the maximum number of elements allowed in the slice.

    var Slice = require( '@stdlib/slice-ctor' );
    
    var s = normalizeSlice( new Slice( -1, null, -1 ), 10, false );
    // returns <Slice>
    
    var v = s.start;
    // returns 9
    
    v = s.stop;
    // returns null
    
    v = s.step;
    // returns -1

    When strict is true, the function returns an error object if an input slice exceeds index bounds.

    var Slice = require( '@stdlib/slice-ctor' );
    
    var s = normalizeSlice( new Slice( -20, 20, 1 ), 10, true );
    // returns { 'code': 'ERR_SLICE_OUT_OF_BOUNDS' }

    A returned error object may have one of the following error codes:

    • ERR_SLICE_OUT_OF_BOUNDS: a slice exceeds index bounds.

    Examples

    var Slice = require( '@stdlib/slice-ctor' );
    var normalizeSlice = require( '@stdlib/slice-base-normalize-slice' );
    
    var s = normalizeSlice( new Slice(), 5, false );
    console.log( 'start: %s. stop: %s. step: %s.', s.start, s.stop, s.step );
    // => 'start: 0. stop: 5. step: 1.'
    
    s = normalizeSlice( new Slice( 1, 4, 2 ), 5, false );
    console.log( 'start: %s. stop: %s. step: %s.', s.start, s.stop, s.step );
    // => 'start: 1. stop: 4. step: 2.'
    
    s = normalizeSlice( new Slice( -1, null, -1 ), 5, false );
    console.log( 'start: %s. stop: %s. step: %s.', s.start, s.stop, s.step );
    // => 'start: 4. stop: null. step: -1.'
    
    s = normalizeSlice( new Slice( -10, -2, 2 ), 5, false );
    console.log( 'start: %s. stop: %s. step: %s.', s.start, s.stop, s.step );
    // => 'start: 0. stop: 3. step: 2.'
    
    s = normalizeSlice( new Slice( 1, 20, 2 ), 5, false );
    console.log( 'start: %s. stop: %s. step: %s.', s.start, s.stop, s.step );
    // => 'start: 1. stop: 5. step: 2.'

    See Also


    Notice

    This package is part of stdlib, a standard library for JavaScript and Node.js, with an emphasis on numerical and scientific computing. The library provides a collection of robust, high performance libraries for mathematics, statistics, streams, utilities, and more.

    For more information on the project, filing bug reports and feature requests, and guidance on how to develop stdlib, see the main project repository.

    Community

    Chat


    License

    See LICENSE.

    Copyright

    Copyright © 2016-2025. The Stdlib Authors.

    Visit original content creator repository https://github.com/stdlib-js/slice-base-normalize-slice
  • wporg-internal-notes

    WordPress.org Internal Notes plugin

    Adds a new sidebar to the block editor for post types that support wporg-internal-notes. Editors can leave notes about the current post that other editors can read, but the notes are not visible on the front end.

    Configuration

    To enable internal notes for a particular post type, add this line to an mu-plugin or somewhere in the plugin that registers the post type:

    add_post_type_support( '[post type slug here]', 'wporg-internal-notes' );

    To enable log entries for changes to posts, which will appear in the same stream with internal notes, add this line:

    add_post_type_support( '[post type slug here]', 'wporg-log-notes' );

    You can also specify only certain change events to log. See logging_enabled() for a list of available events.

    add_post_type_support( '[post type slug here]', 'wporg-log-notes', array( 'status-change' => true ) );

    Development

    Prerequisites

    • Docker
    • Node/npm
    • Yarn
    • Composer

    Setup

    1. Set up repo dependencies: yarn run initial-setup
    2. Start up and provision the environment: yarn run env
    3. Build the assets: yarn workspaces run build. The plugin won’t function until this step is done.
    4. Visit site at localhost:8888
    5. Log in with username admin and password password

    Environment management

    These must be run in the project’s root folder, not in theme/plugin subfolders.

    • Stop the environment: yarn run env:stop or yarn run wp-env stop
    • Restart the environment: yarn run env or yarn run wp-env start

    Asset management

    • Build all assets once: yarn workspaces run build
    • Rebuild all assets on change: yarn workspaces run start

    Visit original content creator repository
    https://github.com/WordPress/wporg-internal-notes

  • OTP-Raspberry-Pi

    Generatore chiavi casuali

    È stato pensato per monitorare i dati ambientali attraverso una raspberry ed introdurre l’entropia sufficiente nel programma.

    Quello che viene eseguito è un ciclo infinito per incrementare una variabile in un range fissato e leggere lo stato della variabile
    quando si verificano le condizioni ambientali stocastiche come piccole variazioni della pressione atmosferica.

    Viene cosi prodotta una sequenza casuale, dimostrabile attraverso l’istogramma delle frequenze si osservano solo distribuzioni uniformi sulle chiavi generate.

    One-Time-Pad

    È il tentativo di implementare un cifrario a flusso di tipo OTP attraverso il fix delle falle crittografiche del noto RC4, cercando di far coesistere la sicurezza dei cifrari OTP alla praticità dei cifrari più moderni come AES.

    Un cifrario OTP è un cifrario perfetto perchè è matematicamente sicuro.

    L’idea di base è quella di usare il cifrario Vigenere, insicuro di per sè, ed imporre particolari condizioni sulle chiavi per creare un nuovo cifrario, di tipo OTP, chiamato Vernam.

    Le condizioni sono:

    1. chiave crittografica lunga quanto il testo in chiaro
    2. casualità della chiave
    3. ad ogni testo in chiaro da cifrare deve corrispondere una chiave diversa (One Time Pad)

    Il cifrario cosi definito resiste anche al bruteforce delle chiavi con potenza di calcolo infinita, perchè implementa il concetto di crittografia negabile, in quanto nel processo di crittoanalisi si estrarrebbero tutti i possibili testi di senso compiuto e non si potrebbe dire quale messaggio sia stato veramente scambiato.

    sincVernam.py

    In sincVernam.py non si usa la matrice di Vigenere per la codifica ma l’operatore XOR per estendere l’alfabeto a tutti i char.

    Essendo il cifrario Vernam di difficile implementazione per l’onerosa gestione delle chiavi, si cerca di adottare dei compromessi.

    Il processo di crittografia è il seguente:

    1. richiesta di una password
    2. generazione dell’hash crittografico della password da usare come seed
    3. inizializzazione di un generatore di numeri peseudocasuali crittograficamente sicuro usando l’hash precedente come seed
    4. generare una sequenza di numeri pseudocasuali ma crittograficamente sicura da usare come chiave crittografica
    5. eseguire lo XOR tra testo in chiaro e chiave crittografica
    6. incrementare un contatore da appendere alla password iniziale per generare chiavi crittografiche sempre diverse
    7. iterare i passaggi precedenti su messaggi in chiaro nuovi

    Vengono quindi soddisfatte tutte le condizioni del cifrario Vernam:

    1. la prima implementando un generatore che garantisce la lunghezza della chiave con il minimo sforzo
    2. la casualità non c’è per consentire di ricavare le chiavi crittografiche a partire da una password, ci si avvicina alla sicurezza OTP per l’uso di un generatore pseudocasuale crittograficamente sicuro
    3. per ogni nuovo messaggio in chiaro viene derivata una nuova chiave crittografica impossibile da ricavare senza conoscere la password iniziale

    Inoltre viene calcolato un hash di integrità del messaggio ed appeso al testo cifrato.

    Si potrebbe anche appendere alla fine del testo cifrato il contatore per garantire la sincronia e poter correggere errori di sincronizzazione nel caso in cui qualche messaggio venga perso. Il valore di questo contatore può essere pubblico svolgendo il ruolo logico di salt crittografico per la derivazione di nuove password.

    Viene anche impostato un tempo di delay casuale di elaborazione dentro alle varie funzioni per mitigare attacchi di timing ed è aggiunto al messaggio in chiaro un timestamp con data e ora della cifratura per mitigare gli attacchi di replica.

    Crittoanalisi

    1. L’unica crittoanalisi nota è sulla password, punto in cui il cifrario è più vulnerabile ad attacchi di bruteforce per esempio, ritenuti mitigabili però attraverso la forza della password scelta come per altri cifrari ritenuti sicuri come AES. Si consiglia di usare il cifrario all’interno di adeguati standard e protocolli sulla gestione delle password.

    2. La crittografia negabile si ottiene trasformando il cifrario a flusso in un cifrario a blocchi che contengano un numero di char in chiaro uguali a quelli del digest dell’algoritmo di hashing crittografico usato, come per esempio sha512, e la derivazione di nuovi hash per ogni blocco di testo in chiaro.

    OTP.py

    Il programma riprende la versione fixata di sincVernam.py ed aggiunge la possibilità di usare, oltre ad una password, un file di dati casuali come chiave crittografica, bypassando a derivazione delle chiavi generate con un generatore pseudocasuale.

    La generazione di chiavi pseudocasuali subentra nel momento in cui viene esaurito il file usato come chiave crittografica, perchè ad ogni byte di messaggio cifrato o decifrato corrisponde una riduzione di un byte del file chiave tramite il suo troncamento, evitandone il reimpiego e garantendo la sicurezza OTP.

    L’uso sicuro richiede lo sviluppo di un protocollo ed un framework all’interno del quale avviene la gestione delle chiavi casuali e della sincronizzazione delle comunicazioni.

    Visit original content creator repository
    https://github.com/ScratchyCode/OTP-Raspberry-Pi

  • Common

    NuGet Tests Tests

    Logo

    Narumikazuchi

    This library contains some small utilities that I would use occasionaly but don’t really fit a certain category. Some of my other libraries also use these types so they basically have been moved to a package for them to share and use.

    Table of Contents

    Installation

    Just add a reference the the package and add the appropriate using statement using Narumikazuchi.

    dotnet add package Narumikazuchi
    

    Types & Usage

    Types

    AlphanumericVersion

    This struct provides all the same functionality that is also provides by the System.Version class but additionally provides the ability to use alphabetic characters as well as a -(dash) character in the version descriptor. With this, version descriptors like 1.0-alpha1 or rc3-1.0.0 are possible.

    AttributeResolver

    The AttributeResolver static class is a simple wrapper around the System.Reflection methods that are used to get specific Attribute classes from assemblies, types, methods, properties, fields or parameters, that are decorated with them. The results of the member methods will get cached and improve performance for the next time the method is called with the same parameter.

    HasAttribute<TAttribute> will check whether or not the object reflected by the passed parameter is decorated with an attribute of type TAttribute and will return true if at least one attribute of that type is found and otherwise false.

    static public System.Boolean HasAttribute<TAttribute>(System.Reflection.Assembly assembly)
        where TAttribute : System.Attribute;
    static public System.Boolean HasAttribute<TAttribute>(System.Reflection.MemberInfo info)
        where TAttribute : System.Attribute;
    static public System.Boolean HasAttribute<TAttribute>(System.Reflection.ParameterInfo info)
        where TAttribute : System.Attribute;

    FetchFetchAllAttributes<TAttribute> will collect all instances of the attributes of type TAttribute the object reflected by the passed parameter is decorated with and return them as an ImmutableArray<TAttribute> to the caller.

    static public System.Collections.Immutable.ImmutableArray<TAttribute> FetchAllAttributes<TAttribute>(System.Reflection.Assembly assembly)
        where TAttribute : System.Attribute;
    static public System.Collections.Immutable.ImmutableArray<TAttribute> FetchAllAttributes<TAttribute>(System.Reflection.MemberInfo info)
        where TAttribute : System.Attribute;
    static public System.Collections.Immutable.ImmutableArray<TAttribute> FetchAllAttributes<TAttribute>(System.Reflection.ParameterInfo info)
        where TAttribute : System.Attribute;

    FetchFetchSingleAttribute<TAttribute> might fail with an NotAllowed exception if the object reflected by the passed parameter is not decorated with an attribute of type TAttribute or if [AttributeUsage(..., AllowMultiple = true)]class TAttribute {...}. Otherwise this method will return the only instance of TAttribute the parameter is decorated with.

    static public TAttribute FetchSingleAttribute<TAttribute>(System.Reflection.Assembly assembly)
        where TAttribute : System.Attribute;
    static public TAttribute FetchSingleAttribute<TAttribute>(System.Reflection.MemberInfo info)
        where TAttribute : System.Attribute;
    static public TAttribute FetchSingleAttribute<TAttribute>(System.Reflection.ParameterInfo info)
        where TAttribute : System.Attribute;

    EqualityComparison<TComparable>

    This delegate got added since there is a System.Comparison<T> delegate to compare for ordering for types that do not implement the System.IComparable<T> interface but no delegate as equivalent for types that do not implement the System.IEquatable<T> interface.
    This might get deprecated once .NET 9 is out with the increases utility for extension methods, since the last time I checked you could just ‘extend’ a type to implement an interface that the original type currently does not, which would make this delegate basically useless. You can look here if you don’t know what I’m talking about.

    EventHandler<TSender> and EventHandler<TSender, TEventArgs>

    I added these delegates since the integrated System.EventHandler and System.EventHandler<T> delegates use the System.Object type for the sender in the method signature. With these 2 new delegates the will be no need to seperately cast the sender parameter on the delegate.

    FailedInitialization

    Sometimes you decide to use a struct instead of a class not because of the ‘value-type’ nature of what you want to implement, but rather the performance that it can bring, especially when the resulting struct in unmanaged. However that might also mean that the struct might be in an invalid state, due to being created with the default expression. This was the motivation behind this exception. However due to how it is named it can also be used in other scenarios and can provide literal feedback just through it’s name alone that something during initialization of something failed.

    ImpossibleState

    This one is mainly an exception for code readability. It might not happen often, but there are times when you just need to satisfy the compiler by throwing an exception while knowing fully well, that this exception will never get hit.

    INotifyPropertyChangedHelper and INotifyPropertyChangingHelper

    The origin of these interfaces was when I started implementing extension methods for collections. Because there were observable collections among them I needed a way to trigger the PropertyChanged and PropertyChanging events from outside of the class or struct. Right now I think this is bad design and am contemplating whether to deprecate these interfaces or not, but for now the are still here I guess.

    NotAllowed

    My motivation for this exception is simple readability. Sometimes it is just easier when the first word you are reading already tells you what the problem was. I’m also aware that readability is subjective. I personally don’t like the suffix ‘Exception’ because there is no other class or struct you can use in a throw statement and with the correct naming you can easily understand what problem occured. The name might also not be quite ideal for now, so it might change in the future. I’m alway open for suggestions on that part.

    Pointer<TAny>

    In rare cases one might need a pointer in C#, but who likes enabling unsafe context just for a few lines for the whole assemply? This struct provides a managed way to use pointers. It implicitly casts from and to System.IntPtr, System.UIntPtr and an unsafe pointer type. It provides the ability to go through an array-like structure, meaning you can perform pointer-arithmetic on it. This is obviously still highly unsafe if used uncorrectly, so use with care.

    The AddressOf method serves as the primary way to construct a Pointer<TAny> struct. Use this to get the pointer to any object you need the pointer of.

    static public Pointer<TAny> AddressOf(ref TAny t);

    If for some reason you only have regular pointers, you can transform them into a Pointer<TAny> with on of these constructors.

    public Pointer(void* pointer);
    public Pointer(IntPtr pointer);
    public Pointer(UIntPtr pointer);

    Using the indexer will offset the pointer. The offset will be index * the width of the pointer. This basically only useful for scanning arrays.

    public TAny this[Int32 index];

    Incase you need the address of the pointer you can get it with the Address property. But then again, you can also just implicitly cast it, if you want to.

    public System.UIntPtr Address
    {
        get;
    }

    Through this property you can get or set the value of the object at the pointers address. Be careful not to set any data where it doesn’t belong.

    public TAny Value
    {
        get;
        set;
    }

    Extensions

    IComparable<TComparable>

    Instead of only having Math.Clamp for primitive numeric types you can now use the SystemExtension.Clamp<TComparable> method on every class or struct that implements the System.IComparable<T> interface.

    static public TComparable Clamp<TComparable>(this TComparable value, 
                                                 TComparable lowerBoundary,
                                                 TComparable higherBoundary) 
        where TComparable : System.IComparable<TComparable>;

    There are also 3 methods to check for boundaries and throw an ArgumentOutOfRangeException should the object not be within the specified bounds. Be aware that all of these methods expect neither the source nor boundary, lowerBoundary or higherBoundary to be null.

    static public void ThrowIfLesserThan<TComparable>(this TComparable source,
                                                      TComparable boundary,
                                                      System.String message = default,
                                                      [CallerArgumentExpression(nameof(source))] System.String? paramName = "")
        where TComparable : System.IComparable<TComparable>;
    static public void ThrowIfBiggerThan<TComparable>(this TComparable source,
                                                      TComparable boundary,
                                                      System.String message = default,
                                                      [CallerArgumentExpression(nameof(source))] System.String? paramName = "")
        where TComparable : System.IComparable<TComparable>;
    static public void ThrowIfOutOfRange<TComparable>(this TComparable source,
                                                      TComparable lowerBoundary,
                                                      TComparable higherBoundary,
                                                      System.String message = default,
                                                      [CallerArgumentExpression(nameof(source))] System.String? paramName = "")
        where TComparable : System.IComparable<TComparable>;

    String

    If you have a string and want to use it as a filename while either expecting or not knowing if it contains invalid characters to be used as filename, then you can use SystemExtension.SanitizeForFilename. This will just omit any invalid characters from the resulting string, so that it can be used as filename.
    This will either get superceded by the planned FilePath type or it will get expanded upon with another overload to specify a character to replace an invalid one.

    static public String SanitizeForFilename(this String raw);

    You can also use an extension method to check whether the System.String is null or whitespace. There are plans to improve the workings for this method but for now it can either throw an ArgumentNullException or a NullReferenceException depending on whether the asArgumentException parameter is set or not.

    static public void ThrowIfNullOrEmpty(this System.String? source,
                                          System.String message = default,
                                          Boolean asArgumentException = default,
                                          [CallerArgumentExpression(nameof(source))] System.String? varName = "")

    Types (Deprecated)

    Converter<TResult> and IConvertible<TResult>

    The Converter<TResult> static class was originally planned to an easy one-liner for conversion of a type that implements the IConvertible<TType> interface. There is now a ‘Narumikazuchi.Generators.Convertibles’ source generator in the works which will supercede the Converter<TResult> class and IConvertible<TType> interface.

    ExceptionInformation and FunctionCallInformation

    These types were originally supposed to help with logging and analyzing failures in an application. However I never found myself actually using them or even thinking of their usefulness. Thus I have made the decision, that the current functionality of exceptions is enough to analyze any failures in logging.

    Extensions (Deprecated)

    Exception

    There was just an extension method ExtractInformation(this Exception source), whose job was to access the ExceptionInformation which was supposed to make exception more logging-friendly and readable. Since that type is now deprecated the method is also no longer needed.

    For Contributors

    • Group files into folders with either similar meaning or covering topics of a similar namespace (i.e. Reflection)
    • DO NOT add sub-namespaces even for files in folders. The entire project used one namespace unless explicitly stated otherwise
    • Only one type per file
    • Filenames should equal the typename. If the type is generic use the following naming scheme Typename`NumberOfTypeParameters.cs
    • Keep files to less than 300 lines of code
    • Only 1 method call per line. If you chain method calls, align them at the dot (.) of the previous method call
    • Split compilation units into multiple files if the type for that CU implements interfaces. Create a file for each implemented interface with the naming scheme of Typename.Interface`NumberOfTypeParameters.cs, if the type is non-generic the backtick (`) and the number of type parameters should be omitted
    • Should the number of lines for private members and their implementations exceed 25 lines create a file with the naming scheme Typename.Private.cs and move private members into there
    • Should the type contain nested types create a seperate file for the nested type with the naming scheme Typename.NestedTypename.cs
    • Use #pragma to supress undesired warnings
    • DO NOT add using System.* to a file. Add usings from the System namespace and it’s sub-namespaces into the .csproj file under <ItemGroup><Using Include="System.*" /></ItemGroup> at the bottom of the file
    • Provide tests for every implemented type. Use sentence-like naming to express what is expected to happen given specific circumstances (i.e. class A_foo.should_return_42.if_instantiated_using_bar())
    • Tests should be implemented in the Tests project. Group the tests for your types according to where or for what it is expected to be used
    • Provide benchmarks for every implemented type. If applicable provide comparisons to native functionality.
    • Benchmarks should be implemented in the Benchmarks project. Group the benchmarks for your types in the same way they are grouped in the main project

    Benchmarks

    The Benchmarks project should be set as the default startup project in visual studio. Since there is no Debug configuration for the project you can just start the project directly from the IDE.
    Alternatively you can run the benchmarks using the CLI:

    dotnet run --project **YOUR_SOLUTION_LOCATION**/Benchmarks/Benchmarks.csproj
    

    Roadmap

    Latest Changelog 6.1.3

    • Added a StaticEventHandler<TEventArgs> delegate for static classes or just events where the sender is irrelevant
    • Added an overload for SanitizeForFilename(this String raw) where you can pass in the System.Char that replaces invalid characters instead of just omitting them
    • Added a FilePath type which checks and replaces invalid characters in a string directly
    • Added a ConstrainToImplementationAttribute which can mark a type parameter in an interface to force it’s implementation as type argument
    • Added an IInlineArray<TSelf, TElement> interface and a InlineArray<TElement> helper class for use with inline arrays (this is just the bare minimum, this will be expanded upon)
    • Added rust-like monad types Optional<TAny>, Result<TResult>, Result<TResult, TError> for better code quality

    Roadmap for 6.2.x

    The following actions are planned for the upcoming version 6.2.x:

    • Implement more granular versions of the ThrowIfNullOrEmpty extension method for System.String
    • Check for performance improvements in SanitizeForFilename(this String raw) and AttributeResolver
    Visit original content creator repository https://github.com/Narumikazuchi/Common