text:
/*
 * generated by Xtext 2.10.0
 */
package it.polimi.dice.dicer.parser.antlr;

import com.google.inject.Inject;
import it.polimi.dice.dicer.parser.antlr.internal.InternalToscaDslParser;
import it.polimi.dice.dicer.services.ToscaDslGrammarAccess;
import org.eclipse.xtext.parser.antlr.AbstractAntlrParser;
import org.eclipse.xtext.parser.antlr.XtextTokenStream;

public class ToscaDslParser extends AbstractAntlrParser {

	@Inject
	private ToscaDslGrammarAccess grammarAccess;

	@Override
	protected void setInitialHiddenTokens(XtextTokenStream tokenStream) {
		tokenStream.setInitialHiddenTokens("RULE_WS", "RULE_ML_COMMENT", "RULE_SL_COMMENT");
	}

	@Override
	protected InternalToscaDslParser createParser(XtextTokenStream stream) {
		return new InternalToscaDslParser(stream, getGrammarAccess());
	}

	@Override
	protected String getDefaultRuleName() {
		return "TopologyTemplate";
	}

	public ToscaDslGrammarAccess getGrammarAccess() {
		return this.grammarAccess;
	}

	public void setGrammarAccess(ToscaDslGrammarAccess grammarAccess) {
		this.grammarAccess = grammarAccess;
	}
}


text:
namespace google {
namespace cloud {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
namespace testing_util {

Timer::Timer(CpuAccounting accounting)
    : accounting_(accounting), start_(std::chrono::steady_clock::now()) {
#if GOOGLE_CLOUD_CPP_HAVE_GETRUSAGE
  (void)getrusage(RUsageWho(), &start_usage_);
#endif  // GOOGLE_CLOUD_CPP_HAVE_GETRUSAGE
}

Timer::Snapshot Timer::Sample() const {
  auto elapsed = std::chrono::duration_cast<std::chrono::microseconds>(
      std::chrono::steady_clock::now() - start_);
#if !GOOGLE_CLOUD_CPP_HAVE_GETRUSAGE
  return Snapshot{elapsed, std::chrono::microseconds()};
#else
  auto as_usec = [](timeval const& tv) {
    return std::chrono::microseconds(std::chrono::seconds(tv.tv_sec)) +
           std::chrono::microseconds(tv.tv_usec);
  };

  struct rusage now {};
  (void)getrusage(RUsageWho(), &now);
  auto const utime = as_usec(now.ru_utime) - as_usec(start_usage_.ru_utime);
  auto const stime = as_usec(now.ru_stime) - as_usec(start_usage_.ru_stime);
  return Snapshot{elapsed, utime + stime};
#endif  // GOOGLE_CLOUD_CPP_HAVE_GETRUSAGE
}

std::string Timer::Annotations() const {
#if !GOOGLE_CLOUD_CPP_HAVE_GETRUSAGE
  return "# No usage annotations are available";
#else
  auto usage = Sample();

  auto as_usec = [](timeval const& tv) {
    return std::chrono::microseconds(std::chrono::seconds(tv.tv_sec)) +
           std::chrono::microseconds(tv.tv_usec);
  };

  struct rusage now {};
  (void)getrusage(RUsageWho(), &now);
  auto utime = as_usec(now.ru_utime) - as_usec(start_usage_.ru_utime);
  auto stime = as_usec(now.ru_stime) - as_usec(start_usage_.ru_stime);
  double cpu_fraction = 0;
  if (usage.elapsed_time.count() != 0) {
    cpu_fraction = static_cast<double>(usage.cpu_time.count()) /
                   static_cast<double>(usage.elapsed_time.count());
  }
  now.ru_minflt -= start_usage_.ru_minflt;
  now.ru_majflt -= start_usage_.ru_majflt;
  now.ru_nswap -= start_usage_.ru_nswap;
  now.ru_inblock -= start_usage_.ru_inblock;
  now.ru_oublock -= start_usage_.ru_oublock;
  now.ru_msgsnd -= start_usage_.ru_msgsnd;
  now.ru_msgrcv -= start_usage_.ru_msgrcv;
  now.ru_nsignals -= start_usage_.ru_nsignals;
  now.ru_nvcsw -= start_usage_.ru_nvcsw;
  now.ru_nivcsw -= start_usage_.ru_nivcsw;
#if GOOGLE_CLOUD_CPP_HAVE_RUSAGE_THREAD
  std::string accounting =
      accounting_ == CpuAccounting::kPerThread ? "per-thread" : "per-process";
#else
  std::string accounting = accounting_ == CpuAccounting::kPerThread
                               ? "per-thread (but unsupported)"
                               : "per-process";
#endif  //  GOOGLE_CLOUD_CPP_HAVE_RUSAGE_THREAD

  std::ostringstream os;
  os << "# accounting                   =" << accounting
     << "# user time                    =" << utime.count() << " us\n"
     << "# system time                  =" << stime.count() << " us\n"
     << "# CPU fraction                 =" << cpu_fraction << "\n"
     << "# maximum resident set size    =" << now.ru_maxrss << " KiB\n"
     << "# integral shared memory size  =" << now.ru_ixrss << " KiB\n"
     << "# integral unshared data size  =" << now.ru_idrss << " KiB\n"
     << "# integral unshared stack size =" << now.ru_isrss << " KiB\n"
     << "# soft page faults             =" << now.ru_minflt << "\n"
     << "# hard page faults             =" << now.ru_majflt << "\n"
     << "# swaps                        =" << now.ru_nswap << "\n"
     << "# block input operations       =" << now.ru_inblock << "\n"
     << "# block output operations      =" << now.ru_oublock << "\n"
     << "# IPC messages sent            =" << now.ru_msgsnd << "\n"
     << "# IPC messages received        =" << now.ru_msgrcv << "\n"
     << "# signals received             =" << now.ru_nsignals << "\n"
     << "# voluntary context switches   =" << now.ru_nvcsw << "\n"
     << "# involuntary context switches =" << now.ru_nivcsw;
  return std::move(os).str();
#endif  // GOOGLE_CLOUD_CPP_HAVE_GETRUSAGE
}

bool Timer::SupportsPerThreadUsage() {
#if GOOGLE_CLOUD_CPP_HAVE_RUSAGE_THREAD
  return true;
#else
  return false;
#endif  // GOOGLE_CLOUD_CPP_HAVE_RUSAGE_THREAD
}

int Timer::RUsageWho() const {
#if GOOGLE_CLOUD_CPP_HAVE_RUSAGE_THREAD
  return accounting_ == CpuAccounting::kPerThread ? RUSAGE_THREAD : RUSAGE_SELF;
#elif GOOGLE_CLOUD_CPP_HAVE_GETRUSAGE
  return RUSAGE_SELF;
#else
  return 0;  // unused, so any value would do.
#endif  // GOOGLE_CLOUD_CPP_HAVE_RUSAGE_THREAD
}

}  // namespace testing_util
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
}  // namespace cloud
}  // namespace google

redpajama_set_name: RedPajamaGithub


text:
package org.yx.db.visit;

import java.util.Collection;
import java.util.List;

import org.yx.db.sql.PojoMeta;

/**
 * 本接口只负责实际的存取,实现类一般不需要null判断等
 */
public interface RecordAccess {

	String get(PojoMeta m, String id);

	List<String> getMultiValue(PojoMeta m, Collection<String> ids);

	void set(PojoMeta m, String id, String json);

	void del(PojoMeta m, String id);

	void delMulti(PojoMeta m, String[] ids);
}


text:
// Copyright 2000-2020 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.codeInsight.unwrap;

import com.intellij.codeInsight.CodeInsightActionHandler;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.FileModificationService;
import com.intellij.codeInsight.highlighting.HighlightManager;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorModificationUtil;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.markup.HighlighterLayer;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.ui.popup.JBPopupListener;
import com.intellij.openapi.ui.popup.LightweightWindowEvent;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.impl.source.tree.RecursiveTreeElementWalkingVisitor;
import com.intellij.psi.impl.source.tree.TreeElement;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.NotNullList;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

public class UnwrapHandler implements CodeInsightActionHandler {
  public static final int HIGHLIGHTER_LEVEL = HighlighterLayer.SELECTION + 1;

  @Override
  public boolean startInWriteAction() {
    return false;
  }

  @Override
  public void invoke(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) {
    if (!EditorModificationUtil.checkModificationAllowed(editor)) return;
    List<MyUnwrapAction> options = collectOptions(project, editor, file);
    selectOption(options, editor, file);
  }

  @NotNull
  private static List<MyUnwrapAction> collectOptions(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) {
    List<MyUnwrapAction> result = new ArrayList<>();

    UnwrapDescriptor descriptor = getUnwrapDescription(file);

    for (Pair<PsiElement, Unwrapper> desc : descriptor.collectUnwrappers(project, editor, file)) {
      PsiElement element = desc.getFirst();
      Unwrapper unwrapper = desc.getSecond();
      if (element == null || unwrapper == null) {
        throw new IllegalStateException(descriptor + " returned "+desc);
      }
      result.add(createUnwrapAction(unwrapper, element, editor, project));
    }

    return result;
  }

  private static UnwrapDescriptor getUnwrapDescription(@NotNull PsiFile file) {
    return LanguageUnwrappers.INSTANCE.forLanguage(file.getLanguage());
  }

  private static MyUnwrapAction createUnwrapAction(@NotNull Unwrapper u, @NotNull PsiElement el, @NotNull Editor ed, @NotNull Project p) {
    return new MyUnwrapAction(p, ed, u, el);
  }

  protected void selectOption(List<? extends MyUnwrapAction> options, Editor editor, PsiFile file) {
    if (options.isEmpty()) return;

    if (!getUnwrapDescription(file).showOptionsDialog() ||
        ApplicationManager.getApplication().isUnitTestMode()
       ) {
      options.get(0).perform();
      return;
    }

    showPopup(options, editor);
  }

  private static void showPopup(final List<? extends AnAction> options, Editor editor) {
    final ScopeHighlighter highlighter = new ScopeHighlighter(editor);

    List<MyItem> model = ContainerUtil.map(options, a -> new MyItem(((MyUnwrapAction)a).getName(), options.indexOf(a)));
    Function<MyItem, MyUnwrapAction> optionByName = item -> (MyUnwrapAction)options.get(item.index);

    JBPopupFactory.getInstance()
      .createPopupChooserBuilder(model)
      .setTitle(CodeInsightBundle.message("unwrap.popup.title"))
      .setMovable(false)
      .setNamerForFiltering(item -> item.name)
      .setSelectionMode(ListSelectionModel.SINGLE_SELECTION)
      .setResizable(false)
      .setRequestFocus(true)
      .setItemChosenCallback((selectedValue) -> optionByName.apply(selectedValue).perform())
      .setItemSelectedCallback(item -> {
        if (item != null) {
          MyUnwrapAction a = optionByName.apply(item);
          List<PsiElement> toExtract = new NotNullList<>();
          PsiElement wholeRange = a.collectAffectedElements(toExtract);
          highlighter.highlight(wholeRange, toExtract);
        }
      })
      .addListener(new JBPopupListener() {
        @Override
        public void onClosed(@NotNull LightweightWindowEvent event) {
          highlighter.dropHighlight();
        }
      })
      .createPopup().showInBestPositionFor(editor);
  }

  private static class MyItem {
    final String name;
    final int index;
    MyItem(String name, int index) {
      this.name = name;
      this.index = index;
    }

    @Override
    public String toString() {
      return name;
    }
  }

  /**
   * @deprecated operate with
   * {@link EditorColors#SEARCH_RESULT_ATTRIBUTES} directly
   */
  @Deprecated
  @ApiStatus.ScheduledForRemoval(inVersion = "2021.2")
  public static TextAttributes getTestAttributesForExtract() {
    EditorColorsManager manager = EditorColorsManager.getInstance();
    return manager.getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
  }

  protected static class MyUnwrapAction extends AnAction {
    private static final Key<Integer> CARET_POS_KEY = new Key<>("UNWRAP_HANDLER_CARET_POSITION");

    private final Project myProject;
    private final Editor myEditor;
    private final Unwrapper myUnwrapper;
    @NotNull
    private final PsiElement myElement;

    MyUnwrapAction(@NotNull Project project, @NotNull Editor editor, @NotNull Unwrapper unwrapper, @NotNull PsiElement element) {
      super(unwrapper.getDescription(element));
      myProject = project;
      myEditor = editor;
      myUnwrapper = unwrapper;
      myElement = element;
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
      perform();
    }

    public void perform() {
      final PsiFile file = myElement.getContainingFile();
      if (!FileModificationService.getInstance().prepareFileForWrite(file)) return;

      CommandProcessor.getInstance().executeCommand(myProject, () -> ApplicationManager.getApplication().runWriteAction(() -> {
        try {
          UnwrapDescriptor d = getUnwrapDescription(file);
          if (d.shouldTryToRestoreCaretPosition()) saveCaretPosition(file);
          int scrollOffset = myEditor.getScrollingModel().getVerticalScrollOffset();

          List<PsiElement> extractedElements = myUnwrapper.unwrap(myEditor, myElement);

          if (d.shouldTryToRestoreCaretPosition()) restoreCaretPosition(file);
          myEditor.getScrollingModel().scrollVertically(scrollOffset);

          highlightExtractedElements(extractedElements);
        }
        catch (IncorrectOperationException ex) {
          throw new RuntimeException(ex);
        }
      }), null, myEditor.getDocument());
    }

    private void saveCaretPosition(PsiFile file) {
      int offset = myEditor.getCaretModel().getOffset();
      PsiElement el = file.findElementAt(offset);
      if (el == null) return;
      int innerOffset = offset - el.getTextOffset();
      el.putCopyableUserData(CARET_POS_KEY, innerOffset);
    }

    private void restoreCaretPosition(final PsiFile file) {
      ((TreeElement)file.getNode()).acceptTree(new RecursiveTreeElementWalkingVisitor() {
        @Override
        protected void visitNode(TreeElement element) {
          PsiElement el = element.getPsi();
          Integer offset = el.getCopyableUserData(CARET_POS_KEY);

          // continue;
          if (offset != null) {
            myEditor.getCaretModel().moveToOffset(el.getTextOffset() + offset);
            el.putCopyableUserData(CARET_POS_KEY, null);
            return;
          }
          super.visitNode(element);
        }
      });
    }

    private void highlightExtractedElements(final List<PsiElement> extractedElements) {
      for (PsiElement each : extractedElements) {
        final TextRange textRange = each.getTextRange();
        HighlightManager.getInstance(myProject).addRangeHighlight(
            myEditor,
            textRange.getStartOffset(),
            textRange.getEndOffset(),
            EditorColors.SEARCH_RESULT_ATTRIBUTES,
            false,
            true,
            null);
      }
    }

    public String getName() {
      return myUnwrapper.getDescription(myElement);
    }

    PsiElement collectAffectedElements(@NotNull List<PsiElement> toExtract) {
      return myUnwrapper.collectAffectedElements(myElement, toExtract);
    }
  }
}


text:
package org.apache.spark.ui.jobs

import javax.servlet.http.HttpServletRequest

import org.apache.spark.scheduler.SchedulingMode
import org.apache.spark.ui.{SparkUI, SparkUITab}

/** Web UI showing progress status of all stages in the given SparkContext. */
private[ui] class StagesTab(parent: SparkUI) extends SparkUITab(parent, "stages") {
  val sc = parent.sc
  val killEnabled = parent.killEnabled
  val listener = parent.jobProgressListener

  attachPage(new AllStagesPage(this))
  attachPage(new StagePage(this))
  attachPage(new PoolPage(this))

  def isFairScheduler = listener.schedulingMode.exists(_ == SchedulingMode.FAIR)

  def handleKillRequest(request: HttpServletRequest) =  {
    if ((killEnabled) && (parent.securityManager.checkModifyPermissions(request.getRemoteUser))) {
      val killFlag = Option(request.getParameter("terminate")).getOrElse("false").toBoolean
      val stageId = Option(request.getParameter("id")).getOrElse("-1").toInt
      if (stageId >= 0 && killFlag && listener.activeStages.contains(stageId)) {
        sc.get.cancelStage(stageId)
      }
      // Do a quick pause here to give Spark time to kill the stage so it shows up as
      // killed after the refresh. Note that this will block the serving thread so the
      // time should be limited in duration.
      Thread.sleep(100)
    }
  }

}


text:
namespace Weingartner.Json.Migration.Common
{
    public class MethodParameter
    {
        public MethodParameter(SimpleType type)
        {
            Type = type;
        }

        public SimpleType Type { get; }
    }
}


text:
Post title

Hi, today I’m going to talk about golang.

Do you know this amazing language?


text:
module.exports = {
  cut: cutBuffer,
  copy: copyBuffer,
  paste: pasteBuffer,
  reverse: reverseBuffer
};

function reverseBuffer(buffer, cb) {
  var chanNumber = buffer.numberOfChannels;
  for (var i = 0; i < chanNumber; ++i) {
    var data = buffer.getChannelData(i);
    Array.prototype.reverse.call(data);
  }
  cb();
}

// copy the buffer to our clipboard, without removing the original section from buffer.
function copyBuffer(context, clipboard, buffer, cb) {
  var start = Math.round(clipboard.start * buffer.sampleRate);
  var end = Math.round(clipboard.end * buffer.sampleRate);

  clipboard.buffer = context.createBuffer(2, end - start, buffer.sampleRate);

  clipboard.buffer.getChannelData(0).set(
    buffer.getChannelData(0).subarray(start, end), 0);
  clipboard.buffer.getChannelData(1).set(
    buffer.getChannelData(1).subarray(start, end), 0);

  cb();
}

// cut the buffer portion to our clipboard, sets empty space in place of the portion
// in the source buffer.
function cutBuffer(context, clipboard, buffer, cb) {
  var start = Math.round(clipboard.start * buffer.sampleRate);
  var end = Math.round(clipboard.end * buffer.sampleRate);

  clipboard.buffer = context.createBuffer(2, end - start, buffer.sampleRate);
  clipboard.buffer.getChannelData(0).set(buffer.getChannelData(0).subarray(start, end));
  clipboard.buffer.getChannelData(1).set(buffer.getChannelData(1).subarray(start, end));

  var nuOldBuffer = context.createBuffer(2, buffer.length, buffer.sampleRate);
  var emptyBuf = context.createBuffer(2, end - start, buffer.sampleRate);

  nuOldBuffer.getChannelData(0).set(buffer.getChannelData(0).subarray(0, start));
  nuOldBuffer.getChannelData(1).set(buffer.getChannelData(1).subarray(0, start))

  nuOldBuffer.getChannelData(0).set(emptyBuf.getChannelData(0), start);
  nuOldBuffer.getChannelData(1).set(emptyBuf.getChannelData(1), start);

  nuOldBuffer.getChannelData(0).set(buffer.getChannelData(0).subarray(end, buffer.length), end);
  nuOldBuffer.getChannelData(1).set(buffer.getChannelData(1).subarray(end, buffer.length), end);
  cb(nuOldBuffer);
}

// insert our clipboard at a specific point in buffer.
function pasteBuffer(context, clipboard, buffer, at, cb) {
  var start = Math.round(clipboard.start * buffer.sampleRate);
  var end = Math.round(clipboard.end * buffer.sampleRate);
  at = at * buffer.sampleRate;

  // create replacement buffer with enough space for cliboard part
  var nuPastedBuffer = context.createBuffer(2, buffer.length + (end - start), buffer.sampleRate);

  // if our clip start point is not at '0' then we need to set the original
  // chunk, up to the clip start point
  if (at > 0) {
    nuPastedBuffer.getChannelData(0).set(buffer.getChannelData(0).subarray(0, at));
    nuPastedBuffer.getChannelData(1).set(buffer.getChannelData(1).subarray(0, at));
  }

  // add the clip data
  nuPastedBuffer.getChannelData(0).set(clipboard.buffer.getChannelData(0), at);
  nuPastedBuffer.getChannelData(1).set(clipboard.buffer.getChannelData(1), at);

  // if our clip end point is not at the end of the original buffer then
  // we need to add remaining data from the original buffer;
  if (end < buffer.length) {
    var newAt = at + (end - start);
    nuPastedBuffer.getChannelData(0).set(buffer.getChannelData(0).subarray(newAt), newAt);
    nuPastedBuffer.getChannelData(1).set(buffer.getChannelData(1).subarray(newAt), newAt);
  }

  cb(nuPastedBuffer);
}


text:
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace CloudStack.Net
{
    public class CancelStorageMaintenanceRequest : APIRequest
    {
        public CancelStorageMaintenanceRequest() : base("cancelStorageMaintenance") {}

        /// <summary>
        /// the primary storage ID
        /// </summary>
        public Guid Id {
            get { return GetParameterValue<Guid>(nameof(Id).ToLower()); }
            set { SetParameterValue(nameof(Id).ToLower(), value); }
        }

    }
    /// <summary>
    /// Cancels maintenance for primary storage
    /// </summary>
    public partial interface ICloudStackAPIClient
    {
        AsyncJobResponse CancelStorageMaintenance(CancelStorageMaintenanceRequest request);
        Task<AsyncJobResponse> CancelStorageMaintenanceAsync(CancelStorageMaintenanceRequest request);
    }
    public partial class CloudStackAPIClient : ICloudStackAPIClient
    {
        public AsyncJobResponse CancelStorageMaintenance(CancelStorageMaintenanceRequest request) => Proxy.Request<AsyncJobResponse>(request);
        public Task<AsyncJobResponse> CancelStorageMaintenanceAsync(CancelStorageMaintenanceRequest request) => Proxy.RequestAsync<AsyncJobResponse>(request);
    }
}


text:
An AltBrowserCodeModel is in charge of handling the text morph of the Alt Browser.

Instance Variables
	aboutToStyle:		<Boolean>
	behavior:		<Class>
	browser:		<AltBrowserModel>

aboutToStyle
	- Say if the next code is to be styled (syntax coloring) or not.

behavior
	- The behavior for the styler ?

browser
	- The instance of the AltBrowserModel we are in


text:
/**
 * This code was generated by
 * \ / _    _  _|   _  _
 *  | (_)\/(_)(_|\/| |(/_  v1.0.0
 *       /       /
 */

import Page = require('../../../base/Page');
import Response = require('../../../http/response');
import V1 = require('../V1');
import { SerializableClass } from '../../../interfaces';

/**
 * Initialize the AlertList
 *
 * @param version - Version of the resource
 */
declare function AlertList(version: V1): AlertListInstance;

interface AlertListInstance {
  /**
   * @param sid - sid of instance
   */
  (sid: string): AlertContext;
  /**
   * Streams AlertInstance records from the API.
   *
   * This operation lazily loads records as efficiently as possible until the limit
   * is reached.
   *
   * The results are passed into the callback function, so this operation is memory
   * efficient.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @param callback - Function to process each record
   */
  each(callback?: (item: AlertInstance, done: (err?: Error) => void) => void): void;
  /**
   * Streams AlertInstance records from the API.
   *
   * This operation lazily loads records as efficiently as possible until the limit
   * is reached.
   *
   * The results are passed into the callback function, so this operation is memory
   * efficient.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @param opts - Options for request
   * @param callback - Function to process each record
   */
  each(opts?: AlertListInstanceEachOptions, callback?: (item: AlertInstance, done: (err?: Error) => void) => void): void;
  /**
   * Constructs a alert
   *
   * @param sid - The SID that identifies the resource to fetch
   */
  get(sid: string): AlertContext;
  /**
   * Retrieve a single target page of AlertInstance records from the API.
   *
   * The request is executed immediately.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @param callback - Callback to handle list of records
   */
  getPage(callback?: (error: Error | null, items: AlertPage) => any): Promise<AlertPage>;
  /**
   * Retrieve a single target page of AlertInstance records from the API.
   *
   * The request is executed immediately.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @param targetUrl - API-generated URL for the requested results page
   * @param callback - Callback to handle list of records
   */
  getPage(targetUrl?: string, callback?: (error: Error | null, items: AlertPage) => any): Promise<AlertPage>;
  /**
   * Lists AlertInstance records from the API as a list.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @param callback - Callback to handle list of records
   */
  list(callback?: (error: Error | null, items: AlertInstance[]) => any): Promise<AlertInstance[]>;
  /**
   * Lists AlertInstance records from the API as a list.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @param opts - Options for request
   * @param callback - Callback to handle list of records
   */
  list(opts?: AlertListInstanceOptions, callback?: (error: Error | null, items: AlertInstance[]) => any): Promise<AlertInstance[]>;
  /**
   * Retrieve a single page of AlertInstance records from the API.
   *
   * The request is executed immediately.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @param callback - Callback to handle list of records
   */
  page(callback?: (error: Error | null, items: AlertPage) => any): Promise<AlertPage>;
  /**
   * Retrieve a single page of AlertInstance records from the API.
   *
   * The request is executed immediately.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @param opts - Options for request
   * @param callback - Callback to handle list of records
   */
  page(opts?: AlertListInstancePageOptions, callback?: (error: Error | null, items: AlertPage) => any): Promise<AlertPage>;
  /**
   * Provide a user-friendly representation
   */
  toJSON(): any;
}

/**
 * Options to pass to each
 *
 * @property callback -
 *                         Function to process each record. If this and a positional
 *                         callback are passed, this one will be used
 * @property done - Function to be called upon completion of streaming
 * @property endDate - Only include alerts that occurred on or before this date and time
 * @property limit -
 *                         Upper limit for the number of records to return.
 *                         each() guarantees never to return more than limit.
 *                         Default is no limit
 * @property logLevel - Only show alerts for this log-level
 * @property pageSize -
 *                         Number of records to fetch per request,
 *                         when not set will use the default value of 50 records.
 *                         If no pageSize is defined but a limit is defined,
 *                         each() will attempt to read the limit with the most efficient
 *                         page size, i.e. min(limit, 1000)
 * @property startDate - Only include alerts that occurred on or after this date and time
 */
interface AlertListInstanceEachOptions {
  callback?: (item: AlertInstance, done: (err?: Error) => void) => void;
  done?: Function;
  endDate?: Date;
  limit?: number;
  logLevel?: string;
  pageSize?: number;
  startDate?: Date;
}

/**
 * Options to pass to list
 *
 * @property endDate - Only include alerts that occurred on or before this date and time
 * @property limit -
 *                         Upper limit for the number of records to return.
 *                         list() guarantees never to return more than limit.
 *                         Default is no limit
 * @property logLevel - Only show alerts for this log-level
 * @property pageSize -
 *                         Number of records to fetch per request,
 *                         when not set will use the default value of 50 records.
 *                         If no page_size is defined but a limit is defined,
 *                         list() will attempt to read the limit with the most
 *                         efficient page size, i.e. min(limit, 1000)
 * @property startDate - Only include alerts that occurred on or after this date and time
 */
interface AlertListInstanceOptions {
  endDate?: Date;
  limit?: number;
  logLevel?: string;
  pageSize?: number;
  startDate?: Date;
}

/**
 * Options to pass to page
 *
 * @property endDate - Only include alerts that occurred on or before this date and time
 * @property logLevel - Only show alerts for this log-level
 * @property pageNumber - Page Number, this value is simply for client state
 * @property pageSize - Number of records to return, defaults to 50
 * @property pageToken - PageToken provided by the API
 * @property startDate - Only include alerts that occurred on or after this date and time
 */
interface AlertListInstancePageOptions {
  endDate?: Date;
  logLevel?: string;
  pageNumber?: number;
  pageSize?: number;
  pageToken?: string;
  startDate?: Date;
}

interface AlertPayload extends AlertResource, Page.TwilioResponsePayload {
}

interface AlertResource {
  account_sid: string;
  alert_text: string;
  api_version: string;
  date_created: Date;
  date_generated: Date;
  date_updated: Date;
  error_code: string;
  log_level: string;
  more_info: string;
  request_headers?: string;
  request_method: string;
  request_url: string;
  request_variables?: string;
  resource_sid: string;
  response_body?: string;
  response_headers?: string;
  service_sid: string;
  sid: string;
  url: string;
}

interface AlertSolution {
}

declare class AlertContext {
  /**
   * Initialize the AlertContext
   *
   * @param version - Version of the resource
   * @param sid - The SID that identifies the resource to fetch
   */
  constructor(version: V1, sid: string);

  /**
   * fetch a AlertInstance
   *
   * @param callback - Callback to handle processed record
   */
  fetch(callback?: (error: Error | null, items: AlertInstance) => any): Promise<AlertInstance>;
  /**
   * Provide a user-friendly representation
   */
  toJSON(): any;
}

declare class AlertInstance extends SerializableClass {
  /**
   * Initialize the AlertContext
   *
   * @param version - Version of the resource
   * @param payload - The instance payload
   * @param sid - The SID that identifies the resource to fetch
   */
  constructor(version: V1, payload: AlertPayload, sid: string);

  private _proxy: AlertContext;
  accountSid: string;
  alertText: string;
  apiVersion: string;
  dateCreated: Date;
  dateGenerated: Date;
  dateUpdated: Date;
  errorCode: string;
  /**
   * fetch a AlertInstance
   *
   * @param callback - Callback to handle processed record
   */
  fetch(callback?: (error: Error | null, items: AlertInstance) => any): Promise<AlertInstance>;
  logLevel: string;
  moreInfo: string;
  requestHeaders: string;
  requestMethod: string;
  requestUrl: string;
  requestVariables: string;
  resourceSid: string;
  responseBody: string;
  responseHeaders: string;
  serviceSid: string;
  sid: string;
  /**
   * Provide a user-friendly representation
   */
  toJSON(): any;
  url: string;
}

declare class AlertPage extends Page<V1, AlertPayload, AlertResource, AlertInstance> {
  /**
   * Initialize the AlertPage
   *
   * @param version - Version of the resource
   * @param response - Response from the API
   * @param solution - Path solution
   */
  constructor(version: V1, response: Response<string>, solution: AlertSolution);

  /**
   * Build an instance of AlertInstance
   *
   * @param payload - Payload response from the API
   */
  getInstance(payload: AlertPayload): AlertInstance;
  /**
   * Provide a user-friendly representation
   */
  toJSON(): any;
}

export { AlertContext, AlertInstance, AlertList, AlertListInstance, AlertListInstanceEachOptions, AlertListInstanceOptions, AlertListInstancePageOptions, AlertPage, AlertPayload, AlertResource, AlertSolution }


text:
package com.pilaf.cs.game.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.jmx.export.annotation.ManagedAttribute;
import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.stereotype.Component;

@Component
@ManagedResource(objectName = "cs:name=MaximumGamesHolder")
public class MaximumGamesHolder {

	@Autowired
	private Environment env;

	@Value("${castlesiege.gamesearch.maxgames}")
	private long maximumGames;

	@ManagedAttribute
	public long getMaximumGames() {
		return maximumGames;
	}

	@ManagedAttribute
	public void setMaximumGames(long maximumGames) {
		this.maximumGames = maximumGames;
	}

	@ManagedAttribute
	public void resetToDefault() {
		Long maxGamesDefault = Long.valueOf(env.getProperty("castlesiege.gamesearch.maxgames"));
		this.setMaximumGames(maxGamesDefault);

	}

}


text:
{- |
Module        : Data.Graph.Simple
Description   : Data structures and algorithms for simple unlabeled graphs
Copyright     : Stefan Höck
Maintainer    : Stefan Höck
Stability     : experimental

See 'Data.Graph.Simple.Graph' and 'Data.Graph.Simple.Query' for
more documentation.
-}
module Data.Graph.Simple (
  module Data.Graph.Simple.Graph
, module Data.Graph.Simple.Query
) where

import Data.Graph.Simple.Graph
import Data.Graph.Simple.Query


text:
//===- StringTableBuilder.cpp - String table building utility -------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "llvm/MC/StringTableBuilder.h"
#include "llvm/ADT/CachedHashString.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/BinaryFormat/COFF.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/raw_ostream.h"
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <utility>
#include <vector>

using namespace llvm;

StringTableBuilder::~StringTableBuilder() = default;

void StringTableBuilder::initSize() {
  // Account for leading bytes in table so that offsets returned from add are
  // correct.
  switch (K) {
  case RAW:
  case DWARF:
    Size = 0;
    break;
  case MachO:
  case ELF:
    // Start the table with a NUL byte.
    Size = 1;
    break;
  case WinCOFF:
    // Make room to write the table size later.
    Size = 4;
    break;
  }
}

StringTableBuilder::StringTableBuilder(Kind K, unsigned Alignment)
    : K(K), Alignment(Alignment) {
  initSize();
}

void StringTableBuilder::write(raw_ostream &OS) const {
  assert(isFinalized());
  SmallString<0> Data;
  Data.resize(getSize());
  write((uint8_t *)Data.data());
  OS << Data;
}

using StringPair = std::pair<CachedHashStringRef, size_t>;

void StringTableBuilder::write(uint8_t *Buf) const {
  assert(isFinalized());
  for (const StringPair &P : StringIndexMap) {
    StringRef Data = P.first.val();
    if (!Data.empty())
      memcpy(Buf + P.second, Data.data(), Data.size());
  }
  if (K != WinCOFF)
    return;
  support::endian::write32le(Buf, Size);
}

// Returns the character at Pos from end of a string.
static int charTailAt(StringPair *P, size_t Pos) {
  StringRef S = P->first.val();
  if (Pos >= S.size())
    return -1;
  return (unsigned char)S[S.size() - Pos - 1];
}

// Three-way radix quicksort. This is much faster than std::sort with strcmp
// because it does not compare characters that we already know the same.
static void multikeySort(MutableArrayRef<StringPair *> Vec, int Pos) {
tailcall:
  if (Vec.size() <= 1)
    return;

  // Partition items so that items in [0, I) are greater than the pivot,
  // [I, J) are the same as the pivot, and [J, Vec.size()) are less than
  // the pivot.
  int Pivot = charTailAt(Vec[0], Pos);
  size_t I = 0;
  size_t J = Vec.size();
  for (size_t K = 1; K < J;) {
    int C = charTailAt(Vec[K], Pos);
    if (C > Pivot)
      std::swap(Vec[I++], Vec[K++]);
    else if (C < Pivot)
      std::swap(Vec[--J], Vec[K]);
    else
      K++;
  }

  multikeySort(Vec.slice(0, I), Pos);
  multikeySort(Vec.slice(J), Pos);

  // multikeySort(Vec.slice(I, J - I), Pos + 1), but with
  // tail call optimization.
  if (Pivot != -1) {
    Vec = Vec.slice(I, J - I);
    ++Pos;
    goto tailcall;
  }
}

void StringTableBuilder::finalize() {
  assert(K != DWARF);
  finalizeStringTable(/*Optimize=*/true);
}

void StringTableBuilder::finalizeInOrder() {
  finalizeStringTable(/*Optimize=*/false);
}

void StringTableBuilder::finalizeStringTable(bool Optimize) {
  Finalized = true;

  if (Optimize) {
    std::vector<StringPair *> Strings;
    Strings.reserve(StringIndexMap.size());
    for (StringPair &P : StringIndexMap)
      Strings.push_back(&P);

    multikeySort(Strings, 0);
    initSize();

    StringRef Previous;
    for (StringPair *P : Strings) {
      StringRef S = P->first.val();
      if (Previous.endswith(S)) {
        size_t Pos = Size - S.size() - (K != RAW);
        if (!(Pos & (Alignment - 1))) {
          P->second = Pos;
          continue;
        }
      }

      Size = alignTo(Size, Alignment);
      P->second = Size;

      Size += S.size();
      if (K != RAW)
        ++Size;
      Previous = S;
    }
  }

  if (K == MachO)
    Size = alignTo(Size, 4); // Pad to multiple of 4.

  // The first byte in an ELF string table must be null, according to the ELF
  // specification. In 'initSize()' we reserved the first byte to hold null for
  // this purpose and here we actually add the string to allow 'getOffset()' to
  // be called on an empty string.
  if (K == ELF)
    StringIndexMap[CachedHashStringRef("")] = 0;
}

void StringTableBuilder::clear() {
  Finalized = false;
  StringIndexMap.clear();
}

size_t StringTableBuilder::getOffset(CachedHashStringRef S) const {
  assert(isFinalized());
  auto I = StringIndexMap.find(S);
  assert(I != StringIndexMap.end() && "String is not in table!");
  return I->second;
}

size_t StringTableBuilder::add(CachedHashStringRef S) {
  if (K == WinCOFF)
    assert(S.size() > COFF::NameSize && "Short string in COFF string table!");

  assert(!isFinalized());
  auto P = StringIndexMap.insert(std::make_pair(S, 0));
  if (P.second) {
    size_t Start = alignTo(Size, Alignment);
    P.first->second = Start;
    Size = Start + S.size() + (K != RAW);
  }
  return P.first->second;
}


text:
from __future__ import absolute_import, division, print_function
import os
import sys
import errno
import base64
import yaml

from jinja2 import Template, Environment, FileSystemLoader, exceptions, contextfilter

PATH = os.path.dirname(os.path.realpath(__file__))
TEMPLATE_PATH = os.path.realpath(os.path.join(PATH, 'templates'))

def render_base64(file):
	try:
		with open(os.path.realpath(file), 'rb') as f:
			return base64.b64encode(f.read())
	except Exception as e:
		print(e, file=sys.stderr)
		sys.exit(1)

def render_hyphens(input):
	return input.replace('_','-')

def render_yaml(input):
	return yaml.safe_dump(input, default_flow_style=False)

def render_shell_string(input):
	return '<%= Shellwords.escape ' + input + ' %>'

def render_plans_json(input):
	return ('<%\n'
	'		plans = { }\n'
	'		p("' + input + '").each do |plan|\n'
	'			plan_name = plan[\'name\']\n'
	'			plans[plan_name] = plan\n'
	'		end\n'
	'	%>\n'
	'	export ' + input.upper() + '=<%= Shellwords.escape JSON.dump(plans) %>')

@contextfilter
def render(context, input):
	template = Template(input)
	return template.render(context)

TEMPLATE_ENVIRONMENT = Environment(trim_blocks=True, lstrip_blocks=True)
TEMPLATE_ENVIRONMENT.loader = FileSystemLoader(TEMPLATE_PATH)
TEMPLATE_ENVIRONMENT.globals['base64'] = render_base64
TEMPLATE_ENVIRONMENT.filters['hyphens'] = render_hyphens
TEMPLATE_ENVIRONMENT.filters['yaml'] = render_yaml
TEMPLATE_ENVIRONMENT.filters['shell_string'] = render_shell_string
TEMPLATE_ENVIRONMENT.filters['plans_json'] = render_plans_json
TEMPLATE_ENVIRONMENT.filters['render'] = render

def render(target_path, template_file, config):
	target_dir = os.path.dirname(target_path)
	if target_dir != '':
		mkdir_p(target_dir)
	with open(target_path, 'wb') as target:
		target.write(TEMPLATE_ENVIRONMENT.get_template(template_file).render(config))

def exists(template_file):
	return os.exists(path(template_file))

def path(template_file):
	return os.path.join(TEMPLATE_PATH, template_file)

def mkdir_p(dir):
	try:
		os.makedirs(dir)
	except os.error as e:
		if e.errno != errno.EEXIST:
			raise


text:
..  include:: /_fragments/languages_spelling_words_ignorelist.rst

..  _languages:

What languages does Office Online support?
==========================================

Office Online supports over 100 languages. In order to control the language of the Office Online UI, see the
:term:`UI_LLCC` placeholder value.

..  important::
    When replacing the :term:`UI_LLCC` parameter, do not use the *LCID* value from the table below. Instead, use the
    *Locale ID* value. You may also use any value provided it is in the format described in :rfc:`1766`.

..  csv-table:: Languages supported in Office Online
    :file: ../tables/languages.csv
    :header-rows: 1


text:
/*
 * To change this license header, choose License Headers reader Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template reader the editor.
 */
package org.redkale.net.sncp;

import java.lang.annotation.*;
import java.lang.reflect.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.logging.*;
import javax.annotation.Resource;
import org.redkale.convert.bson.*;
import org.redkale.convert.json.*;
import org.redkale.mq.*;
import org.redkale.net.*;
import static org.redkale.net.sncp.SncpRequest.*;
import org.redkale.service.*;
import org.redkale.util.*;
import org.redkale.service.RpcCall;
import org.redkale.source.CacheSource;
import org.redkale.source.DataSource;

/**
 *
 * <p>
 * 详情见: https://redkale.org
 *
 * @author zhangjx
 */
public final class SncpClient {

    protected static final Logger logger = Logger.getLogger(SncpClient.class.getSimpleName());

    protected final JsonConvert convert = JsonFactory.root().getConvert();

    protected final String name;

    protected final boolean remote;

    private final Class serviceClass;

    protected final InetSocketAddress clientSncpAddress;

    private final byte[] addrBytes;

    private final int addrPort;

    protected final DLong serviceid;

    protected final int serviceversion;

    protected final SncpAction[] actions;

    protected final MessageAgent messageAgent;

    protected final SncpMessageClient messageClient;

    protected final String topic;

    @Resource
    protected JsonConvert jsonConvert;

    @Resource
    protected BsonConvert bsonConvert;

    //远程模式, 可能为null
    protected Set<String> remoteGroups;

    //远程模式, 可能为null
    protected Transport remoteGroupTransport;

    public <T extends Service> SncpClient(final String serviceName, final Class<T> serviceTypeOrImplClass, final T service, MessageAgent messageAgent, final TransportFactory factory,
        final boolean remote, final Class serviceClass, final InetSocketAddress clientSncpAddress) {
        this.remote = remote;
        this.messageAgent = messageAgent;
        this.messageClient = messageAgent == null ? null : messageAgent.getSncpMessageClient();
        this.topic = messageAgent == null ? null : messageAgent.generateSncpReqTopic(service);
        Class<?> tn = serviceTypeOrImplClass;
        Version ver = tn.getAnnotation(Version.class);
        this.serviceClass = serviceClass;
        this.serviceversion = ver == null ? 0 : ver.value();
        this.clientSncpAddress = clientSncpAddress;
        this.name = serviceName;
        ResourceType rt = tn.getAnnotation(ResourceType.class);
        if (rt != null) tn = rt.value();
        this.serviceid = Sncp.hash(tn.getName() + ':' + serviceName);
        final List<SncpAction> methodens = new ArrayList<>();
        //------------------------------------------------------------------------------
        for (java.lang.reflect.Method method : parseMethod(serviceClass)) {
            methodens.add(new SncpAction(serviceClass, method, Sncp.hash(method)));
        }
        this.actions = methodens.toArray(new SncpAction[methodens.size()]);
        this.addrBytes = clientSncpAddress == null ? new byte[4] : clientSncpAddress.getAddress().getAddress();
        this.addrPort = clientSncpAddress == null ? 0 : clientSncpAddress.getPort();
        if (this.addrBytes.length != 4) throw new RuntimeException("SNCP clientAddress only support IPv4");
    }

    static List<SncpAction> getSncpActions(final Class serviceClass) {
        final List<SncpAction> actions = new ArrayList<>();
        //------------------------------------------------------------------------------
        for (java.lang.reflect.Method method : parseMethod(serviceClass)) {
            actions.add(new SncpAction(serviceClass, method, Sncp.hash(method)));
        }
        return actions;
    }

    public MessageAgent getMessageAgent() {
        return messageAgent;
    }

    public InetSocketAddress getClientAddress() {
        return clientSncpAddress;
    }

    public DLong getServiceid() {
        return serviceid;
    }

    public int getServiceversion() {
        return serviceversion;
    }

    public int getActionCount() {
        return actions.length;
    }

    public Set<String> getRemoteGroups() {
        return remoteGroups;
    }

    public void setRemoteGroups(Set<String> remoteGroups) {
        this.remoteGroups = remoteGroups;
    }

    public Transport getRemoteGroupTransport() {
        return remoteGroupTransport;
    }

    public void setRemoteGroupTransport(Transport remoteGroupTransport) {
        this.remoteGroupTransport = remoteGroupTransport;
    }

    @Override
    public String toString() {
        String service = serviceClass.getName();
        if (remote) service = service.replace("DynLocalService", "DynRemoteService");
        return this.getClass().getSimpleName() + "(service = " + service + ", serviceid = " + serviceid + ", serviceversion = " + serviceversion + ", name = '" + name
            + "', address = " + (clientSncpAddress == null ? "" : (clientSncpAddress.getHostString() + ":" + clientSncpAddress.getPort()))
            + ", actions.size = " + actions.length + ")";
    }

    public String toSimpleString() { //给Sncp产生的Service用
        if(DataSource.class.isAssignableFrom(serviceClass)||CacheSource.class.isAssignableFrom(serviceClass)){
             String service = serviceClass.getAnnotation(SncpDyn.class) ==null? serviceClass.getName() : serviceClass.getSuperclass().getSimpleName();
             return service + "(serviceid=" + serviceid + ", name='" + name + "', actions.size=" + actions.length + ")";
        }
        String service = serviceClass.getAnnotation(SncpDyn.class) ==null? serviceClass.getName() : serviceClass.getSuperclass().getSimpleName();
        if (remote) service = service.replace("DynLocalService", "DynRemoteService");
        return service + "(name = '" + name + "', serviceid = " + serviceid + ", serviceversion = " + serviceversion
            + ", clientaddr = " + (clientSncpAddress == null ? "" : (clientSncpAddress.getHostString() + ":" + clientSncpAddress.getPort()))
            + ((remoteGroups == null || remoteGroups.isEmpty()) ? "" : ", remoteGroups = " + remoteGroups)
            + (remoteGroupTransport == null ? "" : ", remoteGroupTransport = " + Arrays.toString(remoteGroupTransport.getRemoteAddresses()))
            + ", actions.size = " + actions.length + ")";
    }

    public static List<Method> parseMethod(final Class serviceClass) {
        final List<Method> list = new ArrayList<>();
        final List<Method> multis = new ArrayList<>();
        final Map<DLong, Method> actionids = new HashMap<>();
        for (final java.lang.reflect.Method method : serviceClass.getMethods()) {
            if (method.isSynthetic()) continue;
            if (Modifier.isStatic(method.getModifiers())) continue;
            if (Modifier.isFinal(method.getModifiers())) continue;
            if (method.getAnnotation(Local.class) != null) continue;
            if (method.getName().equals("getClass") || method.getName().equals("toString")) continue;
            if (method.getName().equals("equals") || method.getName().equals("hashCode")) continue;
            if (method.getName().equals("notify") || method.getName().equals("notifyAll") || method.getName().equals("wait")) continue;
            if (method.getParameterCount() == 1 && method.getParameterTypes()[0] == AnyValue.class) {
                if (method.getName().equals("init") || method.getName().equals("stop") || method.getName().equals("destroy")) continue;
            }
            //if (onlySncpDyn && method.getAnnotation(SncpDyn.class) == null) continue;

            DLong actionid = Sncp.hash(method);
            Method old = actionids.get(actionid);
            if (old != null) {
                if (old.getDeclaringClass().equals(method.getDeclaringClass()))
                    throw new RuntimeException(serviceClass.getName() + " have one more same action(Method=" + method + ", " + old + ", actionid=" + actionid + ")");
                continue;
            }
            actionids.put(actionid, method);
            if (method.getAnnotation(SncpDyn.class) != null) {
                multis.add(method);
            } else {
                list.add(method);
            }
        }
        multis.sort((m1, m2) -> m1.getAnnotation(SncpDyn.class).index() - m2.getAnnotation(SncpDyn.class).index());
        list.sort((Method o1, Method o2) -> {
            if (!o1.getName().equals(o2.getName())) return o1.getName().compareTo(o2.getName());
            if (o1.getParameterCount() != o2.getParameterCount()) return o1.getParameterCount() - o2.getParameterCount();
            return 0;
        });
        //带SncpDyn必须排在前面
        multis.addAll(list);
        return multis;
    }

    //只给远程模式调用的
    public <T> T remote(final int index, final Object... params) {
        final SncpAction action = actions[index];
        final CompletionHandler handlerFunc = action.handlerFuncParamIndex >= 0 ? (CompletionHandler) params[action.handlerFuncParamIndex] : null;
        if (action.handlerFuncParamIndex >= 0) params[action.handlerFuncParamIndex] = null;
        final BsonReader reader = bsonConvert.pollBsonReader();
        CompletableFuture<byte[]> future = remote0(handlerFunc, remoteGroupTransport, null, action, params);
        if (action.boolReturnTypeFuture) { //与handlerFuncIndex互斥
            CompletableFuture result = action.futureCreator.create();
            future.whenComplete((v, e) -> {
                try {
                    if (e != null) {
                        result.completeExceptionally(e);
                    } else {
                        reader.setBytes(v);
                        byte i;
                        while ((i = reader.readByte()) != 0) {
                            final Attribute attr = action.paramAttrs[i];
                            attr.set(params[i - 1], bsonConvert.convertFrom(attr.genericType(), reader));
                        }
                        Object rs = bsonConvert.convertFrom(Object.class, reader);

                        result.complete(rs);
                    }
                } catch (Exception exp) {
                    result.completeExceptionally(exp);
                } finally {
                    bsonConvert.offerBsonReader(reader);
                }
            }); //需要获取  Executor
            return (T) result;
        }
        if (handlerFunc != null) return null;
        try {
            reader.setBytes(future.get(5, TimeUnit.SECONDS));
            byte i;
            while ((i = reader.readByte()) != 0) {
                final Attribute attr = action.paramAttrs[i];
                attr.set(params[i - 1], bsonConvert.convertFrom(attr.genericType(), reader));
            }
            return bsonConvert.convertFrom(action.handlerFuncParamIndex >= 0 ? Object.class : action.resultTypes, reader);
        } catch (RpcRemoteException re) {
            throw re;
        } catch (TimeoutException e) {
            throw new RpcRemoteException(actions[index].method + " sncp remote timeout, params=" + JsonConvert.root().convertTo(params));
        } catch (InterruptedException | ExecutionException e) {
            throw new RpcRemoteException(actions[index].method + " sncp remote error, params=" + JsonConvert.root().convertTo(params), e);
        } finally {
            bsonConvert.offerBsonReader(reader);
        }
    }

    private CompletableFuture<byte[]> remote0(final CompletionHandler handler, final Transport transport, final SocketAddress addr0, final SncpAction action, final Object... params) {
        final Type[] myparamtypes = action.paramTypes;
        final Class[] myparamclass = action.paramClass;
        if (action.addressSourceParamIndex >= 0) params[action.addressSourceParamIndex] = this.clientSncpAddress;
        if (bsonConvert == null) bsonConvert = BsonConvert.root();
        final BsonWriter writer = bsonConvert.pollBsonWriter(); // 将head写入
        writer.writeTo(DEFAULT_HEADER);
        for (int i = 0; i < params.length; i++) {  //params 可能包含: 3 个 boolean
            BsonConvert bcc = bsonConvert;
            if (params[i] instanceof org.redkale.service.RetResult) {
                org.redkale.convert.Convert cc = ((org.redkale.service.RetResult) params[i]).convert();
                if (cc instanceof BsonConvert) bcc = (BsonConvert) cc;
            }
            bcc.convertTo(writer, CompletionHandler.class.isAssignableFrom(myparamclass[i]) ? CompletionHandler.class : myparamtypes[i], params[i]);
        }
        final int reqBodyLength = writer.count() - HEADER_SIZE; //body总长度
        final long seqid = System.nanoTime();
        final DLong actionid = action.actionid;
        if (messageAgent != null) { //MQ模式
            final ByteArray reqbytes = writer.toByteArray();
            fillHeader(reqbytes, seqid, actionid, reqBodyLength);
            String targetTopic = action.topicTargetParamIndex >= 0 ? (String) params[action.topicTargetParamIndex] : this.topic;
            if (targetTopic == null) targetTopic = this.topic;
            MessageRecord message = messageClient.createMessageRecord(targetTopic, null, reqbytes.getBytes());
            final String tt = targetTopic;
            if (logger.isLoggable(Level.FINER)) {
                message.attach(Utility.append(new Object[]{action.actionName()}, params));
            } else {
                message.attach(params);
            }
            return messageClient.sendMessage(message).thenApply(msg -> {
                if (msg == null || msg.getContent() == null) {
                    logger.log(Level.SEVERE, action.method + " sncp mq(params: " + convert.convertTo(params) + ", message: " + message + ") deal error, this.topic = " + this.topic + ", targetTopic = " + tt + ", result = " + msg);
                    return null;
                }
                ByteBuffer buffer = ByteBuffer.wrap(msg.getContent());
                checkResult(seqid, action, buffer);

                final int respBodyLength = buffer.getInt();
                final int retcode = buffer.getInt();
                if (retcode != 0) {
                    logger.log(Level.SEVERE, action.method + " sncp (params: " + convert.convertTo(params) + ") deal error (retcode=" + retcode + ", retinfo=" + SncpResponse.getRetCodeInfo(retcode) + "), params=" + JsonConvert.root().convertTo(params));
                    throw new RuntimeException("remote service(" + action.method + ") deal error (retcode=" + retcode + ", retinfo=" + SncpResponse.getRetCodeInfo(retcode) + ")");
                }
                byte[] body = new byte[respBodyLength];
                buffer.get(body, 0, respBodyLength);
                return body;
            });
        }
        final SocketAddress addr = addr0 == null ? (action.addressTargetParamIndex >= 0 ? (SocketAddress) params[action.addressTargetParamIndex] : null) : addr0;
        CompletableFuture<AsyncConnection> connFuture = transport.pollConnection(addr);
        return connFuture.thenCompose(conn0 -> {
            final CompletableFuture<byte[]> future = new CompletableFuture();
            if (conn0 == null) {
                future.completeExceptionally(new RpcRemoteException("sncp " + (conn0 == null ? addr : conn0.getRemoteAddress()) + " cannot connect, params=" + JsonConvert.root().convertTo(params)));
                return future;
            }
            if (!conn0.isOpen()) {
                conn0.dispose();
                future.completeExceptionally(new RpcRemoteException("sncp " + conn0.getRemoteAddress() + " cannot connect, params=" + JsonConvert.root().convertTo(params)));
                return future;
            }
            final AsyncConnection conn = conn0;
            final ByteArray array = writer.toByteArray();
            fillHeader(array, seqid, actionid, reqBodyLength);

            conn.write(array, new CompletionHandler<Integer, Void>() {

                @Override
                public void completed(Integer result, Void attachments) {
                    //----------------------- 读取返回结果 -------------------------------------
                    conn.read(new CompletionHandler<Integer, ByteBuffer>() {

                        private byte[] body;

                        private int received;

                        @Override
                        public void completed(Integer count, ByteBuffer buffer) {
                            try {
                                if (count < 1 && buffer.remaining() == buffer.limit()) {   //没有数据可读
                                    future.completeExceptionally(new RpcRemoteException(action.method + " sncp[" + conn.getRemoteAddress() + "] remote no response data, params=" + JsonConvert.root().convertTo(params)));
                                    conn.offerBuffer(buffer);
                                    transport.offerConnection(true, conn);
                                    return;
                                }
                                if (received < 1 && buffer.limit() < buffer.remaining() + HEADER_SIZE) { //header都没读全
                                    conn.setReadBuffer(buffer);
                                    conn.read(this);
                                    return;
                                }
                                buffer.flip();
                                if (received > 0) {
                                    int offset = this.received;
                                    this.received += buffer.remaining();
                                    buffer.get(body, offset, Math.min(buffer.remaining(), this.body.length - offset));
                                    if (this.received < this.body.length) {// 数据仍然不全,需要继续读取
                                        buffer.clear();
                                        conn.setReadBuffer(buffer);
                                        conn.read(this);
                                    } else {
                                        conn.offerBuffer(buffer);
                                        success();
                                    }
                                    return;
                                }
                                checkResult(seqid, action, buffer);

                                final int respBodyLength = buffer.getInt();
                                final int retcode = buffer.getInt();
                                if (retcode != 0) {
                                    logger.log(Level.SEVERE, action.method + " sncp (params: " + convert.convertTo(params) + ") deal error (retcode=" + retcode + ", retinfo=" + SncpResponse.getRetCodeInfo(retcode) + "), params=" + JsonConvert.root().convertTo(params));
                                    throw new RuntimeException("remote service(" + action.method + ") deal error (retcode=" + retcode + ", retinfo=" + SncpResponse.getRetCodeInfo(retcode) + ")");
                                }

                                if (respBodyLength > buffer.remaining()) { // 数据不全,需要继续读取
                                    this.body = new byte[respBodyLength];
                                    this.received = buffer.remaining();
                                    buffer.get(body, 0, this.received);
                                    buffer.clear();
                                    conn.setReadBuffer(buffer);
                                    conn.read(this);
                                } else {
                                    this.body = new byte[respBodyLength];
                                    buffer.get(body, 0, respBodyLength);
                                    conn.offerBuffer(buffer);
                                    success();
                                }
                            } catch (Throwable e) {
                                future.completeExceptionally(new RpcRemoteException(action.method + " sncp[" + conn.getRemoteAddress() + "] remote response error, params=" + JsonConvert.root().convertTo(params)));
                                transport.offerConnection(true, conn);
                                if (handler != null) {
                                    final Object handlerAttach = action.handlerAttachParamIndex >= 0 ? params[action.handlerAttachParamIndex] : null;
                                    handler.failed(e, handlerAttach);
                                }
                                logger.log(Level.SEVERE, action.method + " sncp (params: " + convert.convertTo(params) + ") deal error", e);
                            }
                        }

                        @SuppressWarnings("unchecked")
                        public void success() {
                            future.complete(this.body);
                            transport.offerConnection(false, conn);
                            if (handler != null) {
                                final Object handlerAttach = action.handlerAttachParamIndex >= 0 ? params[action.handlerAttachParamIndex] : null;
                                final BsonReader reader = bsonConvert.pollBsonReader();
                                try {
                                    reader.setBytes(this.body);
                                    int i;
                                    while ((i = (reader.readByte() & 0xff)) != 0) {
                                        final Attribute attr = action.paramAttrs[i];
                                        attr.set(params[i - 1], bsonConvert.convertFrom(attr.genericType(), reader));
                                    }
                                    Object rs = bsonConvert.convertFrom(action.handlerFuncParamIndex >= 0 ? Object.class : action.resultTypes, reader);
                                    handler.completed(rs, handlerAttach);
                                } catch (Exception e) {
                                    handler.failed(e, handlerAttach);
                                } finally {
                                    bsonConvert.offerBsonReader(reader);
                                }
                            }
                        }

                        @Override
                        public void failed(Throwable exc, ByteBuffer attachment2) {
                            future.completeExceptionally(new RpcRemoteException(action.method + " sncp remote exec failed, params=" + JsonConvert.root().convertTo(params)));
                            conn.offerBuffer(attachment2);
                            transport.offerConnection(true, conn);
                            if (handler != null) {
                                final Object handlerAttach = action.handlerAttachParamIndex >= 0 ? params[action.handlerAttachParamIndex] : null;
                                handler.failed(exc, handlerAttach);
                            }
                            logger.log(Level.SEVERE, action.method + " sncp (params: " + convert.convertTo(params) + ") remote read exec failed, params=" + JsonConvert.root().convertTo(params), exc);
                        }
                    });
                }

                @Override
                public void failed(Throwable exc, Void attachment) {
                    future.completeExceptionally(new RpcRemoteException(action.method + " sncp remote exec failed, params=" + JsonConvert.root().convertTo(params)));
                    transport.offerConnection(true, conn);
                    if (handler != null) {
                        final Object handlerAttach = action.handlerAttachParamIndex >= 0 ? params[action.handlerAttachParamIndex] : null;
                        handler.failed(exc, handlerAttach);
                    }
                    logger.log(Level.SEVERE, action.method + " sncp (params: " + convert.convertTo(params) + ") remote write exec failed, params=" + JsonConvert.root().convertTo(params), exc);
                }
            });
            return future;
        });
    }

    private void checkResult(long seqid, final SncpAction action, ByteBuffer buffer) {
        long rseqid = buffer.getLong();
        if (rseqid != seqid) throw new RuntimeException("sncp(" + action.method + ") response.seqid = " + seqid + ", but request.seqid =" + rseqid);
        if (buffer.getChar() != HEADER_SIZE) throw new RuntimeException("sncp(" + action.method + ") buffer receive header.length not " + HEADER_SIZE);
        DLong rserviceid = DLong.read(buffer);
        if (!rserviceid.equals(this.serviceid)) throw new RuntimeException("sncp(" + action.method + ") response.serviceid = " + serviceid + ", but request.serviceid =" + rserviceid);
        int version = buffer.getInt();
        if (version != this.serviceversion) throw new RuntimeException("sncp(" + action.method + ") response.serviceversion = " + serviceversion + ", but request.serviceversion =" + version);
        DLong raction = DLong.read(buffer);
        DLong actid = action.actionid;
        if (!actid.equals(raction)) throw new RuntimeException("sncp(" + action.method + ") response.actionid = " + action.actionid + ", but request.actionid =(" + raction + ")");
        buffer.getInt();  //地址
        buffer.getChar(); //端口
    }

    private void fillHeader(ByteArray buffer, long seqid, DLong actionid, int bodyLength) {
        //---------------------head----------------------------------
        int offset = 0;
        buffer.putLong(offset, seqid); //序列号
        offset += 8;
        buffer.putChar(offset, (char) HEADER_SIZE); //header长度
        offset += 2;
        DLong.write(buffer, offset, this.serviceid);
        offset += 16;
        buffer.putInt(offset, this.serviceversion);
        offset += 4;
        DLong.write(buffer, offset, actionid);
        offset += 16;
        buffer.put(offset, addrBytes);
        offset += addrBytes.length; //4
        buffer.putChar(offset, (char) this.addrPort);
        offset += 2;
        buffer.putInt(offset, bodyLength); //body长度
        offset += 4;
        buffer.putInt(offset, 0); //结果码, 请求方固定传0
        //offset += 4;
    }

//    private void fillHeader(ByteBuffer buffer, long seqid, DLong actionid, int bodyLength) {
//        //---------------------head----------------------------------
//        final int currentpos = buffer.position();
//        buffer.position(0);
//        buffer.putLong(seqid); //序列号
//        buffer.putChar((char) HEADER_SIZE); //header长度
//        DLong.write(buffer, this.serviceid);
//        buffer.putInt(this.serviceversion);
//        DLong.write(buffer, actionid);
//        buffer.put(addrBytes);
//        buffer.putChar((char) this.addrPort);
//        buffer.putInt(bodyLength); //body长度
//        buffer.putInt(0); //结果码, 请求方固定传0
//        buffer.position(currentpos);
//    }
    protected static final class SncpAction {

        protected final DLong actionid;

        protected final Method method;

        protected final Type resultTypes;  //void 必须设为 null

        protected final Type[] paramTypes;

        protected final Class[] paramClass;

        protected final Attribute[] paramAttrs; // 为null表示无RpcCall处理,index=0固定为null, 其他为参数标记的RpcCall回调方法

        protected final int handlerFuncParamIndex;

        protected final int handlerAttachParamIndex;

        protected final int addressTargetParamIndex;

        protected final int addressSourceParamIndex;

        protected final int topicTargetParamIndex;

        protected final boolean boolReturnTypeFuture; // 返回结果类型是否为 CompletableFuture

        protected final Creator<? extends CompletableFuture> futureCreator;

        @SuppressWarnings("unchecked")
        public SncpAction(final Class clazz, Method method, DLong actionid) {
            this.actionid = actionid == null ? Sncp.hash(method) : actionid;
            Type rt = TypeToken.getGenericType(method.getGenericReturnType(), clazz);
            this.resultTypes = rt == void.class ? null : rt;
            this.boolReturnTypeFuture = CompletableFuture.class.isAssignableFrom(method.getReturnType());
            this.futureCreator = boolReturnTypeFuture ? Creator.create((Class<? extends CompletableFuture>) method.getReturnType()) : null;
            this.paramTypes = TypeToken.getGenericType(method.getGenericParameterTypes(), clazz);
            this.paramClass = method.getParameterTypes();
            this.method = method;
            Annotation[][] anns = method.getParameterAnnotations();
            int tpoicAddrIndex = -1;
            int targetAddrIndex = -1;
            int sourceAddrIndex = -1;
            int handlerAttachIndex = -1;
            int handlerFuncIndex = -1;
            boolean hasattr = false;
            Attribute[] atts = new Attribute[paramTypes.length + 1];
            if (anns.length > 0) {
                Class<?>[] params = method.getParameterTypes();
                for (int i = 0; i < params.length; i++) {
                    if (CompletionHandler.class.isAssignableFrom(params[i])) {
                        if (boolReturnTypeFuture) {
                            throw new RuntimeException(method + " have both CompletionHandler and CompletableFuture");
                        }
                        if (handlerFuncIndex >= 0) {
                            throw new RuntimeException(method + " have more than one CompletionHandler type parameter");
                        }
                        Sncp.checkAsyncModifier(params[i], method);
                        handlerFuncIndex = i;
                        break;
                    }
                }
                for (int i = 0; i < anns.length; i++) {
                    if (anns[i].length > 0) {
                        for (Annotation ann : anns[i]) {
                            if (ann.annotationType() == RpcAttachment.class) {
                                if (handlerAttachIndex >= 0) {
                                    throw new RuntimeException(method + " have more than one @RpcAttachment parameter");
                                }
                                handlerAttachIndex = i;
                            } else if (ann.annotationType() == RpcTargetAddress.class && SocketAddress.class.isAssignableFrom(params[i])) {
                                targetAddrIndex = i;
                            } else if (ann.annotationType() == RpcSourceAddress.class && SocketAddress.class.isAssignableFrom(params[i])) {
                                sourceAddrIndex = i;
                            } else if (ann.annotationType() == RpcTargetTopic.class && String.class.isAssignableFrom(params[i])) {
                                tpoicAddrIndex = i;
                            }
                        }
                        for (Annotation ann : anns[i]) {
                            if (ann.annotationType() == RpcCall.class) {
                                try {
                                    atts[i + 1] = ((RpcCall) ann).value().getDeclaredConstructor().newInstance();
                                    RedkaleClassLoader.putReflectionDeclaredConstructors(((RpcCall) ann).value(), ((RpcCall) ann).value().getName());
                                    hasattr = true;
                                } catch (Exception e) {
                                    logger.log(Level.SEVERE, RpcCall.class.getSimpleName() + ".attribute cannot a newInstance for" + method, e);
                                }
                                break;
                            }
                        }
                    }
                }
            }
            this.topicTargetParamIndex = tpoicAddrIndex;
            this.addressTargetParamIndex = targetAddrIndex;
            this.addressSourceParamIndex = sourceAddrIndex;
            this.handlerFuncParamIndex = handlerFuncIndex;
            this.handlerAttachParamIndex = handlerAttachIndex;
            this.paramAttrs = hasattr ? atts : null;
            if (this.handlerFuncParamIndex >= 0 && method.getReturnType() != void.class) {
                throw new RuntimeException(method + " have CompletionHandler type parameter but return type is not void");
            }
        }

        public String actionName() {
            return method.getDeclaringClass().getSimpleName() + "." + method.getName();
        }

        @Override
        public String toString() {
            return "{" + actionid + "," + (method == null ? "null" : method.getName()) + "}";
        }
    }
}


text:
Add [ng-file-upload](https://github.com/danialfarid/ng-file-upload) to [MEAN.JS](http://meanjs.org/)
===================
Using MEAN.JS and ng-file-upload to enable image upload to the Article module.

**Notes**: [MEAN.JS 0.4.2 (2015-11-11)](https://github.com/meanjs/mean/releases/tag/v0.4.2) [ng-file-upload 11.0.0 (2015-12-25)](https://github.com/danialfarid/ng-file-upload/releases/tag/11.0.0)

## Create File Upload Web Service
I created REST API to upload files first and it will be used by Articles to upload images.

#### Install Packages
* Server side, I use connect-multiparty. Multer is already included in MEAN.JS

```bash
$ npm install connect-multiparty --save
```

#### Change configuration
* /config/env/default.js

Configure the file upload path. Make sure you create the folder first.
```js
fileUpload: {
  dest: './modules/core/client/img/uploads/', // file upload destination path
  limits: {
    fileSize: 10*1024*1024 // Max file size in bytes (10 MB)
  }
}
```
* /config/lib/multer.js

Create file upload filter
```js
module.exports.imageUploadFileFilter = function (req, file, cb) {
  if (file.mimetype !== 'image/png' && file.mimetype !== 'image/jpg' && file.mimetype !== 'image/jpeg' && file.mimetype !== 'image/gif') {
    return cb(new Error('Only image files are allowed!'), false);
  }
  cb(null, true);
};
```

#### Add Server Routes
* /modules/core/server/routes/core.server.routes.js

Create Server Router, which will be the REST API endpoint.
```js
app.route('/api/uploads')
  .post(multipartyMiddleware, core.uploads);
```

#### Add Server Controller
* /modules/core/server/controllers/core.server.controller.js

Create Server Controller.
```js
exports.uploads = function (req, res) {
  // console.log('req.headers.content-type:'+req.headers['content-type']); //must be multipart/form-data
  // console.log('req.files.uploadedFile: '+req.files.uploadedFile); //file object
  // console.log('req.files.uploadedFile.fieldname: '+req.files.uploadedFile.fieldName);// "uploadedFile"
  // console.log('req.files.uploadedFile.name: '+req.files.uploadedFile.name); // original filename
  // console.log('req.files.uploadedFile.originalFilename: '+req.files.uploadedFile.originalFilename); // orininal Filename
  // console.log('req.files.uploadedFile.type: '+req.files.uploadedFile.type); //image/jpeg
  // console.log('req.files.uploadedFile.size: '+req.files.uploadedFile.size); // file size
  // console.log('req.body.testkey: '+req.body.testkey); // submited form

  var file=req.files.uploadedFile;
  var user = req.user;
  var message = null;

  //the target folder is ./modules/core/client/img/uploads/base64(username)/
  var userEncode = new Buffer(user.username).toString('base64');
  var destFolder = path.join(path.resolve('./'),config.uploads.fileUpload.dest,userEncode);
  var newFilename = Date.now()+"-"+file.originalFilename;
  var destFile = destFolder+"/"+newFilename;
  //var destURL = req.protocol + '://' + req.get('host') + config.uploads.fileUpload.dest+userEncode+"/"+Date.now()+".jpg";
  var destURL = config.uploads.fileUpload.dest+userEncode+"/"+newFilename;

  //config multer, somehow the diskStorage() is not working
  var storage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, destFolder);
    },
    filename: function (req, file, cb) {
      cb(null, file.originalname + '-' + Date.now());
    }
  });

  var upload = multer({ storage : storage}).single('uploadedFile');
  // Filtering to upload only images
  upload.fileFilter = require(path.resolve('./config/lib/multer')).imageUploadFileFilter;

  // upload file
  upload(req,res,function (err) {
    if(err) {
      return res.status(400).send({
        message: 'Error occurred while uploading profile picture'
      });
    }else{
      // For some reason, the diskStorage function of Multer doesn't work.
      // The following code is to move the file to the destination folder.
      var stat =null;
      try {
        stat = fs.statSync(destFolder);
      } catch (err) {
        fs.mkdirSync(destFolder);
      }
      if (stat && !stat.isDirectory()) {
        throw new Error('Directory cannot be created because an inode of a different type exists at "' + destFolder + '"');
      } else {
        fs.rename(file.path, destFile, function(err) {
          if (err) throw err;
          // delete the temporary file, so that the explicitly set temporary upload dir does not get filled with unwanted files
          fs.unlink(file.path, function() {
            if (err) {
                throw err;
            }else{
              return res.status(200).send({
                uploadedURL: destURL,
                uploadedFile: destFile,
                file: JSON.stringify(req.files),
                message: 'File is uploaded to ' + destURL
              });
            }
          });
        });
      }
    }
  });
};
```
At current point, you should be able to use the REST API to upload file. You can try postman in Chrome like the images below. Please make sure you set Key as "uploadedFile".

## Add Image Feature to Article
I use ng-file-upload for the client side file upload.

#### Install Packages
* Install ng-file-upload

```bash
$ bower install ng-file-upload --save
```
#### Change configuration
* /config/assets/default.js

Add ng-file-upload modules
```js
'public/lib/ng-file-upload/ng-file-upload-shim.js',
'public/lib/ng-file-upload/ng-file-upload.js'
```
* /config/assets/production.js

Add minified version to production configuration
```js
'public/lib/ng-file-upload/ng-file-upload-shim.min.js',
'public/lib/ng-file-upload/ng-file-upload.min.js'
```
* /modules/core/client/app/config.js

Inject ngFileUpload module to dependencies
```js
  var applicationModuleVendorDependencies = ['ngResource', 'ngAnimate', 'ngMessages', 'ui.router', 'ui.bootstrap', 'ui.utils', 'angularFileUpload', 'ngFileUpload'];
```
#### Add image URL to Article Server Models
* /modules/articles/server/models/article.server.model.js

Add image URL field to the Article Model
```js
articleImageURL:{
  type: String,
  default: '',
  trim: true
},
```
#### Change Article Views
* /modules/articles/client/views/create-article.client.view.html

Add Featured Image to the form
```html
<div class="form-group" show-errors>
  <label for="title">Featured Image </label>
  <button type="button" class="btn btn-secondary" ng-show="uploadedFile == null" type="file"
    ngf-select="uploadFiles($file, $invalidFiles)"
    ng-model="uploadedFile" name="file" ngf-model-invalid="errorFiles"
    accept="image/*" ngf-max-size="1MB">
    Select Featured Image</button>
  <div class="text-center">
    <img ng-show="articleForm.file.$valid" ngf-thumbnail="uploadedFile" class="thumb">
  </div>
  <div class="text-center">
    <div class="progress" ng-show="uploadedFile.progress >= 0">
              <div style="width:{{uploadedFile.progress}}%"
                  ng-bind="uploadedFile.progress + '%'"></div>
    </div>
  </div>
  <div class="text-center">
    <button type="button" class="btn btn-secondary" ng-click="uploadedFile = null" ng-show="uploadedFile">Remove</button>
  </div>
  <div class="alert alert-danger" ng-show="articleForm.file.$error.maxSize">File too large
               {{errorFiles[0].size / 1000000|number:1}}MB: max 1M</div>
</div>
```
* /modules/articles/client/views/edit-article.client.view.html

Add Featured Image to the form
```html
<div class="form-group" show-errors>
  <label for="title">Featured Image </label>
  <button ng-show="article.articleImageURL==null || article.articleImageURL==''" type="button" class="btn btn-secondary" type="file"
    ngf-select="uploadFiles($file, $invalidFiles)"
    ng-model="article.articleImageURL" name="file" ngf-model-invalid="errorFiles"
    accept="image/*" ngf-max-size="1MB">
    Select Featured Image</button>
  <div class="text-center" ng-show="article.articleImageURL" >
    <img ng-src="{{article.articleImageURL}}" ngf-thumbnail="article.articleImageURL" class="thumb"/>
  </div>
  <div class="text-center" ng-show="article.articleImageURL">
    <button type="button" class="btn btn-secondary" ng-click="article.articleImageURL = null" >Remove</button>
  </div>
  <div class="alert alert-danger" ng-show="articleForm.file.$error.maxSize">File too large
               {{errorFiles[0].size / 1000000|number:1}}MB: max 1M</div>
</div>
```
* /modules/articles/client/views/list-articles.client.view.html

Show Featured Image in the view
```html
<img ng-src="{{article.articleImageURL}}" height="100" />
```
* /modules/articles/client/views/view-article.client.view.html

Show Featured Image in the view
```html
<img ng-src="{{article.articleImageURL}}" height="100" />
```
#### Change Article Client Controller
* /modules/articles/client/controllers/articles.client.controller.js

Inject Upload and $timeout services to the Article Controller
```js
$scope.uploadFiles = function(file, errFiles) {
    $scope.uploadedFile = file;
    $scope.errFile = errFiles && errFiles[0];
    if (file) {
        file.upload = Upload.upload({
            url: '/api/uploads',
            data: {uploadedFile: file}
        });

        file.upload.then(function (response) {
            console.log('File is successfully uploaded to ' + response.data.uploadedURL);
            $scope.articleImageURL = response.data.uploadedURL;
            $timeout(function () {
                file.result = response.data;
            });
        }, function (response) {
            if (response.status > 0)
                $scope.errorMsg = response.status + ': ' + response.data;
        }, function (evt) {
            file.progress = Math.min(100, parseInt(100.0 *
                                     evt.loaded / evt.total));
        });
    }
};

// Create new Article
$scope.create = function (isValid) {
  $scope.error = null;

  if (!isValid) {
    $scope.$broadcast('show-errors-check-validity', 'articleForm');

    return false;
  }

  // Create new Article object
  var article = new Articles({
    title: $scope.title,
    content: $scope.content,
    articleImageURL: $scope.articleImageURL
  });

  // Redirect after save
  article.$save(function (response) {
    $location.path('articles/' + response._id);

    // Clear form fields
    $scope.title = '';
    $scope.content = '';
    $scope.articleImageURL = '';
  }, function (errorResponse) {
    $scope.error = errorResponse.data.message;
  });
};

// Update existing Article
$scope.update = function (isValid) {
  $scope.error = null;

  if (!isValid) {
    $scope.$broadcast('show-errors-check-validity', 'articleForm');

    return false;
  }

  var article = $scope.article;
  article.articleImageURL = $scope.articleImageURL;

  article.$update(function () {
    $location.path('articles/' + article._id);
  }, function (errorResponse) {
    $scope.error = errorResponse.data.message;
  });
};
```


text:
<?php

class WPML_URL_Converter_Url_Helper {
	/**
	 * @var wpdb
	 */
	private $wpdb;

	/**
	 * @var WPML_Include_Url
	 */
	private $wpml_include_url_filter;

	/**
	 * @var string
	 */
	private $absolute_home;

	/**
	 *
	 * @param wpdb $wpdb
	 * @param WPML_Include_Url $wpml_include_url_filter
	 */
	public function __construct( wpdb $wpdb = null, WPML_Include_Url $wpml_include_url_filter = null ) {
		if ( ! $wpdb ) {
			global $wpdb;
		}

		if ( ! $wpml_include_url_filter ) {
			global $wpml_include_url_filter;
		}

		$this->wpdb                    = $wpdb;
		$this->wpml_include_url_filter = $wpml_include_url_filter;
	}

	/**
	 * Returns the unfiltered home_url by directly retrieving it from wp_options.
	 *
	 * @return string
	 */
	public function get_abs_home() {
		if ( ! $this->absolute_home ) {
			$is_multisite = is_multisite();
			if ( ! $is_multisite && defined( 'WP_HOME' ) ) {
				$this->absolute_home = WP_HOME;
			} elseif ( $is_multisite && ! is_main_site() ) {
				$protocol = preg_match( '/^(https)/', get_option( 'home' ) ) === 1 ? 'https://' : 'http://';
				$sql      = "
					SELECT CONCAT(b.domain, b.path)
					FROM {$this->wpdb->blogs} b
					WHERE blog_id = {$this->wpdb->blogid}
					LIMIT 1
				";

				$this->absolute_home = $protocol . $this->wpdb->get_var( $sql );
			} else {
				$this->absolute_home = $this->get_unfiltered_home_option();
			}
		}

		return apply_filters( 'wpml_url_converter_get_abs_home', $this->absolute_home );
	}

	/**
	 * Checks if a $url points to a WP Admin screen.
	 *
	 * @param string $url
	 * @return bool True if the input $url points to an admin screen.
	 */
	public function is_url_admin( $url ) {
		$url_query_parts = wpml_parse_url( strpos( $url, 'http' ) === false ? 'http://' . $url : $url );

		return isset( $url_query_parts['path'] )
		       && strpos( wpml_strip_subdir_from_url( $url_query_parts['path'] ), '/wp-admin' ) === 0;
	}

	/**
	 * Returns the unfiltered home option from the database.
	 *
	 * @uses \WPML_Include_Url::get_unfiltered_home in case the $wpml_include_url_filter global is loaded
	 *
	 * @return string
	 */
	private function get_unfiltered_home_option() {
		if ( $this->wpml_include_url_filter ) {
			return $this->wpml_include_url_filter->get_unfiltered_home();
		} else {
			$sql = "
				SELECT option_value
				FROM {$this->wpdb->options}
				WHERE option_name = 'home'
				LIMIT 1
			";

			return $this->wpdb->get_var( $sql );
		}
	}
}


text:
/**
 * This code was generated by the xsdtocls codegenerator and is not intended to be changed manually!
 * Note that all your changes will be lost if the codegenerator runs another time on the same destination directory!
 * For further information take a look at: https://github.com/KLINGTdotNET/ssf_project
 */

package com.facebook.api;

class ProfileGetFBMLResponse {
    private String value;

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

    public String getValue() {
        return this.value;
    }

    public String toXML() {
        return "<profile_getFBML_response>" + this.value + "</profile_getFBML_response>";
    }
}


text:
<?php

namespace Dotdigitalgroup\Email\Test\Unit\Model\Sync\Automation\DataField;

use Dotdigitalgroup\Email\Helper\Data;
use Dotdigitalgroup\Email\Model\Apiconnector\Client;
use Dotdigitalgroup\Email\Model\Sync\Automation\DataField\DataFieldUpdater;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Store\Model\Website;
use PHPUnit\Framework\TestCase;

class DataFieldUpdaterTest extends TestCase
{
    /**
     * @var DataFieldUpdater
     */
    private $dataFieldUpdater;

    /**
     * @var Data|\PHPUnit_Framework_MockObject_MockObject
     */
    private $helperMock;

    /**
     * @var Client|\PHPUnit\Framework\MockObject\MockObject
     */
    private $clientMock;

    /**
     * @var StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    private $storeManagerMock;

    /**
     * @var Website|\PHPUnit_Framework_MockObject_MockObject
     */
    private $websiteMock;

    /**
     * @var int
     */
    private $websiteId;

    protected function setUp() :void
    {
        $this->helperMock = $this->createMock(Data::class);
        $this->storeManagerMock = $this->createMock(StoreManagerInterface::class);
        $this->websiteMock = $this->createMock(Website::class);
        $this->clientMock = $this->createMock(Client::class);

        $this->dataFieldUpdater = new DataFieldUpdater(
            $this->helperMock,
            $this->storeManagerMock
        );

        $this->websiteMock->method('getId')
            ->willReturn($this->websiteId = 1234);
    }

    public function testDefaultDataFieldsAreSet()
    {
        $email = 'chaz@kangaroo.com';
        $websiteId = 1;
        $storeName = 'Default Store View';
        $websiteName = 'Main Website';

        $this->setDataFields();

        $this->dataFieldUpdater->setDefaultDataFields(
            $email,
            $websiteId,
            $storeName
        );

        $this->assertEquals(
            $this->getExpectedData($storeName, $websiteName),
            $this->dataFieldUpdater->getData()
        );
    }

    public function testUpdateDataFields()
    {
        $email = 'chaz@kangaroo.com';
        $websiteId = 1;
        $storeName = 'Default Store View';

        $this->setDataFields();

        $this->dataFieldUpdater->setDefaultDataFields(
            $email,
            $websiteId,
            $storeName
        );

        $this->helperMock->expects($this->once())
            ->method('getWebsiteApiClient')
            ->with($this->websiteId)
            ->willReturn($this->clientMock);

        $this->dataFieldUpdater->updateDataFields();
    }

    public function testDataFieldsAreNotUpdatedIfEmpty()
    {
        $email = 'chaz@kangaroo.com';
        $websiteId = 1;
        $storeName = 'Default Store View';
        $websiteName = 'Main Website';

        // setting data fields if none are mapped
        $this->storeManagerMock->expects($this->once())
            ->method('getWebsite')
            ->willReturn($this->websiteMock);

        $this->websiteMock->expects($this->exactly(2))
            ->method('getConfig')
            ->willReturnOnConsecutiveCalls(null, null);

        $this->websiteMock->expects($this->never())
            ->method('getName')
            ->willReturn($websiteName);

        $this->dataFieldUpdater->setDefaultDataFields(
            $email,
            $websiteId,
            $storeName
        );

        $this->helperMock->expects($this->never())
            ->method('getWebsiteApiClient');

        $this->dataFieldUpdater->updateDataFields();
    }

    private function setDataFields()
    {
        $websiteName = 'Main Website';

        $this->storeManagerMock->expects($this->once())
            ->method('getWebsite')
            ->willReturn($this->websiteMock);

        $this->websiteMock->expects($this->exactly(2))
            ->method('getConfig')
            ->willReturnOnConsecutiveCalls('STORE_NAME', 'WEBSITE_NAME');

        $this->websiteMock->expects($this->once())
            ->method('getName')
            ->willReturn($websiteName);
    }

    /**
     * @param $storeName
     * @param $websiteName
     * @return array[]
     */
    private function getExpectedData($storeName, $websiteName)
    {
        return [
            [
                'Key' => 'STORE_NAME',
                'Value' => $storeName
            ],
            [
                'Key' => 'WEBSITE_NAME',
                'Value' => $websiteName
            ]
        ];
    }
}


text:
layout: post
title: Note taking without note taking app
category: workflow
tags:
date: 2016-10-17
last: 2016-10-18
published: true
comments: true
summary: Is it possible to take notes without any note taking apps and lose no convenience?
---

## Why I do not use a note app

Evernote, Quiver, Simplenote, ..., They are all good and I have used them a lot. But now I uninstalled them all. Why?

Some main reasons:

- I prefer to see the note files saved individually in a well used, open, and transparent format, rather than mysterious or private formats defined by the apps themselves.
- I prefer to use my favourite editor rather than the integrated editor reinvented by the apps.

In a word, IMHO, current note taking apps do too much for a note taking job. But could we manage to take notes without the apps and lose no convenience?

## Note format

I decide to use [multimarkdown](https://github.com/fletcher/MultiMarkdown/wiki/MultiMarkdown-Syntax-Guide) because it supports metadata included as part of the document and meanwhile not part of the real contents.

The metadata is a kind of front matter like in [Jekyll post](https://jekyllrb.com/docs/frontmatter/), which describes any infomation you want to add to the document.

Considering a note, the following four variables seems necessary:

```yaml
title: A Note
date: 2016-10-17
category: Cool
tags: workflow, app, mac
```

I restrict the `category` to be only one string, as it is equal to the subfolder name.

And more variables I'd like to add:

- last: last modification date
- comments: true or false
- summary: a brief summary of the note
- published: if published to Jekyll blog

## Manage notes

Finder + Dropbox.

Simply use Finder for note browsing, and Dropbox for syncing to the cloud.

Set a root folder in Dropbox for all notes, e.g. `"Dropbox/Notes"`. Let's call it `notesdir`. Drag it to stay at the side column for quick access.

Then add subfolders as categories. Add a `uncategorized` subfolder for uncategorized notes.

**Tips**: in finder, use list (`Cmd+2`) or column (`Cmd+3`) view to browse note files is (maybe) sufficiently convenient. I prefer the column view, but remember to use the this trick: `Option+drag` to resize the column width to show a lentgh file name, and to let Finder remember the size. Unfortunately the width of all columns must be the same, which is a little ugly, and, this width setting is globally on the mac.

## Edit note

Set in Finder to open and edit the note with your favourite Markdown editor. (I use [MacDown](http://macdown.uranusjr.com/) and [Typora](http://www.typora.io/).)

## Create note

I write a simple shell script to do this. It make a new note file and fill it with initial front matter.

The script is [here](https://gist.github.com/herrkaefer/8c4b84b07e565d8e2ff5e649e55d8f95). Save it as `newnote.sh` and move it to a bash recognized path.

Usage:

```sh
newnote.sh title category
```

- `title` is required. Remember to quote it if spaces exist.
- If `category` is empty, it will be 'uncategorized`.

The note file `notesdir/category/title.md` will be created (if it does not exist) and opened for edit.

## Publish note as Jekyll post

Here I need another script to do the job:

- Copy the note to Jekyll project's `_posts` folder.
- Rename note file to Jekyll required format: `YEAR-MONTH-DAY-title.md`.
- Modify the front matter accordingly, e.g.
	- modify/add `layout` variable
	- modify/add `last` variable
- Sync with blog server
- Add and set `published` variable to true for the original note

`publishnote.sh`: (to add later)

## Do we need a new kind of note taking app, again?

How about writing a new kind of app which implements the above workflow with a minimal UI, and enhance the user experience much?

- Concentrated and user-friendly note browser
- Click buttons or press shortcuts to add, edit, delete, publish, ...

Essentially, the app should be a better replacement of Finder for note browsing, integrated with some common note operations. I think maybe it is worthwhile to implement such an UI. Consider doing it later :-)


text:
class ElectronAccessibilityUI : public content::WebUIController {
 public:
  explicit ElectronAccessibilityUI(content::WebUI* web_ui);
  ~ElectronAccessibilityUI() override;
};

// Manages messages sent from accessibility.js via json.
class ElectronAccessibilityUIMessageHandler
    : public AccessibilityUIMessageHandler {
 public:
  ElectronAccessibilityUIMessageHandler();

  // disable copy
  ElectronAccessibilityUIMessageHandler(
      const ElectronAccessibilityUIMessageHandler&) = delete;
  ElectronAccessibilityUIMessageHandler& operator=(
      const ElectronAccessibilityUIMessageHandler&) = delete;

  void RegisterMessages() final;

 private:
  void RequestNativeUITree(const base::Value::List& args);
};

#endif  // ELECTRON_SHELL_BROWSER_UI_WEBUI_ACCESSIBILITY_UI_H_


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="recent"
        android:id="@+id/bt_recent"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/button3"
        android:layout_centerVertical="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/textView"
        android:layout_above="@+id/button3"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="90dp" />
</RelativeLayout>