text:
export JAVA_HOME=/usr/local/jdk1.8.0_05
export JRE_HOME=${JAVA_HOME}/jre
export CLASSPATH=.:${JAVA_HOME}/lib:${JRE_HOME}/lib
export PATH=${JAVA_HOME}/bin:$PATH


text:
<link rel="import" href="lodash.html">
<link rel="import" href="moment-timezone.html">

redpajama_set_name: RedPajamaGithub


text:
"""Test listing resources.
"""

import datetime
import logging
import testscenarios

from ceilometer.publisher import utils
from ceilometer import sample

from ceilometer.tests import api as tests_api
from ceilometer.tests import db as tests_db

load_tests = testscenarios.load_tests_apply_scenarios

LOG = logging.getLogger(__name__)

class TestListEmptyResources(tests_api.TestBase,
                             tests_db.MixinTestsWithBackendScenarios):

    def test_empty(self):
        data = self.get('/resources')
        self.assertEqual({'resources': []}, data)

class TestListResourcesBase(tests_api.TestBase,
                            tests_db.MixinTestsWithBackendScenarios):

    def setUp(self):
        super(TestListResourcesBase, self).setUp()

        for cnt in [
                sample.Sample(
                    'instance',
                    'cumulative',
                    '',
                    1,
                    'user-id',
                    'project-id',
                    'resource-id',
                    timestamp=datetime.datetime(2012, 7, 2, 10, 40),
                    resource_metadata={'display_name': 'test-server',
                                       'tag': 'self.sample'},
                    source='test_list_resources',
                ),
                sample.Sample(
                    'instance',
                    'cumulative',
                    '',
                    1,
                    'user-id',
                    'project-id',
                    'resource-id-alternate',
                    timestamp=datetime.datetime(2012, 7, 2, 10, 41),
                    resource_metadata={'display_name': 'test-server',
                                       'tag': 'self.sample2'},
                    source='test_list_resources',
                ),
                sample.Sample(
                    'instance',
                    'cumulative',
                    '',
                    1,
                    'user-id2',
                    'project-id2',
                    'resource-id2',
                    timestamp=datetime.datetime(2012, 7, 2, 10, 42),
                    resource_metadata={'display_name': 'test-server',
                                       'tag': 'self.sample3'},
                    source='test_list_resources',
                ),
                sample.Sample(
                    'instance',
                    'cumulative',
                    '',
                    1,
                    'user-id',
                    'project-id',
                    'resource-id',
                    timestamp=datetime.datetime(2012, 7, 2, 10, 43),
                    resource_metadata={'display_name': 'test-server',
                                       'tag': 'self.sample4'},
                    source='test_list_resources',
                )]:
            msg = utils.meter_message_from_counter(
                cnt,
                self.CONF.publisher.metering_secret)
            self.conn.record_metering_data(msg)

class TestListResources(TestListResourcesBase):

    def test_list_resources(self):
        data = self.get('/resources')
        self.assertEqual(3, len(data['resources']))
        self.assertEqual(set(r['resource_id'] for r in data['resources']),
                         set(['resource-id',
                              'resource-id-alternate',
                              'resource-id2']))

    def test_list_resources_non_admin(self):
        data = self.get('/resources',
                        headers={"X-Roles": "Member",
                                 "X-Project-Id": "project-id"})
        self.assertEqual(2, len(data['resources']))
        self.assertEqual(set(r['resource_id'] for r in data['resources']),
                         set(['resource-id', 'resource-id-alternate']))

    def test_list_resources_with_timestamps(self):
        data = self.get('/resources',
                        start_timestamp=datetime.datetime(
                            2012, 7, 2, 10, 41).isoformat(),
                        end_timestamp=datetime.datetime(
                            2012, 7, 2, 10, 43).isoformat())
        self.assertEqual(set(r['resource_id'] for r in data['resources']),
                         set(['resource-id-alternate', 'resource-id2']))

    def test_list_resources_with_timestamps_non_admin(self):
        data = self.get('/resources',
                        start_timestamp=datetime.datetime(
                            2012, 7, 2, 10, 41).isoformat(),
                        end_timestamp=datetime.datetime(
                            2012, 7, 2, 10, 43).isoformat(),
                        headers={"X-Roles": "Member",
                                 "X-Project-Id": "project-id"})
        self.assertEqual(set(r['resource_id'] for r in data['resources']),
                         set(['resource-id-alternate']))

    def test_with_source(self):
        data = self.get('/sources/test_list_resources/resources')
        ids = set(r['resource_id'] for r in data['resources'])
        self.assertEqual(set(['resource-id',
                              'resource-id2',
                              'resource-id-alternate']), ids)

    def test_with_source_non_admin(self):
        data = self.get('/sources/test_list_resources/resources',
                        headers={"X-Roles": "Member",
                        "X-Project-Id": "project-id"})
        ids = set(r['resource_id'] for r in data['resources'])
        self.assertEqual(set(['resource-id', 'resource-id-alternate']), ids)

    def test_with_source_with_timestamps(self):
        data = self.get('/sources/test_list_resources/resources',
                        start_timestamp=datetime.datetime(
                            2012, 7, 2, 10, 41).isoformat(),
                        end_timestamp=datetime.datetime(
                            2012, 7, 2, 10, 43).isoformat())
        ids = set(r['resource_id'] for r in data['resources'])
        self.assertEqual(set(['resource-id2', 'resource-id-alternate']), ids)

    def test_with_source_with_timestamps_non_admin(self):
        data = self.get('/sources/test_list_resources/resources',
                        headers={"X-Roles": "Member",
                                 "X-Project-Id": "project-id"},
                        start_timestamp=datetime.datetime(
                            2012, 7, 2, 10, 41).isoformat(),
                        end_timestamp=datetime.datetime(
                            2012, 7, 2, 10, 43).isoformat())
        ids = set(r['resource_id'] for r in data['resources'])
        self.assertEqual(set(['resource-id-alternate']), ids)

    def test_with_source_non_existent(self):
        data = self.get('/sources/test_list_resources_dont_exist/resources')
        self.assertEqual(data['resources'], [])

    def test_with_user(self):
        data = self.get('/users/user-id/resources')
        ids = set(r['resource_id'] for r in data['resources'])
        self.assertEqual(set(['resource-id', 'resource-id-alternate']), ids)

    def test_with_user_non_admin(self):
        data = self.get('/users/user-id/resources',
                        headers={"X-Roles": "Member",
                                 "X-Project-Id": "project-id"})
        ids = set(r['resource_id'] for r in data['resources'])
        self.assertEqual(set(['resource-id', 'resource-id-alternate']), ids)

    def test_with_user_wrong_tenant(self):
        data = self.get('/users/user-id/resources',
                        headers={"X-Roles": "Member",
                                 "X-Project-Id": "project-jd"})
        ids = set(r['resource_id'] for r in data['resources'])
        self.assertEqual(set(), ids)

    def test_with_user_with_timestamps(self):
        data = self.get('/users/user-id/resources',
                        start_timestamp=datetime.datetime(
                            2012, 7, 2, 10, 42).isoformat(),
                        end_timestamp=datetime.datetime(
                            2012, 7, 2, 10, 42).isoformat())
        ids = set(r['resource_id'] for r in data['resources'])
        self.assertEqual(set(), ids)

    def test_with_user_with_timestamps_non_admin(self):
        data = self.get('/users/user-id/resources',
                        headers={"X-Roles": "Member",
                                 "X-Project-Id": "project-id"},
                        start_timestamp=datetime.datetime(
                            2012, 7, 2, 10, 42).isoformat(),
                        end_timestamp=datetime.datetime(
                            2012, 7, 2, 10, 42).isoformat())
        ids = set(r['resource_id'] for r in data['resources'])
        self.assertEqual(set(), ids)

    def test_with_user_non_existent(self):
        data = self.get('/users/user-id-foobar123/resources')
        self.assertEqual(data['resources'], [])

    def test_with_project(self):
        data = self.get('/projects/project-id/resources')
        ids = set(r['resource_id'] for r in data['resources'])
        self.assertEqual(set(['resource-id', 'resource-id-alternate']), ids)

    def test_with_project_non_admin(self):
        data = self.get('/projects/project-id/resources',
                        headers={"X-Roles": "Member",
                                 "X-Project-Id": "project-id"})
        ids = set(r['resource_id'] for r in data['resources'])
        self.assertEqual(set(['resource-id', 'resource-id-alternate']), ids)

    def test_with_project_with_timestamp(self):
        data = self.get('/projects/project-id/resources',
                        start_timestamp=datetime.datetime(
                            2012, 7, 2, 10, 40).isoformat(),
                        end_timestamp=datetime.datetime(
                            2012, 7, 2, 10, 41).isoformat())
        ids = set(r['resource_id'] for r in data['resources'])
        self.assertEqual(set(['resource-id']), ids)

    def test_with_project_with_timestamp_non_admin(self):
        data = self.get('/projects/project-id/resources',
                        headers={"X-Roles": "Member",
                                 "X-Project-Id": "project-id"},
                        start_timestamp=datetime.datetime(
                            2012, 7, 2, 10, 40).isoformat(),
                        end_timestamp=datetime.datetime(
                            2012, 7, 2, 10, 41).isoformat())
        ids = set(r['resource_id'] for r in data['resources'])
        self.assertEqual(set(['resource-id']), ids)

    def test_with_project_non_existent(self):
        data = self.get('/projects/jd-was-here/resources')
        self.assertEqual(data['resources'], [])

class TestListResourcesMetaquery(TestListResourcesBase,
                                 tests_db.MixinTestsWithBackendScenarios):

    def test_metaquery1(self):
        q = '/sources/test_list_resources/resources'
        data = self.get('%s?metadata.display_name=test-server' % q)
        self.assertEqual(3, len(data['resources']))

    def test_metaquery1_non_admin(self):
        q = '/sources/test_list_resources/resources'
        data = self.get('%s?metadata.display_name=test-server' % q,
                        headers={"X-Roles": "Member",
                                 "X-Project-Id": "project-id"})
        self.assertEqual(2, len(data['resources']))

    def test_metaquery2(self):
        q = '/sources/test_list_resources/resources'
        data = self.get('%s?metadata.tag=self.sample4' % q)
        self.assertEqual(1, len(data['resources']))

    def test_metaquery2_non_admin(self):
        q = '/sources/test_list_resources/resources'
        data = self.get('%s?metadata.tag=self.sample4' % q,
                        headers={"X-Roles": "Member",
                                 "X-Project-Id": "project-id"})
        self.assertEqual(1, len(data['resources']))


text:
// --------------------------------------------------------------------------------------------
// <copyright file="SingleResult.cs" company="Effort Team">
//     Copyright (C) Effort Team
//
//     Permission is hereby granted, free of charge, to any person obtaining a copy
//     of this software and associated documentation files (the "Software"), to deal
//     in the Software without restriction, including without limitation the rights
//     to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//     copies of the Software, and to permit persons to whom the Software is
//     furnished to do so, subject to the following conditions:
//
//     The above copyright notice and this permission notice shall be included in
//     all copies or substantial portions of the Software.
//
//     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//     IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//     FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//     AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//     LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//     OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//     THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------

namespace Effort.Internal.DbCommandTreeTransformation
{
    using System.Collections;
    using System.Collections.Generic;

    internal class SingleResult<T> : IEnumerable<T>
    {
        private T item;

        public SingleResult(T item)
        {
            this.item = item;
        }

        public IEnumerator<T> GetEnumerator()
        {
            yield return item;
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            yield return item;
        }
    }
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/Theme.AppCompat.Light.NoActionBar">

    </android.support.v7.widget.Toolbar>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyleview"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </android.support.v7.widget.RecyclerView>

</LinearLayout>


text:
var assert = require('assert'),
  chai = require('chai'),
  expect = chai.expect,
  should = chai.should(),
  analytics = require('../../index'),
  candlesticks = require('../candlesticks');

describe('analytics', function() {
  describe('#convertOHLC', function() {
    describe('()', function() {
      it('should throw validation error because at least two parameters are required', function() {
        var error = null;

        try {
          analytics.convertOHLC();
        } catch(e) {
          error = e;
        }

        expect('' + error).to.be.equal('TypeError: Wrong number of arguments');
      });
    });

    describe('(candlesticks)', function() {
      it('should throw validation error because at least two parameters are required', function() {
        var error = null;

        try {
          analytics.convertOHLC([]);
        } catch(e) {
          error = e;
        }

        expect('' + error).to.be.equal('TypeError: Wrong number of arguments');
      });
    });

    describe('(candlesticks, timeframe)', function() {
      it('should return empty set if empty array is passed in', function() {
        var error = null;
        var ohlc = null;

        try {
          ohlc = analytics.convertOHLC([], 1);
        } catch(e) {
          error = e;
        }

        expect(error).to.be.equal(null);
        expect(ohlc.length).to.be.equal(0);
      });
    });

    describe('(candlesticks, timeframe)', function() {

      var error = null;
      var ohlc = null;

      before(function() {
        var candlesticks = [
          {"open":1.11399,"low":1.1122,"high":1.11421,"close":1.11393,"time":0},
          {"open":1.11393,"low":1.1129,"high":1.11431,"close":1.1129,"time":100}
        ];

        try {
          ohlc = analytics.convertOHLC(candlesticks, 200);
        } catch(e) {
          error = e;
        }
      });

      it('should merge two predefined candlesticks when converting to larger timeframe', function() {
        expect(ohlc.length).to.equal(1);
      });

      it('should have the opeb price set to the open price of the first candlestick', function() {
        expect(ohlc[0].open).to.equal(1.11399);
      });

      it('should have the high price set to the highest price in specified range', function() {
        expect(ohlc[0].high).to.equal(1.11431);
      });

      it('should have the low price set to the lowest price in a specified range', function() {
        expect(ohlc[0].low).to.equal(1.1122);
      });

      it('should have the close price set to the close price of the last candlestick', function() {
        expect(ohlc[0].close).to.equal(1.1129);
      });

      it('should have time set to the first candlestck', function() {
        expect(ohlc[0].time).to.equal(0);
      });
    });
  });
});


text:
package br.com.munif.microservices.periodoserver;

import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class PeriodoController {

    @Autowired
    private TimeClient timeClient;

    @RequestMapping("/")
    public String getTime() {
        return "Manha/Tarde/Noite" + timeClient.getTime();
    }

}


text:
"""
tests.helper
~~~~~~~~~~~~~

Helper method for writing tests.
"""
import os
from datetime import timedelta
from unittest import mock

from homeassistant import core as ha, loader
import homeassistant.util.location as location_util
import homeassistant.util.dt as dt_util
from homeassistant.helpers.entity import ToggleEntity
from homeassistant.const import (
    STATE_ON, STATE_OFF, DEVICE_DEFAULT_NAME, EVENT_TIME_CHANGED,
    EVENT_STATE_CHANGED)
from homeassistant.components import sun, mqtt

def get_test_config_dir():
    """ Returns a path to a test config dir. """
    return os.path.join(os.path.dirname(__file__), "config")

def get_test_home_assistant(num_threads=None):
    """ Returns a Home Assistant object pointing at test config dir. """
    if num_threads:
        orig_num_threads = ha.MIN_WORKER_THREAD
        ha.MIN_WORKER_THREAD = num_threads

    hass = ha.HomeAssistant()

    if num_threads:
        ha.MIN_WORKER_THREAD = orig_num_threads

    hass.config.config_dir = get_test_config_dir()
    hass.config.latitude = 32.87336
    hass.config.longitude = -117.22743

    # if not loader.PREPARED:
    loader. prepare(hass)

    return hass

def mock_detect_location_info():
    """ Mock implementation of util.detect_location_info. """
    return location_util.LocationInfo(
        ip='1.1.1.1',
        country_code='US',
        country_name='United States',
        region_code='CA',
        region_name='California',
        city='San Diego',
        zip_code='92122',
        time_zone='America/Los_Angeles',
        latitude='2.0',
        longitude='1.0',
        use_fahrenheit=True,
    )

def mock_service(hass, domain, service):
    """
    Sets up a fake service.
    Returns a list that logs all calls to fake service.
    """
    calls = []

    hass.services.register(
        domain, service, lambda call: calls.append(call))

    return calls

def fire_mqtt_message(hass, topic, payload, qos=0):
    hass.bus.fire(mqtt.EVENT_MQTT_MESSAGE_RECEIVED, {
        mqtt.ATTR_TOPIC: topic,
        mqtt.ATTR_PAYLOAD: payload,
        mqtt.ATTR_QOS: qos,
    })

def fire_time_changed(hass, time):
    hass.bus.fire(EVENT_TIME_CHANGED, {'now': time})

def trigger_device_tracker_scan(hass):
    """ Triggers the device tracker to scan. """
    fire_time_changed(
        hass, dt_util.utcnow().replace(second=0) + timedelta(hours=1))

def ensure_sun_risen(hass):
    """ Trigger sun to rise if below horizon. """
    if sun.is_on(hass):
        return
    fire_time_changed(hass, sun.next_rising_utc(hass) + timedelta(seconds=10))

def ensure_sun_set(hass):
    """ Trigger sun to set if above horizon. """
    if not sun.is_on(hass):
        return
    fire_time_changed(hass, sun.next_setting_utc(hass) + timedelta(seconds=10))

def mock_state_change_event(hass, new_state, old_state=None):
    event_data = {
        'entity_id': new_state.entity_id,
        'new_state': new_state,
    }

    if old_state:
        event_data['old_state'] = old_state

    hass.bus.fire(EVENT_STATE_CHANGED, event_data)

def mock_http_component(hass):
    hass.http = MockHTTP()
    hass.config.components.append('http')

def mock_mqtt_component(hass):
    with mock.patch('homeassistant.components.mqtt.MQTT'):
        mqtt.setup(hass, {
            mqtt.DOMAIN: {
                mqtt.CONF_BROKER: 'mock-broker',
            }
        })
        hass.config.components.append(mqtt.DOMAIN)

class MockHTTP(object):
    """ Mocks the HTTP module. """

    def register_path(self, method, url, callback, require_auth=True):
        pass

class MockModule(object):
    """ Provides a fake module. """

    def __init__(self, domain, dependencies=[], setup=None):
        self.DOMAIN = domain
        self.DEPENDENCIES = dependencies
        # Setup a mock setup if none given.
        self.setup = lambda hass, config: False if setup is None else setup

class MockToggleDevice(ToggleEntity):
    """ Provides a mock toggle device. """
    def __init__(self, name, state):
        self._name = name or DEVICE_DEFAULT_NAME
        self._state = state
        self.calls = []

    @property
    def name(self):
        """ Returns the name of the device if any. """
        self.calls.append(('name', {}))
        return self._name

    @property
    def state(self):
        """ Returns the name of the device if any. """
        self.calls.append(('state', {}))
        return self._state

    @property
    def is_on(self):
        """ True if device is on. """
        self.calls.append(('is_on', {}))
        return self._state == STATE_ON

    def turn_on(self, **kwargs):
        """ Turn the device on. """
        self.calls.append(('turn_on', kwargs))
        self._state = STATE_ON

    def turn_off(self, **kwargs):
        """ Turn the device off. """
        self.calls.append(('turn_off', kwargs))
        self._state = STATE_OFF

    def last_call(self, method=None):
        if not self.calls:
            return None
        elif method is None:
            return self.calls[-1]
        else:
            try:
                return next(call for call in reversed(self.calls)
                            if call[0] == method)
            except StopIteration:
                return None


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Class javassist.expr.ExprEditor (Javassist API)
</TITLE>

<META NAME="date" CONTENT="2010-07-19">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
javassist.expr.ExprEditor

Packages that use ExprEditor

javassist
The Javassist Core API.

javassist.expr
This package contains the classes for modifying a method body.

Uses of ExprEditor in javassist

Methods in javassist with parameters of type ExprEditor

 void
CtClass.instrument(ExprEditor editor)

          Modifies the bodies of all methods and constructors
 declared in the class.

 void
CtBehavior.instrument(ExprEditor editor)

          Modifies the method/constructor body.

Uses of ExprEditor in javassist.expr

Methods in javassist.expr with parameters of type ExprEditor

 void
Expr.replace(java.lang.String statement,
        ExprEditor recursive)

          Replaces this expression with the bytecode derived from
 the given source text and ExprEditor.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Javassist, a Java-bytecode translator toolkit.

Copyright (C) 1999-2010 Shigeru Chiba. All Rights Reserved.


text:
/**
 *
 */
package com.samuelpalukuri.projecteuler;

/**
 * @author Samuel_Palukuri
 *
 */
public class P003 implements EulerSolution {

	/* (non-Javadoc)
	 * @see com.samuelpalukuri.projecteuler.EulerSolution#run()
	 */
	@Override
	public String run() {

		long input = 600851475143l;
		long maxPrimeFactor = 3;

		if(input % 2 == 0) {
			maxPrimeFactor = 2;
			return Long.toString(maxPrimeFactor);
		}

		for (long i = 3; i*i <= input; i += 2) {
			if (Library.isPrime(i)) {
				if (600851475143l % i == 0) {
					maxPrimeFactor = i;
				}
			}
		}
		return Long.toString(maxPrimeFactor);
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		long startTime = System.nanoTime();

		System.out.println(new P003().run());

		Library.printTimeTaken(startTime);

	}

}


text:
CURRENT_DIR=${PWD}

# 脚本所在目录
SCRIPT_DIR=$(cd "$(dirname "$0")"; pwd)

## blog 目录
BLOG_DIRECTORY=${SCRIPT_DIR}/..

GITHUB_REF=github.com/GreedBell/blog.git

if ! [ -n "${GITHUB_API_KEY}" ]; then
  echo "no valid GITHUB_API_KEY"
  exit 1
fi

# update master
# echo update SUMMARY.md and README.md
# cd ${BLOG_DIRECTORY}
# git remote add upstream https://GreedBell:${GITHUB_API_KEY}@${GITHUB_REF}
# git fetch upstream
# git reset upstream/master
#
# git config user.email "bell@greedlab.com"
# git config user.name "Bell"
# git add . --all
# git commit -m "update SUMMARY.md and README.md by travis"
# git push -q upstream HEAD:master > /dev/null 2>&1

# deploy the gh-pages
echo Deploy to GitHub Pages
cd ${BLOG_DIRECTORY}/_book
git init
git config user.email "bell@greedlab.com"
git config user.name "Bell"
git remote add upstream https://greedbell:${GITHUB_API_KEY}@${GITHUB_REF}
git fetch upstream
git reset upstream/gh-pages
git add . --all
git commit -m "Deploy to GitHub Pages by scripts"
git push -q upstream HEAD:gh-pages

cd ${CURRENT_DIR}


text:
function Person(job, married) {
    this.job = job;
    this.married = married;
    // add a "speak" method to Person!
    this.speak = function () {
        console.log("Hello!");
    }
}

var user = new Person("Codecademy Student",false);
user.speak();


text:
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache 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.apache.org/licenses/LICENSE-2.0

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.

"""
import collections
import os

from resource_management.libraries.functions.version import format_stack_version
from resource_management.libraries.resources.properties_file import PropertiesFile
from resource_management.libraries.resources.template_config import TemplateConfig
from resource_management.core.resources.system import Directory, Execute, File, Link
from resource_management.core.source import StaticFile, Template, InlineTemplate
from resource_management.libraries.functions import format
from resource_management.libraries.functions.stack_features import check_stack_feature
from resource_management.libraries.functions import StackFeature
from resource_management.libraries.functions import Direction

from resource_management.core.logger import Logger

def kafka(upgrade_type=None):
    import params
    ensure_base_directories()

    kafka_server_config = mutable_config_dict(params.config['configurations']['kafka-broker'])
    # This still has an issue of hostnames being alphabetically out-of-order for broker.id in HDP-2.2.
    # Starting in HDP 2.3, Kafka handles the generation of broker.id so Ambari doesn't have to.

    effective_version = params.stack_version_formatted if upgrade_type is None else format_stack_version(params.version)
    Logger.info(format("Effective stack version: {effective_version}"))

    # listeners and advertised.listeners are only added in 2.3.0.0 onwards.
    if effective_version is not None and effective_version != "" and \
       check_stack_feature(StackFeature.KAFKA_LISTENERS, effective_version):

       listeners = kafka_server_config['listeners'].replace("localhost", params.hostname)
       Logger.info(format("Kafka listeners: {listeners}"))
       kafka_server_config['listeners'] = listeners

       if params.security_enabled and params.kafka_kerberos_enabled:
         Logger.info("Kafka kerberos security is enabled.")
         kafka_server_config['advertised.listeners'] = listeners
         Logger.info(format("Kafka advertised listeners: {listeners}"))
       elif 'advertised.listeners' in kafka_server_config:
         advertised_listeners = kafka_server_config['advertised.listeners'].replace("localhost", params.hostname)
         kafka_server_config['advertised.listeners'] = advertised_listeners
         Logger.info(format("Kafka advertised listeners: {advertised_listeners}"))
    else:
      kafka_server_config['host.name'] = params.hostname

    if params.has_metric_collector:
      kafka_server_config['kafka.timeline.metrics.hosts'] = params.ams_collector_hosts
      kafka_server_config['kafka.timeline.metrics.port'] = params.metric_collector_port
      kafka_server_config['kafka.timeline.metrics.protocol'] = params.metric_collector_protocol
      kafka_server_config['kafka.timeline.metrics.truststore.path'] = params.metric_truststore_path
      kafka_server_config['kafka.timeline.metrics.truststore.type'] = params.metric_truststore_type
      kafka_server_config['kafka.timeline.metrics.truststore.password'] = params.metric_truststore_password

    kafka_data_dir = kafka_server_config['log.dirs']
    kafka_data_dirs = filter(None, kafka_data_dir.split(","))

    rack="/default-rack"
    i=0
    if len(params.all_racks) > 0:
     for host in params.all_hosts:
      if host == params.hostname:
        rack=params.all_racks[i]
        break
      i=i+1

    kafka_server_config['broker.rack']=rack

    Directory(kafka_data_dirs,
              mode=0755,
              cd_access='a',
              owner=params.kafka_user,
              group=params.user_group,
              create_parents = True,
              recursive_ownership = True,
    )

    PropertiesFile("server.properties",
                      dir=params.conf_dir,
                      properties=kafka_server_config,
                      owner=params.kafka_user,
                      group=params.user_group,
    )

    File(format("{conf_dir}/kafka-env.sh"),
          owner=params.kafka_user,
          content=InlineTemplate(params.kafka_env_sh_template)
     )

    if (params.log4j_props != None):
        File(format("{conf_dir}/log4j.properties"),
             mode=0644,
             group=params.user_group,
             owner=params.kafka_user,
             content=InlineTemplate(params.log4j_props)
         )

    if params.security_enabled and params.kafka_kerberos_enabled:
      if params.kafka_jaas_conf_template:
        File(format("{conf_dir}/kafka_jaas.conf"),
             owner=params.kafka_user,
             content=InlineTemplate(params.kafka_jaas_conf_template)
        )
      else:
        TemplateConfig(format("{conf_dir}/kafka_jaas.conf"),
                         owner=params.kafka_user)

      if params.kafka_client_jaas_conf_template:
        File(format("{conf_dir}/kafka_client_jaas.conf"),
             owner=params.kafka_user,
             content=InlineTemplate(params.kafka_client_jaas_conf_template)
        )
      else:
        TemplateConfig(format("{conf_dir}/kafka_client_jaas.conf"),
                       owner=params.kafka_user)

    # On some OS this folder could be not exists, so we will create it before pushing there files
    Directory(params.limits_conf_dir,
              create_parents = True,
              owner='root',
              group='root'
    )

    File(os.path.join(params.limits_conf_dir, 'kafka.conf'),
         owner='root',
         group='root',
         mode=0644,
         content=Template("kafka.conf.j2")
    )

    File(os.path.join(params.conf_dir, 'tools-log4j.properties'),
         owner='root',
         group='root',
         mode=0644,
         content=Template("tools-log4j.properties.j2")
         )

    setup_symlink(params.kafka_managed_pid_dir, params.kafka_pid_dir)
    setup_symlink(params.kafka_managed_log_dir, params.kafka_log_dir)

def mutable_config_dict(kafka_broker_config):
    kafka_server_config = {}
    for key, value in kafka_broker_config.iteritems():
        kafka_server_config[key] = value
    return kafka_server_config

# Used to workaround the hardcoded pid/log dir used on the kafka bash process launcher
def setup_symlink(kafka_managed_dir, kafka_ambari_managed_dir):
  import params
  backup_folder_path = None
  backup_folder_suffix = "_tmp"
  if kafka_ambari_managed_dir != kafka_managed_dir:
    if os.path.exists(kafka_managed_dir) and not os.path.islink(kafka_managed_dir):

      # Backup existing data before delete if config is changed repeatedly to/from default location at any point in time time, as there may be relevant contents (historic logs)
      backup_folder_path = backup_dir_contents(kafka_managed_dir, backup_folder_suffix)

      Directory(kafka_managed_dir,
                action="delete",
                create_parents = True)

    elif os.path.islink(kafka_managed_dir) and os.path.realpath(kafka_managed_dir) != kafka_ambari_managed_dir:
      Link(kafka_managed_dir,
           action="delete")

    if not os.path.islink(kafka_managed_dir):
      Link(kafka_managed_dir,
           to=kafka_ambari_managed_dir)

  elif os.path.islink(kafka_managed_dir): # If config is changed and coincides with the kafka managed dir, remove the symlink and physically create the folder
    Link(kafka_managed_dir,
         action="delete")

    Directory(kafka_managed_dir,
              mode=0755,
              cd_access='a',
              owner=params.kafka_user,
              group=params.user_group,
              create_parents = True,
              recursive_ownership = True,
    )

  if backup_folder_path:
    # Restore backed up files to current relevant dirs if needed - will be triggered only when changing to/from default path;
    for file in os.listdir(backup_folder_path):
      if os.path.isdir(os.path.join(backup_folder_path, file)):
        Execute(('cp', '-r', os.path.join(backup_folder_path, file), kafka_managed_dir),
                sudo=True)
        Execute(("chown", "-R", format("{kafka_user}:{user_group}"), os.path.join(kafka_managed_dir, file)),
                sudo=True)
      else:
        File(os.path.join(kafka_managed_dir,file),
             owner=params.kafka_user,
             content = StaticFile(os.path.join(backup_folder_path,file)))

    # Clean up backed up folder
    Directory(backup_folder_path,
              action="delete",
              create_parents = True)

# Uses agent temp dir to store backup files
def backup_dir_contents(dir_path, backup_folder_suffix):
  import params
  backup_destination_path = params.tmp_dir + os.path.normpath(dir_path)+backup_folder_suffix
  Directory(backup_destination_path,
            mode=0755,
            cd_access='a',
            owner=params.kafka_user,
            group=params.user_group,
            create_parents = True,
            recursive_ownership = True,
  )
  # Safely copy top-level contents to backup folder
  for file in os.listdir(dir_path):
    if os.path.isdir(os.path.join(dir_path, file)):
      Execute(('cp', '-r', os.path.join(dir_path, file), backup_destination_path),
              sudo=True)
      Execute(("chown", "-R", format("{kafka_user}:{user_group}"), os.path.join(backup_destination_path, file)),
              sudo=True)
    else:
      File(os.path.join(backup_destination_path, file),
         owner=params.kafka_user,
         content = StaticFile(os.path.join(dir_path,file)))

  return backup_destination_path

def ensure_base_directories():
  import params
  Directory([params.kafka_log_dir, params.kafka_pid_dir, params.conf_dir],
            mode=0755,
            cd_access='a',
            owner=params.kafka_user,
            group=params.user_group,
            create_parents = True,
            recursive_ownership = True,
            )


text:
package headrevision.BehatReporter.report;

import junit.framework.Assert;
import junit.framework.TestCase;

public class ResultTest extends TestCase {

	public void testResultName() {
		Result sut = Result.PASSED;

		Assert.assertEquals("passed", sut.getName());
	}

}


text:
package de.fhg.igd.iva.colormaps;

import java.awt.Color;
import java.awt.geom.AffineTransform;

/**
 * Transforms a given colormap
 * @author Martin Steiger
 */
public class TransformedColormap implements Colormap
{
	private double m00;
	private double m01;
	private double m02;
	private double m10;
	private double m11;
	private double m12;

	private final Colormap original;

	public static TransformedColormap identity(Colormap colormap)
	{
		return new TransformedColormap(colormap, 1, 0, 0, 1, 0, 0);
	}

	/**
	 * counter-clockwise
	 * @param colormap
	 * @return
	 */
	public static TransformedColormap rotated90(Colormap colormap)
	{
		return new TransformedColormap(colormap, 0, 1, -1, 0, 1, 0);
	}

	public static TransformedColormap rotated180(Colormap colormap)
	{
		return new TransformedColormap(colormap, -1, 0, 0, -1, 1, 1);
	}

	public static TransformedColormap rotated270(Colormap colormap)
	{
		return new TransformedColormap(colormap, 0, -1, 1, 0, 0, 1);
	}

	public static TransformedColormap flippedX(Colormap colormap)
	{
		return new TransformedColormap(colormap, -1, 0, 0, 1, 1, 0);
	}

	public static TransformedColormap flippedY(Colormap colormap)
	{
		return new TransformedColormap(colormap, 1, 0, 0, -1, 0, 1);
	}

	private TransformedColormap(Colormap colormap,
			double m00, double m10,
            double m01, double m11,
            double m02, double m12)
	{
		this.original = colormap;

        this.m00 = m00;
        this.m10 = m10;
        this.m01 = m01;
        this.m11 = m11;
        this.m02 = m02;
        this.m12 = m12;
	}

	@Override
	public Color getColor(double ox, double oy)
	{
		double x = ox * m00 + oy * m01 + m02;
		double y = ox * m10 + oy * m11 + m12;

		return original.getColor(x, y);
	}

	/**
	 * @return a <b>new</b> transformation
	 */
	public AffineTransform getTransformation()
	{
		return new AffineTransform(m00, m10, m01, m11, m02, m12);
	}
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using Color = System.Drawing.Color;

namespace PlatformAPI.GDIPlus
{
    public class ImageAttributesPlus
    {
        ImageAttributesPlus()
        {
            nativeImageAttr = new GpImageAttributes();
            lastResult = NativeMethods.GdipCreateImageAttributes(out nativeImageAttr);
        }

        ~ImageAttributesPlus()
        {
            NativeMethods.GdipDisposeImageAttributes(nativeImageAttr);
        }

        ImageAttributesPlus Clone()
        {
            GpImageAttributes clone;

            SetStatus(NativeMethods.GdipCloneImageAttributes(
                                                nativeImageAttr,
                                                out clone));

            return new ImageAttributesPlus(clone, lastResult);
        }

        GpStatus
        SetToIdentity(
            ColorAdjustType type
            )
        {
            return SetStatus(NativeMethods.GdipSetImageAttributesToIdentity(
                                                nativeImageAttr,
                                                type));
        }

        GpStatus
        Reset(
            ColorAdjustType type
            )
        {
            return SetStatus(NativeMethods.GdipResetImageAttributes(
                                                nativeImageAttr,
                                                type));
        }

        //Status
        //SetColorMatrix(
        //     ColorMatrix colorMatrix,
        //    ColorMatrixFlags mode = ColorMatrixFlagsDefault,
        //    ColorAdjustType type = ColorAdjustTypeDefault
        //    )
        //{
        //    return SetStatus(NativeMethods.GdipSetImageAttributesColorMatrix(
        //                                        nativeImageAttr,
        //                                        type,
        //                                        true,
        //                                        colorMatrix,
        //                                        null,
        //                                        mode));
        //}

        //Status ClearColorMatrix(
        //    ColorAdjustType type = ColorAdjustTypeDefault
        //    )
        //{
        //    return SetStatus(NativeMethods.GdipSetImageAttributesColorMatrix(
        //                                        nativeImageAttr,
        //                                        type,
        //                                        false,
        //                                        null,
        //                                        null,
        //                                        ColorMatrixFlagsDefault));
        //}

        //Status
        //SetColorMatrices(
        //     ColorMatrix *colorMatrix,
        //     ColorMatrix *grayMatrix,
        //    ColorMatrixFlags mode = ColorMatrixFlagsDefault,
        //    ColorAdjustType type = ColorAdjustTypeDefault
        //    )
        //{
        //    return SetStatus(NativeMethods.GdipSetImageAttributesColorMatrix(
        //                                        nativeImageAttr,
        //                                        type,
        //                                        true,
        //                                        colorMatrix,
        //                                        grayMatrix,
        //                                        mode));
        //}

        //Status ClearColorMatrices(
        //    ColorAdjustType type = ColorAdjustTypeDefault
        //    )
        //{
        //    return SetStatus(NativeMethods.GdipSetImageAttributesColorMatrix(
        //                                        nativeImageAttr,
        //                                        type,
        //                                        false,
        //                                        null,
        //                                        null,
        //                                        ColorMatrixFlagsDefault));
        //}

        //Status SetThreshold(
        //    float threshold,
        //    ColorAdjustType type = ColorAdjustTypeDefault
        //    )
        //{
        //    return SetStatus(NativeMethods.GdipSetImageAttributesThreshold(
        //                                        nativeImageAttr,
        //                                        type,
        //                                        true,
        //                                        threshold));
        //}

        //Status ClearThreshold(
        //    ColorAdjustType type = ColorAdjustTypeDefault
        //    )
        //{
        //    return SetStatus(NativeMethods.GdipSetImageAttributesThreshold(
        //                                        nativeImageAttr,
        //                                        type,
        //                                        false,
        //                                        0.0));
        //}

        GpStatus SetGamma(
            float gamma,
            ColorAdjustType type
            )
        {
            return SetStatus(NativeMethods.GdipSetImageAttributesGamma(
                                                nativeImageAttr,
                                                type,
                                                true,
                                                gamma));
        }

        GpStatus ClearGamma(
            ColorAdjustType type
            )
        {
            return SetStatus(NativeMethods.GdipSetImageAttributesGamma(
                                                nativeImageAttr,
                                                type,
                                                false,
                                                0.0f));
        }

        GpStatus SetNoOp(
            ColorAdjustType type
            )
        {
            return SetStatus(NativeMethods.GdipSetImageAttributesNoOp(
                                                nativeImageAttr,
                                                type,
                                                true));
        }

        GpStatus ClearNoOp(
            ColorAdjustType type
            )
        {
            return SetStatus(NativeMethods.GdipSetImageAttributesNoOp(
                                                nativeImageAttr,
                                                type,
                                                false));
        }

        GpStatus SetColorKey(
             Color colorLow,
             Color colorHigh,
            ColorAdjustType type
            )
        {
            return SetStatus(NativeMethods.GdipSetImageAttributesColorKeys(
                                                nativeImageAttr,
                                                type,
                                                true,
                                                colorLow.ToArgb(),
                                                colorHigh.ToArgb()));
        }

        GpStatus ClearColorKey(
            ColorAdjustType type
            )
        {
            return SetStatus(NativeMethods.GdipSetImageAttributesColorKeys(
                                                nativeImageAttr,
                                                type,
                                                false,
                                                0,
                                                0));
        }

        //Status SetOutputChannel(
        //    ColorChannelFlags channelFlags,
        //    ColorAdjustType type = ColorAdjustTypeDefault
        //    )
        //{
        //    return SetStatus(NativeMethods.GdipSetImageAttributesOutputChannel(
        //                                        nativeImageAttr,
        //                                        type,
        //                                        true,
        //                                        channelFlags));
        //}

        //Status ClearOutputChannel(
        //    ColorAdjustType type = ColorAdjustTypeDefault
        //    )
        //{
        //    return SetStatus(NativeMethods.GdipSetImageAttributesOutputChannel(
        //                                        nativeImageAttr,
        //                                        type,
        //                                        false,
        //                                        ColorChannelFlagsLast));
        //}

        //Status SetOutputChannelColorProfile(
        //     WCHAR *colorProfileFilename,
        //    ColorAdjustType type = ColorAdjustTypeDefault
        //    )
        //{
        //    return SetStatus(NativeMethods.GdipSetImageAttributesOutputChannelColorProfile(
        //                                        nativeImageAttr,
        //                                        type,
        //                                        true,
        //                                        colorProfileFilename));
        //}

        //Status ClearOutputChannelColorProfile(
        //    ColorAdjustType type = ColorAdjustTypeDefault
        //    )
        //{
        //    return SetStatus(NativeMethods.GdipSetImageAttributesOutputChannelColorProfile(
        //                                        nativeImageAttr,
        //                                        type,
        //                                        false,
        //                                        null));
        //}

        //Status SetRemapTable(
        //    UINT mapSize,
        //     ColorMap *map,
        //    ColorAdjustType type = ColorAdjustTypeDefault
        //    )
        //{
        //    return SetStatus(NativeMethods.GdipSetImageAttributesRemapTable(
        //                                        nativeImageAttr,
        //                                        type,
        //                                        true,
        //                                        mapSize,
        //                                        map));
        //}

        //Status ClearRemapTable(
        //    ColorAdjustType type = ColorAdjustTypeDefault
        //    )
        //{
        //    return SetStatus(NativeMethods.GdipSetImageAttributesRemapTable(
        //                                        nativeImageAttr,
        //                                        type,
        //                                        false,
        //                                        0,
        //                                        null));
        //}

        //Status SetBrushRemapTable(UINT mapSize,
        //                           ColorMap *map)
        //{
        //    return this.SetRemapTable(mapSize, map, ColorAdjustTypeBrush);
        //}

        //Status ClearBrushRemapTable()
        //{
        //    return this.ClearRemapTable(ColorAdjustTypeBrush);
        //}

        //Status SetWrapMode(WrapMode wrap,
        //                    Color& color = Color(),
        //                   BOOL clamp = false)
        //{
        //    ARGB argb = color.ToArgb();

        //    return SetStatus(NativeMethods.GdipSetImageAttributesWrapMode(
        //                       nativeImageAttr, wrap, argb, clamp));
        //}

        //// The flags of the palette are ignored.

        //Status GetAdjustedPalette(OUT ColorPalette* colorPalette,
        //                          ColorAdjustType colorAdjustType)
        //{
        //    return SetStatus(NativeMethods.GdipGetImageAttributesAdjustedPalette(
        //                       nativeImageAttr, colorPalette, colorAdjustType));
        //}

        GpStatus GetLastStatus()
        {
            GpStatus lastStatus = lastResult;
            lastResult = GpStatus.Ok;

            return lastStatus;
        }

        internal ImageAttributesPlus(GpImageAttributes imageAttr, GpStatus status)
        {
            SetNativeImageAttr(imageAttr);
            lastResult = status;
        }

        internal void SetNativeImageAttr(GpImageAttributes nativeImageAttr)
        {
            this.nativeImageAttr = nativeImageAttr;
        }

        GpStatus SetStatus(GpStatus status)
        {
            if (status != GpStatus.Ok)
                return (lastResult = status);
            else
                return status;
        }

        internal GpImageAttributes nativeImageAttr;
        private GpStatus lastResult;
    }
}


text:
angular
    .module('eArkPlatform.ipview')
    .service('ipFileTreeService', ipFileTreeService);

function ipFileTreeService($http, ipViewService) {

    var ftSvc = this;
    var tree = {};

    ftSvc.buildTree = buildTree;

    function buildTree(path, orderStatus){
        var action = ipViewService.serializeObj({ action: 'gettree', path: path, orderStatus: orderStatus });
        return $http({
            method: 'POST',
            url: '/ip_viewer?',
            data: action,
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
                "X-Requested-With": "XMLHttpRequest"
            }
        }).then(
            function (response) {
                return response;
            },
            function (err) {
                console.log('no gettree response ' + err);
            }
        );
    }

    return ftSvc;
}


text:
import * as admin from 'firebase-admin';

import { WeightHubPublisher } from "./WeightHubPublisher";
import { getFirebaseConfig } from "../firebase";
import { FirebaseOptions } from '../WeightHubConfig';
import quantize from '../quantize';
import { Weight, ActionTarget } from '../WeightHub';

export class FirebasePublisher implements WeightHubPublisher {

    private weightHubPath: string;
    private firebase: admin.app.App;
    private weightHubRef: admin.database.Reference;

    constructor(weightHubPath: string, connection?: FirebaseOptions) {
        this.weightHubPath = weightHubPath;
        const config = getFirebaseConfig(connection)
        this.firebase = admin.initializeApp(config, 'weightHub');
        this.weightHubRef = this.firebase.database().ref(this.weightHubPath);
    }

    async updateWeight(id: string, current: number, percent: number): Promise<boolean> {
        try {
            await this.weightHubRef.child(id).update({ current, percent });
            return true;
        } catch (reason) {
            console.error(`Firebase - Failed to update weight '${id}': ${reason}`);
            return false;
        }
    }

    async createWeight(id: string, current: number): Promise<boolean> {
        const weightRef = this.weightHubRef.child(id);
        try {
            await weightRef.update({ id, current: quantize(current) });
            return true;
        } catch (reason) {
            console.error(`Firebase - Failed to create weight '${id}': ${reason}`)
            return false;
        }
    }

    async getWeight(id: string): Promise<Weight> {
        const snapshot = await this.weightHubRef.child(id).once('value');
        return snapshot.val();
    }

    async set(id: string, field: ActionTarget, value: number): Promise<boolean> {
        try {
            await this.weightHubRef.child(id).update({ [field]: value });
            return true;
        } catch (reason) {
            console.error(`Firebase - Failed to update '${field}' of '${id}'.`);
            return false;
        }
    }

}


text:
import { FieldStore } from '../stores';
import { ReactComponent } from '../types';
import { IWithStoreParamProps, createWithStore, withFieldsRegistered, withParentStore } from '../wrappers';
import { observer } from 'mobx-react';
import { Component, ComponentClass } from 'react';
import * as React from 'react';

export interface IWrappedFieldProps {
  field: FieldStore;
  name?: string;
}

function generateClass<Props>(
  FieldComponent: ReactComponent<Props & IWrappedFieldProps> | string
) {
  if (typeof FieldComponent !== 'string') {
    const WrappedComponent = observer(FieldComponent as ComponentClass<Props & IWrappedFieldProps>);

    return class extends Component<Props & IWithStoreParamProps<FieldStore>, {}> {
      public render() {
        const { __formobx } = this.props; // tslint:disable-line:variable-name
        const props = {
          field: __formobx.store,
          ...this.props as any
        };
        delete props.__formobx;

        return <WrappedComponent {...props} />;
      }
    };
  } else if (FieldComponent === 'input') {
    return class extends Component<Props & IWithStoreParamProps<FieldStore>, {}> {
      public render() {
        const { __formobx } = this.props; // tslint:disable-line:variable-name
        const props = {
          ...__formobx.store.asProps,
          ...this.props as any
        };
        delete props.__formobx;

        return <input {...props} />;
      }
    };
  } else {
    throw new Error(`Unsupported string component type '${FieldComponent}'`);
  }
}

export function field<Props>(
  FieldComponent: ReactComponent<Props & IWrappedFieldProps> | string
) {
  const FormobxField = generateClass(FieldComponent);
  return withParentStore(withFieldsRegistered(createWithStore(FieldStore)(FormobxField)));
}


text:
EXIF manipulation library for PHP 5.3.

##Requirements##

The EXIF library has the following requirements:

 - PHP 5.3+


text:
package org.omni.core.interceptor;

import org.omni.bean.BeanFactoryManager;
import org.omni.commons.log.LogCenter;
import org.omni.core.EventContext;
import org.omni.security.ISecurityManager;
import org.slf4j.Logger;

public abstract class AbstractInterceptor implements FrameworkInterceptor {
	protected ISecurityManager sm;

	protected Logger logger = LogCenter.getLogger(getClass());

	//数字越小优先级越高
	private int priority = 5;

	public AbstractInterceptor() {
		sm = (ISecurityManager) BeanFactoryManager.instance().currentBeanFactory().getBean(ISecurityManager.class);
	}

	public int getPriority() {
		return priority;
	}

	public void setPriority(int priority) {
		this.priority = priority;
	}

	public abstract void preRequest(EventContext context);

	public abstract void postRequest(EventContext context);

}


text:
"""MessageRouter is responsible to create the actor to handle event."""

# standard library imports

# third party related imports

# local library imports
from mobile_push.actors.create_apns_token import CreateApnsTokenActor
from mobile_push.actors.create_gcm_token import CreateGcmTokenActor
from mobile_push.actors.create_topic import CreateTopicActor
from mobile_push.actors.direct_publish import DirectPublishActor
from mobile_push.actors.publish_to_topic import PublishToTopicActor
from mobile_push.actors.subscribe_topic import SubscribeTopicActor
from mobile_push.actors.unsubscribe_topic import UnsubscribeTopicActor

class MessageRouter(object):

    class BaseError(Exception):
        """Base exception class."""

    class ActionError(BaseError):
        """Raises when it is an unrecognizable action."""

    TABLE = {
        'create_topic': CreateTopicActor,
        'create_apns_token': CreateApnsTokenActor,
        'create_gcm_token': CreateGcmTokenActor,
        'subscribe_topic': SubscribeTopicActor,
        'unsubscribe_topic': UnsubscribeTopicActor,
        'publish_to_topic': PublishToTopicActor,
        'direct_publish': DirectPublishActor,
    }

    def __init__(self, message):

        self.message = message

    def get_actor(self):

        action = self.message.get('action')
        factory_cls = self.TABLE.get(action)

        if factory_cls is None:
            raise self.ActionError('Unknown action: %(action)s' % locals())

        return factory_cls()


text:
package lib

import (
	"io"
	"net/url"
)

// ImageSave retrieves one or more images from the docker host as a io.ReadCloser.
// It's up to the caller to store the images and close the stream.
func (cli *Client) ImageSave(imageIDs []string) (io.ReadCloser, error) {
	query := url.Values{
		"names": imageIDs,
	}

	resp, err := cli.get("/images/get", query, nil)
	if err != nil {
		return nil, err
	}
	return resp.body, nil
}


text:
'use strict';

var Home = require('./Home');

// ==============================
// CONCRETE HOME
// ==============================

var House = function () {};
House.prototype = Object.create(Home.prototype);
House.prototype.constructor = House;

House.prototype.foundations = function () {
    return "House foundations\n";
};

House.prototype.walls = function () {
    return "House walls\n";
};

House.prototype.roof = function () {
    return "House roof\n";
};

module.exports = House;


text:
package net.automatalib.incremental.mealy.dag;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Queue;

import net.automatalib.automata.concepts.InputAlphabetHolder;
import net.automatalib.automata.concepts.StateIDs;
import net.automatalib.automata.transducers.MealyMachine;
import net.automatalib.commons.util.IntDisjointSets;
import net.automatalib.commons.util.UnionFind;
import net.automatalib.incremental.ConflictException;
import net.automatalib.incremental.mealy.AbstractGraphView;
import net.automatalib.incremental.mealy.IncrementalMealyBuilder;
import net.automatalib.ts.output.MealyTransitionSystem;
import net.automatalib.visualization.VisualizationHelper;
import net.automatalib.visualization.helper.DelegateVisualizationHelper;
import net.automatalib.words.Alphabet;
import net.automatalib.words.Word;
import net.automatalib.words.WordBuilder;
import net.automatalib.words.impl.Alphabets;
import org.checkerframework.checker.nullness.qual.Nullable;

/**
 * Incrementally builds an (acyclic) Mealy machine, from a set of input and corresponding output words.
 *
 * @param <I>
 *         input symbol class
 * @param <O>
 *         output symbol class
 *
 * @author Malte Isberner
 */
public class IncrementalMealyDAGBuilder<I, O> implements IncrementalMealyBuilder<I, O>, InputAlphabetHolder<I> {

    private final Map<@Nullable StateSignature<O>, State<O>> register = new HashMap<>();
    private final Alphabet<I> inputAlphabet;
    private int alphabetSize;
    private final State<O> init;

    /**
     * Constructor.
     *
     * @param inputAlphabet
     *         the input alphabet to use
     */
    public IncrementalMealyDAGBuilder(Alphabet<I> inputAlphabet) {
        this.inputAlphabet = inputAlphabet;
        this.alphabetSize = inputAlphabet.size();
        StateSignature<O> initSig = new StateSignature<>(alphabetSize);
        this.init = new State<>(initSig);
        register.put(null, init);
    }

    @Override
    public void addAlphabetSymbol(I symbol) {
        if (!this.inputAlphabet.containsSymbol(symbol)) {
            Alphabets.toGrowingAlphabetOrThrowException(this.inputAlphabet).addSymbol(symbol);
        }

        final int newAlphabetSize = this.inputAlphabet.size();
        // even if the symbol was already in the alphabet, we need to make sure to be able to store the new symbol
        if (alphabetSize < newAlphabetSize) {
            register.values().forEach(n -> n.ensureInputCapacity(newAlphabetSize));
            alphabetSize = newAlphabetSize;
        }
    }

    @Override
    public boolean hasDefinitiveInformation(Word<? extends I> word) {
        return getState(word) != null;
    }

    /**
     * Retrieves the (internal) state reached by the given input word, or {@code null} if no information about the input
     * word is present.
     *
     * @param word
     *         the input word
     *
     * @return the corresponding state
     */
    private State<O> getState(Word<? extends I> word) {
        State<O> s = init;

        for (I sym : word) {
            int idx = inputAlphabet.getSymbolIndex(sym);
            s = s.getSuccessor(idx);
            if (s == null) {
                break;
            }
        }
        return s;
    }

    @Override
    public boolean lookup(Word<? extends I> word, List<? super O> output) {
        State<O> curr = init;
        for (I sym : word) {
            int idx = inputAlphabet.getSymbolIndex(sym);
            State<O> succ = curr.getSuccessor(idx);
            if (succ == null) {
                return false;
            }
            output.add(curr.getOutput(idx));
            curr = succ;
        }

        return true;
    }

    @Override
    public void insert(Word<? extends I> word, Word<? extends O> outputWord) {
        State<O> curr = init;
        State<O> conf = null;

        Deque<PathElem<O>> path = new ArrayDeque<>();

        // Find the internal state in the automaton that can be reached by a
        // maximal prefix of the word (i.e., a path of secured information)
        Iterator<? extends O> outWordIterator = outputWord.iterator();
        for (I sym : word) {
            // During this, store the *first* confluence state (i.e., state with multiple incoming edges).
            if (conf == null && curr.isConfluence()) {
                conf = curr;
            }

            int idx = inputAlphabet.getSymbolIndex(sym);
            State<O> succ = curr.getSuccessor(idx);
            if (succ == null) {
                break;
            }

            // If a transition exists for the input symbol, it also has an output symbol.
            // Check if this matches the provided one, otherwise there is a conflict
            O outSym = outWordIterator.next();
            if (!Objects.equals(outSym, curr.getOutput(idx))) {
                throw new ConflictException(
                        "Error inserting " + word.prefix(path.size() + 1) + " / " + outputWord.prefix(path.size() + 1) +
                        ": Incompatible output symbols: " + outSym + " vs " + curr.getOutput(idx));
            }
            path.push(new PathElem<>(curr, idx));
            curr = succ;
        }

        int len = word.length();
        int prefixLen = path.size();

        // The information was already present - we do not need to continue
        if (prefixLen == len) {
            return;
        }

        State<O> last = curr;

        if (conf != null) {
            if (conf == last) {
                conf = null;
            }
            last = hiddenClone(last);
            if (conf == null) {
                PathElem<O> peek = path.peek();
                assert peek != null;
                State<O> prev = peek.state;
                if (prev != init) {
                    updateSignature(prev, peek.transIdx, last);
                } else {
                    updateInitSignature(peek.transIdx, last);
                }
            }
        } else if (last != init) {
            hide(last);
        }

        // We then create a suffix path, i.e., a linear sequence of states corresponding to
        // the suffix (more precisely: the suffix minus the first symbol, since this is the
        // transition which is used for gluing the suffix path to the existing automaton).
        Word<? extends I> suffix = word.subWord(prefixLen);
        Word<? extends O> suffixOut = outputWord.subWord(prefixLen);

        // Here we prepare the "gluing" transition
        I sym = suffix.firstSymbol();
        int suffTransIdx = inputAlphabet.getSymbolIndex(sym);
        O suffTransOut = suffixOut.firstSymbol();

        State<O> suffixState = createSuffix(suffix.subWord(1), suffixOut.subWord(1));

        if (last != init) {
            last = unhide(last, suffTransIdx, suffixState, suffTransOut);

            // the suffixState may be part of our current path and become confluent due to un-hiding
            if (suffixState.isConfluence()) {
                // update the reference with whatever state comes first
                final Iterator<PathElem<O>> iter = path.descendingIterator();
                while (iter.hasNext()) {
                    final State<O> s = iter.next().state;
                    if (s == conf || s == suffixState) {
                        conf = s;
                        break;
                    }
                }
            }
        } else {
            updateInitSignature(suffTransIdx, suffixState, suffTransOut);
        }

        if (path.isEmpty()) {
            return;
        }

        if (conf != null) {
            // If there was a confluence state, we have to clone all nodes on
            // the prefix path up to this state, in order to separate it from other
            // prefixes reaching the confluence state (we do not know anything about them plus the suffix).
            PathElem<O> next;
            do {
                next = path.pop();
                State<O> state = next.state;
                int idx = next.transIdx;
                state = clone(state, idx, last);
                last = state;
            } while (next.state != conf);
        }

        // Finally, we have to refresh all the signatures, iterating backwards until the updating becomes stable.
        while (path.size() > 1) {
            PathElem<O> next = path.pop();
            State<O> state = next.state;
            int idx = next.transIdx;

            // when extending the path we previously traversed (i.e. expanding the suffix), it may happen that we end up
            // adding a cyclic transition. If this is the case, simply clone the current state and update the parent in
            // the next iteration
            if (state == last) {
                last = clone(state, idx, last);
                continue;
            }

            State<O> updated = updateSignature(state, idx, last);
            if (state == updated) {
                return;
            }
            last = updated;
        }

        int finalIdx = path.pop().transIdx;

        updateInitSignature(finalIdx, last);
    }

    private State<O> hiddenClone(State<O> other) {
        StateSignature<O> sig = other.getSignature().duplicate();

        for (int i = 0; i < alphabetSize; i++) {
            State<O> succ = sig.successors.array[i];
            if (succ != null) {
                succ.increaseIncoming();
            }
        }
        return new State<>(sig);
    }

    /**
     * Update the signature of a state, changing only the successor state of a single transition index.
     *
     * @param state
     *         the state which's signature to update
     * @param idx
     *         the transition index to modify
     * @param succ
     *         the new successor state
     *
     * @return the resulting state, which can either be the same as the input state (if the new signature is unique), or
     * the result of merging with another state.
     */
    private State<O> updateSignature(State<O> state, int idx, State<O> succ) {
        StateSignature<O> sig = state.getSignature();
        if (sig.successors.array[idx] == succ) {
            return state;
        }

        register.remove(sig);
        if (sig.successors.array[idx] != null) {
            sig.successors.array[idx].decreaseIncoming();
        }
        sig.successors.array[idx] = succ;
        succ.increaseIncoming();
        sig.updateHashCode();
        return replaceOrRegister(state);
    }

    /**
     * Update the signature of the initial state. This requires special handling, as the initial state is not stored in
     * the register (since it can never legally act as a predecessor).
     *
     * @param idx
     *         the transition index being changed
     * @param succ
     *         the new successor state
     */
    private void updateInitSignature(int idx, State<O> succ) {
        StateSignature<O> sig = init.getSignature();
        State<O> oldSucc = sig.successors.array[idx];
        if (oldSucc == succ) {
            return;
        }
        if (oldSucc != null) {
            oldSucc.decreaseIncoming();
        }
        sig.successors.array[idx] = succ;
        succ.increaseIncoming();
    }

    /**
     * Updates the signature of the initial state, changing both the successor state and the output symbol.
     *
     * @param idx
     *         the transition index to change
     * @param succ
     *         the new successor state
     * @param out
     *         the output symbol
     */
    private void updateInitSignature(int idx, State<O> succ, O out) {
        StateSignature<O> sig = init.getSignature();
        State<O> oldSucc = sig.successors.array[idx];
        if (oldSucc == succ && Objects.equals(out, sig.outputs.array[idx])) {
            return;
        }
        if (oldSucc != null) {
            oldSucc.decreaseIncoming();
        }
        sig.successors.array[idx] = succ;
        sig.outputs.array[idx] = out;
        succ.increaseIncoming();
    }

    private void hide(State<O> state) {
        assert state != init;
        StateSignature<O> sig = state.getSignature();

        register.remove(sig);
    }

    private State<O> createSuffix(Word<? extends I> suffix, Word<? extends O> suffixOut) {
        StateSignature<O> sig = new StateSignature<>(alphabetSize);
        sig.updateHashCode();
        State<O> last = replaceOrRegister(sig);

        int len = suffix.length();
        for (int i = len - 1; i >= 0; i--) {
            sig = new StateSignature<>(alphabetSize);
            I sym = suffix.getSymbol(i);
            O outsym = suffixOut.getSymbol(i);
            int idx = inputAlphabet.getSymbolIndex(sym);
            sig.successors.array[idx] = last;
            sig.outputs.array[idx] = outsym;
            sig.updateHashCode();
            last = replaceOrRegister(sig);
        }

        return last;
    }

    private State<O> unhide(State<O> state, int idx, State<O> succ, O out) {
        StateSignature<O> sig = state.getSignature();
        State<O> prevSucc = sig.successors.array[idx];
        if (prevSucc != null) {
            prevSucc.decreaseIncoming();
        }
        sig.successors.array[idx] = succ;
        if (succ != null) {
            succ.increaseIncoming();
        }
        sig.outputs.array[idx] = out;
        sig.updateHashCode();
        return replaceOrRegister(state);
    }

    private State<O> clone(State<O> other, int idx, State<O> succ) {
        StateSignature<O> sig = other.getSignature();
        if (sig.successors.array[idx] == succ) {
            return other;
        }
        sig = sig.duplicate();
        sig.successors.array[idx] = succ;
        sig.updateHashCode();
        return replaceOrRegister(sig);
    }

    private State<O> replaceOrRegister(State<O> state) {
        StateSignature<O> sig = state.getSignature();
        State<O> other = register.get(sig);
        if (other != null) {
            if (state != other) {
                for (int i = 0; i < sig.successors.array.length; i++) {
                    State<O> succ = sig.successors.array[i];
                    if (succ != null) {
                        succ.decreaseIncoming();
                    }
                }
            }
            return other;
        }

        register.put(sig, state);
        return state;
    }

    private State<O> replaceOrRegister(StateSignature<O> sig) {
        State<O> state = register.get(sig);
        if (state != null) {
            return state;
        }

        state = new State<>(sig);
        register.put(sig, state);
        for (int i = 0; i < sig.successors.array.length; i++) {
            State<O> succ = sig.successors.array[i];
            if (succ != null) {
                succ.increaseIncoming();
            }
        }
        return state;
    }

    @Override
    public GraphView asGraph() {
        return new GraphView();
    }

    @Override
    public AutomatonView asTransitionSystem() {
        return new AutomatonView();
    }

    @Override
    public @Nullable Word<I> findSeparatingWord(MealyMachine<?, I, ?, O> target,
                                                Collection<? extends I> inputs,
                                                boolean omitUndefined) {
        return doFindSeparatingWord(target, inputs, omitUndefined);
    }

    private <S, T> @Nullable Word<I> doFindSeparatingWord(MealyMachine<S, I, T, O> mealy,
                                                          Collection<? extends I> inputs,
                                                          boolean omitUndefined) {
        S init2 = mealy.getInitialState();

        if (init2 == null) {
            return omitUndefined ? null : Word.epsilon();
        }

        State<O> init1 = init;

        Map<State<O>, Integer> ids = new HashMap<>();
        StateIDs<S> mealyIds = mealy.stateIDs();

        int thisStates = register.size();
        int id1 = getStateId(init1, ids), id2 = mealyIds.getStateId(init2) + thisStates;

        IntDisjointSets uf = new UnionFind(thisStates + mealy.size());
        uf.link(id1, id2);

        Queue<Record<S, I, O>> queue = new ArrayDeque<>();

        queue.offer(new Record<>(init1, init2));

        I lastSym = null;

        Record<S, I, O> current;

        explore:
        while ((current = queue.poll()) != null) {
            State<O> state1 = current.state1;
            S state2 = current.state2;

            for (I sym : inputs) {
                int idx = inputAlphabet.getSymbolIndex(sym);
                State<O> succ1 = state1.getSuccessor(idx);
                if (succ1 == null) {
                    continue;
                }

                T trans2 = mealy.getTransition(state2, sym);
                if (trans2 == null) {
                    if (omitUndefined) {
                        continue;
                    }
                    lastSym = sym;
                    break explore;
                }

                Object out1 = state1.getOutput(idx);
                Object out2 = mealy.getTransitionOutput(trans2);
                if (!Objects.equals(out1, out2)) {
                    lastSym = sym;
                    break explore;
                }

                S succ2 = mealy.getSuccessor(trans2);

                id1 = getStateId(succ1, ids);
                id2 = mealyIds.getStateId(succ2) + thisStates;

                int r1 = uf.find(id1), r2 = uf.find(id2);

                if (r1 == r2) {
                    continue;
                }

                uf.link(r1, r2);

                queue.offer(new Record<>(succ1, succ2, current, sym));
            }
        }

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

        int ceLength = current.depth;
        if (lastSym != null) {
            ceLength++;
        }

        @SuppressWarnings("nullness") // we make sure to set each index to a value of type I
        WordBuilder<I> wb = new WordBuilder<>(null, ceLength);

        int index = ceLength;

        if (lastSym != null) {
            wb.setSymbol(--index, lastSym);
        }

        while (current.reachedFrom != null) {
            final I reachedVia = current.reachedVia;
            wb.setSymbol(--index, reachedVia);
            current = current.reachedFrom;
        }

        return wb.toWord();
    }

    private static <O> int getStateId(State<O> state, Map<State<O>, Integer> ids) {
        return ids.computeIfAbsent(state, k -> ids.size());
    }

    @Override
    public Alphabet<I> getInputAlphabet() {
        return inputAlphabet;
    }

    // /////////////////////////////////////////////////////////////////////
    // Equivalence test //
    // /////////////////////////////////////////////////////////////////////

    private static final class Record<S, I, O> {

        private final State<O> state1;
        private final S state2;
        private final I reachedVia;
        private final @Nullable Record<S, I, O> reachedFrom;
        private final int depth;

        @SuppressWarnings("nullness") // we will only access reachedVia after checking reachedFrom for null
        Record(State<O> state1, S state2) {
            this.state1 = state1;
            this.state2 = state2;
            this.reachedFrom = null;
            this.reachedVia = null;
            this.depth = 0;
        }

        Record(State<O> state1, S state2, Record<S, I, O> reachedFrom, I reachedVia) {
            this.state1 = state1;
            this.state2 = state2;
            this.reachedFrom = reachedFrom;
            this.reachedVia = reachedVia;
            this.depth = reachedFrom.depth + 1;
        }
    }

    public class GraphView extends AbstractGraphView<I, O, State<O>, TransitionRecord<O>> {

        @Override
        public Collection<TransitionRecord<O>> getOutgoingEdges(State<O> node) {
            List<TransitionRecord<O>> edges = new ArrayList<>(alphabetSize);
            for (int i = 0; i < alphabetSize; i++) {
                if (node.getSuccessor(i) != null) {
                    edges.add(new TransitionRecord<>(node, i));
                }
            }
            return edges;
        }

        @Override
        public State<O> getTarget(TransitionRecord<O> edge) {
            return edge.source.getSuccessor(edge.transIdx);
        }

        @Override
        public Collection<State<O>> getNodes() {
            return Collections.unmodifiableCollection(register.values());
        }

        @Override
        public I getInputSymbol(TransitionRecord<O> edge) {
            return inputAlphabet.getSymbol(edge.transIdx);
        }

        @Override
        public O getOutputSymbol(TransitionRecord<O> edge) {
            return edge.source.getOutput(edge.transIdx);
        }

        @Override
        public State<O> getInitialNode() {
            return init;
        }

        @Override
        public VisualizationHelper<State<O>, TransitionRecord<O>> getVisualizationHelper() {
            return new DelegateVisualizationHelper<State<O>, TransitionRecord<O>>(super.getVisualizationHelper()) {

                private int id;

                @Override
                public boolean getNodeProperties(State<O> node, Map<String, String> properties) {
                    if (!super.getNodeProperties(node, properties)) {
                        return false;
                    }
                    properties.put(NodeAttrs.LABEL, "n" + (id++));
                    if (node.isConfluence()) {
                        properties.put(NodeAttrs.SHAPE, NodeShapes.OCTAGON);
                    }
                    return true;
                }

            };
        }

    }

    public class AutomatonView implements MealyTransitionSystem<State<O>, I, TransitionRecord<O>, O> {

        @Override
        public State<O> getSuccessor(TransitionRecord<O> transition) {
            State<O> src = transition.source;
            return src.getSuccessor(transition.transIdx);
        }

        @Override
        public State<O> getInitialState() {
            return init;
        }

        @Override
        public @Nullable TransitionRecord<O> getTransition(State<O> state, I input) {
            int inputIdx = inputAlphabet.getSymbolIndex(input);
            if (state.getSuccessor(inputIdx) == null) {
                return null;
            }
            return new TransitionRecord<>(state, inputIdx);
        }

        @Override
        public O getTransitionOutput(TransitionRecord<O> transition) {
            State<O> src = transition.source;
            return src.getOutput(transition.transIdx);
        }
    }
}