text:
---
title: '`export default thing` is different to `export { thing as default }`'
date: 2021-07-03 01:00:00
summary: Here's how they differ, and when it matters…
meta: Here's how they differ, and when it matters…
image: 'asset-url:./img.png'
---

[Dominic Elm](https://twitter.com/elmd_) DM'd me on Twitter to ask me questions about circular dependencies, and, well, I didn't know the answer. After some testing, discussion, and _\*ahem\*_ chatting to the V8 team, we figured it out, but I learned something new about JavaScript along the way.

I'm going to leave the circular dependency stuff to the end of the article, as it isn't totally related. First up:

# Imports are references, not values

Here's an import:

```js
import { thing } from './module.js';
```

In the above example, `thing` is the same as `thing` in `./module.js`. I know that maybe sounds obvious, but what about:

```js
const module = await import('./module.js');
const { thing: destructuredThing } = await import('./module.js');
```

In this case `module.thing` is the same as `thing` in `./module.js`, whereas `destructuredThing` is a new identifier that's assigned the value of `thing` in `./module.js`, and that behaves differently.

Let's say this is `./module.js`:

```js
// module.js
export let thing = 'initial';

setTimeout(() => {
  thing = 'changed';
}, 500);
```

And this is `./main.js`:

```js
// main.js
import { thing as importedThing } from './module.js';
const module = await import('./module.js');
let { thing } = await import('./module.js');

setTimeout(() => {
  console.log(importedThing); // "changed"
  console.log(module.thing); // "changed"
  console.log(thing); // "initial"
}, 1000);
```

Imports are 'live bindings' or what some other languages call a 'reference'. This means when a different value is assigned to `thing` in `module.js`, that change is reflected in the import in `main.js`. The destructured import doesn't pick up the change because destructuring assigns the _current value_ (rather than a live reference) to a new identifier.

The destructuring behaviour isn't unique to imports:

```js
const obj = { foo: 'bar' };

// This is shorthand for:
// let foo = obj.foo;
let { foo } = obj;

obj.foo = 'hello';
console.log(foo); // Still "bar"
```

The above feels natural in my opinion. The potential gotcha here is that named static imports (`import { thing } …`) kinda look like destructuring, but they don't behave like destructuring.

Ok, so here's where we're at:

```js
// These give you a live reference to the exported thing(s):
import { thing } from './module.js';
import { thing as otherName } from './module.js';
import * as module from './module.js';
const module = await import('./module.js');
// This assigns the current value of the export to a new identifier:
let { thing } = await import('./module.js');
```

# But 'export default' works differently

Here's `./module.js`:

```js
// module.js
let thing = 'initial';

export { thing };
export default thing;

setTimeout(() => {
  thing = 'changed';
}, 500);
```

And `./main.js`:

```js
// main.js
import { thing, default as defaultThing } from './module.js';
import anotherDefaultThing from './module.js';

setTimeout(() => {
  console.log(thing); // "changed"
  console.log(defaultThing); // "initial"
  console.log(anotherDefaultThing); // "initial"
}, 1000);
```

…and I wasn't expecting those to be `"initial"`!

## But… why?

You can `export default` a value directly:

```js
export default 'hello!';
```

…which is something you _can't_ do with named exports:

```js
// This doesn't work:
export { 'hello!' as thing };
```

To make `export default 'hello!'` work, the spec gives `export default thing` different semantics to `export thing`. The bit after `export default` is treated like an expression, which allows for things like `export default 'hello!'` and `export default 1 + 2`. This also 'works' for `export default thing`, but since `thing` is treated as an expression it causes `thing` to be passed by value. It's as if it's assigned to a hidden variable before it's exported, and as such, when `thing` is assigned a new value in the `setTimeout`, that change isn't reflected in the hidden variable that's actually exported.

So:

```js
// These give you a live reference to the exported thing(s):
import { thing } from './module.js';
import { thing as otherName } from './module.js';
import * as module from './module.js';
const module = await import('./module.js');
// This assigns the current value of the export to a new identifier:
let { thing } = await import('./module.js');

// These export a live reference:
export { thing };
export { thing as otherName };
// These export the current value:
export default thing;
export default 'hello!';
```

# And 'export { thing as default }' is different

Since you can't use `export {}` to export values directly, it always passes a live reference. So:

```js
// module.js
let thing = 'initial';

export { thing, thing as default };

setTimeout(() => {
  thing = 'changed';
}, 500);
```

And the same `./main.js` as before:

```js
// main.js
import { thing, default as defaultThing } from './module.js';
import anotherDefaultThing from './module.js';

setTimeout(() => {
  console.log(thing); // "changed"
  console.log(defaultThing); // "changed"
  console.log(anotherDefaultThing); // "changed"
}, 1000);
```

Unlike `export default thing`, `export { thing as default }` exports `thing` as a live reference. So:

```js
// These give you a live reference to the exported thing(s):
import { thing } from './module.js';
import { thing as otherName } from './module.js';
import * as module from './module.js';
const module = await import('./module.js');
// This assigns the current value of the export to a new identifier:
let { thing } = await import('./module.js');

// These export a live reference:
export { thing };
export { thing as otherName };
export { thing as default };
// These export the current value:
export default thing;
export default 'hello!';
```

Fun eh? Oh, we're not done yet…

# 'export default function' is another special case

I said that the bit after `export default` is treated like an expression, but there are exceptions to that rule. Taking:

```js
// module.js
export default function thing() {}

setTimeout(() => {
  thing = 'changed';
}, 500);
```

And:

```js
// main.js
import thing from './module.js';

setTimeout(() => {
  console.log(thing); // "changed"
}, 1000);
```

It logs `"changed"`, because `export default function` is given its own special semantics; the function _is_ passed by reference in this case. If we change `module.js` to:

```js
// module.js
function thing() {}

export default thing;

setTimeout(() => {
  thing = 'changed';
}, 500);
```

…it no longer matches the special case, so it logs `ƒ thing() {}`, as it's passed by value again.

## But… why?

It isn't just `export default function` – `export default class` is special-cased in the same way. It's to do with how these statements change behaviour when they're expressions:

```js
function someFunction() {}
class SomeClass {}

console.log(typeof someFunction); // "function"
console.log(typeof SomeClass); // "function"
```

But if we make them expressions:

```js
(function someFunction() {});
(class SomeClass {});

console.log(typeof someFunction); // "undefined"
console.log(typeof SomeClass); // "undefined"
```

`function` and `class` statements create an identifier in the scope/block, whereas `function` and `class` _expressions_ do not (although their names can be used internal to the function/class).

So:

```js
export default function someFunction() {}
console.log(typeof someFunction); // "function"
```

If `export default function` wasn't special-cased, then the function would be treated as an expression, and the log would be `"undefined"`. Special-casing functions also helps with circular dependencies, but I'll get onto that shortly.

To sum up:

```js
// These give you a live reference to the exported thing(s):
import { thing } from './module.js';
import { thing as otherName } from './module.js';
import * as module from './module.js';
const module = await import('./module.js');
// This assigns the current value of the export to a new identifier:
let { thing } = await import('./module.js');

// These export a live reference:
export { thing };
export { thing as otherName };
export { thing as default };
export default function thing() {}
// These export the current value:
export default thing;
export default 'hello!';
```

This kinda makes `export default identifier` the odd one out. I get that `export default 'hello!'` needs to be passed by value, but since there's a special case that makes `export default function` passed by reference, it feels like there should be a special case for `export default identifier` too. I guess it's too late to change it now.

I had a chat with [Dave Herman](https://twitter.com/littlecalculist) about this, who was involved in the design of JavaScript modules. He said that some earlier designs of default exports were in the form `export default = thing`, which would have made it more obvious that `thing` is treated as an expression. I agree!

# What about circular dependencies?

This came to light when Dominic messaged me about circular dependencies. First we need to talk about 'hoisting':

## Hoisting

You might have encountered the age-old weird thing JavaScript does to functions:

```js
thisWorks();

function thisWorks() {
  console.log('yep, it does');
}
```

Function definitions are essentially moved to the top of the file. That only really happens with plain function declarations:

```js
// Doesn't work
assignedFunction();
// Doesn't work either
new SomeClass();

const assignedFunction = function () {
  console.log('nope');
};
class SomeClass {}
```

If you try to access a `let`/`const`/`class` identifier before it's instantiated, it throws an error.

## var is different

…because of course it is.

```js
var foo = 'bar';

function test() {
  console.log(foo);
  var foo = 'hello';
}

test();
```

The above logs `undefined`, because the declaration of `var foo` in the function is hoisted to the start of the function, but the assignment of `'hello'` is left where it is. This was seen as a bit of a gotcha, which is why `let`/`const`/`class` throw an error in similar cases.

## What about circular dependencies?

Circular dependencies are allowed in JavaScript, but they're messy and should be avoided. For example, with:

```js
// main.js
import { foo } from './module.js';

foo();

export function hello() {
  console.log('hello');
}
```

And:

```js
// module.js
import { hello } from './main.js';

hello();

export function foo() {
  console.log('foo');
}
```

This works! It logs `"hello"` then `"foo"`. However, this only works due to hoisting, which lifts both function definitions above both of their calls. If we change the code to:

```js
// main.js
import { foo } from './module.js';

foo();

export const hello = () => console.log('hello');
```

And:

```js
// module.js
import { hello } from './main.js';

hello();

export const foo = () => console.log('foo');
```

…it fails. `module.js` executes first, and as a result it tries to access `hello` before it's instantiated, and throws an error.

Let's get `export default` involved with:

```js
// main.js
import foo from './module.js';

foo();

function hello() {
  console.log('hello');
}

export default hello;
```

And:

```js
// module.js
import hello from './main.js';

hello();

function foo() {
  console.log('foo');
}

export default foo;
```

This is the example Dominic gave me. The above fails, because `hello` in `module.js` points to the hidden variable exported by `main.js`, and it's accessed before it's initialized.

If `main.js` is changed to use `export { hello as default }`, it doesn't fail, because it's passing the function by reference and gets hoisted. If `main.js` is changed to use `export default function hello()`, again it doesn't fail, but this time it's because it hits that super-magic-special-case of `export default function`.

I suspect this is another reason `export default function` was special-cased; to make hoisting work as expected. But again, it feels like `export default identifier` should have been special-cased in the same way for consistency.

So there you go! I learned something new. But, as with my last few posts, please don't add this to your interview questions, just avoid circular dependencies 😀.

<small>Huge thanks to [Toon Verwaest](https://twitter.com/tverwaes), [Marja Hölttä](https://twitter.com/marjakh), and [Mathias Bynens](https://twitter.com/mathias) from the V8 team for making sure I'm using the correct terminology throughout this post, [Dave Herman](https://twitter.com/littlecalculist) and [Daniel Ehrenberg](https://twitter.com/littledan) for giving me some of the history around this, proof-readers [Surma](https://twitter.com/DasSurma), [Adam Argyle](https://twitter.com/argyleink), [Ada Rose Cannon](https://twitter.com/AdaRoseCannon), [Remy Sharp](https://twitter.com/rem), [Lea Verou](https://twitter.com/LeaVerou) (heh, I got a lot of folks to read this, I wanted it to make as much sense as possible) and of course thanks to [Dominic Elm](https://twitter.com/elmd_) for triggering this whole adventure!</small>


text:
# Ansible Managed Workspace

Workspace configuration using the ansible role: tnaglo.unix_home_setup

## Dependencies

- ansible (if used to install on localhost)

## Usage

To install the user and his configure his environment on the local machine you first have to install the requirements:

@todo change the functionality and readme accordingly (add parametrized install script).

`ansible-galaxy install -r roles/requirements.yml`

If the user does not exist yet, run:

`ansible-playbook -i "localhost," -c local create-user.yml -b -K`

Next run:

`ansible-playbook -i "localhost," -c local setup-home.yml`

license: MIT

repository: tnaglo/ansible-managed-workspace

branch_name: refs/heads/master

extension: md

license_type: permissive

repo_name: tnaglo/ansible-managed-workspace


text:
# silverstripe-element-quotation
Adds a simple quotation / testimonial element block

[![License](https://img.shields.io/badge/License-BSD%203--Clause-blue.svg)](LICENSE.md)

# Requirements
* Silverstripe 4.x
* Silverstripe Elemental

# Installation
* Install the code with `composer require dorsetdigital/silverstripe-element-quotation`
* Run a `dev/build?flush` to update your project

# Usage
Once installed, the quotation will be selectable as an Elemental block.

By default, the module doesn't add any styling, it expects you to do this in your own CSS file


text:
# Iris-data-classification
## Accuracy: 95%
## Algorithm: K-Nearest Neighbours
<br>
Classification predictions of Iris data spread across three species. Setosa, Viriginica, Versicolor

![Iris image](images/iris.jfif)

This repository contains a detailed preprocessing of iris dataset. The data is intentionally modified to showcase some of the preprocessing steps. such as null treatment etc.

The famous K nearest neighbour algorithm is used for classification process. We have three classes of flowers.

- Setosa
- Virginica
- Versicolor

Feature Scaling: Normalization using Z-Score/ Standardization

repository: subhambiswajit/Iris-data-classification

branch_name: refs/heads/main

repo_name: subhambiswajit/Iris-data-classification


text:
# PS-PROFILE
A profile script for your Powershell shell terminal with helpful methods to start up your powershell profile.

## Prerequisites
Create a code signing cert (local)

```powershell
PS>New-SelfSignedCertificate -CertStoreLocation cert:\currentuser\my `
-Subject "CN=Dev Code Signing" `
-KeyAlgorithm RSA `
-KeyLength 2048 `
-Provider "Microsoft Enhanced RSA and AES Cryptographic Provider" `
-KeyExportPolicy Exportable `
-KeyUsage DigitalSignature `
-Type CodeSigningCert

# Export cert
PS>Export-Certificate -Cert @(Get-ChildItem Cert:\CurrentUser\My\[replace with cert id])[0] -FilePath
path\to\dev_code_signing.cer

# Add to TrustedPublisher
PS>Get-ChildItem -Path path\to\dev_code_signing.cer | Import-Certificate -CertStoreLocation Cert:\Current
User\TrustedPublisher\

# Add to Root
PS>Get-ChildItem -Path path\to\dev_code_signing.cer | Import-Certificate -CertStoreLocation Cert:\Current
User\Root\
```

## Create/modify profile:
From a command prompt, load the profile script into your favorite text/code editor. e.g. [visual studio code](https://code.visualstudio.com/)

```powershell
PS>code $profile
# Copy the contents of the [profile.ps1](./profile.ps1) file and paste it into your open editor.
# sign the script
PS>Set-AuthenticodeSignature ~\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1 @(Get-ChildItem Cert:\Curre
ntUser\My\[replace with cert id])[0]
```

Save the changes, close and reopen your powershell window. If you copied the file as is:
1. your prompt would have changed
2. added a new cmdlet `New-Powershell` or it's alias `nps`

repository: rabadiw/scripts

repo_name: rabadiw/scripts


text:
# Contributing

Pico welcomes contributions from everyone, whether it's bug fixes, new
features or typo fixes.

If you're unsure about anything feel free to
[email<EMAIL_ADDRESS>with any questions, I'll be happy
to assist you.

# Testing

There are two ways to test Pico's output, one being the provided visual
testing suite and two a web extension that you can test Pico on any real
world website (as long as it doesn't block `eval` (which is most of them so
it's not much of an issue)).

## Development server

To run any of the tests you need to use the development server:

```bash
$ npm run dev
```

Main bundle will be served at `http://localhost:23231/index.js` and
automatically updated whether you change any of the source code.

## Web extension

> Run Pico on any website of your choice.

1. Ensure that you have the development server running

2. Open the web extension (located in `web-ext/` in the root of this
   repository) in the browser of your choice - note that it has only been
   tested with Firefox, so YMMV. If you have Firefox Nightly installed, for
   convenience run `npm run dev:ext` to open the web extension in that
   browser - you will have the development browser separate and clean from
   your day to day one.

3. With the opened browser, browse onto a website you want to test.
   You should see a browser action in your address bar:

   ![Browser action in address bar](https://github.com/gripeless/pico/blob/master/media/browser-action-address-bar.png?raw=true)

   Click on the green puzzle icon to take a screenshot, a new tab should
   open with the output contents in SVG form.

## Testing REPL

> Separate cases to test out individual parts of the renderer.

The test suite spawns a real browser (via
[Playwright](https://github.com/microsoft/playwright)) and lets you compare
the output screenshot from Pico to the "real" viewport.

It is designed with really quick iteration in mind and to allow you to
scaffold out potential problems with the library quickly, whether it's
rendering related, CORS related, or anything browser specific related.

The suite is currently only provided in an interactive form, which means
that you have to use your eyes to judge whether the result is suiting or
not.

### Running the REPL

1. Ensure that you have the development server running

2. Add the following to your hosts file:

	```
	<IP_ADDRESS> test.localhost
	<IP_ADDRESS> test2.localhost
	<IP_ADDRESS> test3.localhost
	<IP_ADDRESS> test4.localhost
	<IP_ADDRESS> test5.localhost
	```

	This lets you test cross-origin related issues without having to do any
	complicated local DNS setup.

3. Start the interactive test REPL:

```bash
$ npm run test:interactive
```

An empty browser window should open (in the background if you're on macOS),
this will show the output of any test you run through the console.

### REPL Commands

#### `open`
Opens the browser output again, useful if you happened to close the original output.

#### `run (case name)`
Runs a test with the specified name.

#### `watch (case name)`
Same as `run`, but will update if either the `source/` directory updates or the case.

Press <kbd>q</kbd> to exit the watcher.

#### `all`
Runs all available tests.

### Adding a new test case

The easiest way to add a new case is to start with an existing one and
modify it to suit your needs. For most cases you won't need any special
browser flags or extra servers - I usually just copy `test/cases/hello` into
a new directory in `test/cases`.

1. Create the test's directory in `test/cases`.
For consistency, the name of the test case should be kebab-case.

2. Add your test to `test/cases/index.ts`

After that's done restart your test REPL and you'll be able to run your test
case.

repository: kicker-matchday/pico

gha_language: TypeScript

gha_license_id: MIT

repo_name: kicker-matchday/pico


text:
# LuBox
LuBox is a Lua inspired scripting language for embedding in .NET applications.

### The main characteristics of LuBox:

1. Lightweigth API which is easy to embed.
2. Sandboxed with restricted access to IO and reflection.
3. Based on the Dynamic Language Runtime (DLR).

### Examples ###
**Introduction**
```csharp
var scriptEngine = new LuScriptEngine();
scriptEngine.Globals.hello = "Hello";
scriptEngine.Execute("hello = hello:ToUpper()");
Console.WriteLine(scriptEngine.Globals.hello); // Output: HELLO
```

**Events**
```csharp
public class Foo
{
    public event Action<string> BarFired;

    public void FireBar()
    {
        BarFired("BAR!");
    }
}
```
```csharp
var scriptEngine = new LuScriptEngine();
Foo foo = new Foo();
scriptEngine.Globals.foo = foo;
scriptEngine.Globals.console = Console.Out;
scriptEngine.Execute(
  @"
  function handleBar(text)
      console:WriteLine(text)
  end
  foo.BarFired:Add(handleBar)");
foo.FireBar(); // Output: HELLO
```

repository: ErikssonMattias/LuBox

repo_name: ErikssonMattias/LuBox


text:
---
id: 233
title: Blackberry Desktop crashes when reading Outlook calendar
date: 2008-04-17T10:14:00-04:00
author: Ron
layout: post
guid: http://blog-autadv.rhcloud.com/?p=233
permalink: /2008/04/blackberry-desktop-crashes-when-reading-outlook-calendar.html
blogger_blog:
  - www.automationadventures.com
blogger_author:
  - Ronald Bruintjes
blogger_permalink:
  - /2008/04/blackberry-desktop-crashes-when-reading.html
blogger_internal:
  - /feeds/8074648837853537542/posts/default/298489913653539384
categories:
  - blackberry
  - crash
  - desktop
  - Productivity
  - synchronization
  - Telecom
  - vista
  - Windows
---
For the past two days, my Blackberry Desktop software has crashed when it was trying to read the Outlook calendar entries. Rebooting didn't help, and I really didn't want to reinstall software and go through the pain of resynchronizing.

Luckily, the solutions was relatively simple. After Googling around for a bit, I came across [this post](http://www.blackberryforums.com/rim-software/36729-ms-outlook-synchronization-error.html#post885771) on [BlackberryForums.com](http://www.blackberryforums.com/), describing an easy and effective way to make my Blackberry's calendar match my Outlook calendar (again).

The KB entry referenced (KB 11703 on the [BlackBerry Technical Solution Center](http://www.blackberry.com/btsc)) describes the procedure for Windows 2000/XP. The procedure is similar on Windows Vista, the only difference is that the Intellisync folder is located at _C:Users<user name>AppDataRoamingResearch In MotionBlackBerryIntellisync_. You don't even have to reconfigure the synchronization settings - after deleting the Intellisync directory, start the Desktop Manager and synchronize your Blackberry.

But I have to agree with the post directly below the solution: I wonder what got it messed up to begin with...


text:
- [Task](#task)
   - [Previous installations](#previous)
   - [Caffe](#caffe)
   - [PyTorch and Caffe2](#pytorch)
   - [NVIDIA DIGITS](#digits)
     - [Install Docker CE](#docker-ce)
     - [Install NVIDIA Container Runtime for Docker](#container)
     - [Install DIGITS with Docker](#digits-docker)
     - [Running DIGITS on Nvidia Docker](#run-digits)

---
### Task
   - Install additional software for neural networks.

There are many packages and modules to work with neural networks.
This manual will install and verify additional software.

---
### Previous installations

   1. [Prepare Python](../04_Python_installation.md)
   2. [Install software for virtual environments](../05_Virtual_environments.md)
   3. [Prepare GPU driver and CUDA](../08_Nvidia_driver_and_CUDA_install.md)
   4. [Install TensorFlow using `pip` or build it from source](09_TensorFlow_installation.md)

---
### Caffe

[Caffe](http://caffe.berkeleyvision.org/) is a deep learning framework
made with expression, speed, and modularity in mind. It is developed by
Berkeley AI Research (BAIR) and by community contributors.

[Ubuntu Installation](http://caffe.berkeleyvision.org/install_apt.html)
of pre-compiled Caffe

**Note**: the cuda version may break if your NVIDIA driver and CUDA toolkit
are not installed by APT.

```shell
# Caffe is a fast, open framework for Deep Learning
sudo apt install caffe-cuda
# Development files for Caffe (CUDA)
sudo apt install libcaffe-cuda-dev
# Library of Caffe, deep leanring framework (CUDA)
sudo apt install libcaffe-cuda1
# Python3 interface of Caffe (CUDA)
sudo apt install python3-caffe-cuda

# Verify. There is no Caffe interface for Python 2.7, only 3.x
python3 -c "import caffe; print(caffe.__version__);"
```

---
### PyTorch and Caffe2

[PyTorch](https://pytorch.org/) is an open-source machine learning library for Python,
based on Torch, used for applications such as natural language processing.
It is primarily developed by Facebook's artificial-intelligence research group,
and Uber's "Pyro" software for probabilistic programming is built on it.

[Torch](https://en.wikipedia.org/wiki/Torch_(machine_learning)) is an open-source
machine learning library, a scientific computing framework, and a script language
based on the Lua programming language. It provides a wide range of algorithms
for deep learning, and uses the scripting language LuaJIT, and an underlying
C implementation. As of 2018, Torch is no longer in active development.

[Caffe2](https://caffe2.ai/) is a new lightweight, modular, and scalable deep
learning framework. Built on the original [Caffe](http://caffe.berkeleyvision.org),
Caffe2 is designed with expression, speed, and modularity in mind,
allowing for a more flexible way to organize computation.

Install stable PyTorch on Linux using `pip` for Python 2.7 and CUDA 10.0:
![Stable PyTorch on Linux using `pip` for Python 2.7 and CUDA 10.0](../data/2018.12.21-pytorch-installation-python27.png)

Install stable PyTorch on Linux using `pip` for Python 3.6 and CUDA 10.0:
![Stable PyTorch on Linux using `pip` for Python 3.x and CUDA 10.0](../data/2018.12.21-pytorch-installation-python36.png)

```shell
sudo su
cd ~
umask 022

sudo pip install https://download.pytorch.org/whl/cu100/torch-1.0.0-cp27-cp27mu-linux_x86_64.whl
sudo pip install -U torchvision

# if the above command does not work, then you have python 2.7 UCS2, use this command
##pip install https://download.pytorch.org/whl/cu100/torch-1.0.0-cp27-cp27m-linux_x86_64.whl

sudo pip3 install https://download.pytorch.org/whl/cu100/torch-1.0.0-cp36-cp36m-linux_x86_64.whl
sudo pip3 install -U torchvision

# PyTorch Caffe (Caffe2 from Facebook) and plugins
sudo pip  install -U ptcaffe
sudo pip  install -U ptcaffe-plugins
sudo pip3 install -U ptcaffe
sudo pip3 install -U ptcaffe-plugins

# Prevent this error - ModuleNotFoundError: No module named 'past'
sudo pip  install -U future
sudo pip3 install -U future

exit  # exit from root

# Verify
python -c "import torch;                   \
    print(torch.cuda.is_available());      \
    print(torch.cuda.get_device_name(0));  \
    print(torch.cuda.device_count());"

python3 -c "import torch;                  \
    print(torch.cuda.is_available());      \
    print(torch.cuda.get_device_name(0));  \
    print(torch.cuda.device_count());"

# Verify Caffe2
python  -c "from caffe2.python import core" 2>/dev/null && echo "Success" || echo "Failure"
python3 -c "from caffe2.python import core" 2>/dev/null && echo "Success" || echo "Failure"
# Verify GPU. Should be >= 1.
python  -c "from caffe2.python import workspace; print(workspace.NumCudaDevices())"
python3 -c "from caffe2.python import workspace; print(workspace.NumCudaDevices())"
```

---
### NVIDIA DIGITS

[NVIDIA DIGITS](https://developer.nvidia.com/digits) or
Interactive Deep Learning GPU Training System is **not a framework**.
DIGITS is a wrapper for NVCaffe, Torch, and TensorFlow;
which provides a graphical web interface to those frameworks
rather than dealing with them directly on the command-line.

Useful links:
   * [Ubuntu Installation](https://github.com/NVIDIA/DIGITS/blob/digits-6.0/docs/UbuntuInstall.md)
   * [DIGITS Docker Installation](https://github.com/NVIDIA/DIGITS/blob/digits-6.0/docs/DockerInstall.md)
   * [NVIDIA Container Runtime for Docker](https://github.com/NVIDIA/nvidia-docker#quick-start)
   * [Get Docker CE for Ubuntu](https://docs.docker.com/install/linux/docker-ce/ubuntu/)
   * [Docker post-installation steps for Linux](https://docs.docker.com/install/linux/linux-postinstall/)

Even more links:
   * [DIGITS Installation Guide](https://docs.nvidia.com/deeplearning/digits/digits-installation/index.html)
   * [DIGITS User Guide](https://docs.nvidia.com/deeplearning/digits/digits-user-guide/index.html)
   * [DIGITS GitHub project](https://github.com/NVIDIA/DIGITS)
   * [NVIDIA repository](http://developer.download.nvidia.com/compute/machine-learning/repos/)
     Go to `ubuntu1804/x86_64` for NVIDIA drivers.
   * [Failure: DIGITS Building](https://github.com/NVIDIA/DIGITS/blob/digits-6.0/docs/BuildDigits.md)

It is assumed, that NVIDIA drivers, Caffe, Torch and TensorFlow are
already installed on your system.

    There are errors when building DIGITS
        and its dependencies from source

:exclamation: **Cannot build it from source. For your review only** :exclamation:

It is assumed, that NumPy was installed.
More over, in my case I have one NumPy installed using `apt` for Python 3.x
and one NumPy installed using `pip` for Python 2.7.
Otherwise TensorFlow wouldn't work for Python 2.7.

By default, Ubuntu installs recommended but not suggested packages.
With `--no-install-recommends`, only the main dependencies
(packages in the `Depends` field) are installed.

# Set PYTHONPATH for Caffe
PYTHONPATH=/usr/lib/python3/dist-packages/caffe
export PYTHONPATH

# Install DIGITS to enable loading data and visualization plug-ins
sudo pip install -e $DIGITS_ROOT

Error — AttributeError: 'module' object has no attribute 'open'
```

Errors — AttributeError: 'module' object has no attribute 'open'

It's seems NVIDIA DIGITS works for Python 2.7,
but Caffe `apt` installation is for Python 3.x only. Ridiculous.

---
  </blockquote>
</details>
<br/>

Starting from DIGITS 6, the preferred method of installation
is using Docker and installing DIGITS inside a Docker container.
To run DIGITS smoothly, Nvidia Docker must be installed.

---
#### <a name="docker-ce" />Install Docker CE

```shell
# Uninstall old Docker versions
sudo apt remove docker docker-engine docker.io

# Install using the repository

# Install packages to allow apt to use a repository over HTTPS
# apt-transport-https - transitional package for HTTPS support
# ca-certificates - common CA certificates
# curl - command line tool for transferring data with URL syntax
# software-properties-common - manage the repositories that you install software from
sudo apt update
sudo apt install \
    apt-transport-https \
    ca-certificates \
    curl \
    software-properties-common

# Add Docker’s official GPG key
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | \
    sudo apt-key add -

# Verify that you now have the key with the fingerprint
# 9DC8 5822 9FC7 DD38 854A E2D8 8D81 803C 0EBF CD88,
# by searching for the last 8 characters of the fingerprint.
sudo apt-key fingerprint 0EBFCD88

# Set up the stable repository
sudo add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   $(lsb_release -cs) \
   stable"

# Install the latest version of Docker CE
sudo apt update
sudo apt install docker-ce

# Verify that Docker CE is installed correctly
sudo docker run hello-world
```

---
#### <a name="container" />Install NVIDIA Container Runtime for Docker

Install [nVidia-Docker](https://github.com/NVIDIA/nvidia-docker).

![NVIDIA Container Runtime for Docker](../data/2018.12.22-nvidia-container-runtime-for-docker.png)

```shell
# If you have nvidia-docker 1.0 installed: we need to remove it
# and all existing GPU containers
sudo docker volume ls -q -f driver=nvidia-docker | \
    sudo xargs -r -I{} -n1 docker ps -q -a -f volume={} | \
    sudo xargs -r docker rm -f
sudo apt purge -y nvidia-docker

# Add the package repositories
curl -s -L https://nvidia.github.io/nvidia-docker/gpgkey | \
    sudo apt-key add -
distribution=$(. /etc/os-release;echo $ID$VERSION_ID)
curl -s -L https://nvidia.github.io/nvidia-docker/$distribution/nvidia-docker.list | \
    sudo tee /etc/apt/sources.list.d/nvidia-docker.list
sudo apt update

# Install nvidia-docker2 and reload the Docker daemon configuration
sudo apt install -y nvidia-docker2
sudo pkill -SIGHUP dockerd

# Test nvidia-smi with the latest official CUDA image
sudo docker run --runtime=nvidia --rm nvidia/cuda:10.0-base nvidia-smi
```

---
#### <a name="digits-docker" />Install DIGITS with Docker

```shell
# Install the latest version of DIGITS's docker image
sudo docker pull nvidia/digits:latest
# Install 6 RC
##sudo docker pull nvidia/digits:6.0-rc
```

---
#### <a name="run-digits" />Running DIGITS on Nvidia Docker

```shell
# To run DIGITS with Nvidia Docker, use the following command:
# nvidia-docker run -v <path to data>:/data/ -p 5000:5000 nvidia/digits:latest
# where <path to data> is where you have stored data sets or other files
# necessary for DIGITS to use on your system.
sudo nvidia-docker run -v ~:/data/ -p 5000:5000 nvidia/digits:latest
# or
sudo nvidia-docker run -v /hdd_purple:/data/ -p 5000:5000 nvidia/digits:latest

libdc1394 error: Failed to initialize libdc1394
/usr/local/lib/python2.7/dist-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.
  warnings.warn('Matplotlib is building the font cache using fc-list. This may take a moment.')
  ___ ___ ___ ___ _____ ___
 |   \_ _/ __|_ _|_   _/ __|
 | |) | | (_ || |  | | \__ \
 |___/___\___|___| |_| |___/ 6.0.0

2018-12-22 12:08:27 [INFO ] Loaded 0 jobs.

# In your browser enter:
http://localhost:5000
```

![NVIDIA DIGITS main page](../data/2018.12.22-nvidia-digits-main-page.png)

There is an error after run:
```libdc1394 error: Failed to initialize libdc1394```.
People on the forums write that you should ignore it.


text:
If you are using nginx and run your site with ssl you might want to add a rather strong
ssl config to it.

Based on the Infos provided by raymii.org and the mozilla foundation on that topic i just put
that setup into some files that you could easily add to your nginx config.
You can use the ssllabs ssltest to check your setup. With the ssl config provided you will easily get a A Rating.
To make it to A+ you need to activate HSTS as well.

### Setup Instructions
1. You should put the folder `secrecy` into /etc/nginx/
2. You should include the basic.conf of secrecy into your nginx.conf `include /etc/nginx/secrecy/basic.conf;` @see the nginx.conf sample file
 1. If you don`t want to add it globally you can also add it to your server definitions, see the sites-available sample
3. Test your nginx config with `nginx -t`
4. Reload your webserver configuration `service nginx reload`

### Upcoming
I will also create a salt formula that will install nginx with some helpfull configuration including that ssl one.

### References
- https://raymii.org/s/tutorials/Strong_SSL_Security_On_nginx.html
- https://wiki.mozilla.org/Security/Server_Side_TLS
- https://www.ssllabs.com/ssltest/

### To create the dh4096.pem file that is needed
`openssl dhparam -out dh4096.pem 4096` and move the file into the right location


text:
---
layout: post
title:   Server Tomcat v9.0 Server at localhost was unable to start within 45 seconds. If the server requires
category: Java
tags: [Java]
excerpt:  Server Tomcat v9.0 Server at localhost was unable to start within 45 seconds. If the server requires
---

解决方案：

步骤1->双击【Servers】

![](http://www.nangongyibin.com/assets/images/Java/20.png)

步骤2 ->打开界面上的timeouts ，将45改成较大的数值即可

![](http://www.nangongyibin.com/assets/images/Java/21.png)

![](http://www.nangongyibin.com/assets/images/Java/22.png)

**[参考文献]**

1. [Server Tomcat v9.0 Server at localhost was unable to start within 45 seconds. If the server requires](https://blog.csdn.net/ancientear/article/details/87854236 "Server Tomcat v9.0 Server at localhost was unable to start within 45 seconds. If the server requires")

gha_language: HTML


text:
---
title: About the google_service_accounts Resource
platform: gcp
---

# google\_service\_accounts

Use the `google_service_accounts` InSpec audit resource to test properties of all, or a filtered group of, GCP service accounts for a project.

## Syntax

A `google_service_accounts` resource block collects GCP service accounts by project then tests that group.

    describe google_service_accounts(project: 'chef-inspec-gcp') do
      it { should exist }
    end

Use this InSpec resource to enumerate IDs then test in-depth using `google_service_account`.

    google_service_accounts(project: 'chef-inspec-gcp').service_account_names.each do |sa_name|
      describe google_service_account(name: sa_name) do
        it { should exist }
      end
    end

## Examples

The following examples show how to use this InSpec audit resource.

### Test that there are no more than a specified number of service accounts for the project

    describe google_service_accounts(project: 'chef-inspec-gcp') do
      its('count') { should be <= 1000}
    end

### Test that an expected service account display name is available

    describe google_service_accounts(project: 'chef-inspec-gcp') do
      its('service_account_display_names'){ should include "gcp_sa_name" }
    end

### Test that an expected service account unique identifier is available

    describe google_service_accounts(project: 'chef-inspec-gcp') do
      its('service_account_ids'){ should include 12345678 }
    end

### Test that a service account with expected name is available

    describe google_service_accounts(project: 'dummy-project') do
      its('service_account_names'){ should include<EMAIL_ADDRESS>}
    end

### Use filtering to retrieve a particular service account

    google_service_accounts(project: 'chef-inspec-gcp').where(service_account_display_names: /^dummyaccount/).service_account_names.each do |sa_name|
      describe google_service_account(name: sa_name) do
        it { should exist }
      end
    end

## Filter Criteria

This resource supports the following filter criteria: `service_account_id`; `service_account_display_name`  and `service_account_name`. Any of these may be used with `where`, as a block or as a method.

## Properties

*  `service_account_ids` - an array of google_service_account identifier integers
*  `service_account_names` - an array of google_service_account name strings
*  `service_account_display_names` - an array of google_service_account display name strings
*  `service_account_emails` - an array of google_service_account email strings

## GCP Permissions

Ensure the [Identity and Access Management (IAM) API](https://console.cloud.google.com/apis/library/iam.googleapis.com/) is enabled for the project.

repository: piotr-zcz/inspec-gcp

gha_license_id: NOASSERTION

repo_name: piotr-zcz/inspec-gcp


text:
---
layout: default
---

# 1994-08-12 - Re: Mail-Future Free Remailers

## Header Data

From<EMAIL_ADDRESS>To<EMAIL_ADDRESS>Message Hash: a1fadbe18b224cf4ca419dc40fb7690aad2c59a4f8ed02dcc6f5f80e403abf50

Message ID<EMAIL_ADDRESS>Reply To: _N/A_

UTC Datetime: 1994-08-12 17:26:22 UTC

Raw Date: Fri, 12 Aug 94 10:26:22 PDT

## Raw message

```
{% raw  %}From<EMAIL_ADDRESS>Date: Fri, 12 Aug 94 10:26:22 PDT
To<EMAIL_ADDRESS>Subject: Re: Mail-Future Free Remailers
Message-ID<EMAIL_ADDRESS>MIME-Version: 1.0
Content-Type: text/plain

-----BEGIN PGP SIGNED MESSAGE-----

Karl writes:
>> People often like to postulate on the list that eventually there
>> won't be any more of these philantropic free remailers, and people
>> will be charging small amounts for every remailed message, to make
>> some money off it.
>> I've thought of a pretty good reason why this might not ever happen.
>> [...] one's primary reason might be to ensure oneself anonymity.

>Interesting point... I guess that is a good reason why free anonymous
>remailers might not ever die out, but pay remailers may be able to
>offer enhanced features and services that would tend to attract the
>vast majority of customers (assuming such a service would be
>considered as valuable by enough people ;)

In actuality having only purely commercial remailers in a chain would likely
lead to security concerns of the following nature. When remailers end up
requiring postage, people will tend to use the cheapest remailers to cut down
on costs. Who will be in a position to offer the cheapest rates under a
commercial proposition? Someone who has deep pockets, perhaps? An entity that
really doesn't rely on profit to stay in business? Our own governmental TLA's
could attract much remailer traffic by offering unbeatable prices (with our
own taxes), even a modest price edge skews traffic in their favor.

This speaks highly for the "every man a remailer" concept. If you know people
who run remailers and trust that they are not compromised, a mix of commercial
and philanthropic remailers may actually be the most secure chain of remailers
to use. One could then safely use the price edge of the commercial remailers
and the advanced features they offer and at the same time thwart the TLA
planted remailers attempts to trace traffic (at least ideally). This could be
done by inserting personally trusted philanthropic remailers into the chain in
strategic places. Hal has been mentioning such strategic placement of
remailers which is very interesting indeed.

Since I leave for Honduras tommorrow I must soon unsubscribe until the 23rd so
that I don't usurp all available disk space on our system with cpunks mail
while I'm gone. All the organized mayhem on the list will be missed (but I'm
not giving up diving in Roaton for it!) see you guys later.

<EMAIL_ADDRESS>

-----BEGIN PGP SIGNATURE-----
Version: 2.6

iQCVAgUBLkkMAz2paOMjHHAhAQFMFQP/er5g6MCw74epniILFOLR2U8TkzDtRDJB
KeZU4ghq+FxZVLjOrFUS6ofDAddwnLE4fPG6cFX3L5vRFowh8p+UzbjVNL/uS2Zv
Ac5BtIEylRC0kPMwFxc+SiiijJq1qfmdz/RiCE7yD4Vp6pv4Kqps40JmSy1HDC3B
3HvgSqCKu90=
=SKvc
-----END PGP SIGNATURE-----

{% endraw %}
```

## Thread

+ Return to [August 1994](/archive/1994/08)

+ Return to "[Al Billings <mimir@io.com>](/authors/al_billings_mimir_at_io_com_)"
+ Return to<EMAIL_ADDRESS>(Timothy C. May)](/authors/tcmay_at_netcom_com_timothy_c_may_)"
+ Return to "[VACCINIA@UNCVX1.OIT.UNC.EDU](/authors/vaccinia_at_uncvx1_oit_unc_edu)"

+ 1994-08-12 (Fri, 12 Aug 94 10:26:22 PDT) - Re: Mail-Future Free Remailers -<EMAIL_ADDRESS>  + 1994-08-12 (Fri, 12 Aug 94 11:44:43 PDT) - [Re: Mail-Future Free Remailers](/archive/1994/08/73486cc060fb9ab8eddf74e369c8a1a18c4c0bcf8f7685aa634b9c88567785e5) -<EMAIL_ADDRESS>(Timothy C. May)_
    + 1994-08-14 (Sat, 13 Aug 94 17:25:45 PDT) - [Re: Mail-Future Free Remailers](/archive/1994/08/1759c6fe9cc81f5da80295c8038a73bb44238013f921e556d743d2f2a80c7e44) - _Al Billings<EMAIL_ADDRESS>


text:
## `sABC.Playerservices`

This library provides methods to receive realtime metadata for:
* the **listener** that is connected to our infrastructure
* a specific radio station **channel**
* a specific radio **station** with all belonging channels

The SDK tries to use websockets to provide the best experience with realtime events. If no websocket connection can be established it falls back to polling. Due to limitations of this mode events are not real-time and not all features are available.

> Note: Listener specific meta data is only available if the channel streamed on streamABC infrastructure. All other types can be used with all backed distributors.

### Installation

Add a reference to our library to your web application like so:
```html
<script src="//playerservices.streamabc.net/sabc.js"></script>
```

> Please load this library with a direct link and don't save local copy to your site. This prevents cross-domain issues makes sure you use the latest version.

### Usage

Create an instance of `sABC.Playerservices` with calling `sABC.newPlayerservices(options?: PlayerservicesConfig)` somewhere in your code:
```javascript
var sabcService = sABC.newPlayerservices({
    debug: false,
    apikey: "abc"
});
```

The function argument is a object with config values:

config key | type       | default value | description
:----------|:-----------|:--------------|:-----------
`debug`    | `boolean`  | `false`       | enables debug output in browser console
`apikey`   | `string`   |               | api key provided by streamABC

After you created your instance you can attach event listeners to receive metadata events and start/stop receiving data.

### Attach Event Listeners

`sABC.Playerservices` emits the following event types:

name          | arguments                          | description
:-------------|:-----------------------------------|:-----------
`metadata`    | JSON object with meta data         | fires if new meta data for current song is available
`metanext`    | JSON object with meta data         | fires if new meta data for next song is available
`error`       | error                              | fires if an error ocurred, the response object property type defines if the error is on the websocket side (ws) or audio side (audio)

You can listen to one or both events:
```javascript
sabcService.on("metadata", function(data) {
    console.log(data)
});

sabcService.on("metanext", function(data) {
    console.log(data)
});
```

The payload `data` of both events contains all available metadata, for example:
```json
{
    "mount": "/sABCTest-sabcfm-mp3-256-5131639",
    "channel": "sABC-live",
    "timestamp": "2017-07-12T16:28:13.452Z",
    "session": "1cf9dc2a-530b-48a1-9979-f1ed1bcc719a",
    "rawdata": "LCD Soundsystem - New York, I Love You but You're Bringing Me Down",
    "artist": "LCD Soundsystem",
    "song": "New York, I Love You but You're Bringing Me Down",
    "type": "now",
    "meta": [
        {
            "ASIN": "B001QC8V4I",
            "artist": "LCD Soundsystem",
            "image": "https://images-eu.ssl-images-amazon.com/images/I/517o3A%2BQ%2BsL._SL160_.jpg",
            "largeimage": "https://images-eu.ssl-images-amazon.com/images/I/517o3A%2BQ%2BsL.jpg",
            "trackurl": "https://www.amazon.de/York-Love-Youre-Bringing-Down/dp/B001QC8V4I?SubscriptionId=<REDACTED_AWS_ACCESS_KEY>&tag=momusicle-21&linkCode=xm2&camp=2025&creative=165953&creativeASIN=B001QC8V4I",
            "type": "amazon"
        },
        {
            "artist": "LCD Soundsystem",
            "artisturl": "https://itunes.apple.com/de/artist/lcd-soundsystem/id29525428?uo=4",
            "image": "http://is5.mzstatic.com/image/thumb/Music/v4/4f/e9/df/4fe9df4a-0ae2-0d17-58ce-edfd5f3385c2/source/100x100bb.jpg",
            "largeimage": "https://images-eu.ssl-images-amazon.com/images/I/517o3A%2BQ%2BsL.jpg",
            "trackurl": "http://is5.mzstatic.com/image/thumb/Music/v4/4f/e9/df/4fe9df4a-0ae2-0d17-58ce-edfd5f3385c2/source/600x600bb.jpg",
            "previewurl": "http://audio.itunes.apple.com/apple-assets-us-std-000001/AudioPreview71/v4/72/63/ad/7263adf0-8314-fd7a-20ff-004e121c1fb8/mzaf_6600252372906776921.plus.aac.p.m4a",
            "trackurl": "https://itunes.apple.com/de/album/new-york-i-love-you-but-youre-bringing-me-down/id742432549?i=742434985&uo=4",
            "type": "itunes"
        }
    ]
}
```

### Start receiving user specific meta data

To receive listener specific meta data the first step is to decorate the streaming url with our listener parameter. There is a convinience utility method `decorateStreamURL(url: string): string` that does exactly this:
```javascript
var streamURL = sabcService.decorateStreamURL("http://sabc-test.stream.vip/1/mp3-256/");
```

You can then start receiving meta data events:
```javascript
var streamURL = sabcService.startMeta();
```

> Note: The stream has to be played using the decorated stream URL to receive meta data events.

### Start receiving channel or station events

Because meta data is not user specific in this mode, you don't need to decorate your stream URL.

You can start receiving events with one of this methods:
* `startMetaStation(station: string): void` - receive meta data for all channels of a station
* `startMetaChannel(channel: string): void` - receive meta data for one channel

> Please use the channel key or station key provided by streamABC. You can find this information in your streamABC management console.

```javascript
sabcService.startMetaChannel("sABC-live");
```

### Stop receiving events and error handling

To stop receive meta data events you can use `stopMeta()` method.
It doesn't matter what mode you use.

The SDK tries to handle connection errors as good as possible and reconnects if a websocket connection is lost.

Error events are emitted if the SDK detects a connection error. A detailed error message is provided as an argument to this event.

> Be aware, that error events are emitted even though the SDK tries to get around it by itself, e.g. falling back to polling if websockets don't work.

repository: streamABC/api-player

repo_name: streamABC/api-player


text:
<!-- README.md is generated from README.Rmd. Please edit that file -->

# LDmergeFM

This script contains an implementation in R of a weighted average
procedure to generate consensus locus-specific LD matrices from multiple
single-cohort correlation files. Together with
[FINEMAP](https://doi.org/10.1093/bioinformatics/btw018), it has been
used in the generation of the
[PGC3-SCZ](https://doi.org/10.1101/2<IP_ADDRESS>92922) fine-mapping
results.

## Input files

`LDmergeFM` requires the
[readr](https://cran.r-project.org/web/packages/readr/index.html),
[dplyr](https://cran.r-project.org/web/packages/dplyr/index.html),
[purrr](https://cran.r-project.org/web/packages/purrr/index.html),
[reshape2](https://cran.r-project.org/web/packages/reshape2/index.html)
and [Matrix](https://cran.r-project.org/web/packages/Matrix/index.html)
packages to be available for your local R installation. It is designed
to be run from the command-line as:

    Rscript --vanilla LDmergeFM.R $LOCUS $COR_FORMAT $ESS_FORMULA

Where the argument `$LOCUS` is the locus identifier for the LD matrix
being calculated, present in all of the input files:

| Filename                | Contents                                                                                |
|-------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `$LOCUS.ref`            | Two-column whitespace-delimited file. **Column 1:** SNP name. **Column 2:** Effect allele. Equivalent to columns 1 and 4 of a `FINEMAP` .z file. No header.                                                                                |
| `$COHORT_$LOCUS.fam`    | 1x `PLINK v1.07+` .fam file for each cohort being analysed (with case/control phenotype). Individuals with missing phenotypes not used to compute the pairwise correlations should be excluded from this file.                                               |
| `$COHORT_$LOCUS.cor.gz` | 1x `LDSTORE v1.1` .cor file (compressed output of *–table* flag) for each cohort being analysed. Output of the `PLINK v1.9+` *–r inter-chr gz* flag (`$COHORT_$LOCUS.ld.gz`) is also acceptable if the `$COR_FORMAT` argument is changed as described below. |

Single-cohort names (`$COHORT`) should be unique but can contain any
non-whitespace characters. The underscore ("\_") separation with
`$LOCUS` is mandatory.

## Changing cohort weights and correlation file format

The other two arguments of the script are optional:

`$COR_FORMAT` indicates whether the input correlations have been
computed with *“LDSTORE”* or *“PLINK”*, allowing the script to correctly
process these files. Defaults to *“LDSTORE”* if not explicit.

`$ESS_FORMULA` indicates how to compute the effective sample size used
as weight of each LD matrix. Options are *“METAL”* for the formula used
in [Willer et al. 2010](https://doi.org/10.1093/bioinformatics/btq340)
or *“NCP”* for the definition of [Matti
Pirinen](https://www.mv.helsinki.fi/home/mjxpirin/GWAS_course/material/GWAS3.html)
and [Vukcevic et al. 2011](https://doi.org/10.1002/gepi.20576). Defaults
to *“METAL”* if not explicit.

Note that if these last two arguments are used, they have to be used
**in the order above**. This implies that to change `$ESS_FORMULA` one
needs to be explicit and state the value of `$COR_FORMAT` as well (but
the converse is not true).

## Output files

| Filename             | Contents                                                                                |
|----------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `$LOCUS.ld`          | Square consensus LD matrix. SNPs are given on the same order as `$LOCUS.ref`.                                                                                |
| `$LOCUS.snps.log`    | SNPs used in the computation of the consensus LD matrix. Should match those on `$LOCUS.ref`.                                                                                |
| `$LOCUS.samples.log` | Cohorts used in the computation of the consensus LD matrix. Should match all of those provided as input files.                                                                                |
| `$LOCUS.heatmap.png` | Basic illustration of the consensus LD structure at the locus. Intended for troubleshooting or to identify regions that could be problematic for fine-mapping. Only generated if R installation has PNG capability. |

## Testing

The [`./test/`](test/) folder contains some input/output files that can
be used to conduct a reproducible run. For illustration purposes, these
files include the region around exon 12 of the
[EDAR](https://www.genecards.org/cgi-bin/carddisp.pl?gene=EDAR) gene,
which contains some very strong linkage as previously discussed by
[Sabeti et al. 2007](https://dx.doi.org/10.1038%2Fnature06250).
Genotypes were derived from polymorphic SNPs from four subpopulations
(Europeans, Sub-Saharan Africans, East Asians and Native Americans) of
the public
[HGDP](ftp://ngs.sanger.ac.uk/production/hgdp/hgdp_wgs.20190516/)
dataset. Please reference [Bergström et
al. 2020](https://dx.doi.org/10.1126/science.aay5012) if you find this
data useful for other purposes.

## Assumptions

`LDmergeFM` has been designed with fine-mapping in a meta-analytic
case-control GWAS setting in mind, so one of its implicit requirements
(in line with [FINEMAP](https://doi.org/10.1093/bioinformatics/btw018))
is that the reference allele for the correlations is the **same** in all
cohorts. Given that inconsistent criteria are currently used to decide
effect/reference alleles, it can help to set these explictly using the
`PLINK` *–a1-allele*/*–ref-allele* flag, which in fact can accept the
format of the `$LOCUS.ref` file.

For a similar reason, `LDmergeFM` expects that all SNPs in the
`$LOCUS.ref` file will be uniquely named and that each of them can be
found in the correlation file of **at least** one cohort. Duplicated or
missing SNPs might cause the script to fail silently, returning
erroneous output, so please ensure these are not present.

## Notes

`LDmergeFM` has not been tested with correlation table files from
`LDSTORE v2+`, please conduct a test run before using those in important
analyses.

`LDmergeFM` can work with an arbitrary number of input matrices but in
its current state is not optimised to take advantage of multicore
environments or matrix sparsity, and thus can be potentially
resource-hungry. If working on systems with resource quotas, please
check `.log` files to make sure the computation of the consensus LD
matrix has used all available data.

`LDmergeFM` is not ancestry-aware. If ancestry-specific consensus
matrices are needed (e.g. for trans-ancestry fine-mapping purposes) you
should run the script separately for each group of single-ancestry
inputs.

## Major version history

**2021-03-09** => *Added some internal checks for better error
reporting. Introduced arguments to accommodate other correlation file
formats and change the calculation for effective sample size weights if
desired. New basic heatmap output.*

**2020-11-13** => *Upload of initial version with essential
functionality.*

## Additional software

`FINEMAP`/`LDSTORE`: <http://www.christianbenner.com/>

`PLINK`: <https://www.cog-genomics.org/plink/1.9/>

## Citation

If this script is helpful for your work, just reference the main
[PGC3-SCZ](https://doi.org/10.1101/2<IP_ADDRESS>92922) paper. If it
ends up being *very* helpful, please let me know so I can keep fighting
impostor syndrome one day at a time :relieved:.

## Contact

Please submit suggestions and bug-reports at
<https://github.com/pintaius/LDmergeFM/issues>.

repository: Pintaius/LDmergeFM

repo_name: Pintaius/LDmergeFM


text:
# Phase 2 presentations

## Guidelines

- Duration: 25 minutes
  - Presentation: up to 15 minutes.
  - Questions & answers: minumum of 10 minutes.
- The presentation should:
  - Demonstrate the working parts of the project, with emphasis on the second part.
    - E.g.
      - Providing credentials.
      - Creating projects.
      - Listing projects.
      - Seeing the details of a project.
      - Deleting a project
    - Avoid repeting similar parts.
  - Highlight the non-trival technical parts of the solution.
    - E.g.
      - How are credentials stored and made available to the HTTP requesting code.
      - How are HTTP requests performed.
      - How are HTTP forms handled.
      - How are errors handled.
      - How is deep-linking supported.
      - How is hypermedia used.
  - Avoid repeating _things_ that were presented in the classes.
    - E.g.
      - Do not describe how `useFetch` works.
  - Identify the main design decisions regarding how the code base is structured.
- Manage the presentation time wisely. Make sure it is well used to highligh the valuable parts of your solution.
- Add a document to the repo with a summary of this presentation, with pointers to the relevant parts of the code or technical documentation.

## Schedule

- [LI61D](https://github.com/isel-leic-daw/2021v-public/wiki/schedule-li61d)
- [LI61N](https://github.com/isel-leic-daw/2021v-public/wiki/schedule-li61n)

gha_language: Kotlin


text:
---
layout: post
title: 'Add CopyTo and MoveTo to context menus in Vista'
---
Here's a fun little productivity tip. Add CopyTo and MoveTo to your right-click context menu in windows explorer. Saves you having to open a second explorer window or navigate away from your current location. Simply open notepad and copy the following lines into it. Watch out for the word wrap. It should total three lines.

    Windows Registry Editor Version 5.00
    [HKEY_CLASSES_ROOT\AllFilesystemObjects\shellex\ContextMenuHandlers\{C2FBB630-2971-11D1-A18C-00C04FD75D13}]
    [HKEY_CLASSES_ROOT\AllFilesystemObjects\shellex\ContextMenuHandlers\{C2FBB631-2971-11D1-A18C-00C04FD75D13}]

Name it copyto.reg ([or download this file](/downloads/copyto.reg)). Double click copyto.reg to add the registry settings.


text:
---
layout: default
---

# 1995-12-02 - Re: nsa and netscape

## Header Data

From: Jeff Weinstein<EMAIL_ADDRESS>To<EMAIL_ADDRESS>Message Hash: 6042d31bfd33471c7fa5f2e5e981680d3d337d7e87c2379b8ae0e0f92c17c714

Message ID<EMAIL_ADDRESS>Reply To<EMAIL_ADDRESS>UTC Datetime: 1995-12-02 07:53:30 UTC

Raw Date: Sat, 2 Dec 1995 15:53:30 +0800

## Raw message

```
{% raw  %}From: Jeff Weinstein<EMAIL_ADDRESS>Date: Sat, 2 Dec 1995 15:53:30 +0800
To<EMAIL_ADDRESS>Subject: Re: nsa and netscape
In-Reply-To<EMAIL_ADDRESS>Message-ID<EMAIL_ADDRESS>MIME-Version: 1.0
Content-Type: text/plain

Bob Bruen, MIT Lab for Nuclear Science wrote:
>
>   The following came from a government source. I thought it might be of
>   interest.
>                        Bob
> --------------------------------------------------------------------------
>
>      At yesterdays FNC  (Federal Networking Council) meeting it was
>      mentioned in passing that NSA has given Netscape a grant of $5 Million
>      (yes $5M) to beef up the security features of Netscape. More info will
>      be forthcoming on this.

  This is not strictly true.  The NSA has given us a contract to add
support for Fortezza to some of our products, including servers and
navigators.  The amount was less than $5M, but I'm not sure that I
should say how much it was.

  One of the things we hope to get out of this work is an architecture
for our products that allows us to easily support other crypto hardware,
including devices that don't use Secret algorithms, and don't require
key-escrow.

	--Jeff

--
Jeff Weinstein - Electronic Munitions Specialist
Netscape Communication Corporation
<EMAIL_ADDRESS>- http://home.netscape.com/people/jsw
Any opinions expressed above are mine.

{% endraw %}
```

## Thread

+ Return to [December 1995](/archive/1995/12)

+ Return to "["Bob Bruen, MIT Lab for Nuclear Science" <BRUEN@mitlns.mit.edu>](/authors/bob_bruen_mit_lab_for_nuclear_science_bruen_at_mitlns_mit_edu_)"
+ Return to<EMAIL_ADDRESS>(Futplex)](/authors/futplex_at_pseudonym_com_futplex_)"
+ Return to "[Jeff Weinstein <jsw@netscape.com>](/authors/jeff_weinstein_jsw_at_netscape_com_)"
+ Return to "[sameer <sameer@c2.org>](/authors/sameer_sameer_at_c2_org_)"
+ Return to<EMAIL_ADDRESS>(david d `zoo' zuhn)](/authors/zuhn_at_sctc_com_david_d_zoo_zuhn_)"

+ 1995-12-01 (Fri, 1 Dec 1995 20:49:43 +0800) - [nsa and netscape](/archive/1995/12/f8f0770362572ae3d6328bf49beabea44bc80568ecaca00cf1925f315d959862) - _"Bob Bruen, MIT Lab for Nuclear Science"<EMAIL_ADDRESS>  + 1995-12-01 (Sat, 2 Dec 1995 02:06:39 +0800) - [Re: nsa and netscape](/archive/1995/12/c9a75c3919e9103192f545b0fc94182164b1270147e402a0d16e3c35f70117cb) - _sameer<EMAIL_ADDRESS>  + 1995-12-02 (Sat, 2 Dec 1995 14:59:30 +0800) - [Re: nsa and netscape](/archive/1995/12/2d093aa2aa5186df31cc4733b8a1711ed453d9a8bcd189b10160ef01ad3fa680) -<EMAIL_ADDRESS>(david d `zoo' zuhn)_
    + 1995-12-02 (Sat, 2 Dec 1995 09:04:44 +0800) - [Re: nsa and netscape](/archive/1995/12/f228d69f111d1cfe0d62450c663f9ef030c8dab99e7d8e9155ee68e41a054e9a) -<EMAIL_ADDRESS>(Futplex)_
  + 1995-12-02 (Sat, 2 Dec 1995 15:53:30 +0800) - Re: nsa and netscape - _Jeff Weinstein<EMAIL_ADDRESS>


text:
---
layout: post
title:  "Make Snaps Work With A Nonstandard Path"
slug:   different-homedir-path
date:   2020-04-30 11:22:21
categories: snap
tags:
 - snap
 - snapcraft
 - apparmor
 - ubuntu-18-04
 - ubuntu
---

## Problem

Snapcraft uses apparmor to contain software running within the snap, and to ensure it doesn't write to the
system outside of expected areas. However, this leads to issues when files are in nonstandard locations, such
as your home directory residing somewhere like `/home/nethome/[user]` for NFS mounted home directories.

## Solution

The solution is to make apparmor aware of new home directory locations.

This can be done in one of two ways.

Interactively, with this command:

```bash
$ sudo dpkg-reconfigure apparmor
```

Or, alternatively, you can run this one-liner to provide the correct configuration, assuming your
alternate homedir is in `/home/nethome/USER`:

```bash
$ echo "@{HOMEDIRS}+=/home/nethome/" | sudo tee /etc/apparmor.d/tunables/home.d/alt-homedir
```

This should now work, without needing to restart any services, allowing snaps to correctly write
to your home directory not at /home.

repository: benyanke/docs

branch_name: refs/heads/gh-pages

extension: markdown

gha_language: SCSS

repo_name: benyanke/docs


text:
---
layout: post
category: writing
title: "things that go bump in the night"
---

Sounds kinda dirty, but I'm actually talking about lo-fi hip hop. I've been a huge Nujabes fan ever since the Samurai Champloo days over a decade ago. Although I enjoy anything from classical to rap, instrumental hip hop has taken hold of a soft spot in my heart and still hasn't let go.

What makes hip hop lo-fi is the lack of perfection that is often found in highly produced music. Think scratches, hums, and unusual frequencies. The result? A jazzy, enchanting and bittersweet wave of nostalgia built from strong but slow beats. It's also very reminiscent of the tunes that were played on Adult Swim back then.

I've found that late nights can be the best time to find some really great tunes, and I've linked some of my personal favorites below. Perfect for slow Sunday mornings, grinding out some video games, or even staying up to finish some work.

Cheers!


text:
# popp - a PO file preprocessor

[popp website](http://treer.github.io/POpp/)

For Gnu .po language translation files. See the [GNU gettext documentation](https://www.gnu.org/software/gettext/manual/html_node/index.html) for information about PO files.

The preprocessor allows your translated text to reference other items of
translated text, in a way that should work within any .PO editor. The use
of $include statements is also supported, and conditional directives
might be added in future.

For example, you can have .PO source files like this:

    msgid "ProductName short"
    msgstr "POpp"

    msgid "Welcome text"
    msgstr "Congratulations on your download of {id:productname short}"

which can be converted automatically to this:

    msgid "ProductName short"
    msgstr "POpp"

    msgid "Welcome text"
    msgstr "Congratulations on your download of POpp"

#### Currently:
  * **The Windows executable can be [downloaded here](https://mega.co.nz/#!7NVEHCZQ!zL9zvNUzWA-Hl5yyHA5jLY-PstFutCUpRNjujEWAO5M)** (v0.2.0)
   - md5: 51f4071976faf82f7cbcd8cf9325fe02 *popp.exe
  * It does *not* support references to or from plural forms, though the rest of the file can be processed.
  * I'm still in the process of trying popp in a real project environment, so for now assume it's only been tested with the automatic test cases, and take care.

#### Licence:
MIT X11

#### Language:
  * C#, compiles with Mono and Visual Studio, but the UnitTests project is a Visual Studio one (VS Express 2013).
  * popp requires v3.5 of the .Net framework.
  * UnitTests require v4.0 of the .Net framework.

## Documentation:

Expands .po msgstrs which reference other msgstr values via a curly brace
notation, for example `{id:ProductName_short}` will be expanded to the msgstr
which has the msgid of `ProductName_short`.

#### Usage:
    popp [options] source.popp [dest.po]

#### Brace notation:

 * `{id:msgid}` or `{id:msgid-msgctxt}`
 * references can be escaped with a backslash, e.g. `\{id:msgid}` is ignored.

**WARNING**: Plural forms are not supported, the file can still be processed,
however lines begining with "msgstr[_n_]" cannot contain references,
and plural forms cannot be referenced with the brace notation.

#### Include directive notation:

    $include "fileName.po"

    # $include "fileName.po"
    #.$include "fileName.po"

The .po hash-comment notations can be used if the file must be editable or
parsable by other .po tools before being processed by popp.

#### Output
Files are written in UTF-8. If your source languages use unicode
characters that your shell can't display, then avoid using pipes and stick with
specifying an input file and an output file. (Or proceed very carefully)

#### Options:

 * -nl, --nLF
  - Use LF for newlines.

 * -nc, --nCRLF
  - Use CRLF for newlines.

 * -ns, --nSource
  - _[Default]_ Determines LF or CRLF for newlines by what the source file
    uses.

 * -s, --sensitive, --casesensitive
  - The msgids inside curly-brace-references are matched case-insensitively
    by default, the --sensitive option expands case-sensitive matches only.

 * -c, --count
  - Returns the number of references contained in the source file, regardless
    of whether the references are valid and can be expanded. No output file
    is written. Can be used as a second pass to confirm all references have
    been expanded (none were misspelled etc), but

    WARNING: Plural forms are not supported and references contained in
    plural-form msgstrs are not counted.

 * -i [path], --includeDirectory [path]
  - Adds a directory to the end of the search path used to locate files
    specified by $include directives.

 * -q, --quiet
  - Suppresses console error messages and info messages

#### Returns:
 * 0 - Success
 * 1 - fatal error - invalid arguments or file permissions.
 * 2 - fatal error - non-specific.
 * 3 - one or more warnings or non-fatal errors occurred.
 * less than 0 - Success, but not all references could be expanded, the
                  negative return value indicates how may references were
                  found that could not be expanded.

repository: Treer/POpp

repo_name: Treer/POpp


text:
# OP-Sample-Finder

This is an Electron + Python app for the [OP-Z sequencer and synthesizer](https://teenage.engineering/products/op-z) to generate OP-Z compatible AIF drum kit files from audio files. The app can search for melodic loops and drum samples in an audio file (WAV,MP3 or AIFF). Furthermore, the application is able to perform drum classification on the extracted drum samples. The MSc thesis paper based on this project can be found [here](https://github.com/hunjunior/OP_Sample_Finder/releases/download/v1.0/MSc_Thesis_David_Pituk.pdf).

The main important files and directories of the project:

- `package.json` - Points to the app's main file and lists its details and dependencies.
- `main.js` - Starts the app and creates a browser window to render HTML. This is the app's **main process**.
- `src/html/index.html` - A web page to render. This is the app's **renderer process**.
- `src/js/renderer.js` - The JS file which contains the functions to perform file/audio processing, DOM manipulation etc.
- `src/drum_JSON_template.json` - The template OP-1 JSON. This will be modified and concatenated to the final AIF kit.
- `src/pyaudioapi/` - This folder contains the python scripts for the back-end (RPC) and for the drum classification and drum track separation.
- `pretrained_models/` - Place holder for the models

A small pdf guide about the app [here](https://github.com/hunjunior/OP_Sample_Finder/releases/download/v1.0/OP_Sample_Finder_Guide.pdf).

## Setup

The following tools are required to be installed to run the project:
- [Git](https://git-scm.com) to clone the repository
- [Node.js](https://nodejs.org/en/download/) (which comes with [npm](http://npmjs.com))
- [Python 3.7](https://www.python.org/downloads/release/python-370/) with the [Virtual Environment (venv)](https://docs.python.org/3/library/venv.html) module

Clone the repository
```bash
git clone https://github.com/hunjunior/OP_Sample_Finder.git
```

Download the models:
- Get the fft-model.model file from [here](https://github.com/hunjunior/OP_Sample_Finder/releases/download/v1.0/fft-model.model) and copy it to the `pretrained_models/drum_classes` folder.
- Download the [4stems.tar.gz](https://github.com/deezer/spleeter/releases/download/v1.4.0/4stems.tar.gz) file from Spleeter and extract its content (checkpoint, model.data-00000-of-00001, model.meta, model.index) to the `pretrained_models/4stems` folder.

Then install the

```bash
# Go into the repository
cd OP_Sample_Finder

# Setup the virtual environment (venv) for the python back-end
# Make sure the python command points to Python 3.7 (on some system it's python3 or python3.7)
python -m venv op_venv/
# Activate the virtualenv (for Linux and Mac) (for Windows it should be 'op_venv\Scripts\activate')
source op_venv/bin/activate
# Install all python dependencies
pip install -r src/pyaudioapi/requirements.txt
# Deactivate virtualenv
deactivate

# Install Node.js dependencies
npm install
# Run the app
npm start
```


text:
---
layout: post
title: "Object Oriented Concepts: Crash Course"
date: 2019-04-23
excerpt: "A crash course in Object Oriented Concepts. For 7.1P"
feature: https://nekox.net/assets/img/nekomimi_71bg.jpg
tags: [University, Object Oriented Programming, Artillery3]
comments: false
---

# Object Oriented Programming: Crash Course

------

Though there have been many paradigms throughout the history of computer programming, none are as iconic and popular as Object-Oriented (OO) Programming--and for good reason.

Object Oriented Programming is the practice of composing programs from objects and their data as opposed to a grocery-list styled procedural program where they are executed from top to bottom. This allows for a more natural and in some way, efficient programming practice as it encourages modularity and code reuse.

## A classy-shooty example

One of the issues with OO programming when explaining it is often the concept of classes. Some people just want names to mean something: 'class' is too vague of a word to make that work.

Let's take warships as an example and then we'll move onto some artillery pieces.

#### Classes and Objects

A certain number of years ago there existed a really big chunck of steel floating on the ocean known as the **Queen Elizabeth-class** battleship. Of the **Queen Elizabeth-class** battleships were two famous ships: **HMS Warspite** and **HMS Queen Elizabeth**.

We can say that HMS Warspite and HMS Queen Elizabeth are members of the Queen Elizabeth-Class of battleships.

- Warspite and Queen Elizabeth are objects of the Queen Elizabeth Class
- Warspite and Queen Elizabeth are different ships of the same model: they have the same calibre of guns, armour, layout, but they are not the same object.
- Warspite and Queen Elizabeth have slightly different information that they hold: they have different names, and different naval personnel on board.
  - Think that the *type* of data is the same (string, people) but the contents are different.

The class of battleship is not a tangible thing: it represents the class of ships that exist but the pure class itself is just an idea; the pure class is a blueprint that is used to make the ships.

Similar to classes, **interfaces** are a funny imaginary beast like most prominent religious figures. In essence, they define that a class has defined inputs and outputs, and acts as a contract that the object must uphold.

On HMS Warspite, her majesty has four turrets mounting twin 381mm guns. On the other hand, if you, the ever-smart Admiral you are, wanted to replace the guns with smaller ones that could fire faster, you need to make sure that the turret your engineers select actually fit onto the warship. In essence, the turret mount is the interface--it defines the size of the turret, how it must rotate, how it loads, and how it fires (because turrets are just decorations if they can't fire).

The use of **interfaces** allows objects to be treated as solely interfaces in some higher-level applications, such as Artillery3 (A3). A3 treats anything that implements the `IWeapon` interface as a weapon as long as it implements commands to fire, charge, depress, and even elevate. Hence, any weapon that implements those methods can be treated like a weapon, allowing for flexibility of treating one object as another. Frankly, a duck can be treated as a weapon as long as it implements those methods.

Go figure.

### Abstraction

We don't often think about the many-thousands of horsepower triple-quadruple-quintuple expansion steam engines that drive Queen Warspite, however-many propellers there are under the waterline. You just yell through some brass tubes to someone else to get their ~~as- haulin--~~moving. This way, a lot of the functions of the Her-Majesty's-Ship (HMS) Her-Majesty (Queen Elizabeth) (did no one think that through?) are *abstractions.*

This form of treating functions as black boxes is the big idea behind abstraction and consequently, the concept of the box is called encapsulation. Putting things you don't know about (such as half-dead cats) in the box is known as Information Hiding. By describing how objects behave based on their methods and the information they expose, their internals can be treated as black boxes, and much like magic, they can be built upon to feature more grandiose effects such as "shoot all them gunzz" at once.

### Encapsulation and Information Hiding

Putting everything into one box: the methods, the data, and the cats, is known as encapsulation. Hiding whatever you've stolen and put inside is known as Information Hiding. They're very similar in that they both surreptitiously put things you don't about into mysterious ~~pills~~ capsules known as objects.

Information Hiding tends to refer to the access levels that an object can feature, often read and written about as *private, protected,*and *public* members. For example, taking the big-boom example from earlier, a warship often has guns inside turrets. The big man controlling the warship doesn't need to know how to reload the gun nor tell them to reload themselves. This is a *protected* or even *private* function, accessible only within the turret. On the other hand, a turret should be exposing it's `shoot()` function to allow the ship to control the turret. A perfect example of this in A3 is Characters (Artillery pieces) exposing their `shoot()` function to the player so that they can shoot.

### Polymorphism

On the other hand, it turns out other ~~bottlesheeps~~ battleships like *Kongou* exist! They are both battleships, hence, it turns out that they're both inherited from a super-battleship class! We can define battleships as a super-class or parent class to our little boots known as Warspite and Kongou as most battleships share common features such as being able to move, having guns, and having armour.

By inheritance in OO Programming, we mean that classes can *inherit the properties and methods* of a parent class. This allows the child class to specialise and extend the class, such as defining the specific class of battleship we're talking about or in the case of A3--how a character is inherited from an entity. Both projectiles and characters are entities as they share common traits, yet they both expand on the concept of entity and specialise the class down to a very specific role (the shootee and shooter).

### Coupling and Cohesion

The oddities of OO design, Coupling refers to the level of interconnectedness between objects. In A3, coupling is can be seen in the abstract factory design used in terrain generation. The World of A3 doesn't need to know anything about the terrain it is generating nor the details of how it is generated: it just creates a factory and tells the factory to make the terrain. This is *decoupling* the world and the generation of the terrain.

Cohesion is a little easier to understand: the gun should only be a gun. It is the gunniest of all guns and nothing will be more gun-like than The Gun. Doesn't do anything else though. By highly specialising a class it allows more concrete responsibility design and reduces overlap in responsibilities by objects. In A3, it'd probably be the guns.

## Responsibility-Driven Design

OO programming is arguably more about design than it is about the actual programming itself. It's quite difficult to really create elegant or neat code that works since most code is an iterative process and trying to create a perfect system or scaffolding at the very start of the project is an fool's errand.

### Roles

There exists in this endless canvas of blue: steel warships, guns, shells, gunpowder, armour, personnel, aircraft, torpedoes, smoke. Out on the azure lanes we see steel giants (and for some reason, small cute girls) battling it out for naval superiority. There are Torpedo Boats, Destroyers, Cruisers-- Light... and the list goes on.

These are all roles: the ocean, the crew, the guns, the shells--they're all things that can exist within a particular program and the environment surrounding it. They identify what a program needs.

### Responsibilities

Roles have responsibilities: aircraft must fly, they then drop bombs, torpedoes, and the like. The responsibilities often supersede the objects themselves: the ocean must hold up all the warships, the planes must be able to pack themselves inside Aircraft Carriers, and physics must work. These involve knowing what a object is able to do or what it needs to know. Each object should, ideally, have only one purpose. This defines the fields and methods of each individual role in the form of objects, and the specialisation of these roles allows you to start defining the relationships between objects.

### Collaborations

As our objects grow, they need to interact somehow. Collaborations defines the intrinsic relational relationship between objects: the world has an ocean, the ocean holds ships, the ships hold planes or guns. There are actually different types of collaborations, but three simple ones are: "uses", "has-a", and "is-a-kind of", being Dependency, Association, and Inheritance respectively.

Aircraft Carriers "use" aircraft, they "have" an engine, and they "are-a-kind of" warship. Easy.

## Design Patterns

The formal version of copy-paste code, design patterns are ways of designing OO programs that very smart people have thought about and us not-so-smart people can use to solve common problems.

#### Concept of Composition

Composition, as described "favoured" by the Gang Of Four, is the concept that we should try to use composition over inheritance. Your pay as a programmer is not how pretty your Christmas-tree of inheritance hierarchies are, but the effectiveness and efficiency of your program. Hence, the concept of composition boils down to favouring the use of interfaces along with putting component objects within a parent object to allow for flexibility since multiple-inheritance is baaaad. Japan tried to cross a Submarine and Aircraft Carrier once. It was not very effective.

Look for PhysicsComponents of Artillery3 -- all the compositions literally have the word 'Component' inside the class name. (StateComponent, ObserverComponent, etc.)

##### Singleton

Look Ma! It's a **GLOBAL VARIABLE!!1!1!!!**

Jokes aside, they really are global objects, and for good reason. In A3, there only needs to be **one** physics engine. Any more and we introduce multiverses and all that bad stuff--no, using Singletons often are more useful for enforcing only one instance of one object to exist at all times. It allows, at least in A3, for Physics Components to register themselves with the Physics Engine without having the Physics Engine reference being passed down through the Christmas tree since, well, if you're using a physics component, there's a physics engine involved for handling collision.

##### Command

I mean, why not have more objects? Commands are turning method calls into objects to decouple objects from the input. The game could call a player to move based on the input from the human on the other side of this screen, however, that involves all parties knowing things... some objects don't want known.

`O\\\\\\\O`

In A3, the use of Commands means that the only the InputHandler knows what the user entered, but never the key the user typed nor the command that is being passed other than that it's of class `command` -- this is then executed with the correct character only through `command.execute()`, never directly calling the character's methods. Again, more classes for more decoupling.

 Though we could go into the SwinAdventure bag example, in A3 the concept of Entities and EntityAssemblies is a composite pattern. In formal terms, the branches are the EntityAssemblies and the Entities are the leaves/end nodes of the pattern. In conceptual terms, a Character is an assembly that can have hulls, weapons, and other attachments, each of which are entities. As assemblies are considered entities, putting an assembly within a character would be the same as putting in an entity.

To update all the entities? `entites.update()`

That calls all the update functions, and the assemblies will call the update functions of their assemblies. Draw works the same way.

##### Abstract Factory

Originally a Strategy Pattern (which will be implemented later for projectile flight), abstract factory is simply delegating the creation of an object/instantiation to another class. It's best described by code here:

```
TerrainFactory _terrainFactory = new TerrainFactoryMidpoint();
_terrainMidP = _terrainFactory.Generate();

_terrainFactory = new TerrainFactoryRandom();
_terrainRand = _terrainFactory.Generate();

```

By delegating the construction of the terrain to the factory class, in a more developed version of A3, the abstract factory can be supplied by either the UI or a parent class. This means that in order to generate the terrain, all one needs to do is to call `_terrainFactory.Generate()`.

This is useful as there are often similar things we want to make but we don't want to be explicit about it-- that is, we don't want to hard code the objects we're making in this class *right now* or it may change later down. Hence, we create an object that does creation for us, the object can be replaced at any time (decoupling once again).

##### Observer

Similar to events but different depending on the person, observers notify subjects of events when something happens. I do plan on using this for UI and achievements later down the line, however, their current implementation in A3 is for ending player turns.

Observers "watch" objects by registering themselves with the object to get notified if something "interesting" happens. In the case of A3, the World registers itself with players such that, when the player finally ends the turn, the World is notified to move on with the game. Otherwise, the world would constantly have to check in on players to see their current progress and it can consume valuable resources or in my case, create unnecessary coupling between the player and world as the world would have to both check if a player is "finished" with their turn and then the world itself would have to change the state of the next player--coupling too high.

By separating the notifications between the player and the world, the players don't need to exist for the world to progress.

##### Strategy

This has not been implemented yet (though it was originally used for terrain generation), the strategy pattern involves switching implementations of a methods through objects. For example, the flight path of objects should be defined by a parabolic arc, however, some objects might split so they have additional parameters or they might have a "homing" capability. Hence, as they all do similar things, the strategy object takes input parameters and adjusts the position of the projectile based on it's internal *strategy*.

This is much more complex in A3 due to the implementation of the Physics Engine.

#### Game Design Patterns

These patterns are somewhat specific to games, however, they are design patterns nonetheless.

##### Game Loop

Draw, Update, Handle Input. The core of all games is the *Game Loop* which is also related to the very common use of the *GameObject* class which has Draw and Update methods, with any and all game thingies inheriting from the *GameObject* class. This standardises the method of which objects interact and progress through time.

Very, very, very, useful.

##### Finite State Machine / Pushdown Automata (Game Ver.)

I've saved this for last as it is the fuzziest for me, personally. Coming from a slightly-VHDL and basic microcontroller background, the concept of Mealy and Moore state machines seem to be akin to the Finite State Machines (FSM) of the Computer Science World. Expanding on this is the concept of *Automata*, in which a FSM is a form of. *Pushdown Automata* is the implementation of Stacks upon *Automata*.

In games, this is used in Game States and not actual Automata. Consider a user interface in a game:

- Open the Esc. Menu
- Open Settings
- Open the Controls Tab
- Open the Hotkeys Window
- Open the Change a HotKey Window
- Open the Controller Mapper

Now we're 6-7 GUIs in and completely lost. How do we get out? Normally, states don't actually contain information from whence they came. This is problematic as under a normal FSM:

- You're in the Controller Mapper

Now let's head back, but to where!? How do we know where we came from? Since there are many ways to enter this GUI, it gets messy. Using a stack allows us to "Stack" states atop one another so that we can just "pop" states when where we need to take a detour and head back into that original state easily.

The implementation of states eventually lead to State Components within Artillery3. They're the most complicated but interesting parts of A3.

------

And that's all for this post! Feel free to point out any mistakes down in the comments below.


text:
---
layout:     post
title:      Search for sender in all mails on Exchange Server
date:       2020-03-08 04:20
author:     Raimund Rittnauer
description:    How to filter all your emails of your Exchange Server for a specific sender address
categories: tech
comments: true
tags:
 - exchange server
 - powershell
---

First of all you have to establish a PowerShell Session with your exchange server.

``` powershell
PS > $UserCredential = Get-Credential
PS > $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://mail.mymailserver.at/PowerShell/ -Authentication Kerberos -Credential $UserCredential
PS > Import-PSSession $Session -DisableNameChecking
```

Now you can access your Exchange Server with the [Exchange PowerShell Module][1]{:target="_blank"}.
_Get-Mailbox_ for example will give you a list of all available mailboxes.

``` powershell
PS > Get-Mailbox
```

If you want to search for all emails in all mailboxes which are from a specific sender address you can use the [pipe operator][2]{:target="_blank"} and the [_Search-Mailbox_][3]{:target="_blank"} command together with the [-SearchQuery][4]{:target="_blank"} parameter.

``` powershell
PS > Get-Mailbox | Search-Mailbox -SearchQuery "from<EMAIL_ADDRESS>-TargetMailbox "raimund" -TargetFolder "searchresults"
```

A copy of all filtered emails is now inside a folder named _searchresults_ in the specified _raimund_ mailbox.

There is also another nice feature called [Compliance Search][5]{:target="_blank"} with the cmdlet [New-ComplianceSearch][6]{:target="_blank"}.

> The Compliance Search feature in Exchange Server allows you to search all mailboxes in your organization. Unlike In-Place eDiscovery where you can search up to 10,000 mailboxes, there are no limits for the number of target mailboxes in a single search.

This is a really nice feature especially if you want to predefine search queries and then just execute them and if you dont want to copy the search results to a folder each time.

``` powershell
PS > New-ComplianceSearch -Name "Search All-Financial Report" -ExchangeLocation all -ContentMatchQuery 'sent>=01/01/2015 AND sent<=06/30/2015 AND subject:"financial report"'
PS > Start-ComplianceSearch -Identity "Search All-Financial Report"
```

[1]: https://docs.microsoft.com/en-us/powershell/module/exchange/?view=exchange-ps
[2]: https://docs.microsoft.com/en-us/powershell/scripting/learn/understanding-the-powershell-pipeline?view=powershell-7
[3]: https://docs.microsoft.com/en-us/powershell/module/exchange/mailboxes/search-mailbox?view=exchange-ps
[4]: https://docs.microsoft.com/en-us/exchange/security-and-compliance/in-place-ediscovery/message-properties-and-search-operators
[5]: https://docs.microsoft.com/en-us/exchange/policy-and-compliance/ediscovery/compliance-search?view=exchserver-2019
[6]: https://docs.microsoft.com/en-us/powershell/module/exchange/policy-and-compliance-content-search/new-compliancesearch?view=exchange-ps


text:
# redux-log-diff

A simple redux middleware that logs changes to the state after every action.

Supports node and browser.

![browser_example](https://cloud.githubusercontent.com/assets/7233925/21834763/7e4bf742-d77d-11e6-94eb-e12c15bf8be2.png)
![node_example](https://cloud.githubusercontent.com/assets/7233925/21834865/1d27d8fe-d77e-11e6-9a63-26fbad2f5d42.png)

## Install

```
$ npm install --save redux-log-diff
```

## Usage
```
import { createStore, applyMiddleware } from 'redux';
import logger from 'redux-log-diff';

const store = createStore(
  reducer,
  applyMiddleware(logger)
);
```

repository: Bebersohl/redux-log-diff

gha_language: JavaScript

repo_name: Bebersohl/redux-log-diff


text:
autoscale: true

# MS_038_F21 | Machine Learning for Artists
## Professor Douglas Goodwin
### MW 09:35-10:50AM
### Scripps Campus, Steele Hall, 229

## [Syllabus](https://github.com/scrippscollege/MS038_F2021/) | [Discord](https://discord.gg/FzzXPwm4)

---
#[fit] 👋 week 01

---
# We are here to learn techniques to use them critically and aesthetically. This is not a theory course or a programming course, though you will learn enough to be dangerous.

---
# What is **Artificial Intelligence**, **Machine Learning**, and **Deep Learning**?

---

^ Concentric circles (NVIDIA blog)

![](https://blogs.nvidia.com/wp-content/uploads/2016/07/Deep_Learning_Icons_R5_PNG.jpg.png)

---
# artificial intelligence

AI is the science of making inorganic stuff so smart that it exhibits (human) intelligence.

---
# weak vs strong AI

Strong AI has a complex algorithm that helps it act in different situations, while all the actions in weak AIs are pre-programmed by a human. Strong AI-powered machines have a mind of their own.

---
# general vs narrow AI

General AI: fabulous machines that have all our senses (maybe even more), all our reason, and think just like we do.

Most of AI today is Narrow AI systems that can only do one (or a few) defined things as well or better than humans.

---
## is fire intelligent? discuss.

![right,fit](https://www.evernote.com/l/ADOJmIpqtVBEZrxQ1NtdO_RmsTwNJ-TJWz8B/image.png)

- fire controls and maintains critical temperature
- fire identifies consumable resources
- fire self-organizes
- fire responds to stimuli
- fire can grow

---
## is the roomba intelligent? discuss.

![right,fit](https://content.syndigo.com/asset/87b964f1-d9fb-4ff8-acb2-88049c71df99/1920.jpeg)

---

![youtube](https://youtu.be/4fzNe48Wn9Y)

---
# machine learning

A field of computer science that uses statistical techniques to give computer systems the ability to "learn" with data, without being explicitly programmed.

![right,fit](https://archive.org/serve/images/petabox-via.jpg)

---
# machine learning vs traditional programming

![right,fit](https://www.evernote.com/l/ADO7v95TAcxM_ZvM_mUHAWkRezK1chdJL5YB/image.png)

---
# deep learning

A technique for implementing Machine Learning

- Uses multi-layered artificial *neural networks* to deliver state-of-the-art accuracy.
- Can automatically learn representations/features from data such as images, video or text.

![right,fit](https://www.evernote.com/l/ADOX9JZ5-GJCF6eBYEwB3qKkwdZfiH_OPEoB/image.png)

---
# background: hubel & weisel

<EMAIL_ADDRESS>
---

![youtube](https://youtu.be/IOHayh06LJ4)

---
# nobel prize for their discoveries concerning information processing in the visual system

1. visual perception is layered
2. layered architectures can solve problems (roomba)

---
# deep learning example

- what do the layers do?
- how does it compare to visual perception?

![right,fit](https://www.evernote.com/l/ADP5b7vRy6ROKqom5viPC06dnS9pYUq2hyoB/image.png)

---
# machine learning approaches

1. supervised learning
2. unsupervised learning
3. reinforced learning

---
# 1/ supervised learning

> “Supervised learning typically requires a large set of positive examples ... and negative examples ... . Each example is labeled by a human with its category—here, 8 or not-8. This label will be used as the supervision signal. Some of the positive and negative examples are used to train the system; these are called the training set.”

^ Excerpt From: Melanie Mitchell. “Artificial Intelligence.” Apple Books.

![right,fit](https://miro.medium.com/max/540/1*xq-pY9H9rzGjiQ7MTrMBoA.png)

---
# 2/ unsupervised learning

## “Yann LeCun himself acknowledges that *unsupervised learning is the dark matter of AI.* In other words, for general AI, almost all learning will have to be unsupervised, but no one has yet come up with the kinds of algorithms needed to perform successful unsupervised learning.”[^1]

[^1]: Melanie Mitchell. “Artificial Intelligence.”

---
# 3/ reinforced/reinforcement learning

> “reinforcement learning requires no labeled training examples. Instead, an agent—the learning program—performs actions in an environment (usually a computer simulation) and occasionally receives rewards from the environment. ... reinforcement learning played a central role in a stunning and momentous achievement in AI: a program that learned to beat the best humans at the complex game of Go.”

^ Excerpt From: Melanie Mitchell. “Artificial Intelligence.” Apple Books.

---

https://www.3blue1brown.com/lessons/neural-networks

---
# machine learning outputs

1.  **Regression**: Predict continuous values (price of a stock)
2. **Classification**: Predict a class/label (cat or dog?)
3. **Clustering**: Most similar other examples (Amazon related products recommendation)
4. **Sequence Prediction**: Predict the next word/sentence

---
# 1/ Regression

---
# 2/ Classification

---
# 3/ Clustering

---
# 4/ Sequence Prediction

---

# what's machine learning good for?

- Object recognition
- Speech recognition / sound detection
- Nlp, sentiment analysis
- Creative: style transfer
- Prediction
- Translation/restoration and transformation

---
# can you make art with ml? yes!

- [Lauren McCarthy](https://lauren-mccarthy.com/)
- Mario Klingemann
- Sofia Crespo
- Tom White
- Anna Ridler
- Alexander Mordvintsev
- Sougwen Chung
- Memo Akten

---
# tools and resources

1. teachable machine (free ?)
2. ml5.js (free)
3. google colab (free-$)
4. runwayml ($$)
5. paperspace ($$)

---
# google's teachable machine

> Train a computer to recognize your own images, sounds, & poses.
A fast, easy way to create machine learning models for your sites, apps, and more – no expertise or coding required.

---

![youtube](https://youtu.be/T2qQGqZxkD0)

---
#


text:
Much stuff of black jack is missing.

## Working Features

- Multiplayer
- Getting cards
- Correct counting of card values (like aces)

## Todos:

- three times card 7 is a black jack
- Split hands
- Double down
- Insurence
- Surrender
- Bets with casino chips

repository: oobenland/JBlackRMIJack

repo_name: oobenland/JBlackRMIJack