text:
---
layout: post
title: "Thank You Rafa"
tags:
- Sports
categories:
- Learn
thumbnail_path: blog/personal/nadal.jpg
---

Today (July 03 2015) is an important day in the history of Tennis - it marks the end of Nadal's domination at Roland Garros. Don't get me wrong here - I'm not saying that Rafa will not win any more tournaments on the Red Clay, but just that I don't see him dominating anymore as much as he has over the years!

I started watching tennis in 2006 and ever since I've been an avid Federer fan. According to me, Federer is the Greatest Player Of All Time - irrespective of either Novak's or Rafa's career achievements after this. Rohan had a great reason in his post [here](http://alearningaday.com/2012/01/why-rafael-nadal-is-the-greatest-role-model-while-not-being-the-greatest-ever-player.html) -

> There’s a certain romance in sport that you cannot ignore. It’s just like romance in relationships.
> There’s magic. You can never explain it but it’s there. And, on the sports field, that magic is only
> invoked by genius. By an X Factor which many great sportsman will never have despite their statistic
> accomplishments.

Federer is a Genius - it is easy to admire a genius but hard to emualate. However, Nadal is the ideal role model for us mere mortals - he was asked to play left-handed by his uncle Toni so that he would have an advantage against most of the right handed players. By hardwork and dedication, he has proved that it is possible to beat the geniuses. I've learnt a lot from Nadal over the years -

**Never Say Die Attitude** - If there's only one thing that you can learn from Rafa, then this is it. He plays every point as if he has never won one and as if this is his last. One match that comes to my mind is the 2013 French Open Semi-Final against Djokovic where he was trailing 2-4 down in the 5th set but goes on to win the match 8-6.

{% include iframe-figure.html url="//www.youtube.com/embed/VKM19zYZX24" caption="Rafael Nadal vs Novak Djokovic 2013 Roland Garros SemiFinal" link="https://www.youtube.com/watch?v=VKM19zYZX24" %}

**Ability to Adapt** - Early in his career, he was termed as a clay court specialist. However, he worked on his game and improved so much that he went on to win the Career Slam. After winning the 2008 Wimbledon, people began to accept that he is not just a clay court player.

{% include iframe-figure.html url="//www.youtube.com/embed/-1yfWb0-jqQ" caption="Rafael Nadal vs Roger Federer 2008 Wimbledon Final" link="https://www.youtube.com/watch?v=-1yfWb0-jqQ" %}

**Humility** - Nadal handles the press conferences (especially the ones after his loss) really well - gives credit to the opponent and doesn't give excuses like weather, injury or time delays. Also, during the 2009 Australian Open Ceremony, he calls Federer one of the Greatest Players Of All time (despite defeating him in the last 3 Grand Slam Finals that they played together).

{% include iframe-figure.html url="//www.youtube.com/embed/XG15FrFsgQM" caption="2009 Australian Open Final Ceremony" link="https://www.youtube.com/watch?v=XG15FrFsgQM" %}

**Role Model** - And more importantly, he has shown us that by hardwork and a never say die attitude you can beat the genius.

I hope he returns to winning form soon and inspires us once again. Happy Birthday and Thank You Rafa!!


text:
---
layout: post
title: Why Metis? - A thorough analysis (Part 1).
---
![Question Mark](/images/question.jpg)

##Why I write a "Why Metis ?" blog :##

<strike>Since this blog probably would never have existed if not for Metis, I thought naturally the first blog should be dedicated to Metis.</strike>

Ok fine, I think the strongest reason is that after three weeks at Metis, I am loving it. So I just wanna talk about it.

###Disclaimer###
      I am a student at Metis, so obviously I am affiliated with Metis. However, everything that is written here are my and only my own opinions.

      I am not told(/paid/forced/threaten... ;P) to write by anyone (but myself of course).

##Reasons why I think Metis is one of the best decisions I ever made:##

* __Before Metis :__

      As many data-scientists-wanna-be, I went through the process of finding which program would be best for me. Even though data science is still relatively new field, there are many choices, such as : NYU data science program, Berkely data science online program, Data Incubator... and Metis. So let's get right on to my selection process:

1. Metis vs Berkeley program :

    This is quite an easy choice for me since I do not trust to put $60,000 for an online program.

    It might work for many people, but for me, the ability to be able to ask a question even when I am vague about the question is crucially important. By "vague about the question", I mean sometimes, I come across a topic and I feel like can't quite graps the big picture. And to understand the big picture better, the best way for me is to have a conversation full of questions, in which some question will be based on the answer of my instructor/TA for my previous question. I don't think you( or I) can do it effectively/efficiently on a message board.

    So no, no online program for me.

2. Metis vs a 2-3 years in school program (NYU, Columbia,...):

    This is actually quite a tough choice. I do like to learn all my topics thoroughly, with proof, with explaination how one come up with such a formula. And this obviously can't be done at a 3 months program as Metis. I do think these programs are great.

    But even if I get to choose again, I will still choose Metis, for couple of reason:

    *Time:*

    It will take 2-3 years to finish these program.
    Data Science is seeing its popularity on the rise right now. With such popularity, within 2-3 years, the job market for this field will be extremly competitive. In stead of being in school learning theory, I rather be in the field learning real life experience. I think enriching my skills through the job than through text book will place me higher in the competitive scale 2 year from now.

    *Money:*

    Metis costs $14,000 ($12,000 for women, hurray!!!) and 3 month of living expense. These in school program cost at least $60,000 and 2-3 years living expense. Enough said.

    *Personal preference :*

    I have been in school for quite a while. I think it's time for me to try something different (new experience is always a very good thing)

3. Mestis vs Data Incubator:

    Data Incubator is quite a famous program (well, at least it appeared in the newspaper). It is a 7 weeks long program, and is free for its fellows. Sound great, isn't it? It is great, definitely. Just not for me.

    I think there is "short", and there is "too short". Besides having a background in math (Master), I was only efficient at coding Maple, which if you look at all the job advertising requirement, Maple is no where to be found.  And 7 weeks is just **too short .**

    I think deciding between these two programs does come down to knowing your own ability. (And also where you get accepted to.)

license: MIT

branch_name: refs/heads/master

extension: md

license_type: permissive


text:
#Docker Compose

Once you prepare your docker client as described in the user guide's [Quick Start](https://github.com/fiware-docker/docker-container-service/blob/master/docs/userguide/user-guide.md/user-guide.md##Quick Start) you can use [Docker Compose](https://docs.docker.com/compose/). We support Docker-Compose 1.6.2 and above.

Note: docker-compose does not support the docker cli --config flag, so the ~/.docker/config.json must contain headers X-Auth-Token and X-Auth-TenantId. Likewise, docker-compose does not support the docker cli -H flag so the environment variable must be set to tcp://docker.lab.fiware.org:2376.

The [docker compose command-line](https://docs.docker.com/compose/reference/) is supported.

These docker compose commands are supported:
- build: NA
- config: NA
- create: supported
- down: supported
- events: not supported
- kill: supported
- logs: supported
- pause: supported
- port: supported
- ps: supported
- pull: supported
- restart: supported
- rm: supported
- run: supported
- scale: supported
- start: supported
- stop: supported
- unpause: supported
- up: supported

There are two versions of the [docker-compose.yml file](https://docs.docker.com/compose/compose-file/) format. Version 1 is the legacy format, which does not support the volume_driver or networks tag.  Most of the version 1 and 2 docker-compose tags are supported, but they may be restricted in a similar manner to the restriction applied to the docker CLI. For instance, the volumes tag is supported, but FDCS does not permit reference to the host filesystem. User defined volumes can be referenced in the in the volumes tag.

## Examples
### Orion and Mongodb
This docker-compose example demonstrates a docker service assembled from docker images **FIWARE/orion** and **mongo:3.2**.  The DB is made persistent on a user define NFS volume called **mongodata**. The orion container communicates with the mongo container over a user defined overlay network called **front**.

This the docker-compose.yml:
```
/orion$ cat docker-compose.yml
version: '2'
networks:
  front:
     driver: "overlay"
volumes:
  mongodata:
#     external: true
     driver: "nfs"
services:
   mongo:
     image: mongo:3.2
     command: --nojournal
     networks:
      - front
     volumes:
      - mongodata:/data/db

   orion:
     image: fiware/orion
     ports:
       - "1026"
     networks:
      - front

     command: -dbhost mongo
```
Notice that it creates a user defined overlay network called **front** and a user defined NFS volume called **mongodata**. Both containers, **orion** and **mongo**, reference the *front* network. The mongo container references the *mongodata* volume and mounts its /data/db on the volume. The *mongodata* volume could have been created outside of the docker-compose file using docker-cli; in that case the *external* tag would have been used.

Initially, there are no running containers, no user defined volumes  and no user defined networks.
```
/orion$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
docker-user-1@rcc-hrl-kvg-558:~/orion$ docker volume ls
DRIVER              VOLUME NAME
docker-user-1@rcc-hrl-kvg-558:~/orion$ docker network ls
NETWORK ID          NAME                DRIVER
```

We launch the service with docker-compose up -d

```
/orion$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
docker-user-1@rcc-hrl-kvg-558:~/orion$ docker volume ls
DRIVER              VOLUME NAME
docker-user-1@rcc-hrl-kvg-558:~/orion$ docker network ls
NETWORK ID          NAME                DRIVER
docker-user-1@rcc-hrl-kvg-558:~/orion$ docker-compose up -d
Creating network "orion_front" with driver "overlay"
Creating volume "orion_mongodata" with nfs driver
Creating orion_orion_1
Creating orion_mongo_1

```
It creates an overlay network (orion_front) and the user defined nfs volume (orion_mongodata), and two contains (orion_orion_1 and orion_mongo_1).
docker_compose prefixes the containers with the directory name from which it launches the docker-compose file.  It also appends a number to the container names that is used when it scales out a service.
```
~/orion$ docker-compose ps
    Name                   Command               State               Ports
---------------------------------------------------------------------------------------
orion_mongo_1   /entrypoint.sh --nojournal       Up      27017/tcp
orion_orion_1   /usr/bin/contextBroker -fg ...   Up      <IP_ADDRESS>:32768->1026/tcp

docker-user-1@rcc-hrl-kvg-558:~/orion$ docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                            NAMES
40e14092eddf        fiware/orion        "/usr/bin/contextBrok"   8 minutes ago       Up 8 minutes        <IP_ADDRESS>:32769->1026/tcp   docker-host-3/orion_orion_1
59a647da904e        mongo:3.2           "/entrypoint.sh --noj"   8 minutes ago       Up 8 minutes        27017/tcp                        docker-host-2/orion_mongo_1

```
Notice that containers are running on different docker hosts. The orion container is running on docker-host-3 and the mongo container is running on docker-host-2. They can interact with each other over their own private overlay network. Notice also that the orion container's port 1026 is mapped to the docoker-host-3's port 32768.  Later we will run curl commands to orion using the host port mapping.

We look at the volume that was created.  Notice that docker-compose also prefixes the volume name with directory name from which the docker-compose file was launched.  Two volume entries appear because the same nfs volume is mounted to both hosts in the cluster.
```
/orion$ docker volume ls
DRIVER              VOLUME NAME
nfs                 orion_mongodata
nfs                 orion_mongodata
```
We look at the network that was created.  Notice that docker-compose also prefixes the network name with directory name from which the docker-compose file was launched.
```
/orion$ docker network ls
NETWORK ID          NAME                DRIVER
1b651ad80f4b        orion_front         overlay
/orion$ docker network inspect orion_front
[
    {
        "Name": "orion_front",
        "Id": "1b651ad80f4b9567626faba94accdf74aa77217d91258105525d56a2d5907426",
        "Scope": "global",
        "Driver": "overlay",
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": [
                {
                    "Subnet": "<IP_ADDRESS>/24",
                    "Gateway": "<IP_ADDRESS>/24"
                }
            ]
        },
        "Containers": {
            "c67fbd499135cf20aa301a5e9c9b8611330a64cf1ac5315ca47fde5b5a4ecf50": {
                "Name": "orion_orion_1",
                "EndpointID": "4d5111cb9303e61bf28f3a5209e788d2e33c9d3f1a5c29ebdfcce8a1503ddc9e",
                "MacAddress": "02:42:0a:00:00:02",
                "IPv4Address": "<IP_ADDRESS>/24",
                "IPv6Address": ""
            },
            "cba077da484f4b5f9ff6b47721810e7660dce5979ed84636573626f28d97d533": {
                "Name": "orion_mongo_1",
                "EndpointID": "fde05d125ba6971218eff9b5092877f7c6e47b8baaa67d156be83957b43baeab",
                "MacAddress": "02:42:0a:00:00:03",
                "IPv4Address": "<IP_ADDRESS>/24",
                "IPv6Address": ""
            }
        },
        "Options": {}
    }
]

```

We fetch orion's host port mapped URL with the docker-compose port command so that we can use curl to get and post entities from/to orion and the mongo DB.
```
/orion$ port=$(docker-compose port orion 1026)
```
We show that DB is initially empty.
```
/orion$ curl $port/v2/entities
[]
```
We add to the DB entity Room2 with attributes temperature and pressure and validates that the entity is indeed added to the DB.
```
/orion$ curl ${port}/v2/entities -s -S --header 'Content-Type: application/json' -X POST -d @- <<EOF
{
  "id": "Room2",
  "type": "Room",
  "temperature": {
    "value": 23,
    "type": "Number"
  },
  "pressure": {
    "value": 720,
    "type": "Number"
  }
}
EOF
/orion$ curl $port/v2/entities
[{"id":"Room2","type":"Room","pressure":{"type":"Number","value":720,"metadata":{}},"temperature":{"type":"Number","value":23,"metadata":{}}}]
```
We now show that the data is persistent by removing the containers with the docker-compose down command.  The containers and network are removed but the volume, mongodata, remains untouched.
```
docker-user-1@rcc-hrl-kvg-558:~/orion$ docker-compose down
Stopping orion_mongo_1 ... done
Stopping orion_orion_1 ... done
Removing orion_mongo_1 ... done
Removing orion_orion_1 ... done
Removing network orion_front
docker-user-1@rcc-hrl-kvg-558:~/orion$ docker network ls
NETWORK ID          NAME                DRIVER
docker-user-1@rcc-hrl-kvg-558:~/orion$ docker volume ls
DRIVER              VOLUME NAME
nfs                 orion_mongodata
nfs                 orion_mongodata

```
We now launch the service again and show that the DB still containers Room2 and  its attributes.

```
docker-user-1@rcc-hrl-kvg-558:~/orion$ docker-compose up -d
Creating network "orion_front" with driver "overlay"
Creating volume "orion_mongodata" with nfs driver
Creating orion_orion_1
Creating orion_mongo_1
docker-user-1@rcc-hrl-kvg-558:~/orion$ docker network ls
NETWORK ID          NAME                DRIVER
d92818b2e5c0        orion_front         overlay
docker-user-1@rcc-hrl-kvg-558:~/orion$ port=$(docker-compose port orion 1026)
docker-user-1@rcc-hrl-kvg-558:~/orion$ curl $port/v2/entities
[{"id":"Room2","type":"Room","pressure":{"type":"Number","value":720.000000},"temperature":{"type":"Number","value":23.000000}}]docker-user-1@rcc-hrl-kvg-558:~/orion$

```

repository: firgavin/docker-container-service

repo_name: firgavin/docker-container-service


text:
# Wilfred

[![.github/workflows/check.yml](https://github.com/wilfred-dev/wilfred/actions/workflows/check.yml/badge.svg)](https://github.com/wilfred-dev/wilfred/actions/workflows/check.yml)
[![Python Versions](https://img.shields.io/pypi/pyversions/wilfred)](https://pypi.org/project/wilfred)
[![pypi](https://img.shields.io/pypi/v/wilfred)](https://pypi.org/project/wilfred)
[![Language grade: Python](https://img.shields.io/lgtm/grade/python/g/wilfred-dev/wilfred.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/wilfred-dev/wilfred/context:python)
[![Total alerts](https://img.shields.io/lgtm/alerts/g/wilfred-dev/wilfred.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/wilfred-dev/wilfred/alerts/)
[![Downloads](https://pepy.tech/badge/wilfred)](https://pepy.tech/project/wilfred)
[![Discord](https://img.shields.io/discord/666366973072113698?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://wilfredproject.org/discord)
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)

Wilfred is a command-line interface for running and managing game servers locally. It uses Docker to run game servers in containers, which means they are completely separated. Wilfred can run any game that can run in Docker.

⚠ Wilfred is currently under development and should not be considered stable. Features may break or may not be implemented yet. Use with caution.

## Documentation

The official documentation is available [here](https://docs.wilfredproject.org/en/latest/). For support, use our [Discord Chat](https://wilfredproject.org/discord). For bugs, you can open an issue [here](https://github.com/wilfred-dev/wilfred/issues).

## Supported games

As long as your server can run in Docker, it can probably run using Wilfred (after some tinkering). These are the games supported by default. You can submit new games to [wilfred-dev/images](https://github.com/wilfred-dev/images).

- Minecraft
  - Vanilla Minecraft
  - BungeeCord
  - Paper
  - Spigot
  - SpongeVanilla
  - Waterfall
  - Bedrock
- Mindustry
- Multi Theft Auto
- Voice Servers
  - TeamSpeak 3
  - Mumble

## Installation

Please refer to the [official documentation](https://docs.wilfredproject.org/en/latest/#installation) for further installation instructions and documentation.

### Quickstart

Make sure you have Docker installed (see the official documentation for more info). The recommended way of installing Wilfred is via [Homebrew](https://brew.sh). Once brew is installed, Wilfred can easily be installed from the official tap.

```bash
brew tap wilfred-dev/wilfred
brew install wilfred
```

Want the bleeding edge? You can install the latest commit using `--HEAD` (bugs are to be expected, don't use in production environments!).

```bash
brew tap wilfred-dev/wilfred
brew install --HEAD wilfred
```

Wilfred can also be installed using `pip`. You need to use **Python 3.7** or newer to run Wilfred.

```bash
pip install wilfred --upgrade
```

Once you got Wilfred installed, run `wilfred setup` to set a path for Wilfred to use to store server files.

![Creating a server in Wilfred](https://raw.githubusercontent.com/wilfred-dev/wilfred/master/docs/quickstart.gif)

To create your first server, use `wilfred create`. Most values have a default value, where you can just press return to use them.

Wilfred will ask you which "image" to use. An image is a set of configuration files that defines a specific game within Wilfred.  A couple of games are already built into Wilfred, but you can also create your own.

Then, Wilfred will ask you to set any environment variables (if available for that image). The environment variables differ from game to game and most of them have a default value.

Once the server is created, you can use `wilfred servers` to list available servers. To start it, use `wilfred start <name>`. To attach to the server console, you can use `wilfred console <name>`. If you want to start the server and attach to the server console in a single command, you can use `wilfred start <name> --console` (it will start the server and then immediately attach to the server console).

## Helping

The best places to contribute are through the issue tracker and the official Discord server. For code contributions, pull requests and patches are always welcome!

## Contributors ✨

Created, written, and maintained by [Vilhelm Prytz](https://github.com/vilhelmprytz).

Copyright (C) 2020-2022, Vilhelm Prytz<EMAIL_ADDRESS>

repository: wilfred-dev/wilfred

gha_language: Python

gha_license_id: MIT

repo_name: wilfred-dev/wilfred


text:
**HOW TO**
- Add this to your main file
```Processing
AnimationManager animationManager;

void setup(){

  animationManager = new AnimationManager();
}

void draw(){

    animationManager.Update();
}
```
- Add this in the file where you want to add animation
```Processing
class MyClass{

	Animation animation;

	MyClass(){

		// Currently only accept .PNG files.
		// Larger value on animation speed, plays animation slower
		animation = new Animation(int rows,int columns, "filename without extension", float animation speed);
	}

	void Loop(){

		animation.Loop(position.x, position.y);
	}

	void SingleCall(){

		// Returns if animation still running.
		boolean = animation.isPlaying();

		animation.Play(position.x, position.y);
		animation.Stop();
	}
}
```

repository: sloopernine/OmniLib-Processing

repo_name: sloopernine/OmniLib-Processing


text:
# homebridge-snowsense
[![verified-by-homebridge](https://badgen.net/badge/homebridge/verified/purple)](https://github.com/homebridge/homebridge/wiki/Verified-Plugins)
[![GitHub last commit](https://img.shields.io/github/last-commit/bbernstein/homebridge-snowsense.svg)](https://github.com/bbernstein/homebridge-snowsense)
[![npm](https://img.shields.io/npm/v/homebridge-snowsense?label=npm%20package)](https://github.com/bbernstein/homebridge-snowsense)
[![npm](https://img.shields.io/npm/dt/homebridge-snowsense.svg)](https://www.npmjs.com/package/homebridge-snowsense)

An Occupancy Sensor that indicates snowy conditions using local weather forecast

This is a plugin for [homebridge](https://github.com/nfarina/homebridge) that is a simple Occupancy Sensor that automatically detects occupancy ON when it's going to snow soon and OFF a while after it stops snowing. Think of **snow** being the **occupant** and you have ample warning of when the (un)welcome guest arrives.

This is based on my earlier project, [homebridge-snowswitch](https://github.com/bbernstein/homebridge-snowswitch) that was similar but acted as a switch rather than a sensor. That former project is no longer supported and does not work.

## New in v2.x

The app was mostly rewritten in TypeScript with settings now compatible with [homebridge-config-ui-x](https://www.npmjs.com/package/homebridge-config-ui-x) so it can be installed and configured without manually editing a config file.

## Installation

For any installation, you'll first need to get an *API Key* from [OpenWeather API](https://openweathermap.org/api/).

### Homebridge UI

Go to 'Plugins' page, search for `homebridge-snowsense` and click 'install'.

### Manually

1. Install homebridge using: `npm install -g homebridge`
2. Install this plugin using: `npm install -g homebridge-snowsense`
3. Update your configuration file. Read below.

## Configuration

### Homebridge UI

Click the 'Settings' button for the plugin and enter the required information.

### Manually

Add the following information to your config file.

**apiKey** [no default] is the *Secret Key* as assigned from
[OpenWeather](https://openweathermap.org/api)

**apiVersion** [default=3.0] is the version of the API to use. If you ware new to
this, then you'll want to use 3.0.

**apiThrottleMinutes** [default=15] is the number of minutes to wait between
API calls. This is to prevent exceeding the API call limit.

**debugOn** [default=false] is a flag to enable debug logging.

**location** field [no default] identifies the location for the snow checking.
It can be a "city,state,country" (eg "Boston,MA,US"), or zip code (eg 02134),
or "latitude,longitude" pair.

**units** [default='imperial'] (values 'metric' or 'imperial') is the units
defined in [OpenWeather Docs](https://openweathermap.org/api/one-call-api).
Basically, 'imperial' is Fahrenheit and 'metric' is Celcius.

**sensors** field [no default] is an array of sensors to create. Each sensor
has the following fields:

**displayName** field [no default] is the name you will see in the *Home* app for
this sensor.

**hoursBeforeSnowIsSnowy** field [default=3] is number of **hours** before
snow starts that the occupancy should go **on**. In other words, if the forecast
says it's going to snow in 3 hours or less, then the sensor turns on.

**hoursAfterSnowIsSnowy** field [default=3] is number of **hours** after
snow is last seen that the occupancy should go **off**. In other words, if the
the last time the current weather said it was snowing 3 or more hours ago, then
the sensor turns off.

**consecutiveHoursFutureIsSnowy** field [default=0] is number of consecutive
**hours** of snow after it starts should trigger the sensor. In other words, if
this is set to two and the forecast says it starts snowing in one hour and it will
also be snowing in two hours, then the sensor turns on.

Here's what the config might look like inside the `platforms` section.

```
        {
            "platform": "SnowSense",
            "name": "SnowSense",
            "apiKey": "**** get your key from OpenWeather ****",
            "apiVersion": "3.0",
            "debugOn": true,
            "apiThrottleMinutes": 15,
            "units": "imperial",
            "location": "Newton,ma,us",
            "onlyWhenCold": false,
            "coldTemperatureThreshold": 32,
            "sensors": [
                {
                    "displayName": "Snowing Now",
                    "hoursBeforeSnowIsSnowy": 0,
                    "hoursAfterSnowIsSnowy": 0,
                    "consecutiveHoursFutureIsSnowy": 0
                },
                {
                    "displayName": "Is Snowy",
                    "hoursBeforeSnowIsSnowy": 3,
                    "hoursAfterSnowIsSnowy": 3,
                    "consecutiveHoursFutureIsSnowy": 0
                }
            ]
        }

```

## Why this exists

I created this for a specific use case, which is to turn on and off snow melting
mats outside my house.

I have been happy with [HeatTrak](https://heattrak.com/) Snow Melting Mats
and when I purchased wireless outlets for them, I liked them even more.
So, on one snowy weekend I decided to take the automation to the next level
and build this plug-in.

Now, if the local forecast expects snow in the next few hours, the snow
melting mats will turn on, and when the snow stops falling, the mats will
turn off a few hours later.

I bought a set of [Etekcity](https://www.amazon.com/gp/product/B074GVPYPY) outlets
and installed [homebridge](https://github.com/nfarina/homebridge) and
[homebridge-vesync](https://www.npmjs.com/package/homebridge-vesync) to control
them from the my Apple-centric home using HomeKit.

To make them work with [HomeKit](https://www.apple.com/ios/home/), I needed
to get [homebridge](https://www.npmjs.com/package/homebridge) working. I
had an old [Raspberry Pi](https://www.raspberrypi.org/) sitting around so
I [installed it there](https://github.com/nfarina/homebridge/wiki/Running-HomeBridge-on-a-Raspberry-Pi)
and put the device in a closet with the rest of my network gear.

This should work pretty well with any switches you can get working with
[HomeKit](https://www.apple.com/ios/home/), and if you can also get
a [homebridge](https://www.npmjs.com/package/homebridge) setup working
and a [OpenWeather](https://openweathermap.org/api) API key, then the HomeKit
App end of this is pretty trivial.

## How to set up the automation

- Launch the [iPhone or iPad **Home** app](https://support.apple.com/en-us/HT204893)
- Create scenes; one to turn **on** the Snow Mats and another to turn them **off**
- Create a new **Automation**
- Select **An accessory is Controlled** as the trigger for the automation
- Select the Controller **IsSnowy**
- Select *When* to be **Turns On**
- Select the **Snow Mats On** scene
- Repeat for turning **Off** when the controller **Turns Off**

## Development notes

The latest version of this plugin was build following information from
[Homebridge Plugin Development](https://developers.homebridge.io/#/)
and the example
[Homebridge Platform Plugin Template](https://github.com/homebridge/homebridge-plugin-template)
and several other plugins around github.

### Reminders to the developer
(since I usually only look once a year and forget these things)

How to release a new [beta version](https://github.com/homebridge/homebridge-plugin-template#publishing-beta-versions):

How to increment beta version:

```agsl
npm run prepublishOnly
npm version prerelease
npm publish --tag beta
```

How to [release a new version](https://github.com/homebridge/homebridge-plugin-template#versioning-your-plugin).

eg (when updating patch version):

```agsl
npm run prepublishOnly
npm version patch
npm publish
```

## Reporting Issues and Suggestions

Please use the [GitHub Issue Tracker](https://github.com/bbernstein/homebridge-snowsense/issues)
to submit reports of issues or suggestions for improvements.

## Thanks

* Thanks to @apollo316 on github for pointing out that the DarkSky api is going
away and @nicoryan and others for recommending OpenWeather.
* Thanks to @rmkjr for suggesting moving from a Switch to an Occupancy Sensor.
* Thanks to @scoutbeer for detailed feedback and help testing v2.0.
* Thanks to @nvogt for suggesting temperature and consecutive hour options.
* Thanks to you for checking it out.

repository: bbernstein/homebridge-snowsense

branch_name: refs/heads/main

gha_language: TypeScript

repo_name: bbernstein/homebridge-snowsense


text:
---
title:  "About"
date:   2017-12-11 10:05:00 +01:00
menu:
  main:
    title: "About"
    name: "About"
    weight: 10
---

I use computers for fun and profit. In my spare time, I participate in the Free
and open-source software community.

## Projects

I wrote and maintain the Linux tiling window manager [i3](https://i3wm.org/)
since 2009.

Shortly thereafter, I started focusing on projects in Go, [my favorite
programming language](/posts/2017-08-19-golang_favorite/).

Sometimes I dabble in electronics: many people know me from the
[kinT](/posts/2020-07-09-kint-kinesis-keyboard-controller/) replacement keyboard
controller for Kinesis Advantage ergonomic keyboards, which allows you to run
the QMK Open Source Firmware. During the pandemic, I [made my doorbell intercom
smarter with MQTT](/posts/2021-03-13-smart-intercom-backpack/).

I used to be a [Debian](https://en.wikipedia.org/wiki/Debian) Linux Developer,
but these days I have [effectively
retired](/posts/2019-03-10-debian-winding-down/), aside from keeping services
running. Instead, I like to publish [Linux distribution research on the topic of
fast package management](/posts/tags/distri/).

My early adoptions are IPv6 and HiDPI, so I contributed patches to numerous
programs (chromium, apt, radvd, vsftpd, etc.)

## Talks

I sometimes give [talks](/talks).

## Contact

To email me, replace the first dot with an @ symbol in this site’s domain.

If you decide to GPG-encrypt your email, expect a delayed clear-text response.

repository: stapelberg/hugo

gha_language: HTML

repo_name: stapelberg/hugo


text:
README
======

Introduction
------------

jCore 0.0.2 - RESTful JSON Network Bindings

Depends on, and includes, the following technologies:

* JSON 3
* jQuery 1.7.2
* Knockout 2.1.0
* Knockout Mapping

Requires:

* Redis 2.4.14
* PHP 5.3.10

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

1. [Install Redis](http://redis.io/download).
2. Place the jCore project under your web root.

Example (0.0.2)
-------------------

You can place your custom client code in `js/script.js`. Here's an example of what a basic client could look like:

	jCore.config({
		root: '/jcore',
		xdebug: false
	});

	var viewModel = {
		resource: jCore.sync({
			// The URI of the resource to sync with.
			uri: '/hello-world',

			// All the properties you declare here will be data-bound.
			// You can set up Knockout declarative bindings to refer to them in your markup.

			//

			//

			init: { text:'', arr:'' }
		}),
		test: jCore.sync({
			uri: '/test',
			init: { foo:'' }
		})
	};

	// Subscribe to changes to a specific observable property.
	viewModel.test.foo.subscribe(function(newValue) {
		console.log(newValue);
	});

 	ko.applyBindings(viewModel);

Discussion
==========

Power to the Clients
--------------------

The "cloud" used to refer to a collection of vague, next-gen networking techniques. Now, it's more clearly defined, but has been defined by organizations with big data centers. They are steering the "cloud" toward being "an online place where your stuff can reside". Using this kind of cloud (now becoming difficult to avoid) provides some benefits, including ubiquitous accessibility, automatic backups, consistency across platforms, automatic software updates, etc.

Privacy is not one of them.

jCore's cloud philosophy makes the server a simple client hub, and gives power to its clients. A user's data is meant to reside on their own machine, and is accessible to only those they specifically grant. HTML5 makes this possible.

jCore is a server/network abstraction, so that you can focus on giving your client power. A jCore server is part resource repository, part notification center. Sync a client-side model with a server-side resource, and it will refresh its state regularly. Using Knockout, you can subscribe to changes with the model, or you can simply let your data bindings flash the update through to the DOM.

Network Performance
-------------------

jCore 0.0.2 does not make use of server-sent events (although a future version might). It uses the standard HTTP request-response model, polling the server for changes. Since this activity is common in jCore 0.0.2, making this efficient was a priority. If the resource hasn't changed, checking the server results in around 20 bytes of transferred data for each synced resource, with an average latency of about 16 ms (regardless of the size of the resource). On the other hand, if the resource has changed, the client downloads the entire JSON resource value. So, make changes to resources only when necessary, and only syncronize what you need.

Proposal 0.0.3a - Write Access to jCore Resources
-------------------------------------------------

Configuring jCore to sync a writeable resource:

	var self = this;

	// This asks jCore for write access to the resource.
	self.resource = jCore.sync({
		uri: '/jcore/ajax/?res=/hello-world',	// The resource id, or URI.
		write: true,	// Do we want write access to this resource? Default is false.
		merge: function(serverValue, clientValue) {
			// This is called when a write conflict is detected.
			// It is optional. By default, the server-side value is retained, and the client
			//	value is discarded.

			// This resends the change we wanted.
			// Right before this is called, jCore received and handled a sync response,
			//	so this might go through this time.
			// If yet another change has been made, and the change request is rejected again,
			//	this merge function will just be called again.
			self.resource(clientValue);
		}
	});

	// On a resource with write access, this causes change requests to be scheduled.
	self.resource('New value');

Change requests contain the uri of the resource to change, the client's old resource value (or
its hash, whichever is lighter-weight), and the client's new resource value.

Similarly to how the server processes sync requests, the server compares the change request value
with the server-side value (comparing hashes if it gets that instead).

If the request's old value (or hash) does NOT match the server's value (or hash), it responds like it
would with a sync request: it sends back a snapshot of the current server-side value of the resource.

However, if it matches, the server sets the server-side resource value to the request's new value (and generates its hash), then sends back a lightweight "synced" code.

This means that if the client sets its local copy of the resource, it might go through or it might not. If it doesn't, its merge function is called. If it doesn't provide a merge function, the client-side value is overwritten.

repository: Azaeres/jcore

path: /docs/disabled/jCore README.md

filename: jCore README.md

repo_name: Azaeres/jcore


text:
---
layout: post
title: "Testing concurrent code execution"
modified:
categories: blog
excerpt: "How to easily test concurrent code execution with java 8"
tags : [test, java]
comments: true
image:
  feature:
date: 2016-09-21T17:00:00-04:00
---

Running good tests is hard. Running tests which test various scenarios in concurrent environment is even harder.

One of my most recent use-cases was to write an integration test which proves that concurrent update of the same entity in a persistent storage throws an exception. There are dozens of other use-cases which require similar test to be written.

The first attempt to write this kind of code is to explicitly create an ExecutorService and submit threads which execute the method being tested. But there was a lot of boilerplate code which pollutes the test. Isn't there a more elegant solution?

After few attempts to improve this, I came up with the following utility method:

{% highlight java %}
public class TestUtils {
    /**
     * Execute in parallel the provided runnable for a limited number of times.
     *
     * @param execution the {@link Runnable} to execute in parallel.
     * @param limit number of times the runnable should be executed.
     */
    public static void awaitParallelExecution(final Runnable execution, final int limit) throws Throwable {
        try {
            CompletableFuture.allOf(Stream.generate(() -> execution)
                    .limit(limit)
                    .map(CompletableFuture::runAsync)
                    .toArray(CompletableFuture[]::new)).join();
        } catch (final CompletionException e) {
            throw e.getCause();
        }
    }
}
{% endhighlight %}

The above code allows to easily test any kind of logic in parallel using CompletableFuture & Stream utilities. Using the above utility looks pretty concise and clear:

{% highlight java %}
public class MyTest {
    @Test(expectedExceptions = CASMismatchException.class)
    public void shouldFailOnConcurrentModification() throws Throwable {
        final Runnable execution = () -> userService.createOrUpdate(accountId, "John");

        //ensure document created
        execution.run();

        //perform update in parallel
        awaitParallelExecution(execution);
    }
}
{% endhighlight %}

This test assert that a hypothetical userService throws the CASMismatchException when the update operation is performed concurrently.

# Conclusion
The above example shows an approach of easily test how a code behave in concurrent environment.


text:
---
layout: post
title: Hello world
---
This is my blog, created using _Jekyll Now_ and hosted on _GitHub Pages_.

Let's clear up all this "git" stuff first. Git (_noun, informal_) is an unpleasant or contemptible person. Git is also a distributed version control system. Try not to confuse the two.

[GitHub](http://github.com) is a place to store and manage code (and related thingymebobs) in a git repository - or _repo_ for short. Repos can be managed from the command line, on the GitHub website, or using one of the many tools available such as [GitHub for Mac](https://mac.github.com). All this stuff is free.

[GitHub Pages](http://pages.github.com) let's you build and host websites stored in a repo. You can host a website (such as this blog) in GitHub Pages. GitHub is free - I may have mentioned this - and so is GitHub Pages.

GitHub Pages uses [Jekyll](http://jekyllrb.com) - a static site generator that is great for blogs. It turns your content into a static website using simple templates. Write content locally, test locally, commit to your repo, and _voila_ - your Github Pages website is auto-magically updated. Static websites are simple; as simple as websites can be.

[Jekyll Now](http://jekyllnow.com) makes light work of creating a basic blog for hosting in GitHub Pages. The code for Jekyll Now is hosted in a git repo, and it's accompanying website is hosted with GitHub Pages. I hope you're following this.

Jekyll content is written in [Markdown](http://daringfireball.net/projects/markdown/), a simple plain text format that is easy to write and easy for programmable electronic devices to convert into HTML.

That's quite enough to be getting on with.


text:
---
layout: post
title: Linker scripts
category: programming
---

I while ago I wrote a post about [linking basics]({% post_url programming/2017-02-11-linking-basics %}), where I talked about ELF files and their structure.
This post is based on chapter 7 from the book [Computer Systems: A Programmer's Perspective ](https://www.amazon.com/Computer-Systems-Programmers-Perspective-3rd/dp/013409266X/ref=sr_1_1?ie=UTF8&qid=1490718500&sr=8-1&keywords=computer+systems) and this [document](http://www.scoberlin.de/content/media/http/informatik/gcc_docs/ld_toc.html)

# Object files
Linkers combines inputs files (relocatable files) into a single output file (executable file), this files are **object files**

Object files come in three forms:
- Relocatable object file. Contains binary code and data in a form that can be combined with other relocatable object files at compile time to create an executable object file.
- Executable object file. Contains binary code and data in a form that can be copied directly into memory and executed.
- Shared object file. A special type of relocatable object file that can be loaded into memory and linked dynamically, at either load time or run time.

Each object file has a list of sections:

 ![ELF object file](/images/posts/linking-basics-1.png)
*Image obtained from this [site](https://people.cs.pitt.edu/~xianeizhang/notes/Linking.html)*

* `.init` is the initialization code before the `main` in C such as set to zero global variables or defined the interrupt vector table.
* `.text` is the machine code of the compiled program
* `.rodata` read-only data, such as `const char`
* `.data`  global variables that have been initialized
* `.bss`  uninitialized global variables
* `.symtab` table symbol with information about functions and global variables that are defined and referenced in the program
* `.debug` debugging symbol table, only generated when compiling with `-g`
* `.line` mapping between actual C code and compiled code, only generated when compiling with `-g`
* `.strtab` a string table for symbol in `.symtab` and `.debug`

## Note
 ELF executables are designed to be easy to load into memory, with contiguous chunks of the executable file mapped to contiguous memory segments. This mapping is described by the _segment header table_. That means that relocatable files **does not** have a segments header table.

# Linker Scripting
I will explain the `STM32F746NGHx_FLASH.ld` linker file found in the `STM32CubeF7`, because I think is the best way to understand this scripting language.

The basic skeleton is as follows:

```text
/* Entry Point */
ENTRY(Reset_Handler)

/* Specify the memory areas */
MEMORY
{
}

/* Define output sections */
SECTIONS
{
}
```

You can notice three linker commands:
- `ENTRY` command defines the location where the program execution starts. It is at the beginning of `.text`. In this case the program will start at the symbol `Reset_Handler`.
- `MEMORY` command describes the location and size of blocks of memory in the target. You can use it to describe which memory regions may be used by the linker, and which memory regions it must avoid.
- `SECTIONS` command tells the linker how to map input sections into output sections, and how to place the output sections in memory.

## MEMORY command
The syntax of this command is:

```text
MEMORY
  {
    name (attr) : ORIGIN = origin, LENGTH = len
    ...
  }
```

The memory mapping described in the [datasheet](https://www.st.com/resource/en/datasheet/DM00166116.pdf) shows the addresses of the memories. `RAM` starts at 0x20000000 and has a length of `320KB` which means that the end of the stack is at 0x20050000,  while the 1MB `FLASH` (with AXIM interface)  starts at 0x8000000.
Thus the memory regions are defined as:

```text
/* Highest address of the user mode stack */
_estack = 0x20050000;    /* end of RAM */

/* Specify the memory areas */
MEMORY
{
RAM (xrw)      : ORIGIN = 0x20000000, LENGTH = 320K
FLASH (rx)      : ORIGIN = 0x8000000, LENGTH = 1024K
}

```

Note that `RAM` has three attributes:  contain executable code (x), read (r) and write (w). On the other hand, `FLASH` is a write (w) section and contain executable code (x).

## SECTIONS command
 The format of this command is:

```text
SECTIONS
{
  sections-command
  sections-command
  ...
}
```

and the full description of an output section looks like this:

```text
section [address] [(type)] : [AT(lma)]
  {
    output-section-command
    output-section-command
    ...
  } [>region] [:phdr :phdr ...] [=fillexp]
```

Before we start, I have to mention that every output section has two addresses:
- A **virtual memory address**, which is the address the section will have when the code runs
- A **load memory address**, where the code lives

There are two memory regions defined: RAM and FLASH. RAM is volatile memory, and hence it is not possible to directly make the data available in RAM, on power up.
Thus, all code and data should be stored in Flash before power-up

The main output sections in the linker file are:

 ![output sections](/images/posts/linker-scripts-1.png)

If we translate this table to linker scripting language:

```text
SECTIONS
{
  /* The startup code goes first into FLASH */
  .isr_vector :
  {
    . = ALIGN(4);
    KEEP(*(.isr_vector)) /* Startup code */
    . = ALIGN(4);
  } >FLASH

  /* The program code and other data goes into FLASH */
  .text :
  {
    . = ALIGN(4);
    *(.text)           /* .text sections (code) */
    *(.text*)          /* .text* sections (code) */
    *(.glue_7)         /* glue arm to thumb code */
    *(.glue_7t)        /* glue thumb to arm code */
    *(.eh_frame)

    KEEP (*(.init))
    KEEP (*(.fini))

    . = ALIGN(4);
    _etext = .;        /* define a global symbols at end of code */
  } >FLASH

  /* Constant data goes into FLASH */
  .rodata :
  {
    . = ALIGN(4);
    *(.rodata)         /* .rodata sections (constants, strings, etc.) */
    *(.rodata*)        /* .rodata* sections (constants, strings, etc.) */
    . = ALIGN(4);
  } >FLASH

    /* used by the startup to initialize data */
  _sidata = LOADADDR(.data);

  /* Initialized data sections goes into RAM, load LMA copy after code */
  .data :
  {
    . = ALIGN(4);
    _sdata = .;        /* create a global symbol at data start */
    *(.data)           /* .data sections */
    *(.data*)          /* .data* sections */

    . = ALIGN(4);
    _edata = .;        /* define a global symbol at data end */
  } >RAM AT> FLASH

  /* Uninitialized data section */
  . = ALIGN(4);
  .bss :
  {
    /* This is used by the startup in order to initialize the .bss secion */
    _sbss = .;         /* define a global symbol at bss start */
    __bss_start__ = _sbss;
    *(.bss)
    *(.bss*)
    *(COMMON)

    . = ALIGN(4);
    _ebss = .;         /* define a global symbol at bss end */
    __bss_end__ = _ebss;
  } >RAM

}
```

Things to note:
- `.`: is the **location counter**, and  always refers to a location in an output section
- `symbol = expression`: assign _expression_ to this _symbol_
- `ALIGN(exp)`:  Return the location counter (.) aligned to the next `exp` boundary. `exp` must be an expression whose value is a power of two.
- `>RAM AT> FLASH`: The linker will normally set the LMA equal to the VMA. You can change that by using the `AT` keyword. The expression lma that follows the AT keyword specifies the load address of the section
- `*(pattern)`: `*` is a [wildcard pattern](http://www.scoberlin.de/content/media/http/informatik/gcc_docs/ld_3.html#SEC23). For example: `*(.text)` means _put here all the .text sections_.
- `KEEP(symbol)`: is a command keeps the symbol, when link-time garbage collection `--gc-sections` is in use

In conclusion, the job of the linker can be summarized as follows:

![Executable file](/images/posts/linker_script.png)

# Final words
If there are files such as `STM32F746NGHx_FLASH.ld`, why should I bother to learn linker scripting language?

- Understanding linkers will help you to manage different input object files from different sources (C, ADA, assembler) into a single executable file.
- Understanding linking will help you understand some computers works, how the code is run.

I hope this guide is helpful ;)

repository: daleonpz/baremetallics

repo_name: daleonpz/baremetallics


text:
Vault
=====

The following are instructions on how to setup a personal test Vault server.
The crypto keys are stored on the machine and Vault is only available over
localhost.

### Installing
Like all HashiCorp's offerings, Vault is a [binary download](https://www.vaultproject.io/downloads.html).
Inside the package is the binary for the Vault Server. Extract it into ~/vault/

To install the [hvac](https://github.com/ianunruh/hvac) Vault library run `pip3 install hvac`

### Configuration
Create the following file as ~/vault/vault.cfg, which sets the location to
store data and where to listen for connections

```
backend "file" {
    path = "~/vault/data"
}

listener "tcp" {
    address = "localhost:8200"
    tls_disable = 1
}
```

### Running the server
This document covers running the Vault server in the foreground. If you want to
run it as a service, take a look at boss-manage/salt_stack/salt/vault/files/service.sh
for a starting point.

From the command line run `./vault server --config=vault.cfg` from ~/vault/

### Initialization
The first time a Vault server is started it needs to be initialized. Every
other time it is started the vault needs to be unsealed to allow access to the
encrypted data. Create the following script (~/vault/startup.py) to handle both
operations and run it each time the Vault server is started.

```python
#!/usr/bin/env python3
import hvac

client = hvac.Client(url="http://localhost:8200")
if not client.is_initialized():
    print("Initializing")
    result = client.initialize(1, 1)

    with open("~/vault/vault_token", "w") as fh:
        fh.write(result["root_token"])
    with open("~/vault/vault_key", "w") as fh:
        fh.write(result["keys"][0])
elif client.is_sealed():
    print("Unsealing")
    with open("~/vault/vault_key", "r") as fh:
        client.unseal(fh.read())
else:
    print("Vault is initialized and unsealed")
```

### Communicating with Vault
Once the Vault server is running and unsealed we can store secrets int it. To
do this we need to authenticate to the server using the *root token* that was
created during initialization. The following python3 code shows connecting to
and working with the local Vault server.

```python
import hvac

with open("~/vault/vault_token", "r") as fh:
        root_token = fh.read()

client = hvac.Client(url="http://localhost:8200", token=root_token)
assert client.is_authenticated()

client.write('secret/foo', baz='bar')
print(client.read('secret/foo'))
client.delete('secret/foo')
```

**Note:** All secrets stored should be stored under "/secret/"
**Note:** Secrets can be stored at any depth, ex "/secret/foo/bar/boo"
**Note:** There can be multiple key/value pairs at any depth


text:
# JSONP ajaxNav v.0.4
Professionally accelerate your site navigation. Link directly thorugh ajax for improving the user experience. Now ajaxNav features history.

Developer friendly. Includes a versatile API. Created with simplicity in mind.

## Documentation
### Instructions
JSONP ajaxNav it's a couple of shortcuts that I use to use extensively for all the web projects that needed ajax navigation, hence the name.
All the javascript functionalities are bundled together and aims to be compatible enough to be deployed in most enviroments (disclaimer: no guarantees :P).
I have a couple of new additions that i will be adding as soon as I test them thoroughly.
As this version with the "JSONP" prefix requires quite a few server work to be implemented in any site, I will be releasing another repo which won't require jsonp output.

### Steps

First of all you have to stop the output of the page when a jsonp call requests it and serve a `jsonp callback` instead.
In a PHP template we won't print innecessary code and just output the content in a callback like this:

```php
<?php
	// First part of the server script, make sure
	// we don't print the document head for jsonp calls...
	if(!$_GET["callback"]) {
?>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title><?php echo $page_title; ?></title>
	</head>
	<body class="<?php echo $body_classes; ?>">
		<div class="wrapper">
			<header id="banner"><?-- etc. --></header>
			<nav id="menu"><?-- etc. --></nav>
			<main id="content">
<?php
	// ...and let's prepare the data we will output
	} else {
		global $data;
		$data['title'] = $page_title;
		$data['bodyclasses'] = $body_classes;
		ob_start();
	}
?>
				<!-- And now is the time for the actual bits of content: -->
				<h1>Lorem ipsum</h1>
				<p>Sit amet, consectetur <a href="<?php echo $site_url; ?>/index.php?sec=adipiscing">adipiscing</a> elit. Nunc fringilla cursus scelerisque. </p>
				<p><a href="<?php echo $site_url; ?>">Back ➜</a></p>
<?php
	// Final part of the server script, make sure we don't print the document footer for jsonp calls...
	if(!$_GET["callback"]) {
?>
			</main>
			<footer><?-- etc. --></footer>
		</div>
	</body>
</html>
<?php
	// ...and let's output the data that we have collected!
} else {
	global $data;
	$data['contents'] = ob_get_contents();
	ob_end_clean();
	echo $_GET["callback"].'('.json_encode($data).');';
}
?>
```

Then you want to include the `jQuery` and `ajaxNav` files at the
 bottom of your document (preferently, it really works anywhere you want).
 Also we will create an instance of ajaxNav and bind ajaxNav to all the hyperlinks

```html
	<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
	<script type="text/javascript" src="ajaxNav.js"></script>
	<script type="text/javascript">
		// You can enable ajaxNav just by passing it the url of your site
		var myAjaxNavSite = new ajaxNav('http://example.com');
	</script>
</body>
```

## That's it!
You can watch a [demo here](http://surgever.com/ajaxnav/demo/).

## License MIT
Project License can be found [here](LICENSE.md).

repository: surgever/jsonp-ajaxnav

repo_name: surgever/jsonp-ajaxnav


text:
### [CVE-2020-17507](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-17507)
![](https://img.shields.io/static/v1?label=Product&message=n%2Fa&color=blue)
![](https://img.shields.io/static/v1?label=Version&message=n%2Fa&color=blue)
![](https://img.shields.io/static/v1?label=Vulnerability&message=n%2Fa&color=brighgreen)

### Description

An issue was discovered in Qt through 5.12.9, and 5.13.x through 5.15.x before 5.15.1. read_xbm_body in gui/image/qxbmhandler.cpp has a buffer over-read.

### POC

#### Reference
No PoCs from references.

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

repository: trickest/cve

repo_name: trickest/cve


text:
# oclInspector
The command line tool for showing OpenCL device information

## Dependencies
oclInspector only depends on pyopencl. Before running it, please check if the pyopencl is installed. If not, please use pip to install it:

```
pip install pyopencl
```

## Run
We can run oclInspector with the following command:

```
python inspector.py
```

## Usage

We can use number key to choose items that we want to see. There are two general commands at all pages which are `0` for going back and `-1` for exit the app immediately.

### Platform
oclInspector lists all of your OpenCL platforms for you at the first page, like:

```
=====================================================================================
 1 platform NAME   : NVIDIA CUDA
            VERSION: OpenCL 1.2 CUDA 8.0.0
            PROFILE: FULL_PROFILE
            VENDOR : NVIDIA Corporation
-------------------------------------------------------------------------------------
 2 platform NAME   : Intel(R) OpenCL
            VERSION: OpenCL 2.0
            PROFILE: FULL_PROFILE
            VENDOR : Intel(R) Corporation
-------------------------------------------------------------------------------------
Please choose which platform you want to see (1 ~ 2, 0 for back, -1 for exit):
```

### Platform devices

We can type the number to see detailed information. In this case, we type 1 if we want to see NVIDIA CUDA platform:
```
Platform name                           :                              NVIDIA CUDA
Platform profile                        :                             FULL_PROFILE
Platform vendor                         :                       NVIDIA Corporation
Platform version                        :                    OpenCL 1.2 CUDA 8.0.0
Platform extensions                     :         cl_khr_global_int32_base_atomics
                                        :     cl_khr_global_int32_extended_atomics
                                        :          cl_khr_local_int32_base_atomics
                                        :      cl_khr_local_int32_extended_atomics
                                        :                              cl_khr_fp64
                                        :            cl_khr_byte_addressable_store
                                        :                               cl_khr_icd
                                        :                        cl_khr_gl_sharing
                                        :                   cl_nv_compiler_options
                                        :             cl_nv_device_attribute_query
                                        :                      cl_nv_pragma_unroll
                                        :                      cl_nv_d3d10_sharing
                                        :                     cl_khr_d3d10_sharing
                                        :                      cl_nv_d3d11_sharing
                                        :                          cl_nv_copy_opts
================================================================================
1  Device name                             :                         GeForce GTX 950M
   Device type                             :                                      GPU
   Device version                          :                          OpenCL 1.2 CUDA
-------------------------------------------------------------------------------------
Please choose which device you want to see (1 ~ 1, 0 for back, -1 for exit):
```

oclInspector lists detailed platform information and lists all devices on this platform.

### Device

Once we choose 1 to see the GeForce GTX 950M, we can see the basic information of device and 4 information group.
```
Device name                             :                         GeForce GTX 950M
Device type                             :                                      GPU
Device version                          :                          OpenCL 1.2 CUDA
Device Profile                          :                             FULL_PROFILE
=====================================================================================
1  Memory                                  :                          Memory info(22)
2  Device info                             :                          Device info(30)
3  Data type                               :                       Data type info(18)
4  Image                                   :                           Image info(11)
Please choose which information group you want to see (1 ~ 4, 0 for back, -1 for exit):
```

### Device information group

We can choose 1 if we want to see memory information:

```
Device name                             :                         GeForce GTX 950M
Device type                             :                                      GPU
Device version                          :                          OpenCL 1.2 CUDA
Device Profile                          :                             FULL_PROFILE
=====================================================================================
Global memory cache line size           :                                     128B
Global memory cache size                :                                  80.00KB
Global memory cache type                :                         READ_WRITE_CACHE
Global memory size                      :                                   2.00GB
Max preferred size of global variables  :                  Not available (version)
Local memory size                       :                                  48.00KB
Local memory type                       :                                    LOCAL
Max constant arguments count            :                                        9
Max size of a constant buffer           :                                  64.00KB
Max global variable size                :                  Not available (version)
Max size of memory object allocation    :                                 512.00MB
Max parameter size                      :                                   4.25KB
Max pipe objects                        :                  Not available (version)
max work group size                     :                                     1024
max work item dimensions                :                                        3
max work item size                      :                         [1024, 1024, 64]
base address align                      :                                     4096
Local memory size                       :                                  48.00KB
The max size of the device queue        :                  Not available (version)
The size of the device queue            :                  Not available (version)
Device command-queue properties         :                  Not available (version)
Host command-queue properties           :            OUT_OF_ORDER_EXEC_MODE_ENABLE
                                        :                         PROFILING_ENABLE
None (1 ~ 0, 0 for back, -1 for exit):
```

- There are a few fields shown `Not available (version)` or `Not available (extensions)` which means this fields is not available on this device.
- For some devices, it cannot read OpenCL device info correctly that may be a driver issue. If this happens, the field shows `ERROR TO READ VALUE`
- If our pyopencl is too old to list properties, a field shows `pyopencl too old to have this.`

## Missing fields (TODO list)
We may find there are some missing fields at [pyopencl API](https://documen.tician.de/pyopencl/runtime_const.html#device_info):

- sub-devices related
- vendor specified: amd, intel, nv, ...
- OpenCL version greater than 2.1 (included)
- pyopencl version greater than 2016.2

## Missing informations (TODO list)
There are some objects which can be inspected and not in the list, like kernel, etc.

repository: phokgoan/oclInspector

repo_name: phokgoan/oclInspector


text:
## These are the questions I was tasked to complete for the take home test

All the implementation are done with python. Though the questions can be implemented with another language I chose to go with python as a python Dev was needed.

####  Problem 1: String transformation (Python, JS)

You are given a string S composed of characters A to Z, formulate a function that transforms a given string by changing each letter as follows: a becomes z, b becomes y, c becomes x, e.t.c

##### Sample input
`>> S = acdz`

##### Sample output
`>> zxwa`

#### Problem 2: String splitting (Python, JS)

You a given a string S of any length, formulate a function that splits the strings into substrings of a given length N and returns the substrings in a list. If the length of S is not evenly divisible by N, it is acceptable to have the last substring with a length less than N, see example below.

##### Sample input
```
>> S = This is a test

>> N = 3

```

##### Sample output
`>> [Thi, s i, s a,  te, st]`

#### Problem 3: Ceiling alarm (Python, JS)

Assume you have a sensor that reports temperature readings periodically. The readings are stored as 2 lists of equal length; List T composed of timestamps for each reading and list R composed of temperature readings for each of the matching timestamps. Your goal is to identify timestamps at which a certain threshold temperature Q was crossed.

Formulate a function that takes lists T and R and a threshold temperature Q and returns a list of timestamps where Q was exceeded. Note that you should only return timestamps representing a datapoint that crosses the threshold, and ignore those that remain above the threshold.

##### Sample input:
```
>> T =  [1460545900,<PHONE_NUMBER>,<PHONE_NUMBER>,<PHONE_NUMBER>,<PHONE_NUMBER>,<PHONE_NUMBER>]

>> R = [0, 7, 12, 18, 8, 17]

>> Q = 10

```

##### Sample output
`>> [1460545920,<PHONE_NUMBER>]`

#### Problem 4: Stock buying (Python, JS)

You are given a list P of average share prices for a particular stock for each day in a given year. Your goal is to buy 1 share and later sell it at maximum profit. Formulate a function that takes list P and returns the best day to buy (B) and the best day to sell (S). You have to buy the share before you can later sell it.

##### Sample input
`>> P = [30, 20, 10, 15, 17, 25, 20, 23]`

##### Sample output
```
>> B = 3 // buy at price 10

>> S = 6 // sell at price 25

```

##### Problem 5: Bounce the ball

Please see the code below which moves a ball through 2D space. You may use and edit *either* the Python or Java code below, whichever you are more comfortable with.

This code defines a wall, but currently allows the ball to pass through it.

Please adjust the code so that the ball bounces back if it contacts the vertical wall.  Ignore physics (friction, gravity, etc).

Please copy the code into your answer, and adjust as you see fit.

```.py
WALL_X = 5 # A vertical line on a 2D coordinate system at x = 5

class Ball(object):

    def __init__(self, _vx=0.5, _vy=0.5):
        self.running = False
        self.x = 0 # Position X
        self.y = 0 # Position Y
        self.vx = _vx # Velocity X
        self.vy = _vy # Velocity Y

    def step(self):
        self.x += self.vx
        self.y += self.vy
        print "Stepped to %s, %s" % (this.x, this.y)

    def run(self, steps=50):
        if not self.running:
            self.running = True
            for s in range(steps):
                self.step()
            self.running = False

b = Ball()
b.run()

```

##### Java

```.java
public class Ball {

    public static int WALL_X = 5; // A vertical line on a 2D coordinate system at x = 5

    private double x;
    private double y;
    private double vx;
    private double vy;
    private boolean running;

    public Ball(double _vx, double _vy) {
        this.running = false;
        this.x = 0; // Position X
        this.y = 0; // Position Y
        this.vx = _vx; // Velocity X
        this.vy = _vy; // Velocity Y
    }

    private void step() {
        this.x += this.vx;
        this.y += this.vy;
        System.out.println("Stepped to " + this.x + ", " + this.y);
    }

    public void run( int steps ) {
        if (!this.running) {
            this.running = true;
            for (int i=0; i<steps; i++) {
            this.step();
            }
            this.running = false;
        }
    }

    public static void  main(String[] args){
        Ball b = new Ball(0.5, 0.5);
        b.run(50);
    }
}

#### Tests

Tests are on `test_problems.py`

repository: kevpy/take-home-test

repo_name: kevpy/take-home-test


text:
# LCD HD44780 (1602 / 2004) with I2C interface

Example *lcd_clock.py* will show time and date on the display.

# How to use it
Get I2C buses...
```bash
ls /dev/i2c*
```
You may receive:
/dev/i2c-**1**

Get I2C address by bus number...
```bash
i2cdetect -y 1
```
You may receive a number like 27 or 3F, these are hex numbers 0x27 or 0x3F
```python
import lcd_i2c_lib as LCD

lcd = LCD.lcd()  # will use defaul values
# or
lcd = LCD.lcd(i2c_address=0x27, i2c_bus=1)
```

# LICENSE
See the [LICENSE](../LICENSE.md) file for license rights and limitations.

license: Unlicense

repository: StMaHa/raspberry-examples

repo_name: StMaHa/raspberry-examples


text:
FixtureManager
==============

The FixtureManager handles the main process.
It consists of the following components and each of these can be replaced:

* **Loader** load the fixtures (yaml, toml, php etc.) and return it as a normalized FixtureCollection object
* **Executor** resolves the references and passes the data to the converter to create objects
* **Persister** save the objects, in example in a database
* **ServiceProvider** provides services which you can use in fixtures
* **EventDispatcher** gives you the possibilty to hook in the process

Default FixtureManager
----------------------

A very simple example to create the default FixtureManager

``` php

use DavidBadura\Fixtures\FixtureManager\FixtureManager;

// $objectManager can be curently Doctrine ORM Entity Manager or Doctrine MongoDb DocumentManager
$fixtureManager = FixtureManager::createDefaultFixtureManager($objectManager);

```

The static method `FixtureManager::createDefaultFixtureManager` expects a persister compatible object.
All Doctrine ObjectManagers are supported as for example
Doctrine ORM, Doctrine Mongo ODM oder Doctrine Couch ODM.

To create your own persister, read the persister documentation.

Use FixtureManager
------------------

The FixtureManager is easy to use.
The first parameter is the path to the fixtures. The second is the options.

``` php

use DavidBadura\Fixtures\FixtureManager\FixtureManager;

$fixtureManager = FixtureManager::createDefaultFixtureManager($objectManager);

$fixtureManager->load('path/to/fixtures', array('tags' => array('install')));

```

Available Options:

 - **tags** filters the fixtures
 - **dry_run** tests the sequence without storing the result

repository: DavidBadura/Fixtures

gha_language: PHP

repo_name: DavidBadura/Fixtures


text:
# InvoicePrinter Server

InvoicePrinter comes with a server that can be run from a command line with `invoice_printer_server`. Since 2.x releases this server is packaged separately in `invoice_printer_server` gem.

Apart from this you can also manually mount the server inside of your Rack application.

## Running the server

### From a command line

Once installed, InvoicePrinter Server provides `invoice_printer_server` executable that starts the Puma server:

```bash
$ invoice_printer_server -h <IP_ADDRESS> -p 5000
```

`-h` defines a host and `-p` defines a port. For help you can run `--help`.

By default server binds to `<IP_ADDRESS>:9393`.

#### As a Docker image

Get the public image and run it:

```bash
$ sudo docker pull strzibnyj/invoice_printer_server:$VERSION
$ sudo docker run -d -p 9393:9393 -v ~/path/to/invocies:/data:Z -t docker.io/strzibnyj/invoice_printer_server
```
You can use `latest` as a `$VERSION`. Specifying the `-v` option is only required when using the `/print` action to create the documents at certain path. It will allow you to provide the desired filename as "/data/invoice-name.pdf".

The server will then be available on `<IP_ADDRESS>:9393`.

Docker image already contains the optional `invoice_printer_fonts` gem.

### As a mountable Rack app

If you want you can always run the server from your custom program or mount it directly from a Rack app.

`InvoicePrinter::Server` is a Rack app as any other. Example:

```ruby
require 'rack/handler/puma'
require 'invoice_printer/server'

Rack::Handler::Puma.run InvoicePrinter::Server.freeze.app
```

## Available API

Endpoints accept similar arguments as the corresponding methods to `InvoicePrinter`. `render` is used for directly getting the PDF output whereas `print` would accept `filename` option and save the document to that
file.

A content type is always `application/json` both for requests and responses.

### `POST /render`

Directly render PDF data.

Options:

- `document` - JSON representation of the document
- `labels` - JSON for labels
- `font` - path to font file or builtin font name
- `bold_font` - path to bold font file or builtin font name
- `stamp` - path to stamp file
- `logo` - path to logotype file
- `background` - path to background file
- `page_size` - letter or A4 page size

These parameters are the same as for the [command line](./COMMAND_LINE.md).

On success a `200` response is returned:

```json
{ "result": "ok", "data": "base64 encoded PDF document" }
```

On error a `400` response is returned:

```json
{ "result": "error", "error": "error description" }
```

#### Examples

##### curl

Example of calling the API to render a document using `curl`:

```
$ curl -X POST http://<IP_ADDRESS>:9393/render -H "Content-Type: application/json" --data '{"document":{"number":"c.<PHONE_NUMBER>01","provider_name":"Petr Novy","provider_tax_id":"56565656","provider_tax_id2":"","provider_lines":"Rolnická 1\n747 05  Opava\nKateřinky","purchaser_name":"Adam Cerny","purchaser_tax_id":"","purchaser_tax_id2":"","purchaser_lines":"Ostravská 1\n747 70  Opava","issue_date":"05/03/2016","due_date":"19/03/2016","subtotal":"Kc 10.000","tax":"Kc 2.100","tax2":"","tax3":"","total":"Kc 12.100,-","bank_account_number":"156546546465","account_iban":"IBAN464545645","account_swift":"SWIFT5456","items":[{"name":"Konzultace","quantity":"2","unit":"hod","price":"Kc 500","tax":"","tax2":"","tax3":"","amount":"Kc 1.000"},{"name":"Programovani","quantity":"10","unit":"hod","price":"Kc 900","tax":"","tax2":"","tax3":"","amount":"Kc 9.000"}],"note":"Osoba je zapsána v zivnostenském rejstríku."}}'
```

##### Node.js

See [/examples/clients/node.js](/examples/clients/node.js).

### `POST /print`

Print resulting document to a file.

Options:

- `document` - JSON representation of the document
- `labels` - JSON for labels
- `font` - path to font file or builtin font name
- `bold_font` - path to bold font file or builtin font name
- `stamp` - path to stamp file
- `logo` - path to logotype file
- `background` - path to background file
- `page_size` - letter or A4 page size
- `filename` - path for saving the generated output PDF

On success a `200` response is returned:

```json
{ "result": "ok", "path": "/path/basically/what/was/sent/as/filepath" }
```

On error a `400` response is returned:

```json
{ "result": "error", "error": "error description" }
```

gha_language: Ruby


text:
## Installation

```
npm install
or
yarn
```

Start dev server for development

```
npm start
or
yarn start-yarn
```

Build

```
npm run build
or
yarn build
```

## Features

- HTML hot reload
- HTML partials(you can include html partial)
- Pretty console output(Friendly errors webpack plugin)
- Babel(es6/7)
- SASS
- Autoprefixing and minifying with postcss

demo : https://krowli.github.io/map-marker-box/

repository: Krowli/map-marker-box

gha_language: JavaScript

repo_name: Krowli/map-marker-box


text:
# Build a COVID-19 Dashboard With Fewer Than 40 Lines of Code

Lance Reinsmith, M.D. is a radiologist and programming hobbyist who lives and works in San Antonio, TX.  Dr. Reinsmith has seen and interpreted many radiologic exams performed on COVID-19 patients at varying stages of the disease.

#### Intro

One of the difficult parts of making sense of the COVID pandemic (caused by the SARS-CoV-2 virus) is sorting through all the myriad data coming at us from every direction.  In this tutorial, I will show you a fun way of manipulating some of these data to build your own dashboard to view United States COVID-19 statistics.  Afterward, you will hopefully be able to enhance your dashboard(s) to make unique visualizations.

This project uses [Streamlit](https://www.streamlit.io/), an exciting and relatively nascent open-source data visualization project.  It makes building beautiful data visualizations as easy as writing a Python script.  If you like what you see here, I suggest you read through their [documentation](https://docs.streamlit.io/en/stable/) and follow this project as it grows.

As stated above, there are many data sources for COVID-19.  We will be using [covidtracking.com](https://covidtracking.com/) as it has a simple [REST API](https://covidtracking.com/data/api).  However, there are many [other sources](https://data.world/resources/coronavirus/) available. I also recommend checking with your local municipality for public data sources.  Remember to be respectful and follow API guidelines.

Below is a screen shot of what the finished dashboard will look like, and [here is a link](https://examplecoviddashboard.herokuapp.com/) to a live demo.

#### Let's get started!

The recommended way to install Streamlit is via pip:

```
pip install streamlit
```

Open a new Python script (I called mine `covid_dashboard.py`), and begin by importing some libraries:

```python
import streamlit as st
import matplotlib.pyplot as plt
import pandas as pd
from datetime import datetime, timedelta
```

Streamlit does not have its own graphing functionality.  Instead, we will use [Matplotlib's](https://matplotlib.org/) pyplot to make our plots.  We need [pandas](https://pandas.pydata.org/) to manipulate the data, and we will also be using Python's built-in datetime library.

Next, we need to define a function to retrieve data from the API.

```python
def fetch_data():
    df = pd.read_json('https://covidtracking.com/api/v1/us/daily.json')
    df['date'] = pd.to_datetime(df['date'], format="%Y%m%d")
    df.set_index('date', inplace=True)
    df.sort_index(ascending=True, inplace=True)
    return df
```

The API output is in JSON format which we can read directly into a pandas DataFrame.  We now convert the 'date' column to datetime objects and reindex the DataFrame with these.  Finally, we sort the DataFrame by these dates.

As the user interacts with our dashboard, the script is frequently re-run.  However, we don't want to poll the API every time the user changes how he/she wants to view the same data.  Streamlit simplifies this by having a<EMAIL_ADDRESS>decorator that we can place ahead of any API call.  This way, the API is only called once despite running the `fetch_data()` function multiple times.  (This is important not to overrun the API endpoint with unnecessary calls for the exact same data over and over again.)

Our decorated function and function call should look like this:

```python
@st.cache
def fetch_data():
    df = pd.read_json('https://covidtracking.com/api/v1/us/daily.json')
    df['date'] = pd.to_datetime(df['date'], format="%Y%m%d")
    df.set_index('date', inplace=True)
    df.sort_index(ascending=True, inplace=True)
    return df

df = fetch_data()
```

Again, the `fetch_data()` only triggers an API call once; from then on, the data are cached.

Next, we construct a dictionary of data descriptors and their corresponding columns in the DataFrame we just constructed from the API.

```python
options = {"Cumulative Positive Results": 'positive',
    "Daily Positive Tests": 'positiveIncrease',
    "Cumulative Deaths": 'death',
    "Daily Deaths": 'deathIncrease',
    "Current Hospitalizations": 'hospitalizedCurrently',
    "Daily Hospitalizations": 'hospitalizedIncrease',
    "Cumulative Hospitalizations": 'hospitalizedCumulative',
    "Current ICU Patients": 'inIcuCurrently',
    "Cumulative ICU Patients": 'inIcuCumulative',
    "Current Ventilator Patients": 'onVentilatorCurrently',
    "Cumulative Ventilator Patients": 'onVentilatorCumulative',
    "Recovered Patients": 'recovered',
    "Daily Tests Performed": 'totalTestResultsIncrease',
    "Cumulative Tests Performed": 'totalTestResults'}
```

Now that we have collected our data, we can start the fun part: making our dashboard!  Let's give it a title:

```python
st.title('COVID-19 Dashboard: US Data')
```

And, it is good practice to reference your data source:

```python
st.subheader('Source: https://covidtracking.com')
```

Streamlit features a collapsable sidebar where you can put options menus and other things you don't want cluttering your main window.  Most Streamlit components can be put in the sidebar by calling them as methods on the `st.sidebar` object.  Let's add some date pickers for the start and end dates of our visualization.  (I'll set an arbitrary initial start date of 1-Mar-2020 and an initial end date matching the latest date in the DataFrame.)

```python
start_date = st.sidebar.date_input("Start Date", value=datetime(2020,3,1))
end_date = st.sidebar.date_input("End Date", value=df.index.max())
```

We now need to have the user pick which visualizations they want to see.  Only seeing a single category or data is boring, so we should use a multi-select.

```python
charts = st.sidebar.multiselect("Select individual charts to display:",
                options=list(options.keys()),
                default=list(options.keys())[:1])
```

The first parameter is the caption, the options are the keys of our `options` dictionary defined above, and the default is the first of those options.  This returns a list of the chosen options which we store in `charts`.

In our main window, we now loop through the `charts` list and plot each one on a single axis.

```python
for chart in charts:
    df[options[chart]].loc[start_date : end_date + timedelta(days=1)].plot(label=chart, figsize=(8,6))
    plt.xlabel('Date')
    plt.legend(loc="upper left")
```

The first line in the loop selects the column in the DataFrame corresponding to the chosen option, filters out the dates chosen, and uses the pandas plot function to plot the data from that column.  The other lines are for formatting the axis; you can customize these to change the look of your charts.

Once all the plots are created, the `pyplot` object still resides in memory, we have to tell Streamlit to show it by calling:

```python
st.pyplot()
```

And that's it!

#### Entire script

```python
import streamlit as st
import matplotlib.pyplot as plt
import pandas as pd
from datetime import datetime, timedelta

@st.cache
def fetch_data():
    df = pd.read_json('https://covidtracking.com/api/v1/us/daily.json')
    df['date'] = pd.to_datetime(df['date'], format="%Y%m%d")
    df.set_index('date', inplace=True)
    df.sort_index(ascending=True, inplace=True)
    return df

df = fetch_data()

options = {"Cumulative Positive Results": 'positive',
    "Daily Positive Tests": 'positiveIncrease',
    "Cumulative Deaths": 'death',
    "Daily Deaths": 'deathIncrease',
    "Current Hospitalizations": 'hospitalizedCurrently',
    "Daily Hospitalizations": 'hospitalizedIncrease',
    "Cumulative Hospitalizations": 'hospitalizedCumulative',
    "Current ICU Patients": 'inIcuCurrently',
    "Cumulative ICU Patients": 'inIcuCumulative',
    "Current Ventilator Patients": 'onVentilatorCurrently',
    "Cumulative Ventilator Patients": 'onVentilatorCumulative',
    "Recovered Patients": 'recovered',
    "Daily Tests Performed": 'totalTestResultsIncrease',
    "Cumulative Tests Performed": 'totalTestResults'}

## Build page
st.title('COVID-19 Dashboard: US Data')
st.subheader('Source: https://covidtracking.com')

start_date = st.sidebar.date_input("Start Date", value=datetime(2020,3,1))
end_date = st.sidebar.date_input("End Date", value=df.index.max())

charts = st.sidebar.multiselect("Select individual charts to display:",
                options=list(options.keys()),
                default=list(options.keys())[0:1])

for chart in charts:
    df[options[chart]].loc[start_date : end_date + timedelta(days=1)].plot(label=chart, figsize=(8,6))
    plt.xlabel('Date')
    plt.legend(loc="upper left")
st.pyplot()
```

#### Launching your dashboard

Once your script is saved, you can view your dashboard by running:

```bash
$ streamlit run covid_dashboard.py
```

A browser window should open to your new, fancy dashboard!  Try changing the dates and chart types in the sidebar.

![Dashboard](dashboard.png)

This is just a starting point.  There is a lot you can do to make it more interactive and show data in different ways.

The source code is also available at [https://github.com/lancereinsmith/covid_dashboard](https://github.com/lancereinsmith/covid_dashboard).

#### Deploying your dashboard

If you would like others to be able to see your dashboard, deploy it to Heroku on a free tier!  The following is based on an [article by Gilbert Tanner](https://gilberttanner.com/blog/deploying-your-streamlit-dashboard-with-heroku).  You will need [git](https://git-scm.com/), a [Heroku](https://www.heroku.com) account and the [Heroku CLI](https://devcenter.heroku.com/articles/heroku-cli) for this.

Clone my repository from GitHub.

```bash
$ git clone https://github.com/lancereinsmith/covid_dashboard.git

$ cd covid_dashboard
```
Replace the `covid_dashboard.py` script with yours.  (You must rename your file to 'covid_dashboard.py' or edit the `Procfile` with the name of your script.)

Next, login to Heroku with your credentials if you have not already done so.

```bash
$ heroku login
```

Create a Heroku app.  This will automatically register a remote git repository called "heroku."

```bash
$ heroku create
```

Push your code to Heroku.  The `Procfile` and `setup.sh` script will do the necessary steps to deploy your site.

```bash
$ git push heroku master
```

When Heroku is finished processing your file, open your site from the command line.

```
$ heroku open
```

If there is a problem, make sure your dyno is scaled:

```bash
heroku ps:scale web=1
```

You now have a hosted dashboard!  Check out the example: [https://examplecoviddashboard.herokuapp.com/](https://examplecoviddashboard.herokuapp.com/). (Because free-tier dynos go to sleep when not used, it may take a while for a site to launch.)

But, you don't have to stop there.  Here are some other ideas:

* Source data from different [states](https://covidtracking.com/api/v1/states/daily.json) and chart comparisons between them.
* Try calculating functions on your data, such as moving averages ([hint](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rolling.html)), to make the plots more interesting.
* Try different chart types using [matplotlib](https://matplotlib.org/gallery.html) and [seaborn](https://seaborn.pydata.org/examples/index.html).
* Allow different user input to customize the views.

Stay safe and have fun!


text:
---
layout: default
---

# 1995-10-16 - Re: My chat with Goeff Greiveldinger

## Header Data

From: Black Unicorn<EMAIL_ADDRESS>To<EMAIL_ADDRESS>Message Hash: 8300a222dd8451d109fbd27caff6d731f87e7de857fe0f4b00cc121e64f8bc98

Message ID<EMAIL_ADDRESS>Reply To<EMAIL_ADDRESS>UTC Datetime: 1995-10-16 02:16:24 UTC

Raw Date: Sun, 15 Oct 95 19:16:24 PDT

## Raw message

```
{% raw  %}From: Black Unicorn<EMAIL_ADDRESS>Date: Sun, 15 Oct 95 19:16:24 PDT
To<EMAIL_ADDRESS>Subject: Re: My chat with Goeff Greiveldinger
In-Reply-To<EMAIL_ADDRESS>Message-ID<EMAIL_ADDRESS>MIME-Version: 1.0
Content-Type: text/plain

On Sun, 15 Oct 1995<EMAIL_ADDRESS>wrote:

> On Sun, 15 Oct 1995, Black Unicorn wrote:
>
> > Effectively the potential for misuse is increased by virtue of the
> > increased numbers of officals (commercial and public) who have access to
> > the material.
>
> Does he mean mandatory commercial key escrow (as in clipper keys held
> by credit agencies?) Or something totally voluntary but standardized
> by the gov?

The problem exists in both these examples.

>
> Of course it all depends on exactly why they really want the escrow anyway.
> If people will encrypt a second time with tomorrow's pgp, why should anyone
> care?

When you see a glaring hole in argument for a government program, you
should smell the stench of fish in the air.  That is the section of the
puzzle that is being hidden until a politically "ripe" time to stick it
in place.  Here that piece is, obviously, banning tomorrow's pgp.

>
> All you'd single encrypt for would be your income tax and the
> financial records you're already required by law to keep (I'm sure I've
> misunderstood this. Can't be so useless.). I know that's not a particularily
> diplomatic carry-over from the debated-to-death clipper thing, but really,
> except as PR, why DO they still take this seriously? (unless you want to
> be paranoid about a ban, hmm, nevermind, debated-to-death)

I'm not so sure it's paranoid.  You have trial baloons floating all
over.  Freeh is a prime example, and no one is screaming loudly enough to
shoot down his blump.  That's a big'ole green light for regulators.>

---
"In fact, had Bancroft not existed,       potestas scientiae in usu est
Franklin might have had to invent him."    in nihilum nil posse reverti
00B9289C28DC0E55  E16D5378B81E1C96 - Finger for Current Key Information

{% endraw %}
```

## Thread

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

+ Return to "[Black Unicorn <unicorn@polaris.mindport.net>](/authors/black_unicorn_unicorn_at_polaris_mindport_net_)"
+ Return to "[Duncan Frissell <frissell@panix.com>](/authors/duncan_frissell_frissell_at_panix_com_)"
+ Return to "[Jim Gillogly <jim@acm.org>](/authors/jim_gillogly_jim_at_acm_org_)"
+ Return to "[Michael Froomkin <froomkin@law.miami.edu>](/authors/michael_froomkin_froomkin_at_law_miami_edu_)"
+ Return to "[s1018954@aix2.uottawa.ca](/authors/s1018954_at_aix2_uottawa_ca)"

+ 1995-10-15 (Sun, 15 Oct 95 13:00:34 PDT) - [My chat with  Goeff Greiveldinger](/archive/1995/10/22f6a92a8337bc5ac5e81b56fa1516872b109db118e740cfe46fec47b6cea004) - _Michael Froomkin<EMAIL_ADDRESS>  + 1995-10-15 (Sun, 15 Oct 95 13:27:27 PDT) - [Re: My chat with Goeff Greiveldinger](/archive/1995/10/13fd7e361f024d30bd553d6d376d0ea862d8834e197b0c3a29341022525453c6) - _Jim Gillogly<EMAIL_ADDRESS>    + 1995-10-15 (Sun, 15 Oct 95 14:27:18 PDT) - [Re: My chat with Goeff Greiveldinger](/archive/1995/10/7329014e20e770c8cd88ef6bf583b6f100aebafb40781b254373eb15fe1189cf) - _Black Unicorn<EMAIL_ADDRESS>      + 1995-10-15 (Sun, 15 Oct 95 14:49:41 PDT) - [Re: My chat with Goeff Greiveldinger](/archive/1995/10/924b3fdcb2d959731601606c7055f112b187ce864831ecda3a3bec6af368d552) - _Duncan Frissell<EMAIL_ADDRESS>      + 1995-10-15 (Sun, 15 Oct 95 16:10:05 PDT) - [Re: My chat with Goeff Greiveldinger](/archive/1995/10/2330e072faced7c3f6d1779e45b5da7bbe6cfe760cfbc3443698760f41a3c1bb) -<EMAIL_ADDRESS>        + 1995-10-16 (Sun, 15 Oct 95 19:16:24 PDT) - Re: My chat with Goeff Greiveldinger - _Black Unicorn<EMAIL_ADDRESS>          + 1995-10-16 (Sun, 15 Oct 95 19:42:21 PDT) - [Re: My chat with Goeff Greiveldinger](/archive/1995/10/6045ff976ea266a1db92f7e7f2700b5b9524a1a1a52ae09805c8bf346415cf67) - _Michael Froomkin<EMAIL_ADDRESS>          + 1995-10-16 (Sun, 15 Oct 95 22:06:02 PDT) - [alt.paranoia.pgp.ban: long rerun (was Re: My chat with...)](/archive/1995/10/7ca756a71e95bfd60b12d24278cd7b97051409ba3ee3f234fb6774989c82528d) -<EMAIL_ADDRESS>


text:
---
layout: post
title: "[LeetCode 143] Reorder List"
comments: true
category: Leetcode

---

### Question
[link](https://oj.leetcode.com/problems/reorder-list/)

Given a singly linked list L: L0→L1→…→Ln-1→Ln,

reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…

You must do this in-place without altering the nodes' values.

For example,

Given {1,2,3,4}, reorder it to {1,4,2,3}.

### Stats

		Adjusted Difficulty
		4

		Time to use
		--------

Ratings/Color = 1(white) 2(lime) 3(yellow) 4/5(red)

### Analysis

__This is a difficult question to think__.

I first solved it with an stack which stores the second half nodes. It works. However, IT IS NOT A IN-PLACE SOLUTION, thus it's wrong.

Eventually I did not solve it.

__There is only one standard solution from the Internet__. [This blog](http://www.programcreek.com/2013/12/in-place-reorder-a-singly-linked-list-in-java/) explains it.

> 1. Break list in the middle to two lists (use fast & slow pointers)
> 2. Reverse the order of the second list
> 3. Merge two list back together

Simple, right? __Because of the nature of linked list, a lot of things can be done in-place__, so we need not use any other data strucutres.

### Solution

The code is a bit lengthy and difficult to write. It took me a while, but passed in 1 go.

### Code

__First, code written by me__

    public void reorderList(ListNode head) {
        if (head == null || head.next == null) {
			return;
		}
		ListNode slow = head, fast = head;
		while (fast != null) {
			if (fast.next != null && fast.next.next != null) {
				fast = fast.next.next;
				slow = slow.next;
			}
			else {
				fast = null;
			}
		}
		// if length = 2, slow point to 1st
		// if length = 3, slow point to 2nd
		// if length = 4, slow point to 2nd
		ListNode secondHalf = slow.next;
		slow.next = null;
		// now reverse secondHalf
		ListNode p = secondHalf;
		while (p.next != null) {
			ListNode tail = p.next.next;
			p.next.next = secondHalf;
			secondHalf = p.next;
			p.next = tail;
		}
		// now merge 2 list: head and secondHalf
		ListNode a = head, b = secondHalf;
		while (a != null && b != null) {
			ListNode temp1 = a.next;
			ListNode temp2 = b.next;
			a.next = b;
			b.next = temp1;
			a = temp1;
			b = temp2;
		}
    }

__Second, code written by [someone](https://oj.leetcode.com/discuss/236/does-this-problem-solution-time-complexity-space-comlexity)__

    public void reorderList(ListNode head) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if (head == null || head.next == null) return;
        ListNode fast = head;
        ListNode slow = head;
        while(fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        ListNode reverseHead = slow.next;           // find the second half of list
        slow.next = null;                           // make first half end point to null
        reverseHead = reverse(reverseHead);         // reverse second half
        ListNode cur = head;
        while(reverseHead != null) {                // link together
            ListNode tmp = reverseHead.next;
            reverseHead.next = cur.next;
            cur.next = reverseHead;
            cur = cur.next.next;
            reverseHead = tmp;
        }
    }
    private ListNode reverse(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode prev = new ListNode(0);
        prev.next = head;
        head = prev;
        ListNode cur = prev.next;
        while(cur.next != null) {
            ListNode tmp = cur.next;
            cur.next = tmp.next;
            tmp.next = prev.next;
            prev.next = tmp;
        }
        return prev.next;
    }

branch_name: refs/heads/source


text:
# Differential Mesh 3d

![img](/img/img.png?raw=true "img")

Differential Mesh is an extension of the Hyphae
(https://github.com/inconvergent/hyphae) algorithm. I started working on it
with the intention of mimicking the growth of (certain types of) lichen.

This three dimensional extension is something else entirely ...

## Prerequisites

In order for this code to run you must first download and install:

*    `zonemap3d`: https://github.com/inconvergent/zonemap-3d
*    `iutils`: https://github.com/inconvergent/iutils
*    `fn`: https://github.com/inconvergent/fn-python3 (only used to generate file
       names, you can skip this by changing file names in `main.py`)

## Other Dependencies

The code also depends on:

*    `numpy`
*    `scipy`
*    `cython`
*    `python-cairo` (do not install with pip, this generally does not work)

## Running it on Linux (Ubuntu)

To install the libraries locally, run `install`. I have only tested this
code in Ubuntu 14.04 LTS, but my guess is that it should work on most other
platforms as well.

Run using the `main-run` script (asdf is a prefix for the generated files and
can be chosen freely):

    ./main-run asdf


text:
# Vue.js

## Creating a new project with the Vue CLI

Perhaps, the easiest way is to just install the vue-cli:

```bash
yarn global add @vue/cli
# or
npm install -g @vue/cli
```

and then create your project template right away:[^vue-create]

```bash
vue create hello-world
```

!!! warning
    You might find a lot of tutorials online using the `vue init webpack project_name` command instead. As far as the documentation is concerned, this is already a legacy (Vue CLI 2) approach, and I would not recommend using it for new projects. Instead, stick to the much easier Vue CLI >= 3 approach described above[^vue-init].

[^vue-create]: [Creating a Project | Vue.js Docs](https://cli.vuejs.org/guide/creating-a-project.html#vue-create)
[^vue-init]: [Pulling 2.x Templates (Legacy) | Vue.js Docs](https://cli.vuejs.org/guide/creating-a-project.html#pulling-2-x-templates-legacy)

## Working with TypeScript

When working with TypeScript, make sure that your components also extend from `Vue`. Othewise, you can get a pretty nasty message by the TS compiler that `this.$store` or anything else that you might expect to be accessible inside your Vue component, is actually `undefined`.

So insted of this (vanilla JS):

```html
<script>
  export default {
    // code goes here...
  };
</script>
```

use this (TypeScript):

```typescript
<script lang="ts">
  import Vue from 'vue' export default Vue.extend(
  {
    // code goes here
  })
</script>
```

repository: preslavrachev/devnotes

repo_name: preslavrachev/devnotes


text:
The oHealthCxt-Browser is a complementary part of an extension to connect Widgets with Cosmos
to display historical data over mashups.
It is important to make clear that this implementation is an extension of an Orion Context browser already implemented at the time this extension was built. The reference resource is available at [Orion Context
Broker](http://catalogue.fiware.org/enablers/publishsubscribe-context-broker-orion-context-broker).

> Moreover is worth mentioning that this is a working progress extension, that will be updated on GitHub
> at [Bifrost](https://github.com/netzahdzc/Bifrost)

repository: netzahdzc/Bifrost

repo_name: netzahdzc/Bifrost