text:
# TypedTextView
[![License](https://img.shields.io/badge/License%20-Apache%202-337ab7.svg)](https://www.apache.org/licenses/LICENSE-2.0)
[![MinSDK](https://img.shields.io/badge/API-15%2B-brightgreen.svg?style=flat)](https://android-arsenal.com/api?level=15)
[![Build Status](https://travis-ci.com/iamporus/TypedTextView.svg?branch=master)](https://travis-ci.com/iamporus/TypedTextView)
[![Language grade: Java](https://img.shields.io/lgtm/grade/java/g/iamporus/TypedTextView.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/iamporus/TypedTextView/context:java)
[![](https://jitpack.io/v/iamporus/TypedTextView.svg)](https://jitpack.io/#iamporus/TypedTextView)
[![Android Arsenal]( https://img.shields.io/badge/Android%20Arsenal-TypedTextView-green.svg?style=flat )]( https://android-arsenal.com/details/1/7711 )

Custom implementation of Android's TextView simulating a keyboard/typewriter.

<img align="right" width="350" src="https://github.com/iamporus/TypedTextView/blob/master/demo.gif">

## Features
* display a **blinking cursor** after every character typed.
* characters are displayed on the screen with **random speed** which simulates human behavior.
* emit **audio keystrokes** with typed characters.
* **Lifecycle-aware** component. Character typing and audio stops/resumes as per Activity/Fragment state.
* support to **maintain state** across Activity/Fragment lifecycle.
* delay on sensing comma(,) and full stops(.) to **simulate user pauses**.
* display **sentences on new line** on sensing full stops in passed text.

## Gradle
* **Step 1.** Add the JitPack repository to your build file.

Add following in your **Project level** build.gradle at the end of repositories:
```gradle
allprojects {
  repositories {
    ...
    maven { url 'https://jitpack.io' }
  }
}
```
* **Step 2.** Add the dependency
```gradle
dependencies {
  ...
  implementation 'com.github.iamporus:TypedTextView:x.y.z'
}
```
The latest version of TypedTextView is  [![](https://jitpack.io/v/iamporus/TypedTextView.svg)](https://jitpack.io/#iamporus/TypedTextView)

## Usage - XML

### Simple Usage
```xml
<com.prush.typedtextview.TypedTextView
        android:id="@+id/typedTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="start"
        android:textSize="24sp"
        app:typed_text="Once there lived a monkey in a jamun tree by a river. The monkey was alone. He had no friends, no family, but he was happy and content."/>

```
### Customizations

```xml
<com.prush.typedtextview.TypedTextView
        android:id="@+id/typedTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="start"
        android:textSize="24sp"
        app:randomize_typing_speed="true"
        app:randomize_type_seed="75"
        app:show_cursor="true"
        app:cursor_blink_speed="530"
        app:sentence_pause="1500"
        app:split_sentences="true"
        app:play_keystrokes_audio="true"                                   //use default audio
        app:play_keystrokes_audio_res="@raw/your_audio_keystroke_res_id"   //OR use custom audio
        app:typed_text="Once there lived a monkey in a jamun tree by a river. The monkey was alone. He had no friends, no family, but he was happy and content."
        app:typing_speed="175"/>
```

## Usage - Java

### Simple Usage
```java
TypedTextView typedTextView = findViewById( R.id.typedTextView );

typedTextView.setTypedText( "Once there lived a monkey in a jamun tree by a river. The monkey was alone. He had no friends, no family, but he was happy and content." );

//Attach TypedTextView's lifecycle to Activity's lifecycle.
getLifecycle().addObserver( typedTextView.getLifecycleObserver() );

```
### Customizations
```java
TypedTextView typedTextView = findViewById( R.id.typedTextView );

//Using Builder

TypedTextView.Builder builder = new TypedTextView.Builder( typedTextView )
                .setTypingSpeed( 175 )
                .splitSentences( true )
                .setSentencePause( 1500 )
                .setCursorBlinkSpeed( 530 )
                .randomizeTypingSpeed( true )
                .showCursor( false )
                .playKeyStrokesAudio( true )
                .randomizeTypeSeed( 250 );

typedTextView = builder.build();

typedTextView.setTypedText( "Once there lived a monkey in a jamun tree by a river. The monkey was alone. He had no friends, no family, but he was happy and content." );

//----------------------------------------------------- OR ---------------------------------------------------------------

//Set typing speed
typedTextView.setTypingSpeed( 175 );

//Configure sentences
typedTextView.splitSentences( true );
typedTextView.setSentencePause( 1500 );

//Configure Cursor
typedTextView.showCursor( true );
typedTextView.setCursorBlinkSpeed( 530 );

//Configure randomizing typing speed to simulate human behaviour
typedTextView.randomizeTypingSpeed( true );
typedTextView.randomizeTypeSeed( 75 );

//Play default keystrokes audio
typedTextView.playKeyStrokesAudio( true );

//OR play custom keystrokes audio
typedTextView.playKeyStrokesAudio( R.raw.your_audio_keystroke_res_id );

//Set text to be typed
typedTextView.setTypedText( "Once there lived a monkey in a jamun tree by a river. The monkey was alone. He had no friends, no family, but he was happy and content." );

//Attach TypedTextView's lifecycle to Activity's lifecycle.
getLifecycle().addObserver( typedTextView.getLifecycleObserver() );

//Set listener to invoke other actions based on status.
typedTextView.setOnCharacterTypedListener( new TypedTextView.OnCharacterTypedListener()
{
  @Override
  public void onCharacterTyped( char character, int index )
  {
    Log.d( TAG, "onCharacterTyped: " + character + " at index " + index );
  }
});

```

## License
```
Copyright 2019 Purushottam Pawar

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
```

repository: iamporus/TypedTextView

repo_name: iamporus/TypedTextView


text:
M-NET API
=========

![forthebadge](https://forthebadge.com/images/badges/fuck-it-ship-it.svg)
![forthebadge](https://forthebadge.com/images/badges/built-with-love.svg)
![forthebadge](https://forthebadge.com/images/badges/uses-js.svg)
![forthebadge](https://forthebadge.com/images/badges/powered-by-electricity.svg)

[![Build Status](https://img.shields.io/travis/rayriffy/mnet-api.svg?style=for-the-badge)](https://travis-ci.org/rayriffy/mnet-api)
[![Codacy](https://img.shields.io/codacy/grade/8ed63a23e45f46a4be2ebcb73d210a31.svg?style=for-the-badge)](https://www.codacy.com/app/rayriffy/mnet-api)
[![Javascript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg?style=for-the-badge)](https://standardjs.com)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg?style=for-the-badge)](https://opensource.org/licenses/MIT)

M-NET API for MWIT

Requirements
------------

-   (Recommended) CentOS 7.x
-   MongoDB 4.x
-   Node LTS

Installation
------------

```bash
yarn
```

Build
-----

For for development

```bash
yarn dev
```

For production build

```bash
yarn build
```

Your complied files will be located at `./build`

Usage
-----

Latest **API V1** documentation can be found [here](API-V1.md)

Contributing
------------

We welcome all contributions by sending PR to this repository.

Licence
-------

M-NET API is licensed under the [MIT licence](https://opensource.org/licenses/MIT). Please see [the licence file](LICENCE) for more information. [tl;dr](https://tldrlegal.com/license/mit-license) you can do whatever you want as long as you include the original copyright and license notice in any copy of the software/source.

Need Help
---------

If you need help with anything, here're following methods:

### Create an Issue

If you have something you want to discuss in detail, or have hit an issue which you believe others will also have in deployment or development of the system, [opening an issue](https://github.com/rayriffy/mnet-api/issues) is the best way to get help. It creates a permanent resource for others wishing to contribute to conversation.

[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Frayriffy%2Fmnet-api.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Frayriffy%2Fmnet-api?ref=badge_large)

license: MIT

repository: rayriffy/mnet-api

branch_name: refs/heads/master

extension: md

gha_language: JavaScript

gha_license_id: MIT

license_type: permissive

repo_name: rayriffy/mnet-api


text:
## Main Concepts

### Summary

**Snowpack is a modern, lightweight build tool for faster web development.** Traditional JavaScript build tools like webpack and Parcel need to rebuild & rebundle entire chunks of your application every time you save a single file. This rebundling step introduces lag between hitting save on your changes and seeing them reflected in the browser.

Snowpack serves your application **unbundled during development.** Every file only needs to be built once and then is cached forever. When a file changes, Snowpack rebuilds that single file. There's no time wasted re-bundling every change, just instant updates in the browser (made even faster via [Hot-Module Replacement (HMR)](#hot-module-replacement)). You can read more about this approach in our [Snowpack 2.0 Release Post.](/posts/2020-05-26-snowpack-2-0-release/)

Snowpack's **unbundled development** still supports the same **bundled builds** that you're used to for production. When you go to build your application for production, you can plug in your favorite bundler via an official Snowpack plugin for Webpack or Rollup (coming soon). With Snowpack already handling your build, there's no complex bundler config required.

**Snowpack gets you the best of both worlds:** fast, unbundled development with optimized performance in your bundled production builds.

![webpack vs. snowpack diagram](/img/snowpack-unbundled-example-3.png)

### Unbundled Development

**Unbundled development** is the idea of shipping individual files to the browser during development. Files can still be built with your favorite tools (like Babel, TypeScript, Sass) and then loaded individually in the browser with dependencies thanks to ESM `import` and `export` syntax. Any time you change a file, Snowpack only ever needs to rebuild that single file.

The alternative is **bundled development.** Almost every popular JavaScript build tool today focuses on bundled development. Running your entire application through a bundler introduces additional work and complexity to your dev workflow that is unnecessary now that ESM is widely supported. Every change -- on every save -- must be rebundled with the rest of your application before your changes can be reflected in your browser.

Unbundled development has several advantages over the traditional bundled development approach:

- Single-file builds are fast.
- Single-file builds are deterministic.
- Single-file builds are easier to debug.
- Project size doesn’t affect dev speed.
- Individual files cache better.

That last point is key: **Every file is built individually and cached indefinitely.** Your dev environment will never build a file more than once and your browser will never download a file twice (until it changes). This is the real power of unbundled development.

### Using NPM Dependencies

NPM packages are mainly published using a module syntax (Common.js, or CJS) that can't run on the web without some build processing. Even if you write your application using browser-native ESM `import` and `export` statements that would all run directly in the browser, trying to import any one npm package will force you back into bundled development.

**Snowpack takes a different approach:** Instead of bundling your entire application for this one requirement, Snowpack processes your dependencies separately. Here's how it works:

```
node_modules/react/**/*     -> http://localhost:3000/web_modules/react.js
node_modules/react-dom/**/* -> http://localhost:3000/web_modules/react-dom.js
```

1. Snowpack scans your website/application for all used npm packages.
2. Snowpack reads these installed dependencies from your `node_modules` directory.
3. Snowpack bundles all of your dependencies separately into single JavaScript files. For example: `react` and `react-dom` are converted to `react.js` and `react-dom.js`, respectively.
4. Each resulting file can be run directly in the browser, and imported via ESM `import` statements.
5. Because your dependencies rarely change, Snowpack rarely needs to rebuild them.

After Snowpack builds your dependencies, any package can be imported and run directly in the browser with zero additional bundling or tooling required. This ability to import npm packages natively in the browser (without a bundler) is the foundation that all unbundled development and the rest of Snowpack is built on top of.

```html
<!-- This runs directly in the browser with `snowpack dev` -->
<body>
  <script type="module">
    import React from 'react';
    console.log(React);
  </script>
</body>
```

repository: iam-frankqiu/snowpack

repo_name: iam-frankqiu/snowpack


text:
# Tideland Go Audit

[![GitHub release](https://img.shields.io/github/release/tideland/go-audit.svg)](https://github.com/tideland/go-audit)
[![GitHub license](https://img.shields.io/badge/license-New%20BSD-blue.svg)](https://raw.githubusercontent.com/tideland/go-audit/master/LICENSE)
[![Go Module](https://img.shields.io/github/go-mod/go-version/tideland/go-audit)](https://github.com/tideland/go-audit/blob/master/go.mod)
[![GoDoc](https://godoc.org/tideland.dev/go/audit?status.svg)](https://pkg.go.dev/mod/tideland.dev/go/audit?tab=packages)
[![Workflow](https://github.com/tideland/go-audit/actions/workflows/build.yml/badge.svg)](https://github.com/tideland/go-audit/actions/)
[![Go Report Card](https://goreportcard.com/badge/github.com/tideland/go-audit)](https://goreportcard.com/report/tideland.dev/go/audit)

## Description

**Tideland Go Audit** provides helpful packages to support testing.

* `asserts` provides routines for assertions helpful in tests and validation
* `capture` allows capturing of STDOUT and STDERR
* `environments` provides setting of environment variables and creation of temporary test directories
* `generators` simplifies generation of test data; with a fixed random on demand even repeatable
* `web` allows simple tests of web handlers

I hope you like it. ;)

## Contributors

- Frank Mueller (https://github.com/themue / https://github.com/tideland / https://tideland.dev)

repository: tideland/go-audit

branch_name: refs/heads/main

gha_language: Go

repo_name: tideland/go-audit


text:
---
layout: post
title: "BestBuy Bot — Open Source GPU/PS5/Xbox Bot"
categories:
  - Edge Case
tags:
  - best buy bot
  - buy RTX from best buy
  - buy PS5 from best buy
  - nerdspeak
  - tampermonkey
  - browser based
  - open source
---

〰〰〰〰〰〰〰〰 ⬇ ⬇ Join FAQ & Support Discord ⬇ ⬇ 〰〰〰〰〰〰

〰〰〰〰〰〰〰〰〰〰 ⬇ ⬇ Source Code ⬇ ⬇ 〰〰〰〰〰〰〰〰

[](https://github.com/kkapuria3/BestBuy-GPU-Bot)

## Description

BestBuy Bot is an Add to cart and Auto Checkout Bot. This auto buying bot can search an item repeatedly on the item page using one keyword. Once the desired item is available it can add to cart and checkout very fast. This auto purchasing BestBuy Bot can work on Firefox Browser so it can run in all Operating Systems. It can run for multiple items simultaneously.

"Running a bot can increase your success chances only ; but does not guarantee that you will successfully cart each time. If you do not agree, then please do not use this code."

## Getting Started

1. Create a [github](https://github.com/login?return_to=%2Fkkapuria3) account. It always helps !
2. Star this repository. Its FREE !
3. Please follow me here if you like my contribution:

[](https://github.com/kkapuria3)

### Dependencies

1. Install [Nerd Speak Extention](https://nerdspeak.net/tech/nerdspeak-stock-helper-extension/)
2. Install [Tampermonkey Extention](https://www.tampermonkey.net/)
3. BestBuy Account (Please be signed in)
4. Please allow [Pop-Ups](https://www.isc.upenn.edu/how-to/configuring-your-web-browser-allow-pop-windows) for ```https://www.bestbuy.com/``` in your browser

### Installing

* Successfully download and install both extensions in your browser
* Go to tampermonkey dashboard from broswer extension and create a new script
* Delete all the contents and copy full code from [best-buy-tm.js](https://raw.githubusercontent.com/kkapuria3/BestBuy-GPU-Bot/main/best-buy-tm.js)
* Save the script
* Updated REQUIRED FLAGS to your specifications

### Testing

* Use these product links to test the BOT
* [AMD - Ryzen 5 5600X](https://www.bestbuy.com/site/amd-ryzen-5-5600x-4th-gen-6-core-12-threads-unlocked-desktop-processor-with-wraith-stealth-cooler/6438943.p?skuId=6438943)
* [AMD - Ryzen 7 5800X](https://www.bestbuy.com/site/amd-ryzen-7-5800x-4th-gen-8-core-16-threads-unlocked-desktop-processor-without-cooler/6439000.p?skuId=6439000)

### Further Details

* Item Keyword corresponds to a keyword in your product name (no spaces allowed)
```
const ITEM_KEYWORD= "3060";
```
* Credit Card CVV  (Not Required. BOT just wont do final checkout)
```
const CREDITCARD_CVV = "***";
```
* Test Mode "YES" will not purchase item. But do all the steps except pressing the last button. ```TESTMODE = "No" ``` will purchase the item.
```
const TESTMODE = "Yes"
```

## Workflow

This tool is designed to multitask. That means, it can run in many tabs simultaneously, if there is a ```ITEM_KEYWORD``` overlap.
If there is no ```ITEM_KEYWORD``` overlap. You will need to create a new copy of script for each ```ITEM_KEYWORD```.

Please make sure your CART is empty.

After updating variables and enabling the script in Tampermonkey, go to the your favourite GPU page in BestBuy.
If the Title of GPU has ```ITEM_KEYWORD```, it will add the item to cart and checkout. If item is out of stock it will keep on refreshing every 5 seconds.

Please use ```TESTMODE = "Yes"``` to test with an item already in stock.

## Authors

* Karan Kapuria

## Version History and Changelog

* 1.0 Initial Release
* 1.1 Handle Please Wait Gracefully
	* If Please Wait button shows up, bot will check every for second ATC button every 20 seconds
	* Whenever second ATC button appears, it will click and checkout
	* Reading Logs in Console
* 2.0 - 'Please Wait...' items can now be CARTED and CHECKEDOUT
 	* If "Please Wait" button shows up, it will enter a loop of retries which will check the color of button.
 	* As long as button stays Gray, it will try and check for Yellow Color
 	* Whenever Yellow ATC button appears again, it will click and checkout
 	* Status Bar is now being added at bottom
 	* Status Bar now shows version and TESTMODE variable
* 2.5 - 'Fixed Memory Leak' no more refresh ! We will recycle tabs.
	* Due to constant reloading of OOS items, memory on your browser slowly blows up
	* We will now kill the tab if item is OOS and open it in new page. Doing this infact reduces the total RAM usage.
	* Button clicks no more use .click() but instead use EventListeners()
	* Status Bar is now 50% of screen.  Little taller so last line is visible when page is loading.
	* Status Bar now shows ITEM_KEYWORD
	* We will now play a music when item is carted.
	* Since BB asks for verifying account sometimes. Alert will help so that you dont miss checkout.
	* MAX_RETRIES will now control when your page gets reloaded when you are stuck on please wait screen. In this case it will perform normal reload.
* 3.0 -  Conjuction with 'Nerd Speak' Extension
  	* MAJOR CHANGE: BOT ONLY WORKS FOR CHROME NOW (Version 2.5 and older are all browser compatible)
  	* Bot will now extract queue time from NS extension
  	* QUEUE_TIME_CUTOFF will keep requesting better queue times until target value is reached
  	* NEW_QUEUE_TIME_DELAY is delay in seconds between requesting new queue times.
  	* Status Bar is 75px fixed
  	* Status Bar now shows more information
  	* Since BB asks for verifying account sometimes. Alert will help so that you dont miss checkout.
  	* MAX_RETRIES will be deprecated in future.


text:
# Facade Class

The `Facade` class is a utility class that provides a simplified interface to access classes or services in your PHP applications.

## Installation

The `Facade` class is a standalone class and doesn't require any installation. You can simply include the class file in your project.

```php
composer require effectra/facade
```

## Usage

To use the `Facade` class, follow these steps:

1. Extend the `Facade` class with your custom facade class.
2. Implement the `getFacadeAccessor()` method in your custom facade class.
3. Optionally, set the resolved instance or container using the `setResolvedInstance()` or `setContainer()` method respectively.
4. Access the methods of the underlying class or service using the static methods of your custom facade class.

Here's an example:

```php
use Effectra\Facade;

class MyFacade extends Facade
{
    protected static function getFacadeAccessor()
    {
        return MyService::class;
    }
}

// Usage
MyFacade::setResolvedInstance(new MyService());
MyFacade::someMethod();
```

In this example, we've created a custom facade class `MyFacade` by extending the `Facade` class. The `getFacadeAccessor()` method in `MyFacade` returns the class name of `MyService` that we want to access using the facade.

By setting the resolved instance using `setResolvedInstance()`, we directly provide an instance of `MyService` to the facade. This allows us to access the methods of `MyService` using the static methods of `MyFacade`.

You can also use a container instead of setting the resolved instance directly. To do so, create a container, bind the class name to a key in the container, and set the container using `setContainer()`.

```php
use Effectra\Facade;
use Effectra\Container\Container;

class MyFacade extends Facade
{
    protected static function getFacadeAccessor()
    {
        return 'myService';
    }
}

// Usage
$container = new Container();
$container->bind('myService', MyService::class);

MyFacade::setContainer($container);
MyFacade::someMethod();
```

In this example, we've used a simple `Container` class to bind the class name of `MyService` to the key `'myService'`. By setting the container using `setContainer()`, the `Facade` class resolves the instance from the container when the static method is called.

Make sure to replace `'MyService'` and `'someMethod()'` with the actual class and method names you're using in your application.

## Contributing

Contributions are welcome! If you find any issues or would like to add new features or improvements, please open an issue or submit a pull request.

Before contributing, please make sure to review the [contribution guidelines](CONTRIBUTING.md).

## License

This class is open-source and available under the [MIT License](LICENSE).

repository: effectra/facade

repo_name: effectra/facade


text:
## Flip Bit to Win

#### Flip Bit to Win: You have an integer and you can flip exactly one bit from a O to a 1. Write code to find the length of the longest sequence of 1 s you could create.

repository: LuigiAndrea/ctci

repo_name: LuigiAndrea/ctci


text:
**Exercise: DOM Manipulations**

Problems for exercises and homework for the ["JavaScript Advanced" course \@
SoftUni](https://softuni.bg/courses/js-advanced)*"*. Submit your solutions in
the SoftUni judge system at
<https://judge.softuni.bg/Contests/1550/Exercise-DOM-Manipulations>.

01\. Subtraction
-----------

An HTML page holds **two text fields** with ids "**firstNumber**" and
"**secondNumber**". Write a function to **subtract** the values from these text
fields and display the result in the **div** named "**result**".

**HTML and JavaScript Code**

Implement the above to provide the following functionality:

-   Your function should take the values of "**firstNumber**" and
    "**secondNumber**", **convert** them to numbers, **subtract** the second
    number from the first one and then append the result to the **\<div\>** with
    **id="result"**.

-   Your function should be able to work with **any 2 numbers** in the inputs,
    not only the ones given in the example.

**Example**

![](media/7c4374090d165de1379da67f13f64b6e.png)

**Hints**

We see that the **textboxes** and the **div** have **id** attributes on them.

![](media/64b87bf62a5766d225d71aef8dae85bf.png)

We can take the numbers directly from the input field by using the
**getElementById()** function. After we have taken the elements from the DOM,
it’s time to do the actual work. We get the values of the two **textboxes**, the
value of a textbox, as one would expect, is **text**. In order to get a
**number**, we need to use a function to **parse them**.

![](media/50d9ad0497215142ec21a073e2339342.png)

All that’s left now is to append the result to the **div**. We use the same
function to get the **result** element by id and change its **text content** to
the result of the **subtraction.**

![](media/b1430dd42c6d7c3005a40638dff6c1b4.png)

Our code is ready now. Submit only the **subtract()** function in judge.

02\. Fill Dropdown
-------------

Your task is to take values from **input** fields with **ids "newItemText"** and
**"newItemValue"**. Then you should create and append an **\<option\>** to the
**\<select\>** with **id "menu".**

**Example**

![](media/ae4721b827279dba893319bb4c619e6b.png)

**Hints**

-   Your function should take the values of **newItemText** and
    **newItemValue**. After that you should create a new **option** element and
    set its **textContent** and its **value** to the newly taken ones.

-   Once you have done all of that, you should **append** the newly created
    **option** as a **child** to the **select** item with id **"menu".**

-   Finally, you should **clear** the value of the two **input** fields.

03\. Accordion
---------

An **html** file is given and your task is to show **more**/**less** information
by clicking a **[ADD] button** (it is not an actual button, but a **span** that
has an **onclick** event attached to it). When **[More] button** is clicked, it
**reveals** the content of a **hidden** div and **changes** the text of the
button to **[Less]**. When the same link is clicked **again** (now reading
**Less**), **hide** the div and **change** the text of the link to **More**.
Link action should be **toggleable** (you should be able to click the button
infinite amount of times).

**Example**

![](media/b9d752e73ba7d1a10cb7f70e7caffa18.png)

![](media/b3298f51187c49c5e4d8198331f14ae5.png)

**Hints**

-   To **change** the text content of a button, you could use
    **getElementsByClassName**. However, that returns a **collection** and we
    need only **one** element from it, so the correct way is to **use
    getElementsByClassName("button")[0]** as it will return the needed span
    element.

-   After that we should change the **display style** of the div with an **id**
    "**extra**". If the display style is "**none**", we should **change** it to
    "**block**" and the **opposite**.

-   Along with all of this, we should **change** the text content of the
    **button** to **[Less]**/[**More]**.

04\. Sections
--------

You will receive an **array** of strings. For each string, create a **div** with
a **paragraph** with the **string** in it. Each paragraph is initially **hidden
(display:none)**. Add a **click event listener** to **each div** that
**displays** the **hidden** paragraph. Finally, you should **append** all divs
to the element with an **id** "**content**".

**Example**

![beforeClick](media/584f4d1f6d6bb096d87eeb6e56300f64.png)

![C:\\Users\\v\\AppData\\Local\\Microsoft\\Windows\\INetCache\\Content.Word\\afterClick.png](media/89c1ec5e53502b0bb4011b1bac9afb0a.png)

05\. Notification
------------

Write a **function** that receives a string **message** and **displays** it
inside a div with an id "**notification**" for 2 seconds. The div is initially
**hidden** and when the function is called, it must be **shown**. After 2
seconds, **hide** the div. In the example below, a notification is shown when
you **click** the button.

**Example**

![](media/0dcdfb9eadbe3b8bd10d6fc5df848b74.png)

When we click the [**GET NOTIFIED**] **button**, a **div** appears in our
upper-right corner. It should **disappear** in 2 seconds.

06\. Time Converter
--------------

Create a program that **converts** different time units. Your task is to add a
**click** event listener to **all** [**CONVERT**] **buttons**. When a button is
**clicked**, read the **corresponding** input field, **convert** the value to
the **three other** time units and **display** it in the input fields.

**Example**

![](media/8dacdb085235afede7dfb0f5e3b1208c.png)

One day is equal to 24 hours/1440 minutes/86400 seconds. Whichever button we
**click,** the input fields should **change** depending on the added value on
the left. (For example, if we write 48 hours and click convert the days, the
field value should change to 2).

07\. Locked Profile
--------------

In this problem, you should **create a JS functonality** which **shows** and
**hides** the additional

information about users.

![](media/badf08bd6b5bdf55c04961b13a88db9d.png)

When one of the [**Show more**] **buttons** is clicked, the **hiden
information** inside the div should

be shown, only if **the profile is not locked**! If the current profile is
**locked,** nothing should

happen.

![](media/9a60031a3dc2450e2ba949d492c6878e.png)

If the **hidden information is displayed** and we **lock the profile again**,
the [**Hide it**] button

should **not be working**! Otherwise, when the profile is **unlocked** and we
click on the **[Hide it]**

button, the new fields must hide again.

08\. Encode and Decode Messages
--------------------------

In this problem, you should **create a JS functonality** which **encodes and
decodes some**

**messages which travel to the network.**

![](media/979b229d7151ad9f6d9d9b203a8dcd4b.png)

This program should contain **two functionalities**.

The first one is to **encode the given message** and **send it** to the
**receiver**.

The second one is to **decode the received message** and **read it (display
it)**.

When the [**Encode and send it**] **button** is clicked, you should get the
given message from the first textarea. When you get the current message, you
should encode it as follows:

-   **Change** the **ASCII CODE** on **every single character** in that message
    when you **add 1** to the current **ASCII NUMBER**, that represent the
    current character in that message

-   **Clear** the **sender textarea** and **append** the encoded message to the
    **receiver textarea**

![](media/0a942a07e1687d6c584ac5151c17ef2c.png)

*After clicking [Encode and send it] button the result should be:*

![](media/b622a58855ae7fab66c2d7dc7233a9be.png)

After that, when the [**Decode and read it**] **button** is clicked. You need to
get the **encoded message** from **the receiver textarea** and do the **opposite
logic** from encoding:

-   **Subtract 1** from the current **ASCII NUMBER**, that represents the
    current character in that message

-   Replace the **encoded message** with the already **decoded message** in the
    receiver textrea, to make it readable

![](media/d123b6e23f8a51dc998a83f658729a14.png)

09\. \*Distance Converter
---------------------

Your task is to convert from **one** distance unit to **another** by adding a
**click** event listener to a button. When it is clicked, **read** the value
from the input field and **get** the **selected** option from the **input** and
**output** units drop downs. Then **calculate** and **display** the converted
value in the **disabled** output field.

**Example**

![](media/bc0b6378561ed01611b803c44615910e.png)

**Hints**

-   Multiply the incoming distance by the following conversion rates to convert
    to meter

-   Divide to convert from meters to the required output unit

-   To see which option is selected, read the properties of its parent:
    **value** gives you the value of the selected option (as displayed in the
    HTML), **selectedIndex** gives you the 0-based index of the selected option.
    For example, if miles are selected, **inputUnits.value** is "**mi**",
    **inputUnits.selectedIndex** is **4**. Option text is irrelevant

-   Use the following table information to do that:

| **1 km**  | **1000 m**    |
|-----------|---------------|
| **1 m**   | **1 m**       |
| **1 cm**  | **0.01 m**    |
| **1 mm**  | **0.001 m**   |
| **1 mi**  | **1609.34 m** |
| **1 yrd** | **0.9144 m**  |
| **1 ft**  | **0.3048 m**  |
| **1 in**  | **0.0254 m**  |

url: https://raw.githubusercontent.com/iPavelGeorgiev/SoftUni/27d2a1d114ab4fdc3eec0df22e24c84aaf1ceb59/JS Advanced/6. DOM Manipulations/2. DOM Manipulations - Exercises/README.md

repository: iPavelGeorgiev/SoftUni

repo_name: iPavelGeorgiev/SoftUni


text:
# Behaviours in PADE
##### PADE Update (LAAI | UFPA), released at 4-22-2019, updated at 5-27-2020

## Content
- [Introduction](#introduction)
- [Agent behaviours on PADE](#agent-behaviours-on-pade)
	- [OneShotBehaviour class](#oneshotbehaviour-class)
	- [WakeUpBehaviour](#wakeupbehaviour-class)
	- [SimpleBehaviour](#simplebehaviour-class)
	- [CyclicBehaviour](#cyclicbehaviour-class)
	- [TickerBehaviour](#tickerbehaviour-class)
	- [SequentialBehaviour](#sequentialbehaviour-class)
- [Behaviour return feature](#behaviour-return-feature)
- [Mutual Exclusion with behaviours](#mutual-exclusion-with-behaviours)
- [Contact us](#contact-us)

## Introduction
This document aims to describe how PADE implements behaviours of agents. The way to implement behaviours in PADE is similar to the paradigm used in [JADE Framework](https://jade.tilab.com/). This is an update provide to PADE by [LAAI](http://www.laai.ufpa.br/). Although this update is incorporated in the code, the features of the previous version of PADE still work normally. We hope you enjoy this update.

## Agent Behaviours on PADE
In this session we will approach quickly the referred way to program behaviours in PADE. The used paradigm is based in [JADE](https://jade.tilab.com/) programming, so, if you want to know more about this agent-based programming style, see some examples with behaviours in JADE.

The first thing to keep in mind while developing behaviours is that behaviours have two main methods to be implemented. They are the `action()` and `done()` methods.

The `action()` method is the most important to be implemented, because is it that will perform the actions of the behaviour (consequently, of the agent). All "hard code" of behaviour must be put on `action()` method.

Next, the `done()` method must implements the end of the behaviour. In other words, it must to tells to PADE when a behaviour finishes its actions. This method must returns a `bool`, which indicates whether a behaviour is ended (by returning `True`), or not (by returning `False`). There are cases where you don't need to implement this method, because it is predefined, as we will see later.

To better understand how PADE executes behaviours actions, the diagram below synthesis the behaviours cycle within PADE scheduler.

![Behaviours life cycle diagram on PADE](../../img/behaviours_lifecycle.png)

At each execution, a behaviour will perform its `action()` method, executing soon after its `done()` method. If the `done()` method returns `False`, the behaviour will be executed again; if the `done()` method returns `True`, the behaviour will execute its `on_end()` method and, then, it will ends. The `on_end()` method can be overridden to execute post-execution actions. It is useful for signalizes when a behaviour ended or clear control structures used in the behaviour execution.

Basically, behaviours may be of two types: finite behaviours or infinite behaviours. They do exactly what their names mean, that is, finite behaviors end at a definite time (its `done()` method will return `True` at some time) and infinite behaviors never end (its `done()` method never returns `True`). The classes in PADE that implement the finite behaviours are `OneShotBehaviour` and `WakeUpBehaviour`. In its turn, the classes that implement the infinite behaviours are `CyclicBehaviour` and`TickerBehaviour`. All of them are subclasses from the `SimpleBehaviour` class, which is a general model to implement behaviours that run alone. On the other hand, the `SequentialBehaviour` class is a subclass of the `CompoundBehaviour` class, which models a special type of behaviour that manage several sub-behaviours.

To further explain the features of the behaviours classes in PADE, we will see each one of them separately in the next sub-sessions.

### OneShotBehaviour class
The `OneShotBehaviour` is a class that models finite behaviours. This is a `SimpleBehaviour` subclass whose main characteristic is that its `done()` method always returns `True`, ending the behaviour soon after its first execution. Let's look at an example by writing a `OneShotBehaviour` that makes an agent says "hello world".

```python
# Needed imports
from pade.behaviours.types import OneShotBehaviour
from pade.core.agent import Agent
from pade.misc.utility import display_message, start_loop

# Defining the HelloWorldAgent (inherits from Agent class)
class HelloWorldAgent(Agent):

	# This method will execute at agent startup
	def setup(self):
		# This adds the 'SayHello' behaviour in the agent
		self.add_behaviour(SayHello(self))

# Defining the SayHello behaviour
class SayHello(OneShotBehaviour):

	# This method executes the main actions of SayHello behaviour
	def action(self):
		# This shows a message, with date/hour information, in console
		display_message(self.agent, 'Hello world!')

# This starts the agent HelloWorldAgent with PADE
if __name__ == '__main__':
	# Defining a HelloWorldAgent object
	helloagent = HelloWorldAgent('hello')
	# Creating a list with agents that will be executed
	agents_list = [helloagent]
	# Passing the agent list to main loop of PADE
	start_loop(agents_list)
```
First, we defined the `HelloWorldAgent`. Next, we described what the agent will execute in its startup. The method `Agent.setup()` defines what the agent will execute when started. Usually we use this method to attach to agent any behaviour that the agent needs to execute first. In its turn, the `Agent.add_behaviour(BaseBehaviour)` method is used to attach a behaviour to be executed by an agent.

> Note: The `BaseBehaviour` class is the basic class from which all other behaviours inherit from, that is, it is the general type of any behavior classes.

After writing the agent, we defined the `SayHello` behaviour. The only method needed to be implemented is the `SayHello.action()`. This method defines the **action** that the agent will takes when performs this behaviour. To `OneShotBehaviour` no other method is needed to be implemented.

The last lines deal with the initiation of the agents within PADE's loop. While instantiating new agents, we need to give to they unique names. These names are passed to Agent `__init__()` under string form or by using an `AID` object. The `start_loop(list)` function receives a list of agents that will be executed on PADE. To start the agents, execute `pade start-runtime file_name.py` on a terminal and enjoy it! 0\/

### WakeUpBehaviour class
The `WakeUpBehaviour` also implements a finite behaviour, with the important difference that this behaviour will wait for a time before perform its actions. Another important spot to focus is that this class implements its actions on `on_wake()` method, rather `action()` method. We can see an example below that models an agent which waits by 5 seconds to makes an ask.

``` python
# Needed imports
from pade.behaviours.types import WakeUpBehaviour
from pade.core.agent import Agent
from pade.misc.utility import display_message, start_loop

# Defining the LaterAgent (inherits from Agent class)
class LateAgent(Agent):

	# This method will execute at agent startup
	def setup(self):
		# The behaviour is created with two args, where
		# the second is a time (in seconds) to behaviour
		# waits.
		behaviour = AmILate(self, 5)
		# This adds a behaviour in the agent
		self.add_behaviour(behaviour)

# Defining the AmILate behaviour
class AmILate(WakeUpBehaviour):

	# This method executes the main actions of behaviour
	def on_wake(self):
		display_message(self.agent, 'Am I late?')

# This starts the agents with PADE
if __name__ == '__main__':
	# Defining a LateAgent object
	lateagent = LateAgent('late')
	# Creating a list with agents that will be executed
	agents_list = [lateagent]
	# Passing the agent list to main loop of PADE
	start_loop(agents_list)
```
Now, executing the `pade start-runtime file_name.py` command in the terminal, we will see the agent waiting 5 seconds before prints the ask "Am I late?" in the screen. This task is performed only once because it is a finite behaviour.

### SimpleBehaviour class
The `SimpleBehaviour` class is the simplest pre-implemented behaviour model in PADE (oh, really?). "Simple" means that you must program the `action()` and `done()` methods. The advantage of this behaviour model is that you can customize its end. Below there is an example where an agent counts and shows in console a counting from 1 to 10.

``` python
from pade.behaviours.types import SimpleBehaviour
from pade.core.agent import Agent
from pade.misc.utility import display, start_loop

class CounterAgent(Agent):
	def setup(self):
		self.add_behaviour(Count(self))

class Count(SimpleBehaviour):
	# Defining initial parameters to behaviour
	def __init__(self, agent):
		# This call to superclass is needed, passing the agent
		super().__init__(agent)
		# Defining counting variable
		self.counter = 1

	def action(self):
		display(self.agent, 'Counting #%d' % self.counter)
		self.counter += 1

	# This method indicates when the behaviour finishes.
	def done(self):
		if self.counter > 10:
			# The behaviour will dies when True is returned
			return True
		return False

	# This method is executed when the behaviour dies x_x
	def on_end(self):
		display(self.agent, 'Counting finished.')

if __name__ == '__main__':
	start_loop([CounterAgent('counter')])
```
This code will create an agent to count from 1 to 10. When the `CounterAgent.counter` variable reach the value 10, the `done()` method will return `True`, finishing the behaviour. We also used the `on_end()` method to signalizes when the counting is ended.

### CyclicBehaviour class
This is a class that implements a infinite behaviours. The main difference between this class and those that implement finite behaviours is that the `done()` method of this class always returns `False`, never ending. The cyclic classes have a close relation with behaviours blocking and messages receiving , but it will be explained in the next docs.

Now, we will see an example of an agent that models a clock and shows a message every 1 second.

``` python
from pade.behaviours.types import CyclicBehaviour
from pade.core.agent import Agent
from pade.misc.utility import display_message, start_loop

class TicTacAgent(Agent):
	def setup(self):
		self.add_behaviour(NoiseBehaviour(self))

class NoiseBehaviour(CyclicBehaviour):
	def action(self):
		display_message(self.agent, 'Tic-tac!')
		self.wait(1) # The behaviour will sleep by 1 second

if __name__ == '__main__':
	tic = TicTacAgent('tictac')
	start_loop([tic])
```
There is not much difference between this code and the codes shown above, except that the `CyclicBehaviour` will execute indefinitely. Moreover, is common to use **blocking** and **waiting** methods with cyclic behaviours, like the `wait(float)` method. This method will block the behaviour until the time argument provided in `timeout` ends. It is useful, in our example, to make `TicTacAgent` shows messages within a limit of time (one second, like a clock).

### TickerBehaviour class
This is the other class that implements infinite behaviours. Like `WakeUpBehaviour`, objects from this class will wait a timeout before execute its actions. The difference between the classes is that the `TickerBehaviour` will execute indefinitely. It is important to highlight that the method that implements actions on this class is the `on_tick()` method, rather `action()`.

We will remake the clock example, now using the `TickerBehaviour` class. The code follows below.

``` python
from pade.behaviours.types import TickerBehaviour
from pade.core.agent import Agent
from pade.misc.utility import display_message, start_loop

class TicTacAgent(Agent):
	def setup(self):
		self.add_behaviour(NoiseBehaviour(self, 1))

class NoiseBehaviour(TickerBehaviour):
	def on_tick(self):
		display_message(self.agent, 'Tic-tac!')

if __name__ == '__main__':
	start_loop([TicTacAgent('tictac')])
```

### SequentialBehaviour class
This is the most different class implementing behaviours in PADE. All behaviours in PADE are scheduled parallel, however, sometimes is necessary perform behaviours in a sequential mode. The `SequentialBehaviour` class is a `CompoundBehaviour` subclass which implements sequential behaviours by adding sub-behaviours. All sub-behaviour of this class must to be a `SimpleBehaviour` or its subclasses. The sub-behaviours are added one by one, following an order, which defines the order that the behaviours will be executed.

Unlike simple behaviours, a `SequentialBehaviour` doesn't require implementation for the `action()` method. You just have to add this behaviour to an agent and it will run its sub-behaviours. The example below shows the usage of this class.

``` python
from pade.behaviours.types import OneShotBehaviour, SequentialBehaviour
from pade.core.agent import Agent
from pade.misc.utility import display, start_loop

class SequentialAgent(Agent):
	def setup(self):
		# Defining the sequential behaviour
		sequential = SequentialBehaviour(self)
		# Adding sub-behaviours into 'sequential'
		sequential.add_subbehaviour(Count1_10(self))
		sequential.add_subbehaviour(Count11_20(self))
		sequential.add_subbehaviour(Count21_30(self))
		# Adding 'sequential' into agent
		self.add_behaviour(sequential)

# Behaviour that counts from 1 to 10
class Count1_10(OneShotBehaviour):
	def action(self):
		for num in range(1,11):
			display(self.agent, num)

# Behaviour that counts from 11 to 20
class Count11_20(OneShotBehaviour):
	def action(self):
		for num in range(11,21):
			display(self.agent, num)

# Behaviour that counts from 21 to 30
class Count21_30(OneShotBehaviour):
	def action(self):
		for num in range(21,31):
			display(self.agent, num)

# Starting loop
if __name__ == '__main__':
	start_loop([SequentialAgent('seq')])
```

In the code above, we used the `add_subbehaviour(BaseBehavior)` method to add three different `OneShotBehaviour` to perform a counting. We can add any `SimpleBehaviour` subclass as sub-behaviour of `sequential` object. The order of addition shown above defined the execution order of `sequential` sub-behaviours. To test, try to swap the order of addition of the sub-behaviours in `sequential` and see what happens with your counting.

Finally, we used the `Agent.add_behaviour(BaseBehaviour)` method to add the `sequential` object to the agent. At this moment, the `sequential` behaviour will execute all of its sub-behaviours.

> Note: You can add any `SimpleBehaviour` subclass as `SequentialBehaviour` sub-behaviour, however, if you add an infinite behaviour, the `SequentialBehaviour` never will ends as well. Take it into account when developing your system.

## Behaviour return feature
While you're developing a small multiagent system, the features described above will probably meet all of your needs. Each agent has defined roles and performs a small number of tasks.

However, the world is cruel and, when you're developing more difficult things, in practice, you will see your code tends to be a mess. You will note that the agents will keep them roles, but many of the small tasks that they perform are the same. At this time, you will feel you are writing the same code again and again. This is a disaster!

To deal with cases like these, PADE provides the behaviour return feature. This feature is similar to function return in Python, however, it is implemented using two methods of the `SimpleBehaviour` class (and subclasses): the methods `set_return(data)` and `wait_return()`. Programmatically speaking, this feature implements a thread synchronization, where one thread (a behaviour) waits for the return by another thread (another behaviour).

To understand how these methods works, lets see a general code. Let's assume that `behaviour_a` has a reference to `behaviour_b`. Let's assume also that `behaviour_a` has a `say(str)` method that shows a message in the screen.

``` python
# Code in behaviour_a
behaviour_a.say('The message is: %s' % behaviour_a.wait_return(behaviour_b))
```

The `behaviour_a` executes the method `wait_return()` which calls the return of `behaviour_b`, provided as an argument. At this time, the `behaviour_a` will block and wait for the `behaviour_b`'s return. Let's assume that the following code is executed in `behaviour_b`:

``` python
# Code in behaviour_b
behaviour_b.set_returns('Use Linux. <3')
```

When `behaviour_b` executes the above line, the string `'Use Linux <3'` is returned to `behaviour_a`. At this time, the `behaviour_a` will resume its execution and print the message in the screen.

The behaviour return feature provides the possibility to share behaviours between different agents. This feature allows the programmer to place recurrent code in one behaviour that can be executed by any agent that performs that actions. In addition to avoid code repetition, the behaviour return feature favors the modularization and the code organization.

Let's see the behaviour return feature working in one example. The example below models agents that choose trips within certain criteria. There are two types of agents: the hurried agents (that choose the shortest trips) and the economic agents (that choose the cheapest trips). Note when the behaviour return is used in the code.

``` python
from pade.behaviours.types import WakeUpBehaviour, OneShotBehaviour
from pade.core.agent import Agent
from pade.misc.utility import display, start_loop
import random

# HurriedPassenger Agent
class HurriedPassenger(Agent):
	def __init__(self, aid, start_time, destination, trips):
		super().__init__(aid)
		self.destination = destination
		self.trips = trips
		self.start_time = start_time

	def setup(self):
		self.add_behaviour(ChooseShortestTrip(self, self.start_time))

class ChooseShortestTrip(WakeUpBehaviour):
	def on_wake(self):
		display(self.agent, 'I started to choose the trips.')
		# Creates a behaviour instance
		selected_trips = FilterDestination(self.agent)
		# Adds it in the agent
		self.agent.add_behaviour(selected_trips)
		# Here this behaiviour will block and wait for the
		# `selected_trips` return
		trips = self.wait_return(selected_trips)
		# After the return, we will choose the shortest trip among
		# the returned trips
		if trips == []:
			display(self.agent, 'There is no trips available to %s.' % self.agent.destination)
		else:
			shortest = 0
			for i in range(1, len(trips)):
				if trips[i]['time'] < trips[shortest]['time']:
					shortest = i
			display(self.agent, 'I chose this trip:')
			print('-', trips[shortest])

# EconomicPassenger Agent
class EconomicPassenger(Agent):
	def __init__(self, aid, start_time, destination, trips):
		super().__init__(aid)
		self.destination = destination
		self.trips = trips
		self.start_time = start_time

	def setup(self):
		self.add_behaviour(ChooseCheapestTrip(self, self.start_time))

class ChooseCheapestTrip(WakeUpBehaviour):
	def on_wake(self):
		display(self.agent, 'I started to choose the trips.')
		# Creates a behaviour instance
		selected_trips = FilterDestination(self.agent)
		# Adds it in the agent
		self.agent.add_behaviour(selected_trips)
		# Here this behaiviour will block and wait for the
		# `selected_trips` return
		trips = self.wait_return(selected_trips)
		# After the return, we will choose the cheapest trip among
		# the returned trips
		if trips == []:
			display(self.agent, 'There is no trips available to %s.' % self.agent.destination)
		else:
			cheapest = 0
			for i in range(1, len(trips)):
				if trips[i]['price'] < trips[cheapest]['price']:
					cheapest = i
			display(self.agent, 'I chose this trip:')
			print('-', trips[cheapest])

class FilterDestination(OneShotBehaviour):
	def action(self):
		selection = list()
		# Select the trips with the correct destination
		for trip in self.agent.trips:
			if trip['destination'] == self.agent.destination:
				selection.append(trip)
		display(self.agent, 'I got the trips for %s.' % self.agent.destination)
		# Sets the selected trips able to be returned
		self.set_return(selection)

if __name__ == '__main__':
	trips = list()
	# Randomly creates the buses destinations
	for number in range(700, 720):
		trips.append({
			'number': number,
			'destination': random.choice(['Belém', 'Recife', 'Teresina', 'Fortaleza']),
			'time' : random.randint(20, 35),
			'price' : random.randint(180, 477) + round(random.random(), 2)
		})
	# Prints the entire trips list
	print('The available trips are:')
	for trip in trips:
		print('-', trip)
	# Initiating loop with the passed agents
	agents = list()
	agents.append(HurriedPassenger('hurried-a', 0, 'Belém', trips))
	agents.append(HurriedPassenger('hurried-b', 2, 'Teresina', trips))
	agents.append(HurriedPassenger('hurried-c', 4, 'Fortaleza', trips))
	agents.append(EconomicPassenger('economic-a', 6, 'Recife', trips))
	agents.append(EconomicPassenger('economic-b', 8, 'Belém', trips))
	agents.append(EconomicPassenger('economic-c', 10, 'Fortaleza', trips))
	start_loop(agents)
```

Run the command `pade start-runtime example_name.py` and watch the magic happens. Note that there are different agents performing different actions, having different roles, but sharing the same `FilterDestination` behaviour.  Both type of agents have a common task which is abstracted into a shared behaviour. This is the main contribution of this feature.

You may say "couldn't you solve this problem using just methods or functions?". I answer yes, I could. However, we can see that in large projects with many behaviours and many agents, use foreign behaviour methods may cause confusion in the development. By encapsulating a common action in a single behaviour, you can easily share a behaviour among as many agents as you want.

## Mutual Exclusion with behaviours
At some point in your programmer's life, you may need a behaviour to perform certain activity that another behaviour should not perform at the same time. This is possible to occurs, as the behaviours in PADE are executed in parallel by default. You can suggest me to use the `SequentialBehaviour`, that can solve the most of the problems like this, but it may not fit all cases. The `SequentialBehaviour` executes one behaviour at a time, and this may not be what you want.

When you want to run two or more behaviours of the same agent simultaneously, and also want they synchronize their activities, the mutual exclusion may fit your need. The main idea of mutual exclusion is establish points of code to be executed without interference from other behaviours. It may be useful when you want to ensure that a shared resource (a variable, an object, a file, or another resource) is accessed synchronously by the behaviours of the same or different agent. It may be used also when you want to switch between different roles that an agent can assume throughout its life cycle.

To deal with that, we will need to handle an object from the class `Lock` of the `threading` module. We must create an object from this class and pass it to all the behaviours that we want to synchronize. Besides that, we need to specify which point of the code will stay locked and unlocked. This point is called critical section.

To pass the `Lock` object to the desired behaviours, we must use the `add_lock(lock)` method from the`SimpleBehaviour` class and subclasses. We can use two different ways to indicate the critical section: the `with` Python statement in the `lock` object, or the `acquire()` and `release()` methods from the class `Lock`. To see how these methods work, refer to the `threading.Lock` [documentation](https://docs.python.org/3/library/threading.html#threading.Lock). To illustrate, we will see examples that use the both ways to do the mutual exclusion.

Programmatically speaking, when a behaviour enters its critical section (by entering the `with` statement or executing the `acquire()` method), it checks if another behaviour already holds the lock. If so, the behaviour will block until the other behaviour releases the lock. The release is done when the behaviour leaves its critical section (by leaving the `with` statement or executing the `release()` method). When the lock is free, the behaviour that was waiting holds the lock and any other behaviour will be unable to execute its critical section as well.

If you want to know more about how the `Lock` class works, see the Python threading module documentation [here](https://docs.python.org/3/library/threading.html#lock-objects).

To clear our thinking, we will see two usage examples of behaviours with mutual exclusion: one using the `acquire()` and `release()` `Lock` methods; other using the `with` statement. First, we will rewrite the counting example implemented with `SequentialBehaviour` class. Note the critical sections.

``` python
from pade.behaviours.types import OneShotBehaviour
from pade.core.agent import Agent
from pade.misc.utility import display, start_loop
import threading

class Sequential(Agent):
	def setup(self):
		# Creating a Lock object
		lock = threading.Lock()
		# Creating the behaviours
		count1 = Count1_10(self)
		count2 = Count11_20(self)
		count3 = Count21_30(self)
		# Adding the same lock to behaviours we
		# want the mutual exclusion
		count1.add_lock(lock)
		count2.add_lock(lock)
		count3.add_lock(lock)
		# Adding the behaviours on agent
		self.add_behaviour(count1)
		self.add_behaviour(count2)
		self.add_behaviour(count3)

# Behaviour that counts from 1 to 10
class Count1_10(OneShotBehaviour):
	def action(self):
		# Here starts the critical section (holds the lock)
		self.lock.acquire()
		display(self.agent, 'Now, I will count from 1 to 10 slowly:')
		for num in range(1,11):
			display(self.agent, num)
			self.wait(1) # I put this so that we can see the behaviours blocking
		# Here ends the critical section (releases the lock)
		self.lock.release()

# Behaviour that counts from 11 to 20
class Count11_20(OneShotBehaviour):
	def action(self):
		# Here starts the critical section (holds the lock)
		self.lock.acquire()
		display(self.agent, 'Now, I will count from 11 to 20 slowly:')
		for num in range(11,21):
			display(self.agent, num)
			self.wait(1)
		# Here ends the critical section (releases the lock)
		self.lock.release()

# Behaviour that counts from 21 to 30
class Count21_30(OneShotBehaviour):
	def action(self):
		# Here starts the critical section (holds the lock)
		self.lock.acquire()
		display(self.agent, 'Now, I will count from 21 to 30 slowly:')
		for num in range(21,31):
			display(self.agent, num)
			self.wait(1)
		# Here ends the critical section (releases the lock)
		self.lock.release()

if __name__ == '__main__':
	start_loop([Sequential('seq')])
```

Running the above code, you will see the same results of the `SequentialBehaviour` approach. Although the results are the same, instead of the behaviours execute one after the other, the behaviours are executed in parallel. However, the critical section of each one was executed one at a time, thanks to the mutual exclusion. Try to remove the critical section points to see what happens with the behaviours. ;)

To make sure that the mutual exclusion really works, lets to see another example. Probably our results will be pretty different, once the threads scheduling is different in our hardware and OS. Even so, the code below aims to show us how the mutual exclusion works when many behaviours tries to hold the lock at the same time.

``` python
from pade.behaviours.types import CyclicBehaviour
from pade.core.agent import Agent
from pade.misc.utility import display, start_loop
import threading

class MutualExclusionAgent(Agent):
	def setup(self):
		# Creating a Lock object
		lock = threading.Lock()
		# Creating the behaviours
		say_biscoito = SayBiscoito(self)
		say_bolacha = SayBolacha(self)
		# Passing the same lock object to behaviours
		say_bolacha.add_lock(lock)
		say_biscoito.add_lock(lock)
		# Adding the behaviours in the agent
		self.add_behaviour(say_biscoito)
		self.add_behaviour(say_bolacha)

class SayBiscoito(CyclicBehaviour):
	def action(self):
		# Defines the entire critical section
		with self.lock:
			for _ in range(5): # The agent will hold the lock by 5 prints
				display(self.agent, 'The correct name is "BISCOITO".')
				self.wait(0.5)

class SayBolacha(CyclicBehaviour):
	def action(self):
		# Defines the entire critical section
		with self.lock:
			# Here the agent will hold the lock only by 1 print, and
			# release it right away
			display(self.agent, '"BOLACHA" is the correct name.')

if __name__ == '__main__':
	start_loop([MutualExclusionAgent('mea')])
```

Run the above code and watch the results. Note that the `SayBiscoito` behaviour holds the lock and prints 5 times its phrase. Afterward, it releases the lock and tries to hold it again. If the `SayBolacha` behaviour can hold the lock first, it prints its phrase by 1 time and releases the lock right away. These two behaviours will continue to disputate the same lock for the eternity. All the times that `SayBiscoito` gets the lock, it will print by 5 times, while the `SayBolacha` will print by once. The `SayBiscoito` never will print 4 or 6 times, because its critical section holds the lock exactly by 5 times.

> **Important note:** keep in mind that mutual exclusion can generate problems with deadlock, even in distributed systems. Then, use it with some software engineering to avoid problems. ;)

## Contact us
All the presented code examples can be found at the `pade/examples/behaviours-and-messages/` directory of this repository.

If you find a bug or need any specific help, feel free to visit us or submit an _issue_ on [GitHub](https://github.com/grei-ufc/pade). We appreciate contributions to make PADE better. ;)

>Written by [@italocampos](https://github.com/italocampos) with [StackEdit](https://stackedit.io/).

---

[Universidade Federal do Pará](https://portal.ufpa.br)
[Laboratory of Applied Artificial Intelligence](http://www.laai.ufpa.br)
Instituto de Ciências Exatas e Naturais
Faculdade de Computação
Belém-PA, Brasil

[Universidade Federal do Ceará](http://www.ufc.br/)
[Grupo de Redes Elétricas Inteligentes](https://github.com/grei-ufc)
Fortaleza-CE, Brasil

repository: italocampos/pade

branch_name: refs/heads/message-queue-in-behaviours

gha_language: Python

repo_name: italocampos/pade


text:
---
title: "How `git` works *(from a work presentation)*"
excerpt: "A text-only version of a talk I gave at work outlining its basic workflows and core technical concepts."
last_modified_at: 2022-07-14T07:14:56
categories:
 - Programming
tags:
  - git
  - tools
  - education
---

There are plenty of guides to using `git` all around the web. Why should I add
another drop to a vast ocean of resources?

Well, as someone who's professional experience with
[VCS](https://en.wikipedia.org/wiki/Version_control) has only involved
[Mercurial](https://www.mercurial-scm.org/), I wanted to give myself a deeper
understand of a tool I was going to be using daily. Furthermore, [research
shows](https://onlinelibrary.wiley.com/doi/abs/10.1002/acp.3410) that teaching
others improves one's understanding of the taught material.

When I was offered the chance to give a presentation on `git` at work, I took it
to build my own understanding, and, hopefully, my colleagues' as well. While
this won't be the *most* comprehensive guide on `git`, I wanted to highlight my
learnings to myself and to you, dear reader.

This guide will assume you have basic understandings of *why* developers use
`git`, though will still dive into "basic" topics that I find interesting from a
technical or usability standpoint.
{: .notice--info }

## Common Workflows
Most developers use a single, centralized repository that all individuals `push`
and `pull` from. But aside from that, there's rarely a "one size fits all"
solution to `git`. Here are some basic approaches that I found in my research:

### Gitflow
The Gitflow approach was pioneered in 2010 by [Vincent Driessen at
nvie](https://nvie.com/posts/a-successful-git-branching-model/) and has
wormed its way into enterprise software globally. The idea revolves around two
core branches in your repo: `main` (or `master`) and some `development` branch.

The `development` branch is where *all* branches diverge from and are eventually
re-merged. Then, whenever a new version of the software should be cut, the
`development` branch is merged into `main`.

Effectively, `main` is *only* ever touched by `development`. This prevents any
incomplete code from being checked into `main` and makes the commit history
(ideally) easier to parse, since each commit represents a new version of the
product.

As mentioned in Driessen's 2020 reflection about Gitflow, in the 10 years since,
most software is continuously released, rather than released version-by-version.
Subsequently, a simpler workflow can accomplish the same result.

### Feature Branches *(Preferred)*
Feature branches are, for the most part, identical to the Gitflow approach, with
one major difference: There isn't a `development` branch. By gating merge
commits to `main` with tests, developers can prevent broken code from ever
making it into `main`, which is a huge advantage for continuous integration and
deployment environments.

Rather than merging from `development` into `main` whenever a release is
necessary, commits in `main` can be [tagged as a
release](https://git-scm.com/book/en/v2/Git-Basics-Tagging). This still provides
the rigid versioning structure necessary for some releases without requiring the
overhead of additional branches and special rules.

### Forking
The forking approach breaks the single-remote mold. Each developer has their
*own* remote that they are able to write to at their leisure (even pushing to
`main`!) This is often used for free and open-source
([FOSS](https://itsfoss.com/what-is-foss/)) projects, so that the maintainer
doesn't need to meddle around with permissions for contributers.

To understand forking, it's first important to understand how remotes work. This
was something I learned while researching this presentation:

Remotes are, true to their name, remote repositories to synchronize your changes
with. While most developers use only one, typically hosted on something like
GitHub or BitBucket, multiple remotes can split the management of a codebase
more than just a branch can -- by allowing completely different commit trees
entirely!

With the forking workflow, developers create their own copy of the source repo
to work in. They can always pull in changes from the source repo to their own
copy, that way they'll stay in sync with new features.

When they're ready to commit a change upstream, they make a pull request (PR)
where they can discuss their changes before merging in. In most cases, the
maintainer of the source repo is the only one with write access and is therefore
the "keeper" of features making it into the mainline.

## Other Important Concepts
There were a few other topics that I learned along my journey from a "how does
`git` implement this" standpoint, even if I was already familiar with the terms
and -- in the case of branches, at least -- how to use them.

### Branches
These became a bit easier to visualize once I had a mappable concept in my head.
Branches are nothing more than pointers to a specific hash in the commit tree.
They move as you make commits, but they aren't doing anything special, they just
mark your progress.

In the above diagram, we can see a `foo` branch based on commit `B` and then with
some work in `W` added on top of it. When we create a new branch from `main`,
(also located at `HEAD`, our currently checked-out branch) we are instantiating
a new pointer to the same commit, and moving `HEAD` to show we've checked it
out.

Once we commit some more work to the `bar` branch, we can see a new node in the
tree, and both `bar` and `HEAD` have advanced to this new point in history. In
this way, branches "grow", much like those on a tree.

It can also be useful to run `git` commands using `HEAD`. Appending `~<number>`
will run on a commit relative that number to `HEAD`.

For example, `git
diff HEAD~1` can show you the differences between your staged files and those
already committed.
{: .notice--info }

### Merging
While merging is a common practice, how does it actually work inside of `git`?
There are a few different types of merges, some simple, some more complex.

The first is a `fast-forward` merge. This is the simplest type of merge, since
it happens when there is been no divergence between the two branches. If you
attempted to merge the `bar` branch from the diagram above into `main`, the
`main` pointer could just be shifted forward, since there hasn't been any
committed work to `main`.

A three-way merge is more complex. We can see an example of one in action below:

In this example, there has been some work committed to `main` while we have
been working on `feat`. Since we want to pull in those changes while we keep
working on `feat`, this is called "a merge of `main` into `feat`".

Because the latest commit of the branch you're on isn't a direct ancestor of the
branch you're merging in, `git` has to do some work. In this case, it examines
the latest snapshot of each branch tip (`C` and `Z`) and their common ancestor
-- where they diverged in the tree -- `B`. `git` then tries to determine what's
*actually* changed using a variety of [merge
strategies](https://git-scm.com/docs/merge-strategies).

In some cases, `git` can't figure this out, and you have to resolve a merge
conflict. But regardless, any changes to `feat` are stored in new merge commit
on the branch (`M`). Future patches can still be applied onto `feat`, as seen by
patch `N`.

It is also possible to apply work between branches using `git rebase`, though
its main benefit is creating a cleaner, more linear `git` history. In my
experience, being proficient with `git merge` will get you by and is a great
place to start.
{: .notice--info }

### Merge Commits
Once you decide to *perform* a merge, now you have a choice of how you'd like
`git` to do it for you.

Merge commits provide granular, in-depth history, since they preserve the work
from each commit in `feat` when joined into `main`. They are best used for
bug-prone logic changes where bisecting commits can expedite detection.

Squash commits combine all of the work from `feat` into a *single* commit onto
`main`. This means the history is much simpler -- one big pile of changes -- but
can be harder to sift through. It's best used for a series of like patches, such
as style fixes or refactors.

Although there's a big trade-off between each, I've heard Squashes favored more
often than not. It may be that, like rebasing, a better `git` history is rarely
appreciated. Though, when it's needed, it can be nice to have done the work and
made your life easier.

---

There's still a lot more I have to learn with `git`. Maybe another presentation
and subsequent post are in order? All I know is that I look forward to
deepening my knowledge of `git` as I use it more both professionally and
personally.

gha_language: Rust


text:
# LtlPacker, code example

## Problem Description

Given 4 trucks each with available capacity, write an algorithm to distribute shipments as evenly as possible, trying to ship all goods and minimize wasted space.

## Summary

For this exercise, I tried a couple of different things.  I have to say, I enjoyed it quite
a bit.  This is exactly the sort of thing I like to work on.

I chose to initialize this project as a gem, and went on from there, so that it would look
a little more professional, but honestly, the solution I settled on could probably fit in
less than 20 lines of code, just using some raw hashes.

The final result prioritizes maximizing the total capacity ships, along with an
even distribution of loads.  I de-prioritized maximizing the shipment total count.
There is a line in the
[best_fit_decreasing_combinations.rb](/best_fit_decreasing_combinations.rb)
file, where you can tweak these settings.  The concern is, since I leaned toward balancing
shipments over everything, a shipment that takes up a whole truck may never leave the dock :)
That, plus the over-fitting issue, when working with sample data, means that a different
choice when sorting shipments may be less efficient overall, but work better against all
datasets.  I'm only shipping 8 shipments, but that allows them to be distributed evenly
across trucks, with two shipments per truck.

I read up a bit on this problem, and settled on the 'best fit, decreasing' algorithm.  It
didn't pack as tightly as I wanted, so I added 'combinations' to it, so that I could pack
shipments two at a time, and create more discrete capacities.

I created a 'brute force' solution, that generated a bunch of possible solutions, and then
did queries against that data set from the console, to see what the possibilities were.
That helped me to set goals for the final algorithm, but in real life, the brute force
solution might be fine.  If the dataset is limited, and processor cycles are cheap, why
not generate every possible load combination, and choose the best one, depending on the
priorities of the day?

## Installation

`git clone git@github.com:tnordloh/ltl_packer.git`

## Running

Since this is a local gem, the best way to run it is to prepend `bundle exec`, and run it
from the root directory of the gem.

I ran this using Ruby version 2.5.1.

Main algorithm:

`bundle exec ./best_fit_decreasing_combinations.rb`

Brute force:

`bundle exec ./brute_force.rb`

If you want to look at the various shipments produced by the brute force version, just
insert `require 'byebug' ; byebug` at the end, and try it out :).

gha_language: Ruby


text:
---
title: 🏎 🏎Advanced Node.Js, A Hands on Guide to Event Loop, Child Process and Worker Threads in Node.Js
date: "2020-01-23T23:46:37.121Z"
layout: post
draft: false
path: "https://blog.soshace.com/advanced-node-js-a-hands-on-guide-to-event-loop-child-process-and-worker-threads-in-node-js/"
category: "Node.js"
tags:
  - "Node.js"
description: "What makes Node.js so performant and Scalable? Why is Node the technology of choice for so many companies? In this article, we will answer these questions and look at some of the advanced concepts that make Node.js unique. Let's dive in !!!"
---


text:
# react-native-pull-to-refresh
> The pull-to-refresh ScrollView component for React Native

forked from https://github.com/moschan/react-native-pull-to-refresh

added cross-platform support (uses PullToRefreshViewAndroid on android devices)

the arrow and indicator are fixed to the top of the pull to refresh view and do not scroll with the content

# License
MIT


text:
---
layout: ../layouts/AboutLayout.astro
title: "About"
---

I'm a software engineer primarily working on backend systems

## Opensource Work

### Zulip

I've started contributing to Zulip in September 2019, since then I've worked on a
variety of projects related to auth, chat features like typing indicators, read receipts etc, automation tests, documentation and other areas.

I was selected as a Google Summer of Code (GSoC) Developer to work with Zulip in the
summers of 2020, 2021.

I have also mentored a student in GSoC 2022.

## Professional Experience

### 100ms.live

I'm working at 100ms.live as a Software engineer in the infra team since May 2022.

## Education

### National Institute of Technology (2018-2022)
Bachelor of Technology in Computer Science & Engineering.


text:
---
title: Psoriasis
...

- Common papulo-squamous disorder
- Affects 2% of the population
- Characterised by demarcated, red, scaly plaques
- Skin becomes inflamed and hyperproliferates at 10 times the normal rate

### Clinical Features

### Chronic Plaque Psoriasis

- Most common type
- Characterised by pinkish red scaly plaques, with a silver scale, especially on extensor surfaces such as knees and elbows
- New sites of plaques at the sites of trauma

### Flexural Psoriasis

- Occurs in later life
- Well-marcated red glaze plaques confined to flexures

### Guttate Psoriasis

- Most commonly seen in kids and young adults
- Explosive Eruption of very small circular or oval plaques appears over the trunk about two weeks after a Strep sore throat

### Erythrodermic and Pustular Psoriasis

- Most severe types
- They can occur together and may be assoicated with malaise, pyrexia and circulatory disturbance
- Can be life-threatening

### Associated Features

- About 50% of people develop nail changes
- 5-10% develop Psoriatic Arthritis

### Treatment

Concerns with control rather than cure and be tailored to patients wishes:

### Chronic Plaque Psoriasis

- Emollients
- Mild to Moderate Topical Steroids
- Synthetic Vitamin D3 Analogues
- Retinoids
- Coal Tar

Topical therapies are sometimes used in combination with UVB or PUVA.

### Flexural Psoriasis

- Mild Steroid
- Tar topical creams
- Calcitriol and 0.1% Tacrolimus ointment

### Erythodermic Psoriasis

- Systemic therapy (Methotrextate, acitretin, ciclosporin, mycophenylate)
- General supportive measures

### Prognosis

- Most with chronic plaque psoriasis will have it lifelong with intervals of remission
- Guttate psoriasis resolves spontaneously in up to a third of individuals

repository: davidecarroll/genmednotes

repo_name: davidecarroll/genmednotes


text:
---
type: rule
archivedreason:
title: What to do with old employees?
guid: 11d6567c-c718-4297-aad1-c1a463e0b7c4
uri: what-to-do-with-old-employees
created: 2017-01-17T11:02:26.0000000Z
authors:
- title: Danijel Malik
  url: https://ssw.com.au/people/danijel-malik
related: []
redirects: []

---

When migrating from TFS to the cloud you will find that a list of historical users may be quite long.

<!--endintro-->

![](old-employees-to-the-cloud.jpg)

Many of these users are likely to be gone but they are preserved in TFS for historical purposes. What are you going to do with them?
**A)** All account stays active (total 700 in AD) – this is a hard one because you need to bring all accounts in Azure AD and generally you don’t need those users
**B)** Old employees are carried over as phantom  (so only 40 are migrated) – Recommended because you will still see the history but not those accounts are not active anymore
       Eg. If Paul Stovell comes back he needs a new account (because you can't reuse the SID)


text:
---
title: SHRead2Error (Python)
keywords: spherical harmonics software package, spherical harmonic transform, legendre functions, multitaper spectral analysis, fortran, Python, gravity, magnetic field
sidebar: mydoc_sidebar
permalink: pyshread2error.html
summary:
tags: [python]
toc: false
---

Read spherical harmonic coefficients from a CHAMP or GRACE-like ascii-formatted file.

## Usage

`cilm`, `error`, `lmax`, `gm`, `r0_pot`, `dot`, `doystart`, `doyend`, `epoch` = SHRead2Error (`filename`, `lmaxin`)

## Returns

`cilm` : float, dimension (2, `lmaxin`+1, `lmaxin`+1)
:   The spherical harmonic coefficients contained in `filename`.

`error` : float, dimension (2, `lmaxin`+1, `lmaxin`+1)
:   The uncertainty of the spherical harmonic coefficients contained in `filename`.

`lmax` : integer
:   The maximum spherical harmonic degree of `cilm`. This is the minimum of the dimension of `cilm` and `lmaxin`.

`gm` : float
:   The mass-gravitational constant.

`r0_pot` : float
:   The reference radius of the potential coefficients.

`dot` : float, dimension (2, `lmaxin`+1, `lmaxin`+1)
:   The time derivatives of the spherical harmonic coefficients. The dimension of this array can be smaller than `lmax+1`.

`doystart` : float
:   The starting time of the solution.

`doyend` : float
:   The ending time of the solution

`epoch` : float
:   The epoch time for the time derivates.

## Parameters

`filename` : character(*)
:   The ascii-formatted filename containing the spherical harmonic coefficients.

`lmaxin` : integer
:   This spherical harmonic degree controls the dimension of the output array `cilm`. The coefficients between `lmax+1` and `lmaxin` will be set to zero.

## Description

`SHRead2Error` will read spherical harmonic coefficients from a CHAMP or GRACE-like ascii-formatted file into an array `cilm`. The errors and time derivatives associated with the coefficients will be read if the optional arrays `error` and `dot` are specified, respectively. The staring and ending date of the solution are specified by the optional parameters `doystart` and `doyend`, and the epoch of the time derivates is specified by the optional parameter `epoch`. The maximum spherical harmonic degree is read from the file, and the file does not need to be ordered by angular degree or order.

This routine does not read and output all parameters in the file. Records that are read (and at least partially output) include: `EARTH`, `GGM`, `SHM`, `GRCOF2`, `GRDOTA`, `CALSDV`, `gfc`, `gfct`, and `dot`. Comments specified by the record `CMMNT` will be print out to the screen, as will the record names that are not currently implemented.

Each line of the file starts with a character string describing what follows.

- `EARTH` or `GGM`: `GM`, `R0_POT`
- `SHM`: Maximum spherical harmonic degree of file.
- `GRCOF2`, `CALSDV`, or `gfc`: spherical harmonic coefficients, formatted as (`l`, `m`, `clm`, `slm`) or (`l`, `m`, `clm`, `slm`, `clm_error`, `slm_error`).

## See also

[shread](pyshread.html), [shread2](pyshread2.html), [shreadjpl](pyshreadjpl.html)

repository: MMesch/SHTOOLS

repo_name: MMesch/SHTOOLS


text:
webaudio-mod-player
===================

This is a Protracker module player implemented in JavaScript using the Web Audio API. It supports standard 4-channel Amiga Protracker modules, as well as 6- and 8-channel PC FastTracker modules. Multichannel modules also work, although mod.dope ('28CH') has only been tested with.

You can test the player here:

http://mod.haxor.fi/

The player supports most Protracker effects, including the 'LED filter' command. Some effects still need work, though (try playing mod.black_queen by Dreamer - pattern loops fail spectacularly).

To install on your own server, clone the repo to the document root and edit+rename example.htaccess to match your domain. Then create a directory 'mods' alongside index.php and structure is like this (note Amiga-style filenames with lowercase 'mod'!):

mods

mods/Mantronix_and_Tip

mods/Mantronix_and_Tip/mod.overload

mods/mod.saf

Copyrights:

- Protracker module player for Web Audio (c) 2012-2014 Jani Halme

- Topaz TTF font (c) 2009 dMG of Trueschool and Divine Stylers

- mod.overload (c) 1991 by Mantronix and Tip of Phenomena

repository: lyzzard/webaudio-mod-player

repo_name: lyzzard/webaudio-mod-player


text:
# "BDD Testing for Django Apps" by Le Xiao

## BDD environment setup

* `behave` library
* Gherkin feature files
* Selenium

### Tooling setup

1. Install chromedriver
1. Install geckodriver
1. Check if Selenium is able to launch a browser

### Testing setup

1. Create feature files
1. Apply a step convention:
  * Keywords translate to page objects and action words that formalize elements and behavior under test
1. Use fixtures for data, or use `factoryboy` to set up dummy data
1. Create a test runner to run all the features, scenarios, etc.

### Page objects

* Ask front-end development to create unique identifiers (whether `id` or custom `data-` attributes) for easier object identification

### Running tests

`python manage.py behave`

## Continuous integration/delivery

* Hiptest as a feature file management tool
* BrowserStack, SauceLabs, SmartBear for cross-platform testing
* PhantomJS or Puppeteer for headless browser testing

Minimizing test run time will cut down on cost for products that charge per-minute of execution time.

## Limitations

* Conditional testing is difficult since test descriptions are linear
* Selenium is sometimes difficult to use when interacting with JavaScript


text:
# flask-blog-template
This is a basic blogging app template developed with Python Flask on the backend. I made it simply to learn how to use the Python Flask framework, but after finishing, I figured someone might find it useful as a starting point/template for their app. Primary features of the template: user authentication, basic user profile including profile picture uploads, creating/editing/deleting posts, and loading posts to a central newsfeed.

**Technologies used:**
   * Python Flask
   * HTML templating with Jinja2
   * CSS3 styling
   * Bootstrap
   * Minimal javascript used for post feed loading
   * MongoDB database

## Usage
1. Fork the repository, clone it, and cd into the directory

1. Resolve the dependencies:
   * `pip install flask flask_login bson flask_bcrypt pymongo flask_wtf wtforms pillow`

1. Set up a mongo database instance. My provider of choice is [mLab](https://www.mlab.com)

1. Set expected environmental variables:
   * SECRET_KEY: some random text will suffice
   * FLASK_ENV: "development"
   * FLASK_APP: the name of the file which initializes the flask app (in this case it is server.py but you can change that)
   * MONGODB_URI: the database uri for the mongo instance
   * *Note: for your convenience, you should consider creating a bash script file (such as env.sh) and set all of the  environmental variables there. Then each time to start development. You simply need to source the file with the command `source env.sh` and the enviormental variables will be set for you.*

1. Start up the server: `flask run`

1. Navigate to localhost:5000

repository: ebadgio/flask-blog-template

repo_name: ebadgio/flask-blog-template


text:
# Automated EDA on financial dataset

Just a simple way to get automated Exploration Data Analysis from financial dataset (OHLCV) using [Streamlit](https://github.com/streamlit/streamlit) and [ta](github.com/bukosabino/ta).

To use this library you need a financial time series dataset including `Timestamp`, `Open`, `High`, `Low`, `Close` and `Volume` columns.

# Requirements

* python3.7 version

# Run

```sh
pip install streamlit==0.48.1 ta==0.4.5
streamlit run https://raw.githubusercontent.com/bukosabino/streamlit-demo-financial-eda/master/app.py
```

# TODO

* Heatmap: Visualize the correlation coefficient in between ta features.
* Web application user can load a .csv file

# Extra

Are you interested in more Streamlit demos related to financial data?

* [Yahoo Finance data web app](https://github.com/paduel/streamlit_finance_chart)

# Contact

Developed by Darío López Padial (Bukosabino).

Please, let me know about any comment or feedback.

repository: paduel/streamlit-demo-financial-eda

repo_name: paduel/streamlit-demo-financial-eda


text:
crunchbase
==========

Python library for pulling data from the CrunchBase API.

## Usage

Make sure to set the environment variable `CRUNCHBASE_TOKEN`, or `CrunchBase(your_crunchbase_key)`

If you already know the permalink or the uuid for a given entity, you can grab the entry
with the `get_entity` method.

```python

    from crunchbase import CrunchBase

    cb_api = CrunchBase('my_key')
    dustin = cb_api.get_person('dustin-moskovitz')
    facebook = cb_api.get_organization('facebook')
    facebook_like_box = cb_api.get_product('facebook-like-box')
    venture_round = cb_api.get_funding_round('b0e3eb999048d301089226cedab900a7')
    fund_raise = cb_api.get_fund_raise('b0e3eb999048d301089226cedab900a7')
    facebook_ipo = cb_api.get_ipo('a3bc391490d52ba8529d1cfc20550a87')
    whats_app_acquisition = cb_api.get_acquisition('90ad2f738079c7c0dffc66cb82487a11')
```

### List all Items

To get the list of every single item for a given entity type, you can do so
with the +get_entities+ method.

```python
    cb_api.get_organizations()
    cb_api.get_people()
    cb_api.get_products()
    cb_api.get_categories()
    cb_api.get_locations()
```

This returns an array containing objects representing each entity.

### Search

Searching the Crunchbase is possible for `organizations`, with this parameters:

```python
    query: str or unicode (name, previous names, location, and domain name)
    name: str or unicode (filter organization by name)
    organization_type: list (filter organization by one or more types).
    locations: list (filter Organizations by one or more Location UUIDs.)
    categories: list (filter Organizations by one or more Category UUIDs.)
    page: str or unicode or int (the page of results to retrieve )

    cb_api.get_organizations(**filters)
```

## Contributing

Contributions are welcome.


text:
---
layout: post
title: Upgrade Ubuntu 18.04 to 20.04
date: 2022-06-27 14:39:00
comment_id: 224
categories: [Ubuntu 18.04, Linux, Ubuntu 20.04]
---

By upgrade from command line:

```sh
sudo apt install update-manager-core
sudo do-release-upgrade
```

## Troubleshooting

### 1. Please install all available updates for your release before upgrading

```sh
sudo apt update
sudo apt upgrade
sudo apt dist-upgrade
```

### 2. To upgrade to the latest non-LTS develoment release, set Prompt=normal

The issue

```sh
To upgrade to the latest non-LTS dvelopment release
set Prompt=normal in /etc/update-manager/release-upgrades
```

#### Reference

- <https://www.cyberciti.biz/faq/upgrade-ubuntu-18-04-to-20-04-lts-using-command-line/>

gha_language: CSS


text:
# StackApps

Integration with the Critical Stack [StackApps](https://github.com/criticalstack/stackapps) component.

- Requirements and Installation
- Verification/Signing Keys
- Drift detection
- StackValues

## Planned Features

- Revision management
- StackValue configuration