text:
[![Circle CI](https://circleci.com/gh/tknerr/linus-kitchen/tree/master.svg?style=shield)](https://circleci.com/gh/tknerr/linus-kitchen/tree/master)

An Ubuntu Desktop 18.04 based development box for Infrastructure-as-Code development with Vagrant, Chef, Ansible & Co.

![Linus' Kitchen Screenshot](https://raw.github.com/tknerr/linus-kitchen/master/linus_kitchen.png)

Yes, it is being set up with Vagrant and Chef, so it's a bit meta...

It is based on the [Zuehlke/linux-developer-vm](https://github.com/Zuehlke/linux-developer-vm) template, and also the Linux based equivalent of [Bill's Kitchen](https://github.com/tknerr/bills-kitchen) (which explains the name).

## What's included?

### Main tools

These are the main tools included in Linus' Kitchen (see CHANGELOG for the specific versions):

  * [Ansible](https://www.ansible.com/)
  * [ChefDK](https://downloads.chef.io/chef-dk/)
  * [Docker](http://docker.io/)
  * [Git](https://git-scm.org/)
  * [Packer](http://packer.io/)
  * [Vagrant](http://vagrantup.com/)
  * [VirtualBox](https://www.virtualbox.org/)
  * [Visual Studio Code](https://code.visualstudio.com/)

#### Chef-based development toolchain

In addition to Chef itself, the following tools (which are all Ruby-based) come included with ChefDK:

  * [berkshelf](https://berkshelf.com/) - a dependency manager for Chef cookbooks
  * [foodcritic](http://www.foodcritic.io/) - a lint tool for Chef cookbooks
  * [chefspec](https://chefspec.github.io/chefspec/) - unit testing for Chef cookbooks
  * [serverspec](http://serverspec.org/) - rspec based framework for testing servers
  * [test-kitchen](http://kitchen.ci/) - a test driver for orchestrating and testing infrastructure

#### Ansible-based development toolchain

In addition to Ansible itself, the following tools (which are all Python-based) are included:

  * [ansible-galaxy](https://docs.ansible.com/ansible/galaxy.html) - a dependency manager for Ansible roles
  * [ansible-lint](https://github.com/willthames/ansible-lint) - a lint tool for Ansible roles
  * [testinfra](https://testinfra.readthedocs.io/) - a pytest based framework for testing servers
  * [molecule](https://molecule.readthedocs.io/) - a test driver for orchestrating and testing infrastructure

### Tweaks and Plugins

Other tweaks worth mentioning:

  * Scripts in `~/.bashrc.d/*.sh` are sourced from `~/.bashrc`, pre-configured with the following:
    * sets up `be` as an alias for `bundle exec`
    * runs `chef shell-init bash` for initializing the ChefDK
    * configures "virtualbox" as the `$VAGRANT_DEFAULT_PROVIDER`
  * Bundler is configured for parallel downloading and retrying (see `~/.bundle/config`)
  * Customized `~/.vagrant.d/Vagrantfile` and `~/.kitchen/config.yml` for caching as much as possible
  * Pre-installed Vagrant plugins:
    * [vagrant-cachier](https://github.com/fgrehm/vagrant-cachier) - caches all kinds of packages you install in the vagrant VMs
    * [vagrant-managed-servers](https://github.com/tknerr/vagrant-managed-servers) - Vagrant Provider for provisioning managed servers via SSH or WinRM
  * Pre-installed Visual Studio Code plugins:
    * [bbenoist.vagrant](https://marketplace.visualstudio.com/items?itemName=bbenoist.vagrant) - allows you to control Vagrant boxes from within VSCode
    * [dhoeric.ansible-vault](https://marketplace.visualstudio.com/items?itemName=dhoeric.ansible-vault) - encrypt/decrypt Ansible vault credentials
    * [donjayamanne.githistory](https://marketplace.visualstudio.com/items?itemName=donjayamanne.githistory) -  view and search the Git history, compare branches, do cherry-picking and more
    * [eamodio.gitlens](https://marketplace.visualstudio.com/items?itemName=eamodio.gitlens) - Various features, most notably an inline Git blame with tooltips
    * [felipecaputo.git-project-manager](https://marketplace.visualstudio.com/items?itemName=felipecaputo.git-project-manager) - configure a list of directories containing Git repositories and navigate through those indexed repositories easily
    * [mde.select-highlight-minimap](https://marketplace.visualstudio.com/items?itemName=mde.select-highlight-minimap) - directly spot highlighted selections in the minimap
    * [ms-python.python](https://marketplace.visualstudio.com/items?itemName=ms-python.python) - provides Python integration
    * [ms-vscode.sublime-keybindings](https://marketplace.visualstudio.com/items?itemName=ms-vscode.sublime-keybindings) - Import your Sublime Text settings and keybindings
    * [Pendrica.chef](https://marketplace.visualstudio.com/items?itemName=Pendrica.chef) - supports the Chef DSL, plenty of Chef snippets
    * [PeterJausovec.vscode-docker](https://marketplace.visualstudio.com/items?itemName=PeterJausovec.vscode-docker) - Easily add configuration files for Docker, Docker Compose to your project. Syntax highlighting and linting for `Dockerfile` files.
    * [rebornix.ruby](https://marketplace.visualstudio.com/items?itemName=rebornix.ruby) - Ruby integration
    * [vscoss.vscode-ansible](https://marketplace.visualstudio.com/items?itemName=vscoss.vscode-ansible) - runs Ansible Playbooks, provides code snippets, syntax highlighting and YAML validation
    * [yzhang.markdown-all-in-one](https://marketplace.visualstudio.com/items?itemName=yzhang.markdown-all-in-one) - Makes editing Markdown files easier. Supports e.g. creation of a TOC, some auto-completion, and export to HTML
    * [zikalino.azure-rest-for-ansible](https://marketplace.visualstudio.com/items?itemName=zikalino.azure-rest-for-ansible) - call the Azure REST API from within VSCode, e.g. control VMs and run provided examples. Creates Ansible playbooks.
  * Placed a `README.md` file on the Desktop to guide first time users after they logged in to the VM
  * Symlinked [`update-vm.sh`](scripts/update-vm.sh) to `/usr/local/bin/update-vm` so it's in the `$PATH` and can be used for updating the VM from the inside (see below)

## Usage

### Obtaining and Starting the VM Image

The latest version of the Linus Kitchen can be downloaded as a VM image from here:

  * https://github.com/tknerr/linus-kitchen/releases

After downloading the .ova file you can import it into VMWare Fusion / Workstation Player via `File -> Import...`.
Once imported, you can simply start the VM and log in:

  * username: "user"
  * password: "user"

From then on just open a terminal and you will have all of the tools available (see "What's included?").

### Updating the VM

You can run these commands from anywhere inside the VM:

  * `update-vm` - update the VM by applying the Chef recipes from the locally checked out repo at `~/vm-setup`
  * `update-vm --pull` - same as above, but update repo before by pulling the latest changes
  * `update-vm --verify-only` - don't update the VM, only run the Serverspec tests
  * `update-vm --provision-only` - don't run the Serverspec tests, only update the vm

### Keyboard Layout and Locale Settings

The VM ships with a full `US` keyboard layout and `en_US.UTF-8` locale by default.

To change the keyboard layout to your preferred language use `System Settings... -> Text Entry` in the VM.

If you have a totally different keymap (e.g. on a MacBook) you can always reconfigure it:
```
sudo dpkg-reconfigure keyboard-configuration
```

If want to reconfigure the locale:
```
sudo dpkg-reconfigure locales
```

## Development

### Prerequisites

You need [VMware Workstation Pro](https://www.vmware.com/products/workstation.html) / [VMware Fusion Pro](https://www.vmware.com/products/workstation.html) and [Vagrant](http://www.vagrantup.com/) with the [vagrant-vmware-plugin](https://www.vagrantup.com/vmware/) installed.

If you don't mind about running 64-bit VirtualBox VMs inside Linus Kitchen, you only even need [VirtualBox](http://virtualbox.org/wiki/Downloads) and [Vagrant](http://www.vagrantup.com/) installed (note that VirtualBox only supports nested 32-bit guests).

All other requirements, including ChefDK will be installed *inside the Vagrant VM* during provisioning, i.e. you don't need them installed on your host machine.

### Basic Development Workflow

Bring up the developer VM:
```
$ vagrant up
```

This will take a while, as it will do quite a few things inside the VM:

 1. Setup a new user account ('user') under which the VM will be provisioned
 2. Download and install [ChefDK](https://downloads.chef.io/chef-dk/)
 3. Copy the current directory into the VM (will be placed in `~/vm-setup`)
 4. Install cookbook dependencies via [Berkshelf](http://berkshelf.com/) to `~/vm-setup/cookbooks/vm/cookbooks`
 5. Trigger a [Chef-Zero](https://www.chef.io/blog/2013/10/31/chef-client-z-from-zero-to-chef-in-8-5-seconds/) run to apply the `~/vm-setup/cookbooks/vm/recipes` to the VM (see "What's included?")
 6. Verify the installation using a battery of [Serverspec](http://serverspec.org/) tests

Watch the vagrant output on the console for seeing progress. At the end you
should see all tests passing:

```
...
==> default:
==> default: update-vm.sh
==> default:   installs chefdk 1.3.40
==> default:   symlinks the update-vm script to /usr/local/bin/
==> default:
==> default: Finished in 26.85 seconds (files took 1.08 seconds to load)
==> default: 59 examples, 0 failures
...
```

If these are passing as expected, you can continue developing on the Chef recipes within this repo.
Please don't forget to add a test for each new feature you add (see "Contributing")

### Running the Acceptance Tests

In addition to the Serverspec tests (which verify that the installed tools are properly configured and working as expected) you can also execute a minimal acceptance test which covers the [common usage scenarios](https://github.com/tknerr/vagrant-workflow-tests/blob/master/spec/acceptance/usage_scenarios_spec.rb) when developing with Vagrant and Chef, including:

  * cloning a [sample-toplevel-cookbook](https://github.com/tknerr/sample-toplevel-cookbook) and [sample-infrastructure-repo](https://github.com/tknerr/sample-infrastructure-repo)
  * running various commands like `bundle install`, `vagrant plugin list`, `vagrant up`, etc..
  * running different kinds of cookbook tests via `rubocop`, `foodcritic`, `chefspec` and `test-kitchen`

The acceptance test is not run by default, but you can run it manually from anywhere inside the VM:
```
$ git clone https://github.com/tknerr/vagrant-workflow-tests
$ cd vagrant-workflow-tests
$ rspec
```

If all goes well you should see an output [like this](https://cloud.githubusercontent.com/assets/365744/3607278/0579cae2-0d45-11e4-81f0-9236c592562a.png).

### Packaging

Whenever you feel like distributing a fat VM image rather than a Vagrantfile,
you can package / export it as a VirtualBox / VMware image. This might be useful
for distributing the initial version of the developer VM to your dev team,
or simply for preserving checkpoint releases as a binary images.

Let's start from a clean state:
```
$ vagrant destroy -f
```

Make sure vagrant-cachier is disabled when you bring up the VM for packaging:
```
$ unset GLOBAL_VAGRANT_CACHIER_ENABLED
$ vagrant up
```

This will provision the VM as usual. Once the provisioning succeeded, we will
do a few cleanup steps before packaging the VM.

First, unmount the /vagrant shared folder:
```
$ vagrant ssh -c "sudo umount /vagrant -f"
```

Then remove the vagrant user account:
```
$ vagrant ssh -c "sudo pkill -KILL -u vagrant"
$ vagrant ssh -c "sudo userdel -f -r vagrant"
```

Finally, shutdown the VM, remove the sharedfolder, and export the VM as an .ova file:

For VirtualBox:
```
$ vagrant halt
$ VBoxManage sharedfolder remove "Linus Kitchen" --name "vagrant"
$ VBoxManage modifyvm "Linus Kitchen" --name "Linus Kitchen v0.1.0"
$ VBoxManage export "Linus Kitchen v0.1.0" --output "linus-kitchen-v0.1.0_virtualbox.ova" --options manifest,nomacs
```

For VMware:
```
$ vagrant halt
$ VMX_FILE=`cat .vagrant/machines/default/vmware_fusion/id`
$ ovftool --name="Linus Kitchen v0.1.0" "$VMX_FILE" linus-kitchen-v0.1.0_vmware.ova
```

Don't forget to throw away the VM when you are done:
```
$ vagrant destroy -f
```

## Contributing

 1. Fork the repository on Github
 1. Create a named feature branch (like `feature/add-xyz`)
 1. Implement your changes, add tests
 1. Commit and push
 1. Submit a Pull Request via Github


text: from index import *

redpajama_set_name: RedPajamaGithub


text:
This is the repository for all the documentation for the Clarify.io API which is currently at [docs.clarify.io](http://docs.clarify.io/).

While this is the current version of our documentation, it was not the first. Check out [An Evolution on Documentation](http://clarify.io/blog/an-evolution-in-documentation/) to understand some of our how and why we got here.

## Adding a Quickstart

1. Create a file in the _quickstarts folder for the Quickstart you plan to write
  * Make sure to set the 'languages' array, that determines which tabs appear for the code samples
  * Make sure to set the 'navtitle' and 'order' values, those determine the link and its order in the sidebar navigation
1. Include the sections which you need from the _includes/sections folder
1. Anytime you want to include a code sample, create a variable called 'tabs' with the name of your samples and include /structural/tabs.html
  * Whatever string you use for the 'tabs' variable should be the name of your code samples.
    * For example, if 'tabs' equals 'monkey' then your PHP sample would be in _includes/source/php/monkey.md while the curl example would be _includes/source/curl/monkey.md
  * Once you have all the samples you want in whatever language, simply add that language to the 'languages' array in the Quickstart front matter.
    * Make sure that you have **all** the samples for a given language before you turn it on. Otherwise the includes will fail and Jekyll won't update the pages.

## Todo list

* ~~Convert existing site~~
* ~~Set up basic template w/ header, footer, etc~~
* ~~Move all the code from Gists into the repo~~
* ~~Find a good syntax highlighter~~
* ~~Add a page of errors~~
* ~~Add a page of callback formats~~
* Convert the swagger iframe to actual docs
* Insights & Reports
  * Spoken Words Report
  * ~~Topics Insight (beta)~~
  * Closed Captioning (beta)
* Code samples
  * Implement PHP for everything
  * Implement Python for everything
  * Implement Java for everything
  * Implement Ruby for everything
  * Implement Node for everything
  * Implement C# for everything
  * ~~Rename includes to be easier to predict~~
  * ~~Add the bundle callback to the basic search quickstart~~
  * Replace the "processed" search results with the raw json
  * Add keyword processing to that quickstart
* Formatting
  * ~~Make it so that things outside paragraphs are formatted correctly~~
  * ~~Remove the paragraphs~~
  * Kill some of the stupid CSS
  * ~~Improve the formatting of inline code/words to stand out better~~
  * ~~Make sure links open in the right windows~~
  * ~~Simplify includes to minimize duplication~~
  * ~~Fix the header/footer margin around the code samples~~
  * ~~Expand the margin between the code samples and the next paragraph/text~~
  * ~~Convert back to the default syntax highlighting where possible~~
* Use front matter better
  * ~~Tag things that are in beta and invite-only~~
  * ~~Add quickstarts to sidebar via a collection~~
  * ~~Shift messages into a subfolder~~
* Move media list out of WordPress

## Contributing

If you want to run this locally yourself, check out Github's getting started documentation here: https://help.github.com/articles/using-jekyll-with-pages/

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


text:
package oneandone

import (
	"net/http"
)

type MonitoringPolicy struct {
	ApiPtr
	idField
	Name         string               `json:"name,omitempty"`
	Description  string               `json:"description,omitempty"`
	State        string               `json:"state,omitempty"`
	Default      *int                 `json:"default,omitempty"`
	CreationDate string               `json:"creation_date,omitempty"`
	Email        string               `json:"email,omitempty"`
	Agent        bool                 `json:"agent"`
	Servers      []Identity           `json:"servers,omitempty"`
	Thresholds   *MonitoringThreshold `json:"thresholds,omitempty"`
	Ports        []MonitoringPort     `json:"ports,omitempty"`
	Processes    []MonitoringProcess  `json:"processes,omitempty"`
}

type MonitoringThreshold struct {
	Cpu          *MonitoringLevel `json:"cpu,omitempty"`
	Ram          *MonitoringLevel `json:"ram,omitempty"`
	Disk         *MonitoringLevel `json:"disk,omitempty"`
	Transfer     *MonitoringLevel `json:"transfer,omitempty"`
	InternalPing *MonitoringLevel `json:"internal_ping,omitempty"`
}

type MonitoringLevel struct {
	Warning  *MonitoringValue `json:"warning,omitempty"`
	Critical *MonitoringValue `json:"critical,omitempty"`
}

type MonitoringValue struct {
	Value int  `json:"value"`
	Alert bool `json:"alert"`
}

type MonitoringPort struct {
	idField
	Protocol          string `json:"protocol,omitempty"`
	Port              int    `json:"port"`
	AlertIf           string `json:"alert_if,omitempty"`
	EmailNotification bool   `json:"email_notification"`
}

type MonitoringProcess struct {
	idField
	Process           string `json:"process,omitempty"`
	AlertIf           string `json:"alert_if,omitempty"`
	EmailNotification bool   `json:"email_notification"`
}

// GET /monitoring_policies
func (api *API) ListMonitoringPolicies(args ...interface{}) ([]MonitoringPolicy, error) {
	url, err := processQueryParams(createUrl(api, monitorPolicyPathSegment), args...)
	if err != nil {
		return nil, err
	}
	result := []MonitoringPolicy{}
	err = api.Client.Get(url, &result, http.StatusOK)
	if err != nil {
		return nil, err
	}
	for index, _ := range result {
		result[index].api = api
	}
	return result, nil
}

// POST /monitoring_policies
func (api *API) CreateMonitoringPolicy(mp *MonitoringPolicy) (string, *MonitoringPolicy, error) {
	result := new(MonitoringPolicy)
	url := createUrl(api, monitorPolicyPathSegment)
	err := api.Client.Post(url, &mp, &result, http.StatusCreated)
	if err != nil {
		return "", nil, err
	}
	result.api = api
	return result.Id, result, nil
}

// GET /monitoring_policies/{id}
func (api *API) GetMonitoringPolicy(mp_id string) (*MonitoringPolicy, error) {
	result := new(MonitoringPolicy)
	url := createUrl(api, monitorPolicyPathSegment, mp_id)
	err := api.Client.Get(url, &result, http.StatusOK)
	if err != nil {
		return nil, err
	}
	result.api = api
	return result, nil
}

// DELETE /monitoring_policies/{id}
func (api *API) DeleteMonitoringPolicy(mp_id string) (*MonitoringPolicy, error) {
	result := new(MonitoringPolicy)
	url := createUrl(api, monitorPolicyPathSegment, mp_id)
	err := api.Client.Delete(url, nil, &result, http.StatusAccepted)
	if err != nil {
		return nil, err
	}
	result.api = api
	return result, nil
}

// PUT /monitoring_policies/{id}
func (api *API) UpdateMonitoringPolicy(mp_id string, mp *MonitoringPolicy) (*MonitoringPolicy, error) {
	url := createUrl(api, monitorPolicyPathSegment, mp_id)
	result := new(MonitoringPolicy)
	err := api.Client.Put(url, &mp, &result, http.StatusAccepted)
	if err != nil {
		return nil, err
	}
	result.api = api
	return result, nil
}

// GET /monitoring_policies/{id}/ports
func (api *API) ListMonitoringPolicyPorts(mp_id string) ([]MonitoringPort, error) {
	result := []MonitoringPort{}
	url := createUrl(api, monitorPolicyPathSegment, mp_id, "ports")
	err := api.Client.Get(url, &result, http.StatusOK)
	if err != nil {
		return nil, err
	}
	return result, nil
}

// POST /monitoring_policies/{id}/ports
func (api *API) AddMonitoringPolicyPorts(mp_id string, mp_ports []MonitoringPort) (*MonitoringPolicy, error) {
	result := new(MonitoringPolicy)
	data := struct {
		Ports []MonitoringPort `json:"ports"`
	}{mp_ports}
	url := createUrl(api, monitorPolicyPathSegment, mp_id, "ports")
	err := api.Client.Post(url, &data, &result, http.StatusAccepted)
	if err != nil {
		return nil, err
	}
	result.api = api
	return result, nil
}

// GET /monitoring_policies/{id}/ports/{id}
func (api *API) GetMonitoringPolicyPort(mp_id string, port_id string) (*MonitoringPort, error) {
	result := new(MonitoringPort)
	url := createUrl(api, monitorPolicyPathSegment, mp_id, "ports", port_id)
	err := api.Client.Get(url, &result, http.StatusOK)
	if err != nil {
		return nil, err
	}
	return result, nil
}

// DELETE /monitoring_policies/{id}/ports/{id}
func (api *API) DeleteMonitoringPolicyPort(mp_id string, port_id string) (*MonitoringPolicy, error) {
	result := new(MonitoringPolicy)
	url := createUrl(api, monitorPolicyPathSegment, mp_id, "ports", port_id)
	err := api.Client.Delete(url, nil, &result, http.StatusAccepted)
	if err != nil {
		return nil, err
	}
	result.api = api
	return result, nil
}

// PUT /monitoring_policies/{id}/ports/{id}
func (api *API) ModifyMonitoringPolicyPort(mp_id string, port_id string, mp_port *MonitoringPort) (*MonitoringPolicy, error) {
	url := createUrl(api, monitorPolicyPathSegment, mp_id, "ports", port_id)
	result := new(MonitoringPolicy)
	req := struct {
		Ports *MonitoringPort `json:"ports"`
	}{mp_port}
	err := api.Client.Put(url, &req, &result, http.StatusAccepted)
	if err != nil {
		return nil, err
	}
	result.api = api
	return result, nil
}

// GET /monitoring_policies/{id}/processes
func (api *API) ListMonitoringPolicyProcesses(mp_id string) ([]MonitoringProcess, error) {
	result := []MonitoringProcess{}
	url := createUrl(api, monitorPolicyPathSegment, mp_id, "processes")
	err := api.Client.Get(url, &result, http.StatusOK)
	if err != nil {
		return nil, err
	}
	return result, nil
}

// POST /monitoring_policies/{id}/processes
func (api *API) AddMonitoringPolicyProcesses(mp_id string, mp_procs []MonitoringProcess) (*MonitoringPolicy, error) {
	result := new(MonitoringPolicy)
	request := struct {
		Processes []MonitoringProcess `json:"processes"`
	}{mp_procs}
	url := createUrl(api, monitorPolicyPathSegment, mp_id, "processes")
	err := api.Client.Post(url, &request, &result, http.StatusAccepted)
	if err != nil {
		return nil, err
	}
	result.api = api
	return result, nil
}

// GET /monitoring_policies/{id}/processes/{id}
func (api *API) GetMonitoringPolicyProcess(mp_id string, proc_id string) (*MonitoringProcess, error) {
	result := new(MonitoringProcess)
	url := createUrl(api, monitorPolicyPathSegment, mp_id, "processes", proc_id)
	err := api.Client.Get(url, &result, http.StatusOK)
	if err != nil {
		return nil, err
	}
	return result, nil
}

// DELETE /monitoring_policies/{id}/processes/{id}
func (api *API) DeleteMonitoringPolicyProcess(mp_id string, proc_id string) (*MonitoringPolicy, error) {
	result := new(MonitoringPolicy)
	url := createUrl(api, monitorPolicyPathSegment, mp_id, "processes", proc_id)
	err := api.Client.Delete(url, nil, &result, http.StatusAccepted)
	if err != nil {
		return nil, err
	}
	result.api = api
	return result, nil
}

// PUT /monitoring_policies/{id}/processes/{id}
func (api *API) ModifyMonitoringPolicyProcess(mp_id string, proc_id string, mp_proc *MonitoringProcess) (*MonitoringPolicy, error) {
	url := createUrl(api, monitorPolicyPathSegment, mp_id, "processes", proc_id)
	result := new(MonitoringPolicy)
	req := struct {
		Processes *MonitoringProcess `json:"processes"`
	}{mp_proc}
	err := api.Client.Put(url, &req, &result, http.StatusAccepted)
	if err != nil {
		return nil, err
	}
	result.api = api
	return result, nil
}

// GET /monitoring_policies/{id}/servers
func (api *API) ListMonitoringPolicyServers(mp_id string) ([]Identity, error) {
	result := []Identity{}
	url := createUrl(api, monitorPolicyPathSegment, mp_id, "servers")
	err := api.Client.Get(url, &result, http.StatusOK)
	if err != nil {
		return nil, err
	}
	return result, nil
}

// POST /monitoring_policies/{id}/servers
func (api *API) AttachMonitoringPolicyServers(mp_id string, sids []string) (*MonitoringPolicy, error) {
	result := new(MonitoringPolicy)
	request := servers{
		Servers: sids,
	}
	url := createUrl(api, monitorPolicyPathSegment, mp_id, "servers")
	err := api.Client.Post(url, &request, &result, http.StatusAccepted)
	if err != nil {
		return nil, err
	}
	result.api = api
	return result, nil
}

// GET /monitoring_policies/{id}/servers/{id}
func (api *API) GetMonitoringPolicyServer(mp_id string, ser_id string) (*Identity, error) {
	result := new(Identity)
	url := createUrl(api, monitorPolicyPathSegment, mp_id, "servers", ser_id)
	err := api.Client.Get(url, &result, http.StatusOK)
	if err != nil {
		return nil, err
	}
	return result, nil
}

// DELETE /monitoring_policies/{id}/servers/{id}
func (api *API) RemoveMonitoringPolicyServer(mp_id string, ser_id string) (*MonitoringPolicy, error) {
	result := new(MonitoringPolicy)
	url := createUrl(api, monitorPolicyPathSegment, mp_id, "servers", ser_id)
	err := api.Client.Delete(url, nil, &result, http.StatusAccepted)
	if err != nil {
		return nil, err
	}
	result.api = api
	return result, nil
}

func (mp *MonitoringPolicy) GetState() (string, error) {
	in, err := mp.api.GetMonitoringPolicy(mp.Id)
	if in == nil {
		return "", err
	}
	return in.State, err
}


text:
#ifndef VULKAN_FUCHSIA_H_
#define VULKAN_FUCHSIA_H_ 1

/*
** This header is generated from the Khronos Vulkan XML API Registry.
**
*/

#ifdef __cplusplus
extern "C" {
#endif

#define VK_FUCHSIA_imagepipe_surface 1
#define VK_FUCHSIA_IMAGEPIPE_SURFACE_SPEC_VERSION 1
#define VK_FUCHSIA_IMAGEPIPE_SURFACE_EXTENSION_NAME "VK_FUCHSIA_imagepipe_surface"
typedef VkFlags VkImagePipeSurfaceCreateFlagsFUCHSIA;
typedef struct VkImagePipeSurfaceCreateInfoFUCHSIA {
    VkStructureType                         sType;
    const void*                             pNext;
    VkImagePipeSurfaceCreateFlagsFUCHSIA    flags;
    zx_handle_t                             imagePipeHandle;
} VkImagePipeSurfaceCreateInfoFUCHSIA;

typedef VkResult (VKAPI_PTR *PFN_vkCreateImagePipeSurfaceFUCHSIA)(VkInstance instance, const VkImagePipeSurfaceCreateInfoFUCHSIA* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface);

#ifndef VK_NO_PROTOTYPES
VKAPI_ATTR VkResult VKAPI_CALL vkCreateImagePipeSurfaceFUCHSIA(
    VkInstance                                  instance,
    const VkImagePipeSurfaceCreateInfoFUCHSIA*  pCreateInfo,
    const VkAllocationCallbacks*                pAllocator,
    VkSurfaceKHR*                               pSurface);
#endif

#ifdef __cplusplus
}
#endif

#endif


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Compan. Bot. Mag. 1:364. 1836

#### Original name
null

### Remarks
null


text:
"""Configuration(json_files=[...]) tests."""

import json

from dependency_injector import providers
from pytest import fixture, mark, raises

@fixture
def config(config_type, json_config_file_1, json_config_file_2):
    if config_type == "strict":
        return providers.Configuration(strict=True)
    elif config_type == "default":
        return providers.Configuration(json_files=[json_config_file_1, json_config_file_2])
    else:
        raise ValueError("Undefined config type \"{0}\"".format(config_type))

def test_load(config):
    config.load()

    assert config() == {
        "section1": {
            "value1": 11,
            "value11": 11,
        },
        "section2": {
            "value2": 2,
        },
        "section3": {
            "value3": 3,
        },
    }
    assert config.section1() == {"value1": 11, "value11": 11}
    assert config.section1.value1() == 11
    assert config.section1.value11() == 11
    assert config.section2() == {"value2": 2}
    assert config.section2.value2() == 2
    assert config.section3() == {"value3": 3}
    assert config.section3.value3() == 3

def test_get_files(config, json_config_file_1, json_config_file_2):
    assert config.get_json_files() == [json_config_file_1, json_config_file_2]

def test_set_files(config):
    config.set_json_files(["file1.json", "file2.json"])
    assert config.get_json_files() == ["file1.json", "file2.json"]

def test_copy(config, json_config_file_1, json_config_file_2):
    config_copy = providers.deepcopy(config)
    assert config_copy.get_json_files() == [json_config_file_1, json_config_file_2]

def test_file_does_not_exist(config):
    config.set_json_files(["./does_not_exist.json"])
    config.load()
    assert config() == {}

@mark.parametrize("config_type", ["strict"])
def test_file_does_not_exist_strict_mode(config):
    config.set_json_files(["./does_not_exist.json"])
    with raises(IOError):
        config.load()
    assert config() == {}

def test_required_file_does_not_exist(config):
    config.set_json_files(["./does_not_exist.json"])
    with raises(IOError):
        config.load(required=True)

@mark.parametrize("config_type", ["strict"])
def test_not_required_file_does_not_exist_strict_mode(config):
    config.set_json_files(["./does_not_exist.json"])
    config.load(required=False)
    assert config() == {}

def test_missing_envs_required(config, json_config_file_3):
    with open(json_config_file_3, "w") as file:
        file.write(
            json.dumps(
                {
                    "section": {
                        "undefined": "${UNDEFINED}",
                    },
                },
            ),
        )
    config.set_json_files([json_config_file_3])
    with raises(ValueError, match="Missing required environment variable \"UNDEFINED\""):
        config.load(envs_required=True)

@mark.parametrize("config_type", ["strict"])
def test_missing_envs_not_required_in_strict_mode(config, json_config_file_3):
    with open(json_config_file_3, "w") as file:
        file.write(
            json.dumps(
                {
                    "section": {
                        "undefined": "${UNDEFINED}",
                    },
                },
            ),
        )
    config.set_json_files([json_config_file_3])
    config.load(envs_required=False)
    assert config.section.undefined() == ""


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Copyright 2005-2014 The Kuali Foundation

    Licensed under the Educational Community License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.opensource.org/licenses/ecl2.php

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<data xmlns="ns:workflow"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="ns:workflow resource:WorkflowData">

  <ruleTemplates xmlns="ns:workflow/RuleTemplate"
                 xsi:schemaLocation="ns:workflow/RuleTemplate resource:RuleTemplate">

    <ruleTemplate>
      <name>KualiAccountTemplate</name>
      <description>Kuali Account Template</description>
      <attributes>
        <attribute>
          <name>KualiAccountAttribute</name>
          <required>true</required>
        </attribute>
      </attributes>
    </ruleTemplate>

    <ruleTemplate>
      <name>KualiChartTemplate</name>
      <description>KualiChartTemplate</description>
      <attributes>
        <attribute>
          <name>KualiChartAttribute</name>
          <required>false</required>
        </attribute>
      </attributes>
    </ruleTemplate>

    <ruleTemplate allowOverwrite="true">
      <name>KualiOrgReviewTemplate</name>
      <description>Kuali Org Review Template</description>
      <attributes>
        <attribute>
          <name>KualiOrgReviewAttribute</name>
          <required>true</required>
        </attribute>
      </attributes>
    </ruleTemplate>

    <ruleTemplate>
      <name>TestKualiTemplate</name>
      <description>Test Kuali Template</description>
      <delegationTemplate>KualiChartTemplate</delegationTemplate>
      <attributes>
        <attribute>
          <name>KualiAccountAttribute</name>
          <required>false</required>
        </attribute>
      </attributes>
    </ruleTemplate>
  </ruleTemplates>
</data>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>TileDraw</title>
    <link rel="stylesheet" href="http://yui.yahooapis.com/3.9.1/build/cssgrids/cssgrids-min.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
    <link rel="shortcut icon" type="image/png" href="../assets/favicon.png">

            API Docs for:

APIs

Classes

Modules

            <input type="search" id="api-filter" placeholder="Type to filter APIs">

Array2d

Console

Entity

Entity.Types

FovROT

Game

Input

LightingROT

Map

Mixins

Mouse

MultiObjectManager

ObjectManager

PerformableAction

PerformableActionInterface

Player

Renderer

RendererLayer

RendererLayer.Types

ResolvableAction

ResolvableActionInterface

Tile

Tile.Types

TileDraw

TileDrawData

Util

ValidTargets

ValidTargetsFinder

        Show:

            <input type="checkbox" id="api-show-inherited" checked>
            Inherited

            <input type="checkbox" id="api-show-protected">
            Protected

            <input type="checkbox" id="api-show-private">
            Private

            <input type="checkbox" id="api-show-deprecated">
            Deprecated

TileDraw Class

            Defined in: src/mixins.js:15

Adds the functionality required for a Renderer or RendererLayer to retrieve TileDrawData from an object.

Index

Methods

Item Index

Methods

                                getTileDrawData

Methods

getTileDrawData

        ()

            TileDrawData

                Defined in

        src/mixins.js:22

Returns as tileDataobject used by Renderer objects to draw tiles.

Returns:

                        TileDrawData:


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.webapps;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.text.format.DateUtils;

import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;

import org.chromium.base.ContextUtils;
import org.chromium.base.Log;
import org.chromium.base.task.AsyncTask;
import org.chromium.base.task.PostTask;
import org.chromium.base.task.TaskTraits;
import org.chromium.blink.mojom.DisplayMode;
import org.chromium.chrome.browser.ShortcutHelper;
import org.chromium.chrome.browser.browserservices.intents.BitmapHelper;
import org.chromium.chrome.browser.browserservices.intents.BrowserServicesIntentDataProvider;
import org.chromium.chrome.browser.browserservices.intents.WebappConstants;
import org.chromium.chrome.browser.browserservices.intents.WebappInfo;
import org.chromium.components.webapk.lib.common.WebApkConstants;
import org.chromium.components.webapps.ShortcutSource;
import org.chromium.device.mojom.ScreenOrientationLockType;
import org.chromium.ui.util.ColorUtils;

import java.io.File;

/**
 * Stores data about an installed web app. Uses SharedPreferences to persist the data to disk.
 * This class must only be accessed via {@link WebappRegistry}, which is used to register and keep
 * track of web app data known to Chrome.
 */
public class WebappDataStorage {
    private static final String TAG = "WebappDataStorage";

    static final String SHARED_PREFS_FILE_PREFIX = "webapp_";
    static final String KEY_SPLASH_ICON = "splash_icon";
    static final String KEY_LAST_USED = "last_used";
    static final String KEY_URL = "url";
    static final String KEY_SCOPE = "scope";
    static final String KEY_ICON = "icon";
    static final String KEY_NAME = "name";
    static final String KEY_SHORT_NAME = "short_name";
    static final String KEY_DISPLAY_MODE = "display_mode";
    static final String KEY_ORIENTATION = "orientation";
    static final String KEY_THEME_COLOR = "theme_color";
    static final String KEY_BACKGROUND_COLOR = "background_color";
    static final String KEY_SOURCE = "source";
    static final String KEY_IS_ICON_GENERATED = "is_icon_generated";
    static final String KEY_IS_ICON_ADAPTIVE = "is_icon_adaptive";
    static final String KEY_LAUNCH_COUNT = "launch_count";
    static final String KEY_VERSION = "version";
    static final String KEY_WEBAPK_PACKAGE_NAME = "webapk_package_name";
    static final String KEY_WEBAPK_INSTALL_TIMESTAMP = "webapk_install_timestamp";
    static final String KEY_WEBAPK_UNINSTALL_TIMESTAMP = "webapk_uninstall_timestamp";
    static final String KEY_WEBAPK_MANIFEST_URL = "webapk_manifest_url";
    static final String KEY_WEBAPK_VERSION_CODE = "webapk_version_code";

    // The completion time of the last check for whether the WebAPK's Web Manifest was updated.
    static final String KEY_LAST_CHECK_WEB_MANIFEST_UPDATE_TIME =
            "last_check_web_manifest_update_time";

    // The last time that the WebAPK update request completed (successfully or unsuccessfully).
    static final String KEY_LAST_UPDATE_REQUEST_COMPLETE_TIME = "last_update_request_complete_time";

    // Whether the last WebAPK update request succeeded.
    static final String KEY_DID_LAST_UPDATE_REQUEST_SUCCEED = "did_last_update_request_succeed";

    // Whether to check updates less frequently.
    static final String KEY_RELAX_UPDATES = "relax_updates";

    // The shell Apk version requested in the last update.
    static final String KEY_LAST_REQUESTED_SHELL_APK_VERSION = "last_requested_shell_apk_version";

    // Whether to show the user the Snackbar disclosure UI.
    static final String KEY_SHOW_DISCLOSURE = "show_disclosure";

    // The path where serialized update data is written before uploading to the WebAPK server.
    static final String KEY_PENDING_UPDATE_FILE_PATH = "pending_update_file_path";

    // Whether to force an update.
    static final String KEY_SHOULD_FORCE_UPDATE = "should_force_update";

    // Whether an update has been scheduled.
    static final String KEY_UPDATE_SCHEDULED = "update_scheduled";

    // Status indicating a WebAPK is not updatable through chrome://webapks.
    public static final String NOT_UPDATABLE = "Not updatable";

    // Number of milliseconds between checks for whether the WebAPK's Web Manifest has changed.
    public static final long UPDATE_INTERVAL = DateUtils.DAY_IN_MILLIS;

    // Number of milliseconds between checks of updates for a WebAPK that is expected to check
    // updates less frequently. crbug.com/680128.
    public static final long RELAXED_UPDATE_INTERVAL = DateUtils.DAY_IN_MILLIS * 30;

    // The default shell Apk version of WebAPKs.
    static final int DEFAULT_SHELL_APK_VERSION = 1;

    // Invalid constants for timestamps and URLs. '0' is used as the invalid timestamp as
    // WebappRegistry and WebApkUpdateManager assume that timestamps are always valid.
    static final long TIMESTAMP_INVALID = 0;
    static final String URL_INVALID = "";
    static final int VERSION_INVALID = 0;

    // We use a heuristic to determine whether a web app is still installed on the home screen, as
    // there is no way to do so directly. Any web app which has been opened in the last ten days
    // is considered to be still on the home screen.
    static final long WEBAPP_LAST_OPEN_MAX_TIME = DateUtils.DAY_IN_MILLIS * 10;

    private static Clock sClock = new Clock();
    private static Factory sFactory = new Factory();

    private final String mId;
    private final SharedPreferences mPreferences;

    /**
     * Called after data has been retrieved from storage.
     * @param <T> The type of the data being retrieved.
     */
    public interface FetchCallback<T> {
        public void onDataRetrieved(T readObject);
    }

    /**
     * Factory used to generate WebappDataStorage objects.
     * Overridden in tests to inject mocked objects.
     */
    public static class Factory {
        /**
         * Generates a WebappDataStorage instance for a specified web app.
         */
        public WebappDataStorage create(final String webappId) {
            return new WebappDataStorage(webappId);
        }
    }

    /**
     * Clock used to generate the current time in millseconds for setting last used time.
     */
    public static class Clock {
        /**
         * @return Current time in milliseconds.
         */
        public long currentTimeMillis() {
            return System.currentTimeMillis();
        }
    }

    /**
     * Opens an instance of WebappDataStorage for the web app specified.
     * @param webappId The ID of the web app.
     */
    static WebappDataStorage open(String webappId) {
        return sFactory.create(webappId);
    }

    /**
     * Sets the clock used to get the current time.
     */
    @VisibleForTesting
    public static void setClockForTests(Clock clock) {
        sClock = clock;
    }

    /**
     * Sets the factory used to generate WebappDataStorage objects.
     */
    @VisibleForTesting
    public static void setFactoryForTests(Factory factory) {
        sFactory = factory;
    }

    /**
     * Asynchronously retrieves the splash screen image associated with the web app. The work is
     * performed on a background thread as it requires a potentially expensive image decode.
     * @param callback Called when the splash screen image has been retrieved.
     *                 The bitmap result will be null if no image was found.
     */
    public void getSplashScreenImage(final FetchCallback<Bitmap> callback) {
        new AsyncTask<Bitmap>() {
            @Override
            protected final Bitmap doInBackground() {
                return BitmapHelper.decodeBitmapFromString(
                        mPreferences.getString(KEY_SPLASH_ICON, null));
            }

            @Override
            protected final void onPostExecute(Bitmap result) {
                assert callback != null;
                callback.onDataRetrieved(result);
            }
        }
                .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

    /**
     * Update the splash screen image associated with the web app with the specified data. The image
     * must have been encoded using {@link BitmapHelper#encodeBitmapAsString}.
     * @param splashScreenImage The image which should be shown on the splash screen of the web app.
     */
    public void updateSplashScreenImage(String splashScreenImage) {
        mPreferences.edit().putString(KEY_SPLASH_ICON, splashScreenImage).apply();
    }

    /**
     * Creates and returns a web app launch intent from the data stored in this object.
     * @return The web app launch intent.
     */
    public Intent createWebappLaunchIntent() {
        // Assume that all of the data is invalid if the version isn't set, so return a null intent.
        int version = mPreferences.getInt(KEY_VERSION, VERSION_INVALID);
        if (version == VERSION_INVALID) return null;

        // Use "standalone" as the default display mode as this was the original assumed default for
        // all web apps.
        return ShortcutHelper.createWebappShortcutIntent(mId, mPreferences.getString(KEY_URL, null),
                mPreferences.getString(KEY_SCOPE, null), mPreferences.getString(KEY_NAME, null),
                mPreferences.getString(KEY_SHORT_NAME, null),
                mPreferences.getString(KEY_ICON, null), version,
                mPreferences.getInt(KEY_DISPLAY_MODE, DisplayMode.STANDALONE),
                mPreferences.getInt(KEY_ORIENTATION, ScreenOrientationLockType.DEFAULT),
                mPreferences.getLong(KEY_THEME_COLOR, ColorUtils.INVALID_COLOR),
                mPreferences.getLong(KEY_BACKGROUND_COLOR, ColorUtils.INVALID_COLOR),
                mPreferences.getBoolean(KEY_IS_ICON_GENERATED, false),
                mPreferences.getBoolean(KEY_IS_ICON_ADAPTIVE, false));
    }

    /**
     * Updates the data stored in this object to match that in the supplied
     * {@link BrowserServicesIntentDataProvider}.
     * @param info The WebappInfo to pull web app data from.
     */
    public void updateFromWebappIntentDataProvider(
            BrowserServicesIntentDataProvider intentDataProvider) {
        if (intentDataProvider == null) return;
        WebappInfo info = WebappInfo.create(intentDataProvider);

        SharedPreferences.Editor editor = mPreferences.edit();
        boolean updated = false;

        // The URL and scope may have been deleted by the user clearing their history. Check whether
        // they are present, and update if necessary.
        String url = mPreferences.getString(KEY_URL, URL_INVALID);
        if (url.equals(URL_INVALID)) {
            url = info.url();
            editor.putString(KEY_URL, url);
            updated = true;
        }

        if (mPreferences.getString(KEY_SCOPE, URL_INVALID).equals(URL_INVALID)) {
            editor.putString(KEY_SCOPE, info.scopeUrl());
            updated = true;
        }

        // For all other fields, assume that if the version key is present and equal to
        // WebappConstants.WEBAPP_SHORTCUT_VERSION, then all fields are present and do not need to
        // be updated. All fields except for the last used time, scope, and URL are either set or
        // cleared together.
        if (mPreferences.getInt(KEY_VERSION, VERSION_INVALID)
                != WebappConstants.WEBAPP_SHORTCUT_VERSION) {
            editor.putInt(KEY_VERSION, WebappConstants.WEBAPP_SHORTCUT_VERSION);

            if (info.isForWebApk()) {
                editor.putString(KEY_WEBAPK_PACKAGE_NAME, info.webApkPackageName());
                editor.putString(KEY_WEBAPK_MANIFEST_URL, info.manifestUrl());
                editor.putInt(KEY_WEBAPK_VERSION_CODE, info.webApkVersionCode());
                editor.putLong(KEY_WEBAPK_INSTALL_TIMESTAMP,
                        fetchWebApkInstallTimestamp(info.webApkPackageName()));
            } else {
                editor.putString(KEY_NAME, info.name());
                editor.putString(KEY_SHORT_NAME, info.shortName());
                editor.putString(KEY_ICON, info.icon().encoded());
                editor.putInt(KEY_DISPLAY_MODE, info.displayMode());
                editor.putInt(KEY_ORIENTATION, info.orientation());
                editor.putLong(KEY_THEME_COLOR, info.toolbarColor());
                editor.putLong(KEY_BACKGROUND_COLOR, info.backgroundColor());
                editor.putBoolean(KEY_IS_ICON_GENERATED, info.isIconGenerated());
                editor.putBoolean(KEY_IS_ICON_ADAPTIVE, info.isIconAdaptive());
                editor.putInt(KEY_SOURCE, info.source());
            }
            updated = true;
        }
        if (updated) editor.apply();
    }

    /**
     * Returns true if this web app recently (within WEBAPP_LAST_OPEN_MAX_TIME milliseconds) was
     * either:
     * - registered with WebappRegistry
     * - launched from the homescreen
     */
    public boolean wasUsedRecently() {
        // WebappRegistry.register sets the last used time, so that counts as a 'launch'.
        return (sClock.currentTimeMillis() - getLastUsedTimeMs() < WEBAPP_LAST_OPEN_MAX_TIME);
    }

    /**
     * Deletes the data for a web app by clearing all the information inside the SharedPreferences
     * file. This does NOT delete the file itself but the file is left empty.
     */
    public void delete() {
        deletePendingUpdateRequestFile();
        mPreferences.edit().clear().apply();
    }

    /**
     * Deletes the URL and scope, and sets all timestamps to 0 in SharedPreferences.
     * This does not remove the stored splash screen image (if any) for the app.
     */
    void clearHistory() {
        deletePendingUpdateRequestFile();

        SharedPreferences.Editor editor = mPreferences.edit();

        editor.remove(KEY_LAST_USED);
        editor.remove(KEY_URL);
        editor.remove(KEY_SCOPE);
        editor.remove(KEY_LAST_CHECK_WEB_MANIFEST_UPDATE_TIME);
        editor.remove(KEY_LAST_UPDATE_REQUEST_COMPLETE_TIME);
        editor.remove(KEY_DID_LAST_UPDATE_REQUEST_SUCCEED);
        editor.remove(KEY_RELAX_UPDATES);
        editor.remove(KEY_SHOW_DISCLOSURE);
        editor.remove(KEY_LAUNCH_COUNT);
        editor.remove(KEY_WEBAPK_UNINSTALL_TIMESTAMP);
        editor.apply();

        // Don't clear fields which can be fetched from WebAPK manifest.
    }

    /**
     * Returns the scope stored in this object, or URL_INVALID if it is not stored.
     */
    public String getScope() {
        return mPreferences.getString(KEY_SCOPE, URL_INVALID);
    }

    /**
     * Returns the URL stored in this object, or URL_INVALID if it is not stored.
     */
    public String getUrl() {
        return mPreferences.getString(KEY_URL, URL_INVALID);
    }

    /** Returns the source stored in this object, or ShortcutSource.UNKNOWN if it is not stored. */
    public int getSource() {
        return mPreferences.getInt(KEY_SOURCE, ShortcutSource.UNKNOWN);
    }

    /** Updates the source. */
    public void updateSource(int source) {
        mPreferences.edit().putInt(KEY_SOURCE, source).apply();
    }

    /** Returns the id stored in this object. */
    public String getId() {
        return mId;
    }

    /**
     * Returns the last used time, in milliseconds, of this object, or -1 if it is not stored.
     */
    public long getLastUsedTimeMs() {
        return mPreferences.getLong(KEY_LAST_USED, TIMESTAMP_INVALID);
    }

    /**
     * Update the information associated with the web app with the specified data. Used for testing.
     * @param splashScreenImage The image encoded as a string which should be shown on the splash
     *                          screen of the web app.
     */
    @VisibleForTesting
    void updateSplashScreenImageForTests(String splashScreenImage) {
        mPreferences.edit().putString(KEY_SPLASH_ICON, splashScreenImage).apply();
    }

    /**
     * Update the package name of the WebAPK. Used for testing.
     * @param webApkPackageName The package name of the WebAPK.
     */
    @VisibleForTesting
    void updateWebApkPackageNameForTests(String webApkPackageName) {
        mPreferences.edit().putString(KEY_WEBAPK_PACKAGE_NAME, webApkPackageName).apply();
    }

    /**
     * Updates the last used time of this object.
     */
    void updateLastUsedTime() {
        mPreferences.edit().putLong(KEY_LAST_USED, sClock.currentTimeMillis()).apply();
    }

    /**
     * Returns the package name if the data is for a WebAPK, null otherwise.
     */
    public String getWebApkPackageName() {
        return mPreferences.getString(KEY_WEBAPK_PACKAGE_NAME, null);
    }

    /**
     * Updates the time of the completion of the last check for whether the WebAPK's Web Manifest
     * was updated.
     */
    void updateTimeOfLastCheckForUpdatedWebManifest() {
        mPreferences.edit()
                .putLong(KEY_LAST_CHECK_WEB_MANIFEST_UPDATE_TIME, sClock.currentTimeMillis())
                .apply();
    }

    /**
     * Returns the completion time, in milliseconds, of the last check for whether the WebAPK's Web
     * Manifest was updated. This time needs to be set when the WebAPK is registered.
     */
    public long getLastCheckForWebManifestUpdateTimeMs() {
        return mPreferences.getLong(KEY_LAST_CHECK_WEB_MANIFEST_UPDATE_TIME, TIMESTAMP_INVALID);
    }

    /**
     * Updates when the last WebAPK update request finished (successfully or unsuccessfully).
     */
    void updateTimeOfLastWebApkUpdateRequestCompletion() {
        mPreferences.edit()
                .putLong(KEY_LAST_UPDATE_REQUEST_COMPLETE_TIME, sClock.currentTimeMillis())
                .apply();
    }

    /**
     * Returns the time, in milliseconds, that the last WebAPK update request completed
     * (successfully or unsuccessfully). This time needs to be set when the WebAPK is registered.
     */
    public long getLastWebApkUpdateRequestCompletionTimeMs() {
        return mPreferences.getLong(KEY_LAST_UPDATE_REQUEST_COMPLETE_TIME, TIMESTAMP_INVALID);
    }

    /**
     * Updates whether the last update request to WebAPK Server succeeded.
     */
    void updateDidLastWebApkUpdateRequestSucceed(boolean success) {
        mPreferences.edit().putBoolean(KEY_DID_LAST_UPDATE_REQUEST_SUCCEED, success).apply();
    }

    /**
     * Returns whether the last update request to WebAPK Server succeeded.
     */
    boolean getDidLastWebApkUpdateRequestSucceed() {
        return mPreferences.getBoolean(KEY_DID_LAST_UPDATE_REQUEST_SUCCEED, false);
    }

    /**
     * Returns whether to show the user a privacy disclosure (used for TWAs and unbound WebAPKs).
     * This is not cleared until the user explicitly acknowledges it.
     */
    public boolean shouldShowDisclosure() {
        return mPreferences.getBoolean(KEY_SHOW_DISCLOSURE, false);
    }

    /**
     * Clears the show disclosure bit, this stops TWAs and unbound WebAPKs from showing a privacy
     * disclosure on every resume of the Webapp. This should be called when the user has
     * acknowledged the disclosure.
     */
    public void clearShowDisclosure() {
        mPreferences.edit().putBoolean(KEY_SHOW_DISCLOSURE, false).apply();
    }

    /**
     * Sets the disclosure bit which causes TWAs and unbound WebAPKs to show a privacy disclosure.
     * This is set the first time an app is opened without storage (either right after install or
     * after Chrome's storage is cleared).
     */
    public void setShowDisclosure() {
        mPreferences.edit().putBoolean(KEY_SHOW_DISCLOSURE, true).apply();
    }

    /** Updates the shell Apk version requested in the last update. */
    void updateLastRequestedShellApkVersion(int shellApkVersion) {
        mPreferences.edit().putInt(KEY_LAST_REQUESTED_SHELL_APK_VERSION, shellApkVersion).apply();
    }

    /** Returns the shell Apk version requested in last update. */
    int getLastRequestedShellApkVersion() {
        return mPreferences.getInt(KEY_LAST_REQUESTED_SHELL_APK_VERSION, DEFAULT_SHELL_APK_VERSION);
    }

    /**
     * Returns whether the previous WebAPK update attempt succeeded. Returns true if there has not
     * been any update attempts.
     */
    boolean didPreviousUpdateSucceed() {
        long lastUpdateCompletionTime = getLastWebApkUpdateRequestCompletionTimeMs();
        if (lastUpdateCompletionTime == TIMESTAMP_INVALID) {
            return true;
        }
        return getDidLastWebApkUpdateRequestSucceed();
    }

    /** Sets whether we should check for updates less frequently. */
    void setRelaxedUpdates(boolean relaxUpdates) {
        mPreferences.edit().putBoolean(KEY_RELAX_UPDATES, relaxUpdates).apply();
    }

    /** Returns whether we should check for updates less frequently. */
    public boolean shouldRelaxUpdates() {
        return mPreferences.getBoolean(KEY_RELAX_UPDATES, false);
    }

    /** Sets whether an update has been scheduled. */
    public void setUpdateScheduled(boolean isUpdateScheduled) {
        mPreferences.edit().putBoolean(KEY_UPDATE_SCHEDULED, isUpdateScheduled).apply();
    }

    /** Gets whether an update has been scheduled. */
    public boolean isUpdateScheduled() {
        return mPreferences.getBoolean(KEY_UPDATE_SCHEDULED, false);
    }

    /** Whether a WebAPK is unbound. */
    private boolean isUnboundWebApk() {
        String webApkPackageName = getWebApkPackageName();
        return (webApkPackageName != null
                && !webApkPackageName.startsWith(WebApkConstants.WEBAPK_PACKAGE_PREFIX));
    }

    /** Sets whether an update should be forced. */
    public void setShouldForceUpdate(boolean forceUpdate) {
        if (!isUnboundWebApk()) {
            mPreferences.edit().putBoolean(KEY_SHOULD_FORCE_UPDATE, forceUpdate).apply();
        }
    }

    /** Whether to force an update. */
    public boolean shouldForceUpdate() {
        return mPreferences.getBoolean(KEY_SHOULD_FORCE_UPDATE, false);
    }

    /** Returns the update status. */
    public String getUpdateStatus() {
        if (isUnboundWebApk()) return NOT_UPDATABLE;
        if (isUpdateScheduled()) return "Scheduled";
        if (shouldForceUpdate()) return "Pending";
        return didPreviousUpdateSucceed() ? "Succeeded" : "Failed";
    }

    /**
     * Returns file where WebAPK update data should be stored and stores the file name in
     * SharedPreferences.
     */
    String createAndSetUpdateRequestFilePath(WebappInfo info) {
        String filePath = WebappDirectoryManager.getWebApkUpdateFilePathForStorage(this).getPath();
        mPreferences.edit().putString(KEY_PENDING_UPDATE_FILE_PATH, filePath).apply();
        return filePath;
    }

    /** Returns the path of the file which contains data to update the WebAPK. */
    @Nullable
    String getPendingUpdateRequestPath() {
        return mPreferences.getString(KEY_PENDING_UPDATE_FILE_PATH, null);
    }

    /**
     * Deletes the file which contains data to update the WebAPK. The file is large (> 1Kb) and
     * should be deleted when the update completes.
     */
    void deletePendingUpdateRequestFile() {
        final String pendingUpdateFilePath = getPendingUpdateRequestPath();
        if (pendingUpdateFilePath == null) return;

        mPreferences.edit().remove(KEY_PENDING_UPDATE_FILE_PATH).apply();
        PostTask.postTask(TaskTraits.BEST_EFFORT_MAY_BLOCK, () -> {
            if (!new File(pendingUpdateFilePath).delete()) {
                Log.d(TAG, "Failed to delete file " + pendingUpdateFilePath);
            }
        });
    }

    /**
     * Returns whether a check for whether the Web Manifest needs to be updated has occurred in the
     * last {@link numMillis} milliseconds.
     */
    boolean wasCheckForUpdatesDoneInLastMs(long numMillis) {
        return (sClock.currentTimeMillis() - getLastCheckForWebManifestUpdateTimeMs()) < numMillis;
    }

    /** Returns whether we should check for update. */
    boolean shouldCheckForUpdate() {
        if (shouldForceUpdate()) return true;
        long checkUpdatesInterval =
                shouldRelaxUpdates() ? RELAXED_UPDATE_INTERVAL : UPDATE_INTERVAL;
        long now = sClock.currentTimeMillis();
        long sinceLastCheckDurationMs = now - getLastCheckForWebManifestUpdateTimeMs();
        return sinceLastCheckDurationMs >= checkUpdatesInterval;
    }

    protected WebappDataStorage(String webappId) {
        mId = webappId;
        mPreferences = ContextUtils.getApplicationContext().getSharedPreferences(
                SHARED_PREFS_FILE_PREFIX + webappId, Context.MODE_PRIVATE);
    }

    /**
     * Fetches the timestamp that the WebAPK was installed from the PackageManager.
     */
    private long fetchWebApkInstallTimestamp(String webApkPackageName) {
        try {
            PackageManager packageManager =
                    ContextUtils.getApplicationContext().getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(webApkPackageName, 0);
            return packageInfo.firstInstallTime;
        } catch (PackageManager.NameNotFoundException e) {
        }
        return 0;
    }

    /**
     * Returns the timestamp when the WebAPK was installed.
     */
    public long getWebApkInstallTimestamp() {
        return mPreferences.getLong(KEY_WEBAPK_INSTALL_TIMESTAMP, 0);
    }

    /**
     * Sets the timestamp when the WebAPK was uninstalled to the current time.
     */
    public void setWebApkUninstallTimestamp() {
        mPreferences.edit()
                .putLong(KEY_WEBAPK_UNINSTALL_TIMESTAMP, sClock.currentTimeMillis())
                .apply();
    }

    /**
     * Returns the timestamp when the WebAPK was uninstalled.
     */
    public long getWebApkUninstallTimestamp() {
        return mPreferences.getLong(KEY_WEBAPK_UNINSTALL_TIMESTAMP, 0);
    }

    /**
     * Increments the number of times that the webapp was launched.
     */
    public void incrementLaunchCount() {
        int launchCount = getLaunchCount();
        mPreferences.edit().putInt(KEY_LAUNCH_COUNT, launchCount + 1).apply();
    }

    /**
     * Returns the number of times that the webapp was launched.
     */
    public int getLaunchCount() {
        return mPreferences.getInt(KEY_LAUNCH_COUNT, 0);
    }

    /**
     * Returns cached Web Manifest URL.
     */
    public String getWebApkManifestUrl() {
        return mPreferences.getString(KEY_WEBAPK_MANIFEST_URL, null);
    }

    /**
     * Returns cached WebAPK version code.
     */
    public int getWebApkVersionCode() {
        return mPreferences.getInt(KEY_WEBAPK_VERSION_CODE, 0);
    }
}


text:
package com.kakao.hbase.manager.command;

import com.kakao.hbase.ManagerArgs;
import com.kakao.hbase.TestBase;
import com.kakao.hbase.common.Args;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Test;

import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class SplitHexStringTest extends TestBase {
    public SplitHexStringTest() {
        super(SplitHexStringTest.class);
    }

    @Test
    public void testSplitRuleRegex() throws Exception {
        String tableName2 = createAdditionalTable(tableName + "2");

        // split
        String tableNameRegex = tableName2 + ".*";
        String[] argsParam = {"zookeeper", tableNameRegex, "Rule", "hexString_down", "3", "--force-proceed"};
        Args args = new ManagerArgs(argsParam);
        assertEquals("zookeeper", args.getZookeeperQuorum());
        Command command = new Split(admin, args);

        command.run();
        waitForSplitting(tableName2, 3);

        assertEquals(1, getRegionInfoList(tableName).size());
        assertEquals(3, getRegionInfoList(tableName2).size());
    }

    @Test
    public void testSplitWithHexStringDowncaseRule() throws Exception {
        List<HRegionInfo> regionInfoList;

        regionInfoList = getRegionInfoList(tableName);
        assertEquals(1, regionInfoList.size());

        String[] argsParam = {"zookeeper", tableName, "Rule", "hexString_down", "5", "--force-proceed"};
        Args args = new ManagerArgs(argsParam);
        assertEquals("zookeeper", args.getZookeeperQuorum());
        Split command = new Split(admin, args);

        command.run();
        waitForSplitting(5);

        regionInfoList = getRegionInfoList(tableName);
        assertEquals(5, regionInfoList.size());
        for (HRegionInfo hRegionInfo : regionInfoList) {
            byte[] startKey = hRegionInfo.getStartKey();
            if (startKey.length > 0) {
                assertTrue(Bytes.toString(startKey).matches("[a-z0-9]*"));
                assertFalse(Bytes.toString(startKey).matches("[A-Z]*"));
            }
        }
    }

    @Test
    public void testSplitWithHexStringUpcaseRule() throws Exception {
        List<HRegionInfo> regionInfoList;

        regionInfoList = getRegionInfoList(tableName);
        assertEquals(1, regionInfoList.size());

        String[] argsParam = {"zookeeper", tableName, "Rule", "hexString_up", "5", "--force-proceed"};
        Args args = new ManagerArgs(argsParam);
        assertEquals("zookeeper", args.getZookeeperQuorum());
        Split command = new Split(admin, args);

        command.run();
        waitForSplitting(5);

        regionInfoList = getRegionInfoList(tableName);
        assertEquals(5, regionInfoList.size());
        for (HRegionInfo hRegionInfo : regionInfoList) {
            byte[] startKey = hRegionInfo.getStartKey();
            if (startKey.length > 0) {
                assertTrue(Bytes.toString(startKey).matches("[A-Z0-9]*"));
                assertFalse(Bytes.toString(startKey).matches("[a-z]*"));
            }
        }
    }
}


text:
namespace OpenQA.Selenium.DevTools.Page
{
    using Newtonsoft.Json;

    /// <summary>
    /// Tries to close page, running its beforeunload hooks, if any.
    /// </summary>
    public sealed class CloseCommandSettings : ICommand
    {
        private const string DevToolsRemoteInterface_CommandName = "Page.close";

        [JsonIgnore]
        public string CommandName
        {
            get { return DevToolsRemoteInterface_CommandName; }
        }

    }

    public sealed class CloseCommandResponse : ICommandResponse<CloseCommandSettings>
    {
    }
}


text:
'use strict';

angular.module('users').controller('MyMessagesController', ['$scope', '$http', '$location', 'Users', 'Authentication',
  function ($scope, $http, $location, Users, Authentication) {
    $scope.user = Authentication.user;

    $scope.getDate = function (date) {
      return moment(date).format('DD-MM-YYYY');
    };

    $scope.getTime = function (date) {
      return moment(date).format('HH:mm');
    };

    $scope.init = function () {
      $http.get('/usermessages').success(function (response) {
        // If successful we assign the response to the global user model
        $scope.messages = response;

        // And redirect to the index page

      }).error(function (response) {
        $scope.error = response.message;
      });
    };
  }
]);


text:
package com.hussainmukadam.watchit.notification;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.hussainmukadam.watchit.BuildConfig;
import com.hussainmukadam.watchit.R;
import com.hussainmukadam.watchit.mainpage.model.TvSeries;
import com.hussainmukadam.watchit.util.Util;
import com.hussainmukadam.watchit.util.WatchItConstants;
import com.hussainmukadam.watchit.BaseActivity;
import com.hussainmukadam.watchit.mainpage.model.Movie;
import com.squareup.picasso.Picasso;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Random;

import io.realm.Realm;
import io.realm.RealmResults;

/**
 * Created by hussain on 8/28/17.
 */

public class NotificationPublisher extends BroadcastReceiver {
    private static final String TAG = "NotificationPublisher";
    private static final String CHANNEL_ID = "1";

    private NotificationManager notifManager;

    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.getAction() != null) {
            Util.debugLog(TAG, "onReceive: Inside Notification Receiver Outside getAction()");
            if (intent.getAction().equals(WatchItConstants.NOTIFICATION_MESSAGE)) {

                Util.debugLog(TAG, "onReceive: Inside Notification Receiver");

                Object randomMovieOrTvSeries = fetchRandomMovieOrTvSeries();

                if (randomMovieOrTvSeries != null && Util.isConnected(context)) {
                    createSuggestionNotification(randomMovieOrTvSeries, context);
                } else {
                    Util.debugLog(TAG, "Inside else");
                    createRetentionNotification(context);
                }
            }
        }
    }

    public void createSuggestionNotification(Object randomMovieOrTvSeries, Context context) {
        NotificationImageTask notificationImageTask = new NotificationImageTask(context);
        Movie movie = null;
        TvSeries tvSeries = null;
        Bitmap largeIconBitmap = null;
        PendingIntent sharePendingIntent;

        Intent doneIntent = new Intent(context, NotificationActionHandler.class);
        Bundle bundle = new Bundle();
        doneIntent.setAction("DONE_ACTION");
        doneIntent.putExtras(bundle);
        PendingIntent donePendingIntent = PendingIntent.getBroadcast(context, WatchItConstants.ALARM_TYPE_RTC, doneIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        if (randomMovieOrTvSeries instanceof Movie) {
            movie = (Movie) randomMovieOrTvSeries;
            Intent shareIntent = new Intent(context, NotificationActionHandler.class);
            Bundle shareBundle = new Bundle();
            shareBundle.putParcelable("NOTIF_DATA", movie);
            shareIntent.setAction("SHARE_ACTION");
            shareIntent.putExtras(shareBundle);
            sharePendingIntent = PendingIntent.getBroadcast(context, WatchItConstants.ALARM_TYPE_RTC, shareIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            try {
                largeIconBitmap = notificationImageTask.execute(BuildConfig.imageBaseUrl + movie.getPosterPath()).get();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            tvSeries = (TvSeries) randomMovieOrTvSeries;
            Intent shareIntent = new Intent(context, NotificationActionHandler.class);
            Bundle shareBundle = new Bundle();
            shareBundle.putParcelable("NOTIF_DATA", tvSeries);
            shareIntent.setAction("SHARE_ACTION");
            shareIntent.putExtras(shareBundle);
            sharePendingIntent = PendingIntent.getBroadcast(context, WatchItConstants.ALARM_TYPE_RTC, shareIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            try {
                largeIconBitmap = notificationImageTask.execute(BuildConfig.imageBaseUrl + tvSeries.getTvPosterPath()).get();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // There are hardcoding only for show it's just strings
        String name = "WatchIt Channels";
        String id = "Suggestions"; // The user-visible name of the channel.
        String description = "Movie/TV Series Suggestion on Weekends"; // The user-visible description of the channel.

        Intent intent;
        PendingIntent pendingIntent;
        NotificationCompat.Builder builder;

        if (notifManager == null) {
            notifManager = NotificationHelper.getNotificationManager(context);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_HIGH;

            NotificationChannel mChannel = notifManager.getNotificationChannel(id);

            if (mChannel == null) {
                mChannel = new NotificationChannel(id, name, importance);
                mChannel.setDescription(description);
                mChannel.enableVibration(true);
                mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
                notifManager.createNotificationChannel(mChannel);
            }

            builder = new NotificationCompat.Builder(context, id);
            //context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
            Intent launchIntent = new Intent(context, BaseActivity.class);
            launchIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            if (movie != null) {
                launchIntent.putExtra("NOTIFICATION_DETAIL", movie);
            } else {
                launchIntent.putExtra("NOTIFICATION_DETAIL", tvSeries);
            }
            pendingIntent = PendingIntent.getActivity(context, 0, launchIntent, PendingIntent.FLAG_UPDATE_CURRENT);

            if (movie != null) {
                builder.setContentTitle(movie.getMovieTitle())
                        .setTicker(movie.getMovieTitle())
                        .setStyle(new NotificationCompat.BigPictureStyle()
                                .bigPicture(largeIconBitmap));
            } else {
                builder.setContentTitle(tvSeries.getTvTitle())
                        .setTicker(tvSeries.getTvTitle())
                        .setStyle(new NotificationCompat.BigPictureStyle()
                                .bigPicture(largeIconBitmap));
            }

            builder.setSmallIcon(R.drawable.ic_logo_notification)
                    .setContentText(context.getString(R.string.app_name))
                    .addAction(R.drawable.ic_done_black_24dp, "DONE", donePendingIntent)
                    .addAction(R.drawable.ic_share_black_24dp, "SHARE", sharePendingIntent)
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setAutoCancel(true)
                    .setContentIntent(pendingIntent)
                    .setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
        } else {
            Log.d(TAG, "createSuggestionNotification: Inside Else lower SDK");
            builder = new NotificationCompat.Builder(context);

            intent = new Intent(context, BaseActivity.class);
            if (movie != null) {
                intent.putExtra("NOTIFICATION_DETAIL", movie);
            } else {
                intent.putExtra("NOTIFICATION_DETAIL", tvSeries);
            }
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

            if (movie != null) {
                builder.setContentTitle(movie.getMovieTitle())
                        .setStyle(new NotificationCompat.BigPictureStyle()
                                .bigPicture(largeIconBitmap));
            } else {
                builder.setContentTitle(tvSeries.getTvTitle())
                        .setStyle(new NotificationCompat.BigPictureStyle()
                                .bigPicture(largeIconBitmap));
            }

            builder.setSmallIcon(R.drawable.ic_logo_notification)
                    .setContentText(context.getString(R.string.app_name))
                    .addAction(R.drawable.ic_done_black, "DONE", donePendingIntent)
                    .addAction(R.drawable.ic_share_black, "SHARE", sharePendingIntent)
                    .setContentIntent(pendingIntent)
                    .setPriority(Notification.PRIORITY_HIGH);
        }

        notifManager.notify(WatchItConstants.NOTIFICATION_ID, builder.build());

    }

    private void createRetentionNotification(Context context) {
        // There are hardcoding only for show it's just strings
        String name = "WatchIt Channels";
        String id = "Retention"; // The user-visible name of the channel.
        String description = "Check out Watch it! Discover new Movies/TV Series to Watch"; // The user-visible description of the channel.

        Intent intent;
        PendingIntent pendingIntent;
        NotificationCompat.Builder builder;

        if (notifManager == null) {
            notifManager = NotificationHelper.getNotificationManager(context);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_HIGH;

            NotificationChannel mChannel = notifManager.getNotificationChannel(id);

            if (mChannel == null) {
                mChannel = new NotificationChannel(id, name, importance);
                mChannel.setDescription(description);
                mChannel.enableVibration(true);
                mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
                notifManager.createNotificationChannel(mChannel);
            }

            builder = new NotificationCompat.Builder(context, id);

            intent = new Intent(context, BaseActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

            builder.setContentTitle(description)  // required
                    .setSmallIcon(R.drawable.ic_logo_notification) // required
                    .setContentText(context.getString(R.string.app_name))  // required
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setAutoCancel(true)
                    .setContentIntent(pendingIntent)
                    .setTicker(context.getString(R.string.app_name))
                    .setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
        } else {

            builder = new NotificationCompat.Builder(context);

            intent = new Intent(context, BaseActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

            builder.setContentTitle(description)                           // required
                    .setSmallIcon(R.drawable.ic_logo_notification) // required
                    .setContentText(context.getString(R.string.app_name))  // required
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setAutoCancel(true)
                    .setContentIntent(pendingIntent)
                    .setTicker(context.getString(R.string.app_name))
                    .setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
                    .setPriority(Notification.PRIORITY_HIGH);
        }

        Notification notification = builder.build();
        notifManager.notify(WatchItConstants.NOTIFICATION_ID, notification);

    }

    private Object fetchRandomMovieOrTvSeries() {
        Realm realm = Realm.getDefaultInstance();
        //TODO: Add Random TV Series to fetch
        RealmResults<Movie> movieRealmResults = realm.where(Movie.class).equalTo("isNotified", false).findAll();

        RealmResults<TvSeries> tvSeriesRealmResults = realm.where(TvSeries.class).equalTo("isNotified", false).findAll();

        Util.debugLog(TAG, "fetchRandomMovieOrTvSeries: Size of movies with isNotified false " + movieRealmResults.size());

        if (movieRealmResults.size() != 0) {

            if (tvSeriesRealmResults.size() != 0) {

                if (movieRealmResults.size() > tvSeriesRealmResults.size()) {
                    Random r = new Random();
                    int randomNumber = r.nextInt(movieRealmResults.size());

                    Movie movie = movieRealmResults.get(randomNumber);

                    realm.beginTransaction();
                    movieRealmResults.get(randomNumber).setNotified(true);
                    realm.commitTransaction();

                    return movie;

                } else {

                    Random r = new Random();
                    int randomNumber = r.nextInt(tvSeriesRealmResults.size());

                    TvSeries tvSeries = tvSeriesRealmResults.get(randomNumber);

                    realm.beginTransaction();
                    tvSeriesRealmResults.get(randomNumber).setNotified(true);
                    realm.commitTransaction();

                    return tvSeries;
                }

            } else {

                Random r = new Random();
                int randomNumber = r.nextInt(movieRealmResults.size());

                Movie movie = movieRealmResults.get(randomNumber);

                realm.beginTransaction();
                movieRealmResults.get(randomNumber).setNotified(true);
                realm.commitTransaction();

                return movie;
            }

        } else {
            return null;
        }
    }
}


text:
<?php

class Controller_Accounts extends Controller_Template
{

	public function action_index()
	{
		$data["subnav"] = array();
		$this->template->screen_name = Auth::get_profile_fields('fullname', 'Unknown name');
		$this->template->title = 'Accounts';
		$this->template->content = \View::forge('accounts/default', $data);
	}
	public function action_delete()
	{
		try {
			Auth::delete_user(Input::post('username'));
		}
		catch (SimpleUserUpdateException $e) {
			Debug::dump($e);
		}
		\Response::redirect('accounts');
	}
	public function action_login()
	{
		$this->template->screen_name = Auth::get_profile_fields('fullname', 'Unknown name');

	    if (\Auth::check()) {
	        \Response::redirect('accounts');
	    }

	    if (\Input::method() == 'POST')
	    {
	        if (\Auth::instance()->login(\Input::param('username'), \Input::param('password')))
	        {
	            if (\Input::param('remember', false)) {
	                \Auth::remember_me();
	            } else {
	                \Auth::dont_remember_me();
	            }
	            \Response::redirect('accounts');
	        }
	        else {
	        	$data['incorrect_username_or_password'] = true;
	        }
	    }
		$data["subnav"] = array('login'=> 'active' );
		$this->template->title = 'Login';
		$this->template->content = \View::forge('accounts/login', $data);
	}

	public function action_register()
	{
	    if ( ! \Config::get('are_new_user_registrations_enabled', false)) {
	        \Response::redirect_back();
	    }

		$data = array();
		$data["errors"] = array();

	    $fieldset = \Fieldset::forge();
	    $fieldset->form()->set_attribute('id', 'register-form');
	    $fieldset->form()->add_csrf();
	    $fieldset->add_model('Model\\Auth_User');
	    $fieldset->add_after('fullname', 'Full Name', array(), array('required'), 'email');

	    //Using email as username
	    $fieldset->disable('username');
	    $fieldset->disable('group_id');

	    $fieldset->field('email')->set_attribute('type', 'email');

	    $fieldset->field('password')->set_attribute('class', 'form-control');
	    $fieldset->field('email')->set_attribute('class', 'form-control');
	    $fieldset->field('fullname')->set_attribute('class', 'form-control');

	    if (\Input::method() == 'POST')
	    {
			$params = Input::post();
			$params['group_id'] = \Config::get('application.user.default_group', 1);
			array_key_exists('email', $params) and $params['username'] = $params['email'];

	        $fieldset->validation()->run($params);

	        if ( ! $fieldset->validation()->error())
	        {
	            try
	            {
	                $created = \Auth::create_user(
	                    $fieldset->validated('email'),//$fieldset->validated('username'),
	                    $fieldset->validated('password'),
	                    $fieldset->validated('email'),
	                    $fieldset->validated('group_id'),
	                    array('fullname' => $fieldset->validated('fullname'))
	                );
	                if ($created)
	                {
	                	\Auth::instance()->login(
	                		$fieldset->validated('username'),
	                		$fieldset->validated('password')
	                	);
	                    \Response::redirect('accounts');
	                }
	            }
	            catch (\SimpleUserUpdateException $e)
	            {
	                // duplicate email
	                if ($e->getCode() == 2){
	                	array_push($data["errors"],
	                		array('email', 'email_already_registered', 'This email is already registered, try logging in.')
	                	);
	                }
	                // duplicate username
	                elseif ($e->getCode() == 3) {
	                	array_push($data["errors"],
	                		array('username', 'username_already_registered', 'This username is already registered, try logging in.')
	                	);
	                }
	                else {

	                    //\Messages::error($e->getMessage());
	                }
	            }
	        }
	        else
	        {
	        	foreach ($fieldset->error() as $field => $error)
			    {
			    	array_push($data["errors"],
			    		array($field,
			    			$error->get_message(':rule'),
			    			$error->get_message()));
	        	}
	        }

	        // validation failed, repopulate form from posted data
	        $fieldset->repopulate();
	    }

	    if ( ! array_key_exists('errors', $data)) {
	    	$data['errors'] = array();
	    }

	    $fieldset->add('submit', '', array('type' => 'submit', 'id'=>'register-form__submit-button', 'value' => 'Create account', 'class' => 'btn btn-primary register-form__submit-button'));

		$data["subnav"] = array('register'=> 'active' );
		$this->template->title = 'Create account';
		$this->template->screen_name = Auth::get_profile_fields('fullname', 'Unknown name');
	    $this->template->content = \View::forge('accounts/register', $data)->set('form', $fieldset, false);
	}

	public function action_logout()
	{
	    \Auth::dont_remember_me();
	    \Auth::logout();
	    //\Messages::success(__('login.logged-out'));

	    // and go back to where you came from (or the application
	    // homepage if no previous page can be determined)
	    //\Response::redirect('accounts');
	    \Response::redirect('accounts/login');

		//$data["subnav"] = array('logout'=> 'active' );
		//$this->template->title = 'Accounts » Logout';
		//$this->template->content = View::forge('accounts/logout', $data);
	}

	public function action_passwordrecovery($hash = null)
	{
		Debug::dump('Error: password recovery is not currently available. Email needs to be set up');
		//TESTED AND WORKS. JUST NEEDS TO BE HOOKED UP TO EMAIL
	    if (\Input::method() == 'POST')
	    {
	        if ($email = \Input::post('email'))
	        {
	            if ($user = \Model\Auth_User::find_by_email($email))
	            {
	                // generate a recovery hash
	                $hash = \Auth::instance()->hash_password(\Str::random()).$user->id;

	                // and store it in the user profile
	                \Auth::update_user(
	                    array(
	                        'lostpassword_hash' => $hash,
	                        'lostpassword_created' => time()
	                    ),
	                    $user->username
	                );
	                $data['password_url'] = '/accounts/lostpassword/'.base64_encode($hash);

	                /*
	                // send an email out with a reset link
	                \Package::load('email');
	                $email = \Email::forge();

	                // use a view file to generate the email message
	                $email->html_body(
	                    \Theme::instance()->view('login/lostpassword')
	                        ->set('url', \Uri::create('login/lostpassword/' . base64_encode($hash) . '/'), false)
	                        ->set('user', $user, false)
	                        ->render()
	                );
					//$domain_name = Uri::base(false);
					//$password_resovery_hash = base64_encode($hash);
					//$email->html_body(
					//	'Reset your password'
					//, false);
	                $email->subject('Harpoon password recovery');
	                $from = \Config::get('customer_service_email_address', array('name'=>'','email'=>''));
	                $email->from($from['from-email'], $from['brand-name']);
	                $email->to($user->email, $user->fullname);

	                try
	                {
	                    $email->send();
	                }
	                catch(\EmailValidationFailedException $e)
	                {
	                    //\Messages::error(__('login.invalid-email-address'));
	                    \Response::redirect_back();
	                }
	                catch(\Exception $e)
	                {
	                    // log the error so an administrator can have a look
	                    logger(\Fuel::L_ERROR, '*** Error sending email ('.__FILE__.'#'.__LINE__.'): '.$e->getMessage());

	                    //\Messages::error(__('login.error-sending-email'));
	                    \Response::redirect_back();
	                }
	                */
	            }
	        }
	        //else
	        //{
	            // inform the user and fall through to the form
	            //\Messages::error(__('login.error-missing-email'));
	        //}

	        // inform the user an email is on the way (or not ;-))
	        //\Messages::info(__('login.recovery-email-send'));
	        //\Response::redirect_back();
	    }
	    elseif ($hash !== null)
	    {
	        $hash = base64_decode($hash);
	        // get the userid from the hash
	        $user = substr($hash, 44);

	        if ($user = \Model\Auth_User::find_by_id($user))
	        {
	            // do we have this hash for this user, and hasn't it expired yet (we allow for 24 hours response)?
	            if (isset($user->lostpassword_hash) and $user->lostpassword_hash == $hash and time() - $user->lostpassword_created < 86400)
	            {
	                // invalidate the hash
	                \Auth::update_user(
	                    array(
	                        'lostpassword_hash' => null,
	                        'lostpassword_created' => null
	                    ),
	                    $user->username
	                );

	                // log the user in and go to the profile to change the password
	                if (\Auth::instance()->force_login($user->id))
	                {
	                    //\Messages::info(__('login.password-recovery-accepted'));
	                    \Response::redirect('profile');
	                }
	            }
	        }
	        //\Messages::error(__('login.recovery-hash-invalid'));
	        \Response::redirect_back();
	    }

		$data["subnav"] = array('passwordrecovery'=> 'active' );

		empty($data['password_url']) and $data['password_url'] = '';
		$this->template->title = 'Accounts » Passwordrecovery';
		$this->template->content = View::forge('accounts/passwordrecovery', $data);
		$this->template->screen_name = Auth::get_profile_fields('fullname', 'Unknown name');

	}
	public function action_changepassword() {
		if ( ! Auth::check()) {
			\Response::redirect('accounts/login');
		}

		if (\Input::method() == 'POST') {
			$is_password_changed = Auth::change_password(
				Input::post('oldpassword'),
				Input::post('newpassword')
			);
			if ($is_password_changed) {
				\Response::redirect('accounts');
			}
		}

		$data = array();
		$data['subnav'] = array();
		$this->template->title = 'Accounts » Change password';
		$this->template->content = View::forge('accounts/change-password', $data);
		$this->template->screen_name = Auth::get_profile_fields('fullname', 'Unknown name');
	}

}


text:
'use strict'

var api = require('../api/pressure')
var def = require('../definition/pressure/pound-per-square-foot')

var unit = 'pound-per-square-foot'

api.augment(unit, def)

module.exports = api.get(unit)


text:
@implementation LoginViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    [self setEdgesForExtendedLayout:UIRectEdgeNone];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.screenName = @"Login";
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO];

    [self.backgroundImage setImage:[[RODImageStore sharedStore] imageForKey:@"B14253A0-E5D0-43DB-A1E1-629EED91FCBE"]];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)doLogin:(id)sender {

    // Block whole window

    MRProgressOverlayView *progressView = [MRProgressOverlayView new];
    progressView.titleLabelText = @"syncing, pls chill a moment";
    progressView.titleLabel.font = [UIFont systemFontOfSize:10];

    [self.navigationController.view.window addSubview:progressView];

    [self.textHandle resignFirstResponder];
    [self.textKey resignFirstResponder];

    [progressView show:YES];

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
    dispatch_async(queue, ^{
        // Perform async operation
        NSString *results = [[RODItemStore sharedStore] login:self.textHandle.text privateKey:self.textKey.text];

        dispatch_sync(dispatch_get_main_queue(), ^{
            // Update UI

            if([RODItemStore sharedStore].authie.registered == 1) {
                [[RODItemStore sharedStore] loadThreads:false];
                [[RODItemStore sharedStore] loadContacts];
                [[RODItemStore sharedStore] loadMessages:nil];

                AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
                [appDelegate.dashViewController setDoGetThreadsOnView:YES];
                appDelegate.dashViewController.navigationItem.titleView = [[RODItemStore sharedStore] generateHeaderView];

                [appDelegate.navigationViewController popToRootViewControllerAnimated:NO];

            } else {
                [self.labelResults setText:results];
            }

            [progressView dismiss:YES];

        });
    });

}

- (IBAction)cancel:(id)sender {

    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate.dashViewController.navigationController popToViewController:appDelegate.registerViewController animated:YES];

}

@end


text:
// Copyright (c) 2009-2014 The VeriCoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#ifndef BITCOIN_CHECKPOINTS_H
#define BITCOIN_CHECKPOINTS_H

#include "uint256.h"

#include <map>

class CBlockIndex;

/**
 * Block-chain checkpoints are compiled-in sanity checks.
 * They are updated every release or three.
 */
namespace Checkpoints
{
typedef std::map<int, uint256> MapCheckpoints;

struct CCheckpointData {
    MapCheckpoints mapCheckpoints;
    int64_t nTimeLastCheckpoint;
    int64_t nTransactionsLastCheckpoint;
    double fTransactionsPerDay;
};

//! Returns true if block passes checkpoint checks
bool CheckBlock(const CCheckpointData& data, int nHeight, const uint256& hash);

//! Return conservative estimate of total number of blocks, 0 if unknown
int GetTotalBlocksEstimate(const CCheckpointData& data);

//! Returns last CBlockIndex* in mapBlockIndex that is a checkpoint
CBlockIndex* GetLastCheckpoint(const CCheckpointData& data);

double GuessVerificationProgress(const CCheckpointData& data, CBlockIndex* pindex, bool fSigchecks = true);

} //namespace Checkpoints

#endif // BITCOIN_CHECKPOINTS_H


text:
package com.zaradai.distributor.messaging;

import org.junit.Test;

import java.net.InetSocketAddress;
import java.util.Set;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;

public class MessageTest {
    private static final InetSocketAddress TEST_ADDRESS = mock(InetSocketAddress.class);
    private static final Object TEST_EVENT = new Object();
    private static final boolean TEST_INCOMING = true;

    @Test
    public void shouldGetSource() throws Exception {
        Message uut = new Message();
        uut.setSource(TEST_ADDRESS);

        assertThat(uut.getSource(), is(TEST_ADDRESS));
    }

    @Test
    public void shouldGetEvent() throws Exception {
        Message uut = new Message();
        uut.setEvent(TEST_EVENT);

        assertThat(uut.getEvent(), is(TEST_EVENT));
    }

    @Test(expected = NullPointerException.class)
    public void shouldThrowIfSettingWithNullEvent() throws Exception {
        Message uut = new Message();
        uut.setEvent(null);
    }

    @Test
    public void shouldGetIncoming() throws Exception {
        Message uut = new Message();
        uut.setIncoming(TEST_INCOMING);

        assertThat(uut.isIncoming(), is(TEST_INCOMING));
    }

    @Test
    public void shouldAddTarget() throws Exception {
        Message uut = new Message();
        uut.addTarget(TEST_ADDRESS);

        Set<InetSocketAddress> res = uut.getTargets();

        assertThat(res.size(), is(1));
        assertThat(res.contains(TEST_ADDRESS), is(true));
    }

    @Test
    public void shouldClearTargets() throws Exception {
        Message uut = new Message();
        uut.addTarget(TEST_ADDRESS);

        uut.clearTargets();

        Set<InetSocketAddress> res = uut.getTargets();

        assertThat(res.size(), is(0));
    }

    @Test
    public void shouldCreateWihBuilder() throws Exception {
        Message uut = new Message.Builder().addTarget(TEST_ADDRESS).event(TEST_EVENT).from(TEST_ADDRESS).build();

        assertThat(uut.getEvent(), is(TEST_EVENT));
        assertThat(uut.isIncoming(), is(false));
        assertThat(uut.getSource(), is(TEST_ADDRESS));

        Set<InetSocketAddress> res = uut.getTargets();

        assertThat(res.size(), is(1));
        assertThat(res.contains(TEST_ADDRESS), is(true));
    }
}


text:
// example-scene.js
// just and example of how to use cosmonaut

var harness = require('cosmonaut-harness');

var scene = new harness.scene({webgl: true});
scene.attachToDom($('#context'));

var sphere = new harness.primitive.sphere({
  radius: 50
});

var cube = new harness.primitive.cube({
  x: -10,
  y: 100,
  z: 10
});

var light = new harness.light();

var lambert = new harness.material();

sphere.set('material', lambert);
cube.set('material', lambert);

scene.addObject(sphere);
scene.addObject(cube);

scene.addLight(light);

var time = 0;

/*scene.on('prerender', function() {
  time++;
});*/

//scene.camera.set('lookAtObject', sphere);

scene.startRenderLoop();


text:
<?php

namespace Medusa\Queue;

interface Queue extends \Traversable, \Countable
{
    public function isEmpty();

    public function peek();

    public function enqueue($value);

    public function dequeue();
}


text:
from .core import *
from .awdlstm import *


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Roomster.Models.DTOs;

namespace Roomster.ViewModels
{
    public class PersonFormVm
    {
        public PersonDto Person { get; set; }
        public List<TeamDto> Teams { get; set; }
    }
}