text:
Title: DRM比我想象中更有破坏力
Date: 2006-11-28 14:35
Author: number5
Category: opinions
Tags: DRM, slashdot, software-piracy, Treacherous-Computing
Slug: 23
Status: published
Wordpress-Id: 23
Link: http://brucewang.net/2006/11/28/23

摘自 <http://slashdot.org/linux/06/11/27/1145230.shtml> 的一篇评论
(精华总在评论中! -- [slashdot](http://slashdot.org)的名言)

> **DRM is about forcing you to run particular EXACT code, and either
> not running at all or refusing to talk to you if you are not.** This
> also happens to be the essence of DRM too... so it's a happy
> coincidence for the pro-DRMer within the technology companies.
>
> Treacherous Computing is hardware that is meant to allow person X to
> set their hardware up to refuse to run (or not cage) software that is
> not digitally signed by them. As you can imagine, this COULD be
> extremely valuable for security. HOWEVER, the collection of companies
> making up the Trusted Computing Group (most of the tech companies)
> decided that the capability to TRUST should be reserved for them. You
> do not get to override it. This "trust" (only running approved code)
> starts with the BIOS, moves up to the kernel and in stuff like Vista
> it then moves into the media subsystem. In a few years, it will move
> into applications like web browsers, or word processors. Not running
> Microsoft Word? No you can't open that document, sorry. Add into this
> nasty mix, the ability of Trusted Computing hardware to execute code
> IN SECRET, and you have a control freak's wet dream. Not only can you
> not change what your computer does, you cannot even know what it is up
> to. The instructions are/can be encrypted.
>
> Imagine it this way: a prison is very useful for keeping criminals in.
> It's not so good if YOU are the convict. In trusted computing as it is
> formulated today, YOU ARE THE CONVICT. You do not have the keys. Don't
> let them treat you like criminals. Demand the right to control your
> own PC -- you paid for it.
>
> Trusted Computing is a political issue because it is a massive power
> grab by the technology companies. People may think Stallman is
> over-reacting, but I assure you that he is not. Look into the
> implications properly.

注: Treacherous Computing = Trusted Computing


text:
# Disassemble 8080
A disassembler for the Intel 8080 written in pure Go.

Takes an 8080 ROM file and prints out the resulting assembly code for the Intel
8080.

## Installation
If you are a golang developer you can install the binary like so:
```bash
$ go get -u github.com/danmrichards/disassemble8080/cmd/disassemble8080/...
```

Alternatively you can clone this repo and build from source:

```bash
$ make
```

## Usage
```bash
Usage of disassemble8080:
  -rom string
        Path to 8080 ROM file
```

license: MIT

branch_name: refs/heads/master

extension: md

license_type: permissive


text:
---
keyword: [task, instance]
---

# Task instances

A task, such as an SQL task, is the basic compute unit in MaxCompute. This topic describes the basic operations on task instances in PyODPS.

## Basic operations

When a task is triggered, a MaxCompute instance is created for the task. For more information, see [Instance](/intl.en-US/Product Introduction/Definitions/Instance.md). You can perform the following operations on MaxCompute instances:

-   `list_instances()`: obtains all instances in a specific project.
-   `exist_instance()`: checks whether a specific instance exists.
-   `get_instance()`: obtains a specific instance.
-   `stop_instance()`: stops a specific instance.

    **Note:** You can also call the `stop()` method to stop a specific instance.

**Example**

```
for instance in o.list_instances():
    print(instance.id)
    o.exist_instance('my_instance_id')
```

## Obtain the Logview URL of an instance

-   For an SQL task instance, you can call the `get_logview_address` method to obtain its Logview URL.

    ```
    # Execute an SQL statement to obtain a specific instance. Then, call the get_logview_address method to obtain the Logview URL of the instance.
    instance = o.run_sql('desc pyodps_iris')
    print(instance.get_logview_address())
    # Obtain the Logview URL of an instance with the specified instance ID.
    instance = o.get_instance('2016042605520945g9k5pvyi2')
    print(instance.get_logview_address())
    ```

-   For an XFlow task instance, you must enumerate its sub-instances and then obtain the Logview URL of each sub-instance.

    ```
    instance = o.run_xflow('AppendID', 'algo_public', {'inputTableName': 'input_table', 'outputTableName': 'output_table'})
    for sub_inst_name, sub_inst in o.get_xflow_sub_instances(instance).items():
        print('%s: %s' % (sub_inst_name, sub_inst.get_logview_address()))
    ```

## Obtain the status of an instance

An instance can be in the `Running`, `Suspended`, or `Terminated` state. You can use the following methods to obtain the status of an instance:

-   `status`: obtains the status of an instance.
-   `is_terminated`: checks whether the execution of the current instance is completed.
-   `is_successful`: checks whether the execution of the current instance is successful. If the instance is running or fails, False is returned.

```
instance = o.get_instance('2016042605520945g9k5pvyi2')
instance.status
<Status.TERMINATED: 'Terminated'>
    from odps.models import Instance
    instance.status == Instance.Status.TERMINATED
    True
    instance.status.value
    'Terminated'
```

**Note:** You can call the `wait_for_completion` method to ask the system to return the status until the execution of the instance is completed. The `wait_for_success` method functions similarly. The difference is that if the instance fails, an exception is thrown.

## Perform operations on sub-instances

A running instance may contain one or more sub-instances. You can call the following methods to perform specific operations on sub-instances:

-   `get_task_names`: obtains all sub-instances. This method returns the names of all sub-instances.

    ```
    instance.get_task_names()
    ['SQLDropTableTask']
    ```

-   `get_task_result`: obtains the execution result of a specific sub-instance. This method returns the execution result of each sub-instance in the form of a dictionary.

    ```
    instance = o.execute_sql('select * from pyodps_iris limit 1')
    instance.get_task_names()
    ['AnonymousSQLTask']
    instance.get_task_result('AnonymousSQLTask')
    '"sepallength","sepalwidth","petallength","petalwidth","name"\n5.1,3.5,1.4,0.2,"Iris-setosa"\n'
    instance.get_task_results()
    OrderedDict([('AnonymousSQLTask', "sepallength","sepalwidth","petallength","petalwidth","name"\n5.1,3.5,1.4,0.2,"Iris-setosa"\n')])
    ```

-   `get_task_progress`: obtains the current running progress of a specific sub-instance when the instance is running.

    ```
    while not instance.is_terminated():
        for task_name in instance.get_task_names():
            print(instance.id, instance.get_task_progress(task_name).get_stage_progress_formatted_string())
            time.sleep(10)
<PHONE_NUMBER>1349613gzbzufck2 2016-05-19 18:14:03 M1_Stg1_job0:0/1/1[100%]
    ```

repository: JoyAbleCN/odps

filename: Task instances.md

repo_name: JoyAbleCN/odps


text:
# Projects for the lecture Numerical Methods of Statistical Physics

The lecture was held by Markus Quandt and Giuseppe Burgio in summer term 2020 at University of Tübingen.

The used language for simulations is C++20. The IDE is CLion.
The used build-system is Debian Buster.
It should also work on other platforms with small modifications in CMakeLists.txt.

## Testing different random-number-generators (RNGs)

![Diagram of Convergence](./Projects/RngTests/Genauigkeit_vs_n_1E10.png)

I did a pi-Test with 2 different random number generators (RNGs). The program can run in a fully parallelized mode.

The RNGs were used from standard C++ header `Random.h`.

We can see the convergence of the **Mersenne-Twister MT19937** algorithm with
up to 1E10 random numbers per calculated point. Convergence doesn't seem to slow down until 1E10, so I assume we can
calculate pi more exactly with more time. The maximum period of random numbers of MT19937 is pow(2,19937)-1, so this
would be a thinkable limit.

The **linear congruential RNG** (LCG) is limited in randomness and periodicity which results in limited convergence. With
this RNG it is not possible to determine pi more exactly than up to 1E-2.

## Forest Fire Simulations
There are some interesting Simulations of Forest-Fire-Cellular-Automatons:

https://people.sc.fsu.edu/~jburkardt/c_src/forest_fire_simulation/forest_fire_simulation.html

https://perso.u-cergy.fr/~ahonecker/bs/software/forest2d.html

## Sand Piles
This project is available under: https://github.com/Babalion/sandpiles

## Calculate spectral dimensions of fractal structures
This project is available under: https://github.com/Babalion/Fractal-Dimensions

## Solve the travelling-salesman-problem (tsp) with a simulated annealing algorithm
This project is available under: https://github.com/Babalion/simulated-annealing-tsp

## Ising Model
### 2 Level System
This project is available under: https://github.com/Babalion/Ising2level

### Sigma-Model
This is an Ising-Spin-System on a square lattice where every spin can direct in an arbitrary angle in 2D.
One can thus parametrize each spin via angle `theta`. You can also view the simulation live via openCV. Example below:

....

gha_language: Makefile

gha_license_id: MIT


text:
# GWSockets

WebSockets for GLua

## Usage

Place either `gmsv_gwsockets_win32.dll` (Windows) or `gmsv_gwsockets_linux.dll` (Linux) into your `GarrysMod/lua/bin` folder. On windows you will require the Visual C++ Redistributable 2017, which you can find [here](https://support.microsoft.com/help/2977003/the-latest-supported-visual-c-downloads).

*NOTE:* CentOS is currently not supported and appears to be having multiple issues. If you need the library to work on CentOS, compile it on CentOS using the instructions all the way at the bottom, but also replace the included ssl libraries with the ones provided by CentOS.

*NOTE:* Even though this module is mainly aimed at servers, it can also be used on clients. Just rename the module to `gmcl_gwsockets_os` and it will work on clientside as well.

You will also need to require the module in lua before you will be able to use it. You can do this running

```LUA
require("gwsockets")
```

## Documentation

### Connecting to a socket server

* First initialize a websocket instance using

  *NOTE:* URL's must include the scheme ( Either `ws://` or `wss://` )

  `Example: "wss://echo.websocket.events/api/socketserver"`

  ```LUA
  GWSockets.createWebSocket( url, verifyCertificate=true )
  ```

  *NOTE:* If you want your websockets to use SSL but don't have a trusted certificate, you can set the second parameter to false.

* If you are running certain versions of Linux (e.g. CentOS) it might be necessary to specify a different path for the root certificates. This is only required if you want to use SSL and verify set verifyCertificates to true when creating a websocket.
 ```LUA
  GWSockets.addVerifyPath( "/etc/ssl/certs" )
  ```

* Next add any cookies or headers you would like to send with the initial request (Optional)

  ```LUA
  WEBSOCKET:setHeader( key, value )
  WEBSOCKET:setCookie( key, value )
  ```

* Add some callbacks (Optional)

  ```LUA
  -- called when a message from the peer has been received
  function WEBSOCKET:onMessage( msg )  end

  -- called whenever anything goes wrong, this is always followed by a call to onDisconnected
  function WEBSOCKET:onError( errMessage ) end

  -- called as soon as the socket is connected
  -- This is a good place to start sending messages
  function WEBSOCKET:onConnected() end

  -- called whenever the socket has been disconnected
  -- this can either be because the socket has been requested to closed (either through user or error)
  -- or because the peer has closed the connection
  -- Note: If the peer does not close the connection gracefully, this might not be called until a write is attempted.
  function WEBSOCKET:onDisconnected() end
  ```

* Lastly open the connection

  ```LUA
  WEBSOCKET:open()
  ```

* Once the socket has been opened you can send messages using the `write` function

  ```LUA
  WEBSOCKET:write( message )
  ```

  *NOTE:* You can write messages to the socket before the connection has been established and the socket
  will wait before sending them until the connection has been established. However, it is best practice
  to only start sending in the onConnected() callback.

* You can close the websocket connection at any time using `close` OR `closeNow`

  ```LUA
  WEBSOCKET:close()
  WEBSOCKET:closeNow()
  ```

  * `close` will wait for all queued messages to be sent and then gracefully close the connection
  * `closeNow` will immediately terminate the connection and discard all queued messages

* You can cancel any queued outbound messages by calling

  ```LUA
  WEBSOCKET:clearQueue()
  ```

* You can check if the websocket is connected using

  ```LUA
  WEBSOCKET:isConnected()
  ```

  *NOTE:* You should avoid using this and instead rely on the callbacks.

## Example:

```LUA
require("gwsockets")
local socket = GWSockets.createWebSocket("wss://echo.websocket.events/")

function socket:onMessage(txt)
    print("Received: ", txt)
end

function socket:onError(txt)
    print("Error: ", txt)
end

-- We start writing only after being connected here. Technically this is not required as this library
-- just waits until the socket is connected before sending, but it's probably good practice
function socket:onConnected()
    print("Connected to echo server")
    -- Write Echo once every second, 10 times
    timer.Create("SocketWriteTimer", 1, 0, function()
        print("Writing: ", "Echo")
        socket:write("Echo")
    end)
    timer.Simple(10, function()
        timer.Remove("SocketWriteTimer")
        -- Even if some of the messages have not reached the other side yet, this type of close makes sure
        -- to only close the socket once all queued messages have been received by the peer.
        socket:close()
    end)
end

function socket:onDisconnected()
    print("WebSocket disconnected")
end

socket:open()
```

## Build

Requires [premake5](https://premake.github.io/download.html#v5).

Depending on your platform run one of the following commands to create a build script:
```console
premake5 --os=windows --file=BuildProjects.lua vs2010    # Windows
premake5 --os=linux   --file=BuildProjects.lua gmake     # Linux
premake5 --os=macosx  --file=BuildProjects.lua gmake     # Mac
```
Then use the appropriate generated solution for your system in the solutions/ folder and build the project.

### Windows

On Windows all you need to do is open the generated visual studio project and build the dll. All libraries and headers are provided already. If you wish to build the 64 bit version you just have to switch the build configuration to x64.

### Linux

On linux only essential programs for building C++ programs are required. On Ubuntu 64-bit these are:

```console
sudo apt-get install build-essential gcc-multilib g++-multilib
```

The required static libraries for linux are included in this repository to avoid library/header version mismatching, but feel free to use your OS' libraries instead.

To build the project simply run
```console
make                           # x86
make config=release_x86_64     # x64
```

### Possible Issues

This library uses OpenSSL built for Ubuntu, which sets the default search path for
root certificates to the one Ubuntu uses. There is a possibility, that this path
is different on other systems. In that case you will need to swap out the libssl.a
and libcrypto.a provided in this repositor with the ones provided by your
operating system.

repository: FredyH/GWSockets

repo_name: FredyH/GWSockets


text:
---
cslItem:
  id: fuchsberger_calia__2020__jmad
  abstract: >-
    JMad is a Java API for the MadX software, which is used at CERN and in many
    other accelerator labs to simulate particle accelerators. JMad plays a key
    role in CERNs accelerator control system as it is bridges numerical
    simulations with the control system of the real CERN accelerators.
  author:
    - family: Fuchsberger
      given: Kajetan
    - family: Calia
      given: Andrea
  citation-key: fuchsberger_calia__2020__jmad
  genre: Java
  issued:
    date-parts:
      - - 2020
        - 12
        - 25
  keyword: "#nosource;accelerator-science-code;collection::pathicles::codes"
  title: JMad
  type: software
  URL: jmad.io
  version: 0.15.3
tags:
  - "#nosource"
  - accelerator-science-code
  - issue:pathicles
  - topic:pathicles/codes
rendered:
  bibliography: |-

      Fuchsberger, K., & Calia, A. 2020. JMad (0.15.3) [Java]. jmad.io

  citation: Fuchsberger & Calia, 2020
bibTex: "@misc{fuchsberger_calia__2020__jmad,\n\tauthor = {Fuchsberger, Kajetan and Calia, Andrea},\n\tyear = {2020},\n\tmonth = {dec 25},\n\ttitle = {JMad},\n\ttype = {Java},\n\thowpublished = {jmad.io},\n}\n\n"
---

branch_name: refs/heads/main


text:
---
layout: text/textblock
---
The content added to a CMS will impact on the accessibility of your site. Even if your CMS functionality is considered ‘accessible’, the content may not be. This applies to both the frontend and backend of a CMS.

A CMS should also help government agencies meet web accessibility guidelines. See [accessibility](/digital-service-standard/9-make-it-accessible/) in the Digital Service Standard.

See also the [Disability Discrimination Act](https://www.humanrights.gov.au/our-work/disability-rights/guides/brief-guide-disability-discrimination-act).

repository: govau/service-manual

gha_language: JavaScript

repo_name: govau/service-manual


text:
# DateRanger
[![Build Status](https://scrutinizer-ci.com/g/obokaman-com/DateRanger/badges/build.png?b=master)](https://scrutinizer-ci.com/g/obokaman-com/DateRanger/build-status/master) [![Code Coverage](https://scrutinizer-ci.com/g/obokaman-com/DateRanger/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/obokaman-com/DateRanger/?branch=master) [![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/obokaman-com/DateRanger/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/obokaman-com/DateRanger/?branch=master)

DateRanger library offer an easy way to create date ranges, allowing to create your own special ranges extending `DateRange` or reuse the basic ones included in the library itself (`Year`, `Month`, `Week` or `Day`). This library was inspired by others like [Calendr](https://github.com/yohang/CalendR) by [Yohan Giarelli](http://yohan.giarel.li/) or [Period](http://period.thephpleague.com/) by [The PHP League](http://thephpleague.com/)

## Installation
DateRanger is available on packagist, so you can easily install with [Composer](https://getcomposer.org/).

Just run the following command:

```bash
$ composer require obokaman/dateranger
```

or include the library in your project's composer.json:

```javascript
    "require": {
        "php": ">=7.2",
        [...]
        "obokaman/dateranger": "^0.1",
        [...]
    },
```

## Example

```php
<?php

include('vendor/autoload.php');

use DateRanger\Period\Year;

$year = new Year();

echo "<h1>{$year->start()->format('Y')}</h1>";
foreach ($year as $month) {
    echo "<table><caption>{$month->start()->format('F')}</caption>";
    echo "<thead><tr><th></th><th>Mon</th><th>Tue</th><th>Wed</th><th>Thu</th><th>Fri</th><th>Sat</th><th>Sun</th></tr></thead><tbody>";
    foreach ($month as $week) {
        echo "<tr><td><small>{$week->start()->format('W')}</small></td>";
        foreach ($week as $day) {
            if (!$day->overlaps($month)) $day_color = '#ddd;';
            elseif ($day->isHoliday()) $day_color = 'red;';
            else $day_color = '#333';

            echo "<td style='border:1px solid #ccc;color:{$day_color}'>";
            echo $day->start()->format('d') . '</td>';
        }
        echo '</tr>';
    }
    echo '</tbody></table>';
}

```

## Basic usage

Library provides several date range objects that extends from `DateRange`. All these objects share some functionality:

* `start()` return a DateTimeImmutable object with the start date for the period.
* `end()` return a DateTimeImmutable object with the end date for the period.
* `getPeriod(string $interval)` returns a DatePeriod object based on the current DateRange, following the given interval in string format (same values accepted by DateInterval constructor).
* `overlaps(DateRange $period)` returns a boolean indicating if period overlaps with other DateRange passed as argument.
* `isCurrent()` returns a boolean indicating if period is the current one: current year, month, week or day, depending on the class being used.
* `equals(DateRange $period)` compares start and end dates between current period and the one passed as argument.

As told above, all date range objects extend from `DateRange`, wich implements `Iterator` and `Countable`, so it's possible to iterate through their "children periods" directly using `foreach` or know how many of them are contained by using `count`.

For instance:

```php
$year = Year::fromYear(2014);
echo count($year); // returns 12.
```

```php
$month = new Month('2014-01-01');
echo count($month) . PHP_EOL; // returns 5 (weeks).

echo $month->start()->format('F') . PHP_EOL; // returns 'January'.
foreach ($month as $week) {
    foreach ($week as $day) {
        if ($month->isOutOfMonth($day)) continue;
        echo $day->start()->format('Y-m-d') . PHP_EOL; // returns 2014-01-01\n [...]
    }
}
```

## Contribute

Comments, feedback and PR are more than welcome!

repository: obokaman-com/DateRanger

repo_name: obokaman-com/DateRanger


text:
Rather than banning a player when they die (like the Vanilla implementation of hardcore does),
create a new world and force everyone to start over. Inspired by [this Reddit post](https://www.reddit.com/r/Minecraft/comments/lp8jjm/we_played_a_multiplayer_hardcore_realm_during/).

**Built for**: Minecraft (Spigot) 1.16.4

## Features
* Create a new set of worlds (Overworld, Nether, End) every time a player dies, and move all players
there (clearing out inventories and resetting expecience)
* Retain past attempts in case someone decided to build some crazy stuff you may want to revisit later
* Customise death messages
* Keep track of death causes for each player (although there is no convenient way of displaying this
yet)
* Close the server on a schedule (i.e. only allow players onto the server at certain times) to ensure
nobody grinds away every night and beats the game single-handedly

Release downloads coming soon(tm). Development builds may be available from
[GitHub Actions](https://github.com/awlck/MultiplayerHardcore/actions/workflows/maven.yml).

[How to configure](https://github.com/awlck/MultiplayerHardcore#config)

repository: awlck/MultiplayerHardcore

repo_name: awlck/MultiplayerHardcore


text:
# Binary Search Trees

## Description

A simple library for AVL binary search trees written in C. Some demo programs are provided to show the library in use.

## Getting Started

Install meson and ninja build system

Clone the git repository:

* git clone <https://github.com/berrym/bst.git>

Build:

* meson build
* ninja -C build

## Executing program

The demos can be found and executed from the build directory, e.g.

* build/test/demo_name

## Authors

Copyright 2021
Michael Berry<EMAIL_ADDRESS>
## License

This project is licensed under the MIT License - see the LICENSE file  for details.

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

repository: berrym/bst

repo_name: berrym/bst


text:
# How to provision a new environment for viim-core

This project uses the open source [capistrano-mb](https://github.com/mattbrictson/capistrano-mb) set of tasks for capistrano to provision new environments. This document contains a quick overview of the provisioning process.

In capistrano terminology, *stage* refers to an environment like `staging` or `production`. These instructions will use the *stage* term for the remainder of the document.

In this document, *provisioning* refers to preparing a server for deployment, including the following steps:

* Installing Nginx, Redis, and PostgreSQL
* Compiling Ruby
* Creating the database
* Setting passwords and other configuration

## Prerequisites

Capistrano runs on your local machine and uses SSH to perform the deployment on the remote server. Therefore:

* The Capistrano gem must be installed (see `README.md` for project setup instructions).
* You must have SSH access to the server.
* Your SSH key must be installed on the server.
* Your account on the server must have `sudo` access.
* Your account must be able to run `sudo` without be prompted for a password. See [How to run sudo command with no password?](http://askubuntu.com/questions/192050/how-to-run-sudo-command-with-no-password).

Furthermore, the server itself must meet the following requirements:

* Ubuntu 14.04 LTS (64 bit).

## 1. Create a new stage (or edit an existing one)

Stages are defined as `.rb` files in the `config/deploy/` directory. The name of the file becomes the name of the stage when executing capistrano commands. For example, the production stage is defined in `config/deploy/production.rb`.

Create a new stage (or modify an existing one to move that stage to a new server address, for example) using the existing stage files as examples. The stage file describes the IP address of the server and other stage-specific information.

## 2. Run the provision command

`bundle exec cap <stage> provision:14_04`

Replace `<stage>` with the name of the stage you wish to provision (e.g. `production`).

You will be prompted to choose passwords and enter other configuration values as the script runs.

It is safe to run the provision command multiple times on the same stage (the scripts are generally idempotent).

## 3. Install a custom SSL key and certificate (optional)

You can upload your SSL key and certificate to the following location:

```
/etc/ssl/viim_core.key
/etc/ssl/viim_core.crt
```

Make sure the files are owned by `root` with permissions `600`.

Once uploaded, restart nginx using this command:

```
sudo service nginx restart
```

## 4. Deploy

Once provisioning is complete, deploy the application using the capistrano instructions in `DEPLOYMENT.md`.

repository: catima/catima

branch_name: refs/heads/development

gha_language: Ruby

repo_name: catima/catima


text:
# Learning to complete images using incomplete data

Most of the image completion and generative models require fully-observed samples to train the network. However, as it's stated in the ambientGAN paper, obtaining high resolution samples can be very expensive or impractical for some applications.

The model in this project combines ideas from the following works:
* AmbientGAN
* Globally and Locally Consistent Image Completion

The AmbientGAN model enables training a generative model directly from noisy or incomplete samples. The generator in the model successfully predicts samples from the true distribution with the use of a measurement function.

On the other hand, the model in Globally and Locally Consistent Image Completion uses fully-observed samples to train the network. The completion network first uses mse loss to pre-train the weights and further uses a discriminator loss to fully train the network.

By combining ideas presented in ambientGAN and GLCIC paper, the network presented in this project learns to fill incomplete regions using only incomplete data (e.g. images randomly blocked by 28 x 28 patch).

## Network
![Alt text](images/network.png?raw=true "network")

## Method
Let's assume that we have incomplete samples and we know the type of noise added to the samples.
Instead of using a random latent vector as an input, the completion network gets masked image as an input. Assuming that the completion network successfully generates the masked region, the generated patch is combined together with the input image using the mask information Xg.

Next, the completed image Xg is fed into the measurement function. As described in the AmbientGAN paper, the measurement function tries to simulate the random measurements on the generated objects Xg. This is possible since we know the type of noise added to the fully-observed images. We can create a measurement function that could simulate the noise added to the image.

The resulting image Yg after the measurement function and the incomplete samples Yr are then passed on to the discriminator that distinguishes real measurements from the fake measurements. As the completion network and the discriminator network are trained adversarially, the completion network learns to generate patches that goes well with the incomplete samples.

## Dataset
[CelebA](http://mmlab.ie.cuhk.edu.hk/projects/CelebA.html) dataset was used in this project. To create incomplete dataset, the original CelebA image was center cropped by 32x32 patch and was resized to 64x64. Then 28x28 patch was added randomly to the image. The blocked regions were filled with ones.

![Alt text](images/dataset.jpg?raw=true "dataset")

## Training
```
$ python train.py
```

To continue training
```
$ python train.py --continue_training=True
```

## Results
![Alt text](images/block_patch_res_1.gif?raw=true "res_1")
![Alt text](images/block_patch_res_2.gif?raw=true "res_2")

## Conclusion
The resulting images show that the presented model learns to fill incompelte regions. There are some images filled with artifacts and inconsistent colors, but in general the completion network learns to generate patches that goes well with the input image.

## Possible Improvements
* Post-processing to fix color inconsistency

## Related Projects
* [AmbientGAN](https://openreview.net/forum?id=Hy7fDog0b)
* [Globally and Locally Consistent Image Completion](http://hi.cs.waseda.ac.jp/~iizuka/projects/completion/en/)


text:
# TODO

- Finish First-run.md
- Move packages list as external files (osx apps, node/gems/brew packages...)
- Dl & install Sublime Package
- Themes (iterm, limechat, ...)
- IE VMs

		curl -s https://raw.github.com/xdissent/ievms/master/ievms.sh | INSTALL_PATH="$HD/Users/MoOx/VMs/ievms" IEVMS_VERSIONS="6 9" bash

`/!\` Eventually install & configure a software like [Synergy](http://synergy-foss.org/download/?list) to be able to control/configure the fresh OS while you are working on another one.

- network sharing
- configure ssh access + change port
- update default Contacts.app template
- configure opendns

- Desktop
  - Customize wallpaper
- Language & Text
  - Edit list as needed
- Spotlight
  - Search Results: Edit list as needed
  - Privacy: Edit list (add others hard drive ?)
- Energy Saver
  - Adapt as you want
- Mouse
  - If you use a mouse : Uncheck "Move content in the direction of finger…"
- Mail, Contacts & Calendars
  - Add your accounts
- Sharing
  - Think to share some files :)

- Sidebar
   - uncheck All my files and iDisk
  - check your computer
- Remove icons you don't want into menu bar by command+click on them and move away

### Activate remote login (for personal use or emergency like thief)

On OS X
Start by changing default SSH port

	subl /private/etc/services

Add your own port

	ssh2             22222/udp  # SSH Remote Login Protocol
	ssh2             22222/tcp  # SSH Remote Login Protocol

Edit

	subl /System/Library/LaunchDaemons/ssh.plist

& Change

	<key>SockServiceName</key>
	<string>ssh2</string>

### [Local mail with postfix relay](http://stevelorek.com/configure-postfix-relay-gmail-osx-lion.html)

### Git(hub) Configuration

[Token info](https://help.github.com/articles/creating-an-oauth-token-for-command-line-use)

	curl -u 'MoOx' -d '{"note":"Update token"}' https://api.github.com/authorizations

Copy your token from the token field & paste your token into ~/.github_token (`echo TOKEN > ./.github_token`), then

	git config --global user.name "Maxime Thirouin"
	git config --global user.email<EMAIL_ADDRESS>	git config --global github.user MoOx
	git config --global github.token $(cat ~/.github_token)

#### [Github SSH Key](https://help.github.com/articles/generating-ssh-keys)

	cd ~/.ssh
	mkdir key_backup
	cp id_rsa* key_backup
	rm id_rsa*
	ssh-keygen -t rsa -C<EMAIL_ADDRESS>	pbcopy < ~/.ssh/id_rsa.pub

[Paste clipboard content as a new key on your Github account settings](https://github.com/settings/ssh)

## First run some apps

Run apps you want to open during startup & activate that option in _Preferences_.

## Setup Internet Accounts

System Preferences > Internet Accounts

### If you have a good Twitter client with notifications

Remove duplicate OS X notifications: System Preferences > Notifications Center > Remove Twitter from center & choose "None" for alert style.

## Setup MenuMeters

System Preferences > MenuMeters

### Setup n64 emulator with high resolution textures

#### With Mupen64Plus

	ln -s ~/Dropbox/Games/n64/hires_textures ~/.local/share/mupen64plus/hires_texture

#### With wine
	brew install wine
	wine ~/Dropbox/Games/n64/project64_1.6.exe
	wine ~/Dropbox/Games/n64/RiceVideoSetup.exe
	ln -s ~/Dropbox/Games/n64/hires_textures ~/.wine/drive_c/Program\ Files/Project64\ 1.6/Plugin"
	wine ~/.wine/drive_c/Program\ Files/Project64\ 1.6/Project64.exe

#### With CrossOver

	# install crossover & project64 then
	ln -s ~/Dropbox/Games/n64/hires_textures ~/Library/Application\ Support/CrossOver/Bottles/project64_1.6.exe/drive_c/Program\ Files/Project64\ 1.6/Plugin

repository: madx/dotfiles

repo_name: madx/dotfiles


text:
How can you use Chrome's DevTools inspector to help you format or position elements?
You can basiclly position anything you want on your page. This lets you have more creative control in the aesthetic appeal of your page.

How can you resize elements on the DOM using CSS?
By using top, left, right, and bottom attributes. Width and height can also be used.

What are the differences between Absolute, Fixed, Static, and Relative positioning? Which did you find easiest to use? Which was most difficult?

I'm not to clear on the exact differences, but I noticed that there were some clear differences in what it did to my boxes. If I put relative, then some of the boxes would scroll down with you. If I put static, then they wouldn't move at all. The easiest one to use was absolute because it made my code work the way I expected it too.

What are the differences between Margin, Border, and Padding?

Margin is the outside space, border is inside the marging and padding the space between the content.

What was your impression of this challenge overall? (love, hate, and why?)
I liked it. It let me learn something important that I needed to know to make my website.


text:
---
hrs_structure:
  division: '1'
  volume: '5'
  title: '15'
  chapter: '261'
  section: 261-15.7
type: hrs_section
tags:
  - Government
menu:
  hrs:
    identifier: HRS_0261-0015_0007
    parent: HRS0261
    name: 261-15.7 Failure to register
weight: 6125
title: Failure to register
full_title: 261-15.7 Failure to register
---
**[§261-15.7] Failure to register.** (a) All aircraft, unless exempted, shall be registered within the time prescribed by rules adopted by the director.

(b) Failure to comply with the registration requirements shall subject the operator of the aircraft to:

(1) A penalty of not more than $100 per aircraft;

(2) The denial of the use of the airport facilities; and

(3) Removal of the aircraft to a location designated pursuant to rules adopted by the director.

(c) The director is authorized to adopt rules pursuant to chapter 91 to effectuate the purposes of sections 261-15.5 to 261-15.7\. [L 1985, c 299, pt of §1]

repository: SamMade/BlueAndKrabby

repo_name: SamMade/BlueAndKrabby


text:
# processhoot
ISN

Download page: https://github.com/marwanpro/processhoot/releases

How to read Source Code:
1) Create a folder: spaceinv_test
2) Download [Source code (zip)] at Download page
3) Copy the source code and data folder in the folder you made previously

repository: notAutomne/processhoot

repo_name: notAutomne/processhoot


text:
# Statistical Learning

The `StatLearn` (short for statistical learning) OnlineStat uses stochastic approximation methods to estimate models that take the form:

``\hat\beta = \argmin_\beta \frac{1}{n} \sum_i f(y_i, x_i'\beta) + \sum_j \lambda_j g(\beta_j),``

where

- ``f`` is a **loss function** of a response variable and linear preditor.
- ``\lambda_j``'s are nonnegative regularization parameters.
- ``g`` is a **penalty function**.

For example, [LASSO Regression](https://en.wikipedia.org/wiki/Lasso_(statistics)) fits this form with:

- ``f(y_i, x_i'\beta) = \frac{1}{2}(y_i - x_i'\beta) ^ 2``
- ``g(\beta_j) = |\beta_j|``

OnlineStats implements interchangeable loss and penalty functions to use for both regression and classification problems.  See the [`StatLearn`](@ref) docstring for details.

## Stochastic Approximation

An important note is that [`StatLearn`](@ref) is unable to estimate coefficients exactly (For precision in regression problems, see [`LinReg`](@ref)).  The upside is that it makes estimating certain models *possible* in an online fashion.

For example, it is **not possible** to get the same coefficients for logistic regression from an O(1)-memory *online* algorithm as you would get from its *offline* counterpart.  This is because the logistic regression likelihood's [sufficient statistics](https://en.wikipedia.org/wiki/Sufficient_statistic) scale with the number of observations.

**All this to say: `StatLearn` lets you do things that would otherwise not be possible at the cost of returning noisy estimates.**

## Algorithms

Besides the loss and penalty functions, you can also plug in a variety of fitting algorithms to `StatLearn`.  Some of these methods are based on the stochastic gradient (gradient of loss evaluated on a single observation).  Other methods are based on the [majorization-minimization (MM)](https://en.wikipedia.org/wiki/MM_algorithm) principle[^1], which offers some guarantees on numerical stability (sometimes at the cost of slower learning).

[^1]: At the moment, the only place to read about the stochastic MM algorithms in detail is [Josh Day's dissertation](https://en.wikipedia.org/wiki/MM_algorithm).  Josh is working on an easier-to-digest introduction to these methods and is also happy to discuss them through GitHub issue/email.

It is a good idea to test out different algorithms on a sample of your dataset.  Plotting the coefficients over time can give you an idea of the stability of the estimates.  Use [`Trace`](@ref), a wrapper around an OnlineStat, to automatically take equally-spaced snapshots of an OnlineStat's state.  Keep in mind the early observations will cause bigger jumps in the cofficients than later observations (based on the learning rate; see [Weights](@ref).  To add further complexity, learning rates (supplied by the `rate` keyword argument) do not affect each algorithm's learning uniformly.  You may need to test different combinations of algorithm/learning rate to find an "optimal" pairing.

```@example statsmodels
using OnlineStats, Plots

# fake data
x = rand(Bool, 1000, 10)
y = x * (1:10) + 10randn(1000)

rate = LearningRate(.8)

o = Trace(StatLearn(SGD(), OnlineStats.l2regloss; rate))
o2 = Trace(StatLearn(MSPI(), OnlineStats.l2regloss; rate))

itr = zip(eachrow(x), y)

fit!(o, itr)
fit!(o2, itr)

plot(
    plot(o, xlab="Nobs", title="SGD Coefficients", lab=nothing),
    plot(o2, xlab="Nobs", title="MSPI Coefficients", lab=nothing),
    link=:y
)
```

gha_language: Julia


text:
# ut3-smallMutators
Simple mutators for ut3

Contains 4 mutators:

*SeparatePlayerSpawns* restricts player spawns to only two (the farthest from each other it can find) and makes each team use only one of them.
In more-than-two team matches, it should isolate only the first team from the rest.

*SetPlayerStats* is your basic stat change mutator, allowing you to set players' health, movement speed, jump speed, number of multiJumps and ragdoll Lifespan. The UPK file should be placed in UTGame\Published\CookedPC.

*StopCullingCorpses* stops ragdolls from disappearing when the camera isn't showing them (they should still disappear after their lifespan time)

*NewBotAdder* adds a console command (used with *mutate*) for instantly adding many bots of a specific type to a team or not.
- command example: *mutate rednewbot reaper 32*

license: Unlicense


text:
# Ninety-Nine Problems in Haskell

This is an adaptation of the [Ninety-Nine Prolog Problems](https://sites.google.com/site/prologsite/prolog-problems) written by Werner Hett at the Berne University of Applied Sciences in Berne, Switzerland.

From the original source:

> The purpose of this problem collection is to give you the opportunity to practice your skills in logic programming. Your goal should be to find the most elegant solution of the given problems. Efficiency is important, but logical clarity is even more crucial. Some of the (easy) problems can be trivially solved using built-in predicates. However, in these cases, you learn more if you try to find your own solution.

> The problems have different levels of difficulty. Those marked with a single asterisk (\*) are easy. If you have successfully solved the preceding problems you should be able to solve them within a few (say 15) minutes. Problems marked with two asterisks (\*\*) are of intermediate difficulty. If you are a skilled Haskell programmer it shouldn't take you more than 30-90 minutes to solve them. Problems marked with three asterisks (\*\*\*) are more difficult. You may need more time (i.e. a few hours or more) to find a good solution.

## Table of Contents

* [Lists](#lists)
* [Arithmetic](#arithmetic)
* [Logic and Codes](#logic-and-codes)
* [Binary Trees](#binary-trees)
* [Multiway Trees](#multiway-trees)
* [Graphs](#graphs)
* [Miscellaneous](#miscellaneous)

## Lists

Lists are recursive type in Haskell.

### [P01](https://github.com/shekhargulati/99-problems/blob/master/haskell/01-lists/P01.hs) **(*) Find the last element of a list**

```haskell
Prelude> last1 ["a","b","c","d"]
"d"
```

We are using `last1` because Haskell already has `last` function.

### [P02](https://github.com/shekhargulati/99-problems/blob/master/haskell/01-lists/P02.hs) **(*) Find the last but one element of a list**

```haskell
Prelude> secondLast [1, 2, 11, 4, 5, 8, 10, 6]
10
```

When list is empty you should get exception as shown below.

```haskell
Prelude> secondLast []
*** Exception: Can't find secondLast element from a list with less than 2 elements
```

When list has one element

```haskell
Prelude> secondLast [1]
*** Exception: Can't find secondLast element from a list with less than 2 elements
```

### [P03](https://github.com/shekhargulati/99-problems/blob/master/haskell/01-lists/P03.hs) **(*) Find the K'th element of a list**

```haskell
Prelude> kth [1,2,3,4,5] 3
4
```

### [P04](https://github.com/shekhargulati/99-problems/blob/master/haskell/01-lists/P04.hs) **(*) Find the number of elements of a list**

```haskell
Prelude> length' [1..5]
5
```

`length'` is a valid function name in Haskell.

### [P05](https://github.com/shekhargulati/99-problems/blob/master/haskell/01-lists/P05.hs) **(*) Reverse a list**

```haskell
Prelude> reverse' [1..5]
[5,4,3,2,1]
```
### [P06](https://github.com/shekhargulati/99-problems/blob/master/haskell/01-lists/P06.hs) **(*) Find out whether a list is a palindrome**

```haskell
Prelude> isPalindrome ["x","a","m","a","x"]
True

Prelude> isPalindrome [1,2,3,4,5]
False
```

### [P07](https://github.com/shekhargulati/99-problems/blob/master/haskell/01-lists/P07.hs) **(\*\*) Flatten a nested list structure**

```haskell
Prelude> flatten (List [Elem 1, List [Elem 2, List [Elem 3, Elem 4], Elem 5]])
[1,2,3,4,5]
```

### [P08](https://github.com/shekhargulati/99-problems/blob/master/haskell/01-lists/P08.hs) **(\*\*) Eliminate consecutive duplicates of list elements**

If a list contains repeated elements they should be replaced with a single copy of the element. The order of the elements should not be changed

```haskell
Prelude> compress ["a", "a", "a", "a", "b", "c", "c", "a", "a", "d", "e", "e", "e", "e"]
["a","b","c","a","d","e"]
```

### [P09](https://github.com/shekhargulati/99-problems/blob/master/haskell/01-lists/P09.hs) **(\*\*) Pack consecutive duplicates of list elements into sublists**

If a list contains repeated elements they should be placed in separate sublists.

```haskell
Prelude> pack ["a", "a", "a", "a", "b", "c", "c", "a", "a", "d", "e", "e", "e", "e"]
[["a","a","a","a"],["b"],["c","c"],["a","a"],["d"],["e","e","e","e"]]
```

### [P10](https://github.com/shekhargulati/99-problems/blob/master/haskell/01-lists/P10.hs) **(*) Run-length encoding of a list**

Use the result of problem 1.09 to implement the so-called run-length encoding data compression method. Consecutive duplicates of elements are encoded as terms [N,E] where N is the number of duplicates of the element E.

```
Prelude> encode ["a", "a", "a", "a", "b", "c", "c", "a", "a", "d", "e", "e", "e", "e"]
[(4,"a"),(1,"b"),(2,"c"),(2,"a"),(1,"d"),(4,"e")]
```

### [P11](https://github.com/shekhargulati/99-problems/blob/master/haskell/01-lists/P11.hs) **(*) Modified run-length encoding**

Modify the result of problem 1.10 in such a way that if an element has no duplicates it is simply copied into the result list. Only elements with duplicates are transferred as [N,E] terms.

```haskell
Prelude> encode_modified ["a", "a", "a", "a", "b", "c", "c", "a", "a", "d", "e", "e", "e", "e"]
[Right (4,"a"),Left "b",Right (2,"c"),Right (2,"a"),Left "d",Right (4,"e")]
```

### [P12](https://github.com/shekhargulati/99-problems/blob/master/haskell/01-lists/P12.hs) **(*) Decode a run-length encoded list**

```haskell
Prelude> decode [Right (4,"a"),Left "b",Right (2,"c"),Right (2,"a"),Left "d",Right (4,"e")]
["a","a","a","a","b","c","c","a","a","d","e","e","e","e"]
```

### [P13](https://github.com/shekhargulati/99-problems/blob/master/haskell/01-lists/P13.hs) **(\*\*) Run-length encoding of a list (direct solution)**

Implement the so-called run-length encoding data compression method directly. i.e. don't explicitly create the sublists containing the duplicates, as in problem P09, but only count them.

```
Prelude> encode_direct ["a", "a", "a", "a", "b", "c", "c", "a", "a", "d", "e", "e", "e", "e"]
[(4,"a"),(1,"b"),(2,"c"),(2,"a"),(1,"d"),(4,"e")]
```

### [P14](https://github.com/shekhargulati/99-problems/blob/master/haskell/01-lists/P14.hs) **(*) Duplicate the elements of a list**

```haskell
Prelude> duplicate ["a","b","c","d"]
["a","a","b","b","c","c","d","d"]
```
### [P15](https://github.com/shekhargulati/99-problems/blob/master/haskell/01-lists/P15.hs) **(\*\*) Duplicate the elements of a list a given number of times**

```haskell
Prelude> duplicate ["a","b","c"] 3
["a","a","a","b","b","b","c","c","c"]
```

### [P16](https://github.com/shekhargulati/99-problems/blob/master/haskell/01-lists/P16.hs) **(\*\*) Drop every N'th element from a list**

```haskell
Prelude> dropEveryNth ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"] 3
["a","b","d","e","g","h","j","k"]
```
### [P17](https://github.com/shekhargulati/99-problems/blob/master/haskell/01-lists/P17.hs) **(*) Split a list into two parts; the length of the first part is given**

```haskell
Prelude> split ["a", "b", "c", "d", "e", "f", "g", "h", "i", "k"] 3
(["a","b","c"],["d","e","f","g","h","i","k"])
```

### [P18](https://github.com/shekhargulati/99-problems/blob/master/haskell/01-lists/P18.hs) **(\*\*) Extract a slice from a list**

```haskell
Prelude> slice ["a", "b", "c", "d", "e", "f", "g", "h", "i", "k"] 3 7
["c","d","e","f"]
```

### [P19](https://github.com/shekhargulati/99-problems/blob/master/haskell/01-lists/P19.hs) **(\*\*) Rotate a list N places to the left**

```haskell
Prelude> rotate ["a", "b", "c", "d", "e", "f", "g", "h"] 3
["d","e","f","g","h","a","b","c"]

Prelude> rotate ["a", "b", "c", "d", "e", "f", "g", "h"] (-2)
["g","h","a","b","c","d","e","f"]
```

### [P20](https://github.com/shekhargulati/99-problems/blob/master/haskell/01-lists/P20.hs) **(*) Remove the K'th element from a list**

```haskell
Prelude> removeAt ["a", "b", "c", "d"] 2
(["a","c","d"],"b")
```

### [P21](https://github.com/shekhargulati/99-problems/blob/master/haskell/01-lists/P21.hs) **(*) Insert an element at a given position into a list**

```haskell
Prelude> insertAt ["a", "b", "c", "d"] 2 "alfa"
["a","alfa","b","c","d"]
```

### [P22](https://github.com/shekhargulati/99-problems/blob/master/haskell/01-lists/P22.hs) **(*) Create a list containing all integers within a given range**

```haskell
Prelude> range 4 9
[4,5,6,7,8,9]
```

### [P23](https://github.com/shekhargulati/99-problems/blob/master/haskell/01-lists/P23.hs) **(\*\*) Extract a given number of randomly selected elements from a list**

```haskell
Prelude> randomSelect ["a", "b", "c", "d", "e", "f", "g", "h"] 3
```

### [P24](https://github.com/shekhargulati/99-problems/blob/master/haskell/01-lists/P24.hs) **(*) Lotto: Draw N different random numbers from the set 1..M**

> Hint: Combine the solutions of problems P22 and P23

```haskell
Prelude> randomSelect_lotto 6 (1,49)
[48,2,42,42,2,8]
```

### [P25](https://github.com/shekhargulati/99-problems/blob/master/haskell/01-lists/P25.hs) **(*) Generate a random permutation of the elements of a list**

> Hint: Use the solution of problem P23

```haskell
Prelude> randomPermutation ["a", "b", "c", "d", "e", "f"]
["b","a","b","c","a","a"]
```

### [P26](https://github.com/shekhargulati/99-problems/blob/master/haskell/01-lists/P26.hs) **(\*\*) Generate the combinations of K distinct objects chosen from the N elements of a list**

```haskell
Prelude> combinations ["a", "b", "c", "d", "e", "f"] 3

[["a","b","c"],["a","b","d"],["a","c","d"],["b","c","d"],["a","b","e"],["a","c","e"],["b","c","e"],["a","d","e"],["b","d","e"],["c","d","e"],["a","b","f"],["a","c","f"],["b","c","f"],["a","d","f"],["b","d","f"],["c","d","f"],["a","e","f"],["b","e","f"],["c","e","f"],["d","e","f"]]
```

### [P27](https://github.com/shekhargulati/99-problems/blob/master/haskell/01-lists/P27.hs) **(\*\*) Group the elements of a set into disjoint subsets**

a) In how many ways can a group of 9 people work in 3 disjoint subgroups of 2, 3 and 4 persons? Write a predicate that generates all the possibilities via backtracking

```haskell
Prelude> length (group3 ["aldo", "beat", "carla", "david", "evi", "flip", "gary", "hugo", "ida"])

1260
```

b) Generalize the above predicate in a way that we can specify a list of group sizes and the predicate will return a list of groups.

```haskell
Prelude> length(group' ["aldo", "beat", "carla", "david", "evi", "flip", "gary", "hugo", "ida"] [2,2,5])

756
```

### [P28](https://github.com/shekhargulati/99-problems/blob/master/haskell/01-lists/P28.hs) **(\*\*) Sorting a list of lists according to length of sublists**

a) We suppose that a list (InList) contains elements that are lists themselves. The objective is to sort the elements of InList according to their **length**. E.g. short lists first, longer lists later, or vice versa.

```haskell
Prelude> lsort [["a", "b", "c"], ["d", "e"], ["f", "g", "h"], ["d", "e"], ["i", "j", "k"], ["m", "n"], ["o"]]

[["o"],["d","e"],["d","e"],["m","n"],["a","b","c"],["f","g","h"],["i","j","k"]]
```

b) Again, we suppose that a list (InList) contains elements that are lists themselves. But this time the objective is to sort the elements of InList according to their **length frequency**; i.e. in the default, where sorting is done in ascending order, lists with rare lengths are placed first, others with a more frequent length come later.

```haskell
Prelude> lfsort [["a", "b", "c"], ["d", "e"], ["f", "g", "h"], ["d", "e"], ["i", "j", "k","l"], ["m", "n"], ["o"]]

[["o"],["i","j","k","l"],["a","b","c"],["f","g","h"],["d","e"],["d","e"],["m","n"]]
```

## Arithmetic

### [P31](https://github.com/shekhargulati/99-problems/blob/master/haskell/02-arithmetic/P31.hs) **(\*\*) Determine whether a given integer number is prime.**

```haskell
Prelude> isPrime 7
True
```

### [P32](https://github.com/shekhargulati/99-problems/blob/master/haskell/02-arithmetic/P32.hs) **(\*\*) Determine the prime factors of a given positive integer.**

```haskell
Prelude> primeFactors 315
[3,3,5,7]

Prelude> primeFactors 33
[3,11]
```

### [P33](https://github.com/shekhargulati/99-problems/blob/master/haskell/02-arithmetic/P33.hs) **(\*\*) Determine the prime factors of a given positive integer (2).**

```haskell
Prelude> primeFactorsMult 315
[[3,2],[5,1],[7,1]]
```

### [P34](https://github.com/shekhargulati/99-problems/blob/master/haskell/02-arithmetic/P34.hs) **(*) A list of prime numbers**

```haskell
Prelude> primeNumbers [7..31]
[7,11,13,17,19,23,29,31]
```

### [P35](https://github.com/shekhargulati/99-problems/blob/master/haskell/02-arithmetic/P35.hs) **(\*\*) Goldbach's conjecture**

```haskell
Prelude> goldbach 28
[5,23]
```

### [P36](https://github.com/shekhargulati/99-problems/blob/master/haskell/02-arithmetic/P36.hs) **(\*\*) A list of Goldbach compositions.**

Given a range of integers by its lower and upper limit, print a list of all even numbers and their Goldbach composition.

```haskell
Prelude> goldbach_list [9..20]
[(10,[3,7]),(12,[5,7]),(14,[3,11]),(16,[3,13]),(18,[5,13]),(20,[3,17])]
```

In most cases, if an even number is written as the sum of two prime numbers, one of them is very small. Very rarely, the primes are both bigger than say 50. Try to find out how many such cases there are in the range 2..3000.

```haskell
Prelude> goldbach_list1 50 [1..2000]
[(992,[73,919]),(1382,[61,1321]),(1856,[67,1789]),(1928,[61,1867])]
```
### [P37](https://github.com/shekhargulati/99-problems/blob/master/haskell/02-arithmetic/P37.hs) **(\*\*) Determine the greatest common divisor of two positive integer numbers.**

```haskell
Prelude> gcd' 36 63
9
```

### [P38](https://github.com/shekhargulati/99-problems/blob/master/haskell/02-arithmetic/P38.hs) **(*) Determine whether two positive integer numbers are coprime.**

```haskell
Prelude> coprime 25 64
True
```

### [P39](https://github.com/shekhargulati/99-problems/blob/master/haskell/02-arithmetic/P39.hs) **(\*\*) Calculate Euler's totient function phi(m).**

```haskell
Prelude> totient_phi 10
4
```

### [P40](https://github.com/shekhargulati/99-problems/blob/master/haskell/02-arithmetic/P40.hs) **(\*\*) Calculate Euler's totient function phi(m) (2).**

See problem P39 for the definition of Euler's totient function. If the list of the prime factors of a number m is known in the form of problem 2.03 then the function phi(m) can be efficiently calculated as follows: Let `[[p1,m1],[p2,m2],[p3,m3],...]` be the list of prime factors (and their multiplicities) of a given number m. Then phi(m) can be calculated with the following formula:

`phi(m) = (p1 - 1) * p1**(m1 - 1) * (p2 - 1) * p2**(m2 - 1) * (p3 - 1) * p3**(m3 - 1) * ...`

Note that a**b stands for the b'th power of a.

```
Prelude> phi 10
4
Prelude> phi 99
60
```

> Also you can import modules defined in 01-lists by starting ghci using the command `ghci -i../01-lists`

### [P41](https://github.com/shekhargulati/99-problems/blob/master/haskell/02-arithmetic/P41.hs) **(*) Compare the two methods of calculating Euler's totient function.**

Use the solutions of problems P39 and P40 to compare the algorithms. Take the number of logical inferences as a measure for efficiency. Try to calculate `phi(10090)` as an example.

### [P46](https://github.com/shekhargulati/99-problems/blob/master/haskell/03-logic-and-codes/P46.hs) **(\*\*) Truth tables for logical expressions.**

Define predicates and/2, or/2, nand/2, nor/2, xor/2, impl/2 and equ/2 (for logical equivalence) which succeed or fail according to the result of their respective operations; e.g. and(A,B) will succeed, if and only if both A and B succeed. Note that A and B can be Prolog goals (not only the constants true and fail).

A logical expression in two variables can then be written in prefix notation, as in the following example: and(or(A,B),nand(A,B)).

Now, write a predicate table/3 which prints the truth table of a given logical expression in two variables.

```
table (\a b -> (and' a (or' a b)))
[(True,True,True),(True,False,True),(False,True,False),(False,False,False)]
```

### [P47](https://github.com/shekhargulati/99-problems/blob/master/haskell/03-logic-and-codes/P47.hs) **(*) Truth tables for logical expressions(2).**

Skipping this problem for now.

### [P48](https://github.com/shekhargulati/99-problems/blob/master/haskell/03-logic-and-codes/P48.hs) **(\*\*) Truth tables for logical expressions(3).**

Skipping this problem for now.

### [P49](https://github.com/shekhargulati/99-problems/blob/master/haskell/03-logic-and-codes/P49.hs) **(\*\*) Gray code.**

An n-bit Gray code is a sequence of n-bit strings constructed according to certain rules. For example,
```
n = 1: C(1) = ['0','1'].
n = 2: C(2) = ['00','01','11','10'].
n = 3: C(3) = ['000','001','011','010','110','111','101','100'].
```

```haskell
Prelude> gray 3
["000","001","011","010","110","111","101","100"]
```


text:
---
layout: post
title: Nginx + Passenger on Gentoo
tags: ["technique", "ops"]
---
From the "niche interest" desk:

Nginx builds all of it's components into one executable (they argue that it's
necessary for their level of speed and security). Gentoo lets you configure
software all kinds of ways, so it's pretty easy to configure exactly which of
the myriad of modules you want to install.  But like every Linux distro,
they've had an ongoing tete-a-tete with Rubygems, so Passenger isn't supported
out of the box in the Gentoo set of options.  Passenger's idea of installing
itself  into Nginx is to recompile the whole thing
- *without* respecting the modules that were already installed.

It's a headache, and I've given up trying to assign blame - I think probably
everyone solved the (very large) problems in front of  them, and it happens
that their solutions don't interact well. (Gentoo Rubyists (and yes, I'm sure
the plural there is optimistic): I'm liking chruby + direnv + bundler as an
adjunct to eselect.)

But, there's a couple of hidden outs that make it entirely feasible to get a
respectable nginx/passenger deploy going on Gentoo, which I'll record here for
my own purposes, at least.

{% highlight bash %}
gem install passenger
mkdir /etc/portage/env
echo "NGINX_ADD_MODULES='$(passenger-config --nginx-addon-dir)'" > /etc/portage/env/nginx-passenger
echo "www-servers/nginx nginx-passenger" >> /etc/portage/package.env
emerge nginx
{% endhighlight %}

In /etc/nginx/nginx.conf, add:

{% highlight bash %}
passenger_root /usr/local/lib64/ruby/gems/2.0.0/gems/passenger-4.0.29/;
passenger_ruby /usr/bin/ruby20;
{% endhighlight %}

repository: nyarly/blog

gha_language: Sass

gha_license_id: NOASSERTION

repo_name: nyarly/blog


text:
# iro.js react component

> The iro.js color picker wrapped in a react component

![preview](http://assets.basithkunimal.com/color-picker.gif)

Here's a [working demo](http://color-picker.basithkunimal.com/)

[![NPM](https://img.shields.io/npm/v/irojs-react.svg)](https://www.npmjs.com/package/irojs-react) [![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com) [![build](https://github.com/basith374/irojs-react/actions/workflows/main.yml/badge.svg)](https://github.com/basith374/irojs-react/actions/workflows/main.yml)

## Install

```bash
npm install --save irojs-react
```

## Usage

```jsx
import React, { Component } from 'react'

import ColorPicker from 'irojs-react'

class Example extends Component {
  render() {
    return <ColorPicker setColor={(color) => console.log(color)} />
  }
}
```

## License

MIT © [basith374](https://github.com/basith374)


text:
![EdynLogo](https://xissburg.com/images/EdynLogo.svg)

_Edyn_ (pronounced like "eh-dyin'") stands for _Entity Dynamics_ and it is a real-time physics engine organized as an ECS (Entity-Component System) using the amazing [EnTT](https://github.com/skypjack/entt) library. The main goals of this library is to be multi-threaded and to support networked and distributed physics simulation of large dynamic worlds.

It is still in an early stage of development and is not yet ready for use. Feel free to explore and contribute meanwhile.

Examples are located in a separate repository: [Edyn Testbed](https://github.com/xissburg/edyn-testbed)

# Build Instructions

## Requirements

A compiler with C++17 support is required, along with `CMake` version 3.12.4 or above.

## Steps

In the _Edyn_ directory:

```
$ mkdir build
$ cd build
$ conan install ../conanfile.txt
$ cmake ..
$ make
```

# The ECS approach

Typical physics engines will offer explicit means to create objects such as rigid bodies, whereas in _Edyn_ object creation is implicit due to the entity-component design. A rigid body is created from the bottom up, by associating its parts to a single entity, such as:

```cpp
entt::registry registry;
auto entity = registry.create();
registry.emplace<edyn::dynamic_tag>(entity);
registry.emplace<edyn::position>(entity, 0, 3, 0);
registry.emplace<edyn::orientation>(entity, edyn::quaternion_axis_angle({0, 1, 0}, edyn::to_radians(30)));
registry.emplace<edyn::linvel>(entity, edyn::vector3_zero);
registry.emplace<edyn::angvel>(entity, 0, 0.314, 0);
auto mass = edyn::scalar{50};
registry.emplace<edyn::mass>(entity, mass);
auto &shape = registry.emplace<edyn::shape>(entity, edyn::box_shape{0.5, 0.2, 0.4});
registry.emplace<edyn::inertia>(entity, shape.inertia(mass));
registry.emplace<edyn::material>(entity, 0.2, 0.9); // Restitution and friction.
registry.emplace<edyn::linacc>(entity, edyn::gravity_earth);
```

There's no explicit mention of a rigid body in the code, but during the physics update all entities that have a combination of the components assigned above will be treated as a rigid body and their state will be updated over time as expected. The update may be carried as follows:

```cpp
// Apply gravity acceleration, increasing linear velocity.
auto view = registry.view<edyn::linvel, const edyn::linacc, const edyn::dynamic_tag>();
view.each([dt] (auto entity, edyn::linvel &vel, const edyn::linacc &acc, [[maybe_unused]] auto) {
  vel += acc * dt;
});
// ...
// Move entity with its linear velocity.
auto view = registry.view<edyn::position, const edyn::linvel, const edyn::dynamic_tag>();
view.each([dt] (auto entity, edyn::position &pos, const edyn::linvel &vel, [[maybe_unused]] auto) {
  pos += vel * dt;
});
// ...
// Rotate entity with its angular velocity.
auto view = registry.view<edyn::orientation, const edyn::angvel, const edyn::dynamic_tag>();
view.each([dt] (auto entity, edyn::orientation &orn, const edyn::angvel &vel, [[maybe_unused]] auto) {
  orn = edyn::integrate(orn, vel, dt);
});
```

Assigning each component to every rigid body entity individually quickly becomes a daunting task which is prone to errors, thus utility functions are provided for common tasks such as creating rigid bodies:

```cpp
// Equivalent to implicit example above.
auto def = edyn::rigidbody_def();
def.kind = edyn::rigidbody_kind::rb_dynamic;
def.position = {0, 3, 0};
def.orientation = edyn::quaternion_axis_angle({0, 1, 0}, edyn::to_radians(30));
def.linvel = edyn::vector3_zero;
def.angvel = {0, 0.314, 0};
def.mass = 50;
def.shape_opt = {edyn::box_shape{0.5, 0.2, 0.4}}; // Shape is optional.
def.update_inertia();
def.restitution = 0.2;
def.friction = 0.9;
def.gravity = edyn::gravity_earth;
auto entity = edyn::make_rigidbody(registry, def);
```

# Basics

_Edyn_ is built as a multi-threaded library from the ground up which requires initializing its worker threads on start-up invoking `edyn::init()`, and then a `edyn::world` must be created before setting up the scene:

```cpp
#include <entt/entt.hpp>
#include <edyn/edyn.hpp>

edyn::init();
entt::registry registry;
auto &world = registry.set<edyn::world>(registry);

// Create rigid bodies and constraints...

// Call `edyn::world::update()` periodically in your main loop somewhere.
for (;;) {
  world.update();
  // Do something with the results, e.g. render scene.
  // ...
}
```

When `edyn::world::update()` is called, it processes any pending changes, creates/destroys workers if needed, dispatches messages to workers, reads and processes messages from workers which are merged into the `entt::registry`, perparing the entities and components to be rendered right after.

Due to its multi-threaded nature, all changes to relevant components in the main `entt::registry` need to be propagated to the worker threads. The `edyn::world` doesn't automatically pick up these changes, thus it's necessary to notify it either by calling `edyn::world::refresh()` or assigning a `edyn::dirty` component to the entity and calling some of its functions such as `edyn::dirty::updated()` (e.g. `registry.emplace<edyn::dirty>(entity).updated<edyn::position, edyn::linvel>()`).

# Documentation

See [docs/Design.md](https://github.com/xissburg/edyn/blob/master/docs/Design.md) to learn more about the engine's planned architecture.


text:
# VMRay Sandbox Analyzer Function for IBM Resilient

## Table of Contents
  - [Overview](#overview)
  - [Installation](#installation)
  - [Function Inputs](#function-inputs)
  - [Function Output](#function-output)
  - [Pre-Process Script](#pre-process-script)
  - [Post-Process Script](#post-process-script)
  - [Rules](#rules)

---

## Release Notes

### v1.0.1
* App Host support
### v1.0.0
* Initial Release

---
## Overview

**This package contains a function that executes a VMRay Malware Sandbox Analysis using VMRay Cloud API. Also included are two example workflows and two example rules that demonstrate how to use this function.**

 ![screenshot](./screenshots/workflow_attachment.jpeg)

* The attachment or artifact to be analyzed must be a file.
* The report only supports JSON format. HTML and PDF are not supported.
* Supports a proxy. Add your proxy details to the [integrations] section of the `app.config` file.

## Requirements

* Resilient platform >= `v35.0.0`
* An Integration Server running `resilient_circuits>=30.0.0`

  * To set up an Integration Server see: [ibm.biz/res-int-server-guide](https://ibm.biz/res-int-server-guide)
---
## Installation

### App Format

The app .zip file is in a container format and requires a Resilient platform configured with an App Host.

The app tar.gz file is an extension format and requires a Resilient platform configured with an integration server.

### App Host
For a complete guide on how to configure App Host and install apps in the Resilient platform, please reference the Resilient Apps topic in the Knowledge Center. [Knowledge Center](https://www.ibm.com/support/knowledgecenter/SSBRUQ).

All the components for running this integration in a container already exist when using the App Host app.

To install,

* Navigate to Administrative Settings and then the Apps tab.
* Click the Install button and select the downloaded file: app-fn_vmray_analyzer-x.x.x.zip.
* Go to the Configuration tab and edit the app.config file, editing the vmray_api_key and making any additional setting changes.

---
  | Config | Required | Example | Description |
  | ------ | :------: | ------- | ----------- |
  | **vmray_api_key** | Yes | `` | *VMRay Analyzer API Key* |
  | **vmray_analyzer_url** | Yes | `https://cloud.vmray.com` | *VMRay Server URL* |
  | **vmray_analyzer_report_request_timeout** | Yes | `60` | *Amount of time in seconds to wait until checking if the report is ready* |

---
### Integration Server

* Download the `app-fn_vmray_analyzer-x.x.x.zip` file.
* Copy the `.zip` to your Integration Server and SSH into it.
* **Unzip** the package:
  ```
  $ unzip app-fn_vmray_analyzer-x.x.x.zip
  ```
* **Install** the package:
  ```
  $ pip install fn_vmray_analyzer-x.x.x.tar.gz
  ```
* Import the **configurations** into your app.config file:
  ```
  $ resilient-circuits config -u -l fn-vmray-analyzer
  ```
* Import the fn_vmray_analyzer **customizations** into the Resilient platform:
  ```
  $ resilient-circuits customize -y -l fn-vmray-analyzer
  ```
* Open the config file, scroll to the bottom and edit your fn_vmray_analyzer configurations:
  ```
  $ nano ~/.resilient/app.config
  ```
* Download the `fn_vmray_analyzer.zip`.
* Copy the `.zip` to your Integration Server and SSH into it.
* **Unzip** the package:
  ```
  $ unzip fn_vmray_analyzer-x.x.x.zip
  ```
* **Change Directory** into the unzipped directory:
  ```
  $ cd fn_vmray_analyzer-x.x.x

  ```
* **Install** the package:
  ```
  $ pip install fn_vmray_analyzer-x.x.x.tar.gz
  ```
* Import the **configurations** into your app.config file:
  ```
  $ resilient-circuits config -u -l fn-vmray-analyzer
  ```
* Import the fn_vmray_analyzer **customizations** into the Resilient platform:
  ```
  $ resilient-circuits customize -y -l fn-vmray-analyzer
  ```
* Open the config file, scroll to the bottom and edit your fn_vmray_analyzer configurations:
  ```
  $ nano ~/.resilient/app.config
  ```
  | Config | Required | Example | Description |
  | ------ | :------: | ------- | ----------- |
  | **vmray_api_key** | Yes | `` | *VMRay Analyzer API Key* |
  | **vmray_analyzer_url** | Yes | `https://cloud.vmray.com` | *VMRay Server URL* |
  | **vmray_analyzer_report_request_timeout** | Yes | `60` | *Amount of time in seconds to wait until checking if the report is ready* |

* **Save** and **Close** the app.config file.
* [Optional]: Run selftest to test the Integration you configured:
  ```
  $ resilient-circuits selftest -l fn-vmray-analyzer
  ```
* **Run** resilient-circuits or restart the Service on Windows/Linux:
  ```
  $ resilient-circuits run
  ```
  ### Uninstall
  If using an integration server, you can uninstall your app as follows:

* SSH into your Integration Server.
* **Uninstall** the package:
  ```
  $ pip uninstall fn-vmray-analyzer
  ```
* Open the config file, scroll to the [fn_vmray_analyzer] section and remove the section or prefix `#` to comment out the section.
* **Save** and **Close** the app.config file.

---

## Function Inputs:

| Function Name | Type | Required | Example  | Info |
| --------- | :---------: | ------------------ | ------| ----|
| `incident_id` | `Number` | Yes | `1001` | The ID of the current Incident|
| `attachment_id` | `Number` | No | `5` | The ID of the Attachment to be analyzed|
| `artifact_id` | `Number` | No | `6` | The ID of the Artifact to be analyzed
| `analyzer_report_status` | `Boolean` | Yes | `No` | Has the analysis report generated successfully. Options are: `Yes` or `No` |
---

## Function Output:
```python
results = {
                "analysis_report_status": analysis_report_status,
                "incident_id": incident_id,
                "artifact_id": artifact_id,
                "attachment_id": attachment_id,
                "sample_final_result": sample_final_result
            }

```
---

## Pre-Process Script:
Example: VMRAY Sandbox Analyzer [Attachment]

```
inputs.incident_id = incident.id
inputs.attachment_id = attatchment.id
```
Example: VMRAY Sandbox Analyzer [Artifact]

```
inputs.incident_id = incident.id
inputs.artifact_id = artifact.id
```

---

## Post-Process Script:
This example adds a Note to the Incident and color codes the `analysis_status` depending if it was **malicious** or **clean**

```
def  font_color(vti_score,sample_severity):
  color = "green"
  try:
    if sample_severity in ["malicious"] or int(vti_score) >= 75:
      color = "red"
    elif sample_severity in ["blacklisted","suspicious"] or int(vti_score) >= 50:
      color = "yellow"
  except:
      pass
  return color

if not results.analysis_report_status:
 noteText = u"""Successful submit <b>{}</b> to VMRay Cloud Analyzer.However it will take time to generate an analysis report, please submit it again later. <br>""".format(attachment.name)

else:
 noteText = u"""Successful submit <b>{}</b> to VMRay Analyzer.Check the results below: <br>""".format(attachment.name)

 for sample in results.sample_final_result:
   noteText += u"""-----------------------------------------------------------------------"""
   color = font_color(sample["sample_report"]["sample_score"],sample["sample_report"]["sample_last_reputation_severity"])
   noteText += u"""<br>VMRay Sandbox Analysis: <b>{sample_filename}</b> complete.<br>
                   VMRAY Online Attachment: <a href={sample_online_report}>{sample_online_report}</a><br>
                   VMRay Analyzer result:  VTI Score: <b style= "color:{color}">{sample_vti_score}</b>,  Severity: <b style= "color:{color}">{sample_severity}</b> <br>
               """.format(sample_filename=sample["sample_report"]["sample_filename"],
                           sample_online_report=sample["sample_report"]["sample_webif_url"],
                           color = color,
                           sample_vti_score = sample["sample_report"]["sample_score"],
                           sample_severity = sample["sample_report"]["sample_last_reputation_severity"])

   noteText += u"""<br>| analysis_id | analysis_job_started | analysis_vti_score | analysis_severity |<br>"""

   for analysis in sample["sample_analysis_report"]:
     color = font_color(analysis["analysis_vti_score"],analysis["analysis_severity"])
     noteText += u"""| <a href={analysis_link}>  {analysis_id} </a> | {analysis_job_started} |  <b style= "color:{color}"> {analysis_vti_score}</b>  | <b style= "color:{color}">{analysis_severity}</b> |<br>
                 """.format(analysis_link=analysis["analysis_webif_url"],
                           analysis_id=analysis["analysis_id"],
                           analysis_job_started=analysis["analysis_job_started"],
                           analysis_vti_score=analysis["analysis_vti_score"],
                           analysis_severity=analysis["analysis_severity"],
                           color=color)

   reputations = [str(reputation["reputation_lookup_severity"]) for reputation in sample["sample_reputation_report"]]

   if "malicious" in reputations:
     color = "red"
     reputation_lookup_severity = "malicious"
   elif "suspicious" in reputations:
     color = "yellow"
     reputation_lookup_severity = "suspicious"
   elif "blacklisted" in reputations:
     color = "yellow"
     reputation_lookup_severity = "blacklisted"
   elif "not_suspicious" in reputations:
     color = "green"
     reputation_lookup_severity = "not_suspicious"
   elif "whitelisted" in reputations:
     color = "green"
     reputation_lookup_severity = "whitelisted"
   else:
     color = "green"
     reputation_lookup_severity = "unknown"

   noteText += u"""Reputation lookup result:  <b style= "color:{color}">{reputation_lookup_severity} </b> <br>""".format(color=color, reputation_lookup_severity=reputation_lookup_severity)

incident.addNote(helper.createRichText(noteText))
```

Example of adding a incident note from post-processing scripts:

 ![screenshot](./screenshots/results_addnote.png)
---

## Rules
| Rule Name | Object Type | Workflow Triggered |
| --------- | :---------: | ------------------ |
| Example: VMRay Sandbox Analysis [Artifact]| `Artifact` | `Example: VMRay Sandbox Analyzer [Artifact]` |

![screenshot](./screenshots/rule_artifact.jpeg)

---
| Rule Name | Object Type | Workflow Triggered |
| --------- | :---------: | ------------------ |
| Example: VMRay Sandbox Analyzer [Attachment]| `Attachment` | `Example: VMRay Sandbox Analyzer [Attachment]` |

![screenshot](./screenshots/rule_attachment.jpeg)

---

repository: ibmresilient/resilient-community-apps

gha_language: Python

repo_name: ibmresilient/resilient-community-apps


text:
[![Windows Build status](https://ci.appveyor.com/api/projects/status/bfwtu7orjfwxookx?svg=true)](https://ci.appveyor.com/project/severin-lemaignan/boxology)

Boxology
========

**Work in progress!! Do not expect much yet!**

An editor to prototype cognitive architectures (with cognitive robotics in
mind!).

![A dummy architecture](doc/example_editor01.png)

The UI has been build on top of
[qt5-node-editor](https://github.com/rochus/qt5-node-editor) by Nicolai Waniek.
Thanks to him!

Main features
-------------

- Convenient UI to create nodes for each cognitive processes;
- Connect them together;
- Label them with their main cognitive role;
- Save/load in a simple JSON format.
- Export to SVG and LaTeX (TikZ)

repository: boxology/boxology

repo_name: boxology/boxology


text:
# azure_devops_sdk.model.TaskAgentPoolMaintenanceJob

## Load the model package
```dart
import 'package:azure_devops_sdk/api.dart';
```

## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**definitionId** | **int** | The maintenance definition for the maintenance job | [optional] [default to null]
**errorCount** | **int** | The total error counts during the maintenance job | [optional] [default to null]
**finishTime** | [**DateTime**](DateTime.md) | Time that the maintenance job was completed | [optional] [default to null]
**jobId** | **int** | Id of the maintenance job | [optional] [default to null]
**logsDownloadUrl** | **String** | The log download url for the maintenance job | [optional] [default to null]
**orchestrationId** | **String** | Orchestration/Plan Id for the maintenance job | [optional] [default to null]
**pool** | [**TaskAgentPoolReference**](TaskAgentPoolReference.md) |  | [optional] [default to null]
**queueTime** | [**DateTime**](DateTime.md) | Time that the maintenance job was queued | [optional] [default to null]
**requestedBy** | [**IdentityRef**](IdentityRef.md) |  | [optional] [default to null]
**result** | **String** | The maintenance job result | [optional] [default to null]
**startTime** | [**DateTime**](DateTime.md) | Time that the maintenance job was started | [optional] [default to null]
**status** | **String** | Status of the maintenance job | [optional] [default to null]
**targetAgents** | [**List<TaskAgentPoolMaintenanceJobTargetAgent>**](TaskAgentPoolMaintenanceJobTargetAgent.md) |  | [optional] [default to []]
**warningCount** | **int** | The total warning counts during the maintenance job | [optional] [default to null]

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


text:
# Kuona API

FIXME

## Prerequisites

You will need [Leiningen][] 2.0.0 or above installed.

[leiningen]: https://github.com/technomancy/leiningen

## Testing

	lein midje
or
	lein midje :autotest

Autotest is a great feature. Every code change is immediately loaded and tests run - really fast feedback.

## Running

To start a web server for the application, run:

	lein run -- -c kuona-properties.json
or
	lein uberjar
	java -jar target/environment-service-0.0.1-standalone.jar -c kuona-properties.json

For local development, the [kuona-project](https://github.com/kuona/kuona-project) with a dev-config. You can use the following command to run the service for development

  lein run -- -c ../dev-config.json

Copyright © 2016 Kuona.io

repository: xuv/kuona-project

repo_name: xuv/kuona-project


text:
---
layout: post
title: Leetcode[110] Balanced Binary Tree
---
###Task1
Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

###Python
```python
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if not root:
            return True
        l = self.findHigh(root.left)
        r = self.findHigh(root.right)
        if abs(l - r) > 1:
            return False
        return self.isBalanced(root.left) and self.isBalanced(root.right)
    def findHigh(self, root):
        if not root:
            return 0
        l = self.findHigh(root.left)
        r = self.findHigh(root.right)
        return max(l, r) + 1
```
###Java

```java
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {

    public int height(TreeNode root) {
        if (root == null) {
            return 0;
        }

        int left = height(root.left);
        int right = height(root.right);
        //ps: there is in fact three condition: left balance, right balance, and height difference less than 1
        if (left == -1 || right == -1 || Math.abs(left - right) > 1) {
            return -1;
        }
        return Math.max(left, right) + 1;
    }

    public boolean isBalanced(TreeNode root) {
        return height(root) != -1;
    }
}

```

###Points

* O(n)
* Divide and conquer
* Height === maximum depth


text:
# Beatson OS X Bootstrapper #

This collection of scripts are used to quickly set up new OS X computers in the Beatson Lab.
* Installs `tcsh` as the default shell
* Installs software managers Homebrew and Conda
* Sets OS X system settings
* Installs general software and tools using Homebrew
* Installs managed bioinformatics tool environment using Conda

## Usage ##

* Download all files to a local directory
* (Optional) edit `brew.file` and/or `osx_defaults.sh` for personal preference
* In terminal, run `bootstrap_beatson.sh`
* If prompted, restart computer

### File Information ###
* bootstrap_beatson.sh
    * the actual bootstrap script. Run this on a new computer to bootstrap.
* brew.file
    * contains the homebrew recipes and casks to install. Collection of useful command line tools and general software applications. Called from `bootstrap_beatson.sh`. Can be updated to add new programs as desired and
* conda_installer.sh
    * Used to setup the Conda environments managed in the Beatson Ansible repository. Rerun to update or replace local environments (interactive).
* osx_defaults.sh
    * a separate script that sets a number of operation system systems for improved experience. Called from `bootstrap_beatson.sh`. Edit this as desired (a number of additional tweaks are documented within and commented out by default).
* readme.md
    * this file

### Author ###
Initially developed by Thom Cuddihy (QFAB, 2017) while embedded with the Beatson Lab


text:
---
title: Authorization
---

A package providing a base authorizations class to help check which permissions a user has.

[![Version](https://img.shields.io/npm/v/@availity/authorizations-core.svg?style=for-the-badge)](https://www.npmjs.com/package/@availity/authorizations-core)

## Installation

### NPM

```bash
npm install @availity/authorizations-axios @availity/api-axios
```

### Yarn

```bash
yarn add @availity/authorizations-axios @availity/api-axios
```

## Usage

`AvAuthorizations` uses `AvPermissionsApi` and `AvRegionsApi` which can be found in [@availity/api-axios](/api/axios-resources/). You do not need to provide these yourself.

```js
import AvAuthorizations from '@availity/authorizations-axios';

const authApi = new AvAuthorizations();
```

## Methods

For all methods, if no region is passed in, defaults to current region.

### `isAuthorized(permissionId, region)`

Returns true or false if the current user has access to the permission in the given region.

### `isAnyAuthorized(permissionIds, region)`

Returns true or false if the current user has access to any of the permissions in the given region.

### `getPermission(permissionId, region)`

Returns the permission object for the given permissionId and region.

### `getPermissions(permissionIds, region)`

Returns an array of permission objects for the permissionIds in the given region.

### `getOrganizations(permissionId, region)`

Returns the organizations array for the permissionId. Will be empty if not authorized.

### `getPayers(permissionId, organizationId, region)`

Check the permissionId for an organization with `organizationId`. Returns its `resources` or an empty array.

repository: Availity/sdk-js

repo_name: Availity/sdk-js


text:
# NAME

Owenslib::Prog::Utils - General programming utilities for Perl.

# SYNOPSIS

# DESCRIPTION

# VERSION

1.07

# METHODS

## new()

Create a new object.

## Timestamps

### get\_time\_local($epoch\_secs)

Return the local timestamp in YYYY-mm-ddTHH:MM:SS format.

$epoc\_secs defaults to now.

### get\_date\_local($epoch\_secs)

Return the local date in YYYY-mm-dd format.

$epoc\_secs defaults to now.

### get\_date\_local\_yesterday()

Return the local date for yesterday in YYYY-mm-dd format.

### get\_time\_utc($epoch\_secs)

Return the UTC timestamp for $epoch\_secs in YYYY-dd-mmTHH:MM::SS format.

### get\_date\_utc($epoch\_secs)

Return the UTC date for $epoch\_secs in YYYY-dd-mm format.

### ($file\_path, line\_num) = get\_file\_line\_num()

Return the path to the file and the line number where this method is called
(useful for logging).

### ($filename, line\_num) = get\_filename\_line\_num()

Return the name of the file (without the directory part) and the line number
where this method is called (useful for logging).

## Logging

### config\_log($opts, $log\_level\_str)

Like `setup_logging()`, but with different default behaviors.

If no options are passed to countermand the defaults, the following options are
assumed to be set to true:

- `log_no_prog`
- `log_no_pid`
- `log_norm_ts`
- `log_src`

The following additional options are supported to countermand the above
defaults:

- `log_prog`
- `log_pid`
- `log_short_ts`
- `log_no_src`

Other options provided act as they do when passed to `setup_logging()`.

### setup\_logging($opts, $log\_level\_str)

Set up logging with the log level set to
`$log_level_str`. `$opts` is an options hash. If the key `log`
is present, its value is treated as a log file to write to,
unless the value is `*STDOUT` or `*STDERR`, in which case those
log lines will be written to those file handles.

This method also sets up 8 functions in the caller's environment
for logging:  `out_log($fmt, @args)`, and
`out_log_$str($fmt, @args)`, where `$str` is each of the log levels listed
below. `$fmt` is the same as for `printf()`. `out_log_tee($fmt, @ARGS)`
logs to the configured log plus standard error.

Log levels are (in ascending order of criticality):

- debug
- info
- notice
- warn
- err
- crit
- alert
- emerg

There is also `out_log_err_ret($rv, $fmt, @rest)` that will
return $rv when done. This is useful for returning from a
function with an error value without using an extra line of code.

#### Options

The following options in $opts change the logging behavior:

- `log_src`: Add the source file name to each log line.
- `log_norm_ts`: Use a more normal logging timestamp instead of stripping all delimiters.
- `log_micro_ts`: Include microseconds in the timestamp.
- `log_no_pid`: Don't including the process ID in the log line.
- `log_no_prog`: Don't include the program name in the log line.
- `log_utc_ts`: Log timestamps in UTC.

## Configuration file parsing

INI-style configuration parsing.

### my $data = setup\_conf($type, $file)

Reads the INI `$file` provided (file path or file handle). Returns the
data as a hash of all keys. Keys are prefixed by the section and a period ('.').
The default section is `global`.

`$type` is a namespace used to store your configuration in the Utils object.
You can retrieve individual fields later using `get_conf_val()` if you
so choose.

### `get_conf_val($type, $field)`

Retrieve the value association with the key `$field` from the configuration
set up with type `$type`.

###

Reads the INI `$file` provided (file path or file handle). Returns the
data as a hash of all keys. Keys are prefixed by the section and a period ('.').
The default section is `global`.

## File I/O

### open\_file\_w($path)

Open the file in read-only mode. Compresses gzip, bzip2, and xz
files based on the filename extention if the corresponding
executables are available.

### open\_file\_ro($path)

Open the file in read-only mode. Decompresses gzip, bzip2, and xz
files based on the filename extention if the corresponding
executables are available.

### get\_gzip()

Look for the gzip executable in the standard places and return the path.

### get\_bzip2()

Look for the bzip2 executable in the standard places and return the path.

### get\_xz()

Look for the xz executable in the standard places and return the path.

### get\_ssh()

Look for the ssh executable in the standard places and return the path.

### get\_rsync()

Look for the rsync executable in the standard places and return the path.

### get\_mv()

Look for the mv executable in the standard places and return the path.

# AUTHOR

Don Owens<EMAIL_ADDRESS>


text:
jsusfx -  Opensource Jesusonic FX implementation
================================================
jsusfx is an opensource implementation of the [JSFX](http://www.reaper.fm/sdk/js/js.php)
scripting language that is available with [Reaper](http://www.reaper.fm).

*There is too much bugs to be usable, but should be good enough for regular use soon!*

While the original JSFX scripting language can do alot of thing in Reaper,
this implementation is focusing on providing dsp scripting processing
for other hosts (like pure-data and Max/MSP) and platforms.

This project comes with a subset of the original eel2 code from Cockos
[WDL](http://www.cockos.com/wdl).

See [this](http://forum.cockos.com/showthread.php?t=27764) for great JSFX
examples.

Limitations
-----------
* Only supports 2 in / 2 out
* No midi support
* No GFX (the GFX section is just ignored)

Pure-data and Max implementation
--------------------------------
The external object is called jsusfx~. See the pd and max directory to
see how to build them.

* It will check on the max/pd path to find the script file specified in the object creation arguments.
* Sliders are normalized to 0..1 for all 'parameters'. If you wish to use the original slider range values, put 0 as a second argument to the creation of the jsus~ object. If you want to normalized to 0..127, put 127 for the second argument.
* Turning on the DSP runs the @init section.
* To change a slider, you need to send the following message [slider <num> <value>]
* You can send the 'compile' message to reload your script. (Max only for now)
* If you double click on the object, you can edit the JSFX script (Max only)

Credits
-------
* The core of the language is from WDL (the authors of JSFX and Reaper)

repository: imclab/jsusfx

repo_name: imclab/jsusfx


text:
The resource will be loaded as json by calling `getResource()` and therefore the number of levels of the resource tree need to be defined
 in
advance by
overriding the method `getDepth()`. In accordance with the sling conventions 0 means a single level.

 ````typescript
     public getDepth(): number {
         return 2;
     }
  ````

# Lazy Loading

If the resource is not fetched synchronuously then the `render` method will call `renderLoading` instead to display a loading spinner or
similar ui.
Asynchronuous loading happens when a ResourceComponent's path prop is changed or a new ResourceComponent
is added to the resource tree in the client. This is often the case when the react router library is used.

````typescript
    public renderLoading(): React.ReactElement<any> {

        return (
            <span>Loading data ...</spany>
        );
    }
 ````

repository: anupammaiti/aem-react

filename: 030_Loading Resource.md

gha_language: Java

repo_name: anupammaiti/aem-react


text:
# Beneath std

> 原文跟踪[beneath-std.md](https://github.com/rust-lang-nursery/nomicon/blob/master/src/beneath-std.md)   Commit: a0c1de174abda5bc5655ed27b0c5741a1a48a92e

This section documents (or will document) features that are provided by the standard library and
that `#![no_std]` developers have to deal with (i.e. provide) to build `#![no_std]` binary crates. A
(likely incomplete) list of such features is shown below:

- #[lang = "eh_personality"]
- #[lang = "start"]
- #[lang = "termination"]
- #[panic_implementation]


text:
# SimpleGoogleCustomSearch

With Simple Google Custom Search, help people search what they need in your website just like in official google site.

## Installation

Add this line to your application's Gemfile:

    gem 'simple_google_custom_search'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install simple_google_custom_search

## Configuration

You need to define a <tt>constant variable</tt> for the API to search the matching words to your domain:

    SGCS_CONFIG = {
        domain: 'YOUR_SITE_URL'
    }

## Usage

To perform a search:

    results = SimpleGoogleCustomSearch.search("simple", offset +optional+)

The +results+ variable is now a SimpleGoogleCustomSearch::ResultSet object:

    results.total            # number of results (integer)
    results.item             # array of result objects (SimpleGoogleCustomSearch::Result)

Iterate through the results:

    results.item.each do |result|
        result.title           # result title
        result.link            # result URL
        result.description     # excerpt, with terms highlighted
    end

## TODO

1. Unit Test
2. Add Pagination

## Contributing

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


text:
---
type: rule
title: Do you know the best sample applications?
uri: the-best-sample-applications
authors:
  - title: Adam Cogan
    url: https://ssw.com.au/people/adam-cogan
  - title: Eric Phan
    url: https://ssw.com.au/people/eric-phan
  - title: Jason Taylor
    url: https://ssw.com.au/people/jason-taylor
  - title: Gabriel George
    url: https://ssw.com.au/people/gabriel-george
related: []
redirects:
  - do-you-know-the-best-sample-applications
created: 2016-03-15T18:31:47.000Z
archivedreason: null
guid: 74c3b270-3a99-4378-8c23-65b9abc77658
---
Before starting a software project and evaluating a new technology, it is important to know what the best practices are. The easiest way to get up and running is by looking at a sample application. Below is a list of sample applications that we’ve curated and given our seal of approval.

<!--endintro-->

### Northwind Schema

![](northwind_schema.png)

### SQL Server

* **[AdventureWorks](https://github.com/Microsoft/sql-server-samples/releases/tag/adventureworks)**
* **[Northwind (old SQL standards)](https://github.com/Microsoft/sql-server-samples/tree/master/samples/databases/northwind-pubs)**

### SQL Server and Azure SQL Database

* **[WideWorldImporters Sample Database](https://github.com/Microsoft/sql-server-samples/tree/master/samples/databases/wide-world-importers)**

### .NET Core

* **[SSW Clean Architecture Solution Template](https://github.com/SSWConsulting/SSW.CleanArchitecture)**
  An example REST API build with .NET 7 following the principles of Clean Architecture.
* **[SSW Northwind Traders](https://github.com/SSWConsulting/Northwind365)**
  A reference application built using Clean Architecture, Angular 8, EF Core 7, ASP.NET Core 7, Duende Identity Server 6.
* **[eShopOnWeb](https://github.com/dotnet-architecture/eShopOnWeb)**
  Sample ASP.NET Core 6.0 reference application, powered by Microsoft, demonstrating a layered application architecture with monolithic deployment model. Download the eBook PDF from docs folder.
* **[eShopOnContainers](https://github.com/dotnet-architecture/eShopOnContainers)**
  Cross-platform .NET sample microservices and container based application that runs on Linux Windows and macOS. Powered by .NET 7, Docker Containers and Azure Kubernetes Services. Supports Visual Studio, VS for Mac and CLI based environments with Docker CLI, dotnet CLI, VS Code or any other code editor.
* **[ContosoUniversity](https://github.com/jbogard/ContosoUniversityDotNetCore-Pages)**
  This application takes the traditional Contoso University sample applications (of which there have been many), and try to adapt it to how our "normal" ASP.NET applications are built.

### Blazor

* **[Awesome Blazor Browser](https://github.com/jsakamoto/awesome-blazor-browser)**
  A Blazor example app that links to many other useful Blazor examples
* **[Blazor Workshop](https://github.com/dotnet-presentations/blazor-workshop/)**
  A Blazor workshop showing how to build fast food website

### UI - Angular

* **[Tour of Heroes](https://angular.io/tutorial/tour-of-heroes)**
  Default Angular sample app as part of the documentation
* **[ngrx Example App](https://github.com/ngrx/platform/tree/master/projects/ngrx.io)**
  Example application utilizing @ngrx libraries, showcasing common patterns and best practices

### UI - React

* **[Intro to React (Tic-tac-toe)](https://react.dev/learn/tutorial-tic-tac-toe)**
  Introductory React tutorial that builds a simple Tic-tac-toe game
* **[Intro to Redux (Counter example)](https://redux.js.org/tutorials/essentials/part-2-app-structure#the-counter-example-app)**
  Introductory React Redux tutorial that builds a simple counter app

gha_language: TSQL