text:
# ----------------------------------------------------------------------------------
#
# Copyright Microsoft Corporation
# Licensed 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.
# ----------------------------------------------------------------------------------

.".\Scaffolding.ps1"

function Get-Address
{
    param([array] $lines)
    Write-Log $lines
    foreach ($hardline in $lines)
    {
         Write-Log $hardline
        if ($hardline.indexOf('http:') -gt 0)
        {
            $outputlines = $hardline.split("`r`n")
            Write-Log $outputlines
            foreach($line in $outputlines)
            {
                Write-Log $line
                $start = $line.indexOf('http://')
                if ($start -gt 0)
                {
                   return ($line.substring($start))
                }
            }
        }
    }

    throw "Unable to determine service address"
}

function Test-NodeHelloInEmulator
{
    Stop-AzureEmulator
    $loc = Get-Location
    Create-NodeBaseService "myNodeService"
    try
    {
	    $info = Start-AzureEmulator
        Write-Log "Emulator output: $info"
        $address = Get-Address $info
        Write-Log "Using service address '$address'"
	    Dump-Document $address
    }
    finally
    {
	    Set-Location $loc
	    Stop-AzureEmulator
	    rm -Recurse ".\myNodeService"
    }
}

function Test-PHPHelloInEmulator
{
    Stop-AzureEmulator
    $loc = Get-Location
    Create-PHPWebService "myPHPService"
    try
    {
	    $info = Start-AzureEmulator
        Write-Log "Emulator output: $info"
        $address = Get-Address $info
        Write-Log "Using service address '$address'"
	    Dump-Document $address
    }
    finally
    {
	    Set-Location $loc
	    Stop-AzureEmulator
	    rm -Recurse ".\myPHPService"
    }
}

function Test-NodeServiceCreation
{
    $loc = Get-Location
    Create-NodeBaseService "myNodeService01"
	Set-Location $loc
    rm -Recurse ".\myNodeService01"
}

function Test-PHPServiceCreation
{
    $loc = Get-Location
    Create-PHPBaseService "myPHPService01"
	Set-Location $loc
	rm -Recurse ".\myPHPService01"
}


text:
package org.opencb.opencga.storage.benchmark.variant.generators;

import org.opencb.opencga.storage.benchmark.variant.queries.RandomQueries;

import java.util.Map;

/**
 * Created by wasim on 01/11/18.
 */
public abstract class ConfiguredQueryGenerator extends QueryGenerator {

    public void setUp(Map<String, String> params) {
        super.setUp(params);
    }

    public abstract void setUp(Map<String, String> params, RandomQueries configuration);

}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace RiakClientFunctionalTest\Command\Kv;

/**
 * @group proto
 * @group functional
 */
class RiakIndexProtoTest extends RiakIndexTest
{
    /**
     * {@inheritdoc}
     */
    protected function createClient()
    {
        return $this->createRiakProtoClient();
    }
}


text:
package org.apache.amber.oauth2.common.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;

import org.apache.amber.oauth2.common.OAuth;
import org.apache.amber.oauth2.common.error.OAuthError;
import org.apache.amber.oauth2.common.exception.OAuthProblemException;
import org.apache.amber.oauth2.common.exception.OAuthSystemException;

/**
 * Common OAuth Utils class.
 *

 * Some methods based on the Utils class from OAuth V1.0a library available at:
 * http://oauth.googlecode.com/svn/code/java/core/
 *
 * @author Maciej Machulak (m.p.machulak@ncl.ac.uk)
 * @author Lukasz Moren (lukasz.moren@ncl.ac.uk)
 * @author Aad van Moorsel (aad.vanmoorsel@ncl.ac.uk)
 */
public final class OAuthUtils {

    private static final String ENCODING = "UTF-8";
    private static final String PARAMETER_SEPARATOR = "&";
    private static final String NAME_VALUE_SEPARATOR = "=";

    public static final String AUTH_SCHEME = "OAuth";

    private static final Pattern OAUTH_HEADER = Pattern.compile("\\s*(\\w*)\\s+(.*)");
    private static final Pattern NVP = Pattern.compile("(\\S*)\\s*\\=\\s*\"([^\"]*)\"");

    public static final String MULTIPART = "multipart/";

    private static final String DEFAULT_CONTENT_CHARSET = ENCODING;

    /**
     * Translates parameters into application/x-www-form-urlencoded String
     *
     * @param parameters parameters to encode
     * @param encoding   The name of a supported
     *                   character
     *                   encoding.
     * @return Translated string
     */
    public static String format(
        final Collection<? extends Map.Entry<String, String>> parameters,
        final String encoding) {
        final StringBuilder result = new StringBuilder();
        for (final Map.Entry<String, String> parameter : parameters) {
            if (!OAuthUtils.isEmpty(parameter.getKey())
                && !OAuthUtils.isEmpty(parameter.getValue())) {
                final String encodedName = encode(parameter.getKey(), encoding);
                final String value = parameter.getValue();
                final String encodedValue = value != null ? encode(value, encoding) : "";
                if (result.length() > 0) {
                    result.append(PARAMETER_SEPARATOR);
                }
                result.append(encodedName);
                result.append(NAME_VALUE_SEPARATOR);
                result.append(encodedValue);
            }
        }
        return result.toString();
    }

    private static String encode(final String content, final String encoding) {
        try {
            return URLEncoder.encode(content,
                encoding != null ? encoding : "UTF-8");
        } catch (UnsupportedEncodingException problem) {
            throw new IllegalArgumentException(problem);
        }
    }

    /**
     * Read data from Input Stream and save it as a String.
     *
     * @param is InputStream to be read
     * @return String that was read from the stream
     */
    public static String saveStreamAsString(InputStream is) throws IOException {
        return toString(is, ENCODING);
    }

    /**
     * Get the entity content as a String, using the provided default character set
     * if none is found in the entity.
     * If defaultCharset is null, the default "UTF-8" is used.
     *
     * @param is             input stream to be saved as string
     * @param defaultCharset character set to be applied if none found in the entity
     * @return the entity content as a String
     * @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE
     * @throws IOException              if an error occurs reading the input stream
     */
    public static String toString(
        final InputStream is, final String defaultCharset) throws IOException {
        if (is == null) {
            throw new IllegalArgumentException("InputStream may not be null");
        }

        String charset = defaultCharset;
        if (charset == null) {
            charset = DEFAULT_CONTENT_CHARSET;
        }
        Reader reader = new InputStreamReader(is, charset);
        StringBuilder sb = new StringBuilder();
        int l;
        try {
            char[] tmp = new char[4096];
            while ((l = reader.read(tmp)) != -1) {
                sb.append(tmp, 0, l);
            }
        } finally {
            reader.close();
        }
        return sb.toString();
    }

    /**
     * Creates invalid_request exception with given message
     *
     * @param message error message
     * @return OAuthException
     */
    public static OAuthProblemException handleOAuthProblemException(String message) {
        return OAuthProblemException.error(OAuthError.TokenResponse.INVALID_REQUEST)
            .description(message);
    }

    /**
     * Creates OAuthProblemException that contains set of missing oauth parameters
     *
     * @param missingParams missing oauth parameters
     * @return OAuthProblemException with user friendly message about missing oauth parameters
     */

    public static OAuthProblemException handleMissingParameters(Set<String> missingParams) {
        StringBuffer sb = new StringBuffer("Missing parameters: ");
        if (!OAuthUtils.isEmpty(missingParams)) {
            for (String missingParam : missingParams) {
                sb.append(missingParam).append(" ");
            }
        }
        return handleOAuthProblemException(sb.toString().trim());
    }

    public static OAuthProblemException handleBadContentTypeException(String expectedContentType) {
        StringBuilder errorMsg = new StringBuilder("Bad request content type. Expecting: ").append(
            expectedContentType);
        return handleOAuthProblemException(errorMsg.toString());
    }

    public static OAuthProblemException handleNotAllowedParametersOAuthException(
        List<String> notAllowedParams) {
        StringBuffer sb = new StringBuffer("Not allowed parameters: ");
        if (notAllowedParams != null) {
            for (String notAllowed : notAllowedParams) {
                sb.append(notAllowed).append(" ");
            }
        }
        return handleOAuthProblemException(sb.toString().trim());
    }

    /**
     * Parse a form-urlencoded document.
     */
    public static Map<String, String> decodeForm(String form) {
        Map<String, String> params = new HashMap<String, String>();
        if (!OAuthUtils.isEmpty(form)) {
            for (String nvp : form.split("\\&")) {
                int equals = nvp.indexOf('=');
                String name;
                String value;
                if (equals < 0) {
                    name = decodePercent(nvp);
                    value = null;
                } else {
                    name = decodePercent(nvp.substring(0, equals));
                    value = decodePercent(nvp.substring(equals + 1));
                }
                params.put(name, value);
            }
        }
        return params;
    }

    /**
     * Return true if the given Content-Type header means FORM_ENCODED.
     */
    public static boolean isFormEncoded(String contentType) {
        if (contentType == null) {
            return false;
        }
        int semi = contentType.indexOf(";");
        if (semi >= 0) {
            contentType = contentType.substring(0, semi);
        }
        return OAuth.ContentType.URL_ENCODED.equalsIgnoreCase(contentType.trim());
    }

    public static String decodePercent(String s) {
        try {
            return URLDecoder.decode(s, ENCODING);
            // This implements http://oauth.pbwiki.com/FlexibleDecoding
        } catch (java.io.UnsupportedEncodingException wow) {
            throw new RuntimeException(wow.getMessage(), wow);
        }
    }

    /**
     * Construct a &-separated list of the given values, percentEncoded.
     */
    public static String percentEncode(Iterable values) {
        StringBuilder p = new StringBuilder();
        for (Object v : values) {
            String stringValue = toString(v);
            if (!isEmpty(stringValue)) {
                if (p.length() > 0) {
                    p.append("&");
                }
                p.append(OAuthUtils.percentEncode(toString(v)));
            }
        }
        return p.toString();
    }

    public static String percentEncode(String s) {
        if (s == null) {
            return "";
        }
        try {
            return URLEncoder.encode(s, ENCODING)
                // OAuth encodes some characters differently:
                .replace("+", "%20").replace("*", "%2A")
                .replace("%7E", "~");
            // This could be done faster with more hand-crafted code.
        } catch (UnsupportedEncodingException wow) {
            throw new RuntimeException(wow.getMessage(), wow);
        }
    }

    private static final String toString(Object from) {
        return (from == null) ? null : from.toString();
    }

    private static boolean isEmpty(Set<String> missingParams) {
        if (missingParams == null || missingParams.size() == 0) {
            return true;
        }
        return false;
    }

    public static Object instantiateClass(Class clazz) throws OAuthSystemException {
        try {
            return (Object)clazz.newInstance();
        } catch (Exception e) {
            throw new OAuthSystemException(e);
        }
    }

    public static Object instantiateClassWithParameters(Class clazz, Class[] paramsTypes,
                                                        Object[] paramValues) throws OAuthSystemException {

        try {
            if (paramsTypes != null && paramValues != null) {
                if (!(paramsTypes.length == paramValues.length)) {
                    throw new IllegalArgumentException("Number of types and values must be equal");
                }

                if (paramsTypes.length == 0 && paramValues.length == 0) {
                    return clazz.newInstance();
                }
                Constructor clazzConstructor = clazz.getConstructor(paramsTypes);
                return clazzConstructor.newInstance(paramValues);
            }
            return clazz.newInstance();

        } catch (NoSuchMethodException e) {
            throw new OAuthSystemException(e);
        } catch (InstantiationException e) {
            throw new OAuthSystemException(e);
        } catch (IllegalAccessException e) {
            throw new OAuthSystemException(e);
        } catch (InvocationTargetException e) {
            throw new OAuthSystemException(e);
        }

    }

    public static String getAuthHeaderField(String authHeader) {

        if (authHeader != null) {
            Matcher m = OAUTH_HEADER.matcher(authHeader);
            if (m.matches()) {
                if (AUTH_SCHEME.equalsIgnoreCase(m.group(1))) {
                    return m.group(2);
                }
            }
        }
        return null;
    }

    public static Map<String, String> decodeOAuthHeader(String header) {
        Map<String, String> headerValues = new HashMap<String, String>();
        if (header != null) {
            Matcher m = OAUTH_HEADER.matcher(header);
            if (m.matches()) {
                if (AUTH_SCHEME.equalsIgnoreCase(m.group(1))) {
                    for (String nvp : m.group(2).split("\\s*,\\s*")) {
                        m = NVP.matcher(nvp);
                        if (m.matches()) {
                            String name = decodePercent(m.group(1));
                            String value = decodePercent(m.group(2));
                            headerValues.put(name, value);
                        }
                    }
                }
            }
        }
        return headerValues;
    }

    // todo: implement method to decode header form (with no challenge)

    /**
     * Construct a WWW-Authenticate or Authorization header with the OAuth challenge/credentials
     */
    public static String encodeOAuthHeader(Map<String, String> entries) {
        StringBuffer sb = new StringBuffer();
        sb.append(OAuth.OAUTH_HEADER_NAME).append(" ");
        for (Map.Entry<String, String> entry : entries.entrySet()) {
            if (!OAuthUtils.isEmpty(entry.getKey()) && !OAuthUtils.isEmpty(entry.getValue())) {
                sb.append(entry.getKey());
                sb.append("=\"");
                sb.append(entry.getValue());
                sb.append("\",");
            }
        }

        return sb.substring(0, sb.length() - 1);
    }

    public static boolean isEmpty(String value) {
        return value == null || "".equals(value);
    }

    public static boolean hasEmptyValues(String[] array) {
        if (array == null || array.length == 0) {
            return true;
        }
        for (String s : array) {
            if (isEmpty(s)) {
                return true;
            }
        }
        return false;
    }

    public static String getAuthzMethod(String header) {
        if (header != null) {
            Matcher m = OAUTH_HEADER.matcher(header);
            if (m.matches()) {
                return m.group(1);

            }
        }
        return null;
    }

    public static Set<String> decodeScopes(String s) {
        Set<String> scopes = new HashSet<String>();
        if (!OAuthUtils.isEmpty(s)) {
            StringTokenizer tokenizer = new StringTokenizer(s, " ");

            while (tokenizer.hasMoreElements()) {
                scopes.add(tokenizer.nextToken());
            }
        }
        return scopes;

    }

    public static String encodeScopes(Set<String> s) {
        StringBuffer scopes = new StringBuffer();
        for (String scope : s) {
            scopes.append(scope).append(" ");
        }
        return scopes.toString().trim();

    }

    public static boolean isMultipart(HttpServletRequest request) {

        if (!"post".equals(request.getMethod().toLowerCase())) {
            return false;
        }
        String contentType = request.getContentType();
        if (contentType == null) {
            return false;
        }
        if (contentType.toLowerCase().startsWith(MULTIPART)) {
            return true;
        }
        return false;
    }

    public static boolean hasContentType(String requestContentType, String requiredContentType) {
        if (OAuthUtils.isEmpty(requiredContentType) || OAuthUtils.isEmpty(requestContentType)) {
            return false;
        }
        StringTokenizer tokenizer = new StringTokenizer(requestContentType, ";");
        while (tokenizer.hasMoreTokens()) {
            if (requiredContentType.equals(tokenizer.nextToken())) {
                return true;
            }
        }

        return false;
    }

}


text:
  {{ layout.container_start() }}

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
        Toggle navigation

      </button>
      Poor Floor Stamp Management System

      {% if not (current_user and current_user.is_authenticated()) %}

Login

      {% else %}

Change Password

            {% if current_user.has_role('admin') %}

Manage Users

            {% endif %}
            {% if current_user.has_role('superadmin') %}

Admin Console

            {% endif %}

      {% endif %}

  {{ layout.container_end() }}


text:
<?php
namespace UNL\UCBCN\Manager;

use UNL\UCBCN\Calendar;
use UNL\UCBCN\Permission;
use UNL\UCBCN\Calendar\Subscription;
use UNL\UCBCN\Calendar\SubscriptionHasCalendar;

class DeleteSubscription extends PostHandler
{
    public $options = array();
    public $calendar;
    public $subscription;

    public function __construct($options = array())
    {
        $this->options = $options + $this->options;
        $this->calendar = Calendar::getByShortname($this->options['calendar_shortname']);

        if ($this->calendar === FALSE) {
            throw new \Exception("That calendar could not be found.", 404);
        }

        $user = Auth::getCurrentUser();
        if (!$user->hasPermission(Permission::CALENDAR_EDIT_SUBSCRIPTIONS_ID, $this->calendar->id)) {
            throw new \Exception("You do not have permission to edit subscriptions on this calendar.", 403);
        }

        $this->subscription = Subscription::getByID($this->options['subscription_id']);

        if ($this->subscription === FALSE) {
            throw new \Exception("That subscription could not be found.", 404);
        }
    }

    public function handlePost(array $get, array $post, array $files)
    {
        if (!isset($post['subscription_id'])) {
            throw new \Exception("The subscription_id must be set in the post data", 400);
        }

        if ($post['subscription_id'] != $this->subscription->id) {
            throw new \Exception("The subscription_id in the post data must match the subscriptions_id in the URL", 400);
        }

        foreach($this->subscription->getSubscribedCalendars() as $calendar) {
            $record = SubscriptionHasCalendar::get($this->subscription->id, $calendar->id);
            $record->delete();
        }

        $this->subscription->delete();

        $this->flashNotice(parent::NOTICE_LEVEL_SUCCESS, 'Subscription Deleted', 'The subscription "' . $this->subscription->name . '" has been deleted.');
        //redirect
        return $this->calendar->getSubscriptionsURL();
    }
}


text:
<?php

namespace ctf0\SimpleMenu\Traits;

use Illuminate\Support\Arr;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

trait Routes
{
    protected $allRoutes = [];
    protected $listFileFound = true;

    public function createRoutes()
    {
        app('router')->group([
            'prefix' => LaravelLocalization::setLocale(),
            'middleware' => [
                'web',
                'localeSessionRedirect',
                'localizationRedirect',
            ],
        ], function () {
            $this->utilCheck();
        });
    }

    protected function utilCheck()
    {
        if (!app('files')->exists($this->listFileDir)) {
            $this->listFileFound = false;

            $this->utilLoop();
            $this->saveRoutesListToFile($this->allRoutes);
        } else {
            $this->utilLoop();
        }
    }

    /**
     * runs everytime you change the current local
     * so routes links gets dynamically changed without causing issues.
     *
     * @return [type] [description]
     */
    protected function utilLoop()
    {
        foreach ($this->cache->tags('sm')->get('pages') as $page) {
            // make route
            $this->routeGen($page);

            // create route list
            if (!$this->listFileFound) {
                $this->createRoutesList($page);
            }
        }
    }

    protected function routeGen($page)
    {
        if ($this->escapeEmptyRoute($page->url)) {
            return;
        }

        // route data
        $url = $page->url;
        $action = $page->action;
        $prefix = $page->prefix;
        $routeName = $page->route_name;

        // page data
        $title = $page->title;
        $body = $page->body;
        $desc = $page->desc;
        $meta = $page->meta;
        $cover = $page->cover;
        $template = $page->template;
        $breadCrumb = $page->getAncestors();

        // middlewares
        $middlewares = is_null($page->middlewares) ? null : preg_split('/[\s,]+/', $page->middlewares);
        $roles = empty($page->roles->pluck('name')->toArray()) ? null : 'role:' . implode(',', $page->roles->pluck('name')->toArray());
        $permissions = empty($page->permissions->pluck('name')->toArray()) ? null : 'perm:' . implode(',', $page->permissions->pluck('name')->toArray());

        // cache the page so we can pass the page params to the controller@method
        $compact = compact('template', 'title', 'body', 'desc', 'meta', 'cover', 'breadCrumb', 'middlewares', 'roles', 'permissions');

        $this->cache->tags('sm')->rememberForever($this->getCrntLocale() . "-$routeName", function () use ($compact) {
            return $compact;
        });

        $route = $this->getRouteUrl($url, $prefix);

        $uses = $action
            ? starts_with($action, '\\') ? $action : "\\$action"
            : '\ctf0\SimpleMenu\Controllers\DummyController@handle';

        $mds = array_filter(Arr::flatten([$middlewares, $roles, $permissions]));

        app('router')->get($route)
            ->uses($uses)
            ->name($routeName)
            ->middleware($mds);
    }

    protected function createRoutesList($page)
    {
        $routeName = $page->route_name;

        foreach ($this->AppLocales() as $code) {
            $url = $page->getTranslationWithoutFallback('url', $code);
            $prefix = $page->getTranslationWithoutFallback('prefix', $code);

            if ($this->escapeEmptyRoute($url)) {
                continue;
            }

            $route = $this->getRouteUrl($url, $prefix);

            $this->allRoutes[$routeName][$code] = $route;
        }
    }

    protected function escapeEmptyRoute($url)
    {
        return empty($url);
    }

    protected function getRouteUrl($url, $prefix)
    {
        if (empty($prefix)) {
            $clear = $url;
        } else {
            $clear = "$prefix/$url";
        }

        return $this->clearExtraSlash($clear);
    }

    protected function saveRoutesListToFile($routes)
    {
        $data = "<?php\n\nreturn " . var_export($routes, true) . ';';
        $data = $this->clearExtraSlash($data);

        // array(...) to [...]
        $data = str_replace('array (', '[', $data);
        $data = str_replace(')', ']', $data);
        $data = preg_replace('/=>\s+\[/', '=> [', $data);

        return app('files')->put($this->listFileDir, $data);
    }

    protected function clearExtraSlash($url)
    {
        return preg_replace('/\/+/', '/', $url);
    }
}


text:
var express = require('express');
var router = express.Router();

/* GET home page. */

router.post('/', function(req, res, next) {
    res.render('admin', { title: '管理员' });
});

module.exports = router;


text:
import React, {Component} from 'react'
import {connect} from 'react-redux'
import {withRouter} from 'react-router'
import _ from 'lodash'

// Components
import {Page} from '@influxdata/clockface'
import {ErrorHandling} from 'src/shared/decorators/errors'
import DashboardHeader from 'src/dashboards/components/DashboardHeader'
import DashboardComponent from 'src/dashboards/components/Dashboard'
import ManualRefresh from 'src/shared/components/ManualRefresh'
import {HoverTimeProvider} from 'src/dashboards/utils/hoverTime'
import VariablesControlBar from 'src/dashboards/components/variablesControlBar/VariablesControlBar'
import LimitChecker from 'src/cloud/components/LimitChecker'
import RateLimitAlert from 'src/cloud/components/RateLimitAlert'

// Actions
import * as dashboardActions from 'src/dashboards/actions'
import * as rangesActions from 'src/dashboards/actions/ranges'
import * as appActions from 'src/shared/actions/app'
import {setActiveTimeMachine} from 'src/timeMachine/actions'
import {
  setAutoRefreshInterval,
  setAutoRefreshStatus,
} from 'src/shared/actions/autoRefresh'

// Utils
import {GlobalAutoRefresher} from 'src/utils/AutoRefresher'
import {
  extractRateLimitResources,
  extractRateLimitStatus,
} from 'src/cloud/utils/limits'
import {pageTitleSuffixer} from 'src/shared/utils/pageTitles'

// Constants
import {AUTOREFRESH_DEFAULT} from 'src/shared/constants'
import {DEFAULT_TIME_RANGE} from 'src/shared/constants/timeRanges'

// Types
import {
  Links,
  Dashboard,
  Cell,
  View,
  TimeRange,
  AppState,
  AutoRefresh,
  AutoRefreshStatus,
  Organization,
} from 'src/types'
import {RemoteDataState} from 'src/types'
import {WithRouterProps} from 'react-router'
import {ManualRefreshProps} from 'src/shared/components/ManualRefresh'
import {Location} from 'history'
import * as AppActions from 'src/types/actions/app'
import * as ColorsModels from 'src/types/colors'
import {toggleShowVariablesControls} from 'src/userSettings/actions'
import {LimitStatus} from 'src/cloud/actions/limits'

interface StateProps {
  limitedResources: string[]
  limitStatus: LimitStatus
  org: Organization
  links: Links
  zoomedTimeRange: TimeRange
  timeRange: TimeRange
  dashboard: Dashboard
  autoRefresh: AutoRefresh
  showVariablesControls: boolean
  views: {[cellID: string]: {view: View; status: RemoteDataState}}
}

interface DispatchProps {
  deleteCell: typeof dashboardActions.deleteCellAsync
  copyCell: typeof dashboardActions.copyDashboardCellAsync
  getDashboard: typeof dashboardActions.getDashboardAsync
  updateDashboard: typeof dashboardActions.updateDashboardAsync
  updateCells: typeof dashboardActions.updateCellsAsync
  updateQueryParams: typeof rangesActions.updateQueryParams
  setDashTimeV1: typeof rangesActions.setDashTimeV1
  setZoomedTimeRange: typeof rangesActions.setZoomedTimeRange
  handleChooseAutoRefresh: typeof setAutoRefreshInterval
  onSetAutoRefreshStatus: typeof setAutoRefreshStatus
  handleClickPresentationButton: AppActions.DelayEnablePresentationModeDispatcher
  onCreateCellWithView: typeof dashboardActions.createCellWithView
  onUpdateView: typeof dashboardActions.updateView
  onSetActiveTimeMachine: typeof setActiveTimeMachine
  onToggleShowVariablesControls: typeof toggleShowVariablesControls
}

interface PassedProps {
  params: {
    dashboardID: string
  }
  location: Location
  cellQueryStatus: {
    queryID: string
    status: object
  }
  thresholdsListType: string
  thresholdsListColors: ColorsModels.Color[]
  gaugeColors: ColorsModels.Color[]
  lineColors: ColorsModels.Color[]
}

type Props = PassedProps &
  StateProps &
  DispatchProps &
  ManualRefreshProps &
  WithRouterProps

@ErrorHandling
class DashboardPage extends Component<Props> {
  public async componentDidMount() {
    const {autoRefresh} = this.props

    if (autoRefresh.status === AutoRefreshStatus.Active) {
      GlobalAutoRefresher.poll(autoRefresh.interval)
    }

    await this.getDashboard()
  }

  public componentDidUpdate(prevProps: Props) {
    const {autoRefresh} = this.props

    if (!_.isEqual(autoRefresh, prevProps.autoRefresh)) {
      if (autoRefresh.status === AutoRefreshStatus.Active) {
        GlobalAutoRefresher.poll(autoRefresh.interval)
        return
      }

      GlobalAutoRefresher.stopPolling()
    }
  }

  public componentWillUnmount() {
    GlobalAutoRefresher.stopPolling()
  }

  public render() {
    const {
      org,
      timeRange,
      zoomedTimeRange,
      dashboard,
      autoRefresh,
      limitStatus,
      limitedResources,
      manualRefresh,
      onManualRefresh,
      showVariablesControls,
      handleClickPresentationButton,
      onToggleShowVariablesControls,
      children,
    } = this.props

    return (
      <Page titleTag={this.pageTitle}>
        <LimitChecker>
          <HoverTimeProvider>
            <DashboardHeader
              org={org}
              dashboard={dashboard}
              timeRange={timeRange}
              autoRefresh={autoRefresh}
              onAddCell={this.handleAddCell}
              onAddNote={this.showNoteOverlay}
              onManualRefresh={onManualRefresh}
              zoomedTimeRange={zoomedTimeRange}
              onRenameDashboard={this.handleRenameDashboard}
              activeDashboard={dashboard ? dashboard.name : ''}
              handleChooseAutoRefresh={this.handleChooseAutoRefresh}
              onSetAutoRefreshStatus={this.handleSetAutoRefreshStatus}
              handleChooseTimeRange={this.handleChooseTimeRange}
              handleClickPresentationButton={handleClickPresentationButton}
              toggleVariablesControlBar={onToggleShowVariablesControls}
              isShowingVariablesControlBar={showVariablesControls}
            />
            <RateLimitAlert
              resources={limitedResources}
              limitStatus={limitStatus}
              className="dashboard--rate-alert"
            />
            {showVariablesControls && !!dashboard && (
              <VariablesControlBar dashboardID={dashboard.id} />
            )}
            {!!dashboard && (
              <DashboardComponent
                dashboard={dashboard}
                timeRange={timeRange}
                manualRefresh={manualRefresh}
                onCloneCell={this.handleCloneCell}
                onPositionChange={this.handlePositionChange}
                onDeleteCell={this.handleDeleteDashboardCell}
                onEditView={this.handleEditView}
                onAddCell={this.handleAddCell}
                onEditNote={this.showNoteOverlay}
              />
            )}
            {children}
          </HoverTimeProvider>
        </LimitChecker>
      </Page>
    )
  }

  private getDashboard = async () => {
    const {params, getDashboard} = this.props

    await getDashboard(params.dashboardID)
  }

  private handleChooseTimeRange = (timeRange: TimeRange): void => {
    const {dashboard, setDashTimeV1, updateQueryParams} = this.props
    setDashTimeV1(dashboard.id, {...timeRange})

    updateQueryParams({
      lower: timeRange.lower,
      upper: timeRange.upper,
    })
  }

  private handleSetAutoRefreshStatus = (
    autoRefreshStatus: AutoRefreshStatus
  ) => {
    const {
      onSetAutoRefreshStatus,
      params: {dashboardID},
    } = this.props

    onSetAutoRefreshStatus(dashboardID, autoRefreshStatus)
  }

  private handleChooseAutoRefresh = (autoRefreshInterval: number) => {
    const {
      handleChooseAutoRefresh,
      params: {dashboardID},
    } = this.props

    handleChooseAutoRefresh(dashboardID, autoRefreshInterval)

    if (autoRefreshInterval === 0) {
      this.handleSetAutoRefreshStatus(AutoRefreshStatus.Paused)
      return
    }

    this.handleSetAutoRefreshStatus(AutoRefreshStatus.Active)
  }

  private handlePositionChange = async (cells: Cell[]): Promise<void> => {
    const {dashboard, updateCells} = this.props
    await updateCells(dashboard, cells)
  }

  private handleAddCell = async (): Promise<void> => {
    const {router, location} = this.props
    router.push(`${location.pathname}/cells/new`)
  }

  private showNoteOverlay = async (id?: string): Promise<void> => {
    if (id) {
      this.props.router.push(`${this.props.location.pathname}/notes/${id}/edit`)
    } else {
      this.props.router.push(`${this.props.location.pathname}/notes/new`)
    }
  }

  private handleEditView = (cellID: string): void => {
    const {router, location} = this.props
    router.push(`${location.pathname}/cells/${cellID}/edit`)
  }

  private handleCloneCell = async (cell: Cell): Promise<void> => {
    const {dashboard, onCreateCellWithView, views} = this.props
    const viewEntry = views[cell.id]
    if (viewEntry && viewEntry.view) {
      await onCreateCellWithView(dashboard.id, viewEntry.view, cell)
    }
  }

  private handleRenameDashboard = async (name: string): Promise<void> => {
    const {dashboard, updateDashboard} = this.props
    const renamedDashboard = {...dashboard, name}

    await updateDashboard(renamedDashboard)
  }

  private handleDeleteDashboardCell = async (cell: Cell): Promise<void> => {
    const {dashboard, deleteCell} = this.props
    await deleteCell(dashboard, cell)
  }

  private get pageTitle(): string {
    const {dashboard} = this.props
    const dashboardName = _.get(dashboard, 'name', 'Loading...')

    return pageTitleSuffixer([dashboardName])
  }
}

const mstp = (state: AppState, {params: {dashboardID}}): StateProps => {
  const {
    links,
    ranges,
    dashboards,
    views: {views},
    userSettings: {showVariablesControls},
    orgs: {org},
    cloud: {limits},
  } = state

  const timeRange =
    ranges.find(r => r.dashboardID === dashboardID) || DEFAULT_TIME_RANGE

  const autoRefresh = state.autoRefresh[dashboardID] || AUTOREFRESH_DEFAULT

  const dashboard = dashboards.list.find(d => d.id === dashboardID)

  const limitedResources = extractRateLimitResources(limits)
  const limitStatus = extractRateLimitStatus(limits)

  return {
    org,
    links,
    views,
    zoomedTimeRange: {lower: null, upper: null},
    timeRange,
    dashboard,
    autoRefresh,
    limitStatus,
    limitedResources,
    showVariablesControls,
  }
}

const mdtp: DispatchProps = {
  getDashboard: dashboardActions.getDashboardAsync,
  updateDashboard: dashboardActions.updateDashboardAsync,
  copyCell: dashboardActions.copyDashboardCellAsync,
  deleteCell: dashboardActions.deleteCellAsync,
  updateCells: dashboardActions.updateCellsAsync,
  handleChooseAutoRefresh: setAutoRefreshInterval,
  onSetAutoRefreshStatus: setAutoRefreshStatus,
  handleClickPresentationButton: appActions.delayEnablePresentationMode,
  setDashTimeV1: rangesActions.setDashTimeV1,
  updateQueryParams: rangesActions.updateQueryParams,
  setZoomedTimeRange: rangesActions.setZoomedTimeRange,
  onCreateCellWithView: dashboardActions.createCellWithView,
  onUpdateView: dashboardActions.updateView,
  onSetActiveTimeMachine: setActiveTimeMachine,
  onToggleShowVariablesControls: toggleShowVariablesControls,
}

export default connect(
  mstp,
  mdtp
)(ManualRefresh<Props>(withRouter<Props>(DashboardPage)))


text:
VMNAME = sumovm
ESCPATH = $(shell printf "%q\n" "$(shell pwd)")
UESCPATH = $(shell pwd | sed -e 's/ /\\ /g' -e 's/\[/\\\[/g' -e 's/\]/\\\]/g')
START ?= 1
END ?= 16

build:
	docker build -t $(VMNAME) .

ubuntu:
	docker run \
		-v /hardmem/results_TRB/:/hardmem/results/ \
		-v $(UESCPATH)/mainCode/:/simulation/mainCode/ \
		-v $(UESCPATH)/sumoAPI/:/simulation/sumoAPI/ \
		-w /simulation/mainCode \
		$(VMNAME) python parallelRun.py $(START) $(END)

ubuntu_special:
	docker run \
		-v /hardmem/results_TRB2/:/hardmem/results/ \
		-v $(UESCPATH)/mainCode/:/simulation/mainCode/ \
		-v $(UESCPATH)/sumoAPI/:/simulation/sumoAPI/ \
		-w /simulation/mainCode \
		$(VMNAME) python ParallelSpecial.py $(START) $(END)

mac:
	docker run \
		-v $(ESCPATH)/results/:/hardmem/results/ \
		-v $(ESCPATH)/mainCode/:/simulation/mainCode/ \
		-v $(ESCPATH)/sumoAPI/:/simulation/sumoAPI/ \
		-w /simulation/mainCode \
		$(VMNAME) python parallelRun.py $(START) $(END)

mac_special:
	docker run \
		-v $(ESCPATH)/results/:/hardmem/results/ \
		-v $(ESCPATH)/mainCode/:/simulation/mainCode/ \
		-v $(ESCPATH)/sumoAPI/:/simulation/sumoAPI/ \
		-w /simulation/mainCode \
		$(VMNAME) python ParallelSpecialMac.py $(START) $(END)

test_ubuntu:
	docker run \
		-v /hardmem/results_jun17/:/hardmem/results/ \
		-v $(UESCPATH)/mainCode/:/simulation/mainCode/ \
		-v $(UESCPATH)/sumoAPI/:/simulation/sumoAPI/ \
		-w /simulation/mainCode \
		$(VMNAME) python dockerTest.py $(START) $(END)

test_sim_ubuntu:
	docker run \
		-v /hardmem/results_jun17/:/hardmem/results/ \
		-v $(UESCPATH)/mainCode/:/simulation/mainCode/ \
		-v $(UESCPATH)/sumoAPI/:/simulation/sumoAPI/ \
		-w /simulation/mainCode \
		$(VMNAME) python ParallelSpecial.py 1 2

test_mac:
	docker run \
		-v $(ESCPATH)/results/:/hardmem/results/ \
		-v $(ESCPATH)/mainCode/:/simulation/mainCode/ \
		-v $(ESCPATH)/sumoAPI/:/simulation/sumoAPI/ \
		-w /simulation/mainCode \
		$(VMNAME) python dockerTest.py $(START) $(END)

echo_test:
	echo $(UESCPATH)

prune:
	docker system prune
	docker container prune
	docker volume prune
	docker image prune


text:
<?php

/**
 * BuddyPress Members Toolbar
 *
 * Handles the member functions related to the WordPress Toolbar
 *
 * @package BuddyPress
 * @subpackage MembersAdminBar
 */

// Exit if accessed directly
if ( !defined( 'ABSPATH' ) ) exit;

/**
 * Add the "My Account" menu and all submenus.
 *
 * @since BuddyPress (1.6)
 * @todo Deprecate WP 3.2 Toolbar compatibility when we drop 3.2 support
 */
function bp_members_admin_bar_my_account_menu() {
	global $bp, $wp_admin_bar;

	// Bail if this is an ajax request
	if ( defined( 'DOING_AJAX' ) )
		return;

	// Logged in user
	if ( is_user_logged_in() ) {

		// Stored in the global so we can add menus easily later on
		$bp->my_account_menu_id = 'my-account-buddypress';

		// Create the main 'My Account' menu
		$wp_admin_bar->add_menu( array(
			'id'     => $bp->my_account_menu_id,
			'group'  => true,
			'title'  => __( 'Edit My Profile', 'buddypress' ),
			'href'   => bp_loggedin_user_domain(),
			'meta'   => array(
			'class'  => 'ab-sub-secondary'
		) ) );

	// Show login and sign-up links
	} elseif ( !empty( $wp_admin_bar ) ) {

		add_filter ( 'show_admin_bar', '__return_true' );

		// Create the main 'My Account' menu
		$wp_admin_bar->add_menu( array(
			'id'    => 'bp-login',
			'title' => __( 'Log in', 'buddypress' ),
			'href'  => wp_login_url( wp_guess_url() )
		) );

		// Sign up
		if ( bp_get_signup_allowed() ) {
			$wp_admin_bar->add_menu( array(
				'id'    => 'bp-register',
				'title' => __( 'Register', 'buddypress' ),
				'href'  => bp_get_signup_page()
			) );
		}
	}
}
add_action( 'bp_setup_admin_bar', 'bp_members_admin_bar_my_account_menu', 4 );

/**
 * Adds the User Admin top-level menu to user pages
 *
 * @package BuddyPress
 * @since BuddyPress (1.5)
 */
function bp_members_admin_bar_user_admin_menu() {
	global $bp, $wp_admin_bar;

	// Only show if viewing a user
	if ( !bp_is_user() )
		return false;

	// Don't show this menu to non site admins or if you're viewing your own profile
	if ( !current_user_can( 'edit_users' ) || bp_is_my_profile() )
		return false;

	// Unique ID for the 'My Account' menu
	$bp->user_admin_menu_id = 'user-admin';

	// Add the top-level User Admin button
	$wp_admin_bar->add_menu( array(
		'id'    => $bp->user_admin_menu_id,
		'title' => __( 'Edit Member', 'buddypress' ),
		'href'  => bp_displayed_user_domain()
	) );

	if ( bp_is_active( 'xprofile' ) ) {
		// User Admin > Edit this user's profile
		$wp_admin_bar->add_menu( array(
			'parent' => $bp->user_admin_menu_id,
			'id'     => $bp->user_admin_menu_id . '-edit-profile',
			'title'  => __( "Edit Profile", 'buddypress' ),
			'href'   => bp_get_members_component_link( 'profile', 'edit' )
		) );

		// User Admin > Edit this user's avatar
		if ( buddypress()->avatar->show_avatars ) {
			$wp_admin_bar->add_menu( array(
				'parent' => $bp->user_admin_menu_id,
				'id'     => $bp->user_admin_menu_id . '-change-avatar',
				'title'  => __( "Edit Avatar", 'buddypress' ),
				'href'   => bp_get_members_component_link( 'profile', 'change-avatar' )
			) );
		}

	}

	if ( bp_is_active( 'settings' ) ) {
		// User Admin > Spam/unspam
		$wp_admin_bar->add_menu( array(
			'parent' => $bp->user_admin_menu_id,
			'id'     => $bp->user_admin_menu_id . '-user-capabilities',
			'title'  => __( 'User Capabilities', 'buddypress' ),
			'href'   => bp_displayed_user_domain() . 'settings/capabilities/'
		) );

		// User Admin > Delete Account
		$wp_admin_bar->add_menu( array(
			'parent' => $bp->user_admin_menu_id,
			'id'     => $bp->user_admin_menu_id . '-delete-user',
			'title'  => __( 'Delete Account', 'buddypress' ),
			'href'   => bp_displayed_user_domain() . 'settings/delete-account/'
		) );

	}

}
add_action( 'admin_bar_menu', 'bp_members_admin_bar_user_admin_menu', 99 );

/**
 * Build the "Notifications" dropdown
 *
 * @package BuddyPress
 * @since BuddyPress (1.5)
 */
function bp_members_admin_bar_notifications_menu() {

	// Bail if notifications is not active
	if ( ! bp_is_active( 'notifications' ) ) {
		return false;
	}

	bp_notifications_toolbar_menu();
}
add_action( 'admin_bar_menu', 'bp_members_admin_bar_notifications_menu', 90 );

/**
 * Remove rogue WP core edit menu when viewing a single user
 *
 * @since BuddyPress (1.6)
 */
function bp_members_remove_edit_page_menu() {
	if ( bp_is_user() ) {
		remove_action( 'admin_bar_menu', 'wp_admin_bar_edit_menu', 80 );
	}
}
add_action( 'add_admin_bar_menus', 'bp_members_remove_edit_page_menu' );


text:
import logging
import requests
from utils.common.datapipeline import DataPipeline

def run(config):
    # Run until out of pages
    orgs = []
    page = 0
    while True:
        page += 1
        r = requests.get(config["parameters"]["src"],
                         params=dict(page=page,fetchSize=1000))
        # Assume that this means we're out of pages
        if r.status_code != 200:
            break
        # Append the organisations
        js = r.json()
        orgs += js["organisation"]
    logging.info("\tGot %s organisations.",len(orgs))

    # Write data
    logging.info("\tWriting to table")
    with DataPipeline(config) as dp:
        for row in orgs:
            dp.insert(row)


text:
Commonly used button.

### Basic usage

::: demo Button provides 7 themes defined by the `type` attribute.

```js
render() {
  return (
    <div>
      <Button>Default Button</Button>
      <Button type="primary">Primary Button</Button>
      <Button type="text">Text Button</Button>
    </div>
  )
}
```
:::

### Disabled Button

The `disableds` attribute determines if the button is disabled.

:::demo Use `disabled` attribute to determine whether a button is disabled. It accepts a `Boolean` value.

```js
render() {
  return (
    <div>
      <Button plain={true} disabled={true}>Default Button</Button>
      <Button type="primary" disabled={true}>Primary Button</Button>
      <Button type="text" disabled={true}>Text Button</Button>
    </div>
  )
}
```
:::

### Color Indication

Different colors represent different meanings.

:::demo Use `plain` attribute to create a plain button, and it accepts a `Boolean` value. You can assign different `type` to a plain button as mentioned above. **Note**: When using the plain button, you still can set `type` to `text`, but it makes no difference. A plain button will be styled like a `text button` by default.
```js
render() {
  return (
    <div className="intro-block">
      <div className="block">
        <span className="demonstration">Default</span>
        <span className="wrapper">
          <Button type="success">Success</Button>
          <Button type="warning">Warning</Button>
          <Button type="danger">Danger</Button>
          <Button type="info">Info</Button>
        </span>
      </div>
      <div className="block">
        <span className="demonstration">Hover to display color</span>
        <span className="wrapper">
          <Button plain={true} type="success">Success</Button>
          <Button plain={true} type="warning">Warning</Button>
          <Button plain={true} type="danger">Danger</Button>
          <Button plain={true} type="info">Info</Button>
        </span>
      </div>
    </div>
  )
}
```
:::

### Icon Button

Use icons to add more meaning to Button. You can use icon alone to save some space, or with text together.

:::demo Use the `icon` attribute to add icon. You can find the icon list in Element icon component. Adding icons to the right side of the text is achievable with an `<i>` tag. Custom icons can be used as well.

```js
render() {
  return (
    <div>
      <Button type="primary" icon="edit"></Button>
      <Button type="primary" icon="share"></Button>
      <Button type="primary" icon="delete"></Button>
      <Button type="primary" icon="search">Search</Button>
      <Button type="primary">Upload<i className="el-icon-upload el-icon-right"></i></Button>
    </div>
  )
}
```
:::

### Button Group

Displayed as a button group, can be used to group a series of similar operations.

:::demo Use tag `Button.Group` to group your buttons.

```js
render() {
  return (
    <div>
      <Button.Group>
          <Button type="primary" icon="arrow-left">Previous Page</Button>
          <Button type="primary">Next Page<i className="el-icon-arrow-right el-icon-right"></i></Button>
      </Button.Group>
      <Button.Group>
          <Button type="primary" icon="edit"></Button>
          <Button type="primary" icon="share"></Button>
          <Button type="primary" icon="delete"></Button>
      </Button.Group>
    </div>
  )
}
```
:::

### Loading Button

Click the button to load data, then the button displays a loading state.

:::demo Set `loading` attribute to `true` to display loading state.

```js
render() {
  return <Button type="primary" loading={true}>Loading</Button>
}
```
:::

### Sizes

Besides default size, Button component provides three additional sizes for you to choose among different scenarios.

:::demo Use attribute `size` to set additional sizes with `large`, `small` or `mini`.

```js
render() {
  return (
    <div>
      <Button type="primary" size="large">Large Button</Button>
      <Button type="primary">Default Button</Button>
      <Button type="primary" size="small">Small Button</Button>
      <Button type="primary" size="mini">Mini Button</Button>
    </div>
  )
}
```
:::

### Attributes
| Attribute      | Description    | Type      | Accepted values       | Default   |
|---------- |-------- |---------- |-------------  |-------- |
| size     | button size   | string  |   large/small/mini            |    —     |
| type     | button type   | string    |   primary/success/warning/danger/info/text |     —    |
| plain     | determine whether it's a plain button   | Boolean    | — | false   |
| loading   | determine whether it's loading   | Boolean    | — | false   |
| disabled  | disable the button    | boolean   | —   | false   |
| icon  | button icon, accepts an icon name of Element icon component | string   |  —  |  —  |
| nativeType | same as native button's `type` | string | button/submit/reset | button |


text:
package net.siufung.bzgzpt.persistence.collect.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.jbinfo.platform.core.basic.exception.ServiceException;
import cn.jbinfo.platform.core.framework.page.MyPage;
import net.siufung.bzgzpt.persistence.collect.dao.IAba31Dao;
import net.siufung.bzgzpt.persistence.collect.domain.Aba31;
import net.siufung.bzgzpt.persistence.collect.domain.BuziPerson;
import net.siufung.bzgzpt.persistence.collect.domain.PersonRollOut;
import net.siufung.bzgzpt.persistence.collect.service.IAba31Service;
import net.siufung.bzgzpt.persistence.collect.service.IBuziPersonService;
import net.siufung.bzgzpt.persistence.collect.service.IOperateLogService;
import net.siufung.bzgzpt.persistence.collect.service.IPersonRolloutService;
import net.siufung.bzgzpt.persistence.uap.domain.Depart;
import net.siufung.bzgzpt.persistence.uap.domain.User;
/**
 * 对Aba31实体进行CRUD操作
 */
@Service("aba31ServiceImpl")
@Transactional
public class Aba31ServiceImpl implements IAba31Service{

	@Resource
	private IAba31Dao aba31Dao;
	@Autowired
	private IBuziPersonService buziPersonService; // 人员服务
	@Autowired
	private IPersonRolloutService personRollOutService;//转出服务
	@Autowired
	private IOperateLogService operateLogService;
	@Override
	public void save(Aba31 aba31) {
		aba31Dao.save(aba31);
	}
	@Override
	public void deleteByAbax3101(Long abax3101) {
		aba31Dao.deleteById(abax3101);
	}
	@Override
	public void update(Aba31 aba31) {
		aba31Dao.update(aba31);
	}
	@Override
	public Aba31 getByAbax3101(Long abax3101) {
		return aba31Dao.getById(abax3101);
	}
	@Override
	public Aba31 getByModel(Aba31 aba31) {
		return aba31Dao.getByModel(aba31);
	}
	@Override
	public List<Aba31> searchList(Aba31 aba31) {
		return aba31Dao.searchList(aba31);
	}
//	public CommPager searchPager(Aba31 aba31,int pageNum,int pageSize) {
//		PageHelper.startPage(pageNum,pageSize);
//		List l = aba31Dao.searchList(aba31);
//		return new CommPager(l);
//	}
	@Override
	public Aba31 get(Aba31 paramT) throws ServiceException {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public Aba31 getById(String id) throws ServiceException {
		// TODO Auto-generated method stub
		return aba31Dao.getById(id);
	}
	@Override
	public List<Aba31> findList(Aba31 paramT) throws ServiceException {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public void insert(Aba31 paramT) throws ServiceException {
		// TODO Auto-generated method stub

	}
	@Override
	public void delete(Aba31 paramT) throws ServiceException {
		// TODO Auto-generated method stub

	}
	@Override
	public Aba31 getByAzcp0002(String azcp0002) {
		// TODO Auto-generated method stub
		return aba31Dao.getByAzcp0002(azcp0002);
	}
	//获取分页数据
	public MyPage<Map<String, Object>> getPage(Aba31 aba31) {
		MyPage<Map<String, Object>> pageView = new MyPage<Map<String, Object>>(aba31.getPageSize(), aba31.getPageIndex());
	    Map<String, Object> map = new HashMap<String, Object>();
	    map.put("paging", pageView);
	    map.put("model", aba31);
	    List<Map<String, Object>> objectList = aba31Dao.queryForPage(map);
	    pageView.setRecords(objectList);
	    return pageView;
	}
	@Override
	public Map<String, Object> rollOut(HttpServletRequest request, Aba31 aba31, BuziPerson buziPerson) {
		Map<String, Object> map = new HashMap<String, Object>();
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("loginUser");
		Depart depart = (Depart) session.getAttribute("loginDepart");
		String areaCode = request.getParameter("areaCode");
		String areaName = request.getParameter("areaName");
		if (user != null && depart != null && areaCode != null && areaName != null) {
			String userCode = user.getLoginName(); // 当前登录人code
			String userName = user.getName(); // 当前登录人名称
			// String departId = depart.getId(); //当前登录人所属部门编码
			String departCodeName = depart.getName();// 当前登录人所属部门名称
			String departAreaCode = depart.getCode();// 当前登录人所属部门归属区划id
			Date currentDate = new Date();
			// 1、查询人员的基本信息
			buziPerson.setDelflag("0");
			BuziPerson resBuziPerson = buziPersonService.getByModel(buziPerson);
			if (resBuziPerson != null) {
				// 根据业务信息主键查询aba31业务信息,如果存在对应记录,则证明此人已办理过此项业务,不能再办理
				aba31.setPersonId(resBuziPerson.getId());
				aba31.setAzzx0017("1");// 有效标记
				Aba31 resAba31 = this.getByModel(aba31);
				if (resAba31 != null) {
					resAba31.setAbax3140("1");
					resAba31.setAzzx0023(areaCode);
					this.update(resAba31);
					// 写入操作日志
					operateLogService.saveOpt("aba31", resAba31.getAbax3101().toString(), "abax3140 : "+resAba31.getAbax3140(), "转出", "用户名:"+user.getName()+"转出优抚业务", user.getId());
					PersonRollOut person = new PersonRollOut();
					person.setIdCard(resAba31.getAzcp0002());
					person.setA1(userCode);// 经办人代码
					person.setA2(userName);// 经办人名称
					person.setA3(departCodeName);// 经办机构
					person.setA4(departAreaCode);// 经办机构代码
					person.setA5(areaName);// 转入机构
					person.setA6(areaCode);// 转入机构代码
					person.setA7(currentDate);// 转入时间
					personRollOutService.save(person);
					map.put("flag", true);
					map.put("msg", "转出成功");
				}
			}
		} else {
			map.put("flag", false);
			map.put("msg", "登录超时,请重新登录");
		}
		return map;
	}
	@Override
	public Map<String, String> getId(String idcard) {
		Map<String, String> map = aba31Dao.getId(idcard);
		return map;
	}
}


text:
br="br0"

# Define list of TAP interfaces to be bridged together
tap="tap0"

ifconfig $br down
brctl delbr $br

for t in $tap; do
    openvpn --rmtun --dev $t
done


text:
package org.wte4j.examples.showcase.client.management;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.gwtbootstrap3.client.ui.Button;
import org.gwtbootstrap3.client.ui.Form;
import org.gwtbootstrap3.client.ui.Image;
import org.gwtbootstrap3.client.ui.InlineHelpBlock;
import org.gwtbootstrap3.client.ui.LinkedGroup;
import org.gwtbootstrap3.client.ui.LinkedGroupItem;
import org.gwtbootstrap3.client.ui.TextBox;
import org.gwtbootstrap3.client.ui.form.error.BasicEditorError;
import org.gwtbootstrap3.client.ui.form.validator.Validator;
import org.wte4j.examples.showcase.client.Application;

import com.google.gwt.core.shared.GWT;
import com.google.gwt.editor.client.Editor;
import com.google.gwt.editor.client.EditorError;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;

public class NewTemplatePanel extends Composite implements NewTemplateDisplay {

	private static NewTemplatePanelUiBinder uiBinder = GWT.create(NewTemplatePanelUiBinder.class);

	@UiField
	Form createTemplateForm;

	@UiField
	TextBox templateName;

	@UiField
	InlineHelpBlock dataModelAlert;

	@UiField
	LinkedGroup dataModelList;

	@UiField
	Button createTemplate;

	@UiField
	Button closeDialog;

	@UiField
	Image loadingSpinner;

	private Map<String, LinkedGroupItem> dataModelNameToItem = new HashMap<String, LinkedGroupItem>();

	public NewTemplatePanel() {
		this.initWidget(uiBinder.createAndBindUi(this));
		initTemplateName();
		initSpinner();
	}

	@SuppressWarnings("unchecked")
	private void initTemplateName() {
		Validator<String> validator = new Validator<String>() {
			@Override
			public int getPriority() {
				return 0;
			}

			@Override
			public List<EditorError> validate(Editor<String> editor,
					String value) {
				List<EditorError> errors = new ArrayList<EditorError>();
				if (value == null || "".equals(value)) {
					errors.add(new BasicEditorError(editor, value, Application.MESSAGES.wte4j_message_template_name_not_empty()));
				}
				return errors;
			}
		};
		templateName.setValidators(validator);
		templateName.setValidateOnBlur(true);
	}

	private void initSpinner() {
		loadingSpinner.setResource(Application.RESOURCES.loadingSpinner());
		loadingSpinner.setVisible(false);
	}

	@Override
	public void setDataModelListItems(List<DataModelItem> dataModelItems) {
		dataModelList.clear();
		dataModelNameToItem.clear();
		boolean first = true;
		for (DataModelItem item : dataModelItems) {
			LinkedGroupItem groupItem = new LinkedGroupItem();
			groupItem.setText(item.getText());
			groupItem.addClickHandler(item.getClickHandler());
			if (first) {
				groupItem.setActive(true);
			} else {
				groupItem.setActive(false);
			}
			first = false;
			dataModelNameToItem.put(item.getText(), groupItem);
			dataModelList.add(groupItem);
		}
	}

	@Override
	public String getTemplateName() {
		return templateName.getText();
	}

	@Override
	public void setTemplateName(String value) {
		templateName.setValue(value);
	}

	@Override
	public void setFocusOnTemplateName() {
		templateName.selectAll();
		templateName.setFocus(true);

	}

	@Override
	public void addCloseDialogClickHandler(ClickHandler clickHandler) {
		closeDialog.addClickHandler(clickHandler);
	}

	@Override
	public void addCreateTemplateClickHandler(ClickHandler clickHandler) {
		createTemplate.addClickHandler(clickHandler);
	}

	@Override
	public boolean validateAddTemplateForm() {
		return createTemplateForm.validate() && isOneDataModelActive();
	}

	private boolean isOneDataModelActive() {
		boolean oneDataModel = false;
		for (String dataModel : dataModelNameToItem.keySet()) {
			LinkedGroupItem item = dataModelNameToItem.get(dataModel);
			if (!oneDataModel && item.isActive()) {
				oneDataModel = true;
			} else if (oneDataModel && item.isActive()) {
				oneDataModel = false;
				break;
			}
		}
		if (!oneDataModel) {
			dataModelAlert.setText(Application.MESSAGES.wte4j_message_one_data_model_selected());
			dataModelAlert.setVisible(true);
		} else {
			dataModelAlert.setVisible(false);
		}
		return oneDataModel;
	}

	@Override
	public String getSelectedDataModel() {
		for (String dataModel : dataModelNameToItem.keySet()) {
			LinkedGroupItem item = dataModelNameToItem.get(dataModel);
			if (item.isActive())
				return dataModel;
		}
		return "";
	}

	@Override
	public void setSelectedDataModel(String selectedDataModel) {
		for (String dataModel : dataModelNameToItem.keySet()) {
			LinkedGroupItem item = dataModelNameToItem.get(dataModel);
			if (dataModel.equals(selectedDataModel))
				item.setActive(true);
			else
				item.setActive(false);
		}
	}

	@Override
	public void showSpinner() {
		closeDialog.setVisible(false);
		createTemplate.setVisible(false);
		loadingSpinner.setVisible(true);
	}

	@Override
	public void hideSpinner() {
		closeDialog.setVisible(true);
		createTemplate.setVisible(true);
		loadingSpinner.setVisible(false);
	}

	interface NewTemplatePanelUiBinder extends UiBinder<Widget, NewTemplatePanel> {
	}
}


text:
require 'tzinfo_timezone'

# remove the existing TimeZone constant
Object.send(:remove_const, :TimeZone)

# Use TzinfoTimezone as the TimeZone class
Object::TimeZone = TzinfoTimezone


text:
package org.wso2.eventsimulator.core.util;

/**
 * Constants related to random data generator
 */
public class RandomDataGeneratorConstants {

    //constants for Property based data generator
    public static final String MODULE_ADDRESS = "address";
    public static final String MODULE_APP = "app";
    public static final String MODULE_BOOL = "bool";
    public static final String MODULE_BUSINESS = "business";
    public static final String MODULE_CODE = "code";
    public static final String MODULE_COMMERCE= "commerce";
    public static final String MODULE_COMPANY = "company";
    public static final String MODULE_CRYPTO = "crypto";
    public static final String MODULE_DATE = "date";
    public static final String MODULE_FINANCE = "finance";
    public static final String MODULE_ID_NUMBER = "idNumber";
    public static final String MODULE_INTERNET = "internet";
    public static final String MODULE_LOREM = "lorem";
    public static final String MODULE_NAME = "name";
    public static final String MODULE_PHONE_NUMBER= "phoneNumber";

//constants for each category/module

//    Address
    public static final String MODULE_ADDRESS_BUILDING_NUMBER = "buildingNumber";
    public static final String MODULE_ADDRESS_CITY = "city";
    public static final String MODULE_ADDRESS_COUNTRY = "country";
    public static final String MODULE_ADDRESS_COUNTRY_CODE = "countryCode";
    public static final String MODULE_ADDRESS_LATITUDE = "latitude";
    public static final String MODULE_ADDRESS_LONGITUDE = "longitude";
    public static final String MODULE_ADDRESS_STATE = "state";
    public static final String MODULE_ADDRESS_STATE_ABBREVIATION = "stateAbbreviation";
    public static final String MODULE_ADDRESS_STREET_ADDRESS = "streetAddress";
    public static final String MODULE_ADDRESS_STREET_ADDRESS_NUMBER = "streetAddressNumber";
    public static final String MODULE_ADDRESS_STREET_NAME = "streetName";
    public static final String MODULE_ADDRESS_TIME_ZONE = "timeZone";
    public static final String MODULE_ADDRESS_ZIP_CODE = "zipCode";

//    App
    public static final String MODULE_APP_NAME = "name";
    public static final String MODULE_APP_VERSION = "version";
    public static final String MODULE_APP_AUTHOR = "author";

//    Bool
    public static final String MODULE_BOOL_BOOL = "bool";

//    Business
    public static final String MODULE_BUSINESS_CREDIT_CARD_EXPIRY = "expiry";
    public static final String MODULE_BUSINESS_CREDIT_CARD_NUMBER = "number";
    public static final String MODULE_BUSINESS_CREDIT_CARD_TYPE = "type";

//    Code
    public static final String MODULE_CODE_ASIN = "asin";
    public static final String MODULE_CODE_EAN8 = "ean8";
    public static final String MODULE_CODE_EAN13 = "ean13";
    public static final String MODULE_CODE_GTIN8 = "gtin8";
    public static final String MODULE_CODE_GTIN13 = "gtin13";
    public static final String MODULE_CODE_IMEI = "imei";
//    public static final String MODULE_CODE_ISBN10 = "isbn10";
//    public static final String MODULE_CODE_ISBN13 = "isbn13";
//    public static final String MODULE_CODE_ISBN_GROUP = "isbnGroup";
//    public static final String MODULE_CODE_ISBNGS1 = "isbnGs1";
//    public static final String MODULE_CODE_ISBNREGISTRANT = "isbnRegistrant";

//    Commerce
    public static final String MODULE_COMMERCE_COLOUR = "colour";
    public static final String MODULE_COMMERCE_DEPARTMENT = "department";
    public static final String MODULE_COMMERCE_MATERIAL = "material";
    public static final String MODULE_COMMERCE_PRICE = "price";
    public static final String MODULE_COMMERCE_PRODUCT_NAME = "productName";
    public static final String MODULE_COMMERCE_PROMOTION_CODE = "promotionCode";

//    Company
//    public static final String MODULE_COMPANY_BS = "bs";
//    public static final String MODULE_COMPANY_BUZZWORD = "buzzWord";
//    public static final String MODULE_COMPANY_CATCH_PHRASE = "catchPhrase";
    public static final String MODULE_COMPANY_INDUSTRY = "industry";
    public static final String MODULE_COMPANY_NAME = "name";
    public static final String MODULE_COMPANY_PROFESSION = "profession";
    public static final String MODULE_COMPANY_URL = "url";

//    Crypto
    public static final String MODULE_CRYPTO_MD5 = "md5";
    public static final String MODULE_CRYPTO_SHA1 = "sha1";
    public static final String MODULE_CRYPTO_SHA256 = "sha256";
    public static final String MODULE_CRYPTO_SHA512 = "sha512";

    //    DateAndTime
    public static final String MODULE_DATE_PAST = "pastDate";
    public static final String MODULE_DATE_FUTURE = "futureDate";
    public static final String MODULE_DATE_BETWEEN = "dateBetween";

//       Finance
    public static final String MODULE_FINANCE_BIC = "bic";
    public static final String MODULE_FINANCE_CREDIT_CARD = "creditCard";
    public static final String MODULE_FINANCE_IBAN = "iban";

//       ID number
    public static final String MODULE_ID_NUMBER_SSN = "ssn";

//       Internet
    public static final String MODULE_INTERNET_DOMAIN_NAME = "domainName";
    public static final String MODULE_INTERNET_EMAIL = "email";
    public static final String MODULE_INTERNET_IPV4_ADDRESS = "ipv4Address";
    public static final String MODULE_INTERNET_IPV4_CIDR_ADDRESS = "ipv4CidrAddress";
    public static final String MODULE_INTERNET_IPV6_ADDRESS = "ipv6Address";
    public static final String MODULE_INTERNET_IPV6_CIDR_ADDRESS = "ipv6CidrAddress";
    public static final String MODULE_INTERNET_MAC_ADDRESS = "macAddress";
    public static final String MODULE_INTERNET_PASSWORD = "password";
    public static final String MODULE_INTERNET_PRIVATE_IPV4_ADDRESS = "privateIpv4Address";
    public static final String MODULE_INTERNET_PUBLIC_IPV4_ADDRESS = "publicIpv4Address";
    public static final String MODULE_INTERNET_SAFE_EMAIL = "safeEmail";
    public static final String MODULE_INTERNET_URL = "url";

//    Lorem
    public static final String MODULE_LOREM_CHARACTER = "character";
    public static final String MODULE_LOREM_PARAGRAPH = "paragraph";
    public static final String MODULE_LOREM_SENTENCE = "sentence";
    public static final String MODULE_LOREM_WORD = "word";

//    Name
    public static final String MODULE_NAME_FIRST_NAME = "firstName";
    public static final String MODULE_NAME_FULL_NAME = "fullName";
    public static final String MODULE_NAME_LAST_NAME = "lastName";
    public static final String MODULE_NAME_TITLE = "title";
    public static final String MODULE_NAME_USERNAME = "username";

//    Phone number
    public static final String MODULE_PHONE_NUMBER_CELL_PHONE = "cellPhone";

}


text:
package org.carlspring.strongbox.storage.repository;

import org.carlspring.strongbox.xml.CustomTag;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * @author carlspring
 */
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public abstract class CustomConfiguration
        implements CustomTag
{

}


text:
module PaperclipOnAkamai

  class << self
    def included base #:nodoc:
      base.extend ClassMethods
    end
  end

  module ClassMethods
    # +has_attached_file+ gives the class it is called on an attribute that maps to a file. This
    # is typically a file stored somewhere on the filesystem and has been uploaded by a user.
    # The attribute returns a Paperclip::Attachment object which handles the management of
    # that file. The intent is to make the attachment as much like a normal attribute. The
    # thumbnails will be created when the new file is assigned, but they will *not* be saved
    # until +save+ is called on the record. Likewise, if the attribute is set to +nil+ is
    # called on it, the attachment will *not* be deleted until +save+ is called. See the
    # Paperclip::Attachment documentation for more specifics. There are a number of options
    # you can set to change the behavior of a Paperclip attachment:
    # * +url+: The full URL of where the attachment is publically accessible. This can just
    #   as easily point to a directory served directly through Apache as it can to an action
    #   that can control permissions. You can specify the full domain and path, but usually
    #   just an absolute path is sufficient. The leading slash *must* be included manually for
    #   absolute paths. The default value is
    #   "/system/:attachment/:id/:style/:basename.:extension". See
    #   Paperclip::Attachment#interpolate for more information on variable interpolaton.
    #     :url => "/:class/:attachment/:id/:style_:basename.:extension"
    #     :url => "http://some.other.host/stuff/:class/:id_:extension"
    # * +default_url+: The URL that will be returned if there is no attachment assigned.
    #   This field is interpolated just as the url is. The default value is
    #   "/:attachment/:style/missing.png"
    #     has_attached_file :avatar, :default_url => "/images/default_:style_avatar.png"
    #     User.new.avatar_url(:small) # => "/images/default_small_avatar.png"
    # * +styles+: A hash of thumbnail styles and their geometries. You can find more about
    #   geometry strings at the ImageMagick website
    #   (http://www.imagemagick.org/script/command-line-options.php#resize). Paperclip
    #   also adds the "#" option (e.g. "50x50#"), which will resize the image to fit maximally
    #   inside the dimensions and then crop the rest off (weighted at the center). The
    #   default value is to generate no thumbnails.
    # * +default_style+: The thumbnail style that will be used by default URLs.
    #   Defaults to +original+.
    #     has_attached_file :avatar, :styles => { :normal => "100x100#" },
    #                       :default_style => :normal
    #     user.avatar.url # => "/avatars/23/normal_me.png"
    # * +whiny_thumbnails+: Will raise an error if Paperclip cannot post_process an uploaded file due
    #   to a command line error. This will override the global setting for this attachment.
    #   Defaults to true.
    # * +convert_options+: When creating thumbnails, use this free-form options
    #   field to pass in various convert command options.  Typical options are "-strip" to
    #   remove all Exif data from the image (save space for thumbnails and avatars) or
    #   "-depth 8" to specify the bit depth of the resulting conversion.  See ImageMagick
    #   convert documentation for more options: (http://www.imagemagick.org/script/convert.php)
    #   Note that this option takes a hash of options, each of which correspond to the style
    #   of thumbnail being generated. You can also specify :all as a key, which will apply
    #   to all of the thumbnails being generated. If you specify options for the :original,
    #   it would be best if you did not specify destructive options, as the intent of keeping
    #   the original around is to regenerate all the thumbnails when requirements change.
    #     has_attached_file :avatar, :styles => { :large => "300x300", :negative => "100x100" }
    #                                :convert_options => {
    #                                  :all => "-strip",
    #                                  :negative => "-negate"
    #                                }
    # * +storage+: Chooses the storage backend where the files will be stored. The current
    #   choices are :filesystem and :s3. The default is :filesystem. Make sure you read the
    #   documentation for Paperclip::Storage::Filesystem and Paperclip::Storage::S3
    #   for backend-specific options.
    def has_attached_file_on_akamai name, options = {}
      include InstanceMethods

      # Add Custom Akamai Url
      url = options[:url] || Paperclip::Attachment.default_options[:url]

      proc = lambda { |a| a.instance.akamai_asset_url(url, name) }
      # Hack for Paperclip Interpolation, validation
      def proc.include?(item); false; end
      options[:url] = proc

      # Call Default Paperclip Setup
      has_attached_file name.to_sym, options

      attr_accessor :_do_akamai_upload

      define_method "upload_#{name}_to_akamai" do
        upload_to_akamai(name)
      end

      define_method "process_upload_#{name}_to_akamai" do
        process_upload_to_akamai(name)
      end

      define_method "do_akamai_upload_for_#{name}?" do
        do_akamai_upload?(name)
      end

      define_method "do_akamai_upload_for_#{name}=" do |value|
        do_akamai_upload(name,value)
      end

      define_method "randomize_#{name}_file_name" do
        randomize_poaasset_file_name(name)
      end

      define_method "enable_#{name}_upload_to_akamai" do
        enable_upload_to_akamai(name)
      end

      # Generate Random Filename (Should solve purging problems)
      send("before_#{name}_post_process", :"randomize_#{name}_file_name")

      # Enable Upload to Akamai
      send("after_#{name}_post_process", :"enable_#{name}_upload_to_akamai")

      # Do Upload
      after_save :"process_upload_#{name}_to_akamai"
    end

  end

  module InstanceMethods #:nodoc:

    def do_akamai_upload?(name)
      @_do_akamai_upload ||= {}
      return @_do_akamai_upload[name]
    end

    def do_akamai_upload(name, value)
      @_do_akamai_upload ||= {}
      @_do_akamai_upload[name] = value
    end

    def process_upload_to_akamai(paperclip_attachment)
      if self.send("do_akamai_upload_for_#{paperclip_attachment}?") && PaperclipOnAkamai::CONFIG["enabled"] && self.send(paperclip_attachment).present?
        if PaperclipOnAkamai::CONFIG["delayed_job"]
          self.send_later("upload_#{paperclip_attachment}_to_akamai")
        else
          self.send("upload_#{paperclip_attachment}_to_akamai")
        end
      end
    end

    def enable_upload_to_akamai(paperclip_attachment)
      self.send("do_akamai_upload_for_#{paperclip_attachment}=",true) # at this time the model hasn't an id, so say after_save callback we need to upload
      self.send("#{paperclip_attachment}_on_akamai=",false) # since something has changed, don't use akamai version until its properly updated
    end

    def upload_to_akamai(paperclip_attachment)
      begin
        self.send("#{paperclip_attachment}_on_akamai=",false)
        att = self.send(paperclip_attachment)
        Net::SSH.start(PaperclipOnAkamai::CONFIG["scp_host"], PaperclipOnAkamai::CONFIG["scp_user"], :keys => [PaperclipOnAkamai::CONFIG["key"]]) do |ssh|
          ssh.exec!("mkdir -p #{File.dirname(File.join(PaperclipOnAkamai::CONFIG["remote_path"],att.url.split("?").first))}")
          ssh.exec!("rm #{File.dirname(File.join(PaperclipOnAkamai::CONFIG["remote_path"],att.url.split("?").first))}/*")
          att.styles.each do |style,value|
            ssh.exec!("mkdir -p #{File.dirname(File.join(PaperclipOnAkamai::CONFIG["remote_path"],att.url(style).split("?").first))}")
            ssh.exec!("rm #{File.dirname(File.join(PaperclipOnAkamai::CONFIG["remote_path"],att.url.split("?").first))}/*")
          end
        end
        Net::SCP.start(PaperclipOnAkamai::CONFIG["scp_host"], PaperclipOnAkamai::CONFIG["scp_user"], :keys => [PaperclipOnAkamai::CONFIG["key"]]) do |scp|
          scp.upload!(att.path, File.join(PaperclipOnAkamai::CONFIG["remote_path"],att.url.split("?").first))
          att.styles.each do |style,value|
            scp.upload!(att.path(style), File.join(PaperclipOnAkamai::CONFIG["remote_path"],att.url(style).split("?").first))
          end
        end
        self.send("#{paperclip_attachment}_on_akamai=",true)
        self.save
      rescue Exception => e
        puts e.inspect
        self.send("#{paperclip_attachment}_on_akamai=",false)
      end
    end

    def akamai_asset_url(url, paperclip_attachment)
      if PaperclipOnAkamai::CONFIG["enabled"] && self.send("#{paperclip_attachment}_on_akamai?")
        return PaperclipOnAkamai::CONFIG["web_host"]+"/"+PaperclipOnAkamai::CONFIG["remote_path"]+url
      else
        url
      end
    end

    def randomize_poaasset_file_name(paperclip_attachment)
      extension = File.extname(self.send("#{paperclip_attachment}_file_name"))
      filename = File.basename(self.send("#{paperclip_attachment}_file_name"), extension)
      self.send(paperclip_attachment).instance_write(:file_name, "#{filename}_#{ActiveSupport::SecureRandom.hex.first(8)}#{extension}")
    end
  end

end

autoload :ActiveRecord, 'activerecord'

# Set it all up.
if Object.const_defined?("ActiveRecord")
  ActiveRecord::Base.send(:include, PaperclipOnAkamai)
  PaperclipOnAkamai::CONFIG = YAML::load_file(File.join(RAILS_ROOT, 'config', 'akamai.yml'))[RAILS_ENV]
  PaperclipOnAkamai::CONFIG["key"] = File.join(RAILS_ROOT,PaperclipOnAkamai::CONFIG["key"]) if PaperclipOnAkamai::CONFIG["key"].present?
end


text:
package com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa;

/*
 */

import com.espirit.moddev.examples.uxbridge.newsdrilldown.News;
import com.espirit.moddev.examples.uxbridge.newsdrilldown.NewsCategory;
import com.espirit.moddev.examples.uxbridge.newsdrilldown.NewsMetaCategory;
import com.espirit.moddev.examples.uxbridge.newsdrilldown.entity.UXBCategory;
import com.espirit.moddev.examples.uxbridge.newsdrilldown.entity.UXBEntity;
import com.espirit.moddev.examples.uxbridge.newsdrilldown.entity.UXBMetaCategory;
import com.mongodb.*;

import org.apache.camel.CamelContext;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.util.ArrayList;

/**
 * This class has the ability to add, delete and cleanup data records in a
 * mongoDB database which might be used as content-repository for an UX-Bridge
 * application.
 *
 */
public class NewsHandler {

	/**
	 * The Constant logger.
	 */
	private static final Logger logger = Logger.getLogger(NewsHandler.class);

	/**
	 * The Constant NEWS_COLLECTION_NAME contains the name of the collection to
	 * store the news in
	 */
	public static final String NEWS_COLLECTION_NAME = "news";

	/**
	 * The Constant CATEGORY_COLLECTION_NAME contains the name of the collection
	 * to store the categories in
	 */
	public static final String CATEGORY_COLLECTION_NAME = "category";

	/**
	 * The Constant META_CATEGORY_COLLECTION_NAME contains the name of the
	 * collection to store the metacategories in
	 */
	public static final String META_CATEGORY_COLLECTION_NAME = "metaCategory";

	/**
	 * The Constant DESTINATION contains the destination of the messages coming
	 * from the broker.
	 */
	private static final String DESTINATION = "mongodb";

	/**
	 * The Mongo object.
	 */
	private Mongo m;

	/**
	 * The database.
	 */
	private DB mdb;

	/**
	 * The DBCollection to store the news in
	 */
	private DBCollection dbNews;

	/**
	 * The DBCollection to store the categories in
	 */
	private DBCollection dbCategories;

	/**
	 * The DBCollection to store the metacategories in
	 */
	private DBCollection dbMetaCategories;

	/**
	 * The webpath.
	 */
	private String webpath;

	/**
	 * Instantiates a new news handler.
	 *
	 * @param host
	 *            Host the mongodb is running
	 * @param port
	 *            Port of the mongodb
	 * @param db
	 *            The name of the mongodb
	 * @throws Exception
	 *             Exception will thrown an database errors
	 * @param webpath
	 *            the webpath
	 */
	public NewsHandler(String host, int port, String db, String webpath) throws Exception {
		this.webpath = webpath;

		m = new Mongo(host, port);
		mdb = m.getDB(db);
		dbNews = mdb.getCollection(NEWS_COLLECTION_NAME);
		dbCategories = mdb.getCollection(CATEGORY_COLLECTION_NAME);
		dbMetaCategories = mdb.getCollection(META_CATEGORY_COLLECTION_NAME);
	}

	/**
	 * Instantiates a new news handler.
	 */
	public NewsHandler() {
	}

	/**
	 * The destroy method of the class
	 */
	public void destroy() {
		if (m != null) {
			m.close();
		}
	}

	/**
	 * Add or update a newsdrilldown item in the db
	 *
	 * @param entity
	 *            The NewsItem
	 * @throws Exception
	 */
	public void add(UXBEntity entity) throws Exception {

		if (entity == null) {
			logger.warn("no UXBEntity given, no action");
			return;
		}

		News news = buildNews(entity);
		handleNews(news);

	}

	/**
	 * Deletes an item from the db
	 *
	 * @param entity
	 *            The item to delete
	 * @throws IOException
	 */
	public void delete(UXBEntity entity) throws IOException {
		if (entity == null) {
			logger.warn("no UXBEntity given, no action");
			return;
		}

		// delete item
		DBObject item = getNewsById(Long.parseLong(entity.getUuid()),
				entity.getLanguage());
		if (item != null) {
			// delete file from filesystem
			URL url = new URL((String) item.get("url"));
			File file = new File(webpath + url.getPath());
			if (file.exists()) {
				// Try acquiring the lock without blocking. This method returns
				// null or throws an exception if the file is already locked.
				try {
					FileChannel channel = new RandomAccessFile(file, "rw")
							.getChannel();
					// Try to lock the file
					FileLock lock = channel.tryLock();
					// Delete the file
					boolean deleteSuccess = file.delete();
					if (!deleteSuccess) {
						logger.debug("Couldn't delete file, file not found. Maybe someone else has deleted it.");
					}
					// Release the lock
					lock.release();
					lock.channel().close();
				} catch (OverlappingFileLockException e) {
					logger.info("File is already locked in this thread or virtual machine");
				}
			}
			// delete the article
			DBObject query = new BasicDBObject();
			query.put("_id", item.get("_id"));
			query.put("fs_id", item.get("fs_id"));
			query.put("language", item.get("language"));
			dbNews.remove(query);
		}

	}

	/**
	 * Deletes every item older than the creationTime of the UXBEntity.
	 *
	 * @param entity
	 *            Entity containing the expireDate (= createTime of the entity)
	 */
	public void cleanup(UXBEntity entity) {

		if (entity == null) {
			logger.warn("no UXBEntity given, no action");
			return;
		}

		// delete newsdrilldown
		DBCursor items = getNewsByLastmodified(entity.getCreateTime());
		for (DBObject item : items) {
			DBObject query = new BasicDBObject();
			query.put("_id", item.get("_id"));
			query.put("fs_id", item.get("fs_id"));
			query.put("language", item.get("language"));
			dbNews.remove(query);
		}

		// delete categories
		items = getCategoriesByLastmodified(entity.getCreateTime());
		for (DBObject item : items) {
			DBObject query = new BasicDBObject();
			query.put("_id", item.get("_id"));
			query.put("fs_id", item.get("fs_id"));
			query.put("language", item.get("language"));
			dbCategories.remove(query);
		}

		// delete metaCategories
		items = getMetaCategoriesByLastmodified(entity.getCreateTime());
		for (DBObject item : items) {
			DBObject query = new BasicDBObject();
			query.put("_id", item.get("_id"));
			query.put("fs_id", item.get("fs_id"));
			query.put("language", item.get("language"));
			dbMetaCategories.remove(query);
		}

	}

	/**
	 * handle the update and save process for the news.
	 *
	 * @param news
	 *            the News object
	 * @throws Exception
	 *             the exception
	 */
	private void handleNews(News news) throws Exception {

		// 1. save the product
		DBObject item = getNewsById(news.getFs_id(), news.getLanguage());
		if (item != null) {
			item.put("fs_id", news.getFs_id());
			item.put("language", news.getLanguage());
			item.put("headline", news.getHeadline());
			item.put("subHeadline", news.getSubheadline());
			item.put("headline", news.getHeadline());
			item.put("teaser", news.getTeaser());
			item.put("content", news.getContent());
			item.put("date", news.getDate());
			item.put("url", news.getUrl());
			item.put("version", news.getVersion());
			item.put("lastmodified", news.getLastmodified());

			BasicDBObject query = new BasicDBObject();
			news.setId((Long) item.get("_id"));
			query.put("_id", news.getId());

			dbNews.update(query, item);
		} else {
			item = new BasicDBObject();

			item.put("fs_id", news.getFs_id());
			item.put("language", news.getLanguage());
			item.put("headline", news.getHeadline());
			item.put("subHeadline", news.getSubheadline());
			item.put("headline", news.getHeadline());
			item.put("teaser", news.getTeaser());
			item.put("content", news.getContent());
			item.put("date", news.getDate());
			item.put("url", news.getUrl());
			item.put("version", news.getVersion());
			item.put("lastmodified", news.getLastmodified());

			news.setId(generateIdentifier(NEWS_COLLECTION_NAME, mdb));
			item.put("_id", news.getId());

			dbNews.insert(item);
		}

		// 2. save categories
		// add categories to news
		BasicDBList catList = new BasicDBList();
		if (news.getCategories() != null) {
			for (NewsCategory cat : news.getCategories()) {
				handleCategory(cat, news);

				DBObject tmpCat = getCategoryById(cat.getFs_id(), cat.getLanguage());
				//catList.add(new DBRef(this.mdb, this.CATEGORY_COLLECTION_NAME, tmpCat.get("_id")));
				catList.add(tmpCat.get("_id"));
			}
		}

		// add list of categories to the news
//		item.put("categories", catList);
		item.put("categories_$$manyToManyIds", catList);

		BasicDBObject query = new BasicDBObject();
		query.put("_id", news.getId());

		dbNews.update(query, item);
	}

	/**
	 * handle the update and save process for the categories.
	 *
	 * @param category
	 *            the NewsCategory object
	 * @param news
	 *            the News object to reference to
	 * @throws Exception
	 *             the exception
	 */
	private void handleCategory(NewsCategory category, News news)
			throws Exception {

		// 1. save the category
		DBObject item = getCategoryById(category.getFs_id(),
				category.getLanguage());

		if (item != null) {
			item.put("fs_id", category.getFs_id());
			item.put("language", category.getLanguage());
			item.put("name", category.getName());
			item.put("version", category.getVersion());
			item.put("lastmodified", category.getLastmodified());

			// newsdrilldown
//			DBObject tmpNews = getNewsById(news.getFs_id(), news.getLanguage());
//			if (tmpNews != null) {
//				DBRef ref = new DBRef(mdb, NEWS_COLLECTION_NAME,
//						tmpNews.get("_id"));
//				item.put("newsdrilldown", ref);
//			}

			BasicDBObject query = new BasicDBObject();
			category.setId((Long) item.get("_id"));
			query.put("_id", category.getId());

			dbCategories.update(query, item);
		} else {
			item = new BasicDBObject();

			item.put("fs_id", category.getFs_id());
			item.put("language", category.getLanguage());
			item.put("name", category.getName());
			item.put("version", category.getVersion());
			item.put("lastmodified", category.getLastmodified());

			// newsdrilldown
//			DBObject tmpNews = getNewsById(news.getFs_id(), news.getLanguage());
//			if (tmpNews != null) {
//				DBRef ref = new DBRef(mdb, NEWS_COLLECTION_NAME,
//						tmpNews.get("_id"));
//				item.put("newsdrilldown", ref);
//			}

			category.setId(generateIdentifier(CATEGORY_COLLECTION_NAME, mdb));
			item.put("_id", category.getId());

			dbCategories.insert(item);
		}

		// 2. save the metaCategories
		if (category.getMetaCategories() != null) {

			BasicDBList metaCatlist = (BasicDBList) item.get("metaCategories_$$manyToManyIds");
			if (metaCatlist == null) {
				metaCatlist = new BasicDBList();
			}

			for (NewsMetaCategory metaCat : category.getMetaCategories()) {
				handleMetaCategory(metaCat, category);

				if (!metaCatlist.contains(metaCat.getId())) {
					metaCatlist.add(metaCat.getId());
				}

				DBObject obj = getMetaCategoryById(metaCat.getFs_id(), metaCat.getLanguage());

				//BasicDBList catlist = (BasicDBList) obj.get("categories");
				BasicDBList catlist = (BasicDBList) obj.get("categories_$$manyToManyIds");
				if (catlist == null) {
					catlist = new BasicDBList();
				}

				//DBRef catRef = new DBRef(this.mdb, this.CATEGORY_COLLECTION_NAME, category.getId());
				if (!catlist.contains(category.getId())) {
					catlist.add(category.getId());
				}

				obj.put("categories_$$manyToManyIds", catlist);

				BasicDBObject query = new BasicDBObject();
				query.put("_id", (Long) obj.get("_id"));

				dbMetaCategories.update(query, obj);
			}

			item.put("metaCategories_$$manyToManyIds", metaCatlist);

			BasicDBObject query = new BasicDBObject();
			query.put("_id", (Long) item.get("_id"));

			dbCategories.update(query, item);
		}

	}

	/**
	 * handle the update and save process for the metacategories.
	 *
	 * @param metaCat
	 *            the NewsMetaCategory object
	 * @param category
	 *            the NewsCategory object to reference to
	 * @throws Exception
	 *             the exception
	 */
	private void handleMetaCategory(NewsMetaCategory metaCat,
			NewsCategory category) {
		DBObject item = getMetaCategoryById(metaCat.getFs_id(),
				metaCat.getLanguage());

		if (item != null) {
			item.put("fs_id", metaCat.getFs_id());
			item.put("language", metaCat.getLanguage());
			item.put("name", metaCat.getName());
			item.put("version", metaCat.getVersion());
			item.put("lastmodified", metaCat.getLastmodified());

			// category
			DBObject cat = getCategoryById(category.getFs_id(),
					category.getLanguage());
			if (cat != null) {
				DBRef ref = new DBRef(mdb, CATEGORY_COLLECTION_NAME,
						cat.get("_id"));
				item.put("category", ref);
			}

			BasicDBObject query = new BasicDBObject();
			query.put("_id", item.get("_id"));
			dbMetaCategories.update(query, item);
		} else {
			item = new BasicDBObject();

			item.put("fs_id", metaCat.getFs_id());
			item.put("language", metaCat.getLanguage());
			item.put("name", metaCat.getName());
			item.put("version", metaCat.getVersion());
			item.put("lastmodified", metaCat.getLastmodified());

			// category
			DBObject cat = getCategoryById(category.getFs_id(),
					category.getLanguage());
			if (cat != null) {
				DBRef ref = new DBRef(mdb, CATEGORY_COLLECTION_NAME,
						cat.get("_id"));
				item.put("category", ref);
			}

			item.put("_id",
					generateIdentifier(META_CATEGORY_COLLECTION_NAME, mdb));

			dbMetaCategories.insert(item);
		}
	}

	/**
	 * loads a news by the document id
	 *
	 * @param id
	 *            the id of the document
	 * @param language
	 *            language abbreviation like EN or DE
	 * @return the document or null
	 */
	private DBObject getNewsById(Long id, String language) {
		BasicDBObject query = new BasicDBObject();
		query.put("fs_id", id);
		query.put("language", language);

		DBCursor cur = dbNews.find(query);

		if (cur.hasNext()) {
			return cur.next();
		}
		return null;
	}

	/**
	 * loads a category by the document id
	 *
	 * @param id
	 *            the id of the document
	 * @param language
	 *            language abbreviation like EN or DE
	 * @return the document or null
	 */
	private DBObject getCategoryById(Long id, String language) {
		BasicDBObject query = new BasicDBObject();
		query.put("fs_id", id);
		query.put("language", language);

		DBCursor cur = dbCategories.find(query);

		if (cur.hasNext()) {
			return cur.next();
		}
		return null;
	}

	/**
	 * loads a metacategory by the document id
	 *
	 * @param id
	 *            the id of the document
	 * @param language
	 *            language abbreviation like EN or DE
	 * @return the document or null
	 */
	private DBObject getMetaCategoryById(Long id, String language) {
		BasicDBObject query = new BasicDBObject();
		query.put("fs_id", id);
		query.put("language", language);

		DBCursor cur = dbMetaCategories.find(query);

		if (cur.hasNext()) {
			return cur.next();
		}
		return null;
	}

	/**
	 * loads newsdrilldown by lastmodified date
	 *
	 * @param expiredate
	 *            date of expiration
	 * @return the documents or null
	 */
	private DBCursor getNewsByLastmodified(long expiredate) {
		BasicDBObject query = new BasicDBObject();
		query.put("lastmodified", new BasicDBObject("$lt", expiredate));

		return dbNews.find(query);
	}

	/**
	 * loads categories by lastmodified date
	 *
	 * @param expiredate
	 *            date of expiration
	 * @return the documents or null
	 */
	private DBCursor getCategoriesByLastmodified(long expiredate) {
		BasicDBObject query = new BasicDBObject();
		query.put("lastmodified", new BasicDBObject("$lt", expiredate));

		return dbCategories.find(query);
	}

	/**
	 * loads metacategories by lastmodified date
	 *
	 * @param expiredate
	 *            date of expiration
	 * @return the documents or null
	 */
	private DBCursor getMetaCategoriesByLastmodified(long expiredate) {
		BasicDBObject query = new BasicDBObject();
		query.put("lastmodified", new BasicDBObject("$lt", expiredate));

		return dbMetaCategories.find(query);
	}

	/**
	 * builds the news for the UXBEntity JAXB-Entity
	 *
	 * @param entity
	 *            The UXBEntity
	 * @return a new News instance
	 */
	public News buildNews(UXBEntity entity) {
		News news = new News();
		news.setFs_id(Long.parseLong(entity.getUuid()));
		news.setContent(entity.getUxb_content().getContent());
		news.setDate(entity.getUxb_content().getDate());
		news.setHeadline(entity.getUxb_content().getHeadline());
		news.setSubheadline(entity.getUxb_content().getSubHeadline());
		news.setTeaser(entity.getUxb_content().getTeaser());
		news.setLanguage(entity.getUxb_content().getLanguage());
		news.setUrl(entity.getUxb_content().getUrl());
		news.setVersion(1);
		news.setLastmodified(entity.getCreateTime());

		news.setCategories(new ArrayList<NewsCategory>());
		// add categories
		if (entity.getUxb_content().getMetaCategories() != null) {
			for (UXBMetaCategory uxMetaCat : entity.getUxb_content()
					.getMetaCategories()) {
				if (uxMetaCat.getCategories() != null) {
					for (UXBCategory uxCat : uxMetaCat.getCategories()) {
						NewsCategory newsCat = buildNewsCategory(uxCat, entity);
						news.getCategories().add(newsCat);
					}
				}
			}
		}

		return news;
	}

	/**
	 * builds the category for the UXBCategory JAXB-Entity
	 *
	 * @param uxCat
	 *            The UXBCategory
	 * @param entity
	 *            The UXBEntity
	 * @return a new NewsCategory instance
	 */
	private NewsCategory buildNewsCategory(UXBCategory uxCat, UXBEntity entity) {
		NewsCategory newsCat = new NewsCategory();
		newsCat.setMetaCategories(new ArrayList<NewsMetaCategory>());
		newsCat.setFs_id(Long.parseLong(uxCat.getFs_id()));
		newsCat.setLanguage(entity.getLanguage());
		newsCat.setName(uxCat.getName());
		newsCat.setVersion(1);
		newsCat.setLastmodified(entity.getCreateTime());

		newsCat.setMetaCategories(new ArrayList<NewsMetaCategory>());

		if (entity.getUxb_content().getMetaCategories() != null) {
			for (UXBMetaCategory uxMetaCat : entity.getUxb_content()
					.getMetaCategories()) {
				newsCat.getMetaCategories().add(
						buildNewsMetaCategory(uxMetaCat, entity));
			}
		}

		return newsCat;
	}

	/**
	 * builds the metacategory for the UXBCategory JAXB-Entity
	 *
	 * @param uxMetaCat
	 *            The UXBMetaCategory
	 * @param entity
	 *            The UXBEntity
	 * @return a new NewsMetaCategory instance
	 */
	private NewsMetaCategory buildNewsMetaCategory(UXBMetaCategory uxMetaCat,
			UXBEntity entity) {
		NewsMetaCategory newsMetaCategory = new NewsMetaCategory();
		newsMetaCategory.setFs_id(Long.parseLong(uxMetaCat.getFs_id()));
		newsMetaCategory.setName(uxMetaCat.getName());
		newsMetaCategory.setLanguage(entity.getLanguage());
		newsMetaCategory.setVersion(1);
		newsMetaCategory.setLastmodified(entity.getCreateTime());

		return newsMetaCategory;
	}

	/**
	 * Mongo ID generation like it is done in the grails gorm framework
	 *
	 * @param collectionName
	 *            The name of the collection the id should be generated for
	 * @param db
	 *            The mongodb connection
	 * @return a new id
	 */
	private Long generateIdentifier(String collectionName, DB db) {

		// get or create the Collection for the ID storage
		DBCollection dbCollection = db.getCollection(collectionName
				+ ".next_id");
		// create entry to store the newly generated id
		DBObject nativeEntry = new BasicDBObject();

		while (true) {
			DBCursor result = dbCollection.find()
					.sort(new BasicDBObject("_id", -1)).limit(1);

			long nextId;
			if (result.hasNext()) {
				final Long current = (Long) result.next().get("_id");
				nextId = current + 1;
			} else {
				nextId = 1;
			}

			nativeEntry.put("_id", nextId);
			final WriteResult writeResult = dbCollection.insert(nativeEntry);
			final CommandResult lastError = writeResult.getLastError();
			if (lastError.ok()) {
				break;
			}

			final Object code = lastError.get("code");
			// duplicate key error try again
			if (code != null && code.equals(11000)) {
				continue;
			}
			break;
		}

		return (Long) nativeEntry.get("_id");
	}

}


text:
class Spacemonkey < Cask
  version 'latest'
  sha256 :no_check

  url 'http://downloads.spacemonkey.com/client/mac/latest'
  appcast 'https://rink.hockeyapp.net/api/2/apps/aa33b6780fdfc71247b2995fa47b5d7c'
  homepage 'https://www.spacemonkey.com'

  link 'SpaceMonkey.app'
end


text:
const autoprefixer = require('autoprefixer');
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

const NODE_ENV = process.env.NODE_ENV;

const prodPlugins = [
  new webpack.optimize.UglifyJsPlugin({
    compressor: {
      warnings: false,
      screw_ie8: true,
    },
  }),
];
const shared = [
  new webpack.DefinePlugin({
    'process.env.NODE_ENV': JSON.stringify(NODE_ENV),
  }),
  new ExtractTextPlugin('[name].css'),
  new webpack.ProvidePlugin({
    fetch: 'imports?this=>global!exports?global.fetch!whatwg-fetch',
  }),
];
const plugins = NODE_ENV === 'production' ? shared.concat(prodPlugins) : shared;

module.exports = {
  entry: {
    app: path.join(__dirname, 'src', 'index.js'),
  },

  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].js',
    publicPath: '/',
  },

  plugins,

  module: {
    preLoaders: [
      { test: /\.json$/, loader: 'json' },
    ],
    loaders: [
      {
        test: /.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {
          presets: ['es2015', 'react', 'stage-1'],
        },
      },
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract('style', 'css-loader?minimize!postcss-loader'),
      },
    ],
  },
  postcss: () => [autoprefixer],
};


text:
#ifndef SkSVGSVG_DEFINED
#define SkSVGSVG_DEFINED

#include "SkSVGElements.h"

class SkSVGSVG : public SkSVGElement {
    DECLARE_SVG_INFO(SVG);
    virtual bool isFlushable();
private:
    SkString f_enable_background;
    SkString f_height;
    SkString f_overflow;
    SkString f_width;
    SkString f_version;
    SkString f_viewBox;
	SkString f_x;
    SkString f_xml_space;
    SkString f_xmlns;
    SkString f_xml_xlink;
	SkString f_y;

    typedef SkSVGElement INHERITED;
};

#endif // SkSVGSVG_DEFINED