text:
package com.sequenceiq.cloudbreak.cm.polling.task;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;

import java.math.BigDecimal;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import com.cloudera.api.swagger.HostsResourceApi;
import com.cloudera.api.swagger.client.ApiClient;
import com.cloudera.api.swagger.client.ApiException;
import com.cloudera.api.swagger.model.ApiHost;
import com.cloudera.api.swagger.model.ApiHostList;
import com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.base.InstanceStatus;
import com.sequenceiq.cloudbreak.cluster.service.ClusterEventService;
import com.sequenceiq.cloudbreak.cm.client.ClouderaManagerApiPojoFactory;
import com.sequenceiq.cloudbreak.cm.polling.ClouderaManagerCommandPollerObject;
import com.sequenceiq.cloudbreak.domain.stack.Stack;
import com.sequenceiq.cloudbreak.domain.stack.instance.InstanceGroup;
import com.sequenceiq.cloudbreak.domain.stack.instance.InstanceMetaData;

@SuppressWarnings("checkstyle:Regexp")
@RunWith(MockitoJUnitRunner.class)
public class ClouderaManagerHostStatusCheckerTest {

    private static final String VIEWTYPE = "FULL";

    @Mock
    private ClouderaManagerApiPojoFactory clouderaManagerApiPojoFactory;

    @Mock
    private ClusterEventService clusterEventService;

    @Mock
    private HostsResourceApi hostsResourceApi;

    private ClouderaManagerHostStatusChecker underTest;

    @Before
    public void init() {
        underTest = new ClouderaManagerHostStatusChecker(clouderaManagerApiPojoFactory, clusterEventService, false);
        when(clouderaManagerApiPojoFactory.getHostsResourceApi(any(ApiClient.class))).thenReturn(hostsResourceApi);
    }

    @Test
    public void shouldBeFalseWhenNoHostsReturned() throws ApiException {
        InstanceMetaData instanceMetaData = validInstanceMetadata();
        when(hostsResourceApi.readHosts(null, null, VIEWTYPE)).thenReturn(new ApiHostList().items(Collections.emptyList()));

        boolean result = underTest.doStatusCheck(getPollerObject(instanceMetaData));

        assertFalse(result);
    }

    @Test
    public void shouldBeFalseWhenHostsReturnedHasNoHeartbeat() throws ApiException {
        InstanceMetaData instanceMetaData = validInstanceMetadata();
        ApiHost apiHost = new ApiHost().ipAddress(instanceMetaData.getPrivateIp());
        when(hostsResourceApi.readHosts(null, null, VIEWTYPE)).thenReturn(new ApiHostList().items(List.of(apiHost)));

        boolean result = underTest.doStatusCheck(getPollerObject(instanceMetaData));

        assertFalse(result);
    }

    @Test
    public void shouldBeFalseWhenHostsReturnedHasOldHeartbeat() throws ApiException {
        InstanceMetaData instanceMetaData = validInstanceMetadata();
        ApiHost apiHost = new ApiHost()
                .ipAddress(instanceMetaData.getPrivateIp())
                .lastHeartbeat(Instant.now().minus(5, ChronoUnit.MINUTES).toString());
        when(hostsResourceApi.readHosts(null, null, VIEWTYPE)).thenReturn(new ApiHostList().items(List.of(apiHost)));

        boolean result = underTest.doStatusCheck(getPollerObject(instanceMetaData));

        assertFalse(result);
    }

    @Test
    public void shouldBeTrueWhenHostsReturnedHasRecentHeartbeat() throws ApiException {
        InstanceMetaData instanceMetaData = validInstanceMetadata();
        ApiHost apiHost = getValidApiHost(instanceMetaData);
        when(hostsResourceApi.readHosts(null, null, VIEWTYPE)).thenReturn(new ApiHostList().items(List.of(apiHost)));

        boolean result = underTest.doStatusCheck(getPollerObject(instanceMetaData));

        assertTrue(result);
    }

    @Test
    public void shouldBeFalseWhenHostsReturnedHasDifferentIp() throws ApiException {
        InstanceMetaData instanceMetaData = validInstanceMetadata();
        ApiHost apiHost = new ApiHost()
                .ipAddress("2.2.2.2")
                .lastHeartbeat(Instant.now().plus(5, ChronoUnit.MINUTES).toString());
        when(hostsResourceApi.readHosts(null, null, VIEWTYPE)).thenReturn(new ApiHostList().items(List.of(apiHost)));

        boolean result = underTest.doStatusCheck(getPollerObject(instanceMetaData));

        assertFalse(result);
    }

    @Test
    public void shouldBeFalseWhenHostsHasMissingHost() throws ApiException {
        InstanceMetaData instanceMetaData = validInstanceMetadata();
        InstanceMetaData instanceMetaData2 = validInstanceMetadata();
        instanceMetaData2.setPrivateIp("2.2.2.2");
        ApiHost apiHost = getValidApiHost(instanceMetaData);
        when(hostsResourceApi.readHosts(null, null, VIEWTYPE)).thenReturn(new ApiHostList().items(List.of(apiHost)));

        boolean result = underTest.doStatusCheck(getPollerObject(instanceMetaData, instanceMetaData2));

        assertFalse(result);
    }

    @Test
    public void shouldBeTrueWhenMultipleValidHosts() throws ApiException {
        InstanceMetaData instanceMetaData = validInstanceMetadata();
        InstanceMetaData instanceMetaData2 = validInstanceMetadata();
        instanceMetaData2.setPrivateIp("2.2.2.2");
        ApiHost apiHost = getValidApiHost(instanceMetaData);
        ApiHost apiHost2 = getValidApiHost(instanceMetaData2);
        when(hostsResourceApi.readHosts(null, null, VIEWTYPE)).thenReturn(new ApiHostList().items(List.of(apiHost, apiHost2)));

        boolean result = underTest.doStatusCheck(getPollerObject(instanceMetaData, instanceMetaData2));

        assertTrue(result);
    }

    @Test
    public void shouldBeFalseWhenOneHostHasDifferentIp() throws ApiException {
        InstanceMetaData instanceMetaData = validInstanceMetadata();
        InstanceMetaData instanceMetaData2 = validInstanceMetadata();
        instanceMetaData2.setPrivateIp("2.2.2.2");
        ApiHost apiHost = getValidApiHost(instanceMetaData);
        ApiHost apiHost2 = getValidApiHost(instanceMetaData2).ipAddress("3.3.3.3");
        when(hostsResourceApi.readHosts(null, null, VIEWTYPE)).thenReturn(new ApiHostList().items(List.of(apiHost, apiHost2)));

        boolean result = underTest.doStatusCheck(getPollerObject(instanceMetaData, instanceMetaData2));

        assertFalse(result);
    }

    @Test
    public void shouldBeTrueWhenOneInstanceHasNoDiscoveryFqdn() throws ApiException {
        InstanceMetaData instanceMetaData = validInstanceMetadata();
        InstanceMetaData instanceMetaData2 = validInstanceMetadata();
        instanceMetaData2.setPrivateIp("2.2.2.2");
        instanceMetaData2.setDiscoveryFQDN(null);
        ApiHost apiHost = getValidApiHost(instanceMetaData);
        when(hostsResourceApi.readHosts(null, null, VIEWTYPE)).thenReturn(new ApiHostList().items(List.of(apiHost)));

        boolean result = underTest.doStatusCheck(getPollerObject(instanceMetaData, instanceMetaData2));

        assertTrue(result);
    }

    @Test
    public void shouldBeTrueWhenOneInstanceIsTerminated() throws ApiException {
        InstanceMetaData instanceMetaData = validInstanceMetadata();
        InstanceMetaData instanceMetaData2 = validInstanceMetadata();
        instanceMetaData2.setPrivateIp("2.2.2.2");
        instanceMetaData2.setInstanceStatus(InstanceStatus.TERMINATED);
        ApiHost apiHost = getValidApiHost(instanceMetaData);
        when(hostsResourceApi.readHosts(null, null, VIEWTYPE)).thenReturn(new ApiHostList().items(List.of(apiHost)));

        boolean result = underTest.doStatusCheck(getPollerObject(instanceMetaData, instanceMetaData2));

        assertTrue(result);
    }

    @Test
    public void shouldBeTrueWhenOneInstanceIsDeletedOnProvider() throws ApiException {
        InstanceMetaData instanceMetaData = validInstanceMetadata();
        InstanceMetaData instanceMetaData2 = validInstanceMetadata();
        instanceMetaData2.setPrivateIp("2.2.2.2");
        instanceMetaData2.setInstanceStatus(InstanceStatus.DELETED_ON_PROVIDER_SIDE);
        ApiHost apiHost = getValidApiHost(instanceMetaData);
        when(hostsResourceApi.readHosts(null, null, VIEWTYPE)).thenReturn(new ApiHostList().items(List.of(apiHost)));

        boolean result = underTest.doStatusCheck(getPollerObject(instanceMetaData, instanceMetaData2));

        assertTrue(result);
    }

    @Test
    public void shouldBeTrueWhenOneInstanceIsStopped() throws ApiException {
        InstanceMetaData instanceMetaData = validInstanceMetadata();
        InstanceMetaData instanceMetaData2 = validInstanceMetadata();
        instanceMetaData2.setPrivateIp("2.2.2.2");
        instanceMetaData2.setInstanceStatus(InstanceStatus.STOPPED);
        ApiHost apiHost = getValidApiHost(instanceMetaData);
        when(hostsResourceApi.readHosts(null, null, VIEWTYPE)).thenReturn(new ApiHostList().items(List.of(apiHost)));

        boolean result = underTest.doStatusCheck(getPollerObject(instanceMetaData, instanceMetaData2));

        assertTrue(result);
    }

    @Test
    public void shouldBeTrueWhenOneInstanceIsFailed() throws ApiException {
        InstanceMetaData instanceMetaData = validInstanceMetadata();
        InstanceMetaData instanceMetaData2 = validInstanceMetadata();
        instanceMetaData2.setPrivateIp("2.2.2.2");
        instanceMetaData2.setInstanceStatus(InstanceStatus.FAILED);
        ApiHost apiHost = getValidApiHost(instanceMetaData);
        when(hostsResourceApi.readHosts(null, null, VIEWTYPE)).thenReturn(new ApiHostList().items(List.of(apiHost)));

        boolean result = underTest.doStatusCheck(getPollerObject(instanceMetaData, instanceMetaData2));

        assertTrue(result);
    }

    @Test
    public void shouldBeTrueWhenOneInstanceIsOrchestrationFailed() throws ApiException {
        InstanceMetaData instanceMetaData = validInstanceMetadata();
        InstanceMetaData instanceMetaData2 = validInstanceMetadata();
        instanceMetaData2.setPrivateIp("2.2.2.2");
        instanceMetaData2.setInstanceStatus(InstanceStatus.ORCHESTRATION_FAILED);
        ApiHost apiHost = getValidApiHost(instanceMetaData);
        when(hostsResourceApi.readHosts(null, null, VIEWTYPE)).thenReturn(new ApiHostList().items(List.of(apiHost)));

        boolean result = underTest.doStatusCheck(getPollerObject(instanceMetaData, instanceMetaData2));

        assertTrue(result);
    }

    private ApiHost getValidApiHost(InstanceMetaData instanceMetaData) {
        return new ApiHost()
                    .ipAddress(instanceMetaData.getPrivateIp())
                    .lastHeartbeat(Instant.now().plus(5, ChronoUnit.MINUTES).toString());
    }

    private InstanceMetaData validInstanceMetadata() {
        InstanceMetaData instanceMetaData = new InstanceMetaData();
        instanceMetaData.setDiscoveryFQDN("ins1");
        instanceMetaData.setInstanceStatus(InstanceStatus.SERVICES_RUNNING);
        instanceMetaData.setPrivateIp("1.1.1.1");
        return instanceMetaData;
    }

    private ClouderaManagerCommandPollerObject getPollerObject(InstanceMetaData... instanceMetaDatas) {
        Stack stack = new Stack();
        InstanceGroup instanceGroup = new InstanceGroup();
        instanceGroup.setInstanceMetaData(Set.of(instanceMetaDatas));
        stack.setInstanceGroups(Set.of(instanceGroup));
        return new ClouderaManagerCommandPollerObject(stack, new ApiClient(), BigDecimal.ONE);
    }

}


text:
import './style.scss';

import { g, CONST } from '../../basic';

const vdom = g.vdom;
const $ = g.$;
const $$ = g.$$;

class SelectorManager {

    constructor (className = '.g-select') {

        this.original = $$(className);

        this.renderedList = {};

        this.generate();

        document.addEventListener('click', e => {
            this.flush();
        });
    }

    generate () {
        this.original.forEach(item => {
            const name = item.name;
            if (name in this.renderedList) {
                g.warn('Name already exist', item);
                return;
            }
            this.renderedList[name] = new Selector(item, this);
        });
    }

    flush () {
        for (name in this.renderedList) {
            this.renderedList[name].hide();
        }
        // this.renderedList.forEach(selector => {
        //     selector.hide();
        // });
    }

    getList () {
        return this.renderedList;
    }
}

class Selector {

    constructor (select, manager) {
        this.select = select;
        this.manager = manager;
        this.parentNode = select.parentNode;
        this.nodeAttrs = g.attrs(select);
        this.options = [];
        this.optionsGroup = {};
        this.optionsOriginal = $$('option', this.select);
        this.mode = this.nodeAttrs['data-mode'] ? this.nodeAttrs['data-mode'].split(/[,\s,]/) : [];
        this.selected = { value: '', text: '' };
        this.child = null;
        this.nodeChildren = [];
        this.selectRendered = null;

        this.walkOriginal();
        this.inputGenerator();
        this.optionListGenerator();
        this.buttonsGenerator();
        this.render();
    }

    walkOriginal () {

        this.optionsOriginal.forEach(child => {

            const text = child.innerText;
            const attrs = g.attrs(child);

            if ('selected' in attrs) {
                this.selected.text = text;
                this.selected.value =  attrs['value'];
            }

            const listItem = new vdom('li', attrs, [ text ]);
            listItem.addEvent('click', e => {

                const li = e.target;
                const ul = li.parentNode;
                const parent = ul.parentNode;
                const input = $('input', parent);

                if (g.attr(li, 'disabled')) {
                    return;
                }

                parent.classList.remove('slideDown');

                if (this.mode.indexOf('clearable') >= 0) {
                    const close = $('.close', parent);
                    close.classList.remove('hidden');
                }

                input.value = li.innerText;
                g.attr(input, 'data-value', g.attr(li, 'value'));
            });

            if (this.mode.indexOf('group') < 0) {
                this.options.push(listItem);
            } else {
                const groupName = attrs['data-group'] || 'Other';
                if (Array.isArray(this.optionsGroup[groupName])) {
                    this.optionsGroup[groupName].push(listItem);
                } else {
                    this.optionsGroup[groupName] = [];
                    this.optionsGroup[groupName].push(listItem);
                }
            }

        });
    }

    optionListGenerator () {

        let optionList = [];

        if (this.mode.indexOf('group') >= 0) {

            const optionsGroupAfter = [];
            for (let groupName in this.optionsGroup) {
                optionsGroupAfter.push(new vdom('li', {
                    class: 'g-group--name'
                }, [
                    groupName
                ]));

                this.optionsGroup[groupName].forEach(option => {
                    optionsGroupAfter.push(option);
                });
            }
            optionList = new vdom('ul', {}, optionsGroupAfter);

        } else {
            optionList = new vdom('ul', {}, this.options);
        }

        this.nodeChildren.push(optionList);
    }

    inputGenerator () {

        const input = new vdom('input', {
            type: 'text',
            name: this.nodeAttrs.name,
            readonly: true,
            value: this.selected.text,
            'data-value': this.selected.value,
            placeholder: '请选择'
        });
        input.addEvent('click', e => {

            const parent = e.target.parentNode;
            const renderedList = this.manager.getList();

            // console.log(this.manager.getList());
            for (name in renderedList) {
                // consol
                if (renderedList[name] !== this) {
                    renderedList[name].hide();
                }
            };

            parent.classList.toggle('slideDown');

            e.stopPropagation();
        });

        this.nodeChildren.push(input);
    }

    buttonsGenerator () {

        //arror
        const arror = new vdom('div', {
            class: 'arror'
        }, []);
        this.nodeChildren.push(arror);

        // Add clean button
        if (this.mode.indexOf('clearable') < 0) {
            return;
        }
        const close = new vdom('div', {
            class: 'close hidden'
        }, []);
        close.addEvent('click', e => {
            const parent = e.target.parentNode;
            const input = $('input', parent);
            const close = $('.close', parent);

            input.value = '';
            input.dataset.value = '';

            close.classList.add('hidden');
        });
        this.nodeChildren.push(close);
    }

    render () {

        const node = new vdom('div', {
            class: 'g-selector'
        }, this.nodeChildren);
        this.selectRendered = node.render();

        this.parentNode.insertBefore(this.selectRendered, this.select);

        this.select.remove();
    }

    hide () {
        this.selectRendered.classList.remove('slideDown');
    }
}

export default new SelectorManager();

redpajama_set_name: RedPajamaGithub


text:
        [:hero text]

How did we get here? Routing!

    Congratulations, you've altered the route / to use the Home controller instead of the Install controller.

        Let's render! Break-it-down.

namespace Bc\App\Controllers\Example\View;

use Bc\App\RouteExtenders\ExampleRouteExtender;

class Home extends ExampleRouteExtender {

    protected function init()
    {
        $this->render(
            $this->getThemePart('/src/main/home.php'),
            null,
            [
                '[:nav]' => $this->nav->getNav(true),
                '[:hero text]' => $this->getThemePartContents('/src/tokenHTML/hero/text-home.php')
            ]
        );
    }
}

init() is a required method of route controllers. You must have it!

The job of the init() is to call render, or you could echo out json and exit!

Call render() ─ it takes 3 arguments: the path to the template file, the data (optional), and the tokens to apply (optional).

                        path

                        this is dependent on which theme you are using. If you want to use the default theme, defined in settings, then you can use $this->getThemePart() which will append what you pass to it to html/themes/yourtheme

                        data

                        this is an object or array of data that you want to pass to your template. Access it as $data

                        tokens

                        this is an associative array of token => value format, where the token name (ie '[:hero text]') can be used in plain HTML in the template file and replaced when rendered with either nothing (no token value supplied) or the value in the array (which could be html, another component rendered using output buffering etc)

Let's review order of operations

html/index.php is hit ─ core is initialized (reads route config, instantiates corresponding controller)

app/controllers/example/view/Home.php ─ Where the class declaration for Home is defined, extending core route classes, and one custom extender.

            Route Extender Order in this case:

app/controllers/routeExtenders/ExampleRouteExtender.php ─ Custom route extender to put methods relating to routing for the "Example" controller bundle.  Write whatever is useful to your bundle, extending one of the core routeExtenders.

app/controllers/core/routeExtenders/DataRouteExtender.php ─ A core route extender providing methods for easily connecting to the Db classes. Don't really need this extender on the home page since we aren't using any data. Could have used ExtendedRouteExtender

app/controllers/core/routeExtenders/ExtendedRouteExtender.php ─ Extra methods for dealing with almost all types of controller needs - loads format and validate services, the nav utility, calls custom methods.

app/controllers/core/routeExtender.php ─ the OG of routes, has the constructor, renders, applies tokens, has theme management methods etc. At the very least, route controllers must extend this class.

app/controllers/example/view/Home.php ─ route controllers must have init method and usually override the render method.

init calls render ─ which takes a path, data, and tokens.


text:
<?php

namespace Rancher\Exception;

/**
 * Class ResourceNotFoundException
 * @package Rancher\Exception
 */
class ResourceNotFoundException extends \RuntimeException implements RancherException
{

}


text:
var gulp = require('gulp'),
  gutil = require('gulp-util'),
  webserver = require('gulp-webserver');

gulp.task('js', function() {
  gulp.src('builds/development/js/**/*')
});

gulp.task('html', function() {
  gulp.src('builds/development/*.html')
});

gulp.task('css', function() {
  gulp.src('builds/development/css/*.css')
});

gulp.task('watch', function() {
  gulp.watch('builds/development/js/**/*', ['js']);
  gulp.watch('builds/development/css/*.css', ['css']);
  gulp.watch(['builds/development/*.html',
    'builds/development/views/*.html'], ['html']);
});

gulp.task('webserver', function() {
  gulp.src('builds/development/')
    .pipe(webserver({
      livereload: true,
      open: true
    }));
});

gulp.task('default', ['watch', 'html', 'js', 'css', 'webserver']);


text:
The sites, urls and additional notes are stored in `_data/sites.json`. If you want to add a site to the list you'll need the following information:

- `name`: The name of the service.
- `url`: The url of the account-deletion page. If no such page exists, the url should be a contact or help page explaining the process of account deletion.
- `url_CODE`: *(optional)* Use the language `CODE` as suffix of the url field to provide language-specific deletion codes, shown on the respective language page.
- `difficulty`: This is an indicator used on the site to determine the difficulty of account deletion. Use one of:
    - `easy`: Sites with a simple process such as a 'delete account' button
    - `medium`: Sites that do allow account deletion but require you to perform additional steps
    - `hard`: Sites that require you to contact customer services or those that don't allow automatic or easy account deletion
    - `impossible`: For sites where it's basically impossible to totally delete your account, even if you contact them
- `notes`: *(optional)* Notes will be shown when someone hovers on that service. Notes may include additional information you might need to delete your account (e.g. Skype) or consequences of deleting your account (e.g. iTunes).
- `notes_CODE`: *(optional)* Use the language `CODE` as suffix of the `notes` field to provide language-specific instructions, shown on the respective language page.
- `email`: *(optional)* If you have to send an email to a company to cancel your account, add the email address here. We'll do the rest.
- `email_subject`: *(optional)* Set the subject for the email link. If unset, the default text is "Account Deletion Request".
- `email_body`: *(optional)* Set the body for the email link. If unset, the default text is "Please delete my account, my username is XXXXXX".
- `domains`: This is used by the [Chrome extension](https://github.com/jdm-contrib/justdelete.me-chrome-extension)

## Contribution checklist

1. Have you updated to the latest version of the project? `git pull`
2. If you have modified an existing service's difficulty, please explain why/give sources.
3. URLs must be direct links to either deletion, or if this is not available, a relevant help article.
4. Any steps for the process should be detailed in the notes (if necessary).
5. Be sure to indent 4 spaces per level.
6. Be sure to place your entry ALPHABETICALLY in the current list.
7. Please test that your changes work validating `sites.json` with something like [JSON Lint](http://jsonlint.com/) or the included "validate_json.rb" script

## Translation

If you want to help on the translation of the site, you can read [translation reference](TRANSLATION_REFERENCE.md) to see what each of the keys is describing or translating.

### Modify an existing Translation

Look for the `CODE.json` file in the `_data/trans/` directory where `CODE` is your [short country code](https://en.wikipedia.org/wiki/Country_code)

### Add a new translation

1. Create a new `CODE.json` file in the `_data/trans/` directory where `CODE` is your [short country code](https://en.wikipedia.org/wiki/Country_code)
2. Copy the contents of `en.json` to your new file
3. Translate each line
4. Within the `_pages/` directory, copy `_pages/index.html` to a new `CODE.html` file, and update the `lang: CODE` line to match the new page's code
5. Visit [gosquared/flags](https://github.com/gosquared/flags/tree/master/flags/flags-iso/shiny) and get the shiny 16px and 24px flags for your language.
6. Save the flag icons onto `assets/icons` as `CODE16.png` and `CODE24.png`, where `CODE` is your short country code.
7. On `assets/css/style.css` insert a `dropdown` and a `background-image` that reference these flags.


text:
package org.pentaho.di.ui.core;

import org.eclipse.jface.action.MenuManager;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.TreeItem;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.util.Utils;
import org.pentaho.ui.xul.containers.XulMenupopup;

/**
 * This class is used to define a number of default values for various settings throughout Kettle. It also contains a
 * number of static final methods to make your life easier.
 *
 * @author Matt
 * @since 07-05-2003
 *
 */
public class ConstUI {
  /**
   * Default icon size
   */
  public static final int ICON_SIZE = 32;

  public static final int SMALL_ICON_SIZE = 16;

  public static final int MEDIUM_ICON_SIZE = 24;

  /**
   * Default line width for arrows & around icons
   */
  public static final int LINE_WIDTH = 1;

  /**
   * Default grid size to which the graphical views snap.
   */
  public static final int GRID_SIZE = 16;

  /**
   * The minimal size of a note on a graphical view (width & height)
   */
  public static final int NOTE_MIN_SIZE = 20;

  /**
   * Offset between pointer and tooltip position.
   */
  public static final int TOOLTIP_OFFSET = 5;

  /**
   * The default red-component of the background color
   */
  public static final int COLOR_BACKGROUND_RED = 255;

  /**
   * The default green-component of the background color
   */
  public static final int COLOR_BACKGROUND_GREEN = 255;

  /**
   * The default blue-component of the background color
   */
  public static final int COLOR_BACKGROUND_BLUE = 255;

  /**
   * The default red-component of the graph background color
   */
  public static final int COLOR_GRAPH_RED = 255;

  /**
   * The default green-component of the graph background color
   */
  public static final int COLOR_GRAPH_GREEN = 255;

  /**
   * The default blue-component of the graph background color
   */
  public static final int COLOR_GRAPH_BLUE = 255;

  /**
   * The default red-component of the tab selected color
   */
  public static final int COLOR_TAB_RED = 240;

  /**
   * The default green-component of the tab selected color
   */
  public static final int COLOR_TAB_GREEN = 240;

  /**
   * The default blue-component of the tab selected color
   */
  public static final int COLOR_TAB_BLUE = 240;

  /**
   * the default canvas refresh interval for running transformations
   */
  public static final int INTERVAL_MS_TRANS_CANVAS_REFRESH = 1000;

  /**
   * margin between points of controls
   */
  public static final int SMALL_MARGIN = 5;

  /**
   * margin between points of controls
   */
  public static final int MEDUIM_MARGIN = 10;

  /**
   * Determine the level of where the TreeItem is position in a tree.
   *
   * @param ti
   *          The TreeItem
   * @return The level of the item in the tree
   */
  public static final int getTreeLevel( TreeItem ti ) {
    int level = 0;
    TreeItem parent = ti.getParentItem();
    while ( parent != null ) {
      level++;
      parent = parent.getParentItem();
    }

    return level;
  }

  /**
   * Get an array of strings containing the path from the given TreeItem to the parent.
   *
   * @param ti
   *          The TreeItem to look at
   * @return An array of string describing the path to the TreeItem.
   */
  public static final String[] getTreeStrings( TreeItem ti ) {
    int nrlevels = getTreeLevel( ti ) + 1;
    String[] retval = new String[nrlevels];
    int level = 0;

    retval[nrlevels - 1] = ti.getText();
    TreeItem parent = ti.getParentItem();
    while ( parent != null ) {
      level++;
      retval[nrlevels - level - 1] = parent.getText();
      parent = parent.getParentItem();
    }

    return retval;
  }

  /**
   * Return the tree path seperated by Const.FILE_SEPARATOR, starting from a certain depth in the tree.
   *
   * @param ti
   *          The TreeItem to get the path for
   * @param from
   *          The depth to start at, use 0 to get the complete tree.
   * @return The tree path.
   */
  public static final String getTreePath( TreeItem ti, int from ) {
    String[] path = getTreeStrings( ti );

    if ( path == null ) {
      return null;
    }

    String retval = "";

    for ( int i = from; i < path.length; i++ ) {
      if ( !path[i].equalsIgnoreCase( Const.FILE_SEPARATOR ) ) {
        retval += Const.FILE_SEPARATOR + path[i];
      }
    }

    return retval;
  }

  /**
   * Flips the TreeItem from expanded to not expanded or vice-versa.
   *
   * @param ti
   *          The TreeItem to flip.
   */
  public static final void flipExpanded( TreeItem ti ) {
    ti.setExpanded( !ti.getExpanded() );
  }

  public static final TreeItem findTreeItem( TreeItem parent, String name ) {
    return findTreeItem( parent, null, name );
  }

  /**
   * Finds a TreeItem with a certain label (name) in a (part of a) tree.
   *
   * @param parent
   *          The TreeItem where we start looking.
   * @param parentName
   *          The name of the parent to match as well (null=not used)
   * @param name
   *          The name or item label to look for.
   * @return The TreeItem if the label was found, null if nothing was found.
   */
  public static final TreeItem findTreeItem( TreeItem parent, String parentName, String name ) {
    return findTreeItem( null, parent, parentName, name );
  }

  private static final TreeItem findTreeItem( TreeItem grandParent, TreeItem parent, String parentName, String name ) {
    if ( Utils.isEmpty( parentName ) ) {
      if ( parent.getText().equalsIgnoreCase( name ) ) {
        return parent;
      }
    } else {
      if ( grandParent != null && grandParent.getText().equalsIgnoreCase( "OTHER" ) ) {
        System.out.println( "Other" );
      }
      if ( grandParent != null
        && grandParent.getText().equalsIgnoreCase( parentName ) && parent.getText().equalsIgnoreCase( name ) ) {
        return parent;
      }
    }

    TreeItem[] ti = parent.getItems();
    for ( int i = 0; i < ti.length; i++ ) {
      TreeItem child = findTreeItem( parent, ti[i], parentName, name );
      if ( child != null ) {
        return child;
      }
    }
    return null;
  }

  public static void displayMenu( XulMenupopup xulMenuPopup, Control control ) {

    MenuManager menuMgr = (MenuManager) xulMenuPopup.getManagedObject();
    Menu menu = menuMgr.createContextMenu( control );
    menuMgr.updateAll( true );
    displayMenu( menu, control );
  }

  public static void displayMenu( Menu menu, Control control ) {
    Menu oldMenu = control.getMenu();
    if ( oldMenu != null && oldMenu != menu ) {
      oldMenu.setVisible( false );
    }

    // XXX: Stubbing out this line prevents context dialogs from appearing twice
    // on OS X. Tested on Windows to be sure there is no adverse effect.
    // Unfortunately, I do *not* understand why this works. I ran it by
    // mcasters and he didn't know for sure either.
    // control.setMenu(menu);
    menu.setVisible( true );
  }

}


text:
module Portus
  # The Config class is a convenient wrapper around the different configuration
  # files that provides a simple way to retrieve the evaluated app config.
  class Config
    # The default file corresponds to the default config of the app. The local
    # file can overwrite values from the default file.
    def initialize(default, local)
      @default = default
      @local   = local
    end

    # Returns a hash with the app configuration contained in it.
    def fetch
      cfg = {}
      cfg = YAML.load_file(@default) if File.file?(@default)

      if File.file?(@local)
        # Check for bad user input in the local config.yml file.
        local = YAML.load_file(@local)
        unless local.is_a?(Hash)
          raise StandardError, "Wrong format for the config-local file!"
        end
        cfg.merge!(local)
      end

      add_enabled(cfg)
    end

    protected

    # Add the `enabled?` method to the given object. The `enabled?` method is
    # a convenient method that checks whether a specific feature is enabled or
    # not. This method takes advantage of the convention that each feature has
    # the "enabled" key inside of it. If this key exists in the checked
    # feature, and it's set to true, then this method will return true. It
    # returns false otherwise.
    def add_enabled(obj)
      obj.define_singleton_method(:enabled?) do |feature|
        return false if !self[feature] || self[feature].empty?
        self[feature]["enabled"].eql?(true)
      end
      obj
    end
  end
end


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Ann. Wetter. Gesellsch. Ges. Naturk. 4: 244 (1819)

#### Original name
Erysiphe astragali DC., 1815

### Remarks
null


text:
import { Component } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';

import 'rxjs/add/operator/switchMap';

import { PageComponent } from '../../shared/page.component';
import { Event } from '../event.model';
import { EventsService } from '../../events/events.service';

@Component({
    moduleId: module.id,
    selector: 'events-detail',
    templateUrl: './events-detail.component.html',
    styleUrls: ['./events-detail.component.css']
})
export class EventsDetailComponent implements PageComponent {
    events: Event;

    constructor(
        private eventsService: EventsService,
        private route: ActivatedRoute
    ) { }

    ngOnInit() {
        //console.log(this.route.params);
        this.route.params
            .switchMap((params: Params) => this.eventsService.getEventsById(params['id']))
            .subscribe(currentEvents => this.events = currentEvents);
    }
}


text:
Game::Game()
{
}

Game::~Game()
{
	Destroy();
}

bool Game::Initialize(Score * score)
{
	bullets.fill(Bullet());
	scoreHandler = score;
	enemyDirection = true;
	finished = false;
	victory = false;
	return true;
}

bool Game::Destroy()
{
	player.Shutdown();

	enemies.clear();
	walls.clear();

	return true;
}

int Game::RenderGame(sf::RenderWindow * window, const sf::Time &frameTime)
{
	FinishGameCheck(window, frameTime);

	if (!finished)
	{
		//InputCheck(frameTime.asSeconds());

		BulletCheck();

		aiMove(frameTime);
		enemyFire();
		for (auto& bullet : bullets)
		{
			if (bullet.IsAlive())
			{
				bullet.Move(100 * frameTime.asSeconds());
			}
		}
		for (auto& enemy : enemies)
		{
			if (enemy.IsAlive())
			{
				if ((enemy.GetPosX() < 0 || enemy.GetPosX() > 800) && !enemyDescent)
				{
					enemyDirection = !enemyDirection;
					enemyDescent = true;

					if (enemy.GetPosX() < 0)
					{
						boundaryCompensation = -enemy.GetPosX();
					}
					else
					{
						boundaryCompensation = 800 - enemy.GetPosX();
					}
				}
			}
		}

		Draw(window);
	}
	else
	{
		if (victory)
		{
			if (scoreHandler->winScore(window))
			{
				scoreHandler->SaveScore();
				return 1;
			}

		}
		else
		{
			if (scoreHandler->loseScore(window))
			{
				scoreHandler->SaveScore();
				return 1;
			}
		}

	}

	return 0;
}
void Game::Draw(sf::RenderWindow * window)
{
	window->draw(*player.GetModel());

	for (auto& bullet : bullets)
	{
		if (bullet.IsAlive())
		{
			window->draw(*bullet.GetModel());
		}
	}
	for (auto& enemy : enemies)
	{
		if (enemy.IsAlive())
		{
			window->draw(*enemy.GetModel());
		}
	}
	for (auto& wall : walls)
	{
		if (wall.IsAlive())
		{
			window->draw(*wall.GetModel());
		}
	}
	window->draw(scoreHandler->GetTotalScore());
	window->draw(scoreHandler->GetHighScore());
}

void Game::InputCheck(const float &frameTime)
{
	if (sf::Event::KeyPressed)
	{
		if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))
		{
			finished = true;
		}

		if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
		{
			player.Move(frameTime, true);
		}
		else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
		{
			player.Move(frameTime, false);
		}

		if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space) && !player.IsShooting())
		{
			playerFire();
		}
		else if (!sf::Keyboard::isKeyPressed(sf::Keyboard::Space))
		{
			player.SetShooting(false);
		}
	}
}

void Game::BulletCheck()
{
	for (auto& bullet : bullets)
	{
		if (bullet.IsAlive())
		{
			if (bullet.GetPosY() < -1)
			{
				bullet.Kill();
				continue;
			}

			if (CheckCollision(bullet, player))
			{
				player.Kill();
			}

			for (auto& enemy : enemies)
			{
				if (enemy.IsAlive())
				{
					if (CheckCollision(bullet, enemy))
					{
						scoreHandler->AddPoints(enemy.GetPoints());
						enemy.Kill();
						bullet.Kill();
						break;
					}
				}
			}

			for (auto& wall : walls)
			{
				if (wall.IsAlive())
				{
					if (CheckCollision(bullet, wall))
					{
						wall.Kill();
						bullet.Kill();
						break;
					}
				}
			}
		}
	}
}

bool Game::CheckCollision(Object& object1, Object& object2)
{
	if (object1.GetModel()->getGlobalBounds().intersects(object2.GetModel()->getGlobalBounds()))
	{
		if (object1.GetTeam() != object2.GetTeam())
		{
			return true;
		}
	}
	return false;
}

void Game::aiMove(const sf::Time &frameTime)
{
	for (int i = 0; i < enemies.size(); ++i)
	{
		if (enemies.at(i).IsAlive())
		{
			if (!enemyDescent)
			{
				enemies.at(i).Move(frameTime.asSeconds(), enemyDirection);
			}
			else
			{
				enemies.at(i).Descend();
				enemies.at(i).Move(frameTime.asSeconds(), enemyDirection);
			}
		}
	}
	enemyDescent = false;
}

void Game::playerFire()
{
	for (auto& bullet : bullets)
	{
		if (bullet.IsAlive() != true)
		{
			bullet.Initialize(player.GetPosX() + 9, player.GetPosY(), 1);
			break;
		}
	}
	player.SetShooting(true);
}

void Game::enemyFire()
{
	int enemyShoot;

	for (int i = 0; i < enemies.size(); ++i)
	{
		if (enemies.at(i).IsAlive())
		{
			enemyShoot = rand() % 10000;
			if (enemyShoot == 1)
			{
				for (auto& bullet : bullets)
				{
					if (bullet.IsAlive() != true)
					{
						bullet.Initialize(enemies.at(i).GetPosX(), enemies.at(i).GetPosY(), 2);
						break;
					}
				}
			}
		}
	}
}

bool Game::PlaceWall(int startPosX, int startPosY)
{
	for (int i = 0; i < 5; ++i)
	{
		for (int j = 0; j < 3; ++j)
		{
			walls.emplace_back();
			walls.back().Initialize(startPosX + i * 15, startPosY + j * 15, 0);
		}
	}

	return true;
}

bool Game::CreatePlayer(int startPosX, int startPosY)
{
	player.Initialize(startPosX, startPosY, 1);
	return true;
}

bool Game::CreateEnemy(int startPosX, int startPosY)
{
	enemies.emplace_back();
	enemies.back().Initialize(startPosX, startPosY, 2);
	return true;
}

void Game::FinishGameCheck(sf::RenderWindow * window, const sf::Time &frameTime)
{
	if (!player.IsAlive())
	{
		finished = true;
	}

	bool isAnyEnemyAlive = false;
	for (auto& enemy : enemies) //Check if any enemy is alive
	{
		if (enemy.IsAlive())
		{
			isAnyEnemyAlive = true;
		}
	}

	if (!isAnyEnemyAlive) // Victory if all enemies are dead
	{
		victory = true;
		finished = true;
	}
}

size_t Game::GetTotalEnemies()
{
	return enemies.size();
}

size_t Game::GetTotalWalls()
{
	return walls.size();
}

size_t Game::GetTotalBullets()
{
	return bullets.size();
}


text:
This repo contains the Dockerfile used to build the Datadog Agent (https://github.com/DataDog/dd-agent).

The Datadog Agent is built using a Chef omnibus project (https://github.com/DataDog/dd-agent-omnibus) on CircleCi.

The base image of the container is a homemade i386 image of Centos 5.

You'll need:
```
VirtualBox (Last tested on 4.3.x)
Vagrant (Last tested on 1.7)
```

Then you can clone the repo and run:
```
vagrant up
```


text:
<?php
/**
 * Created by PhpStorm.
 * User: helei
 * Date: 2017/3/6
 * Time: 下午9:08
 */

namespace Payment\Client;

use Payment\Common\PayException;
use Payment\Config;
use Payment\QueryContext;

/**
 * 查询的客户端类
 * Class Query
 * @package Payment\Client
 */
class Query
{
    protected static $supportType = [
        Config::ALI_CHARGE,
        Config::ALI_REFUND,
        Config::ALI_TRANSFER,
        Config::ALI_RED,

        Config::WX_CHARGE,
        Config::WX_REFUND,
        Config::WX_RED,
        Config::WX_TRANSFER,

        Config::CMB_CHARGE,
        Config::CMB_REFUND,
    ];

    /**
     * 异步通知类
     * @var QueryContext
     */
    protected static $instance;

    protected static function getInstance($queryType, $config)
    {
        if (is_null(self::$instance)) {
            static::$instance = new QueryContext();

            try {
                static::$instance->initQuery($queryType, $config);
            } catch (PayException $e) {
                throw $e;
            }
        }

        return static::$instance;
    }

    /**
     * @param string $queryType
     * @param array $config
     * @param array $metadata
     * @return array
     * @throws PayException
     */
    public static function run($queryType, $config, $metadata)
    {
        if (! in_array($queryType, self::$supportType)) {
            throw new PayException('sdk当前不支持该类型查询,当前仅支持:' . implode(',', self::$supportType) . __LINE__);
        }

        try {
            $instance = self::getInstance($queryType, $config);

            $ret = $instance->query($metadata);
        } catch (PayException $e) {
            throw $e;
        }

        return $ret;
    }
}


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=type.N928.html">

Redirecting to type.N928.html...


text:
package com.levelup.palabre.inoreaderforpalabre.ui.activity;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.levelup.palabre.api.datamapping.Category;
import com.levelup.palabre.api.datamapping.Source;
import com.levelup.palabre.api.utils.PalabreUtils;
import com.levelup.palabre.inoreaderforpalabre.BuildConfig;
import com.levelup.palabre.inoreaderforpalabre.InoreaderExtension;
import com.levelup.palabre.inoreaderforpalabre.R;
import com.levelup.palabre.inoreaderforpalabre.core.SharedPreferenceKeys;
import com.levelup.palabre.inoreaderforpalabre.inoreader.InoreaderLoginService;
import com.levelup.palabre.inoreaderforpalabre.inoreader.InoreaderService;
import com.levelup.palabre.inoreaderforpalabre.inoreader.data.addsubscription.AddSubscriptionResponse;
import com.levelup.palabre.inoreaderforpalabre.inoreader.data.auth.OAuthToken;
import com.levelup.palabre.inoreaderforpalabre.inoreader.data.userinfo.UserInfo;
import com.levelup.palabre.inoreaderforpalabre.ui.adapter.CategorySourceAdapter;
import com.levelup.palabre.inoreaderforpalabre.ui.adapter.CategorySourceItemTouchCallback;

import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {
    private String TAG = MainActivity.class.getSimpleName();

    @InjectView(R.id.login)
    AppCompatButton loginButton;
    @InjectView(R.id.recycler_view)
    RecyclerView catSourceList;
    @InjectView(R.id.login_container)
    View loginContainer;
    @InjectView(R.id.search_bar)
    View searchBar;
    @InjectView(R.id.add_feed)
    View addFeed;
    @InjectView(R.id.add_feed_text)
    EditText addFeedText;
    @InjectView(R.id.add_feed_progress)
    View addFeedprogress;

    private CategorySourceAdapter adapter;
    private MenuItem logoutMenu;
    private MenuItem addMenu;
    private boolean inSearchMode;
    private String searchText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.inject(this);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        addFeed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addFeed();
            }
        });

        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startLogin();
            }
        });

        initList();

        manageIntent(getIntent());

    }

    private void startLogin() {
        String crsf_protection = UUID.randomUUID().toString();
        PreferenceManager.getDefaultSharedPreferences(this)
                .edit()
                .putString(SharedPreferenceKeys.CRSF, crsf_protection)
                .apply();
        try {
            final Uri authCodeUri = InoreaderService.getAuthCodeUri(crsf_protection);
            if (BuildConfig.DEBUG) Log.d(TAG, "Launch with: " + authCodeUri.toString());
            Intent intent = new Intent(Intent.ACTION_VIEW, authCodeUri);
            intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            startActivity(intent);
            finish();
        } catch (ActivityNotFoundException e) {
            Snackbar.make(loginButton, R.string.no_browser, Snackbar.LENGTH_LONG).show();
        }
    }

    private void firstRefresh() {

        InoreaderService.getInstance(MainActivity.this).resetAdapters();

        Call<UserInfo> userInfoRequest = InoreaderService.getInstance(MainActivity.this).getUserInformation();
        userInfoRequest.enqueue(new Callback<UserInfo>() {
            @Override
            public void onResponse(Call<UserInfo> call, Response<UserInfo> response) {
                if (!response.isSuccessful()) {
                    Snackbar.make(loginButton, R.string.login_error, Snackbar.LENGTH_LONG).show();
                    return;
                }
                UserInfo result = response.body();
                PreferenceManager.getDefaultSharedPreferences(MainActivity.this)
                        .edit()
                        .putString(SharedPreferenceKeys.USER_ID, result.getUserId())
                        .putString(SharedPreferenceKeys.USER_NAME, result.getUserName())
                        .apply();

                InoreaderExtension.refreshCategoriesAndSources(MainActivity.this, new InoreaderExtension.OnCategoryAndSourceRefreshed() {
                    @Override
                    public void onFinished() {
                        initList();
                        try {
                            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("palabre://extauth"));
                            startActivity(intent);
                            MainActivity.this.finish();
                        } catch (Exception e) {
                            // Palabre is not installed
                            Snackbar.make(loginButton, R.string.intent_error, Snackbar.LENGTH_LONG).show();
                        }
                    }

                    @Override
                    public void onFailure(Throwable throwable) {
                        Snackbar.make(loginButton, R.string.login_error, Snackbar.LENGTH_LONG).show();
                    }

                    @Override
                    public void onprogressChanged(int progress) {

                    }
                });
            }

            @Override
            public void onFailure(Call<UserInfo> call, Throwable t) {
                if (BuildConfig.DEBUG) Log.w(TAG, t.getMessage(), t);
                Snackbar.make(loginButton, R.string.login_error, Snackbar.LENGTH_LONG).show();

            }
        });

    }

    @Override
    protected void onResume() {
        PalabreUtils.checkPalabreInstallationAndWarn(this);
        super.onResume();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        manageIntent(intent);
        super.onNewIntent(intent);
    }

    private void manageIntent(Intent intent) {

        Uri data = intent.getData();

        //Getting the code for Feedly
        if (data != null) {
            if (data.getScheme().equals("palabre-inoreader")) {

                if (data.getAuthority().equals("auth")) {
                    if (BuildConfig.DEBUG) Log.d(TAG, "Auth data: " + data.toString());

                    String crsf = PreferenceManager.getDefaultSharedPreferences(this).getString(SharedPreferenceKeys.CRSF, "");
                    if (crsf.equals(data.getQueryParameter("state"))) {

                        Call<OAuthToken> call = InoreaderLoginService.getInstance(this).login(data.getQueryParameter("code"));
                        call.enqueue(new Callback<OAuthToken>() {
                            @Override
                            public void onResponse(Call<OAuthToken> call, Response<OAuthToken> response) {
                                if (!response.isSuccessful()) {
                                    Snackbar.make(loginButton, R.string.login_error, Snackbar.LENGTH_LONG).show();

                                } else {

                                    final OAuthToken oAuthToken = response.body();

                                    if (BuildConfig.DEBUG) Log.d(TAG, "Expires in: "+oAuthToken.getExpiresIn());

                                    if (BuildConfig.DEBUG) Log.d(TAG, "Saving token: "+oAuthToken.getAccessToken());

                                    long expiration = System.currentTimeMillis() + (oAuthToken.getExpiresIn() * 1000);
                                    if (BuildConfig.DEBUG) Log.d(TAG, "Expires: "+new Date(expiration));

                                    PreferenceManager.getDefaultSharedPreferences(MainActivity.this)
                                            .edit()
                                            .putString(SharedPreferenceKeys.ACCESS_TOKEN, oAuthToken.getAccessToken())
                                            .putString(SharedPreferenceKeys.REFRESH_TOKEN, oAuthToken.getRefreshToken())
                                            .putLong(SharedPreferenceKeys.EXPIRES, expiration)
                                            .apply();

                                    firstRefresh();

                                }
                            }

                            @Override
                            public void onFailure(Call<OAuthToken> call, Throwable t) {
                                Snackbar.make(loginButton, R.string.login_error, Snackbar.LENGTH_LONG).show();
                            }
                        });

                    } else {
                        Snackbar.make(loginButton, R.string.login_error, Snackbar.LENGTH_LONG).show();
                    }
                }
            }
        }

        String action = intent.getAction();
        String type = intent.getType();

        if (Intent.ACTION_SEND.equals(action) && type != null) {
            if (BuildConfig.DEBUG) Log.d(TAG, "Extra: " + intent.getStringExtra(Intent.EXTRA_TEXT));

            //Menu not inflated yet
            if (logoutMenu == null) {
                searchText = intent.getStringExtra(Intent.EXTRA_TEXT);
            } else {
                String feedUrl = intent.getStringExtra(Intent.EXTRA_TEXT);
                launchAutoSearch(feedUrl);
            }
        }
    }

    private void launchAutoSearch(String feedUrl) {
        switchSearchMode();
        addFeedText.setText(feedUrl);
        addFeed();
    }

    private void addFeed() {

        switchSearchModeProgress();
        hideKeyboard(addFeedText);
        Call<AddSubscriptionResponse> request = InoreaderService.getInstance(this).addSubscription(addFeedText.getText().toString());
        request.enqueue(new Callback<AddSubscriptionResponse>() {
            @Override
            public void onResponse(Call<AddSubscriptionResponse> call, Response<AddSubscriptionResponse> response) {
                if (!response.isSuccessful()) {
                    switchSearchModeProgress();
                    Snackbar.make(loginButton, R.string.add_error, Snackbar.LENGTH_LONG).show();
                } else {
                    AddSubscriptionResponse result = response.body();
                    if (result.getNumResults() > 0) {

                        InoreaderExtension.refreshCategoriesAndSources(MainActivity.this, new InoreaderExtension.OnCategoryAndSourceRefreshed() {
                            @Override
                            public void onFinished() {
                                adapter.reload();
                                switchSearchMode();
                                switchSearchModeProgress();
                                addFeedText.setText("");
                                catSourceList.smoothScrollToPosition(adapter.getItemCount());
                            }

                            @Override
                            public void onFailure(Throwable throwable) {
                                switchSearchModeProgress();
                                Snackbar.make(loginButton, R.string.add_error, Snackbar.LENGTH_LONG).show();
                            }

                            @Override
                            public void onprogressChanged(int progress) {

                            }
                        });

                    } else {
                        switchSearchModeProgress();
                        Snackbar.make(loginButton, R.string.add_error, Snackbar.LENGTH_LONG).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<AddSubscriptionResponse> call, Throwable t) {
                switchSearchModeProgress();
                Snackbar.make(loginButton, R.string.add_error, Snackbar.LENGTH_LONG).show();
            }
        });

    }

    private void initList() {

        CategorySourceItemTouchCallback categorySourceItemTouchCallback = new CategorySourceItemTouchCallback(this, ItemTouchHelper.UP | ItemTouchHelper.DOWN, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT, catSourceList);

        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(categorySourceItemTouchCallback);
        adapter = new CategorySourceAdapter(this, itemTouchHelper);

        categorySourceItemTouchCallback.setAdapter(adapter);

        catSourceList.setLayoutManager(new LinearLayoutManager(this));
        catSourceList.setAdapter(adapter);

        itemTouchHelper.attachToRecyclerView(catSourceList);

        catSourceList.addItemDecoration(itemTouchHelper);

        if (!TextUtils.isEmpty(PreferenceManager.getDefaultSharedPreferences(MainActivity.this).getString(SharedPreferenceKeys.USER_ID, ""))) {
            loginContainer.setVisibility(View.GONE);
            catSourceList.setVisibility(View.VISIBLE);
        } else {
            catSourceList.setVisibility(View.GONE);
            loginContainer.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);

        logoutMenu = menu.findItem(R.id.action_logout);
        addMenu = menu.findItem(R.id.action_add);

        if (!TextUtils.isEmpty(searchText)) {
            launchAutoSearch(searchText);
            searchText = "";
        }

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == android.R.id.home) {

            if (inSearchMode) {
                switchSearchMode();
            } else {

                finish();
            }
        } else if (id == R.id.action_logout) {

            PreferenceManager.getDefaultSharedPreferences(this).edit()
                    .clear()
                    .apply();

            List<Category> cats = Category.getAll(this);
            for (Category cat : cats) {
                cat.delete(this);
            }

            List<Source> sources = Source.getAll(this);
            for (Source source : sources) {
                source.delete(this);
            }

            catSourceList.setVisibility(View.GONE);
            loginContainer.setVisibility(View.VISIBLE);

        } else if (id == R.id.action_add) {
            switchSearchMode();
        }

        return super.onOptionsItemSelected(item);
    }

    private void switchSearchMode() {
        inSearchMode = !inSearchMode;
        logoutMenu.setVisible(!inSearchMode);
        addMenu.setVisible(!inSearchMode);
        if (inSearchMode) {
            searchBar.setVisibility(View.VISIBLE);

        } else {
            searchBar.setVisibility(View.GONE);

        }
    }

    private void switchSearchModeProgress() {
        if (addFeed.getVisibility() == View.VISIBLE) {
            addFeed.setVisibility(View.GONE);
            addFeedprogress.setVisibility(View.VISIBLE);
        } else {
            addFeed.setVisibility(View.VISIBLE);
            addFeedprogress.setVisibility(View.GONE);

        }
    }

    @Override
    public void onBackPressed() {
        if (inSearchMode) {
            switchSearchMode();
        } else {
            super.onBackPressed();
        }
    }

    /**
     * Hides the keyboard.
     *
     * @param view
     */
    private void hideKeyboard(View view) {
        Context context = view.getContext();
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    // validating email id
    private boolean isValidEmail(String email) {
        String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
                + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

        Pattern pattern = Pattern.compile(EMAIL_PATTERN);
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }
}


text:
/**
 * @test
 * @bug 6405536 6414980
 * @summary Make sure that we can parse certificates using various named curves
 *   and verify their signatures
 * @author Andreas Sterbenz
 * @library ..
 */

import java.io.*;
import java.util.*;

import java.security.cert.*;
import java.security.*;
import java.security.interfaces.*;

import javax.security.auth.x500.X500Principal;

public class ReadCertificates extends PKCS11Test {

    private static CertificateFactory factory;

    private static SecureRandom random;

    private static Collection<X509Certificate> readCertificates(File file) throws Exception {
        System.out.println("Loading " + file.getName() + "...");
        InputStream in = new FileInputStream(file);
        Collection<X509Certificate> certs = (Collection<X509Certificate>)factory.generateCertificates(in);
        in.close();
        return certs;
    }

    public static void main(String[] args) throws Exception {
        main(new ReadCertificates());
    }

    public void main(Provider p) throws Exception {
        if (p.getService("Signature", "SHA1withECDSA") == null) {
            System.out.println("Provider does not support ECDSA, skipping...");
            return;
        }
        Security.insertProviderAt(p, 1);

        random = new SecureRandom();
        factory = CertificateFactory.getInstance("X.509");
        try {
            // clear certificate cache in from a previous run with a different
            // provider (undocumented hack for the Sun provider)
            factory.generateCertificate(null);
        } catch (CertificateException e) {
            // ignore
        }
        Map<X500Principal,X509Certificate> certs = new LinkedHashMap<X500Principal,X509Certificate>();

        File dir = new File(BASE, "certs");
        File closedDir = new File(CLOSED_BASE, "certs");
        File[] files = concat(dir.listFiles(), closedDir.listFiles());
        Arrays.sort(files);
        for (File file : files) {
            if (file.isFile() == false) {
                continue;
            }
            Collection<X509Certificate> certList = readCertificates(file);
            for (X509Certificate cert : certList) {
                X509Certificate old = certs.put(cert.getSubjectX500Principal(), cert);
                if (old != null) {
                    System.out.println("Duplicate subject:");
                    System.out.println("Old Certificate: " + old);
                    System.out.println("New Certificate: " + cert);
                    throw new Exception(file.getPath());
                }
            }
        }
        System.out.println("OK: " + certs.size() + " certificates.");

        for (X509Certificate cert : certs.values()) {
            X509Certificate issuer = certs.get(cert.getIssuerX500Principal());
            System.out.println("Verifying " + cert.getSubjectX500Principal() + "...");
            PublicKey key = issuer.getPublicKey();
            // First try the provider under test (if it does not support the
            // necessary algorithm then try any registered provider).
            try {
                cert.verify(key, p.getName());
            } catch (NoSuchAlgorithmException e) {
                System.out.println("Warning: " + e.getMessage() +
                ". Trying another provider...");
                cert.verify(key);
            }
        }

        // try some random invalid signatures to make sure we get the correct
        // error
        System.out.println("Checking incorrect signatures...");
        List<X509Certificate> certList = new ArrayList<X509Certificate>(certs.values());
        for (int i = 0; i < 20; i++) {
            X509Certificate cert, signer;
            do {
                cert = getRandomCert(certList);
                signer = getRandomCert(certList);
            } while (cert.getIssuerX500Principal().equals(signer.getSubjectX500Principal()));
            try {
                cert.verify(signer.getPublicKey());
                throw new Exception("Verified invalid signature");
            } catch (SignatureException e) {
                System.out.println("OK: " + e);
            } catch (InvalidKeyException e) {
                System.out.println("OK: " + e);
            }
        }

        Security.removeProvider(p.getName());
        System.out.println("OK");
    }

    private static X509Certificate getRandomCert(List<X509Certificate> certs) {
        int n = random.nextInt(certs.size());
        return certs.get(n);
    }

}


text:
import OS from 'os-family';
import browserTools from 'testcafe-browser-tools';
import { killBrowserProcess } from '../../../../../utils/process';
import BrowserStarter from '../../../utils/browser-starter';

const browserStarter = new BrowserStarter();

function correctOpenParametersForMac (parameters) {
    parameters.macOpenCmdTemplate = parameters.macOpenCmdTemplate
        .replace('open', 'open -n')
        .replace(' {{{pageUrl}}}', '');

    parameters.macOpenCmdTemplate += ' {{{pageUrl}}}';
}

function buildFirefoxArgs (config, platformArgs, { marionettePort, tempProfileDir }) {
    return []
        .concat(
            marionettePort ? ['-marionette'] : [],
            !config.userProfile ? ['-no-remote', '-new-instance', `-profile "${tempProfileDir.path}"`] : [],
            config.headless ? ['-headless'] : [],
            config.userArgs ? [config.userArgs] : [],
            platformArgs ? [platformArgs] : []
        )
        .join(' ');
}

export async function start (pageUrl, runtimeInfo) {
    const { browserName, config } = runtimeInfo;

    const firefoxInfo           = await browserTools.getBrowserInfo(config.path || browserName);
    const firefoxOpenParameters = Object.assign({}, firefoxInfo);

    if (OS.mac && !config.userProfile)
        correctOpenParametersForMac(firefoxOpenParameters);

    firefoxOpenParameters.cmd = buildFirefoxArgs(config, firefoxOpenParameters.cmd, runtimeInfo, runtimeInfo.newInstance);

    await browserStarter.startBrowser(firefoxOpenParameters, pageUrl);
}

export async function stop ({ browserId }) {
    await killBrowserProcess(browserId);
}


text:
SELECT a FROM (SELECT * FROM t1 ORDER BY a LIMIT 5)
INTERSECT SELECT a FROM (SELECT a FROM t1 ORDER BY a LIMIT 2)
ORDER BY 1
LIMIT ii;


text:
package mcjty.rftools.network;

import mcjty.rftools.RFTools;
import mcjty.rftools.dimension.world.GenericWorldProvider;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import net.minecraftforge.common.DimensionManager;

public class DimensionSyncPacket {

    private ByteBuf data = Unpooled.buffer();

    private byte[] dimensions;

    public void addDimension(int id) {
        data.writeByte(id);
    }

    public void consumePacket(ByteBuf data) {
        dimensions = new byte[data.readableBytes()];
        data.readBytes(dimensions);
    }

    public ByteBuf getData() {
        return data;
    }

    public void execute() {
        // Only do this on client side.
        for (byte id : dimensions) {
            RFTools.log("DimensionSyncPacket: Registering id: id = " + id);
            if (!DimensionManager.isDimensionRegistered(id)) {
                DimensionManager.registerProviderType(id, GenericWorldProvider.class, false);
                DimensionManager.registerDimension(id, id);
            }
        }
    }

}


text:
create database javademo default charset utf8 collate utf8_general_ci;

use javademo;

create table student(id int primary key auto_increment, name varchar(25) not null, age int);

create table admin(id int primary key auto_increment, name varchar(25) not null, age int);


text:
I see that you have found your way to my boilerplate. How nice!

## Description
I built it to shorten time in setting up new web projects such as small web applications, wordpress plugins etc. Hopefully this will be of value to you aswell.

## Suggestions
Add an issue or make a pull request.

## License
I have chosen to make this project MIT-licensed. You can change anything you want when using this in your project, no worries.

## Requirements
* Node
* Node Package Manager (NPM)
* Bower
* Sass

## Installation / setup
With some easy steps, you can configure the boilerplate to work for your project.

Start by installing the Node dependencies for gulp to work.
```
npm install
```

Install the bower dependencies.
```
bower install
```

If you need any front-end packages like jQuery, Angular, Bootstrap or such, use bower to fetch them
```
bower install <package-name> --save
```

Open up the gulp-file and change the options at the top of the file if you want to configure it for your liking.

Use this command while developing SASS and JS (it will compile the files when they are changed)
```
gulp watch
```

Use this command when you want to minify SASS and uglify JS.
```
gulp dist
```

I hope that this comes to use!


text:
using System;
using System.Collections.Generic;
using System.IO.Abstractions;
using ICSharpCode.NRefactory.CSharp;
using ICSharpCode.NRefactory.TypeSystem;
using System.Linq;

namespace OmniSharp.Solution
{
    /// <summary>
    /// Placeholder that can be used for files that don't belong to a project yet.
    /// </summary>
    public class OrphanProject : Project
    {
        public const string ProjectFileName = "OrphanProject";
        public OrphanProject(IFileSystem fileSystem, Logger logger) : base(fileSystem, logger)
        {
            Title = "Orphan Project";
            Files = new List<CSharpFile>();

            ProjectId = Guid.NewGuid();

            References = new List<IAssemblyReference>();
            FileName = ProjectFileName;
            string mscorlib = FindAssembly("mscorlib");
            Console.WriteLine(mscorlib);
            ProjectContent = new CSharpProjectContent()
                .SetAssemblyName(ProjectFileName)
                .AddAssemblyReferences(LoadAssembly(mscorlib));
        }

        private CSharpFile GetFile(string fileName, string source)
        {
            var file = Files.FirstOrDefault(f => f.FileName.Equals(fileName, StringComparison.InvariantCultureIgnoreCase));
            if (file == null)
            {
                file = new CSharpFile(this, fileName, source);
                Files.Add (file);

                this.ProjectContent = this.ProjectContent
                    .AddOrUpdateFiles(file.ParsedFile);
            }
            return file;
        }
    }
}