text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2017 The Android Open Source Project

     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.
-->

<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/coordinator_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

  <androidx.core.widget.NestedScrollView
      android:id="@+id/scrolling_content"
      android:layout_width="match_parent"
      android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/scrolling_content_inner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

      <TextView
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:gravity="center_horizontal"
          android:text="@string/scroll_top"/>

      <TextView
          android:id="@+id/textview_dialogue"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:padding="16dp"
          android:textSize="48sp"/>

      <TextView
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:gravity="center_horizontal"
          android:text="@string/scroll_bottom"/>

    </LinearLayout>

  </androidx.core.widget.NestedScrollView>

  <com.google.android.material.bottomnavigation.BottomNavigationView
      android:id="@+id/bottom_navigation"
      android:layout_width="match_parent"
      android:layout_height="56dp"
      android:layout_gravity="bottom"
      app:itemBackground="@color/sand_default"
      app:itemIconTint="@color/emerald_translucent"
      app:itemTextColor="@color/emerald_text"
      app:layout_behavior="@string/hide_bottom_view_on_scroll_behavior"
      app:menu="@menu/bottom_navigation_view_content"/>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

redpajama_set_name: RedPajamaGithub


text:
package backtype.storm.utils;

import clojure.lang.IFn;
import java.util.TimerTask;

public class ClojureTimerTask extends TimerTask {
	IFn _afn;

	public ClojureTimerTask(IFn afn) {
		super();
		_afn = afn;
	}

	@Override
	public void run() {
		_afn.run();
	}
}


text:
/**
 *
 */
/**
 * @author Eric Peng
 *
 */
package org.colorcoding.ibas.bobas.test.messages;

import org.colorcoding.ibas.bobas.messages.RuntimeLog;

import junit.framework.TestCase;

public class testRuntimeLog extends TestCase {

    public void testMultiLogSave() throws InterruptedException {
        int theadCount = 99;

        for (int i = 0; i < theadCount; i++) {
            Thread threads = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        testRuntimeLogSave();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, String.valueOf(i));
            threads.start();
        }
        Thread.sleep(120000);
        System.out.println("主线程结束!");
    }

    public void testRuntimeLogSave() throws InterruptedException {
        for (int i = 0; i < 1000000; i++) {
            RuntimeLog.log("message [%s] by [%s]", i, Thread.currentThread().getName());
        }
        // Thread.sleep(10000);
    }
}


text:
package com.github.onsdigital.babbage.api.endpoint.search;

import com.github.davidcarboni.restolino.framework.Api;
import com.github.onsdigital.babbage.api.util.SearchRendering;
import com.github.onsdigital.babbage.api.util.SearchUtils;

import com.github.onsdigital.babbage.response.BabbageRedirectResponse;
import com.github.onsdigital.babbage.response.base.BabbageResponse;
import com.github.onsdigital.babbage.search.helpers.ONSQuery;
import com.github.onsdigital.babbage.search.helpers.base.SearchQueries;
import com.github.onsdigital.babbage.search.input.TypeFilter;
import com.github.onsdigital.babbage.search.model.ContentType;
import com.github.onsdigital.babbage.search.model.SearchResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static com.github.onsdigital.babbage.configuration.ApplicationConfiguration.appConfig;
import static com.github.onsdigital.babbage.search.builders.ONSQueryBuilders.*;
import static com.github.onsdigital.babbage.search.helpers.SearchRequestHelper.extractPage;
import static com.github.onsdigital.babbage.search.helpers.SearchRequestHelper.extractSearchTerm;
import static org.apache.commons.lang.ArrayUtils.isEmpty;

@Api
public class Search {

    // available allFilters on the page
    private static Set<TypeFilter> allFilters = TypeFilter.getAllFilters();
    private static ContentType[] contentTypesToCount = TypeFilter.contentTypes(allFilters);

    @GET
    public void get(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String searchTerm = extractSearchTerm(request);
        String[] filter = request.getParameterValues("filter");
        boolean searchAdditionalContent = false;
        if (extractPage(request) == 1 && isEmpty(filter)) {
            searchAdditionalContent = true;
        }

        BabbageResponse babbageResponse;
        String timeSeriesRedirect = SearchUtils.getRedirectWhenTimeSeries(request, searchTerm);
        if (timeSeriesRedirect != null) {
            babbageResponse =
                    new BabbageRedirectResponse(
                            timeSeriesRedirect,
                            appConfig().babbage().getSearchResponseCacheTime());
        } else {
            Map<String, SearchResult> results =
                    SearchUtils.search(
                            searchTerm,
                            queries(request, searchTerm, searchAdditionalContent),
                            searchAdditionalContent);
            babbageResponse = SearchRendering.buildResponse(request, getClass().getSimpleName(), results);
        }
        babbageResponse.apply(request, response);
    }

    private SearchQueries queries(HttpServletRequest request, String searchTerm, boolean searchAdditionalContent) {
        ONSQuery query = SearchUtils.buildSearchQuery(request, searchTerm, allFilters);
        List<ONSQuery> queries = toList(query, typeCountsQuery(query.query()).types(contentTypesToCount));
        if (searchAdditionalContent) {
            queries.add(bestTopicMatchQuery(searchTerm).name("featuredResult").highlight(true));
        }
        return () -> queries;
    }
}


text:
import time

def wait_for_transaction(blockchain_client, txn_hash, max_wait=60, sleep_time=5):
    start = time.time()
    while True:
        txn_receipt = blockchain_client.get_transaction_receipt(txn_hash)
        if txn_receipt is not None:
            break
        elif time.time() > start + max_wait:
            raise ValueError("Could not get transaction receipt")
        time.sleep(sleep_time)
    return txn_receipt

def wait_for_block(blockchain_client, block_number, max_wait=60, sleep_time=5):
    start = time.time()
    while time.time() < start + max_wait:
        latest_block_number = blockchain_client.get_block_number()
        if latest_block_number >= block_number:
            break
        time.sleep(sleep_time)
    else:
        raise ValueError("Did not reach block")
    return blockchain_client.get_block_by_number(block_number)

def get_max_gas(blockchain_client):
    latest_block = blockchain_client.get_block_by_number('latest')
    max_gas_hex = latest_block['gasLimit']
    max_gas = int(max_gas_hex, 16)
    return max_gas

def get_transaction_params(_from=None, to=None, gas=None, gas_price=None,
                           value=0, data=None):
    params = {}

    if _from is None:
        raise ValueError("No default from address specified")

    params['from'] = _from

    if to is None and data is None:
        raise ValueError("A `to` address is only optional for contract creation")
    elif to is not None:
        params['to'] = to

    if gas is not None:
        params['gas'] = hex(gas)

    if gas_price is not None:
        params['gasPrice'] = hex(gas_price)

    if value is not None:
        params['value'] = hex(value).rstrip('L')

    if data is not None:
        params['data'] = data

    return params

def construct_filter_args(from_block=None, to_block=None, address=None,
                          topics=None):
    params = {}
    if from_block is not None:
        params["fromBlock"] = from_block
    if to_block is not None:
        params["toBlock"] = to_block
    if address is not None:
        params["address"] = address
    if topics is not None:
        params["topics"] = topics
    return(params)


text:
/*global Reply*/
/**

  A Gambit is a Trigger + Reply or Reply Set
  - We define a Reply as a subDocument in Mongo.

**/

// var regexreply = require("../parse/regexreply");

module.exports = function (mongoose, facts) {
  var Utils = require("../utils");
  var regexreply = require("../parse/regexreply");
  var debug = require("debug")("Gambit");
  var norm = require("node-normalizer");
  var findOrCreate = require("mongoose-findorcreate");
  var gNormalizer;

  norm.loadData(function () {
    gNormalizer = norm;
    debug("Normaizer Loaded.");
  });

  /**

    I trigger is the matching rule behind a piece of input. It lives in a topic or several topics.
    A trigger also contains one or more replies.

  **/

  var gambitSchema = new mongoose.Schema({
    id: {type: String, index: true, default: Utils.genId()},

    // This is the input string that generates a rule,
    // In the event we want to export this, we will use this value.
    // Make this filed conditionally required if trigger is supplied
    input: {type: String},

    // The Trigger is a partly baked regex.
    trigger: {type: String, index: true},

    // If the trigger is a Question Match
    isQuestion: {type: Boolean, default: false},

    // If the trigger is a Answer Type Match
    qType: {type: String, default: ""},
    qSubType: {type: String, default: ""},

    // The filter function for the the expression
    filter: {type: String, default: ""},

    // An array of replies.
    replies: [{ type: String, ref: "Reply"}],

    // replies: [Reply.schema],

    // This will redirect anything that matches elsewhere.
    // If you want to have a conditional rediect use reply redirects
    // TODO, change the type to a ID and reference another gambit directly
    // this will save us a lookup down the road (and improve performace.)
    redirect: {type: String, default: ""}
  });

  gambitSchema.pre("save", function (next) {
    var self = this;

    // FIXME: This only works when the replies are populated which is not always the case.
    // self.replies = _.uniq(self.replies, function(item, key, id) {
    //   return item.id;
    // });

    // If input was supplied, we want to use it to generate the trigger
    if (self.input) {
      var input = gNormalizer.clean(self.input);
      // We want to convert the input into a trigger.
      regexreply.parse(Utils.quotemeta(input, true), facts, function (trigger) {
        self.trigger = trigger;
        next();
      });
    } else {
      // Otherwise we populate the trigger normally
      next();
    }
  });

  gambitSchema.methods.addReply = function (replyData, callback) {
    var self = this;
    if (!replyData) {
      return callback("No data");
    }

    var reply = new Reply(replyData);
    reply.save(function (err) {
      if (err) {
        return callback(err);
      }

      self.replies.addToSet(reply._id);
      self.save(function (err2) {
        callback(err2, reply);
      });
    });
  };

  // TODO - Test against Qtypes too.
  gambitSchema.methods.doesMatch = function (message, cb) {
    var self = this;
    var match = false;
    regexreply.postParse(this.trigger, message, null, function (regexp) {
      var compiledRE = new RegExp("^" + regexp + "$", "i");
      debug("clean'" + message.clean + "' against " + self.trigger + " (" + regexp + ")");
      debug("lemma'" + message.lemString + "' against " + self.trigger + " (" + regexp + ")");

      match = message.clean.match(compiledRE);
      if (!match) {
        match = message.lemString.match(compiledRE);
      }
      cb(null, match);
    });
  };

  gambitSchema.plugin(findOrCreate);

  try {
    return mongoose.model("Gambit", gambitSchema);
  } catch(e) {
    return mongoose.model("Gambit");
  }
};


text:
package eu.leads.processor.common.continuous;

import eu.leads.processor.plugins.EventType;

import java.io.IOException;
import java.io.ObjectStreamException;
import java.io.Serializable;

/**
 * Created by vagvaz on 10/5/15.
 */
public class EventTriplet implements Serializable {
  EventType type;
  Object key;
  Object value;

  public EventTriplet(EventType type, Object key, Object value){
    this.type = type;
    this.key = key;
    this.value = value;
  }
  public EventType getType() {
    return type;
  }

  public void setType(EventType type) {
    this.type = type;
  }

  public Object getKey() {
    return key;
  }

  public void setKey(Object key) {
    this.key = key;
  }

  public Object getValue() {
    return value;
  }

  public void setValue(Object value) {
    this.value = value;
  }

   private void writeObject(java.io.ObjectOutputStream out)   throws IOException {
     out.writeInt(type.getValue());
     out.writeObject(key);
     out.writeObject(value);
   }
   private void readObject(java.io.ObjectInputStream in)
       throws IOException, ClassNotFoundException{
     int typeInt = in.readInt();
     switch (typeInt){
       case 1:
         type = EventType.CREATED;
         break;
       case 2:
         type = EventType.MODIFIED;
         break;
       case 3:
         type = EventType.REMOVED;
         break;
       default:
         type = EventType.CREATED;
         break;
     }
     key = in.readObject();
     value = in.readObject();
   }
   private void readObjectNoData()
       throws ObjectStreamException {
     type = null;
     key =null;
     value = null;
   }
}


text:
package org.hirschhorn.puertorico.constants;

public enum BuildingType {
  SmallIndigoPlant,
  LargeIndigoPlant,
  SmallSugarMill,
  LargeSugarMill,
  TobbacoPlant,
  CoffeStorage,
  SmallMarket,
  Hacienda,
  ConstructionHut,
  SmallWarehouse,
  Hospice,
  Office,
  LargeMarket,
  LargeWharehouse,
  Factory,
  University,
  Harbor,
  Wharf,
  GuildHall,
  Residence,
  Fortress,
  CityHall,
  CustomsHouse;
}


text:
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Main where

import Test.Framework (defaultMain, testGroup, Test)
import Test.Framework.Providers.QuickCheck2 (testProperty)

import qualified Data.Identifiers.Hashable as H
import qualified Data.Identifiers.ListLike as L

main :: IO ()
main = defaultMain tests

tests :: [Test]
tests = [ testGroup "QuickCheck Data.Identifiers.Hashable"
            [ testProperty "hasId"                H.prop_hasId
            , testProperty "stableId"             H.prop_stableId
            , testProperty "keyRetrieval"         H.prop_keyRetrieval
            , testProperty "keyRetrievalUnsafe"   H.prop_keyRetrievalUnsafe
            , testProperty "idempotent"           H.prop_idempotent
            , testProperty "stableCombine"        H.prop_stableCombine
            , testProperty "propermigration"      H.prop_properMigration
            ]
        , testGroup "QuickCheck Data.Identifiers.ListLike"
            [ testProperty "hasId"                L.prop_hasId
            , testProperty "stableId"             L.prop_stableId
            , testProperty "keyRetrieval"         L.prop_keyRetrieval
            , testProperty "keyRetrievalUnsafe"   L.prop_keyRetrievalUnsafe
            , testProperty "idempotent"           L.prop_idempotent
            , testProperty "stableCombine"        L.prop_stableCombine
            , testProperty "propermigration"      L.prop_properMigration
            ]
        ]


text:
from dockyard.utils.wrapper import auth
from tornado.gen import coroutine
from dockyard.service.interface import BaseHandler

class ApiUserAppHandeler(BaseHandler):
    @coroutine
    def get(self, path, *args, **kwargs):
        if path == "list":  return self.get_apps()
        else:               return self.get_app()

    @coroutine
    def post(self, path, *args, **kwargs):
        pass

    @auth
    @coroutine
    def put(self, path, *args, **kwargs):
        pass

    @auth
    @coroutine
    def delete(self, path, *args, **kwargs):
        pass

    def get_app(self):
        pass

    def get_apps(self):
        pass

    def get_status(self):
        pass


text:
package org.jetbrains.plugins.groovy.refactoring.introduce.parameter;

import com.intellij.codeInsight.template.TextResult;
import com.intellij.codeInsight.template.impl.TemplateManagerImpl;
import com.intellij.codeInsight.template.impl.TemplateState;
import com.intellij.openapi.editor.event.DocumentAdapter;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.editor.impl.DocumentMarkupModel;
import com.intellij.openapi.editor.markup.EffectType;
import com.intellij.openapi.editor.markup.HighlighterTargetArea;
import com.intellij.openapi.editor.markup.MarkupModel;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.PsiParameter;
import com.intellij.psi.PsiType;
import com.intellij.refactoring.IntroduceParameterRefactoring;
import com.intellij.refactoring.introduce.inplace.OccurrencesChooser;
import com.intellij.refactoring.rename.inplace.InplaceRefactoring;
import com.intellij.ui.JBColor;
import com.intellij.ui.components.JBCheckBox;
import com.intellij.usageView.UsageInfo;
import com.intellij.util.ArrayUtil;
import gnu.trove.TIntArrayList;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrParametersOwner;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import org.jetbrains.plugins.groovy.refactoring.introduce.GrAbstractInplaceIntroducer;
import org.jetbrains.plugins.groovy.refactoring.introduce.GrIntroduceContext;
import org.jetbrains.plugins.groovy.refactoring.introduce.GrIntroduceHandlerBase;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;

/**
 * Created by Max Medvedev on 9/1/13
 */
public class GrInplaceParameterIntroducer extends GrAbstractInplaceIntroducer<GrIntroduceParameterSettings> {
  private final IntroduceParameterInfo myInfo;
  private final TIntArrayList myParametersToRemove;

  private JBCheckBox myDelegateCB;

  private final LinkedHashSet<String> mySuggestedNames;

  public GrInplaceParameterIntroducer(IntroduceParameterInfo info, GrIntroduceContext context, OccurrencesChooser.ReplaceChoice choice) {
    super(GrIntroduceParameterHandler.REFACTORING_NAME, choice, context);
    myInfo = info;

    GrVariable localVar = GrIntroduceHandlerBase.resolveLocalVar(context);
    mySuggestedNames = GroovyIntroduceParameterUtil.suggestNames(localVar, context.getExpression(), context.getStringPart(), info.getToReplaceIn(), context.getProject());

    myParametersToRemove = new TIntArrayList(GroovyIntroduceParameterUtil.findParametersToRemove(info).getValues());
  }

  @Override
  protected String getActionName() {
    return GrIntroduceParameterHandler.REFACTORING_NAME;
  }

  @Override
  protected String[] suggestNames(boolean replaceAll, @Nullable GrVariable variable) {
    return ArrayUtil.toStringArray(mySuggestedNames);
  }

  @Override
  protected JComponent getComponent() {

    JPanel previewPanel = new JPanel(new BorderLayout());
    previewPanel.add(getPreviewEditor().getComponent(), BorderLayout.CENTER);
    previewPanel.setBorder(new EmptyBorder(2, 2, 6, 2));

    DocumentAdapter documentAdapter = new DocumentAdapter() {
      @Override
      public void documentChanged(DocumentEvent e) {
        final TemplateState templateState = TemplateManagerImpl.getTemplateState(myEditor);
        if (templateState != null) {
          final TextResult value = templateState.getVariableValue(InplaceRefactoring.PRIMARY_VARIABLE_NAME);
          if (value != null) {
            updateTitle(getVariable(), value.getText());
          }
        }
      }
    };
    myEditor.getDocument().addDocumentListener(documentAdapter);

    myDelegateCB = new JBCheckBox("Delegate via overloading method");
    myDelegateCB.setMnemonic('l');
    myDelegateCB.setFocusable(false);

    JPanel panel = new JPanel(new BorderLayout());
    panel.add(previewPanel, BorderLayout.CENTER);
    panel.add(myDelegateCB, BorderLayout.SOUTH);
    return panel;
  }

  @Override
  protected void saveSettings(@NotNull GrVariable variable) {

  }

  @Override
  protected void updateTitle(@Nullable GrVariable variable) {
    if (variable == null) return;
    updateTitle(variable, variable.getName());
  }

  @Override
  protected void updateTitle(@Nullable GrVariable variable, String value) {
    if (getPreviewEditor() == null || variable == null) return;
    final PsiElement declarationScope = ((PsiParameter)variable).getDeclarationScope();
    if (declarationScope instanceof PsiMethod) {
      final PsiMethod psiMethod = (PsiMethod)declarationScope;
      final StringBuilder buf = new StringBuilder();
      buf.append(psiMethod.getName()).append(" (");
      boolean frst = true;
      final List<TextRange> ranges2Remove = new ArrayList<TextRange>();
      TextRange addedRange = null;

      int i = 0;
      for (PsiParameter parameter : psiMethod.getParameterList().getParameters()) {
        if (frst) {
          frst = false;
        }
        else {
          buf.append(", ");
        }
        int startOffset = buf.length();
        /*if (myMustBeFinal || myPanel.isGenerateFinal()) {
          buf.append("final ");
        }*/
        buf.append(parameter.getType().getPresentableText()).append(" ").append(variable == parameter ? value : parameter.getName());
        int endOffset = buf.length();
        if (variable == parameter) {
          addedRange = new TextRange(startOffset, endOffset);
        }
        else if (myParametersToRemove.contains(i)) {
          ranges2Remove.add(new TextRange(startOffset, endOffset));
        }
        i++;
      }

      assert addedRange != null;

      buf.append(")");
      setPreviewText(buf.toString());
      final MarkupModel markupModel = DocumentMarkupModel.forDocument(getPreviewEditor().getDocument(), myProject, true);
      markupModel.removeAllHighlighters();
      for (TextRange textRange : ranges2Remove) {
        markupModel.addRangeHighlighter(textRange.getStartOffset(), textRange.getEndOffset(), 0, getTestAttributesForRemoval(), HighlighterTargetArea.EXACT_RANGE);
      }
      markupModel.addRangeHighlighter(addedRange.getStartOffset(), addedRange.getEndOffset(), 0, getTextAttributesForAdd(), HighlighterTargetArea.EXACT_RANGE);
      //revalidate();
    }
  }

  private static TextAttributes getTextAttributesForAdd() {
    final TextAttributes textAttributes = new TextAttributes();
    textAttributes.setEffectType(EffectType.ROUNDED_BOX);
    textAttributes.setEffectColor(JBColor.RED);
    return textAttributes;
  }

  private static TextAttributes getTestAttributesForRemoval() {
    final TextAttributes textAttributes = new TextAttributes();
    textAttributes.setEffectType(EffectType.STRIKEOUT);
    textAttributes.setEffectColor(JBColor.BLACK);
    return textAttributes;
  }

  @Override
  protected GrVariable runRefactoring(GrIntroduceContext context, GrIntroduceParameterSettings settings, boolean processUsages) {
    GrExpressionWrapper wrapper = createExpressionWrapper(context);
    if (processUsages) {
      GrIntroduceExpressionSettingsImpl patchedSettings =
        new GrIntroduceExpressionSettingsImpl(settings, settings.getName(), settings.declareFinal(), settings.parametersToRemove(),
                                              settings.generateDelegate(), settings.replaceFieldsWithGetters(), context.getExpression(),
                                              context.getVar(), settings.getSelectedType(), context.getVar() != null || settings.replaceAllOccurrences(),
                                              context.getVar() != null, settings.isForceReturn());
      GrIntroduceParameterProcessor processor = new GrIntroduceParameterProcessor(patchedSettings, wrapper);
      processor.run();
    }
    else {
      GrIntroduceParameterProcessor processor = new GrIntroduceParameterProcessor(settings, wrapper);
      processor.performRefactoring(UsageInfo.EMPTY_ARRAY);
    }
    GrParametersOwner owner = settings.getToReplaceIn();
    return ArrayUtil.getLastElement(owner.getParameters());
  }

  @NotNull
  private static GrExpressionWrapper createExpressionWrapper(@NotNull GrIntroduceContext context) {
    GrExpression expression = context.getExpression();
    GrVariable var = context.getVar();
    assert expression != null || var != null ;

    GrExpression initializer = expression != null ? expression : var.getInitializerGroovy();
    return new GrExpressionWrapper(initializer);
  }

  @Nullable
  @Override
  protected GrIntroduceParameterSettings getInitialSettingsForInplace(@NotNull GrIntroduceContext context,
                                                                      @NotNull OccurrencesChooser.ReplaceChoice choice,
                                                                      String[] names) {
    GrExpression expression = context.getExpression();
    GrVariable var = context.getVar();
    PsiType type = var != null ? var.getDeclaredType() :
                   expression != null ? expression.getType() :
                   null;

    return new GrIntroduceExpressionSettingsImpl(myInfo, names[0], false, new TIntArrayList(), false,
                                                 IntroduceParameterRefactoring.REPLACE_FIELDS_WITH_GETTERS_NONE, expression,
                                                 var, type, false, false, false);

  }

  @Override
  protected GrIntroduceParameterSettings getSettings() {
    return new GrIntroduceExpressionSettingsImpl(myInfo, getInputName(), false, myParametersToRemove, myDelegateCB.isSelected(),
                                                 IntroduceParameterRefactoring.REPLACE_FIELDS_WITH_GETTERS_NONE, null,
                                                 null, getSelectedType(), isReplaceAllOccurrences(), false, false);
  }
}


text:
package org.jboss.seam.faces.test.security;

import java.util.Collection;
import java.util.Set;

import org.jboss.seam.security.Authenticator;
import org.jboss.seam.security.Identity;
import org.picketlink.idm.api.Group;
import org.picketlink.idm.api.Role;
import org.picketlink.idm.api.User;

/**
 * @author bleathem
 */
public class IdentityMock implements Identity {

    @Override
    public boolean addGroup(String name, String groupType) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public boolean addRole(String role, String group, String groupType) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void checkGroup(String group, String groupType) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void checkPermission(Object resource, String permission) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void checkRestriction(String expr) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void checkRole(String role, String group, String groupType) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void filterByPermission(Collection<?> collection, String permission) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Class<Authenticator> getAuthenticatorClass() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public String getAuthenticatorName() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Set<Group> getGroups() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Set<Role> getRoles() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public User getUser() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public boolean hasPermission(Object resource, String permission) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public boolean hasRole(String role, String group, String groupType) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public boolean inGroup(String name, String groupType) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public boolean isLoggedIn() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public boolean isVerified() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public String login() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void logout() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void quietLogin() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void removeGroup(String name, String groupType) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void removeRole(String role, String group, String groupType) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void setAuthenticatorClass(Class<? extends Authenticator> authenticatorClass) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void setAuthenticatorName(String authenticatorName) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public boolean tryLogin() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

}


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/action_save"
        android:showAsAction="always"
        android:icon="@drawable/ic_action_save"
        android:title="@string/action_save"
        />
    <item
        android:id="@+id/action_discard"
        android:showAsAction="always"
        android:icon="@drawable/ic_action_discard"
        android:title="@string/action_discard"
        />
</menu>


text:
namespace views {

// static
std::unique_ptr<ViewsTextServicesContextMenu>
ViewsTextServicesContextMenu::Create(ui::SimpleMenuModel* menu,
                                     Textfield* client) {
  return std::make_unique<ViewsTextServicesContextMenuBase>(menu, client);
}

bool ViewsTextServicesContextMenu::IsTextDirectionCheckedForTesting(
    ViewsTextServicesContextMenu* menu,
    base::i18n::TextDirection direction) {
  NOTREACHED();
  return false;
}

}  // namespace views


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Class CommonMessages
   </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Class CommonMessages
   ">
    <meta name="generator" content="docfx 2.28.2.0">

    <link rel="shortcut icon" href="../favicon.ico">
    <link rel="stylesheet" href="../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../styles/docfx.css">
    <link rel="stylesheet" href="../styles/main.css">
    <meta property="docfx:navrel" content="../toc.html">
    <meta property="docfx:tocrel" content="toc.html">

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

              </button>

              <form class="navbar-form navbar-right" role="search" id="search">

                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">

              </form>

          Show / Hide Table of Contents

Class CommonMessages

A static class that defines the common diagnostic messages.

Inheritance

System.Object

CommonMessages

Inherited Members

      System.Object.Equals(System.Object)

      System.Object.Equals(System.Object, System.Object)

      System.Object.GetHashCode()

      System.Object.GetType()

      System.Object.MemberwiseClone()

      System.Object.ReferenceEquals(System.Object, System.Object)

      System.Object.ToString()

Namespace: Juhta.Net.Common

Assembly: Juhta.Net.dll

Syntax

public static class CommonMessages

Fields

    |
    Improve this Doc

    View Source

Error001

Invalid '{0}' parameter value was passed to the method '{1}'. The value cannot be null.

Declaration

public static readonly ErrorMessage Error001

Field Value

        Type
        Description

        ErrorMessage

    |
    Improve this Doc

    View Source

Error002

Value of the parameter '{0}' cannot be an empty string or a string containing nothing but white space
characters.

Declaration

public static readonly ErrorMessage Error002

Field Value

        Type
        Description

        ErrorMessage

    |
    Improve this Doc

    View Source

Error003

File '{0}' could not be locked within a {1} millisecond timeout.

Declaration

public static readonly ErrorMessage Error003

Field Value

        Type
        Description

        ErrorMessage

    |
    Improve this Doc

    View Source

Error004

Portion of the file '{0}' could not be locked within a {1} millisecond timeout.

Declaration

public static readonly ErrorMessage Error004

Field Value

        Type
        Description

        ErrorMessage

    |
    Improve this Doc

    View Source

Error005

Invalid '{0}' parameter value was passed to the method '{1}'. The value '{2}' does not conform to the
regex pattern '{3}'.

Declaration

public static readonly ErrorMessage Error005

Field Value

        Type
        Description

        ErrorMessage

    |
    Improve this Doc

    View Source

Error006

Method '{0}' of the class '{1}' cannot be executed because the current state of the instance doesn't allow
it.

Declaration

public static readonly ErrorMessage Error006

Field Value

        Type
        Description

        ErrorMessage

    |
    Improve this Doc

    View Source

Error007

File '{0}' does not exist.

Declaration

public static readonly ErrorMessage Error007

Field Value

        Type
        Description

        ErrorMessage

    |
    Improve this Doc

    View Source

Error008

Directory '{0}' does not exist.

Declaration

public static readonly ErrorMessage Error008

Field Value

        Type
        Description

        ErrorMessage

    |
    Improve this Doc

    View Source

Error009

Method '{0}' is not supported by the type '{1}'.

Declaration

public static readonly ErrorMessage Error009

Field Value

        Type
        Description

        ErrorMessage

    |
    Improve this Doc

    View Source

Error010

Property '{0}' is not supported by the type '{1}'.

Declaration

public static readonly ErrorMessage Error010

Field Value

        Type
        Description

        ErrorMessage

    |
    Improve this Doc

    View Source

Error011

An error occurred in the closing process of the library '{0}': {1}

Declaration

public static readonly ErrorMessage Error011

Field Value

        Type
        Description

        ErrorMessage

    |
    Improve this Doc

    View Source

Error012

Static method '{0}' of the class '{1}' cannot be executed because the current state of the class doesn't
allow it.

Declaration

public static readonly ErrorMessage Error012

Field Value

        Type
        Description

        ErrorMessage

    |
    Improve this Doc

    View Source

Error013

The lenghts of the arrays '{0}' and '{1}' do not match.

Declaration

public static readonly ErrorMessage Error013

Field Value

        Type
        Description

        ErrorMessage

    |
    Improve this Doc

    View Source

Error014

Only one instance of the singleton class '{0}' is allowed to be created at a time.

Declaration

public static readonly ErrorMessage Error014

Field Value

        Type
        Description

        ErrorMessage

    |
    Improve this Doc

    View Source

Error015

Property '{0}' of an instance of the class '{1}' cannot be executed because the instance has been disposed.

Declaration

public static readonly ErrorMessage Error015

Field Value

        Type
        Description

        ErrorMessage

    |
    Improve this Doc

    View Source

Error016

Method '{0}' of an instance of the class '{1}' cannot be executed because the instance has been disposed.

Declaration

public static readonly ErrorMessage Error016

Field Value

        Type
        Description

        ErrorMessage

    |
    Improve this Doc

    View Source

Error017

An instance of the class '{0}' could not be created because the type was not found in the assembly '{1}'.

Declaration

public static readonly ErrorMessage Error017

Field Value

        Type
        Description

        ErrorMessage

    |
    Improve this Doc

    View Source

Error018

Property '{0}' of the class '{1}' cannot be executed because the current state of the instance doesn't
allow it.

Declaration

public static readonly ErrorMessage Error018

Field Value

        Type
        Description

        ErrorMessage

                    Improve this Doc

                    View Source

              Back to top

            Copyright © 2017-2019 Juha Lähteenmäki
Generated by DocFX


text:
namespace loss
{
    Kernel::Kernel(uint32_t id) :
        _id(id),
        _running(false),
        _process_manager(this),
        _dev_fs(nullptr),
        _tty_device(nullptr),
        _root_user(nullptr),
        _kernel_proc(nullptr),
        _proc_fs(nullptr),
        _keyboard(nullptr)
    {

    }

    ReturnCode Kernel::init()
    {
        if (_vfs.root_filesystem() == nullptr)
        {
            // TODO
            return INTERNAL_ERROR;
        }

        _dev_fs = new loss::RamFileSystem();
        auto result = _vfs.mount("/dev", _dev_fs);
        if (result != SUCCESS)
        {
            return result;
        }

        _tty_device = new KernelStream(this);
        result = _vfs.create_char_device("/dev/tty0", _tty_device);
        if (result != SUCCESS)
        {
            return result;
        }

        //_keyboard = new KeyboardDriver(this, "/dev/kb0");
        _keyboard = new KernelStream(this);
        result = _vfs.create_char_device("/dev/kb0", _keyboard);
        if (result != SUCCESS)
        {
            return result;
        }

        kernel_message(true, "Setup VFS");

        result = _user_manager.create_new_user("root", _root_user);
        if (result != SUCCESS)
        {
            std::string error("Error creating root user: ");
            error += ReturnCodes::desc(result);
            kernel_message(false, error);
            return result;
        }
        kernel_message(true, "Created root user");

        KernelProcess *proc;
        result = _process_manager.create_kernel_proc("/dev/tty0", proc);
        if (result != SUCCESS)
        {
            std::string error("Error creating kernel process: ");
            error += ReturnCodes::desc(result);
            kernel_message(false, error);
            return result;
        }
        kernel_message(true, "Created kernel process");
        _kernel_proc = proc;

        _proc_fs = new ProcFileSystem(this);
        result = _vfs.mount("/proc", _proc_fs);
        if (result != SUCCESS)
        {
            std::string error("Error creating proc filesystem: ");
            error += ReturnCodes::desc(result);
            kernel_message(false, error);
            return result;
        }
        kernel_message(true, "Created proc filesystem");
        _running = true;

        return SUCCESS;
    }
    ReturnCode Kernel::boot()
    {
        IProcess *proc;
        auto proc_result = _process_manager.create_process_from_file("/etc/init.d", "/dev/tty0", _root_user, proc);
        if (proc_result != SUCCESS)
        {
            return proc_result;
        }

        proc_result = _process_manager.create_process_from_file("/etc/long_proc.lua", "/dev/tty0", _root_user, proc);
        if (proc_result != SUCCESS)
        {
            return proc_result;
        }

        proc_result = _process_manager.create_native_process("/dev/tty0", "term", _root_user, proc);
        if (proc_result != SUCCESS)
        {
            return proc_result;
        }

        run();

        return SUCCESS;
    }
    ReturnCode Kernel::shutdown()
    {
        _running = false;
        _process_manager.shutdown();

        return SUCCESS;
    }
    ReturnCode Kernel::run()
    {
        _process_manager.run();

        _running = false;

        return SUCCESS;
    }

    uint32_t Kernel::id() const
    {
        return _id;
    }
    bool Kernel::is_running() const
    {
        return _running;
    }

    VirtualFileSystem &Kernel::virtual_file_system()
    {
        return _vfs;
    }
    const VirtualFileSystem &Kernel::virtual_file_system() const
    {
        return _vfs;
    }

    ProcessManager &Kernel::process_manager()
    {
        return _process_manager;
    }
    const ProcessManager &Kernel::process_manager() const
    {
        return _process_manager;
    }

    UserManager &Kernel::user_manager()
    {
        return _user_manager;
    }
    const UserManager &Kernel::user_manager() const
    {
        return _user_manager;
    }

    User *Kernel::root_user() const
    {
        return _root_user;
    }
    KernelProcess *Kernel::kernel_proc() const
    {
        return _kernel_proc;
    }
    KernelStream *Kernel::tty_device() const
    {
        return _tty_device;
    }
    KernelStream *Kernel::keyboard() const
    {
        return _keyboard;
    }

    void Kernel::kernel_message(bool success, const std::string &message)
    {
        std::stringstream ss;
        ss << "[ " << (success ? "SUCCESS" : "FAIL") << " ] " << message << '\n';
        _tty_device->write(0, ss.str().size(), (const uint8_t *)(ss.str().c_str()));
    }
}


text:
namespace ecomplex
{

class Symbol;

class LoadFromPSD
{
public:
	static void Load(const Json::Value& value, const std::string& dir, Symbol& complex);

private:
	static ee::SprPtr LoadItem(const Json::Value& value, const std::string& dir, int tw, int th);

	static ee::SprPtr LoadGroup(const Json::Value& value, const std::string& dir, int tw, int th);
	static ee::SprPtr LoadLayer(const Json::Value& value, const std::string& dir, int tw, int th);

}; // LoadFromPSD

}

#endif // _EASYCOMPLEX_LOAD_FROM_PSD_H_


text:
var config = require('config').api;
var Data = require('Data');
var r = require('rethinkdb');

function defaultError(res, error) {
	res.status(500).json(error);
}

function defaultQuery(res, query) {
	Data.query(query)
		.then(function(results) {
			res.status(200).json(results);
		})
		.catch(function(error) {
			defaultError(res, error);
		});
}

function coerce(param) {

	if (/\|/.test(param)) {
		var args = param.split('|');

		switch (args[1]) {
			case 'bool':
				if (args[0] === 'true') {
					param = true;
				} else {
					param = false;
				}
				break;
			case 'int':
				param = parseInt(param, 10);
				break;
			case 'float':
				param = parseFloat(param);
				break;
		}

	}

	return param;

}

module.exports = function(app, router) {

	router.route('/:table')
		.get(function(req, res) {

			var query = r.table(req.params.table);

			defaultQuery(res, query);

		});

	router.route('/:table/:id')
		.get(function(req, res) {

			var query = r.table(req.params.table).get(req.params.id);

			defaultQuery(res, query);

		});

	router.route('/:table/:secondary/:tertiary')
		.get(function(req, res) {

			var query = r.table(req.params.table);

			var op = req.params.tertiary.substr(0,1);
			var value = coerce(req.params.tertiary.substr(1));

			if (config.id_regex.test(req.params.secondary)) {
				query = query.get(req.params.secondary).pluck(req.params.tertiary);
			} else if (op === '=') {

				var filter = {};
				filter[req.params.secondary] = value;

				query = query.filter(filter);

			} else if (op === '~') {

				query = query.filter(function(item) {
					return item(req.params.secondary).match(value);
				});

			}

			defaultQuery(res, query);

		});

};


text:
A python script for estimating the Inverse Instantaneous Coalescent Rate (IICR) based on independent values of
the coalescence times, simulated with the ms software.

This is the python script that has been used to estimate the IICRs presented in Lounès 2017 (cite the paper). In order to
run the script, a working compiled version of ms (link to ms) must be placed in the same folder as the script *estimateIICR.py*.

This script illustrates that it is possible to estimate the IICRs courves (which corresponds with the PSMC inferences) for
any model of population genetics for which one can write a ms command. Note that in the case of a *panmictic* model, the
IICR corresponds exactly to the changes in the population size. However, when the panmixia hypothesis is violated, the link
between population size changes and the IICR (that can also be estimated from full genomes using the PSMC) is not clear.
Sometimes, as shown in Mazet et al 2016, the IICR and the population size are inversely related.

What is interested is that the notion of IICR provides a tool for characterizing a wide class of models in population genetics.
This script allows to see the IICR corresponding to any model for wich it is possible to simulate data under ms. Note that the
data used by the script are independent values of coalescence times.

For using the script
--------------------

1. Get a version of ms
2. Set the parameters by modifying the json file
3. Run the script


text:
<?php

namespace Symfony\Bridge\Twig\Node;

/**
 * Compiles a call to {@link FormRendererInterface::renderBlock()}.
 *
 * The function name is used as block name. For example, if the function name
 * is "foo", the block "foo" will be rendered.
 *
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class RenderBlockNode extends \Twig_Node_Expression_Function
{
    public function compile(\Twig_Compiler $compiler)
    {
        $compiler->addDebugInfo($this);
        $arguments = iterator_to_array($this->getNode('arguments'));
        $compiler->write('$this->env->getExtension(\'form\')->renderer->renderBlock(');

        if (isset($arguments[0])) {
            $compiler->subcompile($arguments[0]);
            $compiler->raw(', \''.$this->getAttribute('name').'\'');

            if (isset($arguments[1])) {
                $compiler->raw(', ');
                $compiler->subcompile($arguments[1]);
            }
        }

        $compiler->raw(')');
    }
}


text:
react-menus
===========

> A carefully crafted menu for React

## Install

```sh
$ npm install react-menus --save
```

## Description

The `react-menus` component is a context-menu like widget for React. It features **smart positioning**, overflow **scrolling** on too many menu items and **smart submenu positioning**.

## Changelog

See [Changelog](./CHANGELOG.md)

## Roadmap

See [Roadmap](./ROADMAP.md)

## Usage

```jsx
var items = [
    {
        label: 'hello',
        onClick: function(itemProps, index, event) {
            console.log('well, hello')
        }
    },
    '-', //show separator
    {
        label: 'hi'
    },
    {
		label: 'export',
		disabled: true
	}
]

function onClick(event, props, index){

}

<Menu items={items} onClick={onClick}/>
```

For rendering separators, just use a `'-'` in the items array.

## Properties

 * items: Object[]
 * onClick: Function(event, props, index) - Called on a click on a direct menu item. For clicks on menu items at any level of nesting, use `onChildClick`
 * onChildClick: Function(event, props) - Called when a menu item at any level of nesting was clicked
 * columns: String[] - defaults to ['label']

For every item in the items property, a row will be rendered, with all the columns specified in `props.columns`. Every column displays the value in item[<column_name>].

Every item can optionally have an **onClick** property, which is called when the item is clicked. (**onClick: Function(event, itemProps, index)**). Making an item disabled is done by specifying **disabled: true** on the item object.

 * expander: String/ReactElement - an expander tool to use when a menu item has other subitems. Defaults to the unicode arrow character **›**.

### Styling & advanced usage

By default, the `react-menus` component comes with built-in structural styles as well as with styles for a default nice theme. The specified theme is applied to menu items. If you don't want to render menu items with the default theme, just specify `theme=''` (or any falsy value).

```jsx
var items = [ {label: 'Save', onClick: function(){} }, { label: 'Export'}]
<Menu theme='' items={items} />
```

Or you can specify your own theme for the button. The value for the `theme` property is just an object with different styles:

```jsx
var theme = {
	style: { background: 'blue'},
	overStyle: { background: 'red', color: 'white'},
	activeStyle: { background: 'magenta'},
	expandedStyle: { background: 'magenta'},
	disabledStyle: {background: 'gray'}
}

<Menu theme={theme} items={items} />
```

Or you can specify a theme as string: 'default'. The `'default'` theme is the only one built in.

```jsx
<Menu theme='default' />
```
But you can add named themes:
```jsx
var theme = require('react-menus').theme

theme.goldenTheme = { overStyle: {background: 'yellow'}}

<Menu theme='goldenTheme' />
```

For styling menu separators, set the desired style properties on `Menu.Separator.style`

```jsx
var Menu = require('react-menus')

var Separator = Menu.Separator

Separator.style = {
    background: 'red' //the color of the separator
}

Separator.size = 10 //will be 10 px in height
```

### Style props

Styling menu items overrides theme styles.

 * itemStyle - style to be applied to menu items. Overrides `theme.style`
 * itemOverStyle - style to be applied to menu items on mouse over. Overrides `theme.overStyle`
 * itemActiveStyle - style to be applied to menu items on mouse down on the item. Overrides `theme.activeStyle`
 * itemExpandedStyle - style to be applied to menu items when the item is expanded. Overrides `theme.expandedStyle`
 * itemDisabledStyle - style to be applied to disabled menu items. Overrides `theme.defaultStyle`

 * cellStyle - style to be applied to menu item cells (expect the expander cell).

### Scrolling

Menu scrolling is enabled by default (`enableScroll: true`). When you have too many items, and the menu is bigger than it's parent container, the menu shows a scrolling user interface.

Or you can specify a `maxHeight` property on the menu, and if that is exceeded, the menu is scrollable.

```jsx
<Menu maxHeight={200} items={items}/>
```

Of course you can turn off scrolling with `enableScroll: false`

### Smart submenus

Showing and hiding submenus is implemented with a smart algorithm, as described [here](http://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown). Also submenu positioning is made taking into account the available space. More documentation on this soon.

## License

```MIT```


text:
- [Browserify](http://browserify.org/)
- ~~[eugeneware/debowerify](https://github.com/eugeneware/debowerify)~~ -> Removed.
- [babel/babel](https://babeljs.io/)
- [babel/babelify](https://github.com/babel/babelify)
- [babel-preset-es2015](https://www.npmjs.com/package/babel-preset-es2015)
- [babel-preset-react](https://www.npmjs.com/package/babel-preset-react)
- [babel-preset-babili](https://www.npmjs.com/package/babel-preset-babili)
- [babel/babel-eslint](https://github.com/babel/babel-eslint)
- [adametry/gulp-eslint](https://github.com/adametry/gulp-eslint)
- ~~[spalger/gulp-jshint](https://github.com/spalger/gulp-jshint)~~ -> Replaced to "ESLint"
- [terinjokes/gulp-uglify](https://github.com/terinjokes/gulp-uglify)

## 参考

- [ESLint 最初の一歩](http://qiita.com/mysticatea/items/f523dab04a25f617c87d)
- [babel な ESLint の設定をがんばった](https://havelog.ayumusato.com/develop/javascript/e660-eslint_with_babel.html)


text:
.. _example_notebooks:

################
Example Analyses
################

1. `Cultured foraminifera data <http://nbviewer.jupyter.org/github/oscarbranson/latools/blob/master/Supplement/cultured_foram_manual.ipynb>`_, and comparison to manually reduced data.
2. `Downcore (fossil) foraminifera data <http://nbviewer.jupyter.org/github/oscarbranson/latools/blob/master/Supplement/fossil_foram_manual.ipynb>`_, and comparison to manually reduced data.
3. `Downcore (fossil) foraminifera data <http://nbviewer.jupyter.org/github/oscarbranson/latools/blob/master/Supplement/fossil_foram_iolite.ipynb>`_, and comparison to data reduced with `Iolite <https://iolite-software.com/>`_.
4. `Zircon data <http://nbviewer.jupyter.org/github/oscarbranson/latools/blob/master/Supplement/zircon_manual.ipynb>`_, and comparison to values reported in `Burnham and Berry, 2017 <https://www.nature.com/articles/ngeo2942>`_.

All these notebooks and associated data are available for download `here <https://github.com/oscarbranson/latools/tree/master/Supplement>`_.


text:
<?php

namespace Botonomous;

use Botonomous\listener\SlashCommandListener;

/**
 * Class Config.
 */
class Config extends AbstractConfig
{
    protected static $configs = [
        'timezone'             => 'Australia/Melbourne',
        'oAuthToken'           => 'OAuth_Access_Token',
        'botUserToken'         => 'Bot_User_OAuth_Access_Token',
        'botUserId'            => 'YOUR_BOT_USER_ID',
        'botUsername'          => 'YOUR_BOT_USERNAME',
        'logger'               => [
            'enabled' => true,
            'monolog' => [
                'channel'  => 'logger',
                'handlers' => [
                    'file' => [
                        // should be full path
                        'fileName' => 'bot.log',
                    ],
                ],
            ],
        ],
        'iconURL'              => 'YOUR_BOT_ICON_URL_48_BY_48',
        'asUser'               => true,
        // possible values are: SlashCommandListener::KEY, EventListener::KEY
        'listener'         => SlashCommandListener::KEY,
        // this is used if there is no command has been specified in the message
        'defaultCommand'     => 'qa',
        'commandPrefix'      => '/',
        /*
         * App credentials - This is required for Event listener
         * Can be found at https://api.slack.com/apps
         */
        'clientId'     => 'YOUR_APP_CLIENT_ID',
        'clientSecret' => 'YOUR_APP_SECRET',
        'scopes'       => ['bot'],
        /*
         * use this token to verify that requests are actually coming from Slack
         */
        'verificationToken'    => 'YOUR_APP_VERIFICATION_TOKEN',
        'appId'                => 'YOUR_APP_ID',
        'accessControlEnabled' => false,
    ];
}


text:
#ifndef _CALRATADIE_
#define _CALRATADIE_
/**
  *File: calRataDie.h

  *Description:

   this file declares class calRataDie

  *Version: 1.0 "@(#) calRataDie. header. ver. 1.0. Premalatha, Vidyadhar Mudkavi, CTFD, NAL."

  *Dependencies:

  *Authors: Premalatha, Vidyadhar Mudkavi, CTFD, NAL.

  *Date:
  */

// system includes
#include <iostream>

// standard template
#include <string>
#include <vector>

// local includes
#include "calFn.h"

#if 0
// const declarations
namespace cal
{
   static char* weekDay[7] = { "Sunday", "Monday", "Tuesday", "Wednesday",
                               "Thursday", "Friday", "Saturday"
                             };
}
#endif

// function prototypes
// forward declarations
class calGregorian;
class calJulianDayNumber;
class calJulian;
class calIso;

// begin class declaration
class calRataDie
{
   friend class calFn;
   friend class calGregorian;
   friend inline std::ostream& operator<<(std::ostream& os, const calRataDie& rd);
   public:
   // constructors
      calRataDie(); // default
      calRataDie(long int date);
      calRataDie(const calRataDie& rata_die);

   // assignment operator
      calRataDie& operator=(const calRataDie& rata_die);
      inline calRataDie& operator=(long int fixed_date);

   // destructor
      ~calRataDie();

   // other functionality
      calGregorian Gregorian() const;
      calJulian    Julian() const;
      calIso       Iso() const;

      long int     GregorianYear() const;
      inline std::string  DayOfWeek() const;

      calJulianDayNumber JulianDayNumber() const;

      inline calRataDie operator-(long int decrement) const;

   protected:
      long int operator()() const { return pv_date; }
   private:
      long int pv_date;
      //long int pv_iso_date;

      static char* pv_weekDay[7];
};

// include any inline code here

inline std::string calRataDie::DayOfWeek() const
{
   long int lindex = calFn::Mod(pv_date, 7);
   int index = static_cast<int>( calFn::Mod(pv_date, 7) );
   return pv_weekDay[ index ];
}

inline calRataDie& calRataDie::operator=(long int fixed_date)
{
   pv_date = fixed_date; return *this;
}

inline calRataDie calRataDie::operator-(long int decrement) const
{
   return calRataDie(pv_date-decrement);
}

inline std::ostream& operator<<(std::ostream& os, const calRataDie& rd)
{
   os << rd.pv_date; return os;
}

/**
   declare any typedef statements here   (e.g.: typedef aVortex areVortices;)
  */
// here are the alternate names
typedef calRataDie calFixed;
typedef calRataDie calRD;
                              //
                              //      \\^//
                              //     o(!_!)o
                              // __m__  o  __m__
                              //

#endif   // _CALRATADIE_


text:
include(FindCXXFeatures)
include(CheckCXXSourceCompiles)

message(STATUS "CXX11_COMPILER_FLAGS=${CXX11_COMPILER_FLAGS}")
set(CMAKE_REQUIRED_FLAGS ${CXX11_COMPILER_FLAGS})

# Required features
# =================
set(ALIAS_CODE
    "#include <complex>
     template<typename Real>
     using Complex = std::complex<Real>;
     int main()
     {
         Complex<double> a;
     }")
check_cxx_source_compiles("${ALIAS_CODE}" EL_HAVE_TEMPLATE_ALIAS)
if(NOT EL_HAVE_TEMPLATE_ALIAS)
  message(FATAL_ERROR "C++11 template aliasing not detected. You may want to make sure that your compiler is sufficiently up-to-date (e.g., g++ >= 4.7)")
endif()

# Standard but inconsistently supported features
# ==============================================
set(STEADYCLOCK_CODE
    "#include <chrono>
     int main()
     {
         std::chrono::steady_clock clock;
         return 0;
     }")
set(NOEXCEPT_CODE
    "#include <vector>
     void Foo( const std::vector<int>& x ) noexcept { }
     int main()
     { return 0; }")
check_cxx_source_compiles("${STEADYCLOCK_CODE}" EL_HAVE_STEADYCLOCK)
check_cxx_source_compiles("${NOEXCEPT_CODE}" EL_HAVE_NOEXCEPT)

# C++11 random number generation
# ==============================
# Note: It was noticed that, for certain relatively recent Intel compiler
#       releases, the following snippets will suggest that normal distributions
#       are supported, but not uniform integer or real distributions.
#       Unfortunately, it has been observed that, when one attempts to sample
#       from a normal distribution, the application hangs indefinitely.
#       Thus, Elemental takes the approach of requiring all of the following
#       to be detected before any are used.
set(NORMAL_CODE
    "#include <random>
     int main()
     {
         std::random_device rd;
         std::mt19937 mt(rd());
         std::normal_distribution<double> dist(0,1);
         const double x = dist(mt);
         return 0;
     }")
set(UNIFORM_INT_CODE
    "#include <random>
     int main()
     {
         std::random_device rd;
         std::mt19937 mt(rd());
         std::uniform_int_distribution<int> dist(0,10);
         const int x = dist(mt);
         return 0;
     }")
set(UNIFORM_REAL_CODE
    "#include <random>
     int main()
     {
         std::random_device rd;
         std::mt19937 mt(rd());
         std::uniform_real_distribution<double> dist(0,1);
         const double x = dist(mt);
         return 0;
     }")
check_cxx_source_compiles("${NORMAL_CODE}" EL_HAVE_NORMAL_DIST)
check_cxx_source_compiles("${UNIFORM_INT_CODE}" EL_HAVE_UNIFORM_INT_DIST)
check_cxx_source_compiles("${UNIFORM_REAL_CODE}" EL_HAVE_UNIFORM_REAL_DIST)
if(EL_HAVE_NORMAL_DIST AND
   EL_HAVE_UNIFORM_INT_DIST AND
   EL_HAVE_UNIFORM_REAL_DIST)
  set(EL_HAVE_CXX11RANDOM TRUE)
else()
  set(EL_HAVE_CXX11RANDOM FALSE)
endif()

# "restrict" support
# ==================
set(RESTRICT_CODE "int main() { int* RESTRICT a; return 0; }")
set(CMAKE_REQUIRED_DEFINITIONS "-DRESTRICT=__restrict__")
check_cxx_source_compiles("${RESTRICT_CODE}" HAVE___restrict__)
set(CMAKE_REQUIRED_DEFINITIONS "-DRESTRICT=__restrict")
check_cxx_source_compiles("${RESTRICT_CODE}" HAVE___restrict)
set(CMAKE_REQUIRED_DEFINITIONS "-DRESTRICT=restrict")
check_cxx_source_compiles("${RESTRICT_CODE}" HAVE_restrict)
if(HAVE___restrict__)
  set(RESTRICT "__restrict__")
  message(STATUS "Using __restrict__ keyword.")
elseif(HAVE___restrict)
  set(RESTRICT "__restrict")
  message(STATUS "Using __restrict keyword.")
elseif(HAVE_restrict)
  set(RESTRICT "restrict")
  message(STATUS "Using restrict keyword.")
else()
  set(RESTRICT "")
  message(STATUS "Could not find a restrict keyword.")
endif()

set(CMAKE_REQUIRED_FLAGS)
set(CMAKE_REQUIRED_DEFINITIONS)


text:
package rui.coder.design.pattern.behaviour.mediator;

import java.util.Date;

public class ChatRoom {
   public static void showMessage(User user, String message){
      System.out.println(new Date().toString()
         + " [" + user.getName() +"] : " + message);
   }
}


text:
package com.bearsoft.org.netbeans.modules.form.layoutsupport;

import com.bearsoft.org.netbeans.modules.form.layoutsupport.delegates.BorderLayoutSupport;
import com.bearsoft.org.netbeans.modules.form.layoutsupport.delegates.BoxLayoutSupport;
import com.bearsoft.org.netbeans.modules.form.layoutsupport.delegates.CardLayoutSupport;
import com.bearsoft.org.netbeans.modules.form.layoutsupport.delegates.FlowLayoutSupport;
import com.bearsoft.org.netbeans.modules.form.layoutsupport.delegates.GridLayoutSupport;
import com.bearsoft.org.netbeans.modules.form.layoutsupport.delegates.MarginLayoutSupport;
import com.bearsoft.org.netbeans.modules.form.layoutsupport.delegates.MenuFakeSupport;
import com.bearsoft.org.netbeans.modules.form.layoutsupport.delegates.ScrollPaneSupport;
import com.bearsoft.org.netbeans.modules.form.layoutsupport.delegates.SplitPaneSupport;
import com.bearsoft.org.netbeans.modules.form.layoutsupport.delegates.TabbedPaneSupport;
import com.bearsoft.org.netbeans.modules.form.layoutsupport.delegates.ToolBarSupport;
import com.eas.client.forms.containers.ScrollPane;
import com.eas.client.forms.containers.SplitPane;
import com.eas.client.forms.containers.TabbedPane;
import com.eas.client.forms.containers.ToolBar;
import com.eas.client.forms.layouts.BoxLayout;
import com.eas.client.forms.layouts.CardLayout;
import com.eas.client.forms.layouts.MarginLayout;
import com.eas.client.forms.menu.Menu;
import com.eas.client.forms.menu.MenuBar;
import com.eas.client.forms.menu.PopupMenu;
import java.util.*;

/**
 * Registry and factory class for LayoutSupportDelegate implementations.
 *
 * @author Tomas Pavek
 */
public class LayoutSupportRegistry {

    private static final Map<Class<?>, Class<?>> containerToLayoutDelegate = new HashMap<>();
    private static final Map<Class<?>, Class<?>> layoutToLayoutDelegate = new HashMap<>();
    public static final String DEFAULT_SUPPORT = "<default>"; // NOI18N

    static {
        // fill in default containers
        containerToLayoutDelegate.put(
                ScrollPane.class, // NOI18N
                ScrollPaneSupport.class); // NOI18N
        containerToLayoutDelegate.put(
                SplitPane.class, // NOI18N
                SplitPaneSupport.class); // NOI18N
        containerToLayoutDelegate.put(
                TabbedPane.class, // NOI18N
                TabbedPaneSupport.class); // NOI18N
        containerToLayoutDelegate.put(
                ToolBar.class, // NOI18N
                ToolBarSupport.class); // NOI18N
        containerToLayoutDelegate.put(
                MenuBar.class, // NOI18N
                MenuFakeSupport.class); // NOI18N
        containerToLayoutDelegate.put(
                Menu.class, // NOI18N
                MenuFakeSupport.class); // NOI18N
        containerToLayoutDelegate.put(
                PopupMenu.class, // NOI18N
                MenuFakeSupport.class); // NOI18N
    }

    static {
        // fill in default layouts
        layoutToLayoutDelegate.put(
                java.awt.BorderLayout.class, // NOI18N
                BorderLayoutSupport.class); // NOI18N
        layoutToLayoutDelegate.put(
                java.awt.FlowLayout.class, // NOI18N
                FlowLayoutSupport.class); // NOI18N
        layoutToLayoutDelegate.put(
                BoxLayout.class, // NOI18N
                BoxLayoutSupport.class); // NOI18N
        layoutToLayoutDelegate.put(
                java.awt.GridLayout.class, // NOI18N
                GridLayoutSupport.class); // NOI18N
        layoutToLayoutDelegate.put(
                CardLayout.class, // NOI18N
                CardLayoutSupport.class); // NOI18N
        layoutToLayoutDelegate.put(
                MarginLayout.class, // NOI18N
                MarginLayoutSupport.class); // NOI18N
    }

    // --------------
    // get methods
    public static Class<?> getSupportClassForContainer(Class<?> containerClass) {
        return containerToLayoutDelegate.get(containerClass);
    }

    public Class<?> getSupportClassForLayout(Class<?> layoutClass) {
        return layoutToLayoutDelegate.get(layoutClass);
    }

    // ------------
    // creation methods
    public LayoutSupportDelegate createSupportForContainer(Class<?> containerClass)
            throws ClassNotFoundException,
            InstantiationException,
            IllegalAccessException {
        Class<?> delegateClass = getSupportClassForContainer(containerClass);
        if (delegateClass == null) {
            return null;
        }
        return (LayoutSupportDelegate) delegateClass.newInstance();
    }

    public static LayoutSupportDelegate createSupportForLayout(Class<?> layoutClass)
            throws ClassNotFoundException,
            InstantiationException,
            IllegalAccessException {
        Class<?> supportClass = layoutToLayoutDelegate.get(layoutClass);
        return (LayoutSupportDelegate) supportClass.newInstance();
    }
}


text:
package com.github.bjuvensjo.rsimulator.jms;

import com.github.bjuvensjo.rsimulator.core.Simulator;
import com.github.bjuvensjo.rsimulator.core.SimulatorResponse;
import com.github.bjuvensjo.rsimulator.core.config.CoreModule;
import com.github.bjuvensjo.rsimulator.jms.config.GlobalConfig;
import com.github.bjuvensjo.rsimulator.jms.config.JmsModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.model.RouteDefinition;

import java.util.Optional;

/**
 * JmsSimulator.
 */
public class JmsSimulator extends RouteBuilder {
    private static final String className = JmsSimulator.class.getName();
    private String jms;
    private String queue;
    private String replyTo;
    private String simulatorContentType;
    private Decoder decoder;
    private Encoder encoder;
    private int concurrentConsumers;
    private int maxConcurrentConsumers;
    private int receiveTimeout;

    @Inject
    private Simulator simulator;

    public JmsSimulator() {
        Injector injector = Guice.createInjector(new CoreModule(), new JmsModule());
        injector.injectMembers(this);
    }

    @Override
    public void configure() {
        RouteDefinition definition = from(jms +
                ":queue:" + queue +
                "?replyTo=" + replyTo +
                "&useMessageIDAsCorrelationID=true" +
                "&concurrentConsumers=" + concurrentConsumers +
                "&maxConcurrentConsumers=" + maxConcurrentConsumers +
                "&receiveTimeout=" + receiveTimeout);

        definition.to("log:" + className + "?showAll=true&multiline=true");

        if (decoder != null) {
            definition.bean(decoder);
        }

        definition.process(exchange -> {
            String request = exchange.getIn().getBody(String.class);
            Optional<SimulatorResponse> simulatorResponseOptional = simulator.service(GlobalConfig.rootPath, "", request, simulatorContentType);
            String responseBody = simulatorResponseOptional.map(SimulatorResponse::getResponse).orElse("No simulatorResponse found!");
            exchange.getIn().setBody(responseBody);
        });

        if (encoder != null) {
            definition.bean(encoder);
        }

        definition.to("log:" + className + "?showAll=true&multiline=true");
    }

    public void setJms(String jms) {
        this.jms = jms;
    }

    public void setQueue(String queue) {
        this.queue = queue;
    }

    public void setReplyTo(String replyTo) {
        this.replyTo = replyTo;
    }

    public void setSimulatorContentType(String simulatorContentType) {
        this.simulatorContentType = simulatorContentType;
    }

    public void setDecoder(Decoder decoder) {
        this.decoder = decoder;
    }

    public void setEncoder(Encoder encoder) {
        this.encoder = encoder;
    }

    public void setConcurrentConsumers(int concurrentConsumers) {
        this.concurrentConsumers = concurrentConsumers;
    }

    public void setMaxConcurrentConsumers(int maxConcurrentConsumers) {
        this.maxConcurrentConsumers = maxConcurrentConsumers;
    }

    public void setReceiveTimeout(int receiveTimeout) {
        this.receiveTimeout = receiveTimeout;
    }
}


text:
A debian:jessie based Python Spark container. Used as the base image for OpenGov's PySpark setup. Installs many python dependencies such as numpy, scipy, and pandas.

## Docker Tagging Convention
The images should be tagged in the format of:

```
opengovorg/pyspark:<spark version>-<hadoop version>-<iteration>
```

where:

* \<spark version\>: The version of Spark including the major, minor, and patch
* \<hadoop version\>: The version of Spark including the major, minor, and patch
* \<iteration\>: The iteration version of this release which may include upgraded python dependency versions

## License
MIT


text:
//
//  ========================================================================
//  Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd.
//  ------------------------------------------------------------------------
//  All rights reserved. This program and the accompanying materials
//  are made available under the terms of the Eclipse Public License v1.0
//  and Apache License v2.0 which accompanies this distribution.
//
//      The Eclipse Public License is available at
//      http://www.eclipse.org/legal/epl-v10.html
//
//      The Apache License v2.0 is available at
//      http://www.opensource.org/licenses/apache2.0.php
//
//  You may elect to redistribute this code under either of these licenses.
//  ========================================================================
//

package org.eclipse.jetty.util;

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;

/* ------------------------------------------------------------ */
/**
 * TYPE Utilities.
 * Provides various static utiltiy methods for manipulating types and their
 * string representations.
 *
 * @since Jetty 4.1
 */
public class TypeUtil
{
    private static final Logger LOG = Log.getLogger(TypeUtil.class);
    public static int CR = '\015';
    public static int LF = '\012';

    /* ------------------------------------------------------------ */
    private static final HashMap<String, Class<?>> name2Class=new HashMap<String, Class<?>>();
    static
    {
        name2Class.put("boolean",java.lang.Boolean.TYPE);
        name2Class.put("byte",java.lang.Byte.TYPE);
        name2Class.put("char",java.lang.Character.TYPE);
        name2Class.put("double",java.lang.Double.TYPE);
        name2Class.put("float",java.lang.Float.TYPE);
        name2Class.put("int",java.lang.Integer.TYPE);
        name2Class.put("long",java.lang.Long.TYPE);
        name2Class.put("short",java.lang.Short.TYPE);
        name2Class.put("void",java.lang.Void.TYPE);

        name2Class.put("java.lang.Boolean.TYPE",java.lang.Boolean.TYPE);
        name2Class.put("java.lang.Byte.TYPE",java.lang.Byte.TYPE);
        name2Class.put("java.lang.Character.TYPE",java.lang.Character.TYPE);
        name2Class.put("java.lang.Double.TYPE",java.lang.Double.TYPE);
        name2Class.put("java.lang.Float.TYPE",java.lang.Float.TYPE);
        name2Class.put("java.lang.Integer.TYPE",java.lang.Integer.TYPE);
        name2Class.put("java.lang.Long.TYPE",java.lang.Long.TYPE);
        name2Class.put("java.lang.Short.TYPE",java.lang.Short.TYPE);
        name2Class.put("java.lang.Void.TYPE",java.lang.Void.TYPE);

        name2Class.put("java.lang.Boolean",java.lang.Boolean.class);
        name2Class.put("java.lang.Byte",java.lang.Byte.class);
        name2Class.put("java.lang.Character",java.lang.Character.class);
        name2Class.put("java.lang.Double",java.lang.Double.class);
        name2Class.put("java.lang.Float",java.lang.Float.class);
        name2Class.put("java.lang.Integer",java.lang.Integer.class);
        name2Class.put("java.lang.Long",java.lang.Long.class);
        name2Class.put("java.lang.Short",java.lang.Short.class);

        name2Class.put("Boolean",java.lang.Boolean.class);
        name2Class.put("Byte",java.lang.Byte.class);
        name2Class.put("Character",java.lang.Character.class);
        name2Class.put("Double",java.lang.Double.class);
        name2Class.put("Float",java.lang.Float.class);
        name2Class.put("Integer",java.lang.Integer.class);
        name2Class.put("Long",java.lang.Long.class);
        name2Class.put("Short",java.lang.Short.class);

        name2Class.put(null,java.lang.Void.TYPE);
        name2Class.put("string",java.lang.String.class);
        name2Class.put("String",java.lang.String.class);
        name2Class.put("java.lang.String",java.lang.String.class);
    }

    /* ------------------------------------------------------------ */
    private static final HashMap<Class<?>, String> class2Name=new HashMap<Class<?>, String>();
    static
    {
        class2Name.put(java.lang.Boolean.TYPE,"boolean");
        class2Name.put(java.lang.Byte.TYPE,"byte");
        class2Name.put(java.lang.Character.TYPE,"char");
        class2Name.put(java.lang.Double.TYPE,"double");
        class2Name.put(java.lang.Float.TYPE,"float");
        class2Name.put(java.lang.Integer.TYPE,"int");
        class2Name.put(java.lang.Long.TYPE,"long");
        class2Name.put(java.lang.Short.TYPE,"short");
        class2Name.put(java.lang.Void.TYPE,"void");

        class2Name.put(java.lang.Boolean.class,"java.lang.Boolean");
        class2Name.put(java.lang.Byte.class,"java.lang.Byte");
        class2Name.put(java.lang.Character.class,"java.lang.Character");
        class2Name.put(java.lang.Double.class,"java.lang.Double");
        class2Name.put(java.lang.Float.class,"java.lang.Float");
        class2Name.put(java.lang.Integer.class,"java.lang.Integer");
        class2Name.put(java.lang.Long.class,"java.lang.Long");
        class2Name.put(java.lang.Short.class,"java.lang.Short");

        class2Name.put(null,"void");
        class2Name.put(java.lang.String.class,"java.lang.String");
    }

    /* ------------------------------------------------------------ */
    private static final HashMap<Class<?>, Method> class2Value=new HashMap<Class<?>, Method>();
    static
    {
        try
        {
            Class<?>[] s ={java.lang.String.class};

            class2Value.put(java.lang.Boolean.TYPE,
                           java.lang.Boolean.class.getMethod("valueOf",s));
            class2Value.put(java.lang.Byte.TYPE,
                           java.lang.Byte.class.getMethod("valueOf",s));
            class2Value.put(java.lang.Double.TYPE,
                           java.lang.Double.class.getMethod("valueOf",s));
            class2Value.put(java.lang.Float.TYPE,
                           java.lang.Float.class.getMethod("valueOf",s));
            class2Value.put(java.lang.Integer.TYPE,
                           java.lang.Integer.class.getMethod("valueOf",s));
            class2Value.put(java.lang.Long.TYPE,
                           java.lang.Long.class.getMethod("valueOf",s));
            class2Value.put(java.lang.Short.TYPE,
                           java.lang.Short.class.getMethod("valueOf",s));

            class2Value.put(java.lang.Boolean.class,
                           java.lang.Boolean.class.getMethod("valueOf",s));
            class2Value.put(java.lang.Byte.class,
                           java.lang.Byte.class.getMethod("valueOf",s));
            class2Value.put(java.lang.Double.class,
                           java.lang.Double.class.getMethod("valueOf",s));
            class2Value.put(java.lang.Float.class,
                           java.lang.Float.class.getMethod("valueOf",s));
            class2Value.put(java.lang.Integer.class,
                           java.lang.Integer.class.getMethod("valueOf",s));
            class2Value.put(java.lang.Long.class,
                           java.lang.Long.class.getMethod("valueOf",s));
            class2Value.put(java.lang.Short.class,
                           java.lang.Short.class.getMethod("valueOf",s));
        }
        catch(Exception e)
        {
            throw new Error(e);
        }
    }

    /* ------------------------------------------------------------ */
    /** Array to List.
     * <p>
     * Works like {@link Arrays#asList(Object...)}, but handles null arrays.
     * @return a list backed by the array.
     */
    public static <T> List<T> asList(T[] a)
    {
        if (a==null)
            return Collections.emptyList();
        return Arrays.asList(a);
    }

    /* ------------------------------------------------------------ */
    /** Class from a canonical name for a type.
     * @param name A class or type name.
     * @return A class , which may be a primitive TYPE field..
     */
    public static Class<?> fromName(String name)
    {
        return name2Class.get(name);
    }

    /* ------------------------------------------------------------ */
    /** Canonical name for a type.
     * @param type A class , which may be a primitive TYPE field.
     * @return Canonical name.
     */
    public static String toName(Class<?> type)
    {
        return class2Name.get(type);
    }

    /* ------------------------------------------------------------ */
    /** Convert String value to instance.
     * @param type The class of the instance, which may be a primitive TYPE field.
     * @param value The value as a string.
     * @return The value as an Object.
     */
    public static Object valueOf(Class<?> type, String value)
    {
        try
        {
            if (type.equals(java.lang.String.class))
                return value;

            Method m = class2Value.get(type);
            if (m!=null)
                return m.invoke(null, value);

            if (type.equals(java.lang.Character.TYPE) ||
                type.equals(java.lang.Character.class))
                return new Character(value.charAt(0));

            Constructor<?> c = type.getConstructor(java.lang.String.class);
            return c.newInstance(value);
        }
        catch(NoSuchMethodException e)
        {
            // LogSupport.ignore(log,e);
        }
        catch(IllegalAccessException e)
        {
            // LogSupport.ignore(log,e);
        }
        catch(InstantiationException e)
        {
            // LogSupport.ignore(log,e);
        }
        catch(InvocationTargetException e)
        {
            if (e.getTargetException() instanceof Error)
                throw (Error)(e.getTargetException());
            // LogSupport.ignore(log,e);
        }
        return null;
    }

    /* ------------------------------------------------------------ */
    /** Convert String value to instance.
     * @param type classname or type (eg int)
     * @param value The value as a string.
     * @return The value as an Object.
     */
    public static Object valueOf(String type, String value)
    {
        return valueOf(fromName(type),value);
    }

    /* ------------------------------------------------------------ */
    /** Parse an int from a substring.
     * Negative numbers are not handled.
     * @param s String
     * @param offset Offset within string
     * @param length Length of integer or -1 for remainder of string
     * @param base base of the integer
     * @return the parsed integer
     * @throws NumberFormatException if the string cannot be parsed
     */
    public static int parseInt(String s, int offset, int length, int base)
        throws NumberFormatException
    {
        int value=0;

        if (length<0)
            length=s.length()-offset;

        for (int i=0;i<length;i++)
        {
            char c=s.charAt(offset+i);

            int digit=convertHexDigit((int)c);
            if (digit<0 || digit>=base)
                throw new NumberFormatException(s.substring(offset,offset+length));
            value=value*base+digit;
        }
        return value;
    }

    /* ------------------------------------------------------------ */
    /** Parse an int from a byte array of ascii characters.
     * Negative numbers are not handled.
     * @param b byte array
     * @param offset Offset within string
     * @param length Length of integer or -1 for remainder of string
     * @param base base of the integer
     * @return the parsed integer
     * @throws NumberFormatException if the array cannot be parsed into an integer
     */
    public static int parseInt(byte[] b, int offset, int length, int base)
        throws NumberFormatException
    {
        int value=0;

        if (length<0)
            length=b.length-offset;

        for (int i=0;i<length;i++)
        {
            char c=(char)(0xff&b[offset+i]);

            int digit=c-'0';
            if (digit<0 || digit>=base || digit>=10)
            {
                digit=10+c-'A';
                if (digit<10 || digit>=base)
                    digit=10+c-'a';
            }
            if (digit<0 || digit>=base)
                throw new NumberFormatException(new String(b,offset,length));
            value=value*base+digit;
        }
        return value;
    }

    /* ------------------------------------------------------------ */
    public static byte[] parseBytes(String s, int base)
    {
        byte[] bytes=new byte[s.length()/2];
        for (int i=0;i<s.length();i+=2)
            bytes[i/2]=(byte)TypeUtil.parseInt(s,i,2,base);
        return bytes;
    }

    /* ------------------------------------------------------------ */
    public static String toString(byte[] bytes, int base)
    {
        StringBuilder buf = new StringBuilder();
        for (byte b : bytes)
        {
            int bi=0xff&b;
            int c='0'+(bi/base)%base;
            if (c>'9')
                c= 'a'+(c-'0'-10);
            buf.append((char)c);
            c='0'+bi%base;
            if (c>'9')
                c= 'a'+(c-'0'-10);
            buf.append((char)c);
        }
        return buf.toString();
    }

    /* ------------------------------------------------------------ */
    /**
     * @param c An ASCII encoded character 0-9 a-f A-F
     * @return The byte value of the character 0-16.
     */
    public static byte convertHexDigit( byte c )
    {
        byte b = (byte)((c & 0x1f) + ((c >> 6) * 0x19) - 0x10);
        if (b<0 || b>15)
            throw new IllegalArgumentException("!hex "+c);
        return b;
    }

    /* ------------------------------------------------------------ */
    /**
     * @param c An ASCII encoded character 0-9 a-f A-F
     * @return The byte value of the character 0-16.
     */
    public static int convertHexDigit( int c )
    {
        int d= ((c & 0x1f) + ((c >> 6) * 0x19) - 0x10);
        if (d<0 || d>15)
            throw new NumberFormatException("!hex "+c);
        return d;
    }

    /* ------------------------------------------------------------ */
    public static void toHex(byte b,Appendable buf)
    {
        try
        {
            int d=0xf&((0xF0&b)>>4);
            buf.append((char)((d>9?('A'-10):'0')+d));
            d=0xf&b;
            buf.append((char)((d>9?('A'-10):'0')+d));
        }
        catch(IOException e)
        {
            throw new RuntimeException(e);
        }
    }

    /* ------------------------------------------------------------ */
    public static void toHex(int value,Appendable buf) throws IOException
    {
        int d=0xf&((0xF0000000&value)>>28);
        buf.append((char)((d>9?('A'-10):'0')+d));
        d=0xf&((0x0F000000&value)>>24);
        buf.append((char)((d>9?('A'-10):'0')+d));
        d=0xf&((0x00F00000&value)>>20);
        buf.append((char)((d>9?('A'-10):'0')+d));
        d=0xf&((0x000F0000&value)>>16);
        buf.append((char)((d>9?('A'-10):'0')+d));
        d=0xf&((0x0000F000&value)>>12);
        buf.append((char)((d>9?('A'-10):'0')+d));
        d=0xf&((0x00000F00&value)>>8);
        buf.append((char)((d>9?('A'-10):'0')+d));
        d=0xf&((0x000000F0&value)>>4);
        buf.append((char)((d>9?('A'-10):'0')+d));
        d=0xf&value;
        buf.append((char)((d>9?('A'-10):'0')+d));

        Integer.toString(0,36);
    }

    /* ------------------------------------------------------------ */
    public static void toHex(long value,Appendable buf) throws IOException
    {
        toHex((int)(value>>32),buf);
        toHex((int)value,buf);
    }

    /* ------------------------------------------------------------ */
    public static String toHexString(byte b)
    {
        return toHexString(new byte[]{b}, 0, 1);
    }

    /* ------------------------------------------------------------ */
    public static String toHexString(byte[] b)
    {
        return toHexString(b, 0, b.length);
    }

    /* ------------------------------------------------------------ */
    public static String toHexString(byte[] b,int offset,int length)
    {
        StringBuilder buf = new StringBuilder();
        for (int i=offset;i<offset+length;i++)
        {
            int bi=0xff&b[i];
            int c='0'+(bi/16)%16;
            if (c>'9')
                c= 'A'+(c-'0'-10);
            buf.append((char)c);
            c='0'+bi%16;
            if (c>'9')
                c= 'a'+(c-'0'-10);
            buf.append((char)c);
        }
        return buf.toString();
    }

    /* ------------------------------------------------------------ */
    public static byte[] fromHexString(String s)
    {
        if (s.length()%2!=0)
            throw new IllegalArgumentException(s);
        byte[] array = new byte[s.length()/2];
        for (int i=0;i<array.length;i++)
        {
            int b = Integer.parseInt(s.substring(i*2,i*2+2),16);
            array[i]=(byte)(0xff&b);
        }
        return array;
    }

    public static void dump(Class<?> c)
    {
        System.err.println("Dump: "+c);
        dump(c.getClassLoader());
    }

    public static void dump(ClassLoader cl)
    {
        System.err.println("Dump Loaders:");
        while(cl!=null)
        {
            System.err.println("  loader "+cl);
            cl = cl.getParent();
        }
    }

    public static URL jarFor(String className)
    {
        try
        {
            className=className.replace('.','/')+".class";
            // hack to discover jstl libraries
            URL url = Loader.getResource(null,className,false);
            String s=url.toString();
            if (s.startsWith("jar:file:"))
                return new URL(s.substring(4,s.indexOf("!/")));
        }
        catch(Exception e)
        {
            LOG.ignore(e);
        }
        return null;
    }

    public static Object call(Class<?> oClass, String method, Object obj, Object[] arg)
       throws InvocationTargetException, NoSuchMethodException
    {
        // Lets just try all methods for now
        Method[] methods = oClass.getMethods();
        for (int c = 0; methods != null && c < methods.length; c++)
        {
            if (!methods[c].getName().equals(method))
                continue;
            if (methods[c].getParameterTypes().length != arg.length)
                continue;
            if (Modifier.isStatic(methods[c].getModifiers()) != (obj == null))
                continue;
            if ((obj == null) && methods[c].getDeclaringClass() != oClass)
                continue;

            try
            {
                return methods[c].invoke(obj,arg);
            }
            catch (IllegalAccessException e)
            {
                LOG.ignore(e);
            }
            catch (IllegalArgumentException e)
            {
                LOG.ignore(e);
            }
        }

        throw new NoSuchMethodException(method);
    }
}