text:
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.history;

import com.intellij.CommonBundle;
import com.intellij.icons.AllIcons;
import com.intellij.ide.CopyProvider;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.VcsInternalDataKeys;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.colors.EditorColorsListener;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.ide.CopyPasteManager;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Splitter;
import com.intellij.openapi.util.Clock;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Getter;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.*;
import com.intellij.openapi.vcs.changes.ByteBackedContentRevision;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vcs.changes.ContentRevision;
import com.intellij.openapi.vcs.changes.CurrentContentRevision;
import com.intellij.openapi.vcs.changes.issueLinks.IssueLinkRenderer;
import com.intellij.openapi.vcs.changes.issueLinks.TableLinkMouseListener;
import com.intellij.openapi.vcs.impl.VcsBackgroundableActions;
import com.intellij.openapi.vcs.vfs.VcsFileSystem;
import com.intellij.openapi.vcs.vfs.VcsVirtualFile;
import com.intellij.openapi.vcs.vfs.VcsVirtualFolder;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.ui.*;
import com.intellij.ui.dualView.CellWrapper;
import com.intellij.ui.dualView.DualView;
import com.intellij.ui.dualView.DualViewColumnInfo;
import com.intellij.ui.dualView.TreeTableView;
import com.intellij.ui.speedSearch.SpeedSearchUtil;
import com.intellij.ui.table.TableView;
import com.intellij.util.ArrayUtil;
import com.intellij.util.Consumer;
import com.intellij.util.PlatformIcons;
import com.intellij.util.TreeItem;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.text.DateFormatUtil;
import com.intellij.util.ui.ColumnInfo;
import com.intellij.util.ui.StatusText;
import com.intellij.util.ui.UIUtil;
import com.intellij.vcsUtil.VcsUtil;
import org.jetbrains.annotations.CalledInAwt;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.io.IOException;
import java.util.List;
import java.util.*;

import static java.util.Comparator.comparing;
import static java.util.Comparator.reverseOrder;

/**
 * author: lesya
 */
public class FileHistoryPanelImpl extends JPanel implements DataProvider, Disposable, EditorColorsListener, CopyProvider {
  private static final String COMMIT_MESSAGE_TITLE = VcsBundle.message("label.selected.revision.commit.message");
  private static final String VCS_HISTORY_POPUP_ACTION_GROUP = "VcsHistoryInternalGroup.Popup";
  private static final String VCS_HISTORY_TOOLBAR_ACTION_GROUP = "VcsHistoryInternalGroup.Toolbar";

  public static final DataKey<VcsFileRevision> PREVIOUS_REVISION_FOR_DIFF = DataKey.create("PREVIOUS_VCS_FILE_REVISION_FOR_DIFF");

  private final String myHelpId;

  @NotNull private final AbstractVcs myVcs;
  private final VcsHistoryProvider myProvider;
  @NotNull private final FileHistoryRefresherI myRefresherI;
  @NotNull private final FilePath myFilePath;
  @Nullable private final VcsRevisionNumber myStartingRevision;
  @NotNull private final Map<VcsRevisionNumber, Integer> myRevisionsOrder = ContainerUtil.newHashMap();
  @NotNull private final Map<VcsFileRevision, VirtualFile> myRevisionToVirtualFile = ContainerUtil.newHashMap();
  @NotNull private final DetailsPanel myDetails;
  @NotNull private final DualView myDualView;
  @Nullable private final JComponent myAdditionalDetails;
  @Nullable private final Consumer<VcsFileRevision> myRevisionSelectionListener;

  @NotNull private VcsHistorySession myHistorySession;
  private VcsFileRevision myBottomRevisionForShowDiff;
  private List<Object> myTargetSelection;
  private boolean myIsStaticAndEmbedded;
  private Splitter myDetailsSplitter;
  private Splitter mySplitter;

  public FileHistoryPanelImpl(@NotNull AbstractVcs vcs,
                              @NotNull FilePath filePath,
                              @NotNull VcsHistorySession session,
                              VcsHistoryProvider provider,
                              @NotNull FileHistoryRefresherI refresherI,
                              final boolean isStaticEmbedded) {
    this(vcs, filePath, null, session, provider, refresherI, isStaticEmbedded);
  }

  public FileHistoryPanelImpl(@NotNull AbstractVcs vcs,
                              @NotNull FilePath filePath,
                              @Nullable VcsRevisionNumber startingRevision,
                              @NotNull VcsHistorySession session,
                              VcsHistoryProvider provider,
                              @NotNull FileHistoryRefresherI refresherI,
                              final boolean isStaticEmbedded) {
    super(new BorderLayout());
    myHelpId = provider.getHelpId() != null ? provider.getHelpId() : "reference.versionControl.toolwindow.history";

    myIsStaticAndEmbedded = false;
    myVcs = vcs;
    myProvider = provider;
    myRefresherI = refresherI;
    myHistorySession = session;
    myFilePath = filePath;
    myStartingRevision = startingRevision;
    myDetails = new DetailsPanel(vcs.getProject());

    refreshRevisionsOrder();

    final VcsDependentHistoryComponents components = provider.getUICustomization(session, this);
    myAdditionalDetails = components.getDetailsComponent();
    myRevisionSelectionListener = components.getRevisionListener();

    final DualViewColumnInfo[] columns = createColumnList(vcs.getProject(), provider, components.getColumns());
    @NonNls String storageKey = "FileHistory." + provider.getClass().getName();
    final HistoryAsTreeProvider treeHistoryProvider = myHistorySession.getHistoryAsTreeProvider();
    if (treeHistoryProvider != null) {
      myDualView = new DualView(new TreeNodeOnVcsRevision(null, treeHistoryProvider.createTreeOn(myHistorySession.getRevisionList())),
                                columns, storageKey, myVcs.getProject());
    }
    else {
      myDualView =
        new DualView(new TreeNodeOnVcsRevision(null, ContainerUtil.map(myHistorySession.getRevisionList(), TreeItem::new)), columns,
                     storageKey, myVcs.getProject());
      myDualView.switchToTheFlatMode();
    }
    new TableSpeedSearch(myDualView.getFlatView()).setComparator(new SpeedSearchComparator(false));
    final TableLinkMouseListener listener = new TableLinkMouseListener();
    listener.installOn(myDualView.getFlatView());
    listener.installOn(myDualView.getTreeView());
    myDualView.setEmptyText(CommonBundle.getLoadingTreeNodeText());

    setupDualView(fillActionGroup(true, new DefaultActionGroup(null, false)));
    if (isStaticEmbedded) {
      setIsStaticAndEmbedded(true);
    }
    DefaultActionGroup toolbarGroup = new DefaultActionGroup(null, false);
    fillActionGroup(false, toolbarGroup);

    ActionToolbar toolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.FILEHISTORY_VIEW_TOOLBAR, toolbarGroup,
                                                                            isStaticEmbedded);
    JComponent centerPanel = createCenterPanel();
    toolbar.setTargetComponent(centerPanel);
    for (AnAction action : toolbarGroup.getChildren(null)) {
      action.registerCustomShortcutSet(action.getShortcutSet(), centerPanel);
    }

    add(centerPanel, BorderLayout.CENTER);
    add(toolbar.getComponent(), isStaticEmbedded ? BorderLayout.NORTH : BorderLayout.WEST);

    chooseView();

    Disposer.register(vcs.getProject(), this);
  }

  private static void makeBold(Component component) {
    if (component instanceof JComponent) {
      JComponent jComponent = (JComponent)component;
      Font font = jComponent.getFont();
      if (font != null) {
        jComponent.setFont(font.deriveFont(Font.BOLD));
      }
    }
    else if (component instanceof Container) {
      Container container = (Container)component;
      for (int i = 0; i < container.getComponentCount(); i++) {
        makeBold(container.getComponent(i));
      }
    }
  }

  @NotNull
  public static String getPresentableText(@NotNull VcsFileRevision revision, boolean withMessage) {
    // implementation reflected by com.intellij.vcs.log.ui.frame.VcsLogGraphTable.getPresentableText()
    StringBuilder sb = new StringBuilder();
    sb.append(VcsUtil.getShortRevisionString(revision.getRevisionNumber())).append(" ");
    sb.append(revision.getAuthor());
    long time = revision.getRevisionDate().getTime();
    sb.append(" on ").append(DateFormatUtil.formatDate(time)).append(" at ").append(DateFormatUtil.formatTime(time));
    if (revision instanceof VcsFileRevisionEx) {
      if (!Comparing.equal(revision.getAuthor(), ((VcsFileRevisionEx)revision).getCommitterName())) {
        sb.append(" (committed by ").append(((VcsFileRevisionEx)revision).getCommitterName()).append(")");
      }
    }
    if (withMessage) {
      sb.append(" ").append(MessageColumnInfo.getSubject(revision));
    }
    return sb.toString();
  }

  /**
   * Checks if the given historyPanel shows the history for given path and revision number.
   */
  static boolean sameHistories(@NotNull FileHistoryPanelImpl historyPanel,
                               @NotNull FilePath filePath2,
                               @Nullable VcsRevisionNumber startingRevision2) {
    return sameHistories(historyPanel.myFilePath, historyPanel.myStartingRevision, filePath2, startingRevision2);
  }

  public static boolean sameHistories(@NotNull FilePath filePath1, @Nullable VcsRevisionNumber startingRevision1,
                                      @NotNull FilePath filePath2, @Nullable VcsRevisionNumber startingRevision2) {
    String existingRevision = startingRevision1 == null ? null : startingRevision1.asString();
    String newRevision = startingRevision2 == null ? null : startingRevision2.asString();
    return filePath1.equals(filePath2) && Comparing.equal(existingRevision, newRevision);
  }

  @NotNull
  private DualViewColumnInfo[] createColumnList(@NotNull Project project,
                                                @NotNull VcsHistoryProvider provider,
                                                @Nullable ColumnInfo[] additionalColumns) {
    ArrayList<DualViewColumnInfo> columns = new ArrayList<>();
    columns.add(new TreeNodeColumnInfoWrapper<>(
      new RevisionColumnInfo(comparing(revision -> myRevisionsOrder.get(revision.getRevisionNumber()), reverseOrder()))));
    if (!provider.isDateOmittable()) columns.add(new TreeNodeColumnInfoWrapper<>(new DateColumnInfo()));
    columns.add(new TreeNodeColumnInfoWrapper<>(new AuthorColumnInfo()));
    if (additionalColumns != null) {
      for (ColumnInfo additionalColumn : additionalColumns) {
        columns.add(new TreeNodeColumnInfoWrapper(additionalColumn));
      }
    }
    columns.add(new TreeNodeColumnInfoWrapper<>(new MessageColumnInfo(project)));
    return columns.toArray(new DualViewColumnInfo[0]);
  }

  @CalledInAwt
  public void setHistorySession(@NotNull VcsHistorySession session) {
    if (myTargetSelection == null) {
      myTargetSelection = myDualView.getFlatView().getSelectedObjects();
    }

    myHistorySession = session;
    refreshRevisionsOrder();
    HistoryAsTreeProvider treeHistoryProvider = session.getHistoryAsTreeProvider();

    if (myHistorySession.getRevisionList().isEmpty()) {
      adjustEmptyText();
    }

    if (treeHistoryProvider != null) {
      myDualView.setRoot(new TreeNodeOnVcsRevision(null,
                                                   treeHistoryProvider.createTreeOn(myHistorySession.getRevisionList())),
                         myTargetSelection);
    }
    else {
      myDualView.setRoot(new TreeNodeOnVcsRevision(null, ContainerUtil.map(myHistorySession.getRevisionList(), TreeItem::new)),
                         myTargetSelection);
    }

    mySplitter.revalidate();
    mySplitter.repaint();
    myDualView.expandAll();
    myDualView.repaint();
  }

  @CalledInAwt
  public void finishRefresh() {
    if (myHistorySession.getHistoryAsTreeProvider() != null) {
      // scroll tree view to most recent change
      final TreeTableView treeView = myDualView.getTreeView();
      final int lastRow = treeView.getRowCount() - 1;
      if (lastRow >= 0) {
        treeView.scrollRectToVisible(treeView.getCellRect(lastRow, 0, true));
      }
    }
    myTargetSelection = null;

    mySplitter.revalidate();
    mySplitter.repaint();
  }

  private void adjustEmptyText() {
    VirtualFile virtualFile = myFilePath.getVirtualFile();
    if ((virtualFile == null || !virtualFile.isValid()) && !myFilePath.getIOFile().exists()) {
      myDualView.setEmptyText("File " + myFilePath.getName() + " not found");
    }
    else if (VcsCachingHistory.getHistoryLock(myVcs, VcsBackgroundableActions.CREATE_HISTORY_SESSION, myFilePath, myStartingRevision)
      .isLocked()) {
      myDualView.setEmptyText(CommonBundle.getLoadingTreeNodeText());
    }
    else {
      myDualView.setEmptyText(StatusText.DEFAULT_EMPTY_TEXT);
    }
  }

  private void setupDualView(@NotNull DefaultActionGroup group) {
    myDualView.setShowGrid(true);
    PopupHandler.installPopupHandler(myDualView.getTreeView(), group, ActionPlaces.UPDATE_POPUP, ActionManager.getInstance());
    PopupHandler.installPopupHandler(myDualView.getFlatView(), group, ActionPlaces.UPDATE_POPUP, ActionManager.getInstance());
    IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> IdeFocusManager.getGlobalInstance().requestFocus(myDualView, true));

    myDualView.addListSelectionListener(e -> updateMessage());
    myDualView.setRootVisible(false);
    myDualView.expandAll();

    myDualView.setTreeCellRenderer(new MyTreeCellRenderer(myDualView.getTree().getCellRenderer(), () -> myHistorySession));
    myDualView.setCellWrapper(new MyCellWrapper(() -> myHistorySession));

    myDualView.installDoubleClickHandler(EmptyAction.wrap(ActionManager.getInstance().getAction(IdeActions.ACTION_SHOW_DIFF_COMMON)));

    myDualView.getFlatView().getTableViewModel().setSortable(true);
    RowSorter<? extends TableModel> rowSorter = myDualView.getFlatView().getRowSorter();
    if (rowSorter != null) {
      rowSorter.setSortKeys(Collections.singletonList(new RowSorter.SortKey(0, SortOrder.DESCENDING)));
    }
  }

  private void updateMessage() {
    //noinspection unchecked
    List<TreeNodeOnVcsRevision> selection = (List<TreeNodeOnVcsRevision>)myDualView.getSelection();
    myDetails.update(selection);
    if (selection.isEmpty()) {
      return;
    }
    if (myRevisionSelectionListener != null) {
      myRevisionSelectionListener.consume(selection.get(0).getRevision());
    }
  }

  @NotNull
  protected JComponent createCenterPanel() {
    mySplitter = new OnePixelSplitter(true, "vcs.history.splitter.proportion", 0.6f);
    mySplitter.setFirstComponent(myDualView);

    JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(myDetails);
    scrollPane.setBorder(IdeBorderFactory.createBorder(SideBorder.LEFT));

    myDetailsSplitter = new OnePixelSplitter(false, "vcs.history.details.splitter.proportion", 0.5f);
    myDetailsSplitter.setFirstComponent(scrollPane);
    myDetailsSplitter.setSecondComponent(myAdditionalDetails);

    setupDetails();
    return mySplitter;
  }

  private void setupDetails() {
    boolean showDetails = !myIsStaticAndEmbedded && VcsConfiguration.getInstance(myVcs.getProject()).SHOW_FILE_HISTORY_DETAILS;
    myDualView.setViewBorder(IdeBorderFactory.createBorder(SideBorder.LEFT));
    mySplitter.setSecondComponent(showDetails ? myDetailsSplitter : null);
  }

  private void chooseView() {
    if (VcsConfiguration.getInstance(myVcs.getProject()).SHOW_FILE_HISTORY_AS_TREE) {
      myDualView.switchToTheTreeMode();
    }
    else {
      myDualView.switchToTheFlatMode();
    }
  }

  @NotNull
  private DefaultActionGroup fillActionGroup(boolean popup, DefaultActionGroup result) {
    if (popup) {
      result.add(ActionManager.getInstance().getAction(IdeActions.ACTION_EDIT_SOURCE));
    }

    AnAction actionGroup = ActionManager.getInstance().getAction(popup ? VCS_HISTORY_POPUP_ACTION_GROUP : VCS_HISTORY_TOOLBAR_ACTION_GROUP);
    result.add(actionGroup);
    AnAction[] additionalActions =
      myProvider.getAdditionalActions(() -> ApplicationManager.getApplication().invokeAndWait(() -> myRefresherI.refresh(true)));
    if (additionalActions != null) {
      for (AnAction additionalAction : additionalActions) {
        if (popup || additionalAction.getTemplatePresentation().getIcon() != null) {
          result.add(additionalAction);
        }
      }
    }
    if (!myIsStaticAndEmbedded) {
      result.add(new MyShowDetailsAction());
    }

    if (!popup && myHistorySession.getHistoryAsTreeProvider() != null) {
      result.add(new MyShowAsTreeAction());
    }

    return result;
  }

  @Override
  public Object getData(@NotNull String dataId) {
    if (CommonDataKeys.NAVIGATABLE.is(dataId)) {
      VcsFileRevision[] selectedRevisions = getSelectedRevisions();
      if (selectedRevisions.length != 1) return null;
      VcsFileRevision firstSelectedRevision = ArrayUtil.getFirstElement(selectedRevisions);
      if (!myHistorySession.isContentAvailable(firstSelectedRevision)) {
        return null;
      }
      VirtualFile virtualFileForRevision = createVirtualFileForRevision(firstSelectedRevision);
      if (virtualFileForRevision != null) {
        return new OpenFileDescriptor(myVcs.getProject(), virtualFileForRevision);
      }
      else {
        return null;
      }
    }
    else if (CommonDataKeys.PROJECT.is(dataId)) {
      return myVcs.getProject();
    }
    else if (VcsDataKeys.VCS_FILE_REVISION.is(dataId)) {
      return ArrayUtil.getFirstElement(getSelectedRevisions());
    }
    else if (VcsDataKeys.VCS_NON_LOCAL_HISTORY_SESSION.is(dataId)) {
      return !myHistorySession.hasLocalSource();
    }
    else if (VcsDataKeys.VCS.is(dataId)) {
      return myVcs.getKeyInstanceMethod();
    }
    else if (VcsDataKeys.VCS_FILE_REVISIONS.is(dataId)) {
      return getSelectedRevisions();
    }
    else if (VcsDataKeys.REMOTE_HISTORY_CHANGED_LISTENER.is(dataId)) {
      return (Consumer<String>)s -> myDualView.rebuild();
    }
    else if (VcsDataKeys.CHANGES.is(dataId)) {
      return getChanges();
    }
    else if (VcsDataKeys.VCS_VIRTUAL_FILE.is(dataId)) {
      VcsFileRevision[] selectedRevisions = getSelectedRevisions();
      if (selectedRevisions.length == 0) return null;
      return createVirtualFileForRevision(ArrayUtil.getFirstElement(selectedRevisions));
    }
    else if (VcsDataKeys.FILE_PATH.is(dataId)) {
      return myFilePath;
    }
    else if (VcsDataKeys.IO_FILE.is(dataId)) {
      return myFilePath.getIOFile();
    }
    else if (CommonDataKeys.VIRTUAL_FILE.is(dataId)) {
      VirtualFile virtualFile = myFilePath.getVirtualFile();
      return virtualFile == null || !virtualFile.isValid() ? null : virtualFile;
    }
    else if (VcsDataKeys.FILE_HISTORY_PANEL.is(dataId)) {
      return this;
    }
    else if (VcsDataKeys.HISTORY_SESSION.is(dataId)) {
      return myHistorySession;
    }
    else if (VcsDataKeys.HISTORY_PROVIDER.is(dataId)) {
      return myProvider;
    }
    else if (PlatformDataKeys.COPY_PROVIDER.is(dataId)) {
      return this;
    }
    else if (PREVIOUS_REVISION_FOR_DIFF.is(dataId)) {
      TableView<TreeNodeOnVcsRevision> flatView = myDualView.getFlatView();
      if (flatView.getSelectedRow() == (flatView.getRowCount() - 1)) {
        // no previous
        return myBottomRevisionForShowDiff != null ? myBottomRevisionForShowDiff : VcsFileRevision.NULL;
      }
      else {
        return flatView.getRow(flatView.getSelectedRow() + 1).getRevision();
      }
    }
    else if (VcsInternalDataKeys.FILE_HISTORY_REFRESHER.is(dataId)) {
      return myRefresherI;
    }
    else if (PlatformDataKeys.HELP_ID.is(dataId)) {
      return myHelpId;
    }
    return null;
  }

  @Nullable
  private Change[] getChanges() {
    final VcsFileRevision[] revisions = getSelectedRevisions();

    if (revisions.length > 0) {
      Arrays.sort(revisions, comparing(VcsRevisionDescription::getRevisionNumber));

      for (VcsFileRevision revision : revisions) {
        if (!myHistorySession.isContentAvailable(revision)) {
          return null;
        }
      }

      final ContentRevision startRevision = new LoadedContentRevision(myFilePath, revisions[0], myVcs.getProject());
      final ContentRevision endRevision = (revisions.length == 1) ? new CurrentContentRevision(myFilePath) :
                                          new LoadedContentRevision(myFilePath, revisions[revisions.length - 1], myVcs.getProject());

      return new Change[]{new Change(startRevision, endRevision)};
    }
    return null;
  }

  private VirtualFile createVirtualFileForRevision(VcsFileRevision revision) {
    if (!myRevisionToVirtualFile.containsKey(revision)) {
      FilePath filePath = (revision instanceof VcsFileRevisionEx ? ((VcsFileRevisionEx)revision).getPath() : myFilePath);
      myRevisionToVirtualFile.put(revision, filePath.isDirectory()
                                            ? new VcsVirtualFolder(filePath.getPath(), null, VcsFileSystem.getInstance())
                                            : new VcsVirtualFile(filePath.getPath(), revision, VcsFileSystem.getInstance()));
    }
    return myRevisionToVirtualFile.get(revision);
  }

  @NotNull
  public VcsFileRevision[] getSelectedRevisions() {
    //noinspection unchecked
    List<TreeNodeOnVcsRevision> selection = (List<TreeNodeOnVcsRevision>)myDualView.getSelection();
    VcsFileRevision[] result = new VcsFileRevision[selection.size()];
    for (int i = 0; i < selection.size(); i++) {
      result[i] = selection.get(i).getRevision();
    }
    return result;
  }

  @Override
  public void dispose() {
    myDualView.dispose();
  }

  private void refreshRevisionsOrder() {
    final List<VcsFileRevision> list = myHistorySession.getRevisionList();
    myRevisionsOrder.clear();

    int cnt = 0;
    for (VcsFileRevision revision : list) {
      myRevisionsOrder.put(revision.getRevisionNumber(), cnt);
      ++cnt;
    }
  }

  public void setIsStaticAndEmbedded(boolean isStaticAndEmbedded) {
    myIsStaticAndEmbedded = isStaticAndEmbedded;
    myDualView.setZipByHeight(isStaticAndEmbedded);
    myDualView.getFlatView().updateColumnSizes();
    if (myIsStaticAndEmbedded) {
      myDualView.getFlatView().getTableHeader().setBorder(IdeBorderFactory.createBorder(SideBorder.TOP));
      myDualView.getTreeView().getTableHeader().setBorder(IdeBorderFactory.createBorder(SideBorder.TOP));
      myDualView.getFlatView().setBorder(null);
      myDualView.getTreeView().setBorder(null);
    }
  }

  public void setBottomRevisionForShowDiff(VcsFileRevision bottomRevisionForShowDiff) {
    myBottomRevisionForShowDiff = bottomRevisionForShowDiff;
  }

  @Override
  public boolean equals(Object obj) {
    return obj instanceof FileHistoryPanelImpl && sameHistories((FileHistoryPanelImpl)obj, myFilePath, myStartingRevision);
  }

  @Override
  public int hashCode() {
    int result = myFilePath.hashCode();
    result = 31 * result + (myStartingRevision != null ? myStartingRevision.asString().hashCode() : 0); // NB: asString to conform to equals
    return result;
  }

  @Override
  public void performCopy(@NotNull DataContext dataContext) {
    String text = StringUtil.join(getSelectedRevisions(), revision -> getPresentableText(revision, true), "\n");
    CopyPasteManager.getInstance().setContents(new StringSelection(text));
  }

  @Override
  public boolean isCopyEnabled(@NotNull DataContext dataContext) {
    //noinspection unchecked
    return ((List<TreeNodeOnVcsRevision>)myDualView.getSelection()).size() > 0;
  }

  @Override
  public boolean isCopyVisible(@NotNull DataContext dataContext) {
    return true;
  }

  @Override
  public void globalSchemeChange(EditorColorsScheme scheme) {
    updateMessage();
  }

  private class TreeNodeColumnInfoWrapper<T extends Comparable<T>> extends FileHistoryColumnWrapper<T> {
    TreeNodeColumnInfoWrapper(@NotNull ColumnInfo<VcsFileRevision, T> additionalColumn) {
      super(additionalColumn);
    }

    @Override
    protected DualView getDualView() {
      return myDualView;
    }

    @Override
    public TableCellRenderer getCustomizedRenderer(TreeNodeOnVcsRevision revision, @Nullable TableCellRenderer renderer) {
      if (renderer instanceof BaseHistoryCellRenderer) {
        ((BaseHistoryCellRenderer)renderer)
          .setCurrentRevision(myHistorySession.isCurrentRevision(revision.getRevision().getRevisionNumber()));
      }
      return renderer;
    }
  }

  private abstract static class BaseHistoryCellRenderer extends ColoredTableCellRenderer {
    private boolean myIsCurrentRevision = false;

    protected SimpleTextAttributes getDefaultAttributes() {
      return myIsCurrentRevision ? SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES : SimpleTextAttributes.REGULAR_ATTRIBUTES;
    }

    public void setCurrentRevision(boolean currentRevision) {
      myIsCurrentRevision = currentRevision;
    }
  }

  public static class RevisionColumnInfo extends ColumnInfo<VcsFileRevision, VcsRevisionNumber> {
    @Nullable private final Comparator<VcsFileRevision> myComparator;
    @NotNull private final ColoredTableCellRenderer myRenderer;

    public RevisionColumnInfo(@Nullable Comparator<VcsFileRevision> comparator) {
      super(VcsBundle.message("column.name.revision.version"));
      myComparator = comparator;
      myRenderer = new BaseHistoryCellRenderer() {
        @Override
        protected void customizeCellRenderer(JTable table, Object value, boolean selected, boolean hasFocus, int row, int column) {
          setOpaque(selected);
          append(VcsUtil.getShortRevisionString((VcsRevisionNumber)value), getDefaultAttributes());
          SpeedSearchUtil.applySpeedSearchHighlighting(table, this, false, selected);
        }
      };
    }

    @Nullable
    @Override
    public VcsRevisionNumber valueOf(VcsFileRevision revision) {
      return revision.getRevisionNumber();
    }

    @Nullable
    @Override
    public Comparator<VcsFileRevision> getComparator() {
      return myComparator;
    }

    @Override
    public String getPreferredStringValue() {
      return StringUtil.repeatSymbol('m', 10);
    }

    @Nullable
    @Override
    public TableCellRenderer getRenderer(VcsFileRevision revision) {
      return myRenderer;
    }
  }

  public static class DateColumnInfo extends ColumnInfo<VcsFileRevision, Date> {
    @NotNull private final ColoredTableCellRenderer myRenderer;

    public DateColumnInfo() {
      super(VcsBundle.message("column.name.revision.date"));

      myRenderer = new BaseHistoryCellRenderer() {
        @Override
        protected void customizeCellRenderer(JTable table, Object value, boolean selected, boolean hasFocus, int row, int column) {
          setOpaque(selected);
          Date date = (Date)value;
          if (date != null) {
            append(DateFormatUtil.formatDateTime(date), getDefaultAttributes());
          }
          SpeedSearchUtil.applySpeedSearchHighlighting(table, this, false, selected);
        }
      };
    }

    @NotNull
    @Override
    public Comparator<VcsFileRevision> getComparator() {
      return comparing(revision -> valueOf(revision));
    }

    @Nullable
    @Override
    public Date valueOf(VcsFileRevision revision) {
      return revision.getRevisionDate();
    }

    @Override
    public String getPreferredStringValue() {
      return DateFormatUtil.formatDateTime(Clock.getTime() + 1000);
    }

    @Nullable
    @Override
    public TableCellRenderer getRenderer(VcsFileRevision revision) {
      return myRenderer;
    }
  }

  private static class AuthorCellRenderer extends BaseHistoryCellRenderer {
    private String myTooltipText;

    /**
     * @noinspection MethodNamesDifferingOnlyByCase
     */
    public void setTooltipText(final String text) {
      myTooltipText = text;
    }

    @Override
    protected void customizeCellRenderer(JTable table, @Nullable Object value, boolean selected, boolean hasFocus, int row, int column) {
      setToolTipText(myTooltipText);
      if (selected || hasFocus) {
        setBackground(table.getSelectionBackground());
        setForeground(table.getSelectionForeground());
      }
      else {
        setBackground(table.getBackground());
        setForeground(table.getForeground());
      }
      if (value != null) append(value.toString(), getDefaultAttributes());
      SpeedSearchUtil.applySpeedSearchHighlighting(table, this, false, selected);
    }
  }

  public static class AuthorColumnInfo extends ColumnInfo<VcsFileRevision, String> {
    private final TableCellRenderer AUTHOR_RENDERER = new AuthorCellRenderer();

    public AuthorColumnInfo() {
      super(VcsBundle.message("column.name.revision.list.author"));
    }

    @Nullable
    @Override
    public TableCellRenderer getRenderer(VcsFileRevision revision) {
      return AUTHOR_RENDERER;
    }

    @Override
    public TableCellRenderer getCustomizedRenderer(VcsFileRevision revision, TableCellRenderer renderer) {
      if (renderer instanceof AuthorCellRenderer) {
        if (revision instanceof VcsFileRevisionEx) {
          VcsFileRevisionEx ex = (VcsFileRevisionEx)revision;
          StringBuilder sb = new StringBuilder(StringUtil.notNullize(ex.getAuthor()));
          if (ex.getAuthorEmail() != null) sb.append(" <").append(ex.getAuthorEmail()).append(">");
          if (ex.getCommitterName() != null && !Comparing.equal(ex.getAuthor(), ex.getCommitterName())) {
            sb.append(", via ").append(ex.getCommitterName());
            if (ex.getCommitterEmail() != null) sb.append(" <").append(ex.getCommitterEmail()).append(">");
          }
          ((AuthorCellRenderer)renderer).setTooltipText(sb.toString());
        }
      }

      return renderer;
    }

    @Nullable
    @Override
    public String valueOf(VcsFileRevision revision) {
      if (revision instanceof VcsFileRevisionEx) {
        if (!Comparing.equal(revision.getAuthor(), ((VcsFileRevisionEx)revision).getCommitterName())) {
          return revision.getAuthor() + "*";
        }
      }
      return revision.getAuthor();
    }

    @Override
    @NonNls
    public String getPreferredStringValue() {
      return StringUtil.repeatSymbol('m', 14);
    }

    @NotNull
    @Override
    public Comparator<VcsFileRevision> getComparator() {
      return comparing(revision -> valueOf(revision));
    }
  }

  public static class MessageColumnInfo extends ColumnInfo<VcsFileRevision, String> {
    private final ColoredTableCellRenderer myRenderer;
    private final IssueLinkRenderer myIssueLinkRenderer;

    public MessageColumnInfo(Project project) {
      super(COMMIT_MESSAGE_TITLE);
      myRenderer = new BaseHistoryCellRenderer() {
        @Override
        protected void customizeCellRenderer(JTable table, Object value, boolean selected, boolean hasFocus, int row, int column) {
          setOpaque(selected);
          if (value instanceof String) {
            String message = (String)value;
            myIssueLinkRenderer.appendTextWithLinks(message, getDefaultAttributes());
            SpeedSearchUtil.applySpeedSearchHighlighting(table, this, false, selected);
          }
        }
      };
      myIssueLinkRenderer = new IssueLinkRenderer(project, myRenderer);
    }

    @NotNull
    public static String getSubject(@NotNull VcsFileRevision object) {
      final String originalMessage = object.getCommitMessage();
      if (originalMessage == null) return "";

      int index = StringUtil.indexOfAny(originalMessage, "\n\r");
      return index == -1 ? originalMessage : originalMessage.substring(0, index);
    }

    @Nullable
    @Override
    public String valueOf(VcsFileRevision revision) {
      return getSubject(revision);
    }

    @Override
    public String getPreferredStringValue() {
      return StringUtil.repeatSymbol('m', 80);
    }

    @Nullable
    @Override
    public TableCellRenderer getRenderer(VcsFileRevision revision) {
      return myRenderer;
    }

    @NotNull
    @Override
    public Comparator<VcsFileRevision> getComparator() {
      return comparing(revision -> valueOf(revision));
    }
  }

  private static class LoadedContentRevision implements ByteBackedContentRevision {
    private final FilePath myFile;
    private final VcsFileRevision myRevision;
    private final Project myProject;

    private LoadedContentRevision(final FilePath file, final VcsFileRevision revision, final Project project) {
      myFile = file;
      myRevision = revision;
      myProject = project;
    }

    @Override
    public String getContent() throws VcsException {
      try {
        return VcsHistoryUtil.loadRevisionContentGuessEncoding(myRevision, myFile.getVirtualFile(), myProject);
      }
      catch (IOException e) {
        throw new VcsException(VcsBundle.message("message.text.cannot.load.revision", e.getLocalizedMessage()));
      }
    }

    @Nullable
    @Override
    public byte[] getContentAsBytes() throws VcsException {
      try {
        return VcsHistoryUtil.loadRevisionContent(myRevision);
      }
      catch (IOException e) {
        throw new VcsException(VcsBundle.message("message.text.cannot.load.revision", e.getLocalizedMessage()));
      }
    }

    @Override
    @NotNull
    public FilePath getFile() {
      return myFile;
    }

    @Override
    @NotNull
    public VcsRevisionNumber getRevisionNumber() {
      return myRevision.getRevisionNumber();
    }
  }

  private static class MyTreeCellRenderer implements TreeCellRenderer {
    private final TreeCellRenderer myDefaultCellRenderer;
    private final Getter<? extends VcsHistorySession> myHistorySession;

    MyTreeCellRenderer(final TreeCellRenderer defaultCellRenderer, final Getter<? extends VcsHistorySession> historySession) {
      myDefaultCellRenderer = defaultCellRenderer;
      myHistorySession = historySession;
    }

    @Override
    public Component getTreeCellRendererComponent(JTree tree,
                                                  Object value,
                                                  boolean selected,
                                                  boolean expanded,
                                                  boolean leaf,
                                                  int row,
                                                  boolean hasFocus) {
      final Component result = myDefaultCellRenderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);

      final TreePath path = tree.getPathForRow(row);
      if (path == null) return result;
      TreeNodeOnVcsRevision node = row >= 0 ? ((TreeNodeOnVcsRevision)path.getLastPathComponent()) : null;

      if (node != null) {
        if (myHistorySession.get().isCurrentRevision(node.getRevision().getRevisionNumber())) {
          makeBold(result);
        }
        if (!selected && myHistorySession.get().isCurrentRevision(node.getRevision().getRevisionNumber())) {
          result.setBackground(new JBColor(new Color(188, 227, 231), new Color(188, 227, 231)));
        }
        ((JComponent)result).setOpaque(false);
      }
      else if (selected) {
        result.setBackground(UIUtil.getTableSelectionBackground());
      }
      else {
        result.setBackground(UIUtil.getTableBackground());
      }

      return result;
    }
  }

  private static class MyCellWrapper implements CellWrapper {
    private final Getter<? extends VcsHistorySession> myHistorySession;

    MyCellWrapper(final Getter<? extends VcsHistorySession> historySession) {
      myHistorySession = historySession;
    }

    @Override
    public void wrap(Component component,
                     JTable table,
                     Object value,
                     boolean isSelected,
                     boolean hasFocus,
                     int row,
                     int column,
                     Object treeNode) {
      VcsFileRevision revision = ((TreeNodeOnVcsRevision)treeNode).getRevision();
      if (myHistorySession.get().isCurrentRevision(revision.getRevisionNumber())) {
        makeBold(component);
      }
    }
  }

  private class MyShowAsTreeAction extends ToggleAction implements DumbAware {
    MyShowAsTreeAction() {
      super(VcsBundle.message("action.name.show.files.as.tree"), null, PlatformIcons.SMALL_VCS_CONFIGURABLE);
    }

    @Override
    public boolean isSelected(@NotNull AnActionEvent e) {
      return VcsConfiguration.getInstance(myVcs.getProject()).SHOW_FILE_HISTORY_AS_TREE;
    }

    @Override
    public void setSelected(@NotNull AnActionEvent e, boolean state) {
      VcsConfiguration.getInstance(myVcs.getProject()).SHOW_FILE_HISTORY_AS_TREE = state;
      chooseView();
    }
  }

  private class MyShowDetailsAction extends ToggleAction implements DumbAware {

    MyShowDetailsAction() {
      super("Show Details", "Display details panel", AllIcons.Actions.PreviewDetailsVertically);
    }

    @Override
    public boolean isSelected(@NotNull AnActionEvent e) {
      return VcsConfiguration.getInstance(myVcs.getProject()).SHOW_FILE_HISTORY_DETAILS;
    }

    @Override
    public void setSelected(@NotNull AnActionEvent e, boolean state) {
      VcsConfiguration.getInstance(myVcs.getProject()).SHOW_FILE_HISTORY_DETAILS = state;
      setupDetails();
    }
  }
}


text:
'use strict'

const db = require('APP/db')
const Product = db.model('product')

const { assertAdmin } = require('./auth.filters')

module.exports = require('express').Router()
  .param('id',
  (req, res, next, id) => {
    Product.findById(id)
      .then(product => {
        if (!product) res.sendStatus(404)
        req.requestProduct = product
        next()
        return null
      })
      .catch(next)
  })
  .get('/',
  (req, res, next) =>
    Product.findAll()
      .then(product => res.json(product))
      .catch(next))
  .post('/', assertAdmin,
  (req, res, next) =>
    Product.create(req.body)
      .then(user => res.status(201).json(user))
      .catch(next))
  .get('/:productId',
  (req, res, next) => {
    res.json(req.requestedProduct)
      .catch(next)
  })
  .put('/:productId', assertAdmin,
  (req, res, next) =>
    req.requestedProduct.update(req.body)
      .then(product => {
        res.json(product)
      })
      .catch(next))
  .delete('/:productId', assertAdmin,
  (req, res, next) => {
    req.requestedUser.destroy()
      .then(() => res.sendStatus(204))
      .catch(next)
  })

redpajama_set_name: RedPajamaGithub


text:
#pragma once

#include "../container.hpp"

namespace morda{

/**
 * @brief Pile container widget.
 * Pile container is a container which lays out its children in a pile, each widget is centered inside of the container.
 * From GUI script it can be instantiated as 'pile'.
 */
class pile : public container{
public:
	pile(const pile&) = delete;
	pile& operator=(const pile&) = delete;

	/**
	 * @brief Constructor.
	 * @param c - context.
	 * @param desc - description of the widget.
	 */
	pile(std::shared_ptr<morda::context> c, const treeml::forest& desc);

public:
	morda::vector2 measure(const morda::vector2& quotum)const override;

	void lay_out() override;
};

}


text:
local common = require('test_scripts/API/VehicleData/common')

--[[ Scenario ]]
common.runner.Title("Preconditions")
common.runner.Step("Clean environment and update preloaded_pt file", common.preconditions)
common.runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start)

common.runner.Title("Test")
for param in common.spairs(common.getVDParams(true)) do
  common.runner.Step("Register App_1", common.registerApp, { common.app[1] })
  common.runner.Step("Register App_2", common.registerAppWOPTU, { common.app[2] })
  common.runner.Title("VD parameters: " .. param)
  common.runner.Step("App1 subscribes to VD " .. param,
    common.processSubscriptionRPC, { common.rpc.sub, param, common.app[1], common.isExpectedSubscription })
  common.runner.Step("App2 subscribes to VD " .. param,
    common.processSubscriptionRPC, { common.rpc.sub, param, common.app[2], common.isNotExpectedSubscription })
  common.runner.Step("OnVehicleData for both apps", common.sendOnVehicleDataTwoApps,
    { param, common.isExpected, common.isExpected })
  common.runner.Step("Unregister App1 without unsubscribes from VD " .. param,
    common.unregisterAppWithUnsubscription, { param, common.app[1], common.isNotExpectedSubscription })
  common.runner.Step("OnVehicleData for both apps", common.sendOnVehicleDataTwoApps,
    { param, common.isNotExpected, common.isExpected })
  common.runner.Step("Unregister App2 with unsubscribes from VD " .. param,
    common.unregisterAppWithUnsubscription, { param, common.app[2], common.isExpectedSubscription })
  common.runner.Step("OnVehicleData for both apps", common.sendOnVehicleDataTwoApps,
    { param, common.isNotExpected, common.isNotExpected })
end

common.runner.Title("Postconditions")
common.runner.Step("Stop SDL", common.postconditions)


text:
#region License and Terms

// CustomExtensions - Custom Extension Methods For C#
// Copyright (c) 2011 - 2013 Jonathan Comtois. All rights reserved.
//
// 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.

#endregion

using CustomExtensions.UnitTests.Customization.Customizations;

namespace CustomExtensions.UnitTests.Customization.Fixtures
{
    public class LatinMultipleMockingFixture : BaseFixture
    {
        public LatinMultipleMockingFixture(int repeatCount = 3) : base(repeatCount)
        {
            Customize(new LatinMultipleMockingCustomization());
        }
    }
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
Atti Ist. bot. Univ. Lab. crittog. Pavia, Sér. 5 10(1): 47, 73 (1953)

#### Original name
Enterostigmatomyces Cif. & Tomas.

### Remarks
null


text:
package com.hp.security.jauth.admin.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.hp.security.jauth.core.model.Config;
import com.hp.security.jauth.core.util.Constants;

import freemarker.template.TemplateException;

/**
 * @author huangyiq
 * yiqingh@hp.com
 */
@Controller
@RequestMapping("config")
public class ConfigController extends BaseController {

    @RequestMapping("view")
    public String view(HttpServletRequest request, HttpServletResponse response, Model model) throws IOException,
            TemplateException {
        List<Config> configs = configService.findAll();
        Map<String, Object> root = new HashMap<String, Object>();
        root.put("configs", configs);
        model.addAttribute(configs);
        return super.baseReturn(request, response, root, "config");
    }

    @RequestMapping("detail")
    public String detail(@RequestParam(required = false) String key, HttpServletRequest request,
            HttpServletResponse response, Model model) throws IOException, TemplateException {
        Map<String, Object> root = new HashMap<String, Object>();
        if (null != key) {
            Config config = configService.findByKey(key);
            root.put("config", config);
            model.addAttribute(config);
        }
        return super.baseReturn(request, response, root, "config_detail");
    }

    @RequestMapping("update")
    public void update(Config config, HttpServletRequest request, HttpServletResponse response, Model model) throws IOException,
            TemplateException {
        configService.update(config);
        model.addAttribute(Constants.SUCCESS);
        view(request, response, model);
    }

    @RequestMapping("save")
    public void save(Config config, HttpServletRequest request, HttpServletResponse response, Model model) throws IOException,
            TemplateException {
        configService.save(config);
        model.addAttribute(Constants.SUCCESS);
        view(request, response, model);
    }

}


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
org.slf4j.instrumentation (SLF4J 1.7.21 Test API)
</TITLE>

<META NAME="date" CONTENT="2016-04-04">

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

org.slf4j.instrumentation

Classes

ToStringHelperTest


text:
require File.dirname(__FILE__) + '/spec_helper'

class StringSerializer < YARD::Serializers::Base
  attr_accessor :files, :string
  def initialize(files, string)
    @files = files
    @string = string
  end

  def serialize(object, data)
    files << object
    string << data
  end
end

RSpec.describe YARD::Templates::Engine.template(:default, :onefile) do
  before do
    Registry.clear
    if defined?(::Encoding)
      @eenc = Encoding.default_external
      Encoding.default_external = 'ascii-8bit'
      @ienc = Encoding.default_internal
      Encoding.default_internal = 'ascii-8bit'
    end
  end

  after do
    if defined?(::Encoding)
      Encoding.default_internal = @ienc
      Encoding.default_external = @eenc
    end
  end

  def render
    @files = []
    @output = String.new("")
    YARD.parse_string <<-eof
      class A
        # Foo method
        # @return [String]
        def foo; end

        # Bar method
        # @return [Numeric]
        def bar; end
      end
    eof
    readme = CodeObjects::ExtraFileObject.new('README',
      "# This is a code comment\n\n# Top of file\n\n\nclass C; end")
    Templates::Engine.generate Registry.all(:class),
      :serializer => StringSerializer.new(@files, @output),
      :onefile => true, :format => :html, :readme => readme, :files => [readme,
        CodeObjects::ExtraFileObject.new('LICENSE', 'This is a license!')]
  end

  it "renders html" do
    render
    expect(@files).to eq ['index.html']
    expect(@output).to include("This is a code comment")
    expect(@output).to include("This is a license!")
    expect(@output).to include("Class: A")
    expect(@output).to include("Foo method")
    expect(@output).to include("Bar method")
  end
end


text:
import * as repository from '../repository';
import Aggregate from '../aggregate';

export default class CommandHandler {

  get module() {
    return this.__module;
  }

  get repository() {
    return repository.getRepository();
  }

  getAggregate(name, module) {
    return Aggregate.get(name, module || this.module);
  }

}


text:
class TokenService
  def self.build(friendly_id:, password:)
    "#{friendly_id}#{password}"
  end

  def self.extract(token:)
    begin
      friendly_id = token[0..4]
      password    = token[5..-1]
    rescue Exception => e
      friendly_id, password = nil
    end

    return {
      friendly_id: friendly_id,
      password: password
    }
  end
end


text:
package net.twibs.demo

import java.awt.Desktop
import java.io.File
import java.net.URI

import net.twibs.util.RunMode
import org.eclipse.jetty.server.Server
import org.eclipse.jetty.webapp.WebAppContext

object Demo {
  def main(args: Array[String]): Unit = {
    val port = 9905
    System.setProperty(RunMode.SYSTEM_PROPERTY_NAME, RunMode.DEVELOPMENT.name)
    val server = new Server(port)
    server.setStopAtShutdown(true)
    val webAppContext = new WebAppContext()
    webAppContext.setClassLoader(Thread.currentThread.getContextClassLoader)
    webAppContext.setContextPath("")
    webAppContext.setResourceBase(new File("src/main/webapp").getAbsolutePath)
    webAppContext.addFilter(classOf[DemoFilter], "/*", null)
    server.setHandler(webAppContext)
    server.start()
    Desktop.getDesktop.browse(new URI(s"http://localhost:$port"))
  }
}


text:
use std::time::{Duration, SystemTime, UNIX_EPOCH};

/// Return the numeric value corresponding to the time for the specified date
/// according to universal time. The value returned is the number of milliseconds
/// since 1 January 1970 00:00:00.
pub(crate) fn get_time(time: SystemTime) -> u64 {
    time.duration_since(UNIX_EPOCH)
        .unwrap_or_else(|_| Duration::from_secs(0))
        .as_millis() as u64
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::{Duration, UNIX_EPOCH};

    #[test]
    fn test_get_time() {
        assert_eq!(0, get_time(UNIX_EPOCH));
        assert_eq!(0, get_time(UNIX_EPOCH + Duration::from_nanos(1)));
        assert_eq!(1, get_time(UNIX_EPOCH + Duration::from_millis(1)));
        assert_eq!(1000, get_time(UNIX_EPOCH + Duration::from_secs(1)));
    }
}


text:
//
//  XKMeViewController.m
//  百思不得姐
//
//  Created by MD313  on 15/9/1.
//  Copyright (c) 2015年 xiaokai. All rights reserved.
//

#import "XKMeViewController.h"
#import "XKSettingViewController.h"
#import "XKMeCell.h"
#import "XKMeFooterView.h"
#import "XKViewForFooterSection.h"

@interface XKMeViewController ()

@end

@implementation XKMeViewController

static NSString * const XKMeCellID = @"meCell";

- (void)viewDidLoad {
    [super viewDidLoad];
    // 设置导航控制器
    [self setupNav];
    // 设置内容
    [self setupTable];
}
/**
 *  设置内容
 */
- (void)setupTable
{
    // 注册
    [self.tableView registerClass:[XKMeCell class] forCellReuseIdentifier:XKMeCellID];
    // cell头部间距
    self.tableView.sectionHeaderHeight = 0;
    // 内边距
    self.tableView.contentInset = UIEdgeInsetsMake(-25, 0, 0, 0);

    self.tableView.tableFooterView = [[XKMeFooterView alloc] init];
}
/**
 *  设置导航控制器
 */
- (void)setupNav
{
    self.navigationItem.title = @"我的";
    // 导航栏右边按钮
    UIBarButtonItem *moonItem = [UIBarButtonItem itemWithImage:@"mine-moon-icon" highImage:@"mine-moon-icon-click" target:self action:@selector(moonClick)];
    UIBarButtonItem *settingItem = [UIBarButtonItem itemWithImage:@"mine-setting-icon" highImage:@"mine-setting-icon-click" target:self action:@selector(settingClick)];

    self.navigationItem.rightBarButtonItems = @[settingItem, moonItem];

    // 背景颜色
    self.view.backgroundColor = XKCommonBgColor;
}
- (void)moonClick
{
    XKLog(@"%s",__func__);
}
- (void)settingClick
{
    XKSettingViewController *setting = [[XKSettingViewController alloc] initWithStyle:UITableViewStyleGrouped];

    [self.navigationController pushViewController:setting animated:YES];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    XKMeCell *cell = [tableView dequeueReusableCellWithIdentifier:XKMeCellID];
    if (indexPath.section == 0) {
        cell.textLabel.text = @"登录/注册";
        cell.imageView.image = [UIImage imageNamed:@"defaultUserIcon"];
    }else{
        cell.textLabel.text = @"离线下载";
    }

    return cell;
}

//- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
//{
//    if (section == 0) {
//        return [[XKViewForFooterSection alloc] init];
//    }
//    return nil;
//}
@end


text:
package edu.stanford.nlp.stats;

import java.util.Random;

/**
 * This is an interface for probability measures, which will allow
 * samples to be drawn and the probability of objects computed.
 *
 * @author Jenny Finkel
 */

public interface ProbabilityDistribution<E> extends java.io.Serializable {

  public double probabilityOf(E object) ;
  public double logProbabilityOf(E object) ;
  public E drawSample(Random random) ;

}


text:
using System;
using System.Collections.ObjectModel;

namespace OOPvsFunc
{
    public class SwitchMenuGUI : IGUI
    {
        public IAction GetAction()
        {
            string input = Console.ReadLine();

            switch (input)
            {
                case "n":
                    return new SwitchMenuAction(new TerminalGUI());
                case "p":
                    return new SwitchMenuAction(new PrettyTerminalGUI());
                case "s":
                    return new SwitchMenuAction(new SimpleMenuGUI());
                default:
                    Console.WriteLine("Please enter a correct input\n----------------------\n");
                    throw new FormatException();
            }
        }

        public void ShowMenu()
        {
            Console.WriteLine(@"Hello welcome to the personprogram.
            Enter n for Normal Menu
            Enter p for Pretty Menu
            Enter s for Simple Menu
            ");
        }

        public void ShowPeople(ReadOnlyCollection<Person> people)
        {
            throw new InvalidOperationException();
        }
    }
}


text:
package de.neue_phase.asterisk.ClickDial.settings.extractModels;

public class ExtractAsteriskManagerInterfaceConnectionData implements ISettingsExtractModel {
    private String hostname;
    private Integer port;

    public ExtractAsteriskManagerInterfaceConnectionData (String hostname, String port) {
        this.hostname = hostname;
        this.port = new Integer(port);
    }

    public ExtractAsteriskManagerInterfaceConnectionData (String hostname, Integer port) {
        this.hostname = hostname;
        this.port = port;
    }

    public String getHostname () {
        return hostname;
    }

    public Integer getPort () {
        return port;
    }

    public String getConnectionString () {
        return hostname +":"+ port.toString ();
    }
}


text:
from __future__ import absolute_import, division, print_function, unicode_literals

class EasyPDFError(Exception):
    """
    Base error class
    """

class UnsupportedMediaPathException(EasyPDFError):
    """
    Resource not found or unavailable
    """

class PDFRenderingError(EasyPDFError):
    """
    PDF Rendering error. Check HTML template for errors.
    """

    def __init__(self, message, content, log, *args, **kwargs):
        super(PDFRenderingError, self).__init__(message, *args, **kwargs)
        self.content = content
        self.log = log


text:
from model.group import Group

class GroupHelper:

    def __init__(self, app):
        self.app = app

    def open_group_page(self):
        if not (self.app.wd.current_url.endswith('/group.php') and len(self.app.wd.find_elements_by_name("new"))>0):
            self.app.wd.find_element_by_link_text("groups").click()

    def return_to_group_page(self):
        self.app.wd.find_element_by_link_text("group page").click()

    def select_first(self):
        self.app.wd.find_element_by_name("selected[]").click()

    def click_delete(self):
        self.app.wd_helper.click_button('delete')

    def click_edit(self):
        self.app.wd_helper.click_button('edit')

    def click_update(self):
        self.app.wd.find_element_by_name('update').click()

    def count(self):
        return len(self.app.wd.find_elements_by_name("selected[]"))

    def group_exists(self):
        return self.count() > 0

    def change_fields(self, group):
        self.click_edit()
        self.app.wd_helper.fill_field(field_name='group_name', field_text=group.name)
        self.app.wd_helper.fill_field(field_name='group_header', field_text=group.header)
        self.app.wd_helper.fill_field(field_name='group_footer', field_text=group.footer)
        self.click_update()
        self.app.group_helper.return_to_group_page()

    def edit_all_fields(self):
        self.click_edit()
        #fill group params
        group = Group(self.app.wd_helper.get_field_val('group_name') + '_edit',
                      self.app.wd_helper.get_field_val('group_header') + '_edit',
                      self.app.wd_helper.get_field_val('group_footer') + '_edit')
        self.app.wd_helper.fill_field(field_name='group_name', field_text=group.name)
        self.app.wd_helper.fill_field(field_name='group_header', field_text=group.header)
        self.app.wd_helper.fill_field(field_name='group_footer', field_text=group.footer)
        self.click_update()
        self.app.group_helper.return_to_group_page()

    def add(self, group):
        #click group creation button
        self.app.wd.find_element_by_name("new").click()
        #fill group params
        self.app.wd_helper.fill_field(field_name='group_name', field_text=group.name)
        self.app.wd_helper.fill_field(field_name='group_header', field_text=group.header)
        self.app.wd_helper.fill_field(field_name='group_footer', field_text=group.footer)
        #click submit button
        self.app.wd.find_element_by_name("submit").click()
        self.app.group_helper.return_to_group_page()


text:
<?php

namespace Dock\Docker\Dns;

interface ContainerAddressResolver
{
    /**
     * Get DNS addresses for the given container.
     *
     * @param string $containerName
     * @param string $imageName
     *
     * @return string[]
     */
    public function getDnsByContainerNameAndImage($containerName, $imageName);
}


text:
This document assumes you have a Linux machine (or VM), and that you have a brand new Ubuntu Linux environment setup, but does not assume familiarity with Linux. If you don't have a Linux environment and you're using Windows, you may want to read instructions on how to setup a Linux VM on Windows first.

Before you begin please make sure you can connect to your Linux machine and login. Command line instructions for Linux will be shown starting with `$`; you should only type the text following the `$`.

## Basic Setup
Based on instructions from: https://docs.docker.com/engine/installation/linux/ubuntulinux/

This will update Linux and get curl and vim, which you'll need later.
```
$ sudo apt-get update
$ sudo apt-get upgrade
$ sudo apt-get install curl
$ sudo apt-get install vim
```
Unless you have another text editor you prefer, vim may be useful for beginners; instructions below use vim.

### Initial checks
```
$ uname -r
```
You should get `3.2.0-23-generic`, `3.13.0-88-generic`, or something similar depending on what the current version is.

```
$ lsb_release -a
```
^ You should get a response like:
```
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 12.04.5 LTS
Release:        12.04
Codename:       precise
```

## Get Kubernetes

```
$ curl -O https://storage.googleapis.com/kubernetes-release/release/v1.2.4/bin/linux/amd64/kubectl
```
*This will take a while.*

## Get Vagrant on Linux

```
$ sudo apt-get install vagrant
$ cd kubernetes
$ export KUBERNETES_PROVIDER=vagrant
$ ./cluster/kube-up.sh
```
*Note that the last command will throw a lot of errors.*

## Install Git
```
$ sudo apt-get install git
$ git --version
```
These instructions were last tested with git version 1.7.9.5.

## Clone the Dashboard Repo
```
git clone https://github.com/kubernetes/dashboard.git
```

## Install Kubernetes Dashboard Requirements

See the requirement list on the [Getting Started page](getting-started.md).

### Install Docker

Based on instructions from: https://docs.docker.com/engine/installation/linux/ubuntulinux/

#### Setup
```
$ sudo apt-get update
$ sudo apt-get install apt-transport-https ca-certificates
$ sudo apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D
```

```
$ cd /etc/apt/sources.list.d/
$ sudo vim docker.list
```
* i = insert
* Type `deb https://apt.dockerproject.org/repo ubuntu-precise main`
* Esc = stops inserting
* `:x` = exits and saves

```
$ sudo apt-get update
$ sudo apt-get purge lxc-docker
$ apt-cache policy docker-engine
```

#### Only needed for Ubuntu Precise 12.04
```
$ sudo apt-get update
$ sudo apt-get install linux-image-generic-lts-trusty
$ sudo reboot
```
#### Do the Docker install
```
$ sudo apt-get update
$ sudo apt-get install docker-engine
$ sudo service docker start
$ sudo docker run hello-world
```

You should receive a message that includes: `This message shows that your installation appears to be working correctly`.

#### Configure Docker for your user
Based on instructions from https://docs.docker.com/engine/installation/linux/ubuntulinux/#create-a-docker-group

The example below uses "username" as a placeholder. Please substitute with the user you are logged in as, which can be seen by using `$ id`.
If you are running Linux in a VM using Vagrant, your username will be "vagrant".

```
$ sudo groupadd docker
$ sudo usermod -aG docker username
$ env
$ sudo reboot
$ docker run hello-world
```

You should get the same message as above, that includes: `This message shows that your installation appears to be working correctly`.

`$ status docker` --> should say  "docker start/running, process [some number]"
`$ docker ps` --> should show a table of information (or at least headers)

### Install Go

Get the latest download URL from https://golang.org/dl/
```
$ wget https://storage.googleapis.com/golang/go1.6.2.linux-amd64.tar.gz
```
*Add Go to the path*
```
$ go version
```
Should return something like `go version go1.6.2 linux/amd64`

### Install Node and NPM
For some reason doing this...
```
$ sudo apt-get install nodejs
```
... gives a much older version, so instead we will get the more recent version:
```
$ curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -
$ sudo apt-get install -y nodejs
$ node -v
$ npm -v
```
Should return `v6.2.1` and `3.9.3` respectively.

### Install Java 7
```
$ sudo apt-get install openjdk-7-jre
$ java -version
```
Should return `java version "1.7.0_101"`.

### Install Gulp using npm
```
$ sudo npm install --global gulp-cli
$ sudo npm install --global gulp
$ gulp -v
```
Should return `CLI version 3.9.1` and `Local version 3.9.1`.

## Install Other Dashboard Dependencies Automatically with NPM

```
$ cd /dashboard
$ npm install
```
This will install all the dependencies that are in the `package.json` file.

## Run the Kubernetes Cluster
```
$ gulp local-up-cluster
```
If you need to stop the cluster you can run `$ docker kill $(docker ps -aq)`

```
$ gulp serve
```

Now you may [continue with the Getting Started guide](getting-started.md) to learn more about developing with the Kubernetes Dashboard.


text:
'use strict';
import Koa from 'koa'
import log from './utils/log'
import middleware from './middleware'
import { connectDatabase } from './db/mongodb'
import api from './api'
import config from './config'
const port = config.port
const app = new Koa()

app.use(async (ctx, next) => {
  const start = new Date();
  await next();
  const ms = new Date() - start;
  log.info(`${ctx.method} ${decodeURIComponent(ctx.url)} ${ctx.status} - ${ms}ms`);
});
app.use(middleware())
app.use(api())
app.use(ctx => ctx.status = 404)

;(async () => {
  try {
    const db = await connectDatabase(config.mongoDB)
    log.info(`Connected to ${db.host}:${db.port}/${db.name}`)
    await app.listen(port, () => log.info(`Server started on port ${port}`))
  } catch(e) {
    log.error(e);
  }
})()

export default app


text:
from typing import Any, Callable, Dict

from django.http import HttpRequest, HttpResponse
from django.utils.translation import ugettext as _

from zerver.decorator import api_key_only_webhook_view
from zerver.lib.actions import check_send_stream_message
from zerver.lib.request import REQ, has_request_variables
from zerver.lib.response import json_error, json_success
from zerver.models import UserProfile

@api_key_only_webhook_view('Zapier')
@has_request_variables
def api_zapier_webhook(request: HttpRequest, user_profile: UserProfile,
                       payload: Dict[str, Any]=REQ(argument_type='body'),
                       stream: str=REQ(default='zapier')) -> HttpResponse:
    subject = payload.get('subject')
    content = payload.get('content')
    if subject is None:
        return json_error(_("Subject can't be empty"))
    if content is None:
        return json_error(_("Content can't be empty"))
    check_send_stream_message(user_profile, request.client, stream, subject, content)
    return json_success()


text:
import bz2
import os
import sqlite3
import sys

dumpfile = sys.argv[1] if len(sys.argv) > 1 else 'openvectors.dump.bz2'

ch = raw_input("This will re-write the existing openvectors.db. Continue?(y/n):").lower()

if ch == 'y':
    try:
        os.remove('openvectors.db')
        os.remove('openvectors.dump')
    except:
        pass
    zipfile = bz2.BZ2File(dumpfile)
    data = zipfile.read()
    dump = dumpfile[:-4]
    open(dump, 'wb').write(data)
    f = open(dump, 'r+')
    s = [y for x, y in enumerate(f) if x not in [line - 1 for line in range(3, 9)]]
    f.seek(0)
    f.write(''.join(s))
    f.truncate(f.tell())
    f.close()

    con = sqlite3.connect('openvectors.db')
    cursor = con.cursor()
    try:
        cursor.executescript(
            'CREATE TABLE open_vectors (id INTEGER NOT NULL,word TEXT(65),vector TEXT,PRIMARY KEY (id));')
    except:
        pass

    with open(dump, 'r') as f:
        for line in f:
            cursor.executescript(line)

    con.close()
    os.remove('openvectors.dump')
    print "openvectors.db has been populated!"


text:
fpath=($DOTFILES/onepassword/functions $fpath)
autoload -U $DOTFILES/onepassword/functions/*(:t)


text:
package com.soprasteria.initiatives.auth;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.mongodb.repository.config.EnableReactiveMongoRepositories;

@SpringBootApplication
@EnableReactiveMongoRepositories
public class InitiativesAuthApplication {

    public static void main(String[] args) {
        SpringApplication.run(InitiativesAuthApplication.class, args);
    }

}


text:
from OpenGLCffi.GLES3 import params
@params(api='gles3', prms=['texture', 'level', 'format', 'type', 'data'])
def glClearTexImageEXT(texture, level, format, type, data):
	pass

@params(api='gles3', prms=['texture', 'level', 'xoffset', 'yoffset', 'zoffset', 'width', 'height', 'depth', 'format', 'type', 'data'])
def glClearTexSubImageEXT(texture, level, xoffset, yoffset, zoffset, width, height, depth, format, type, data):
	pass


text:
Sample code for Chapter 15 - "Context managers and something else"

From the book "Fluent Python" by Luciano Ramalho (O'Reilly, 2015)
http://shop.oreilly.com/product/0636920032519.do


text:
<title>Color Cube</title>
<link rel="stylesheet" type="text/css" href="../style.css">

This simple visualization colors a cube using the x-coordinate for the red value, the y-coordinate for the green value and the z-coordinate for the blue value:

With this coloration, the origin is black and the point [1,1,1] is white.

Complete code for this example:

Examples Page


text:
using QRest.Core.Compilation;
using System.Collections.Generic;
using System.Linq.Expressions;

namespace QRest.Core.Operations
{
    public abstract class OperationBase : IOperation
    {
        public abstract string Key { get; }
        public override string ToString() => Key;
        public abstract Expression CreateExpression(ParameterExpression root, Expression context, IReadOnlyList<Expression> arguments, IAssembler assembler);
    }
}


text:
import { IModel } from '../../../../common/contracts';;
import { IProfileAvatarFileEntry } from './';

export interface IProfileAvatar extends IModel {
    avatarFileEntry?: IProfileAvatarFileEntry,
    avatarFileEntryId?: string
}


text:
package com.highway.study.anim;

import android.animation.TypeEvaluator;

/**
 * @author JH
 * @date 2017/8/9
 */

public class CharEvaluator implements TypeEvaluator<Character> {
    @Override
    public Character evaluate(float fraction, Character startValue, Character endValue) {
        int start = (int)startValue;
        int end = (int)endValue;
        int current = (int) (start + fraction * (end - start));
        char result = (char)current;
        return result;
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>com.ambientideas.cryptography</groupId>
		<artifactId>crypto-samples</artifactId>
		<version>1.0.2</version>
	</parent>

	<artifactId>jce-message-digest</artifactId>

	<dependencies>
		<dependency>
			<groupId>commons-codec</groupId>
			<artifactId>commons-codec</artifactId>
			<version>1.13</version>
		</dependency>
	</dependencies>
</project>


text:
package blog.activemq.jms.boot;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.config.JmsListenerContainerFactory;
import org.springframework.jms.config.SimpleJmsListenerContainerFactory;

import javax.jms.ConnectionFactory;

/**
 * Created by Bikash on 3/15/2016.
 */
@Configuration
public class AppicationConfig {
    @Bean
        // Required for durable subscription
    JmsListenerContainerFactory<?> durableJmsContainerFactory(ConnectionFactory connectionFactory) {
        SimpleJmsListenerContainerFactory factory = new SimpleJmsListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setSubscriptionDurable(true);
        factory.setClientId("cid001");
        return factory;
    }
}


text:
@interface JavaUtilLinkedHashMap ()

@property (readonly) NSMutableArray *index;
@property (readonly) BOOL lastAccessedOrder;

@end

@interface JavaUtilLinkedHashMap_KeySet : JavaUtilHashMap_KeySet
@end

@interface JavaUtilLinkedHashMap_KeySetIterator :
    JavaUtilHashMap_KeySetIterator
@end

@interface JavaUtilLinkedHashMap_EntrySet : JavaUtilHashMap_EntrySet
@end

@interface JavaUtilLinkedHashMap_EntrySetIterator :
    JavaUtilHashMap_EntrySetIterator
@end

@interface JavaUtilLinkedHashMap_Values : JavaUtilHashMap_Values
@end

@interface JavaUtilLinkedHashMap_ValuesIterator :
    JavaUtilHashMap_ValuesIterator
@end


text:
http://www.euro-hash.eu/

![HSCoin](http://www.euro-hash.eu/images/hsc_256x256x32.png)

## What is HSCoin
Hscoin is like Bitcoin, but based on Litecoin

## License
HSCoin is released under the terms of the MIT license. See [COPYING](COPYING)
for more information or see http://opensource.org/licenses/MIT.

## Development and contributions - omg developers
Developers work in their own trees, then submit pull requests when they think
their feature or bug fix is ready.

## Very Much Frequently Asked Questions

### How much HSC can exist?
Total of 100,000,000,000 much coins

### BASE
Scrypt Proof of Work

1 Minute Block Targets, 4 Hour Diff Readjustments

Special reward system: Random block rewards

1-100,000: 0-1,000,000 Hscoin Reward

100,001 - 200,000: 0-500,000 Hscoin Reward

200,001- 300,000: 0-250,000 Hscoin Reward

300,001 - 400,000: 0-125,000 Hscoin Reward

400,001 - 500,000: 0-62,500 Hscoin Reward

500,001 - 600,000: 0-31,250 Hscoin Reward

600,000+ - 10,000 Reward (flat)

### Wow plz make hscoind

    sudo apt-get install build-essential \
                         libssl-dev \
                         libdb5.1++-dev \
                         libboost-all-dev \
                         libqrencode-dev \
                         libminiupnpc-dev

    cd src/
    make -f makefile.unix USE_UPNP=1 USE_IPV6=1 USE_QRCODE=1

### ports
RPC 9392
P2P 9393

![](http://www.euro-hash.eu)


text:
package ru.kosm.finauth.core.activity;

import java.util.Map;
import java.util.Objects;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import ru.kosm.finauth.core.AppContext;
import ru.kosm.finauth.domain.Account;
import ru.kosm.finauth.domain.Operation;

/**
 * Activity adjusting the account balance
 *
 * @author kosm
 */
public class AdjustAccountActivity implements Activity {

	private final static transient Logger logger = LogManager.getLogger(AdjustAccountActivity.class);

	private final String idParamName;

	/**
	 * Constructor
	 *
	 * @param idParamName Name of context parameter to be used to refer to the account
	 */
	public AdjustAccountActivity(String idParamName) {
		this.idParamName = idParamName;
	}

	@Override
	public void execute(AppContext appContext, Operation operation, Map<String, Object> operOutput)
			throws ActivityException {
		Account account = Objects.requireNonNull(appContext.getAccountCache()
				.get(Objects.requireNonNull(operation.getContext().get(idParamName),
						"Missing parameter: " + idParamName)), "No such account");
		String amountStr = (String)Objects.requireNonNull(operation.getContext().get("amount"), "No amount");
		long amount = Long.parseLong(amountStr);
		if (account.getBalance() + amount < 0) {
			throw new ActivityException("Not enough money, accountId: " + account.getAccountId());
		}
		operation.getCacheActions().add((a, o) -> account.setBalance(account.getBalance() + amount));

		logger.trace("Adjusted account with id {}, amount {}", account.getAccountId(),
				(amount > 0 ? "+" : "") + amountStr);
	}

}


text:
package examples.auction;

import java.util.List;

import io.baratine.vault.IdAsset;

public interface AuctionVaultSync extends AuctionVault
{
  IdAsset create(AuctionDataInit data);

  Auction findByTitle(String title);

  List<AuctionData> findAuctionDataByTitle(String title);

  List<IdAsset> findIdsByTitle(String title);
}


text:
module.exports = {
    iterateKeySet: require('./iterateKeySet'),
    toTree: require('./toTree'),
    toTreeWithUnion: require('./toTreeWithUnion'),
    pathsComplementFromTree: require('./pathsComplementFromTree'),
    pathsComplementFromLengthTree: require('./pathsComplementFromLengthTree'),
    hasIntersection: require('./hasIntersection'),
    toPaths: require('./toPaths'),
    collapse: require('./collapse')
};


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

using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace DbLinq.Data.Linq.Sugar.ExpressionMutator.Implementation
{
    internal class MemberMemberBindingMutator : IMemberBindingMutator
    {
        protected MemberMemberBinding MemberMemberBinding { get; private set; }

        public IEnumerable<Expression> Operands
        {
            get
            {
                // a MemberMemberBindings is recursive, so let's recurse
                foreach (var memberBinding in MemberMemberBinding.Bindings)
                {
                    foreach (Expression operand in MemberBindingMutatorFactory.GetMutator(memberBinding).Operands)
                        yield return operand;
                }
            }
        }

        public MemberBinding Mutate(IList<Expression> operands)
        {
            var bindings = new List<MemberBinding>();
            int operandsIndex = 0;
            // same thing here. The difficulty is that we have to split out operands
            foreach (var memberBinding in MemberMemberBinding.Bindings)
            {
                int operandsCount = MemberBindingMutatorFactory.GetMutator(memberBinding).Operands.Count();
                var subOperands = operands.Skip(operandsIndex).Take(operandsCount).ToList();
                bindings.Add(MemberBindingMutatorFactory.GetMutator(memberBinding).Mutate(subOperands));
                operandsIndex += operandsCount;
            }
            return Expression.MemberBind(MemberMemberBinding.Member, bindings);
        }

        public MemberMemberBindingMutator(MemberMemberBinding memberMemberBinding)
        {
            MemberMemberBinding = memberMemberBinding;
        }
    }
}


text:
class CreatePersistentVolumeClaim < ActiveRecord::Migration[4.2]
  def change
    create_table :persistent_volume_claims do |t|
      t.belongs_to :ems, :type => :bigint
      t.string     :ems_ref
      t.string     :name
      t.timestamp  :ems_created_on
      t.string     :resource_version
      t.text       :desired_access_modes, :array => true, :default => []
      t.string     :phase
      t.text       :actual_access_modes, :array => true, :default => []
      t.text       :capacity

      t.timestamps
    end
  end
end


text:
(function(){
Template.__checkName("postRank");
Template["postRank"] = new Template("Template.postRank", (function() {
  var view = this;
  return HTML.Raw('');
}));

})();


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace _02_InternationalCompany.France {

    public partial class MasterPageFrance {

        /// <summary>
        /// ContentPlaceHolderFrance control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.ContentPlaceHolder ContentPlaceHolderFrance;
    }
}


text:
namespace StripeTests
{
    using Newtonsoft.Json;
    using Stripe;
    using Xunit;

    public class DisputeTest : BaseStripeTest
    {
        public DisputeTest(StripeMockFixture stripeMockFixture)
            : base(stripeMockFixture)
        {
        }

        [Fact]
        public void Deserialize()
        {
            string json = this.GetFixture("/v1/disputes/dp_123");
            var dispute = JsonConvert.DeserializeObject<Dispute>(json);
            Assert.NotNull(dispute);
            Assert.IsType<Dispute>(dispute);
            Assert.NotNull(dispute.Id);
            Assert.Equal("dispute", dispute.Object);
        }

        [Fact]
        public void DeserializeWithExpansions()
        {
            string[] expansions =
            {
              "charge",
            };

            string json = this.GetFixture("/v1/disputes/dp_123", expansions);
            var dispute = JsonConvert.DeserializeObject<Dispute>(json);
            Assert.NotNull(dispute);
            Assert.IsType<Dispute>(dispute);
            Assert.NotNull(dispute.Id);
            Assert.Equal("dispute", dispute.Object);

            Assert.NotNull(dispute.Charge);
            Assert.Equal("charge", dispute.Charge.Object);
        }
    }
}


text:
package com.adobe.dp.css;

import com.adobe.dp.xml.util.SMap;

public class AndElementMatcher extends ElementMatcher {

	ElementMatcher first;

	ElementMatcher second;

	AndElementMatcher(AndSelector selector, ElementMatcher first, ElementMatcher second) {
		super(selector);
		if (first == null || second == null)
			throw new NullPointerException();
		this.first = first;
		this.second = second;
	}

	public void popElement() {
		second.popElement();
		first.popElement();
	}

	public MatchResult pushElement(String ns, String name, SMap attrs) {
		MatchResult f = first.pushElement(ns, name, attrs);
		MatchResult s = second.pushElement(ns, name, attrs);
		if (f == null || s == null)
			return null;
		if (f.getPseudoElement() == null)
			return s;
		if (s.getPseudoElement() == null)
			return f;
		return null; // something illegal like :first-letter:before
	}

}


text:
namespace bluez {

BluetoothInputClient::Properties::Properties(
    dbus::ObjectProxy* object_proxy,
    const std::string& interface_name,
    const PropertyChangedCallback& callback)
    : dbus::PropertySet(object_proxy, interface_name, callback) {
  RegisterProperty(bluetooth_input::kReconnectModeProperty, &reconnect_mode);
}

BluetoothInputClient::Properties::~Properties() {}

// The BluetoothInputClient implementation used in production.
class BluetoothInputClientImpl : public BluetoothInputClient,
                                 public dbus::ObjectManager::Interface {
 public:
  BluetoothInputClientImpl() : object_manager_(NULL), weak_ptr_factory_(this) {}

  ~BluetoothInputClientImpl() override {
    object_manager_->UnregisterInterface(
        bluetooth_input::kBluetoothInputInterface);
  }

  // BluetoothInputClient override.
  void AddObserver(BluetoothInputClient::Observer* observer) override {
    DCHECK(observer);
    observers_.AddObserver(observer);
  }

  // BluetoothInputClient override.
  void RemoveObserver(BluetoothInputClient::Observer* observer) override {
    DCHECK(observer);
    observers_.RemoveObserver(observer);
  }

  // dbus::ObjectManager::Interface override.
  dbus::PropertySet* CreateProperties(
      dbus::ObjectProxy* object_proxy,
      const dbus::ObjectPath& object_path,
      const std::string& interface_name) override {
    Properties* properties =
        new Properties(object_proxy, interface_name,
                       base::Bind(&BluetoothInputClientImpl::OnPropertyChanged,
                                  weak_ptr_factory_.GetWeakPtr(), object_path));
    return static_cast<dbus::PropertySet*>(properties);
  }

  // BluetoothInputClient override.
  Properties* GetProperties(const dbus::ObjectPath& object_path) override {
    return static_cast<Properties*>(object_manager_->GetProperties(
        object_path, bluetooth_input::kBluetoothInputInterface));
  }

 protected:
  void Init(dbus::Bus* bus) override {
    object_manager_ = bus->GetObjectManager(
        bluetooth_object_manager::kBluetoothObjectManagerServiceName,
        dbus::ObjectPath(
            bluetooth_object_manager::kBluetoothObjectManagerServicePath));
    object_manager_->RegisterInterface(
        bluetooth_input::kBluetoothInputInterface, this);
  }

 private:
  // Called by dbus::ObjectManager when an object with the input interface
  // is created. Informs observers.
  void ObjectAdded(const dbus::ObjectPath& object_path,
                   const std::string& interface_name) override {
    for (auto& observer : observers_)
      observer.InputAdded(object_path);
  }

  // Called by dbus::ObjectManager when an object with the input interface
  // is removed. Informs observers.
  void ObjectRemoved(const dbus::ObjectPath& object_path,
                     const std::string& interface_name) override {
    for (auto& observer : observers_)
      observer.InputRemoved(object_path);
  }

  // Called by BluetoothPropertySet when a property value is changed,
  // either by result of a signal or response to a GetAll() or Get()
  // call. Informs observers.
  void OnPropertyChanged(const dbus::ObjectPath& object_path,
                         const std::string& property_name) {
    for (auto& observer : observers_)
      observer.InputPropertyChanged(object_path, property_name);
  }

  dbus::ObjectManager* object_manager_;

  // List of observers interested in event notifications from us.
  base::ObserverList<BluetoothInputClient::Observer> observers_;

  // Weak pointer factory for generating 'this' pointers that might live longer
  // than we do.
  // Note: This should remain the last member so it'll be destroyed and
  // invalidate its weak pointers before any other members are destroyed.
  base::WeakPtrFactory<BluetoothInputClientImpl> weak_ptr_factory_;

  DISALLOW_COPY_AND_ASSIGN(BluetoothInputClientImpl);
};

BluetoothInputClient::BluetoothInputClient() {}

BluetoothInputClient::~BluetoothInputClient() {}

BluetoothInputClient* BluetoothInputClient::Create() {
  return new BluetoothInputClientImpl();
}

}  // namespace bluez


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Travessa</tipo><logradouro>do DAER</logradouro><bairro>União</bairro><cidade>Gravataí</cidade><uf>RS</uf><cep>94025392</cep></feed>


text: body { background: #FFABAC; }


text:
const int ddLogLevel = LOG_LEVEL_VERBOSE;
NSString* const kHostName = @"susmita.local";

#elif SNAPSHOT
const int ddLogLevel = LOG_LEVEL_VERBOSE;

#elif STAGING
const int ddLogLevel = LOG_LEVEL_ERROR;

#elif RELEASE
const int ddLogLevel = LOG_LEVEL_OFF;

#elif PRODUCTION
const int ddLogLevel = LOG_LEVEL_OFF;

#else

#endif


text:
package com.wheat7.cashew.viewmodel;

import android.databinding.BaseObservable;
import android.databinding.Bindable;

/**
 * Created by wheat7 on 2017/8/19.
 */

public class InfoViewModel extends BaseObservable {

    @Bindable
    public String mImageCacheSize = new String();

}


text:
import { IServerLog } from './log.contract';
import { ModelType, LogLevel, LogRole, LogAction } from '../../enums/model.enum';
import { serializeAs, deserializeAs } from 'cerialize';
import { Creator } from '../user/user.model';
import { SrvTimeFormat } from './../../interfaces/response.interface';
import { FormatTime } from 'ws-format-time';
import { JsonHelper } from '../../../utils/app.utils';

export class ApplicationLog {

    @serializeAs('type')
    @deserializeAs(Number, 'type')
    private type: ModelType;
    public get Type() { return this.type; }

    @serializeAs('level')
    @deserializeAs(Number, 'level')
    private level: LogLevel;
    public get Level() { return this.level; }

    @serializeAs('role')
    @deserializeAs(Number, 'role')
    private role: LogRole;
    public get Role() { return this.role; }

    @serializeAs('action')
    @deserializeAs(Number, 'action')
    private action: LogAction;
    public get Action() { return this.action; }

    @serializeAs('target_type')
    @deserializeAs(Number, 'target_type')
    private target_type: ModelType;
    public get TargetType() { return this.target_type; }

    @serializeAs('target_id')
    @deserializeAs('target_id')
    private target_id: string;
    public get TargetID() { return this.target_id; }

    @serializeAs('target_key')
    @deserializeAs('target_key')
    private target_key: string;
    public get TargetKey() { return this.target_key; }
    public set TargetKey(value: string) { this.target_key = value; }

    @serializeAs('desc')
    @deserializeAs('desc')
    private desc: string;
    public get Description() { return this.desc; }

    @serializeAs(Creator, 'creator')
    @deserializeAs(Creator, 'creator')
    private creator: Creator;
    public get Creator() { return this.creator; }

    @serializeAs('id')
    @deserializeAs('id')
    private id: string;
    public get ID() { return this.id; }

    @serializeAs('create_time')
    @deserializeAs(Number, 'create_time')
    private create_time: number;
    private _createTime: FormatTime;
    public get CreateTime() {
        return this._createTime || (this._createTime = FormatTime.Create(1000 * (this.create_time || 0)));
    }

    @serializeAs('update_time')
    @deserializeAs(Number, 'update_time')
    private update_time: number;
    private _updateTime: FormatTime;
    public get UpdateTime() {
        return this._updateTime || (this._updateTime = FormatTime.Create(1000 * (this.update_time || 0)));
    }

    public static Parse = (iuser: IServerLog) => JsonHelper.FromJson<ApplicationLog>(JsonHelper.ToJSON(iuser), ApplicationLog);

    public static ParseList = (iusers: IServerLog[]) => (iusers || []).map(iuser => JsonHelper.FromJson<ApplicationLog>(JsonHelper.ToJSON(iuser), ApplicationLog));

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>easy-cloud</artifactId>
        <groupId>com.ecspringcloud.easycloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>ec-provider-user-interface</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
        </dependency>
    </dependencies>
</project>


text:
layout: post
title: AvaTax Developer Guide
date: 2017-09-29 12:00
author: Julia King
comments: true
categories: [avatax]
product: blog
doctype: blog
disqus: 1
redirect_to: https://www.avalara.com/us/en/blog/2017/09/avatax-developer-guide.html
---
If including tax calculation and remittance capabilities into your application has been daunting, tiresome, and therefore easy to put on the back burner, we understand. Your users need these capabilities to keep the tax auditors at bay, but you don't have time to wade through pages of documentation to try to understand the complexities of sales and use tax. We want to help you deliver that huge operational efficiency and tax protection to your users quickly and easily.

Introducing the AvaTax Developer Guide.  We've condensed and simplified our documentation into a fun-to-read chapter format to help you successfully build your integration to AvaTax.

Quick integration

In each chapter, we cover everything from how to obtain your free sandbox account to why your users should care about consumer use tax. It's easy to navigate around the different areas of interest and return to them as needed.

Learn how Avalara uses logic around specific product taxability to deliver the most accurate tax rate for that product.

Should your users report shipping and handling charges?

How can you ensure that your application can still calculate tax when you've lost connection to the internet? We have the best practices for calculating tax offline.

The guide can direct you to the correct API reference page for every function, so you can work at your own pace. Each chapter also includes test cases you can use to check if your software is working correctly.

Connector developers

For developers working on integrating AvaTax into accounting systems or web storefronts, we have a list of certification requirements you should consider if you wish to apply for Avalara Certified Connector status. Getting certified is a great way to learn the theory of tax and how it applies to your software.

The AvaTax Developer Guide teaches you everything you need to know to create a robust integration for all types of customers. Quickstart chapters will help you get started fast, customization chapters will help you map your accounting system's features to AvaTax, and the advanced chapters will help you ensure compatibility with large enterprises when they begin using your software. And, if you've ever wondered why some large enterprises use location-based reporting, we've got you covered.

Please come and see what's new. As always, we welcome your feedback on our new format and how it can be improved. Relax, we'll handle the tax.


text:
<?php

return [
    'plugin' => [
        'name' => 'FFooter',
        'description' => 'Featured footer is a plugin for creating dynamic footers',
    ],
    'ffooterx' => [
        'menu_label' => 'Manager',
        'menu_description' => 'Manage Blog Posts',
        'footer' => 'Footer',
    ],
    'footer' => [
        'title' => 'Title',
        'title_placeholder' => 'New footer title',
        'list_title' => 'Manage the Footer',
        'sort_order' => 'Order',
        'public' => 'Public',
        'categories' => 'Categories',
        'created' => 'Created',
        'updated' => 'Updated',
        'state' => 'State',
        'rotate' => 'Rotate',
        'tab_edit' => 'Edit',
        'public' => 'Public',
        'link_url_placeholder' => 'http://www.example.com',
     ],

];


text:
namespace Microsoft.Robotics.Tests.Reflecta
{
    using System;

    public class FrameReceivedEventArgs : EventArgs
    {
        public FrameReceivedEventArgs(byte sequence, byte[] frame)
        {
            Sequence = sequence;
            Frame = frame;
        }

        public byte Sequence { get; set; }

        public byte[] Frame { get; set; }
    }
}


text:
<?php

/**
 * @group Database
 */
class MovePageTest extends MediaWikiTestCase {

	/**
	 * @dataProvider provideIsValidMove
	 * @covers MovePage::isValidMove
	 * @covers MovePage::isValidFileMove
	 */
	public function testIsValidMove( $old, $new, $error ) {
		$this->setMwGlobals( 'wgContentHandlerUseDB', false );
		$mp = new MovePage(
			Title::newFromText( $old ),
			Title::newFromText( $new )
		);
		$status = $mp->isValidMove();
		if ( $error === true ) {
			$this->assertTrue( $status->isGood() );
		} else {
			$this->assertTrue( $status->hasMessage( $error ) );
		}
	}

	/**
	 * This should be kept in sync with TitleTest::provideTestIsValidMoveOperation
	 */
	public static function provideIsValidMove() {
		return array(
			// for MovePage::isValidMove
			array( 'Test', 'Test', 'selfmove' ),
			array( 'Special:FooBar', 'Test', 'immobile-source-namespace' ),
			array( 'Test', 'Special:FooBar', 'immobile-target-namespace' ),
			array( 'MediaWiki:Common.js', 'Help:Some wikitext page', 'bad-target-model' ),
			array( 'Page', 'File:Test.jpg', 'nonfile-cannot-move-to-file' ),
			// for MovePage::isValidFileMove
			array( 'File:Test.jpg', 'Page', 'imagenocrossnamespace' ),
		);
	}

	/**
	 * Integration test to catch regressions like T74870. Taken and modified
	 * from SemanticMediaWiki
	 */
	public function testTitleMoveCompleteIntegrationTest() {
		$oldTitle = Title::newFromText( 'Help:Some title' );
		WikiPage::factory( $oldTitle )->doEditContent( new WikitextContent( 'foo' ), 'bar' );
		$newTitle = Title::newFromText( 'Help:Some other title' );
		$this->assertNull(
			WikiPage::factory( $newTitle )->getRevision()
		);

		$this->assertTrue( $oldTitle->moveTo( $newTitle, false, 'test1', true ) );
		$this->assertNotNull(
			WikiPage::factory( $oldTitle )->getRevision()
		);
		$this->assertNotNull(
			WikiPage::factory( $newTitle )->getRevision()
		);
	}
}