Blog

  • acf-conditional-logic-advanced

    === ACF Conditional Logic Advanced ===
    Contributors: andrej.pavlovic
    Tags: acf, advanced custom fields, acf-field, conditional logic
    Requires at least: 3.6.0
    Tested up to: 4.9.9
    License: GPLv2
    License URI: http://www.gnu.org/licenses/gpl-2.0.html
    
    Adds an Advanced Conditional Logic field setting to ACF that can show/hide individual fields based on post template, format, and/or category.
    
    = Links =
    * [Website](https://github.com/andrejpavlovic/acf-conditional-logic-advanced)
    * [Support](https://github.com/andrejpavlovic/acf-conditional-logic-advanced/issues)
    * [Advanced Custom Fields](https://www.advancedcustomfields.com/)
    
    == Screenshots ==
    
    1. Post Category options
    2. Advanced Conditional Logic field setting options: Template, Format, Category
    
    == Changelog ==
    
    = 1.1.3 =
    * Small fix to prevent acf-input category check from throwing errors when editing menus
    
    = 1.1.2 =
    * Small fix for Yes/No when editing Field in Field Group
    * Tested with ACF 5.7.7
    
    = 1.1.1 =
    
    * Don't display Conditional Logic Advanced row when field type is "Clone".
    
    = 1.1.0 =
    * Added support for custom taxonomies.
    * Added support for non-hierarchical taxonomies. (e.g. Tags)
    * Reorganized the Post Template dropdown options.
    
    = 1.0.3 =
    * composer.json - fixed version
    
    = 1.0.2 =
    * composer.json - fixed name
    
    = 1.0.1 =
    * Added composer.json
    
    = 1.0.0 =
    * Initial release.
    

    Visit original content creator repository
    https://github.com/andrejpavlovic/acf-conditional-logic-advanced

  • acf-conditional-logic-advanced

    === ACF Conditional Logic Advanced ===
    Contributors: andrej.pavlovic
    Tags: acf, advanced custom fields, acf-field, conditional logic
    Requires at least: 3.6.0
    Tested up to: 4.9.9
    License: GPLv2
    License URI: http://www.gnu.org/licenses/gpl-2.0.html
    
    Adds an Advanced Conditional Logic field setting to ACF that can show/hide individual fields based on post template, format, and/or category.
    
    = Links =
    * [Website](https://github.com/andrejpavlovic/acf-conditional-logic-advanced)
    * [Support](https://github.com/andrejpavlovic/acf-conditional-logic-advanced/issues)
    * [Advanced Custom Fields](https://www.advancedcustomfields.com/)
    
    == Screenshots ==
    
    1. Post Category options
    2. Advanced Conditional Logic field setting options: Template, Format, Category
    
    == Changelog ==
    
    = 1.1.3 =
    * Small fix to prevent acf-input category check from throwing errors when editing menus
    
    = 1.1.2 =
    * Small fix for Yes/No when editing Field in Field Group
    * Tested with ACF 5.7.7
    
    = 1.1.1 =
    
    * Don't display Conditional Logic Advanced row when field type is "Clone".
    
    = 1.1.0 =
    * Added support for custom taxonomies.
    * Added support for non-hierarchical taxonomies. (e.g. Tags)
    * Reorganized the Post Template dropdown options.
    
    = 1.0.3 =
    * composer.json - fixed version
    
    = 1.0.2 =
    * composer.json - fixed name
    
    = 1.0.1 =
    * Added composer.json
    
    = 1.0.0 =
    * Initial release.
    

    Visit original content creator repository
    https://github.com/andrejpavlovic/acf-conditional-logic-advanced

  • report-task

    Build and DeploycodecovKnown Vulnerabilities

    Report Task

    This repository contains the implementation for a containerized Spring Cloud Task. The task generates reports by getting the relevant data from our MDM, compiling a PDF and uploading it to the MDM. Currently the task is started by the MDM via the AWS Fargate API and the MDM sends an E-Mail on task completion.

    Developers

    Developers need to have at least maven and docker on their machines. Currently you need to install java 15 sdk on your system. On Ubuntu you should use SDKMAN!.

    The following environment variables have to be set for running the JUnit test:

    MDM_ENDPOINT=https://dev.metadata.fdz.dzhw.eu
    MDM_TASK_USER=taskuser
    MDM_TASK_PASSWORD=**** (see s3://metadatamanagement-private/sensitive_variables.tf)

    The docker image can be build with:

    mvn -Pdev clean install

    If you want to run the task against an MDM instance running on your local machine, you can run:

    docker run -it --network=host dzhw/report-task java -jar /app/report-task.jar --task.id=dat-gra2005-ds2$ --task.version=1.2.3 --task.onBehalfOf=dataprovider --task.language=de --task.type=DATA_SET_REPORT --mdm.username=${MDM_TASK_USER} --mdm.password=${MDM_TASK_PASSWORD} --mdm.endpoint=http://127.0.0.1:8080

    For further configuration options you should get familiar with Spring Boot @ConfigurationProperties and have a look into src/main/java/eu/dzhw/fdz/metadatamanagement/tasks/reporttask/config.

    Template Editing

    The latex files which are compiled within this task are generated with FreeMarker. The templates can be edited under /src/main/resources/template/. Changes to the latex styles and images can be made here: /latex-packages/doc/

    Continous Integration

    Every commit to the branches development, test or master will be pushed to Amazon ECR. Github Actions are used for executing the build and pushing to AWS.

    Issues

    If you find any issues or have questions regarding this task, feel free to file an issue in our MDM.

    Visit original content creator repository https://github.com/dzhw/report-task
  • report-task

    Build and DeploycodecovKnown Vulnerabilities

    Report Task

    This repository contains the implementation for a containerized Spring Cloud Task. The task generates reports by getting the relevant data from our MDM, compiling a PDF and uploading it to the MDM. Currently the task is started by the MDM via the AWS Fargate API and the MDM sends an E-Mail on task completion.

    Developers

    Developers need to have at least maven and docker on their machines. Currently you need to install java 15 sdk on your system. On Ubuntu you should use SDKMAN!.

    The following environment variables have to be set for running the JUnit test:

    MDM_ENDPOINT=https://dev.metadata.fdz.dzhw.eu
    MDM_TASK_USER=taskuser
    MDM_TASK_PASSWORD=**** (see s3://metadatamanagement-private/sensitive_variables.tf)

    The docker image can be build with:

    mvn -Pdev clean install

    If you want to run the task against an MDM instance running on your local machine, you can run:

    docker run -it --network=host dzhw/report-task java -jar /app/report-task.jar --task.id=dat-gra2005-ds2$ --task.version=1.2.3 --task.onBehalfOf=dataprovider --task.language=de --task.type=DATA_SET_REPORT --mdm.username=${MDM_TASK_USER} --mdm.password=${MDM_TASK_PASSWORD} --mdm.endpoint=http://127.0.0.1:8080

    For further configuration options you should get familiar with Spring Boot @ConfigurationProperties and have a look into src/main/java/eu/dzhw/fdz/metadatamanagement/tasks/reporttask/config.

    Template Editing

    The latex files which are compiled within this task are generated with FreeMarker. The templates can be edited under /src/main/resources/template/. Changes to the latex styles and images can be made here: /latex-packages/doc/

    Continous Integration

    Every commit to the branches development, test or master will be pushed to Amazon ECR. Github Actions are used for executing the build and pushing to AWS.

    Issues

    If you find any issues or have questions regarding this task, feel free to file an issue in our MDM.

    Visit original content creator repository https://github.com/dzhw/report-task
  • Design-Patterns

    Design Patterns

    This repository contains examples and notes for design patterns. It is aimed at helping developers understand, apply, and practice design patterns in real-world scenarios.


    🚀 Features

    • Beginner-Friendly: Simple explanations for each pattern without unnecessary complexity.
    • Organized Structure: Patterns are categorized into Creational, Structural, and Behavioral groups.

    📂 Repository Structure

    design-patterns/
    ├── creational/
    │   ├── singleton/
    │   ├── factory/
    |   ├── abstractfactory/
    |   ├── prototype/
    │   └── builder/
    ├── structural/
    │   ├── adapter/
    │   ├── bridge/
    │   └── decorator/
    └── behavioral/
        ├── strategy/
        ├── observer/
        └── state/
    

    Each folder contains:

    • README.md: Explanation and use case for the pattern.

    🎯 Goals

    • Learn: Deepen your understanding of design patterns.
    • Practice: Write in your prefered language following best practices.
    • Apply: Integrate patterns into your projects effectively.

    🛠️ Getting Started

    1. Clone the repository:

      git clone https://github.com/bytewhisperer11/design-pattern
      cd design-pattern
    2. Navigate to a specific pattern folder to review the code and explanation.

    📖 List of Patterns

    Creational Patterns

    • Singleton
    • Factory
    • Builder

    Structural Patterns

    • Adapter
    • Bridge
    • Decorator

    Behavioral Patterns

    • Strategy
    • Observer
    • State

    🤝 Contributing

    Contributions are welcome!
    If you have an idea for improvement or a new pattern to add, feel free to fork the repository and submit a pull request.


    📜 License

    This project is licensed under the MIT License.


    📧 Contact

    For questions or suggestions, feel free to reach out:
    GitHub Profile


    🚧 Work in Progress

    This repository is a work in progress. New patterns, examples, and notes are being added every now and then.
    Keep following to stay updated!

    Visit original content creator repository
    https://github.com/bytewhisperer11/Design-Patterns

  • TGP_Del

    Librairie TGP Del

    Permet le contrôle d’une diode électroluminescente (DEL) pour Arduino. Outre son état, on peut la mettre en mode clignotant, ajuster le délai et modifier son intensité lumineuse. Son mode de fonctionnement est non-bloquant.

    Il existe deux classes : DelPin.h pour une DEL branchée sur une broche, et Del.h, pour contrôler une DEL virtuelle où l’utilisateur aura la responsabilité de faire le contrôle matériel correspondant.

    Notes de version

    2.0.1 :

    • Uniformisation du pointeur de fonction pour toutes les plateformes.

    2.0.0 :

    • Refonte pour que Del gère les comportements virtuels et que DelPin gère une Del matérielle.
    • Permet l’utilisation de la Del générique via une fonction de référence;
    • Permet l’utilisation des fonctions lambdas
    • Mise à jour de la gestion des PWMs sur la version 3 de ESP32-Arduino
    • Permettre le fonctionnement (PWM) sur la version antérieure 2 de ESP32-Arduino

    Utilisation

    Voici l’exemple simple avec une DEL branchée sur une broche.

    #include <DelPin.h> 
    
    DelPin maDEL(LED_BUILTIN); 
    
    void setup()
    {
        maDel.on();
        maDel.setBlinking(true);
        maDel.setBlinkingInterval(250);
        maDel.setBrightness(100);
    }
    
    void loop()
    {
      maDEL.refresh();
    
    }

    Constructeurs

    Del()
    Del(SignalUpdater updater);

    Constructeur générique pour une DEL virtuelle, sans spécification matérielle. On peut aussi fournir une fonction qui aura la responsabilité de modifier matériellement la del; la fonction doit recevoir un float, qui correspond au pourcentage d’intensité voulu pour la

    DelPin(int pin)

    On spécifie le numéro de la broche sur lequel est branché la Del.

    Méthodes disponibles

    Méthodes de Del.h

     void refresh()

    Cette méthode doit être placée en début de boucle loop(): elle permet de mettre à jour l’état de la DEL sans bloquer l’exécution du reste de la boucle.


     void on()
     void off()

    Ces méthodes permettent respectivement d’allumer ou d’éteindre la del. Elles sont équivalentes à set(true) et set(false).


    void set(bool value) 
    bool get()

    Permet de lire et modifier l’état de la del (allumée ou éteinte).


    void setBlinking(bool value)
    bool getBlinking()

    Permet de lire et modifier le mode clignotement (activé ou non). Même si le mode clignotement est activé, cela n’allume pas pour autant la del.


    void setBlinkingInterval(unsigned long value)
    unsigned long getBlinkingInterval()

    Permet de lire et modifier le temps d’intervalle du clignotement, en millisecondes.


    void setBrightness(float value)
    float getBrightness()

    Permet de lire et modifier l’intensité lumineuse de la del, entre 0 et 100%. NOTE: Modifier l’intensité lumineuse supérieur à 0 ne va pas nécessairement allumer la DEL: il faut également faire appel à la méthode .on() ou .set(true).


    void setSignalUpdater(SignalUpdater updater)

    Permet de définir une fonction de mise à jour personnalisée pour la DEL. Cette fonction est appelée à chaque fois que la DEL est mise à jour. La fonction doit recevoir un float, qui correspond au pourcentage d’intensité voulu pour la del.

    Méthodes de DelPin.h


    void begin()

    Initialise la DEL. Cette méthode doit être appelée dans la fonction setup().


    int getPinNumber()

    Retourne le numéro de la broche sur laquelle la DEL est connectée.


    int getChannel()

    Retourne le numéro du canal PWM utilisé (uniquement pour les anciennes versions d’ESP32).


    int getAddress()

    Permet de lire le numéro de la broche utilisée lors de l’initialisation de l’objet pour la classe DelPin.

    Visit original content creator repository
    https://github.com/TechnoPhysCAL/TGP_Del

  • corporate_structure

    NodeJS NestJS RxJS Typeorm TypeScript Postgres Swagger JWT NPM Postman Git WebStorm

    Description

    A tiny server app based on Node.js (Nest.js). The app implements simple organization user structure management operations. The following user roles are supported: a. Administrator (top-most user, only he can change user roles); b. Boss (any user with at least 1 subordinate); c. Regular user (user without subordinates). Each user except the Administrator must have a boss (strictly one). The following REST API endpoints exposed:

    1. Register user.
    2. Authenticate as a user.
    3. Return list of users, taking into account the following:
    • administrator can see everyone;
    • boss can see herself and all subordinates (recursively);
    • regular user can see only himself.
    1. Change user’s boss (only boss can do that and only for his subordinates).

    Swagger documentation 📋

    Postman collections 📬

    Admin’s credentials 🔐

     filrsrtName: "Admin"
     lastName: "Admin"
     enail: "admin@gmail.com"
     password: "test"

    Installation ☕

    $ npm install
    or
    $ yarn install

    Setup environment on the Server🔧

    # development mode
    1. Create inside server dir file .env
    2. Copy content from .env.dist to .env
    3. Change the data in the .env file to required
    

    Migrations 🔧

    # generate migrations
    $ npm run migration:generate src/db/migrations/migration_name
    
    # run migrations
    $ npm run migration:run

    Seeding the database 🌱

    # seed table
    $ npm run seed:run
    

    Running the app 🚀

    # development
    $ npm run start
    
    # watch mode
    $ npm run start:dev
    
    # production mode
    $ npm run start:prod

    Running the app and the database in the Docker 🐋

    Change in the .env file variable 
    from 
    POSTGRES_HOST=localhost 
    to 
    POSTGRES_HOST=docker-host
    
    # build the container
    $ docker-compose build
    
    # start the container
    $ docker-compose up
    
    # stop the container
    $ docker-compose down
    Visit original content creator repository https://github.com/TarasMakarchuk/corporate_structure
  • Eth_Mining_Research_Report

    Personal Ethereum Mining Revenue Compared to Reported Average

    Andrew Keyes

    Bachelor of Arts in Experimental Psychology

    Department of Psychology, California State University, Stanislaus

    April 2022

    Abstract

    Study comparing the revenue of a personal Ethereum miner in US Dollars (USD) to the average rate of Ethereum mining revenue relative to megahash, over November 28th, 2021 to March 18, 2022. Average weekly Ethereum mining revenue rate in USD per megahash, weekly personal Ethereum revenue, and the price of 1 Ethereum was collected over 15 weeks to calculate average Ethereum mining revenue and personal mining revenue per week in USD. Results depict higher revenue in the average rate of Ethereum mining compared to the personal Ethereum miner relative to megahash.

    Introduction

    Ethereum (ETH) mining revenue is nothing new, yet still a practice new to so many. Blockchain technology provides operability of ETH’s network and has become a passion that I participate in through ETH mining. Revenue analysis of personal mining operations in comparison to the reported network average would reveal whether my machine outperformed the network in revenue relative to megahash. This study inspects the relationship of revenue in USD between the personal ETH miner and the reported ETH mining average.

    ETH is a cryptocurrency, currently operating under a Proof of Work (PoW) mechanism governed by the algorithm Ethash. PoW is a decentralized consensus protocol, in which miners: do the work- direct validation within the ETH ecosystem and provide proof of their work. ETH miners provide a “certificate of legitimacy” for transactions, balances, and market orders. The miner “independently agglomerates a set of valid transactions into a block and attempts to solve a predefined cryptographic puzzle as PoW, which involves data from the block and a specific prior block. The first miner to solve the problem broadcasts his solution to the network, and by virtue of the solution, is able to add the block to the ever-growing blockchain as a child of the prior block.” (Bissias et al., 2019)

    Anyone is capable of mining with a computer, internet connection, electricity, and money for graphic processing units (GPUs). Users can use this capacity for revenue to create profits through proper management of hashrate, electric rate, and power consumption.

    Hashrate is primarily dependent on the hardware used. Hashrate defines the miner’s performance rate, the higher the more revenue. “Based on the number of shares a miner submits over a specific time period, the miner’s hash rate can be derived. Hash rate refers to the number of unique attempted PoW solutions generated over a period of time” (Knottenbelt et al., 2018). A specific hashrate may earn less as more miners come online, and new components outdo prior models. This change is termed an ‘increase in network difficulty’, in turn reducing mining revenue.

    Electricity is a priority when computing profitability but disappears when it comes to revenue. It’s possible to earn revenue without profit, if the electric bill is larger than ETH payouts, you are paying more than you are earning. It’s important to compute electric rate and consumption when considering profit. The present study is concerned with revenue, not profitability, so electric consumption will not be considered.

    Many operating systems allow ETH mining, including Windows. While other operating systems are designed specifically for Proof of Work, like Hive OS. Miners are rewarded through participation, if a new block is solved/ created, two ETH are minted to the miner. Due to intense difficulty to participate in the worldwide network as a solo miner, most miners opt towards joining a mining pool (group mining). Countless pools exist, as well as payment methods to distribute among participating miners. Before having a pool to mine with mining software is required. Various options are widespread furthering decentralization in the network including Phoenix Miner, NBMiner, and GMiner.

    Revenue is acquired through block rewards and transaction fees. A block in ETH is a batch of transactions which allows for validation of dozens of transactions to be synchronized at once. Blocks contain a reference to its parent block, and all are chained together to the first genesis block. “Block time refers to the time it takes to mine a new block. In Ethereum, the average block time is between 12 to 14 seconds and is evaluated after each block.” (Smith, 2022)

    Understanding the relationship between personal ETH mining revenue and the reported ETH mining revenue average can help answer individual questions and concerns regarding mining’s value. For example, how average revenue trends relate to personal profits relative to hashrate, discover inefficient mining practices, and develop a deeper understanding of ETH mining difficulty to profitability. To fulfill the performance of a full-time miner, one must truly become a full-time miner. Meaning not taking away mining time from the machines. As a college student extraneous variables enter the situation making providing that of a full-time miner becomes distant. I hypothesize personal ETH miner revenue will perform lower overall in comparison to reported average ETH mining revenue.

    Methods

    Materials

    Around 170 megahash is reached by the personal ETH miner. Which consists of 4 GPU’s: 2x Nvidia GeoForce RTX 2080 8gb, and 2x Nvidia Geforce RTX 3060Ti LHR. Internet access is gained through a wired connection into a wireless router extender. The miner uses Hive OS to operationalize the machine, Nbminer as the miner, and Ethermine for the pool.

    Hive OS is a computer operating system optimized for mining of cryptocurrencies. Nbminer, one of many miners, provides extra efficiency for LHR cards making it an understandable miner option. Ethermine, the mining pool within this study, offers a PPLNS payout scheme, “Pay-Per-Last-N-Shares”. When a block is found the reward of each miner is calculated based on the participation to the last number of pool shares. Ethermine provides instant payouts as soon as the threshold of 0.005 ETH is met.

    BitInfoChart aggregates a historical chart of ETH’s mining profitability in USD per day for one megahash. Multiple timelines are available with daily data points from 3-months to 3-years to even all-time (7/30/15).

    Procedures

    15 weeks of personal mining revenue was gathered from November 28th, 2021 (Week 48, 2021) to March 18, 2022 (Week 12, 2022) with a mining rig averaging 170 megahash through Ethermine. Data was grouped weekly Sunday-Saturday, with the United States Dollar (USD) price of 1 ETH listed for the corresponding week. Revenue in ETH was multiplied with the price of 1 ETH each week to create a weekly estimate of personal miner revenue in USD.

    Reported average daily mining revenue collected on BitInfoChart was transformed into weekly revenue averages in USD per 1 megahash. To create an estimate of reported average mining revenue in USD relative to the hashrate output of the personal miner, weekly avg USD per 1 megahash was multiplied with 170.

    Results

    A Paired Samples T-Test conducted on SPSS comparing personal mining revenue in USD (M= 46.51, SD= 16.81, N= 16) and reported average revenue in USD (M= 58.23, SD= 15.12, N= 16) revealed a significant difference in revenue; t(15)= 6.1, p = .001. Results fail to reject the hypothesis; Personal ETH miner revenue will perform lower overall in comparison to reported average ETH mining revenue. Proving the personal miner is under performing based on the average reported revenue.

    TrendChart

    Visual analysis depicts clear discrepancies each week in ETH mining revenue between personal and reported rates. The initial revenue found in the first week, week 49 2021, is the closest the two values are throughout the whole study, a 0.58 cent difference. The line chart displays the downward trend of ETH mining revenue over the course of the study. Based on visual analysis, revenue is lower, and drops are more significant in personal mining than in the reported average.

    Discussion

    Findings revealed the expected hypothesis to be true, personal ETH miner revenue will be lower overall in comparison to the reported average ETH mining revenue. Revenue from mining is multifactorial, hardware could crash, electricity could be cut off, or internet connection could be lost.

    Lower revenue in personal mining can be linked to an unstable mining operation. Hive OS, the operating system used for my miner is known to randomly crash forcing a mandatory physical reset. Which could leave the miner not working for hours, increasing down-time rather than ETH. Additional crashes occur when rebooting the wifi router to clear cache and speed connection. This happens often and randomly, forfeiting away a lot of potential participation. Since the personal miner is also a workstation it’s necessary to turn off the miner when there’s tasks to complete. Graphic designing, video editing, report writing, and researching take precedence over mining ETH. Additionally, playing video games for a couple hours a week takes away from operational mining time. Low overclock settings may have influenced the decrease in revenue as well. These settings are set low for hardware safety and longevity, which may negatively affect returns. Crypto’s volatility could have played a big role, if the personal miner amassed a large amount of down time while the market was booming, a lot of potential revenue could have been lost.

    Results imply personal operations could be more efficient in terms of ETH mining in various measures. Whether it be up-time or hashrate, it is clear that there is still room to grow. This has shown how much potential revenue I have missed out on due to not maintaining a stable participation rate throughout the study.

    Cryptocurrency mining revenue is hot in the media and in the rooms they operate. Many will go to the greatest extent to receive maximum revenue. In the comparison of personal miner revenue and the reported ETH revenue rate, a distinction is made clear of those who maximize their ability to reap revenue mining ETH and those who don’t.

    References

    Bissias, G., Levine, B. N., Ozisik, A. P. (2019). Estimation of Miner Hash Rates and Consensus on Blockchains. Cornell University, Computer Science. https://doi.org/10.48550/arXiv.1707.00082

    Knottenbelt, W. J., Pritz, P. J., Werner, S. M., Zamyatin, A. (2019). Uncle Traps: Harvesting Rewards in a Queue-based Ethereum Mining Pool. VALUETOOLS 2019: 12th EAI International Conference on Performance Evaluation Methodologies and Tools, 127–134. https://doi.org/10.1145/3306309.3306328

    Smith, C., (2022, January 3) BLOCKS. Ethereum. https://ethereum.org/en/developers/docs/blocks/

    Visit original content creator repository https://github.com/akeyess/Eth_Mining_Research_Report
  • demo-ionic-tabs-back-button

    Demo: Ionic tabs + global pages with ion-back-button

    Ionic 4 project with a tab based layout and workarounds for the ion-back-button.
    The demo shows two ways how to navigate from a tabbed page to a ‘global’ page and back,
    without losing tab-states.

    Live Demo

    Getting Started

    git clone https://github.com/servrox/demo-ionic-tabs-back-button.git
    cd demo-ionic-tabs-back-button
    yarn
    ionic serve
    

    Solutions shown in demo

    First solution is a workaround that overcomes the problem.
    The second one is a fix which deals directly with the problem
    by using ion-back-button-tabs a custom ionic 4 component.

    1. Passing previous page (s. global-page-one)

    This solution overcomes the problem by using an ion-button instead of the ion-back button.
    To make it work following steps are necessary:

    1. Get the route you want to navigate back later.
    this.currentRoute = btoa(this.router.url);
    
    1. Pass that value to the page called. (url params used here)

    <ion-button 
        [routerLink]="['/global-page-one', {p: currentRoute}]"
        routerDirection="forward">
        Global Page One
    </ion-button>
    
    1. On the page called check if a route was given
    this.previousPage = this.route.snapshot.paramMap.get('p') ? atob(this.route.snapshot.paramMap.get('p')) : null;
    
    1. Use given route when user clicks back
    back() { this.navCtrl.navigateBack(this.previousPage); }
    

    To make the ion-button look exactly like the ion-back-button, you can check which platform is being used.

    this.showText = this.plt.is('ios');
    

    If the page with the back-button is the first page called, the real ion-back-button can be used. This works because then the defaultHref is taken.

    this.router.events.subscribe((event: RouterEvent) => {
        if (event instanceof NavigationEnd) { 
            this.useRealBackButton = event.id === 1; 
        }
    });
    

    Final solution looks like this in template:

    <ion-buttons slot="start">
        <ion-back-button *ngIf="useRealBackButton" 
            [defaultHref]="previousPage ? previousPage : "https://github.com/tabs/tab1"">
        </ion-back-button>
        <ion-button *ngIf="!useRealBackButton" (click)="back()">
            <ion-icon name="arrow-back"></ion-icon>
            {{ showText ? 'Back' : null }}
        </ion-button>
    </ion-buttons>
    

    In this solution swiping back (iOS gesture) is disabled for the particular page.

    ngOnInit() { this.routerOutlet.swipeGesture = !this.plt.is('ios');
      [...]
    ionViewDidLeave() { this.routerOutlet.swipeGesture = this.plt.is('ios'); }
    

    ion-back-button-tabs supports swiping back! (see below)

    2. Using ion-back-button-tabs component (s. global-page-two)

    1. Install from npm
    npm i ion-back-button-tabs --save
    
    1. Import BackButtonTabsModule to the page module (global-page-two.module.ts)

    import { NgModule } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { FormsModule } from '@angular/forms';
    import { Routes, RouterModule } from '@angular/router';
    import { IonicModule } from '@ionic/angular';
    
    import { GlobalPageTwoPage } from './global-page-two.page';
    
    import { BackButtonTabsModule } from 'ion-back-button-tabs';
    
    const routes: Routes = [
      {
        path: '',
        component: GlobalPageTwoPage
      }
    ];
    
    @NgModule({
      imports: [
        CommonModule,
        FormsModule,
        IonicModule,
        RouterModule.forChild(routes),
        BackButtonTabsModule
      ],
      declarations: [GlobalPageTwoPage]
    })
    export class GlobalPageTwoPageModule { }
    
    1. Get attributes for ion-back-button-tabs
    • tabsPrefix is the url path set for the TabsPage component (e.g. ‘tabs’)

    import { NgModule } from '@angular/core';
    import { RouterModule, Routes } from '@angular/router';
    import { TabsPage } from './tabs.page';
    
    const routes: Routes = [
      {
        path: 'tabs',
        component: TabsPage,
        children: [
          {
            path: 'tab1',
            children: [
              {
                path: '',
                loadChildren: '../tab1/tab1.module#Tab1PageModule'
              }
            ]
          },
          {
            path: 'tab2',
    ...
    
    • tabsPageSelector is the selector of the TabsPage component (e.g. ‘app-tabs’)

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'app-tabs',
      templateUrl: 'tabs.page.html',
      styleUrls: ['tabs.page.scss']
    })
    export class TabsPage {}
    
    
    1. Use ion-back-button-tabs in template

    <ion-back-button-tabs 
      defaultHref="https://github.com/tabs/tab1" 
      tabsPrefix="tabs" 
      tabsPageSelector="app-tabs">
    </ion-back-button-tabs>
    

    Problem explained

    When navigating from a page inside a tab to a ‘global’ page,
    the ion-back button will no longer work properly.
    More specifically, the back button no longer navigates to the previously opened page, instead it uses the redirect of the tabs-routing.
    This happens because the ion-back-button uses only the main-IonRouterOutlet, instead of also checking tabs-IonRouterOutlet.
    Which means that the StackController inside the main-IonRouterOutlet only knows the route of the tabs module (e.g. ‘tabs’).
    ^No guarantee on this^
    Problem is also described in the official Bug Report.

    Built With

    Authors

    Visit original content creator repository
    https://github.com/servrox/demo-ionic-tabs-back-button

  • monetary

    monetary

    A library to handle currencies and money. Targeted at blockchain and cross-chain applications.

    About

    Building systems with money is pretty hard. Especially when the monetary amounts that the application has to deal with uses different decimal representations, has numerous accounting units, and the same currency exists on multiple chains.

    To tackle these issues, this library serves as a common interface to deal with monetary amounts in a safe and predictable way.

    Objectives

    The overall goal of this library is two-fold:

    1. Provide a secure currency interface. This includes safe arithmetic, type checking to ensure conversions between currencies are done correctly, and correct rounding.
    2. Provide a universal currency interface. The interface should be able to have an identifiable name and ticker, and an “origin”.

    Specification

    We provide a light-weight specification to establish a common set of rules for the monetary library. Please check the specification for more details.

    References

    • A good portion of this specification was inspired by this excellent post on safe-money.
    • There is also a great library for fiat currencies called dinero.js based on this post.

    Library

    Getting started

    Install from npmjs:

    npm i @interlay/monetary-js

    Or

    yarn add @interlay/monetary-js

    Usage

    Assuming that the library already provides the currencies you require, you can readily use them as indicated below.
    You may also add your own currencies without having to make an upstream contribution as explained in the defining your own currencies section.

    import Big from "big.js";
    import { Bitcoin, Ethereum, BitcoinAmount, EthereumAmount, ExchangeRate} from "@interlay/monetary-js";
    
    const bitcoins = new BitcoinAmount(0.5);
    const ethers = new EthereumAmount(new Big(1).mul(10).pow(-9)); // one gwei
    const sameEthers = new EthereumAmount("1e-9"); // also one gwei
    
    // conversions to string and Big of different units
    console.log(`We have ${bitcoins.toString()} BTC, and ${ethers.toString()} ethers.`);
    
    const weiBig: Big = ethers.toBig(0); // value in atomic units (ETH * 10^-18 aka. wei)
    const gweiBig: Big = ethers.toBig(9); // value in gwei (wei * 10^9)
    const alsoEthBig: Big = ethers.toBig(18); // value in eth (wei * 10^18)
    const ethBig: Big = ethers.toBig(); // value in eth (no parameter => assumes "natural" denomination)
    
    const satoshiString: string = bitcoins.toString(true); // value as string in atomic units (satoshi)
    const btcString: string = bitcoins.toString(); // value as string in "natural" units (btc)
    
    // converting between different currencies
    const ETHBTCRate = new ExchangeRate<Ethereum, Bitcoin>(
      Ethereum,
      Bitcoin,
      new Big(0.0598)
    );
    
    // for ETH/BTC, "base" is ETH, "counter" is BTC
    const bitcoinsAsEthers: EthereumAmount = ETHBTCRate.toBase(bitcoins);
    
    // type-safe arithmetic
    const totalEthers = ethers.add(bitcoinsAsEthers);
    // ethers.add(bitcoins); // error

    Defining your own currencies

    Monetary-js comes with Bitcoin, Ethereum and Polkadot predefined, but it is meant to be extensible for any currency. src/currencies/bitcoin.ts can be used as an example for the minimal work needed to define a currency. Another example is DummyCurrency defined inline for unit tests in test/monetary.test.ts

    The first step is to define our currency, parametrising the type with decimals.

    export const Bitcoin: Currency<typeof BitcoinUnit> = {
      name: "Bitcoin",
      ticker: "BTC",
      decimals: 8,
      humanDecimals: 5
    } as const;
    export type Bitcoin = typeof Bitcoin;

    For a MonetaryAmount, the internal representation will be stored with a 10 to the power of decimals shift of the Currency. Rounding, default behaviors for toString() and toBig() will represent the amounts at that precision.
    For example, when using an amount of 0.5 Bitcoin, the internal representation is represented as 0.5 * 10^8 (50,000,000 Satoshi)
    and all operations (.add(...), .sub(...), etc.) will use the internal representation.

    humanDecimals is used for pretty-printing approximate (truncated) stringified values using toHuman().

    At this point, the currency is usable:

    import { Bitcoin, BitcoinUnit } from "src/currencies/bitcoin";
    const btcAmount = new MonetaryAmount<Bitcoin, BitcoinUnit>(
      Bitcoin,
      0.5,
      Bitcoin.units.BTC
    );

    However, this is a bit verbose. We can subclass MonetaryAmount for convenience:

    export class BitcoinAmount extends MonetaryAmount<Bitcoin, BitcoinUnit> {
      // added convenience method
      static zero = () => new BitcoinAmount(0);
    }

    Development

    Installation

    Checkout the code and install the dependencies:

    git clone https://github.com/interlay/monetary.git
    cd monetary
    yarn install

    Build:

    yarn build

    And run tests:

    yarn test

    Contributing

    Contributions are what make the open source community such an amazing place to be learn, inspire, and create. Any contributions you make are greatly appreciated. Our basic contributing guidelines are found in this repository.

    1. Fork the project
    2. Create your feature branch (git checkout -b feat/AmazingFeature)
    3. Sign and commit your changes (git commit -S -m 'feat: Add some AmazingFeature')
    4. Push to the branch (git push origin feat/AmazingFeature)
    5. Open a pull request

    If you are searching for a place to start or would like to discuss features, reach out to us on the #development channel:

    License

    (C) Copyright 2023 Interlay Ltd

    monetary is licensed under the terms of the MIT License. See LICENSE.

    Contact

    Website: Interlay.io

    Twitter: @interlayHQ

    Email: contact@interlay.io

    Visit original content creator repository
    https://github.com/interlay/monetary