text:
---
layout: default
title: "The UpdateButton Component"
---

# `<UpdateButton>`

This component allows to create a button that updates a record by calling the [`useUpdate hook`](./useUpdate.md).

<video controls playsinline muted loop poster="./img/updatebutton.png" >
  <source src="./img/updatebutton.webm" type="video/webm" />
  <source src="./img/updatebutton.mp4" type="video/mp4" />
  Your browser does not support the video tag.
</video>

## Usage

Use `<UpdateButton>` inside the actions toolbar of the [`Edit`](./Edit.md#actions) or [`Show`](./Show.md#actions) views.

{% raw %}
```jsx
import { Edit, SimpleForm, TextInput, TopToolbar, UpdateButton } from 'react-admin';

const PostEditActions = () => (
    <TopToolbar>
        <UpdateButton label="Reset views" data={{ views: 0 }} />
    </TopToolbar>
);

export const PostEdit = () => (
    <Edit actions={<PostEditActions />}>
        <SimpleForm>
            <TextInput source="title" />
            <TextInput source="body" />
        </SimpleForm>
    </Edit>
);
```
{% endraw %}

## Props

`<UpdateButton>` accepts the following props:

| Prop             | Required | Type        | Default    | Description                                              |
| ---------------- | -------- | ----------- | ---------- | -------------------------------------------------------- |
| `data`           | Required | `object`    |            | The data used to update the record                       |
| `mutationMode`   | Optional | `string`    | `undoable` | Mutation mode (`'undoable'`, `'pessimistic'` or `'optimistic'`) |
| `confirmTitle`   | Optional | `ReactNode` | `ra.message.bulk_update_title` | The title of the confirmation dialog when `mutationMode` is not `undoable` |
| `confirmContent` | Optional | `ReactNode` | `ra.message.bulk_update_content` | The content of the confirmation dialog when `mutationMode` is not `undoable` |
| `mutationOptions` | Optional | `Object`  |        | The react-query mutation options |

`<UpdateButton>` also accepts the [Button props](./Buttons.md#button).

## `data`

The data used to update the record. Passed to the `dataProvider.update` method. This prop is required.

{% raw %}
```tsx
import { TopToolbar, UpdateButton } from 'react-admin';

const PostEditActions = () => (
    <TopToolbar>
        <UpdateButton label="Reset views" data={{ views: 0 }} />
    </TopToolbar>
);
```
{% endraw %}

## `mutationMode`

The mutation mode determines when the side effects (redirection, notifications, etc.) are executed:

- `pessimistic`: The mutation is passed to the dataProvider first. When the dataProvider returns successfully, the mutation is applied locally, and the side effects are executed.
- `optimistic`: The mutation is applied locally and the side effects are executed immediately. Then the mutation is passed to the dataProvider. If the dataProvider returns successfully, nothing happens (as the mutation was already applied locally). If the dataProvider returns in error, the page is refreshed and an error notification is shown.
- `undoable` (default): The mutation is applied locally and the side effects are executed immediately. Then a notification is shown with an undo button. If the user clicks on undo, the mutation is never sent to the dataProvider, and the page is refreshed. Otherwise, after a 5 seconds delay, the mutation is passed to the dataProvider. If the dataProvider returns successfully, nothing happens (as the mutation was already applied locally). If the dataProvider returns in error, the page is refreshed and an error notification is shown.

By default, the `<UpdateButton>` uses the `undoable` mutation mode. This is part of the "optimistic rendering" strategy of react-admin ; it makes user interactions more reactive.

You can change this default by setting the `mutationMode` prop. For instance, to remove the ability to undo the changes, use the `optimistic` mode:

{% raw %}
```jsx
import { TopToolbar, UpdateButton } from 'react-admin';

const PostEditActions = () => (
    <TopToolbar>
        <UpdateButton label="Reset views" data={{ views: 0 }} mutationMode="optimistic" />
    </TopToolbar>
);
```
{% endraw %}

And to make the action blocking, and wait for the dataProvider response to continue, use the `pessimistic` mode:

{% raw %}
```jsx
import { TopToolbar, UpdateButton } from 'react-admin';

const PostEditActions = () => (
    <TopToolbar>
        <UpdateButton label="Reset views" data={{ views: 0 }} mutationMode="pessimistic" />
    </TopToolbar>
);
```
{% endraw %}

**Tip**: When using any other mode than `undoable`, the `<UpdateButton>` displays a confirmation dialog before calling the dataProvider.

## `confirmTitle`

Only used when `mutationMode` is either `optimistic` or `pessimistic` to change the confirmation dialog title:

{% raw %}
```jsx
import { TopToolbar, UpdateButton } from 'react-admin';

const PostEditActions = () => (
    <TopToolbar>
        <UpdateButton
            label="Reset views"
            data={{ views: 0 }}
            mutationMode="optimistic"
            confirmTitle="Reset views"
        />
    </TopToolbar>
);
```
{% endraw %}

## `confirmContent`

Only used when `mutationMode` is either `optimistic` or `pessimistic` to change the confirmation dialog content:

{% raw %}
```jsx
import { TopToolbar, UpdateButton } from 'react-admin';

const PostEditActions = () => (
    <TopToolbar>
        <UpdateButton
            label="Reset views"
            data={{ views: 0 }}
            mutationMode="optimistic"
            confirmContent="Do you really want to reset the views?"
        />
    </TopToolbar>
);
```
{% endraw %}

## `mutationOptions`

`<UpdateButton>` calls `dataProvider.update()` via react-query's `useMutation` hook. You can customize the options you pass to this hook, e.g. to pass [a custom `meta`](./Actions.md#meta-parameter) to the `dataProvider.update()` call.

{% raw %}
```jsx
import { TopToolbar, UpdateButton } from 'react-admin';

const PostEditActions = () => (
    <TopToolbar>
        <UpdateButton
            label="Reset views"
            data={{ views: 0 }}
            mutationOptions={{ meta: { foo: 'bar' } }}
        />
    </TopToolbar>
);
```
{% endraw %}

You can also use `mutationOptions` to override success or error side effects, by setting the `mutationOptions` prop. Refer to the [useMutation documentation](https://tanstack.com/query/v3/docs/react/reference/useMutation) in the react-query website for a list of the possible options.

Let's see an example with the success side effect. By default, when the action succeeds, react-admin shows a notification, and refreshes the view. You can override this behavior and pass custom success side effects by providing a `mutationOptions` prop with an `onSuccess` key:

{% raw %}
```jsx
import * as React from 'react';
import { useNotify, useRefresh, useRedirect, TopToolbar, UpdateButton } from 'react-admin';

const PostEditActions = () => {
    const notify = useNotify();
    const redirect = useRedirect();

    const onSuccess = () => {
        notify(`Changes saved`);
        redirect('/posts');
    };

    return (
        <TopToolbar>
            <UpdateButton
                label="Reset views"
                data={{ views: 0 }}
                mutationOptions={{ onSuccess }}
            />
        </TopToolbar>
    );
}
```
{% endraw %}

The default `onSuccess` function is:

```js
() => {
    notify('ra.notification.updated', {
        messageArgs: { smart_count: 1 },
        undoable: mutationMode === 'undoable'
    });
}
```

**Tip**: When you use `mutationMode="pessimistic"`, the `onSuccess` function receives the response from the `dataProvider.update()` call, which is the edited record (see [the dataProvider documentation for details](./DataProviderWriting.md#response-format)). You can use that response in the success side effects:

{% raw %}
```jsx
import * as React from 'react';
import { useNotify, useRefresh, useRedirect, TopToolbar, UpdateButton } from 'react-admin';

const PostEditActions = () => {
    const notify = useNotify();
    const redirect = useRedirect();

    const onSuccess = (data) => {
        notify(`Changes to post "${data.title}" saved`);
        redirect('/posts');
    };

    return (
        <TopToolbar>
            <UpdateButton
                label="Reset views"
                data={{ views: 0 }}
                mutationOptions={{ onSuccess }}
            />
        </TopToolbar>
    );
}
```
{% endraw %}

Similarly, you can override the failure side effects with an `onError` option. By default, when the save action fails at the dataProvider level, react-admin shows a notification error.

{% raw %}
```jsx
import * as React from 'react';
import { useNotify, useRefresh, useRedirect, TopToolbar, UpdateButton } from 'react-admin';

const PostEditActions = () => {
    const notify = useNotify();
    const refresh = useRefresh();
    const redirect = useRedirect();

    const onError = (error) => {
        notify(`Could not edit post: ${error.message}`);
        redirect('/posts');
        refresh();
    };

    return (
        <TopToolbar>
            <UpdateButton
                label="Reset views"
                data={{ views: 0 }}
                mutationOptions={{ onError }}
            />
        </TopToolbar>
    );
}
```
{% endraw %}

The `onError` function receives the error from the `dataProvider.update()` call. It is a JavaScript Error object (see [the dataProvider documentation for details](./DataProviderWriting.md#error-format)).

The default `onError` function is:

```jsx
(error) => {
    notify(typeof error === 'string' ? error : error.message || 'ra.notification.http_error', { type: 'error' });
}
```

## `sx`

The sx prop lets you style the component and its children using Material-ui's [sx syntax](https://mui.com/system/the-sx-prop/).

{% raw %}
```jsx
import { TopToolbar, UpdateButton } from 'react-admin';

const PostEditActions = () => (
    <TopToolbar>
        <UpdateButton label="Reset views" data={{ views: 0 }} sx={{ width: 500 }} />
    </TopToolbar>
);
```
{% endraw %}

repository: marmelab/react-admin

repo_name: marmelab/react-admin


text:
##VH(i)ZR - VueJs, HoriZon RethinkDB Admin demo app
====
VH(i)ZR - **Vue**js **H**or**i****Z**on **R**ethinkdb

It is just a crude database admin demo app using [Horizon] (http://horizon.io/) - A realtime open-sourced backend for realtime apps

![screenshot] (http://res.cloudinary.com/froogle/image/upload/v1464335352/vhizr.png)

Dependencies
* VueJs, Vue-Loader
* Webpack, Webpack-dev-server
* Horizon
* RethinkDB

To get the example running on your system
```javascript
git clone https://github.com/sachinbhutani/vhizr vhizr
cd vhizr
npm install
npm run dev
```
Point your [browser] to [http://localhost:9090] (http://localhost:9090/)`

The app needs an existing rethinkdb instance to be running.
If you like VH(i)ZR to run an rethinkdb instance for you
use
`npm run rdev` instead of  `npm run dev`

####Adding a collection to VH(i)ZR####
No collection are included in the interface unless explicitly added.
If a existing collection is added, it's data is available for display and update instantly.
Try adding default user collection **users*
If the collection does not exist it would be created for you with no data

####Removing a collection to VH(i)ZR####
To remove a collection from VH(i)ZR, Select the collection from the menu and then click
"Remove from VH(i)ZR".
Removing a collection from VH(i)ZR only removed it from the admin interface and
does not delete data from the collection

####Schemas/Forms??####
Based on the solution for issues [#138] (https://github.com/rethinkdb/horizon/issues/138) and [#468] (https://github.com/rethinkdb/horizon/issues/468)
I may be able to add schema/validation and automated forms to the interface.
but for now you would need to edit JSON.

####TODO####
* Pagination
* Authentication and Authorization
* Permissions
* Schema validation and auto-forms

License: MIT

license: MIT

repository: IguMail/vhizr

branch_name: refs/heads/master

extension: md

license_type: permissive

repo_name: IguMail/vhizr


text:
#
   Insomnia

Insomnia will remind you to take a rest and that you can always come back to the work tomorrow.
Inspired by http://sleepyti.me a website that calculates optimal times to fall asleep based on when you want to wake up.
The idea is that when you wake up in the middle of a sleep cycle you will feel groggy, however if you wakeup during the
transition between sleep cycles you will feel refreshed!

This application uses the averages that sleep cycles are 90 minutes each and a person takes 15 minutes to fall asleep from when they begin to try and calculates the times for you to sleep. It will notify you throughout the night when the optimal times to shutdown your computer and start to head to sleep and provide a button to do just that. This application works well with https://justgetflux.com/

#
 Screenshots

MenuBar

Notification

Main Window

About Window

Preferences Window

#
 Downloads

To get the full sourced version run

      git clone https://github.com/alexanderepstein/Insomnia

Otherwise to just get the application download your respective platforms file from the list of download links below.

* Debian Linux 32 Bit

* Debian Linux 64 Bit

* Mac OS 64 Bit

* Windows 32 Bit

* Windows 64 Bit

#
 Install

* Mac: Open up a new finder window and go to the Applications folder. Then drag the Insomnia.app from the Insomnia dmg to the Applications folder. Double Clicking on the app should run it and it could be kept in the dock from here.

* Linux: Open up a terminal and navigate to the folder containing the downloaded installer files and run

           sudo dpkg -i Insomnia_1.1.0_amd64.deb
           or
           sudo dpkg -i Insomnia_1.1.0_x86.deb
  this will actually install Insomnia as a utility application which can be accessed from your respective distributions application launchpad.

* Windows: Open up another windows explorer and navigate to your program files folder (x86 or 64 bit is irrelevant).  Now drag the entire Insomnia Windows folder you extracted  from the downloaded zip in the previous step over to the program files folder. Go into the folder that was just dragged over and find the Insomnia.exe and run it. Now the application will show up in the dock where it can be pinned.

#
 Uninstall

* Mac: Go to the applications folder and delete the Insomnia application.

* Linux: Open up a terminal and run

      sudo dpkg --remove Insomnia

* Windows: Open up the program files folder and delete the Insomnia folder.

#
 License

MIT License

Copyright (c) 2017 Alex Epstein

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#
 Helping Out

(It is assumed you already have node installed and therefore npm)

To download the full source code and install the devDependencies run the following lines

    git clone https://github.com/alexanderepstein/Insomnia
    cd Insomnia
    npm install
    cd ..
    electron Insomnia //this will run the application

If you get some error and the application wont run try running the following lines and see if that works

 Linux/Mac

    cd Insomnia
    sudo npm install -g

 Windows

Right click on the start menu icon at the bottom left and click on the option to open a command prompt in developer mode
cd to the insomnia directory then run

     npm install -g

 If you have a feature you would like to add or optimizations to the original code

   * Feel free to fork this repository and submit a pull request
   * Add an issue labeled as an enhancement and if I think its a good idea I will do my best to implement it myself


text:
Bounds calculators

```
    Bounds bounds = new GameObjectBoundsCalculator().Calculate(gameObject);
    # => Center: (0.0, 0.8, 0.0), Extents: (0.5, 0.8, 0.5)

    bounds.size
    # => (1.0, 1.6, 1.0)
```

The scripts come in two flavors:

* GameObjectBoundsCalculator for regular instantiated GameObjects
* PrefabBoundsCalculator for prefabs

They both use Collider bounds for their calculations.  If that's not what you
want, you could modify GameObjectsBoundsCalculator to use one of these:

* Renderer.bounds: http://docs.unity3d.com/Documentation/ScriptReference/Renderer-bounds.html
* Mesh.bounds: http://docs.unity3d.com/Documentation/ScriptReference/Mesh-bounds.html

PrefabBoundsCalculator is a little special.  There appears to be no way to get
the bounds of a Prefab without instantiating it, so this class does the naive
thing by instantiating it briefly, grabbing the bounds, then deleting it.  I was
able to use this without unforseen side-effects, but you know, I have no idea
what kind of city-sized meshes you guys out there are building.

Contact me if you've got any questions, bugs or contract work to throw my way.

Cheers,

Mike

<EMAIL_ADDRESS>
@mikelovesrobots on Twitter


text:
# hackerrank
Repo for HackerRank projects

#### Note: Send stdin stream, split on each new line, to an array for easier manipulation.
example if input is the var assigned stdin:
let inputArr = input.split("\n");

repository: cdamyx/hackerrank

repo_name: cdamyx/hackerrank


text:
# The Gizmo/Serverless Example

This example shows how to use service initiation in the [Gizmo server](https://godoc.org/github.com/NYTimes/gizmo/server) to fetch secrets from Vault.

To run this against your own Vault installation, update the values in `server/run_local.sh` for local development.

repository: darrenmcc/gcp-vault

repo_name: darrenmcc/gcp-vault


text:
---
title: "Git: Correcting mistakes 1 (stashing)"
date: "2020-12-04"
description: Do you find git daunting when you have to run any command other than the common ones? Do you face a fear of messing up like never before? This blog series will help you fight that fear. This blog covers 'stash'.
---

Do you find git daunting when you have to run any command other than the common ones? Do you face a fear of messing up like never before? This blog series will help you fight that fear.

![image](https://imgs.xkcd.com/comics/git.png)

When we go wrong, we follow the steps mentioned in the meme, which include saving our work and downloading a fresh copy. 🙃 While this seems like a good "jugaad" (hack), it becomes tedious. However, there is always a better solution.

Let's start with a simple command which will be useful in some such scenarios.

### Stash

A glance at what the [Pro Git](https://git-scm.com/book/en/v2) book written by Scott Chacon and Ben Straub says

> Stashing takes the dirty state of your working directory — that is, your modified tracked files and staged
> changes — and saves it on a stack of unfinished changes that you can reapply at any time (even on a different branch).

Right..... Okay...... But, what does this mean? 🤔

Well, a real-world analogy would be helpful here.

Think of stashing as placing all your valuable changes safely in a box.
When filling a box, you add new items on top of each other. Similarly, changes of subsequent stashes get added on top like a stack.

![image](https://media1.giphy.com/media/YhlZFaFx04fYY/giphy.gif)

We tend to cram stuff when packing.🙂 However, everything in a stash is neatly stacked and indexed in a well-organized manner. You can pull out changes from any index without affecting the rest.

Cool. Right? 🤩

Let's look at the commands in action. I urge you to try these out on a local repo to get a better understanding. Except for [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git), no installations are necessary.

1. Create a folder. And a file with some initial text.
2. Open git bash or terminal in that folder and run `git init` in the folder to initialize a git repository.
3. Add and commit changes.

4. Time for stashing now. Add some new text in your file.

5. Run `git stash` to stash the changes.
6. Create a new file with some text and add it for git to track it.

7. Stash using `git stash save "named stash"` to save the stash with a name this time.

8. Now view a list of stashes made with guess what? 🙃 `git stash list`.

9. Get more details of each stash with `git stash show stash{1} -p`.

10. Run `git stash apply` to apply the most recently saved changes on your working directory.

11. Changes will still be present on the stash. Run `git stash drop` to drop them. Alternately, `git stash pop` can be used to apply and drop changes using a single command.

12. Use `git stash clear` to remove all changes from the stash without applying them.

**Note:** Index can be specified as `stash@{1}` with `apply` and `drop`. By default, they operate on the most recent stash present on the top.

Stashing acts as a lifeline when we need changes in the future. A few cases are listed :

- Imagine that, to work on a feature for a project, you clone the repository and create your branch and start working. Somebody else's PR gets accepted and merged, which has code useful for you too. Now what? Stash your current changes, fetch the new changes from the remote, and finally apply the stashed content.
- Another such scenario is when you forget something meant for a commit and already start working on a new one. Complete the work on it by stashing changes for later.
- Let's suppose you are working on branch A. You commit changes and move on to making changes for another branch called B. You realize later that you forgot to switch to branch B in your excitement. Stashing will solve the problem here.

Congratulations on reaching the end. 🎉 To get notified about other posts in this series,

<form name="collect-email" method="POST" data-netlify="true">
<input type="hidden" name="form-name" value="collect-email" />

    Name <input type="text" name="name" />

    Email <input type="email" name="email" />

    <button type="submit">Send</button>

</form>

repository: purvasheth/MyBlog

repo_name: purvasheth/MyBlog


text:
# Bootstrap More
Bootstrap Sass with some flavors as a rails engine

Bootstrap v. 3.0.2

### TODO:
- Write a gem description
- Move docs from test/dummy :S (sorry about that)
- Add the flavors to all components
- Documented the flavors

## Installation

Add this line to your application's Gemfile:

    gem 'bootstrap-more'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install bootstrap-more

## Usage

TODO: Write usage instructions here

## Author

**Cristian Ferrari**
[https://github.com/cristianferrarig](https://github.com/cristianferrarig)

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request

repository: cristianferrarig/bootstrap-more

repo_name: cristianferrarig/bootstrap-more


text:
# a julia implementation of Random Projection Tree Classifier

## Method and Algorithm

### A rough description of the algorithm

The data are first stored in a root node of a tree.

Then the data is split in 2 descendant nodes.
There are 2 modes of splitting:

* By random sampling a random vector on the unit sphere and deciding
  to send each data vector in the left or right node depending on the sign of the cosine between the sampled unit vector and the data.

* By computing a gravity center of the points in a node and taking half the node near the
 gravity center in the one node (the left for example) and the other half in the other descendant node. This mode of splitting helps getting some sphericity of data in the final leaves.

We thus expect to get data in leaves defined by hyperplanes and having minimal sphericity.
The balance between the 2 modes of node splitting is adjusted by the **_threshold_** parameters in type RPTreeArg.

### Implementation

The implementation relies on a minimal binary Tree type implemented in file Tree.jl.

The construction of the random projection tree **_(RPTree)_** is somewhat parallelised:

* If ``nworkers() > 1`` the 2 nodes of the first generation are affected to 2 differents tasks.

* If ``Threads.nthreads() > 1`` the nodes of the second generations are affected to 2 different threads, thus achieving a moderate level of parallelism. (Some work to be done to better adapt this part of the code).

## Testing

The code was tested in Mass Spectrometry Imaging problems mainly with distances:

* Euclidean     L2
* Cityblock     L1
* Jaccard       fuzzy nucleotide :  $d(a,b) = 1 - \frac{\sum_{i}{\min(a_i,b_i)}}{\sum_i{\max(a_i, b_i)}}$

* CosineDist

(Cf package Distances)

A typical tree with 22000 vectors of length 11500 needs 50s to build with a depth of 8 i.e with 256 leaves and Jaccard distances (with parallelism level 4 i.e 2 workers and 4 threads on a laptop).

## License

Licensed under either of

* Apache License, Version 2.0 <http://www.apache.org/licenses/LICENSE-2.0>

* MIT license  <http://opensource.org/licenses/MIT>

at your option.

This software was written on my own while working at [CEA](http://www.cea.fr/), [CEA-LIST](http://www-list.cea.fr/en/)

## References

1. **DasGupta S. Freund Y. Random projection trees for vector quantization 2009**.
2. **DasGupta S. Freund Y. Random projection trees and low dimensional manifolds 2007**.


text:
# [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

# DateMeForReal

# Description

The applicaition is a dating app built with React.

# Table of Contents
* [Description](#description)
* [Installation](#installation)
* [Usage](#usage)
* [License](#license)
* [Contributing](#contribute)
* [Built with](#Builtwith)
* [Contributors](#Contributors)

# Installation

Run the following command to install all required packages:

- `npm i`

This application requires the following dependencies:

- Node
- Express
- AWS Amplify
- React
- ReactDOM
- mongodb
- mongoose
- axios
- react-tinder-card
- aos
- react-particles-js

# Usage

App is listening on port 3000 when running on local machine. Run the following commands to start:

- `npm run seed`
- `npm start`

App is deployed on Heroku. Access via link below:

[https://glacial-basin-52400.herokuapp.com/]

# License

This application is licensed under [MIT](https://github.com/qifeng86/DateMeForReal/blob/develop/LICENSE)

# Builtwith
- HTML
- CSS
- Google Fonts
- Javascript
- Node.js
- Heroku
- React
- ReactDOM
- axios
- mongodb
- mongoose
- mongodb atlas
- heroku
- Node
- Express
- AWS Amplify
- react-tinder-card
- aos
- react-particles-js

# Contributors

- Qi Feng: [https://github.com/qifeng86].
- Jeff Woda: [https://github.com/wodaje].
- Alex Gold: [https://github.com/johnbark855].
- Jalyn Campbell: [https://github.com/JCyberAI].
- Alexander Marzullo: [https://github.com/Amarz94].

branch_name: refs/heads/develop

gha_language: JavaScript

gha_license_id: MIT


text:
# \<nodecg-widget-obs\> [![Bower version](https://badge.fury.io/bo/nodecg-widget-obs.svg)](https://badge.fury.io/bo/nodecg-widget-obs)

[`nodecg-widget-obs`](https://github.com/NodeCG/nodecg-obs/packages/nodecg-widget-obs) provides a UI for configuring a connection to OBS via obs-websocket. It's made to be used with it's backend counterpart: [`nodecg-utility-obs`](https://github.com/NodeCG/nodecg-obs/packages/nodecg-utility-obs), but you could implement your own backend if you prefer!

## Install

`$ bower install --save nodecg-widget-obs`

For full documentation, see [`nodecg-obs`](https://github.com/NodeCG/nodecg-obs)


text:
## Xero Accounting - download report from Xero accounting ([download template](https://github.com/aimakerspace/TagUI-Bricks/releases/download/v1.0.0/Xero-Accounting.zip))

This automation flow downloads a specific recurring report from Xero cloud accounting software. It is created at [CA Trust PAC](https://casingapore.org), an accounting firm in Singapore, with the help of intern students from [Temasek Polytechnic](https://www.tp.edu.sg).

![xero_cover.png](https://raw.githubusercontent.com/aimakerspace/TagUI-Bricks/master/Xero-Accounting/xero_cover.png)

#### TagUI Workflow
```
// start by opening existing browser session
// and create a new tab to visit Xero homepage
click chromelogo.png
click newtab.png
keyboard https://go.xero.com[enter]

// enter credentials and login by using [ctrl]a
// to select any pre-filled text and type over
click email.png
keyboard [ctrl]a
keyboard your_email
click password.png
keyboard [ctrl]a
keyboard your_password
click loginbutton.png
wait 2 seconds

// navigate to the aged receivables report
click accountingmenu.png
click reportoption.png
click agedreceivablebutton.png
wait 10 seconds

// enter filter criteria for the report
click reportsettingsbutton.png
click todaydropdown.png
click endoflastmonth.png
click standarddropdown.png
click groupbyoption.png
click contactgroupdropdown.png
click partneroption.png
click updatebutton.png
wait 2 seconds

// download the report to Excel spreadsheet
click exportbutton.png
click excelbutton.png
wait 5 seconds

// log out so that users can sign in again
click profilebutton.png
click logoutbutton.png
wait 3 seconds

// close the new tab opened at the start
keyboard [ctrl]w
```

>In this workflow, visual automation is used to interact with UI elements on Xero website using image snapshots. Using web element identiers work as well, if not better. In that mode, user will not see the mouse cursor moving.

#### Image Assets

![xero_accounting.png](https://raw.githubusercontent.com/aimakerspace/TagUI-Bricks/master/Xero-Accounting/xero_accounting.png)

repository: jiangrongbo/TagUI-Bricks

repo_name: jiangrongbo/TagUI-Bricks


text:
# SFTP Server
## Custom SFTP Server Service for window and Linux server

- SFTP server which is supports both windows and Linux
- Easy to setup
- Create User with Specific directory with custom directory access
- JSON based users Credentials management
- Configurable server port

# Tech
- .Net Core

# Service Installation on Windows Server
- Goto SFTP Application Directory
- Click on CreateService.bat
- After that, you can check SFTP Service in windows service

# Create User's

```json
{
	"ServerPort": 2222,
	"Users": [
		{
			"Username": "admin",
			"Password": "admin",
			"Directory": "c:\\sftp\\web"
		}
	]
}
```

# Reference
https://nuane.com/sftp-lite/

## License
MIT
**Free Software**

repository: deveshspraxa/sftp

repo_name: deveshspraxa/sftp


text:
---
layout: post
title: "How to encapsulate your doctrine operations into transaction really easily"
excerpt: "When doing multiple database operations in a single http request, command line, method,...we often need to use a database transaction to keep data safe."
tags: [Symfony, doctrine, transaction, transactional, easy, callable, anonymous, function]
image: symfony.gif
comments: true
last_modified_at: "2020-04-09"
---

When doing multiple database operations in a single http request, command line, method,...
we often need to use a database transaction to keep data safe.

![Symfony](/images/posts/symfony.gif)

# Example in an Action of a Controller

{% highlight php startinline=true %}
<?php
public function testAction()
{
    $conn = $this->getDoctrine()->getConnection();
    $conn->setAutoCommit(false);
    $conn->beginTransaction();

    try {
        $everythingIsFine = $this->get('service')->do();
        if ($everythingIsFine) {
            $conn->commit();
            return new Response("OK");
        }

        $conn->rollback();
        return new Response("NOT OK");

    } catch (\Exception $ex) {
        $conn->rollback();
        return new Response("NOT OK");
    }
}

{% endhighlight %}

# A better choice

* Add a method that allows you to keep your code DRY.
* This method gets a `callable` param (a function/method to execute) and deals with potential exceptions, and transaction `commit()` and `rollback()` operations.
* It's a really dead simple example and a reminder, feel free to improve it.
* You could also move it into a service for instance.

{% highlight php startinline=true %}
<?php

protected function transactionalExec(callable $func)
{
    $conn = $this->getDoctrine()->getConnection();
    $conn->setAutoCommit(false);
    $conn->beginTransaction();

    try {
        $success = $func();

        if (null === $success) {
            throw new \Exception('Your transactional callable must return a boolean value');
        }

        if ($success) {
            $conn->commit();
        } else {
            $conn->rollback();
        }

    } catch (\Exception $ex) {
        $conn->rollback();
        $success = false;
    }

    return $success;
}

public function testAction()
{

    $transactionalSuccess = $this->transactionalExec(function()
        use (...)
    {
        $everythingIsFine = $this->get('service')->do();

        return $everythingIsFine;
    });

    if ($transactionalSuccess) {
        return new Response("OK");
    }

    return new Response("NOT OK");

}

{% endhighlight %}

extension: markdown


text:
# unit-conversion

[![Latest Version on Packagist](https://img.shields.io/packagist/v/davidstrada/unit-conversion.svg?style=flat-square)](https://packagist.org/packages/davidstrada/unit-conversion)
[![GitHub Tests Action Status](https://img.shields.io/github/workflow/status/davidstrada/unit-conversion/Tests?label=tests)](https://github.com/davidstrada/unit-conversion/actions?query=workflow%3ATests+branch%3Amaster)
[![Total Downloads](https://img.shields.io/packagist/dt/davidstrada/unit-conversion.svg?style=flat-square)](https://packagist.org/packages/davidstrada/unit-conversion)

Unit conversion package.

## Installation

You can install the package via composer:

```bash
composer require davidstrada/unit-conversion
```

## Usage

```php
$lbs = Weight::fromKilograms(100)->toLbs();
$this->assertEquals(220.4623, $lbs);
```

## Testing

```bash
composer test
```

## Changelog

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

## Contributing

Please see [CONTRIBUTING](.github/CONTRIBUTING.md) for details.

## Security Vulnerabilities

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

## Credits

- [David](https://github.com/davidstrada)
- [All Contributors](../../contributors)

## License

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

repository: DavidStrada/unit-conversion

repo_name: DavidStrada/unit-conversion


text:
# Forest cover (loss) compuatation with Google Earth Engine

Calculate forest cover (loss) for provided species distribution maps

## Data upload

Species' distribution maps have to be uploaded first to the Google Earth Engine (GEE). In order to reduce the size of upload and ease data processing, we compress the maps with the following command:

```
gdal_translate -a_nodata 255 -co NBITS=1 -co COMPRESS=CCITTFAX4 -co PHOTOMETRIC=MINISWHITE -ot Byte [original name] [new name]
```

The abovementioned command uses [CCITTFAX4](https://en.wikipedia.org/wiki/Group_4_compression), a CCITT Group 4 compression especially suitable for black and white images. That's exactly what we need: `1` to indicate presence of the species in the given area (pixel) and `0` absence.

In order to process **parallel** all files in a directory tree:

```
find . -name '*.tif' -type f -print0 | parallel -0 gdal_translate -a_nodata 255 -co NBITS=1 -co COMPRESS=CCITTFAX4 -co PHOTOMETRIC=MINISWHITE -ot Byte {} {.}_CCITTFAX4.tif
```

In short, the command finds all `tif` images and pipes (sends) all the names to a tool called `parallel`. As name suggests, the latter parallelises the task by sending its input (paths) to separate processes of `gdal_translate`. The `gdal` syntax is the same as in the original command for a single file, but what changes is how we capture name of the file: `{}` grabs name of a file (in full), while `{.}` denotes name of the file without extension.


text:
---
layout: post
title:  "RSA Key Exchange Algorithm"
date:   2016-08-29 16:54:20 -0400
---

08.29.2016

RSA Key Exchange Algorithm

**RSA**, designed by Ron Rivest, Adi Shamir, and Leonard Adleman in 1977, is one of the first practical public-key cryptosystems and is widely used for secure data transmission.  It is extremely difficult to factor the product of two large prime numbers and RSA took advantage of this mathematical property and made it into an asymmetric cryptographic algorithm.

Today, I am not going to talk about the history or the background of RSA, nor the practicality of the algorithm itself.  Instead, we will be talking about the pure mathematical aspects of RSA, and maybe we’ll build some Ruby methods to clarify some of the key points as well.

Before diving deep into RSA, it is very important to understand a few key concepts:

 - What is greatest common divisor.
 - What is a prime number.
 - What does it mean to be relatively prime to a number.
 - Power modular arithmetic.
 - Inverse modular arithmetic.

**Greatest Common Divisor:** is the largest positive integer that divides the numbers without a remainder.
 *For Example:* 18 and 12, common divisor are: 6,3,2
 *For Example:* 18 and 12, the greatest common divisor is 6

#simple method to find the GCD using The Euclidean Algorithm
#GCD method
def gcd(a,b)
  return b if a==0
  return gcd(b%a,a)
end

**Prime number:** A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.

*To verify whether a number is prime, you only need to check from 2 to square root of that particular number.  If there aren’t any within the range that can be divided with the remainder of 0, then the number is a prime.*

#A simple and slow prime method to find the next prime of a number
#random prime generator
def primeGen(num)
  loop do
    if num%2==0
      num += 1
      next
    elsif num%3==0 || num%5==0
      num += 2
      next
    else
      return num if Prime.prime?(num)
      num += 1
    end
  end
end

**Co-prime:** This one is a little bit tricky, is two integers a and b are said to be relatively prime, mutually prime, if the only positive integer that divides both of them is 1.

*For example:* 1,3,5,7 are coprimes of 8. Where as 1,2,4,5,7,8 are coprimes of 9

An interesting property for prime numbers: The number of coprimes for prime numbers will be the prime number - 1
For example, [1,2,3,4] are coprimes of 5 and [1,2,3,4,5,6] are coprimes 7

#here’s a ruby method to randomly pick a coprime from a given input
def get_E(limit)
  lower = limit >> 1
  loop do
    e = rand(lower..limit)
    return e if (gcd(e,limit)==1)
  end
end

**Power Modular Arithmetic:**
This arithmetic comes in the form of (b^e)%n, the result will always be less than n.
Without the proper algorithm, this arithmetic will have the potential to overflow the variable.

#power mod method
def power_mod(base,exp,mod)
  result = 1
  while ( exp > 0 )
    ( result = (result * base) % mod ) if exp % 2 == 1
    exp = exp >> 1
    base = (base*base) % mod
  end
  return result
end

Lastly, the **Inverse modular arithmetic.** The Inverse modular arithmetic can be expressed by the following equation:

 **ax + by = gcd(a, b)**

A well known method to solve the modular multiplicative inverse is to use extended Euclidean algorithm.
[https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm](http://)

We know that in RSA, we will be dealing with finding the inverse mod of two numbers that are relatively prime, in this case, the section for gcd(a,b) can be simplified to 1:

 **ax + by = 1**

We need to find x where x is a positive number.

This method can be a little bit difficult to code so I grabbed [https://rosettacode.org/](http://) for help:

# inverse mod function obtained from https://rosettacode.org/wiki/Modular_inverse#Ruby
def extended_gcd(a, b)
  last_remainder, remainder = a.abs, b.abs
  x, last_x, y, last_y = 0, 1, 1, 0
  while remainder != 0
    last_remainder, (quotient, remainder) = remainder, last_remainder.divmod(remainder)
    x, last_x = last_x - quotient*x, x
    y, last_y = last_y - quotient*y, y
  end

  return last_remainder, last_x * (a < 0 ? -1 : 1)
end

def invmod(e, et)
  g, x = extended_gcd(e, et)
  if g != 1
    raise 'The maths are broken!'
  end
  x % et
end

**That took a while to explain what’s required to understand RSA.**

Let’s use the methods above to demonstrate it, don’t forget to put **require 'prime'** on top of your ruby file.

**In a parallel world, Alice has a password that wants to send to Bob.  Bob will start to generate some numbers and will send some public keys to Alice.**

#that’s the range for the random generator
range = (99999999..999999999)
p = primeGen(rand(range))
q = primeGen(rand(range))

puts "Random P: #{p}"
puts "Random Q: #{q}"

**Bob will have to generate two prime numbers, called *p* and *q*,**
**N will be the product of P and Q**

n = p*q
puts "N = #{n}"

**PHI is the number of coprimes in N, if p has p-1 coprimes and q has q-1 coprimes, the number of coprimes for will be (p-1)*(q-1)**

phi = (p-1)*(q-1)
puts "PHI: #{phi}"

**E is a number that is relatively prime to PHI**

e = get_E(phi)
puts "The chosen E: #{e}"

**Finally, D is the inverse mod of E and PHI.**

d = invmod(e,phi)
puts "D = #{d}"

**Then Bob sends the public keys to Alice, which is N and E**

**Alice receives N and E and proceeds to encrypt**

puts "\nBob sends N and E to Alice."

**Alice wants to send *12345678* to Bob.**

m = 12345678
puts "Alice wants to send this message to Bob: #{m}"

**Alice encrypts the password using the power mod, m^e mod N and sends the cipher message to Bob**.

puts "Alice uses E and N to encrypt the message."
cipher = power_mod(m,e,n)
puts "Alice encrypts the message to: #{cipher}"

puts "\nAlice then sends her ciphered message back to Bob."

**Finally, Bob receives the ciphered message and decrypts the password by using power mod again, cipher^d mod N**

decipher =  power_mod(cipher,d,n)

if m == decipher
  puts "Bob decrypts the message and revealed: #{decipher}"
else
  puts "Unable to reveal the secret"
end

##############################Complete Code##############################

require 'prime'

# inverse mod function obtained from https://rosettacode.org/wiki/Modular_inverse#Ruby
def extended_gcd(a, b)
  last_remainder, remainder = a.abs, b.abs
  x, last_x, y, last_y = 0, 1, 1, 0
  while remainder != 0
    last_remainder, (quotient, remainder) = remainder, last_remainder.divmod(remainder)
    x, last_x = last_x - quotient*x, x
    y, last_y = last_y - quotient*y, y
  end

  return last_remainder, last_x * (a < 0 ? -1 : 1)
end

def invmod(e, et)
  g, x = extended_gcd(e, et)
  if g != 1
    raise 'The maths are broken!'
  end
  x % et
end

#power mod method
def power_mod(base,exp,mod)
  result = 1
  while ( exp > 0 )
    ( result = (result * base) % mod ) if exp % 2 == 1
    exp = exp >> 1
    base = (base*base) % mod
  end
  return result
end

#random prime generator
def primeGen(num)
  loop do
    if num%2==0
      num += 1
      next
    elsif num%3==0 || num%5==0
      num += 2
      next
    else
      return num if Prime.prime?(num)
      num += 1
    end
  end
end

#GCD method
def gcd(a,b)
  return b if a==0
  return gcd(b%a,a)
end

#get E from PHI
def get_E(limit)
  lower = limit >> 1
  loop do
    e = rand(lower..limit)
    return e if (gcd(e,limit)==1)
  end
end

puts "This is an RSA Example"

range = (99999999..999999999)
p = primeGen(rand(range))
q = primeGen(rand(range))

puts "Random P: #{p}"
puts "Random Q: #{q}"
n = p*q
puts "N = #{n}"
phi = (p-1)*(q-1)
puts "PHI: #{phi}"
e = get_E(phi)
puts "The chosen E: #{e}"
d = invmod(e,phi)
puts "D = #{d}"

puts "\nBob sends N and E to Alice."
m = 12345678
puts "Alice wants to send thsi message to Bob: #{m}"
puts "Alice uses E and N to encrypt the message."
cipher = power_mod(m,e,n)
puts "Alice encrypts the message to: #{cipher}"

puts "\nAlice then sends her ciphered message back to Bob."
decipher =  power_mod(cipher,d,n)

if m == decipher
  puts "Bob decrypts the message and revealed: #{decipher}"
else
  puts "Unable to reveal the secret"
end

**No matter how many times you run the simulation, Bob will always get the same message that Alice wants to send!**

This is an RSA Example
Random P: 432751903
Random Q: 821428381
N =<PHONE_NUMBER>55959043
PHI:<PHONE_NUMBER>01778760
The chosen E:<PHONE_NUMBER>47020309
D =<PHONE_NUMBER>79699149

Bob sends N and E to Alice.
Alice wants to send thsi message to Bob: 12345678
Alice uses E and N to encrypt the message.
Alice encrypts the message to:<PHONE_NUMBER>9119844

Alice then sends her ciphered message back to Bob.
Bob decrypts the message and revealed: 12345678

Have a nice day,

-irevived1


text:
# Distraction Free

When vibrate isn't enough, nor DND, use Airplane Mode.  The radios of the phone are turned off, saving power and cutting off **all** distractions, except for any alarms or alerts configured.  Phone is usable, but no calls, emails, text messages.

Swipe up from the bottom and click the airplane icon.

[iOS: Understanding airplane mode](http://support.apple.com/kb/HT1355)

# settings

- [Battery Guide](http://www.overthought.org/blog/2014/the-ultimate-guide-to-solving-ios-battery-drain)

# shortcuts

## camera

## Flashlight

When you need a little light in the dark:

* Swipe up
* Tap flashlight icon

# iCloud / Apple ID

Useful for:

* device syncing
* iMessages

And with iOS8

* File syncing (iCloud Drive)
* Photos (iCloud Photo Library)
* more device syncing (Handoff)

gha_language: CSS

gha_license_id: NOASSERTION


text:
## Exercise 3.25

Deforest the following:

    hyloN' :: (Maybe a -> a) -> (a -> Maybe a) -> a -> a
    hyloN' f g = foldN' f . unfoldN' g

We'd like to calculate a new definition for hyloN' that does not use
foldN' or unfoldN'.  We'll try to proceed by case analysis on g in the
expression:

    hyloN' f g x = case g x of ...

This looks slightly redundant.

repository: Zipheir/origami-notes

branch_name: refs/heads/main

repo_name: Zipheir/origami-notes


text:
# robotic-claw
> Experiment with controlling a robotic claw with smartphone gyroscope

## Hardware
* [Robotic Claw - MKII](https://www.sparkfun.com/products/11524)
* [Arduino Uno](https://www.sparkfun.com/products/11021)
* [Servo - Generic Metal Gear (Micro Size)](https://www.sparkfun.com/products/10333)
* [USB Cable A to B](https://www.sparkfun.com/products/512)
* [3 X Jumper Wires Standard 7"](https://www.sparkfun.com/products/11026)

### Setting it up
![Board setup](promo/servo.png)

## Install
Make sure you have Node.js and npm installed

```bash
$ git clone https://github.com/simon-johansson/robotic-claw.git && cd robotic-claw
$ npm install
```

## Starting the server
Connect the Arduino to the host machine and then, from the host, run
```bash
$ npm start
```
Open ``http://localhost:3000/instructions`` on the host machine and follow the instructions to controll the claw.

## License
MIT

repository: simon-johansson/robotic-claw

repo_name: simon-johansson/robotic-claw


text:
# platform-paths

Retrieve platform specific paths to user folders such as `downloads`, `documents`, etc.

Supports `linux`, `darwin`, and `win32` platforms.

Available paths: `tmp`, `home`, `downloads`, `documents`, `pictures`, `music`, `videos`, `desktop`.

Retrieval methods:

-   Linux: uses `xdg-user-dir` with a fallback to standard path names.
-   Windows: uses `reg query` to retrieve and parse out the paths with a fallback to standard path names.
-   macOS: simply constructs the standard path, as afaik these don't change on mac.

Pros:

-   Tiny & simple.
-   No dependencies.
-   No native modules, bindings, or binaries.
-   Built in caching.

Cons:

-   Potentially less robust than other alternatives.

## Install

```
npm install platform-paths
```

## Usage

```js
import {getPlatformPath, platformPaths, getDownloadsPath} from 'platform-paths';

const downloadsPath = await getPlatformPath('downloads');
// or
const downloadsPath = await platformPaths.download();
// or
const downloadsPath = await getDownloadsPath();
```

## API

Exported interfaces:

```ts
interface Options {
	maxAge?: number; // milliseconds, default: 0 (no caching)
}

// Name getter
async function getPlatformPath(name: string, options?: Options): Promise<string>;

// Individual getters
async function getTmpPath(options?: Options): Promise<string>;
async function getHomePath(options?: Options): Promise<string>;
async function getDownloadsPath(options?: Options): Promise<string>;
async function getDocumentsPath(options?: Options): Promise<string>;
async function getPicturesPath(options?: Options): Promise<string>;
async function getMusicPath(options?: Options): Promise<string>;
async function getVideosPath(options?: Options): Promise<string>;
async function getDesktopPath(options?: Options): Promise<string>;

// Individual getters as a map
const platformPaths = {
	tmp: (options?: Options) => Promise<string>,
	home: (options?: Options) => Promise<string>,
	downloads: (options?: Options) => Promise<string>,
	documents: (options?: Options) => Promise<string>,
	pictures: (options?: Options) => Promise<string>,
	music: (options?: Options) => Promise<string>,
	videos: (options?: Options) => Promise<string>,
	desktop: (options?: Options) => Promise<string>,
};

// Checks if string is a platform path identifier
// (one of platformPaths keys)
function isPlatformPathIdentifier(name: string): name is keyof typeof platformPaths;

// Manual cache clearing
function clearCache(): void;
```

### Caching

The retrieval methods for these paths are not _instant_, so if you're calling this a lot, you might want to enable caching.

This is done by simply passing a `maxAge` option to any of the exported methods. This options is `0` by default (caching disabled):

```js
// Re-queries when older than 10 seconds
const downloadsPath = getPlatformPath('downloads', {maxAge: 10_000});

// Only queries 1st time, then always cached
const downloadsPath = getDownloadsPath({maxAge: Infinity});
```

## License

MIT

repository: tomasklaen/platform-paths

repo_name: tomasklaen/platform-paths


text:
# Bootstrapping the Kubernetes Worker Nodes

All the commands need to be run on each of the worker nodes (`p1` and `p2` in this case)

## Prerequisites

Install `socat`, `conntrack` and `ipset`

```shell
sudo apt-get update
sudo apt-get -y install socat conntrack ipset
```

Enable `systemd-resolved` for DNS.

```shell
sudo systemctl enable systemd-resolved.service
sudo systemctl start systemd-resolved.service
```

Disable Swap

As per [this guide](https://www.paulcourt.co.uk/article/pi-swap), there are few commands to run in order to disable the swap permanently.

```shell
sudo dphys-swapfile swapoff
sudo dphys-swapfile uninstall
sudo update-rc.d dphys-swapfile remove
sudo rm -f /etc/init.d/dphys-swapfile

sudo service dphys-swapfile stop
sudo systemctl disable dphys-swapfile.service
```

Enable `br_netfilter` kernel module. This is used by `kube-proxy`.

```shell
echo br_netfilter | sudo tee -a /etc/modules
```

After these steps `reboot` the node.

## Install the Worker Binaries

```shell
sudo mkdir -p \
  /etc/cni/net.d \
  /opt/cni/bin \
  /var/lib/kubelet \
  /var/lib/kube-proxy \
  /var/lib/kubernetes \
  /var/run/kubernetes

sudo mv bin/containerd* bin/ctr /bin/
sudo mv bin/crictl bin/kube* bin/runc bin/recvtty /usr/local/bin/
sudo mv bin/* /opt/cni/bin/
```

## Configure CNI Networking

Pod CIDR is `10.200.${i}.0/24` where `${i}` is the sequence of the worker node. In this case, for the Pi 1 is `<IP_ADDRESS>/24` and for the Pi 2 is `<IP_ADDRESS>/24`. Choose accordingly one of the following for the appropriated worker node.

```shell
POD_CIDR=<IP_ADDRESS>/24
POD_CIDR=<IP_ADDRESS>/24
```

```shell
cat <<EOF | sudo tee /etc/cni/net.d/10-bridge.conf
{
    "cniVersion": "0.3.1",
    "name": "bridge",
    "type": "bridge",
    "bridge": "cnio0",
    "isGateway": true,
    "ipMasq": true,
    "ipam": {
        "type": "host-local",
        "ranges": [
          [{"subnet": "${POD_CIDR}"}]
        ],
        "routes": [{"dst": "<IP_ADDRESS>/0"}]
    }
}
EOF
```

```shell
cat <<EOF | sudo tee /etc/cni/net.d/99-loopback.conf
{
    "cniVersion": "0.3.1",
    "name": "lo",
    "type": "loopback"
}
EOF
```

## Configure Containerd

Important attention to `titilambert/armv6-pause:latest`, the original `k8s.gcr.io/pause` doesn’t work on ARMv6, so I found an alternative already published that worked for me. You can always build the image yourself from the source once compiled the `pause` binary but I didn’t go that far.

```shell
sudo mkdir -p /etc/containerd/
```

```shell
cat << EOF | sudo tee /etc/containerd/config.toml
[plugins]
  [plugins.cri]
    sandbox_image = "docker.io/titilambert/armv6-pause:latest"
    [plugins.cri.containerd]
      snapshotter = "overlayfs"
      [plugins.cri.containerd.default_runtime]
        runtime_type = "io.containerd.runtime.v1.linux"
        runtime_engine = "/usr/local/bin/runc"
        runtime_root = ""
EOF
```

```shell
cat <<EOF | sudo tee /etc/systemd/system/containerd.service
[Unit]
Description=containerd container runtime
Documentation=https://containerd.io
After=network.target

[Service]
ExecStartPre=/sbin/modprobe overlay
ExecStart=/bin/containerd
Restart=always
RestartSec=5
Delegate=yes
KillMode=process
OOMScoreAdjust=-999
LimitNOFILE=1048576
LimitNPROC=infinity
LimitCORE=infinity

[Install]
WantedBy=multi-user.target
EOF
```

This is more for troubleshooting, but it's handy to have it already configured in case it's needed.
```shell
cat << EOF | sudo tee /etc/crictl.yaml
runtime-endpoint: unix:///run/containerd/containerd.sock
image-endpoint: unix:///run/containerd/containerd.sock
timeout: 3
debug: true
pull-image-on-create: false
EOF
```

## Configure the Kubelet

```shell
sudo mv certs/${HOSTNAME}-key.pem certs/${HOSTNAME}.pem /var/lib/kubelet/
sudo mv config/${HOSTNAME}.kubeconfig /var/lib/kubelet/kubeconfig
sudo mv certs/ca.pem /var/lib/kubernetes/
```

```shell
cat <<EOF | sudo tee /var/lib/kubelet/kubelet-config.yaml
kind: KubeletConfiguration
apiVersion: kubelet.config.k8s.io/v1beta1
authentication:
  anonymous:
    enabled: false
  webhook:
    enabled: true
  x509:
    clientCAFile: "/var/lib/kubernetes/ca.pem"
authorization:
  mode: Webhook
clusterDomain: "cluster.local"
clusterDNS:
  - "<IP_ADDRESS>"
podCIDR: "${POD_CIDR}"
resolvConf: "/run/systemd/resolve/resolv.conf"
runtimeRequestTimeout: "15m"
tlsCertFile: "/var/lib/kubelet/${HOSTNAME}.pem"
tlsPrivateKeyFile: "/var/lib/kubelet/${HOSTNAME}-key.pem"
EOF
```

```shell
cat <<EOF | sudo tee /etc/systemd/system/kubelet.service
[Unit]
Description=Kubernetes Kubelet
Documentation=https://github.com/kubernetes/kubernetes
After=containerd.service
Requires=containerd.service

[Service]
ExecStart=/usr/local/bin/kubelet \\
  --config=/var/lib/kubelet/kubelet-config.yaml \\
  --container-runtime=remote \\
  --container-runtime-endpoint=unix:///var/run/containerd/containerd.sock \\
  --image-pull-progress-deadline=2m \\
  --kubeconfig=/var/lib/kubelet/kubeconfig \\
  --network-plugin=cni \\
  --register-node=true \\
  --v=2
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF
```

## Configure the Kubernetes Proxy

```shell
sudo mv config/kube-proxy.kubeconfig /var/lib/kube-proxy/kubeconfig
```

```shell
cat <<EOF | sudo tee /var/lib/kube-proxy/kube-proxy-config.yaml
kind: KubeProxyConfiguration
apiVersion: kubeproxy.config.k8s.io/v1alpha1
clientConnection:
  kubeconfig: "/var/lib/kube-proxy/kubeconfig"
mode: "iptables"
clusterCIDR: "<IP_ADDRESS>/16"
EOF
```

```shell
cat <<EOF | sudo tee /etc/systemd/system/kube-proxy.service
[Unit]
Description=Kubernetes Kube Proxy
Documentation=https://github.com/kubernetes/kubernetes

[Service]
ExecStart=/usr/local/bin/kube-proxy \\
  --config=/var/lib/kube-proxy/kube-proxy-config.yaml \\
  --masquerade-all
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF
```

## Enable and Start Services

```shell
sudo systemctl daemon-reload
sudo systemctl enable containerd kubelet kube-proxy
sudo systemctl start containerd kubelet kube-proxy
```

## Test Worker Nodes

On the worker nodes, test `containerd` is up and running using `crictl tool`.

```shell
sudo crictl info
```

On the master node, $HOME directory, run:

```shell
$ kubectl get nodes --kubeconfig config/admin.kubeconfig
NAME   STATUS   ROLES    AGE   VERSION
p1     Ready    <none>   34h   v1.18.13-rc.0.15+6d211539692cee-dirty
p2     Ready    <none>   12m   v1.18.13-rc.0.15+6d211539692cee-dirty
```

The trailing `-dirty` is because I didn’t commit my changes to the kubelet source above, therefore the build script picked up on it and updated the version id.


text:
### [CVE-2020-6270](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-6270)
![](https://img.shields.io/static/v1?label=Product&message=SAP%20NetWeaver%20AS%20ABAP%20(Banking%20Services)&color=blue)
![](https://img.shields.io/static/v1?label=Version&message=%3C710%20&color=brighgreen)
![](https://img.shields.io/static/v1?label=Vulnerability&message=Missing%20Authorization%20Check&color=brighgreen)

### Description

SAP NetWeaver AS ABAP (Banking Services), versions - 710, 711, 740, 750, 751, 752, 75A, 75B, 75C, 75D, 75E, does not perform necessary authorization checks for an authenticated user due to Missing Authorization Check, allowing wrong and unexpected change of individual conditions by a malicious user leading to wrong prices.

### POC

#### Reference
No PoCs from references.

#### Github
- https://github.com/Live-Hack-CVE/CVE-2020-6270

repository: trickest/cve

gha_language: HTML

repo_name: trickest/cve


text:
# Scala.js typings for markdown-escape

Typings are for version 1.1

## Library description:
escape Markdown control characters

|                    |                 |
| ------------------ | :-------------: |
| Full name          | markdown-escape |
| Keywords           | Markdown, escape, string |
| # releases         | 2 |
| # dependents       | 0.0 |
| # downloads        | 41438.0 |
| # stars            | 11.0 |

## Links
- [Homepage](https://github.com/kemitchell/markdown-escape.js#readme)
- [Bugs](https://github.com/kemitchell/markdown-escape.js/issues)
- [Repository](https://github.com/kemitchell/markdown-escape.js)
- [Npm](https://www.npmjs.com/package/markdown-escape)

## Note
This library has been generated from typescript code from [DefinitelyTyped](https://definitelytyped.org).

Provided with :purple_heart: from [ScalablyTyped](https://github.com/oyvindberg/ScalablyTyped)

## Usage
See [the main readme](../../readme.md) for instructions.

repository: ScalablyTyped/Distribution

repo_name: ScalablyTyped/Distribution


text:
# Python-in-2-days

Welcome to Python-in-2-days.  Here you will learn about Interactive Python (Jupyter Notebooks), linear algebra with NumPy, dataframes with Pandas, rich and interactive plotting tools with MatPlotLib and Seaborn, exploratory data analysis, machine learning model validation, and scientific computing with SciPy. From there you can extend these tools to other datasets and applications in machine learning.

This repo was built using material from **Jake VanderPlas - Python Data Science Handbook**.


text:
# Promises

A presentation about (the basics of) promises. Specifically for Angular 1 developers. Made in [reveal.js](https://github.com/hakimel/reveal.js).

## Usage
Open index.html in a browser.

repository: flauwekeul/presentation-promises

repo_name: flauwekeul/presentation-promises


text:
# Sandblock - Ethereum smart contracts

[![Twitter Follow](https://img.shields.io/twitter/follow/espadrine.svg?style=social&label=Follow)](https://twitter.com/sandblock_io)

## Satisfaction Token

![SAT Token Flow](art/sat_token_flow.png "SAT Token Flow")

### Warning: This contracts has not been thoroughly audited, it will evolve and improve before launching.

The core protocol of the Sandblock project is named the Satisfaction Protocol, composed of subsections to handle the different aspects of the Customer Satisfaction related metrics. This protocol is decentralized and is based on Smart Contracts on the Ethereum blockchain. The Satisfaction Protocol handles the most important and sensitive aspects of the Sanblock project regarding the token economy, the rewards attributions and the various brand rules.

## Getting Started

We recommend using [Truffle](https://github.com/ConsenSys/truffle) and [Ganache](https://github.com/trufflesuite/ganache-cli) to test and deploy the Satisfaction Protocol

```sh
npm install -g truffle
npm install -g ganache-cli
```

### Installing

Install all the dependencies

```sh
npm install
```

## Running the tests

Tests on local machine

```sh
truffle test --network ganache
```

## Built With

* [Web3](https://github.com/ethereum/web3.js/) - Ethereum JavaScript API
* [Truffle](http://truffleframework.com) - Development framework for Ethereum
* [Ganache](https://github.com/trufflesuite/ganache-cli) - Fast Ethereum RPC client for testing and development
* [OpenZeppelin](https://github.com/OpenZeppelin/openzeppelin-solidity) - A framework to build secure smart contracts on Ethereum

## Contributing

Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on our code of conduct, and the process for submitting pull requests to us.

## Authors

* **Jeremy Grenier** - [jeremygrenier](https://github.com/jeremygrenier)

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details

repository: wechain/satisfaction-protocol

repo_name: wechain/satisfaction-protocol


text:
# KeyValueStore [![Build Status](https://travis-ci.org/object-layer/key-value-store.svg?branch=master)](https://travis-ci.org/object-layer/key-value-store)

Transactional key-value store on top of any database.

### Why?

I needed a key-value store supporting ACID transactions. Since currently there are not many solutions out there, I created a layer above SQL databases like MySQL. My hope is that in the near future I will be able to replace the SQL database with something doing just what I want.

### Features

- Simple API.
- If a key is an array it is serialized in a way that sort element-wise.
- Easy transactions with automatic begin/commit/rollback.
- Asynchronous functions return promises, feel free to handle them with ES7 async/await feature.

### Supported databases

- Every databases supported by [AnySQL](https://www.npmjs.com/package/anysql).
- More to come...

## Installation

```
npm install --save key-value-store
```

## Usage

### Simple operations

```javascript
import KeyValueStore from 'key-value-store';

let store = new KeyValueStore('mysql://test@localhost/test');

async function simple() {
  let key = ['users', 'abcde12345'];

  // Create
  await store.put(key, { firstName: 'Manu', age: 42 });

  // Read
  let user = await store.get(key);

  // Update
  await store.put(key, { firstName: 'Manu', age: 43 });

  // Delete
  await store.delete(key);
}
```

### Range queries

```javascript
import KeyValueStore from 'key-value-store';

let store = new KeyValueStore('mysql://test@localhost/test');

async function query() {
  return await store.find({
    prefix: 'users',
    startAfter: 'abcde12345',
    limit: 30
  });
}
```

### Transactions

```javascript
import KeyValueStore from 'key-value-store';

let store = new KeyValueStore('mysql://test@localhost/test');

async function criticalOperation() {
  await store.transaction(async function(transaction) {
    let key = ['users', 'abcde12345'];
    let user = await transaction.get(key);
    user.age++;
    await transaction.put(key, user);
    // ...
    // if no error has been thrown, the transaction is automatically committed
  });
}
```

## Basic concepts

### Keys and values

Keys and values can be any kind of data.

If a key is an array it is automatically serialized in a way that sort element-wise. Thanks to that, keys can easily represent "path" (e.g.: ['users', 'abcde12345']).

Values are serialized with `JSON.stringify`. If you need to customize the serialization of your objects, you can implement a `toJSON()` method on them.

### Promise based API

Every asynchronous operation returns a promise. It is a good idea to handle them with the great ES7 async/await feature. Since ES7 is not really there yet, you should compile your code with something like [Babel](https://babeljs.io/).

## API

### `new KeyValueStore(url)`

Create a store for the specified URL.

```javascript
import KeyValueStore from 'key-value-store';

let store = new KeyValueStore('mysql://test@localhost/test');
```

### `store.get(key, [options])`

Get an item from the store.

```javascript
let user = await store.get(['users', 'abcde12345']);
```

#### `options`

- `errorIfMissing` _(default: `true`)_: if `true`, an error is thrown if the specified `key` is missing from the store. If `false`, the method returns `undefined` when the `key` is missing.

### `store.put(key, value, [options])`

Put an item in the store.

```javascript
await store.put(['users', 'abcde12345'], { firstName: 'Manu', age: 42 });
```

#### `options`

- `createIfMissing` _(default: `true`)_: if `false`, an error is thrown if the specified `key` is missing from the store. This way you can ensure an "update" semantic.
- `errorIfExists` _(default: `false`)_: if `true`, an error is thrown if the specified `key` is already present in the store. This way you can ensure a "create" semantic.

### `store.delete(key, [options])`

Delete an item from the store.

```javascript
await store.delete(['users', 'abcde12345']);
```

#### `options`

- `errorIfMissing` _(default: `true`)_: if `true`, an error is thrown if the specified `key` is missing from the store. If `false`, the method returns `false` when the `key` is missing.

### `store.getMany(keys, [options])`

Get several items from the store. Return an array of objects composed of two properties: `key` and `value`. The order of the specified `keys` is preserved in the result.

```javascript
let users = await store.getMany([
  ['users', 'abcde12345'],
  ['users', 'abcde67890'],
  // ...
]);
```

#### `options`

- `errorIfMissing` _(default: `true`)_: if `true`, an error is thrown if one of the specified `keys` is missing from the store.
- `returnValues` _(default: `true`)_: if `false`, only keys found in the store are returned (no `value` property).

### `store.putMany(items, [options])`

Not implemented yet.

### `store.deleteMany(keys, [options])`

Not implemented yet.

### `store.find([options])`

Fetch items matching the specified criteria. Return an array of objects composed of two properties: `key` and `value`. The returned items are ordered by key.

```javascript
// Fetch all users
let users = await store.find({ prefix: 'users' });

// Fetch 30 users after the 'abcde12345' key
let users = await store.find({
  prefix: 'users',
  startAfter: 'abcde12345',
  limit: 30
});
```

#### `options`

- `prefix`: fetch items with keys starting with the specified value.
- `start`, `startAfter`: fetch items with keys greater than (or equal to if you use the `start` option) the specified value.
- `end`, `endBefore`: fetch items with keys less than (or equal to if you use the `end` option) the specified value.
- `reverse` _(default: `false`)_: if `true`, reverse the order of returned items.
- `limit` _(default: `50000`)_: limit the number of fetched items to the specified value.
- `returnValues` _(default: `true`)_: if `false`, only keys found in the store are returned (no `value` property).

### `store.count([options])`

Count items matching the specified criteria.

```javascript
let users = await store.count({
  prefix: 'users',
  startAfter: 'abcde12345'
});
```

#### `options`

- `prefix`: count items with keys starting with the specified value.
- `start`, `startAfter`: count items with keys greater than (or equal to if you use the `start` option) the specified value.
- `end`, `endBefore`: count items with keys less than (or equal to if you use the `end` option) the specified value.

### `store.findAndDelete([options])`

Delete items matching the specified criteria. Return the number of deleted items.

```javascript
let deletedItemsCount = await store.findAndDelete({
  prefix: 'users',
  startAfter: 'abcde12345'
});
```

#### `options`

- `prefix`: delete items with keys starting with the specified value.
- `start`, `startAfter`: delete items with keys greater than (or equal to if you use the `start` option) the specified value.
- `end`, `endBefore`: delete items with keys less than (or equal to if you use the `end` option) the specified value.

### `store.transaction(fun)`

Run the specified function inside a transaction. The function receives a transaction handler as first argument. This handler should be used as a replacement of the store for every operation made during the execution of the transaction. If any error occurs, the transaction is aborted and the store is automatically rolled back.

```javascript
// Increment a counter
await store.transaction(async function(transaction) {
  let value = await transaction.get('counter');
  value++;
  await transaction.put('counter', value);
});
```

### `store.close()`

Close all connections to the store.

## License

MIT

repository: object-layer/key-value-store

repo_name: object-layer/key-value-store


text:
# react-native-modal-popover
Pure JS popover component for react-native

![Android](https://raw.githubusercontent.com/doomsower/react-native-modal-popover/master/gifs/android.gif)
![iOS](https://raw.githubusercontent.com/doomsower/react-native-modal-popover/master/gifs/ios.gif)

## About this module
The original [react-native-popover](https://github.com/jeanregisser/react-native-popover) is now outdated,
so I decided to publish my own module to avoid using github url in my package.json. Something got lost in
the process of rewriting, but now it uses `Modal` and native animation drivers, and also has cool helper
to use with Touchables. Thanks to @jeanregisser and to the authors of hanging PRs for their code.

## Install
```sh
yarn add react-native-modal-popover
```

## Usage

This module exports two react components, `Popover` and `PopoverTouchable`.
`Popover` works pretty much like original `Popover`, and `PopoverTouchable` is a nice wrapper.
Render it with two children - something with `onPress` and `Popover` and it'll manage the popover for you.

```jsx
import React from 'react';
import { Button, StyleSheet, Text, View } from 'react-native';
import Popover, { PopoverTouchable } from 'react-native-modal-popover';

const styles = StyleSheet.create({
  app: {
    ...StyleSheet.absoluteFillObject,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#c2ffd2',
  },
  content: {
    padding: 16,
    backgroundColor: 'pink',
    borderRadius: 8,
  },
  arrow: {
    borderTopColor: 'pink',
  },
  background: {
    backgroundColor: 'rgba(0, 0, 255, 0.5)'
  },
});

const App = () => (
  <View style={styles.app}>
    <PopoverTouchable onPopoverDisplayed={() => console.log('Popover displayed!')}>
      <Button title="Press me!" onPress={() => console.log('I don\'t work')}/>
      <Popover
        contentStyle={styles.content}
        arrowStyle={styles.arrow}
        backgroundStyle={styles.background}
      >
        <Text>Hello from inside popover!</Text>
      </Popover>
    </PopoverTouchable>
  </View>
);

export default App;
```

## Props

### `Popover`

Prop              | Type      | Optional | Default               | Description
----------------- | --------- | -------- | --------------------- | -----------
visible           | bool      | Yes      | false                 | Show/Hide the popover
fromRect          | Rect      | No*      |                       | Rectangle at which to anchor the popover. **Optional** when used inside `PopoverTouchable`, **required** when used standalone
displayArea       | Rect      | Yes      | Screen - 10px padding | Area where the popover is allowed to be displayed
placement         | string    | Yes      | 'auto'                | How to position the popover - top | bottom | left | right | auto. When 'auto' is specified, it will determine the ideal placement so that the popover is fully visible within `displayArea`.
onClose           | function  | Yes      |                       | Callback to be fired when the user closes the popover
backgroundStyle   | ViewStyle | Yes      |                       | Custom style to be applied to background overlay
contentStyle      | ViewStyle | Yes      |                       | Custom style to be applied to popover reactangle. Use it to set round corners, background color, etc.
arrowStyle        | ViewStyle | Yes      |                       | Custom style to be applied to popover arrow. Use `borderTopColor` to match content backgroundColor

### `PopoverTouchable`

Prop                 | Type        | Optional | Default               | Description
-------------------- | ----------- | -------- | --------------------- | -----------
onPopoverDisplayed   | () => void  | Yes      |                       | Callback to be fired when touchable is pressed and popover is displayed.

### `Rect`

Rect is an object with the following properties: `{x: number, y: number, width: number, height: number}`

## Contributing

If you want to add some features, feel free to submit PR.

repository: ShMcK/react-native-modal-popover

repo_name: ShMcK/react-native-modal-popover


text:
# 2020-Fall COMP4901K-Project COVID-19 Named Entity Recognition
This is the code for the Group Project of course **Machine Learning for Natural Language Processing (COMP4901K) Fall-2020**

Basically speaking, BERT and BiLSTM are the two approaches to solve the task. The final result shows that Double Layer BiLSTM is
our best choice.

> Dataset are provided in the data folder for reproduction

Use `pip install -r requirements.txt` to install the packages needed. We've tested this repository under Python 3.6 and
CentOS 7.0

## 0. Some non-functional codes:

`evaluate.py` : Sample code provided for evaluating the output and results.

## 1. BERT Classification
By fine-tuning the pretrained BERT model from `HuggingFace`, I embedded all the words and
use the provided BERT classification model to do the named entity recognition on the test set. Details can be found at: https://huggingface.co/transformers/model_doc/bert.html

The models are saved at the `./models/` and the results are saved at `./results/`

**The best results achieved is 89.3% on the validation set.** This is probably because there are some domain knowledge and BERT can't treat them well.

Codes related are provided below, to reproduce, please follow this sequence:

`BERT_finetuning.py` **(This code is deprecated by `BERT_revised.py`)**: code for fine-tuning the BERT model with the old version of `BertTokenizer`, which `tokenize` and `convert_token_to_id` is used, followed by classification.

`BERT_revised.py` : code for fine-tuning the BERT model with `transformer 3.4.0`, where`BertTokenizer.encode` is used, followed by a classification.

`BERT_find_best_model.py` : code for finding the best model according to the validation accuracy.

`BERT_loss_visualization.py` : visualizing the training/validation loss/accuracy for all the models.

`BERT_predict_verify.py`: code for generating result on the test data and verify the result by checking the generation's length.

## 2. Glove + Bi-LSTM

Since BERT is not performing that excellent in this task, an alternative is the pretrained-word-embedding + LSTM
I used the Glove embedding with 6 Billion tokens in 100 dimensions. Details can be found at: https://nlp.stanford.edu/projects/glove/
Then I used the Bidirectional-LSTM model to do the classification as its capable of capturing some long-term information with the ability of fitting the neural network with non-linearity.

**The best result achieved is 92.1% on the validation set.** This is high enough for this course project.

The models are saved at `./lstm_models/` and the results, answers as well as the loss recording are all saved at `./lstm_results/`

Codes related are:

`LSTM_NER.py` : The full code to do the embedding, train the model and do the classification. Please check the arguments for detail.

`BiLSTM.ipynb` : A jupyter notebook of coding during the developing process. All codes are compiled together in the `LSTM_NER.py` with code-readability enhanced.

`LSTM_find_best_model.py` : The code to find the best lstm model trained from all the models, it will read the generated accuracy list and find the one with the highest accuracy.

### 3. Glove Update (2020/11/20) :
---
We've added the Glove downloading part into the LSTM_NER.py code and now the code can automatically download all the glove pretrained model.

User can pass a parameter of how many billion words is the glove pretrained on to decide which glove model to use.

### 4. LSTM Structure update (2020/11/24) :
---
We've experimented on two more model structures: BiLSTM + BiLSTM and LSTM + BiLSTM. User can pass a parameter called `model` to decide which
lstm structure to use.

We experimented on double layers of Bidirectional LSTM and triple layers of BiLSTM, both networks converged at around 40 epochs, **the double layers BiLSTM achieved the highest accuracy of 93.25%**, which is our best record.

### 5. Word2vec model introduced (2020/11/24) :
---
We introduced a new word2vec model for the embedding rather than Glove. We tried for two times, the first time we use the `word2vec-google-news-300` pretrained model for embedding, it is relatively old and haven't been updated for years but still shows a good results with final accuracy `0.9201`.

And we are also thinking about that maybe using our own database to train the model is better, since the sentences are all in the specific domain. So we next use the word2vec to train on the given dataset and use this as embedding. The final accuracy is `0.9253`, which is slightly better.


text:
WinUsbPy
========

WinUsbPy is a python wrapper over [WinUsblibrary](http://msdn.microsoft.com/en-us/library/windows/hardware/ff540196%28v=vs.85%29.aspx)

It contains two different layers:

- A 1:1 wrapper over WinUsb which allows calling C++ functions directly from involved dlls.
- A high level api which simplifies a lot of C++/windll/ctypes messy interactions offering just a bunch of easy methods.

Install WinUsbPy
========
~~~
python setup.py install
~~~

Low Level Api
========
Low level api offers three methods for invoking functions from three different dlls.

``` python
#args: arguments of the C++ function called
def exec_function_winusb(self, function_name, *args):
def exec_function_kernel32(self, function_name, *args):
def exec_function_setupapi(self, function_name, *args):
```

if we need to call [SetupDiGetClassDevs](http://msdn.microsoft.com/en-us/library/windows/hardware/ff551069%28v=vs.85%29.aspx) which presents this prototype:

``` c++
HDEVINFO SetupDiGetClassDevs(_In_opt_ const GUID *ClassGuid,_In_opt_ PCTSTR Enumerator,_In_opt_ HWND hwndParent,_In_ DWORD Flags);
```

``` python
from winusbpy import *
from ctypes import *
from ctypes.wintypes import *
from winusbclasses import DIGCF_DEVICE_INTERFACE, DIGCF_PRESENT

api = WinUSBApi()
byte_array = c_byte * 8
guid = GUID(0xA5DCBF10L, 0x6530, 0x11D2, byte_array(0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED))
flags = DWORD(DIGCF_DEVICE_INTERFACE | DIGCF_PRESENT)

hdev_info = api.exec_function_setupapi("SetupDiGetClassDevs", byref(guid), None, None, flags)
```

[Good resources of WinUsb if you develop using this low level layer](http://msdn.microsoft.com/en-us/library/windows/hardware/ff540174(v=vs.85).aspx)

High Level Api
========
Built on top of the low level wrapper is a more usable api to perform common USB operations. Here it is list of defined functions:

``` python
# Possible keyword arguments: default, present, allclasses, profile, deviceinterface (Boolean), Usually called as follows list_usb_devices(deviceinterface=True, present=True)
def list_usb_devices(self, **kwargs):

# vid and pid must be str, returns True if device was correctly initialized and False otherwise
def init_winusb_device(self, vid, pid):

# Returns True if device was correctly closed and False otherwise.
def close_winusb_device(self):

# Returns last error code. See http://msdn.microsoft.com/en-us/library/windows/desktop/ms681382%28v=vs.85%29.aspx
def get_last_error_code(self):

# Returns information for a open device (0x03:High Speed, 0x01:full-speed or lower), query=1 in order to get USB speed.
def query_device_info(self, query=1):

# Returns a UsbInterfaceDescriptor object with information about a specified interface
def query_interface_settings(self, index):

# Change current interface, Winusb opens first interface (0 index) when a device is initialized
def change_interface(self, index):

# Returns a PipeInfo object with information of a specified pipe within current interface
def query_pipe(self, pipe_index):

# Send a control requesto to open device, setup_packet is a UsbSetupPacket object.
# buff = None implies no data is going to be transferred besides setup packet
# buff = [0] create a buffer of length 1. Buffer could be IN or OUT, direction is defined in setup packet
# it returns a dict with the response and with the buffer under the keywords 'result' and 'buffer'
def control_transfer(self, setup_packet, buff=None):

#Send Bulk data to the Usb device, write_buffer must be of type "bytes"
def write(self, pipe_id, write_buffer):

#Read Bulk data from the Usb device, Returns of a buffer not greater than length_buffer length
def read(self, pipe_id, length_buffer):
```

Let's say hello to our device:

``` python
from winusbpy import *
vid = "vid_device" # for example: VID:067b PID:2303
pid = "pid_device"

api = WinUsbPy()
result = api.list_usb_devices(deviceinterface=True, present=True)
if result:
  if api.init_winusb_device(vid, pid):

    # print device interface 0 descriptors
    interface_descriptor = api.query_interface_settings(0)
    if interface_descriptor != None:
        print("bLength: " + str(interface_descriptor.b_length))
        print("bDescriptorType: " + str(interface_descriptor.b_descriptor_type))
        print("bInterfaceNumber: " + str(interface_descriptor.b_interface_number))
        print("bAlternateSetting: " + str(interface_descriptor.b_alternate_setting))
        print("bNumEndpoints " + str(interface_descriptor.b_num_endpoints))
        print("bInterfaceClass " + str(interface_descriptor.b_interface_class))
        print("bInterfaceSubClass: " + str(interface_descriptor.b_interface_sub_class))
        print("bInterfaceProtocol: " + str(interface_descriptor.b_interface_protocol))
        print("iInterface: " + str(interface_descriptor.i_interface))

    # print device endpoint descriptors
    pipe_info_list = map(api.query_pipe, range(interface_descriptor.b_num_endpoints))
    for item in pipe_info_list:
        print("PipeType: " + str(item.pipe_type))
        print("PipeId: " + str(item.pipe_id))
        print("MaximumPacketSize: " + str(item.maximum_packet_size))
        print("Interval: " + str(item.interval))

    api.write(0x02, b"hello") # send bulk packet on OUT endpoint 2

    # close
    api.close_winusb_device()
```

Real examples
========
In "Examples" folder there are two real examples configuring a PL2303 serial usb device, listing characteristics and sending data.
[Using Low Level Api](https://github.com/felHR85/WinUsbPy/blob/master/winusbpy/examples/winusbtest.py)

[Using High Level Api](https://github.com/felHR85/WinUsbPy/blob/master/winusbpy/examples/winusbtest2.py)

repository: Vlastbia/WinUsbPy

gha_language: Python

repo_name: Vlastbia/WinUsbPy


text:
# Mixi.Media

Mixi.Media is a service for personalizing content network. Please visit our [Mixi.Media](https://Mixi.Media/dashboard) for more information.

## Example

```html
<amp-embed height="284" type="miximedia" data-blockid="91908"> </amp-embed>
```

## Configuration

For details on the configuration semantics, please contact the ad network or refer to their documentation.

### Required parameters

-   `data-blockid` - insert your block_id

repository: ampproject/amphtml

repo_name: ampproject/amphtml


text:
---
author: camerazn
comments: true
date: 2013-05-07 17:44:16+00:00
layout: post
slug: reverse-engineering-doubleclick-ad-statistics-part-1
title: Reverse Engineering Doubleclick Ad Statistics (Part 1)
wordpress_id: 96
tags:
- beacons
- doubleclick
- engineering
- hackity hack
- reverse engineering
---

One of the projects I'm on seeks to proxy web beacons. Basically, I have a WSGI app that serves a 1x1 px gif, and then triggers a Celery app that goes out and actually "clicks" on the intended web beacon. During preliminary load testing with a Doubleclick beacon (actually a Doubleclick link counter), we discovered that requesting that beacon 1000 times in 5 minutes (one request ever 1/3 second) only reported around 30 "clicks." We've been throwing tests at Doubleclick to see what it reports under different scenarios:

  * 1000 clicks evenly distributed over 5 minutes: 30 clicks

  * 1000 clicks chunked into 50 groups of 20 (I misunderstood how JMeter works): 50 clicks

  * 300 clicks over an hour (1 per 12 seconds): 300 clicks

  * 500 clicks with spoofed User_agent strings (1 per 12 seconds): 500 clicks

So it appears that Doubleclick has a "cooldown" between clicks and doesn't really care about the User_agent. How long is that cooldown? We know it's greater than 1/3 second and less than 12 seconds.

Today, I'm running a test that looks like this:

**Number of clicks**

**Rate of clicks**

**Delay between clicks**

**Total time**

10240

240 per minute

.25 seconds

2560 s (42.6m)

5120

120 per minute

.5 seconds

2560 s (42.6m)

2560

80 per minute

.75 seconds

1920 s (32m)

1280

40 per minute

1.5 seconds

1920 s (32m)****

640

20 per minute

3 seconds

1920 s (32m)

320

10 per minute

6 seconds

1920 s (32m)

By taking the total number of clicks recorded today (which I'll know tomorrow), I'll be able to start approximating the cooldown (for example, if I see 2240 and change clicks, I'll know that the cooldown is between 1.5 and .75 seconds).

Will update later.


text:
# Ancestry clustering
This tutorial explains how to cluster and classify genomes using 1000 Genomes data with GTM (our [ugtm](https://github.com/hagax8/ugtm) implementation) and t-SNE (sklearn implementation). Data files used in the following tutorial can be downloaded from [https://lovingscience.com/ancestries](https://lovingscience.com/ancestries/downloads.html).

### Requirements
The following python packages are required:
* ugtm
* sklearn
* altair
* matplotlib
* numpy
* pandas

### Files in directory
* worldmap_1000G.py: Python script, creates interactive visualization gathering GTM, t-SNE and PCA
* runGTM.py: runs GTM (using ugtm package) or t-SNE (using sklearn)
* data: directory, contains csv data files
* data/dataframe_1000G_noadmixed.csv: csv file, 1000 Genomes project dataframe with corresponding t-SNE and GTM coordinates

## Download files
You can download files for ancestry classification using 1000 genomes Phase 3 data from [here](http://lovingscience.com/ancestries/downloads.html), which are already formatted for this software. In this tutorial, we will use the following files:
- [recoded_1000G.noadmixed.mat](http://lovingscience.com/ancestries/downloads.html): 20 populations from 1000 Genomes Project (excluding MXL, ACB, ASW, ITU, STU, GIH)
- [recoded_1000G.raw.noadmixed.lbls3_3](http://lovingscience.com/ancestries/downloads.html): the corresponding ancestry labels (GBR and CEU were merged to obtain one category for Northern/Western European ancestry)
- [recoded_1000G.raw.noadmixed.lbls3](http://lovingscience.com/ancestries/downloads.html): the corresponding ancestry labels (GBR and CEU were not merged)
- [recoded_1000G.raw.noadmixed.ids](http://lovingscience.com/ancestries/downloads.html): the corresponding individual IDs

You can find out how these files were created by [clicking here](https://github.com/hagax8/uGTM/wiki/Appendix:-Generate-ancestry-files).

## Build GTM and t-SNE maps

To build a GTM with parameters [k,m,l,s] = [16,4,0.1,0.3] and 10 principal components, run the following command:

```
python runGTM.py --model GTM --data recoded_1000G.noadmixed.mat \
--labels recoded_1000G.raw.noadmixed.lbls3 --labeltype discrete \
--out outputname --pca --n_components 10 --regularization 0.1 \
--rbf_width_factor 0.3 --missing --missing_strategy median \
--random_state 8 --ids recoded_1000G.raw.noadmixed.ids
```

It should be noted that our genotype file has missing values that we are handling with the --missing and --missing strategy options. You should obtain a pdf and an html file. The html file looks like this:
[1000G_GTM_20populations.html](http://www.lovingscience.com/ancestries/downloads/1000G_GTM_20populations.html)

To build a t-SNE map, run:

```
python runGTM.py --model GTM --data recoded_1000G.noadmixed.mat \
--labels recoded_1000G.raw.noadmixed.lbls3 --labeltype discrete \
--out outputname --pca --n_components 10 \
--missing --missing_strategy median \
--random_state 8 --ids recoded_1000G.raw.noadmixed.ids
```

Click here to access the t-SNE map: [1000G_t-SNE_20populations.html](http://www.lovingscience.com/ancestries/downloads/1000G_t-SNE_20populations.html)

## Evaluation of classification performances in a crossvalidation experiment, compare GTM and linear SVM:
```
python runGTM.py --model GTM --data recoded_1000G.noadmixed.mat \
--labels recoded_1000G.raw.noadmixed.lbls3_3 --labeltype discrete \
--out outputname --pca --n_components 10 \
--missing --missing_strategy median \
--random_state 8 --crossvalidate
```
This will give us per-class reports. Default class priors are equiprobable (cf. --prior option), which is generally only OK if classes are balanced. For imbalanced classes, use "--prior estimated" option.

## Train on provided data and project a test set onto the map:
The great thing about generative topographic mapping (GTM) is that we can project external test sets on the map without having to re-train the map.
The ugtm package also includes some nice functions for classification models and generates posterior probabilities for test set individuals (--test) to belong to a specific class, based on the class labels (--labels) of the training set (--data).

```
python runGTM.py --model GTM --data recoded_1000G.noadmixed.mat \
--test recoded_1000G_MXL.mat --labels recoded_1000G.raw.noadmixed.lbls3_3 \
--labeltype discrete --out outputname --pca --n_components 10 \
--missing --missing_strategy median \
--random_state 8
```

This will give us:
* predictions for individuals (output_indiv_predictions.csv)
* posterior probabilities for each ancestry (output_indiv_probabilities.csv)
* posterior probabilities for the whole test set (output_group_probabilities.csv)
* a map with projected test set colored in black.

The projection for MXL population (Mexicans) can be visualized here: [1000G_GTM_projection_MXL.html](http://www.lovingscience.com/ancestries/downloads/1000G_GTM_projection_MXL.html)

## Addendum 1: map based on AFR superpopulation only
To construct t-SNE and GTM maps based on AFR populations:
* Download:
  * [recoded_1000G.noadmixed.AFR.mat](http://lovingscience.com/ancestries/downloads.html): African (AFR) populations from 1000 Genomes Project (excluding ACB and ASW)
  * [recoded_1000G.raw.noadmixed.AFR.lbls3](http://lovingscience.com/ancestries/downloads.html): the corresponding ancestry labels
  * [recoded_1000G.raw.noadmixed.AFR.ids](http://lovingscience.com/ancestries/downloads.html): the corresponding individual IDs

* Build GTM and t-SNE:

  * GTM (cf. [output](http://www.lovingscience.com/ancestries/downloads/1000G_GTM_20populations.AFR.html))
  ```
  python runGTM.py --model GTM --data recoded_1000G.noadmixed.AFR.mat \
  --labels recoded_1000G.raw.noadmixed.AFR.lbls3 --labeltype discrete \
  --out 1000G_GTM_AFR --pca --n_components 10 \
  --regularization 0.1 --rbf_width_factor 0.3 \
  --missing --missing_strategy median \
  --random_state 8 --ids recoded_1000G.raw.noadmixed.AFR.ids
  ```
  * t-SNE (cf. [output](http://www.lovingscience.com/ancestries/downloads/1000G_t-SNE_20populations.html)):
  ```
  python runGTM.py --model GTM --data recoded_1000G.noadmixed.AFR.mat \
  --labels recoded_1000G.raw.noadmixed.AFR.lbls3 --labeltype discrete \
  --out 1000G_t-SNE_AFR --pca --n_components 10 \
  --missing --missing_strategy median \
  --random_state 8 --ids recoded_1000G.raw.noadmixed.AFR.ids
  ```

* African subpopulations classification performance:
```
python runGTM.py --model GTM --data recoded_1000G.noadmixed.AFR.mat \
--labels recoded_1000G.raw.noadmixed.AFR.lbls3 \
--labeltype discrete --out outputname --pca --n_components 10 \
--missing --missing_strategy median \
--random_state 8 --crossvalidate
```

## Addendum 2: Arabidopsis Thaliana geographic visualization
Cf. github repository [https://github.com/hagax8/arabidopsis_viz](https://github.com/hagax8/arabidopsis_viz)


text:
---
layout: default
---

# 1997-07-02 - non-US encryption

## Header Data

From: Megan McCormack<EMAIL_ADDRESS>To<EMAIL_ADDRESS>Message Hash: d7ca09dd0f725753cf240b78f4377c827f5bc92a7d196af8ac47c1acf33debea

Message ID<EMAIL_ADDRESS>Reply To: _N/A_

UTC Datetime: 1997-07-02 05:54:11 UTC

Raw Date: Wed, 2 Jul 1997 13:54:11 +0800

## Raw message

```
{% raw  %}From: Megan McCormack<EMAIL_ADDRESS>Date: Wed, 2 Jul 1997 13:54:11 +0800
To<EMAIL_ADDRESS>Subject: non-US encryption
Message-ID<EMAIL_ADDRESS>MIME-Version: 1.0
Content-Type: text/plain

I'm looking for a maillist for discussion of
non-US encryption software. Their was one
at braae.ru.ac.za which now apears to be defunct.

Thanks,
Megan

   **************  Chop wood, carry water, check e-mail  ************

                             Megan McCormack
    			   http://www.asis.com/~meganm

{% endraw %}
```

## Thread

+ Return to [July 1997](/archive/1997/07)

+ Return to "[Megan McCormack <meganm@asis.com>](/authors/megan_mccormack_meganm_at_asis_com_)"

+ 1997-07-02 (Wed, 2 Jul 1997 13:54:11 +0800) - non-US encryption - _Megan McCormack<EMAIL_ADDRESS>


text:
# plushu-command-whitelist

Expose commands to pass through as Plushu commands

## Usage

```bash
$ plushu command-whitelist echo
$ plushu echo test
test
$
```

repository: plushu/plushu-command-whitelist

repo_name: plushu/plushu-command-whitelist


text:
  v1.0

  A simple & low-overhead web dashboard for linux systems

    Demo  |

      Docs

## Features
* **Small** ----- Under 400KB on disk _(with .git removed)!_
* **Simple** ---- A minimalist, beautiful dashboard
* **Easy** ------ Drop-in installation
* **Versatile** -- Choose your stack from Python, Docker

## Installation

### Step 1
```sh
## 1. clone the repo
git clone https://gitee.com/louisyoung1/linux-sys-dashboard.git

## 2. go to the cloned directory
cd linux-sys-dashboard

```
OR, if you prefer to download manually:

```sh
## 1. Download the .zip
curl -LOk https://gitee.com/louisyoung1/linux-sys-dashboard/repository/archive/master.zip && unzip master.zip

## 2. navigate to downloaded & unzipped dir
cd linux-sys-dashboard

```

### Step 2

See instructions for preferred server linux-dash server :

* [Python](#if-using-python)
* [Python](#if-using-python)

#### If Using Python
```sh
# Start the server (on port 80 by default; may require sudo).
python index.py
```

#### If Using Docker

Make sure you have the Docker enabled, You can install it with one command

```sh
curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun
```

## Support

For general help, please contact me in [Louis-House](https://www.louisyoung.work/Contact).

## Security

**It is strongly recommended** that all **[Linux-sys Dashboard](https://gitee.com/louisyoung1/linux-sys-dashboard)** installations be protected via a security measure of your choice.

**[Linux-sys Dashboard](https://gitee.com/louisyoung1/linux-sys-dashboard)** does not provide any security or authentication features.

## License

The MIT License (**[MIT](https://gitee.com/louisyoung1/linux-sys-dashboard/blob/master/LICENSE)**)

repository: gcgcgc/linux-sys-dashboard

repo_name: gcgcgc/linux-sys-dashboard