text:
#pragma once

#include <algorithm>
#include <exception>
#include <functional>
#include <memory>
#include <type_traits>
#include <vector>

#include <folly/Optional.h>
#include <folly/Portability.h>
#include <folly/MoveWrapper.h>
#include <folly/futures/DrivableExecutor.h>
#include <folly/futures/Promise.h>
#include <folly/futures/Try.h>
#include <folly/futures/FutureException.h>
#include <folly/futures/detail/Types.h>

// boring predeclarations and details
#include <folly/futures/Future-pre.h>

// not-boring helpers, e.g. all in folly::futures, makeFuture variants, etc.
// Needs to be included after Future-pre.h and before Future-inl.h
#include <folly/futures/helpers.h>

namespace folly {

template <class T>
class Future {
 public:
  typedef T value_type;

  // not copyable
  Future(Future const&) = delete;
  Future& operator=(Future const&) = delete;

  // movable
  Future(Future&&) noexcept;
  Future& operator=(Future&&) noexcept;

  /// Construct a Future from a value (perfect forwarding)
  template <class T2 = T, typename =
            typename std::enable_if<
              !isFuture<typename std::decay<T2>::type>::value>::type>
  /* implicit */ Future(T2&& val);

  template <class T2 = T, typename =
            typename std::enable_if<
              std::is_same<Unit, T2>::value>::type>
  Future();

  ~Future();

  /** Return the reference to result. Should not be called if !isReady().
    Will rethrow the exception if an exception has been
    captured.
    */
  typename std::add_lvalue_reference<T>::type
  value();
  typename std::add_lvalue_reference<const T>::type
  value() const;

  /// Returns an inactive Future which will call back on the other side of
  /// executor (when it is activated).
  ///
  /// NB remember that Futures activate when they destruct. This is good,
  /// it means that this will work:
  ///
  ///   f.via(e).then(a).then(b);
  ///
  /// a and b will execute in the same context (the far side of e), because
  /// the Future (temporary variable) created by via(e) does not call back
  /// until it destructs, which is after then(a) and then(b) have been wired
  /// up.
  ///
  /// But this is still racy:
  ///
  ///   f = f.via(e).then(a);
  ///   f.then(b);
  // The ref-qualifier allows for `this` to be moved out so we
  // don't get access-after-free situations in chaining.
  // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
  inline Future<T> via(
      Executor* executor,
      int8_t priority = Executor::MID_PRI) &&;

  /// This variant creates a new future, where the ref-qualifier && version
  /// moves `this` out. This one is less efficient but avoids confusing users
  /// when "return f.via(x);" fails.
  inline Future<T> via(
      Executor* executor,
      int8_t priority = Executor::MID_PRI) &;

  /** True when the result (or exception) is ready. */
  bool isReady() const;

  /// sugar for getTry().hasValue()
  bool hasValue();

  /// sugar for getTry().hasException()
  bool hasException();

  /** A reference to the Try of the value */
  Try<T>& getTry();

  /// If the promise has been fulfilled, return an Optional with the Try<T>.
  /// Otherwise return an empty Optional.
  /// Note that this moves the Try<T> out.
  Optional<Try<T>> poll();

  /// Block until the future is fulfilled. Returns the value (moved out), or
  /// throws the exception. The future must not already have a callback.
  T get();

  /// Block until the future is fulfilled, or until timed out. Returns the
  /// value (moved out), or throws the exception (which might be a TimedOut
  /// exception).
  T get(Duration dur);

  /// Call e->drive() repeatedly until the future is fulfilled. Examples
  /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
  /// value (moved out), or throws the exception.
  T getVia(DrivableExecutor* e);

  /// Unwraps the case of a Future<Future<T>> instance, and returns a simple
  /// Future<T> instance.
  template <class F = T>
  typename std::enable_if<isFuture<F>::value,
                          Future<typename isFuture<T>::Inner>>::type
  unwrap();

  /** When this Future has completed, execute func which is a function that
    takes one of:
      (const) Try<T>&&
      (const) Try<T>&
      (const) Try<T>
      (const) T&&
      (const) T&
      (const) T
      (void)

    Func shall return either another Future or a value.

    A Future for the return type of func is returned.

    Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });

    The Future given to the functor is ready, and the functor may call
    value(), which may rethrow if this has captured an exception. If func
    throws, the exception will be captured in the Future that is returned.
    */
  template <typename F, typename R = detail::callableResult<T, F>>
  typename R::Return then(F func) {
    typedef typename R::Arg Arguments;
    return thenImplementation<F, R>(std::move(func), Arguments());
  }

  /// Variant where func is an member function
  ///
  ///   struct Worker { R doWork(Try<T>); }
  ///
  ///   Worker *w;
  ///   Future<R> f2 = f1.then(&Worker::doWork, w);
  ///
  /// This is just sugar for
  ///
  ///   f1.then(std::bind(&Worker::doWork, w));
  template <typename R, typename Caller, typename... Args>
  Future<typename isFuture<R>::Inner>
  then(R(Caller::*func)(Args...), Caller *instance);

  /// Execute the callback via the given Executor. The executor doesn't stick.
  ///
  /// Contrast
  ///
  ///   f.via(x).then(b).then(c)
  ///
  /// with
  ///
  ///   f.then(x, b).then(c)
  ///
  /// In the former both b and c execute via x. In the latter, only b executes
  /// via x, and c executes via the same executor (if any) that f had.
  template <class Executor, class Arg, class... Args>
  auto then(Executor* x, Arg&& arg, Args&&... args)
    -> decltype(this->then(std::forward<Arg>(arg),
                           std::forward<Args>(args)...));

  /// Convenience method for ignoring the value and creating a Future<Unit>.
  /// Exceptions still propagate.
  Future<Unit> then();

  /// Set an error callback for this Future. The callback should take a single
  /// argument of the type that you want to catch, and should return a value of
  /// the same type as this Future, or a Future of that type (see overload
  /// below). For instance,
  ///
  /// makeFuture()
  ///   .then([] {
  ///     throw std::runtime_error("oh no!");
  ///     return 42;
  ///   })
  ///   .onError([] (std::runtime_error& e) {
  ///     LOG(INFO) << "std::runtime_error: " << e.what();
  ///     return -1; // or makeFuture<int>(-1)
  ///   });
  template <class F>
  typename std::enable_if<
    !detail::callableWith<F, exception_wrapper>::value &&
    !detail::Extract<F>::ReturnsFuture::value,
    Future<T>>::type
  onError(F&& func);

  /// Overload of onError where the error callback returns a Future<T>
  template <class F>
  typename std::enable_if<
    !detail::callableWith<F, exception_wrapper>::value &&
    detail::Extract<F>::ReturnsFuture::value,
    Future<T>>::type
  onError(F&& func);

  /// Overload of onError that takes exception_wrapper and returns Future<T>
  template <class F>
  typename std::enable_if<
    detail::callableWith<F, exception_wrapper>::value &&
    detail::Extract<F>::ReturnsFuture::value,
    Future<T>>::type
  onError(F&& func);

  /// Overload of onError that takes exception_wrapper and returns T
  template <class F>
  typename std::enable_if<
    detail::callableWith<F, exception_wrapper>::value &&
    !detail::Extract<F>::ReturnsFuture::value,
    Future<T>>::type
  onError(F&& func);

  /// func is like std::function<void()> and is executed unconditionally, and
  /// the value/exception is passed through to the resulting Future.
  /// func shouldn't throw, but if it does it will be captured and propagated,
  /// and discard any value/exception that this Future has obtained.
  template <class F>
  Future<T> ensure(F func);

  /// Like onError, but for timeouts. example:
  ///
  ///   Future<int> f = makeFuture<int>(42)
  ///     .delayed(long_time)
  ///     .onTimeout(short_time,
  ///       []() -> int{ return -1; });
  ///
  /// or perhaps
  ///
  ///   Future<int> f = makeFuture<int>(42)
  ///     .delayed(long_time)
  ///     .onTimeout(short_time,
  ///       []() { return makeFuture<int>(some_exception); });
  template <class F>
  Future<T> onTimeout(Duration, F&& func, Timekeeper* = nullptr);

  /// This is not the method you're looking for.
  ///
  /// This needs to be public because it's used by make* and when*, and it's
  /// not worth listing all those and their fancy template signatures as
  /// friends. But it's not for public consumption.
  template <class F>
  void setCallback_(F&& func);

  /// A Future's callback is executed when all three of these conditions have
  /// become true: it has a value (set by the Promise), it has a callback (set
  /// by then), and it is active (active by default).
  ///
  /// Inactive Futures will activate upon destruction.
  FOLLY_DEPRECATED("do not use") Future<T>& activate() & {
    core_->activate();
    return *this;
  }
  FOLLY_DEPRECATED("do not use") Future<T>& deactivate() & {
    core_->deactivate();
    return *this;
  }
  FOLLY_DEPRECATED("do not use") Future<T> activate() && {
    core_->activate();
    return std::move(*this);
  }
  FOLLY_DEPRECATED("do not use") Future<T> deactivate() && {
    core_->deactivate();
    return std::move(*this);
  }

  bool isActive() {
    return core_->isActive();
  }

  template <class E>
  void raise(E&& exception) {
    raise(make_exception_wrapper<typename std::remove_reference<E>::type>(
        std::move(exception)));
  }

  /// Raise an interrupt. If the promise holder has an interrupt
  /// handler it will be called and potentially stop asynchronous work from
  /// being done. This is advisory only - a promise holder may not set an
  /// interrupt handler, or may do anything including ignore. But, if you know
  /// your future supports this the most likely result is stopping or
  /// preventing the asynchronous operation (if in time), and the promise
  /// holder setting an exception on the future. (That may happen
  /// asynchronously, of course.)
  void raise(exception_wrapper interrupt);

  void cancel() {
    raise(FutureCancellation());
  }

  /// Throw TimedOut if this Future does not complete within the given
  /// duration from now. The optional Timeekeeper is as with futures::sleep().
  Future<T> within(Duration, Timekeeper* = nullptr);

  /// Throw the given exception if this Future does not complete within the
  /// given duration from now. The optional Timeekeeper is as with
  /// futures::sleep().
  template <class E>
  Future<T> within(Duration, E exception, Timekeeper* = nullptr);

  /// Delay the completion of this Future for at least this duration from
  /// now. The optional Timekeeper is as with futures::sleep().
  Future<T> delayed(Duration, Timekeeper* = nullptr);

  /// Block until this Future is complete. Returns a reference to this Future.
  Future<T>& wait() &;

  /// Overload of wait() for rvalue Futures
  Future<T>&& wait() &&;

  /// Block until this Future is complete or until the given Duration passes.
  /// Returns a reference to this Future
  Future<T>& wait(Duration) &;

  /// Overload of wait(Duration) for rvalue Futures
  Future<T>&& wait(Duration) &&;

  /// Call e->drive() repeatedly until the future is fulfilled. Examples
  /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
  /// reference to this Future so that you can chain calls if desired.
  /// value (moved out), or throws the exception.
  Future<T>& waitVia(DrivableExecutor* e) &;

  /// Overload of waitVia() for rvalue Futures
  Future<T>&& waitVia(DrivableExecutor* e) &&;

  /// If the value in this Future is equal to the given Future, when they have
  /// both completed, the value of the resulting Future<bool> will be true. It
  /// will be false otherwise (including when one or both Futures have an
  /// exception)
  Future<bool> willEqual(Future<T>&);

  /// predicate behaves like std::function<bool(T const&)>
  /// If the predicate does not obtain with the value, the result
  /// is a folly::PredicateDoesNotObtain exception
  template <class F>
  Future<T> filter(F predicate);

  /// Like reduce, but works on a Future<std::vector<T / Try<T>>>, for example
  /// the result of collect or collectAll
  template <class I, class F>
  Future<I> reduce(I&& initial, F&& func);

  /// Create a Future chain from a sequence of callbacks. i.e.
  ///
  ///   f.then(a).then(b).then(c)
  ///
  /// where f is a Future<A> and the result of the chain is a Future<D>
  /// becomes
  ///
  ///   f.thenMulti(a, b, c);
  template <class Callback, class... Callbacks>
  auto thenMulti(Callback&& fn, Callbacks&&... fns)
    -> decltype(this->then(std::forward<Callback>(fn)).
                      thenMulti(std::forward<Callbacks>(fns)...));

  // Nothing to see here, just thenMulti's base case
  template <class Callback>
  auto thenMulti(Callback&& fn)
    -> decltype(this->then(std::forward<Callback>(fn)));

  /// Create a Future chain from a sequence of callbacks. i.e.
  ///
  ///   f.via(executor).then(a).then(b).then(c).via(oldExecutor)
  ///
  /// where f is a Future<A> and the result of the chain is a Future<D>
  /// becomes
  ///
  ///   f.thenMultiWithExecutor(executor, a, b, c);
  template <class Callback, class... Callbacks>
  auto thenMultiWithExecutor(Executor* x, Callback&& fn, Callbacks&&... fns)
    -> decltype(this->then(std::forward<Callback>(fn)).
                      thenMulti(std::forward<Callbacks>(fns)...));

  // Nothing to see here, just thenMultiWithExecutor's base case
  template <class Callback>
  auto thenMultiWithExecutor(Executor* x, Callback&& fn)
    -> decltype(this->then(std::forward<Callback>(fn)));

  /// Discard a result, but propagate an exception.
  Future<Unit> unit() {
    return then([]{ return Unit{}; });
  }

 protected:
  typedef detail::Core<T>* corePtr;

  // shared core state object
  corePtr core_;

  explicit
  Future(corePtr obj) : core_(obj) {}

  void detach();

  void throwIfInvalid() const;

  friend class Promise<T>;
  template <class> friend class Future;

  template <class T2>
  friend Future<T2> makeFuture(Try<T2>&&);

  // Variant: returns a value
  // e.g. f.then([](Try<T> t){ return t.value(); });
  template <typename F, typename R, bool isTry, typename... Args>
  typename std::enable_if<!R::ReturnsFuture::value, typename R::Return>::type
  thenImplementation(F func, detail::argResult<isTry, F, Args...>);

  // Variant: returns a Future
  // e.g. f.then([](Try<T> t){ return makeFuture<T>(t); });
  template <typename F, typename R, bool isTry, typename... Args>
  typename std::enable_if<R::ReturnsFuture::value, typename R::Return>::type
  thenImplementation(F func, detail::argResult<isTry, F, Args...>);

  Executor* getExecutor() { return core_->getExecutor(); }
  void setExecutor(Executor* x, int8_t priority = Executor::MID_PRI) {
    core_->setExecutor(x, priority);
  }
};

} // folly

#include <folly/futures/Future-inl.h>


text:
/*
 * User: anna
 * Date: 11-Nov-2008
 */
package org.jetbrains.idea.eclipse.conversion;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.projectRoots.JavaSdkType;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.eclipse.ConversionException;
import org.jetbrains.idea.eclipse.EclipseXml;
import org.jetbrains.idea.eclipse.IdeaXml;
import org.jetbrains.idea.eclipse.EclipseModuleManager;
import org.jetbrains.idea.eclipse.config.EclipseModuleManagerImpl;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class EclipseClasspathWriter {
  private static final Logger LOG = Logger.getInstance("#" + EclipseClasspathWriter.class.getName());
  private final ModuleRootModel myModel;
  private final Map<String, Element> myOldEntries = new HashMap<String, Element>();

  public EclipseClasspathWriter(final ModuleRootModel model) {
    myModel = model;
  }

  public void writeClasspath(Element classpathElement, @Nullable Element oldRoot) throws ConversionException {
    if (oldRoot != null) {
      for (Object o : oldRoot.getChildren(EclipseXml.CLASSPATHENTRY_TAG)) {
        final Element oldChild = (Element)o;
        final String oldKind = oldChild.getAttributeValue(EclipseXml.KIND_ATTR);
        final String oldPath = oldChild.getAttributeValue(EclipseXml.PATH_ATTR);
        myOldEntries.put(oldKind + getJREKey(oldPath), oldChild);
      }
    }

    for (OrderEntry orderEntry : myModel.getOrderEntries()) {
      createClasspathEntry(orderEntry, classpathElement);
    }

    @NonNls String outputPath = "bin";
    final String compilerOutputUrl = myModel.getModuleExtension(CompilerModuleExtension.class).getCompilerOutputUrl();
    final EclipseModuleManager eclipseModuleManager = EclipseModuleManagerImpl.getInstance(myModel.getModule());
    final String linkedPath = eclipseModuleManager.getEclipseLinkedVarPath(compilerOutputUrl);
    if (linkedPath != null) {
      outputPath = linkedPath;
    } else {
      final VirtualFile contentRoot = EPathUtil.getContentRoot(myModel);
      final VirtualFile output = myModel.getModuleExtension(CompilerModuleExtension.class).getCompilerOutputPath();
      if (contentRoot != null && output != null && VfsUtil.isAncestor(contentRoot, output, false)) {
        outputPath = EPathUtil.collapse2EclipsePath(output.getUrl(), myModel);
      }
      else if (output == null && compilerOutputUrl != null) {
        outputPath = EPathUtil.collapse2EclipsePath(compilerOutputUrl, myModel);
      }
    }
    for (String support : eclipseModuleManager.getUsedCons()) {
      final Integer place = eclipseModuleManager.getSrcPlace(support);
      addOrderEntry(EclipseXml.CON_KIND, support, classpathElement, place != null ? place.intValue() : -1);
    }
    final Element orderEntry = addOrderEntry(EclipseXml.OUTPUT_KIND, outputPath, classpathElement);
    setAttributeIfAbsent(orderEntry, EclipseXml.PATH_ATTR, EclipseXml.BIN_DIR);
  }

  private void createClasspathEntry(OrderEntry entry, Element classpathRoot) throws ConversionException {
    final EclipseModuleManager eclipseModuleManager = EclipseModuleManagerImpl.getInstance(entry.getOwnerModule());
    if (entry instanceof ModuleSourceOrderEntry) {
      final boolean shouldPlaceSeparately =
        eclipseModuleManager.isExpectedModuleSourcePlace(Arrays.binarySearch(myModel.getOrderEntries(), entry));
      final ContentEntry[] entries = myModel.getContentEntries();
      for (final ContentEntry contentEntry : entries) {
        final VirtualFile contentRoot = contentEntry.getFile();
        for (SourceFolder sourceFolder : contentEntry.getSourceFolders()) {
          final String srcUrl = sourceFolder.getUrl();
          String relativePath = EPathUtil.collapse2EclipsePath(srcUrl, myModel);
          if (!Comparing.equal(contentRoot, EPathUtil.getContentRoot(myModel))) {
            final String linkedPath = EclipseModuleManagerImpl.getInstance(entry.getOwnerModule()).getEclipseLinkedSrcVariablePath(srcUrl);
            if (linkedPath != null) {
              relativePath = linkedPath;
            }
          }
          final Integer idx = eclipseModuleManager.getSrcPlace(srcUrl);
          addOrderEntry(EclipseXml.SRC_KIND, relativePath, classpathRoot, shouldPlaceSeparately && idx != null ? idx.intValue() : -1);
        }
      }
    }
    else if (entry instanceof ModuleOrderEntry) {
      Element orderEntry = addOrderEntry(EclipseXml.SRC_KIND, "/" + ((ModuleOrderEntry)entry).getModuleName(), classpathRoot);
      setAttributeIfAbsent(orderEntry, EclipseXml.COMBINEACCESSRULES_ATTR, EclipseXml.FALSE_VALUE);
      setExported(orderEntry, ((ExportableOrderEntry)entry));
    }
    else if (entry instanceof LibraryOrderEntry) {
      final LibraryOrderEntry libraryOrderEntry = (LibraryOrderEntry)entry;
      final String libraryName = libraryOrderEntry.getLibraryName();
      if (libraryOrderEntry.isModuleLevel()) {
        final String[] files = libraryOrderEntry.getRootUrls(OrderRootType.CLASSES);
        if (files.length > 0) {
          if (libraryName != null &&
              libraryName.contains(IdeaXml.JUNIT) &&
              Comparing.strEqual(files[0], EclipseClasspathReader.getJunitClsUrl(libraryName.contains("4")))) {
            final Element orderEntry =
              addOrderEntry(EclipseXml.CON_KIND, EclipseXml.JUNIT_CONTAINER + "/" + libraryName.substring(IdeaXml.JUNIT.length()),
                            classpathRoot);
            setExported(orderEntry, libraryOrderEntry);
          }
          else {
            boolean newVarLibrary = false;

            boolean link = false;
            String eclipseVariablePath = eclipseModuleManager.getEclipseVariablePath(files[0]);
            if (eclipseVariablePath == null) {
              eclipseVariablePath = eclipseModuleManager.getEclipseLinkedVarPath(files[0]);
              link = eclipseVariablePath != null;
            }

            if (eclipseVariablePath == null && !eclipseModuleManager.isEclipseLibUrl(files[0])) { //new library was added
              newVarLibrary = true;
              eclipseVariablePath = EPathUtil.collapse2EclipseVariabledPath(libraryOrderEntry, OrderRootType.CLASSES);
            }
            Element orderEntry;
            if (eclipseVariablePath != null) {
              orderEntry = addOrderEntry(link ? EclipseXml.LIB_KIND : EclipseXml.VAR_KIND, eclipseVariablePath, classpathRoot);
            }
            else {
              LOG.assertTrue(!StringUtil.isEmptyOrSpaces(files[0]), "Library: " + libraryName);
              orderEntry = addOrderEntry(EclipseXml.LIB_KIND, EPathUtil.collapse2EclipsePath(files[0], myModel), classpathRoot);
            }

            final String srcRelativePath;
            String eclipseSrcVariablePath = null;

            boolean addSrcRoots = true;
            final String[] srcFiles = libraryOrderEntry.getRootUrls(OrderRootType.SOURCES);
            if (srcFiles.length == 0) {
              srcRelativePath = null;
            }
            else {
              final String srcFile = srcFiles[0];
              srcRelativePath = EPathUtil.collapse2EclipsePath(srcFile, myModel);
              if (eclipseVariablePath != null) {
                eclipseSrcVariablePath = eclipseModuleManager.getEclipseSrcVariablePath(srcFile);
                if (eclipseSrcVariablePath == null) {
                  eclipseSrcVariablePath = eclipseModuleManager.getEclipseLinkedSrcVariablePath(srcFile);
                }
                if (eclipseSrcVariablePath == null) {
                  eclipseSrcVariablePath = EPathUtil.collapse2EclipseVariabledPath(libraryOrderEntry, OrderRootType.SOURCES);
                  if (eclipseSrcVariablePath != null) {
                    eclipseSrcVariablePath = "/" + eclipseSrcVariablePath;
                  } else {
                    if (newVarLibrary) { //new library which cannot be replaced with vars
                      orderEntry.detach();
                      orderEntry = addOrderEntry(EclipseXml.LIB_KIND, EPathUtil.collapse2EclipsePath(files[0], myModel), classpathRoot);
                    }
                    else {
                      LOG.info("Added root " + srcRelativePath + " (in existing var library) can't be replaced with any variable; src roots placed in .eml only");
                      addSrcRoots = false;
                    }
                  }
                }
              }
            }
            setOrRemoveAttribute(orderEntry, EclipseXml.SOURCEPATH_ATTR, addSrcRoots ? (eclipseSrcVariablePath != null ? eclipseSrcVariablePath : srcRelativePath) : null);

            EJavadocUtil.setupJavadocAttributes(orderEntry, libraryOrderEntry, myModel);
            setExported(orderEntry, libraryOrderEntry);
          }
        }
      }
      else {
        final Element orderEntry;
        if (eclipseModuleManager.getUnknownCons().contains(libraryName)) {
          orderEntry = addOrderEntry(EclipseXml.CON_KIND, libraryName, classpathRoot);
        } else if (Comparing.strEqual(libraryName, IdeaXml.ECLIPSE_LIBRARY)) {
          orderEntry = addOrderEntry(EclipseXml.CON_KIND, EclipseXml.ECLIPSE_PLATFORM, classpathRoot);
        }
        else {
          orderEntry = addOrderEntry(EclipseXml.CON_KIND, EclipseXml.USER_LIBRARY + "/" + libraryName, classpathRoot);
        }
        setExported(orderEntry, libraryOrderEntry);
      }
    }
    else if (entry instanceof JdkOrderEntry) {
      if (entry instanceof InheritedJdkOrderEntry) {
        if (!EclipseModuleManagerImpl.getInstance(entry.getOwnerModule()).isForceConfigureJDK()) {
          addOrderEntry(EclipseXml.CON_KIND, EclipseXml.JRE_CONTAINER, classpathRoot);
        }
      }
      else {
        final Sdk jdk = ((JdkOrderEntry)entry).getJdk();
        String jdkLink;
        if (jdk == null) {
          jdkLink = EclipseXml.JRE_CONTAINER;
        }
        else {
          jdkLink = EclipseXml.JRE_CONTAINER;
          if (jdk.getSdkType() instanceof JavaSdkType) {
            jdkLink += EclipseXml.JAVA_SDK_TYPE;
          }
          jdkLink += "/" + jdk.getName();
        }
        addOrderEntry(EclipseXml.CON_KIND, jdkLink, classpathRoot);
      }
    }
    else {
      throw new ConversionException("Unknown EclipseProjectModel.ClasspathEntry: " + entry.getClass());
    }
  }

  private Element addOrderEntry(String kind, String path, Element classpathRoot) {
    return addOrderEntry(kind, path, classpathRoot, -1);
  }

  private Element addOrderEntry(String kind, String path, Element classpathRoot, int idx) {
    final Element element = myOldEntries.get(kind + getJREKey(path));
    if (element != null){
      final Element clonedElement = (Element)element.clone();
      if (idx == -1 || idx >= classpathRoot.getContentSize()) {
        classpathRoot.addContent(clonedElement);
      } else {
        classpathRoot.addContent(idx, clonedElement);
      }
      return clonedElement;
    }
    Element orderEntry = new Element(EclipseXml.CLASSPATHENTRY_TAG);
    orderEntry.setAttribute(EclipseXml.KIND_ATTR, kind);
    if (path != null) {
      orderEntry.setAttribute(EclipseXml.PATH_ATTR, path);
    }
    if (idx == -1) {
      classpathRoot.addContent(orderEntry);
    } else {
      classpathRoot.addContent(idx, orderEntry);
    }
    return orderEntry;
  }

  private static String getJREKey(String path) {
    return path.startsWith(EclipseXml.JRE_CONTAINER) ? EclipseXml.JRE_CONTAINER : path;
  }

  private static void setExported(Element orderEntry, ExportableOrderEntry dependency) {
    setOrRemoveAttribute(orderEntry, EclipseXml.EXPORTED_ATTR, dependency.isExported() ? EclipseXml.TRUE_VALUE : null);
  }

  private static void setOrRemoveAttribute(Element element, String name, String value) {
    if (value != null) {
      element.setAttribute(name, value);
    }
    else {
      element.removeAttribute(name);
    }
  }

  private static void setAttributeIfAbsent(Element element, String name, String value) {
    if (element.getAttribute(name) == null) {
      element.setAttribute(name, value);
    }
  }

}

redpajama_set_name: RedPajamaGithub


text:
/**
 *
 */
package com.weibo.lodil;

import java.util.Collection;
import java.util.Map;

/**
 * key - map/hash dictionary interface
 *
 * @author tangfulin
 *
 */
public interface HashDictionary extends BasicDictionary {

	public DictValue hget(DictKey key, DictHashField field);

	public Map<DictHashField, DictValue> hgetAll(DictKey key);

	public Map<DictHashField, DictValue> hmget(DictKey key, Collection<DictHashField> fields);

	public Collection<DictKey> hkeys(DictKey key);

	public Collection<DictHashField> hvals(DictKey key);

	/**
	 * XXX redis will return 0 for add new field and value, 1 for update old
	 * field's value
	 *
	 * @param key
	 * @param field
	 * @param value
	 * @return true for succ, false otherwise
	 */
	public boolean hset(DictKey key, DictHashField field, DictValue value);

	public boolean hmset(DictKey key, Map<DictHashField, DictValue> values);

	public boolean hexist(DictKey key, DictHashField field);

	/**
	 *
	 * @param key
	 * @param field
	 * @return true if and only if all fields deleted suc, false otherwise XXX
	 *         if deleted parts fields and return false, it will *NOT* rollback!
	 */
	public boolean hdel(DictKey key, DictHashField... field);

	public long hlen(DictKey key);

	/**
	 * deal with numbers
	 *
	 * @param key
	 * @return
	 */
	public long hincr(DictKey key, DictHashField field);

	public long hdecr(DictKey key, DictHashField field);

	public long hincrBy(DictKey key, DictHashField field, long num);

	public long hdecrBy(DictKey key, DictHashField field, long num);

}


text:
cd "D:\Visual Studio Projects\C++\DarkBasic\Physics\DBProPhysicsMaster\Release\DaveMilton"
del DBProPhysics.zip
pkzip DBProPhysics.zip DBProPhysicsMaster.dll "C:\Program Files\Dark Basic Software\Dark Basic Pro\Compiler\plugins-user\PhysicsMainLang.loc" "C:\Program Files\Dark Basic Software\Help files\PhysicsHelp.chm"

cd "D:\Visual Studio Projects\C++\DarkBasic\Physics\DBProPhysicsMaster\Release\DavidSmith"
del DBProPhysics.zip
pkzip DBProPhysics.zip DBProPhysicsMaster.dll "C:\Program Files\Dark Basic Software\Dark Basic Pro\Compiler\plugins-user\PhysicsMainLang.loc" "C:\Program Files\Dark Basic Software\Help files\PhysicsHelp.chm"

cd "D:\Visual Studio Projects\C++\DarkBasic\Physics\DBProPhysicsMaster\Release\IanMatrix"
del DBProPhysics.zip
pkzip DBProPhysics.zip DBProPhysicsMaster.dll "C:\Program Files\Dark Basic Software\Dark Basic Pro\Compiler\plugins-user\PhysicsMainLang.loc" "C:\Program Files\Dark Basic Software\Help files\PhysicsHelp.chm"

cd "D:\Visual Studio Projects\C++\DarkBasic\Physics\DBProPhysicsMaster\Release\LeeBamber"
del DBProPhysics.zip
pkzip DBProPhysics.zip DBProPhysicsMaster.dll "C:\Program Files\Dark Basic Software\Dark Basic Pro\Compiler\plugins-user\PhysicsMainLang.loc" "C:\Program Files\Dark Basic Software\Help files\PhysicsHelp.chm"

cd "D:\Visual Studio Projects\C++\DarkBasic\Physics\DBProPhysicsMaster\Release\MikeJohnson"
del DBProPhysics.zip
pkzip DBProPhysics.zip DBProPhysicsMaster.dll "C:\Program Files\Dark Basic Software\Dark Basic Pro\Compiler\plugins-user\PhysicsMainLang.loc" "C:\Program Files\Dark Basic Software\Help files\PhysicsHelp.chm"

cd "D:\Visual Studio Projects\C++\DarkBasic\Physics\DBProPhysicsMaster\Release\NickKingsley"
del DBProPhysics.zip
pkzip DBProPhysics.zip DBProPhysicsMaster.dll "C:\Program Files\Dark Basic Software\Dark Basic Pro\Compiler\plugins-user\PhysicsMainLang.loc" "C:\Program Files\Dark Basic Software\Help files\PhysicsHelp.chm"

cd "D:\Visual Studio Projects\C++\DarkBasic\Physics\DBProPhysicsMaster\Release\RichDavey"
del DBProPhysics.zip
pkzip DBProPhysics.zip DBProPhysicsMaster.dll "C:\Program Files\Dark Basic Software\Dark Basic Pro\Compiler\plugins-user\PhysicsMainLang.loc" "C:\Program Files\Dark Basic Software\Help files\PhysicsHelp.chm"

cd "D:\Visual Studio Projects\C++\DarkBasic\Physics\DBProPhysicsMaster\Release\RickVanner"
del DBProPhysics.zip
pkzip DBProPhysics.zip DBProPhysicsMaster.dll "C:\Program Files\Dark Basic Software\Dark Basic Pro\Compiler\plugins-user\PhysicsMainLang.loc" "C:\Program Files\Dark Basic Software\Help files\PhysicsHelp.chm"

cd "D:\Visual Studio Projects\C++\DarkBasic\Physics\DBProPhysicsMaster\Release\RobKnight"
del DBProPhysics.zip
pkzip DBProPhysics.zip DBProPhysicsMaster.dll "C:\Program Files\Dark Basic Software\Dark Basic Pro\Compiler\plugins-user\PhysicsMainLang.loc" "C:\Program Files\Dark Basic Software\Help files\PhysicsHelp.chm"

cd "D:\Visual Studio Projects\C++\DarkBasic\Physics\DBProPhysicsMaster\Release\TimStone"
del DBProPhysics.zip
pkzip DBProPhysics.zip DBProPhysicsMaster.dll "C:\Program Files\Dark Basic Software\Dark Basic Pro\Compiler\plugins-user\PhysicsMainLang.loc" "C:\Program Files\Dark Basic Software\Help files\PhysicsHelp.chm"

cd "D:\Visual Studio Projects\C++\DarkBasic\Physics\DBProPhysicsMaster"

ftp -s:CopyToServer.ftp r39.easily.co.uk


text:
/**
 * Controllers for the tree module.
 *
 * @author Albert Smit
 */
package nl.tudelft.lifetiles.tree.controller;


text:
<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"
    android:background="#e0e0e0"
    tools:context="com.example.androidapplication.contacts.SplashActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Contacts"
        android:textAlignment="center"
        android:textStyle="bold"
        android:id="@+id/textViewAppName1"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp"
        android:textSize="30dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Directory"
        android:textAlignment="center"
        android:textStyle="bold"
        android:textSize="30dp"
        android:layout_marginTop="5dp"
        android:id="@+id/textViewAppName2"
        android:layout_below="@+id/textViewAppName1"
        android:layout_centerHorizontal="true" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageViewAppImg"
        android:src="@drawable/splashicon"
        android:layout_centerVertical="true"
        android:layout_alignStart="@+id/textViewAppName2" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="All Rigths Reserved"
        android:id="@+id/textViewCopyRight"
        android:layout_alignParentBottom="true"
        android:layout_alignEnd="@+id/imageViewAppImg" />
</RelativeLayout>


text:
module.exports =
cmd = atom.config.get('Repl.gdb')
prompt = ""
args = []
endSequence = '\n'


text:
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-unsafe-call */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */

// See https://www.gatsbyjs.com/docs/how-to/testing/unit-testing/#setting-up-your-environment

global.___loader = {
	enqueue: jest.fn()
};


text:
package org.apache.flink.table.runtime.operators.join.lookup;

import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.api.common.typeutils.base.ListSerializer;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.core.memory.MemorySegmentFactory;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.data.binary.BinaryRowData;
import org.apache.flink.table.data.util.RowDataUtil;
import org.apache.flink.table.runtime.collector.ListenableCollector;
import org.apache.flink.types.RowKind;
import org.apache.flink.util.Collector;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * The lookup join handler which holds a {@link LookupJoinRunner} to process lookup for insert or
 * update_after record and directly process delete and update_before record via local state.
 */
public class KeyedLookupJoinWrapper extends KeyedProcessFunction<RowData, RowData, RowData> {

    private static final long serialVersionUID = 1L;
    private static final Logger LOG = LoggerFactory.getLogger(KeyedLookupJoinWrapper.class);
    private static final String STATE_CLEARED_WARN_MSG =
            "The state is cleared because of state ttl. "
                    + "This will result in incorrect result. You can increase the state ttl to avoid this.";

    private final LookupJoinRunner lookupJoinRunner;
    private final StateTtlConfig ttlConfig;
    private final TypeSerializer<RowData> serializer;
    private final boolean lookupKeyContainsPrimaryKey;

    // TODO to be unified by FLINK-24666
    private final boolean lenient = true;
    private transient BinaryRowData emptyRow;
    // for which !lookupKeyContainsPrimaryKey
    private transient ValueState<List<RowData>> state;

    // for which lookupKeyContainsPrimaryKey
    private transient ValueState<RowData> uniqueState;

    private transient FetchedRecordListener collectListener;

    public KeyedLookupJoinWrapper(
            LookupJoinRunner lookupJoinRunner,
            StateTtlConfig ttlConfig,
            TypeSerializer<RowData> serializer,
            boolean lookupKeyContainsPrimaryKey) {
        this.lookupJoinRunner = lookupJoinRunner;
        this.ttlConfig = ttlConfig;
        this.serializer = serializer;
        this.lookupKeyContainsPrimaryKey = lookupKeyContainsPrimaryKey;
    }

    @Override
    public void open(Configuration parameters) throws Exception {
        super.open(parameters);
        lookupJoinRunner.setRuntimeContext(getRuntimeContext());
        lookupJoinRunner.open(parameters);

        if (lookupKeyContainsPrimaryKey) {
            ValueStateDescriptor<RowData> valueStateDescriptor =
                    new ValueStateDescriptor<>("unique-value", serializer);
            if (ttlConfig.isEnabled()) {
                valueStateDescriptor.enableTimeToLive(ttlConfig);
            }
            uniqueState = getRuntimeContext().getState(valueStateDescriptor);
        } else {
            ValueStateDescriptor<List<RowData>> valueStateDescriptor =
                    new ValueStateDescriptor<>("values", new ListSerializer<>(serializer));
            state = getRuntimeContext().getState(valueStateDescriptor);
            if (ttlConfig.isEnabled()) {
                valueStateDescriptor.enableTimeToLive(ttlConfig);
            }
        }
        emptyRow = initEmptyRow(lookupJoinRunner.tableFieldsCount);
        collectListener = new FetchedRecordListener();
        lookupJoinRunner.collector.setCollectListener(collectListener);
    }

    private BinaryRowData initEmptyRow(int arity) {
        BinaryRowData emptyRow = new BinaryRowData(arity);
        int size = emptyRow.getFixedLengthPartSize();
        byte[] bytes = new byte[size];
        emptyRow.pointTo(MemorySegmentFactory.wrap(bytes), 0, size);
        for (int index = 0; index < arity; index++) {
            emptyRow.setNullAt(index);
        }
        return emptyRow;
    }

    @Override
    public void processElement(
            RowData in,
            KeyedProcessFunction<RowData, RowData, RowData>.Context ctx,
            Collector<RowData> out)
            throws Exception {

        lookupJoinRunner.prepareCollector(in, out);
        collectListener.reset();

        // do lookup for acc msg
        if (RowDataUtil.isAccumulateMsg(in)) {
            // clear local state first
            deleteState();

            // fetcher has copied the input field when object reuse is enabled
            lookupJoinRunner.doFetch(in);

            // update state will empty row if lookup miss
            if (!collectListener.collected) {
                updateState(emptyRow);
            }

            lookupJoinRunner.padNullForLeftJoin(in, out);
        } else {
            // do state access for non-acc msg
            if (lookupKeyContainsPrimaryKey) {
                RowData rightRow = uniqueState.value();
                // should distinguish null from empty(lookup miss)
                if (null == rightRow) {
                    stateStaledErrorHandle(in, out);
                } else {
                    collectDeleteRow(in, rightRow, out);
                }
            } else {
                List<RowData> rightRows = state.value();
                if (null == rightRows) {
                    stateStaledErrorHandle(in, out);
                } else {
                    for (RowData row : rightRows) {
                        collectDeleteRow(in, row, out);
                    }
                }
            }
            // clear state at last
            deleteState();
        }
    }

    private void collectDeleteRow(RowData in, RowData right, Collector<RowData> out) {
        lookupJoinRunner.outRow.replace(in, right);
        lookupJoinRunner.outRow.setRowKind(RowKind.DELETE);
        out.collect(lookupJoinRunner.outRow);
    }

    @Override
    public void close() throws Exception {
        lookupJoinRunner.close();
        super.close();
    }

    void deleteState() {
        if (lookupKeyContainsPrimaryKey) {
            uniqueState.clear();
        } else {
            state.clear();
        }
    }

    void updateState(RowData row) {
        try {
            if (lookupKeyContainsPrimaryKey) {
                uniqueState.update(row);
            } else {
                // This can be optimized if lookupFunction can be unified collecting a collection of
                // rows instead of collecting each row
                List<RowData> rows = state.value();
                if (null == rows) {
                    rows = new ArrayList<>();
                }
                rows.add(row);
                state.update(rows);
            }
        } catch (IOException e) {
            throw new RuntimeException("Failed to update state!", e);
        }
    }

    class FetchedRecordListener implements ListenableCollector.CollectListener<RowData> {
        boolean collected;

        void reset() {
            collected = false;
        }

        @Override
        public void onCollect(RowData record) {
            collected = true;
            if (null == record) {
                updateState(emptyRow);
            } else {
                updateState(record);
            }
        }
    }

    private void stateStaledErrorHandle(RowData in, Collector out) {
        if (lenient) {
            LOG.warn(STATE_CLEARED_WARN_MSG);
            if (lookupJoinRunner.isLeftOuterJoin) {
                lookupJoinRunner.padNullForLeftJoin(in, out);
            }
        } else {
            throw new RuntimeException(STATE_CLEARED_WARN_MSG);
        }
    }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Botanicheskie Materialy 15: 133 (1962)

#### Original name
Polyporus peckianus Cooke, 1879

### Remarks
null


text:
$(function () {

  if ($('body.momentum-cms-admin-menus-edit, body.momentum-cms-admin-menus-update, body.momentum-cms-admin-menus-new, body.momentum-cms-admin-menus-create').length) {

    var ol = $('ol.ui-nested-sortable');

    function bind_ui_nested_sortable() {
      ol.nestedSortable({
        forcePlaceholderSize: true,
        handle: 'div',
        helper: 'clone',
        items: 'li',
        opacity: .6,
        placeholder: 'placeholder',
        revert: 250,
        tabSize: 25,
        tolerance: 'pointer',
        toleranceElement: '> div'
      });
    }

    function createLiNode(data) {
      var display = $("<div />").html(data.label);
      var li = $("<li />")
        .html(display)
        .attr('data-label', data.label)
        .attr('data-linkable-type', data.linkable_type)
        .attr('data-linkable-id', data.linkable_id)
        .attr('id', "list-" + data.id.valueOf());
      return li;
    }

    function buildUnsavedList(json, list) {
      if ($.isArray(json)) {
        $.each(json, function (key, value) {
          buildUnsavedList(value, list);
        });
        return;
      }
      if (json) {
        var li = createLiNode(json);

        if (json.children && json.children.length) {
          var sublist = $("<ol/>");
          buildUnsavedList(json.children, sublist)
          li.append(sublist);
        }
        list.append(li)
      }
    }

    // New list....
    if (ol.find('li').length == 0) {
      var menu_json = $('.cms-admin-site-menus-json').val()
      if (menu_json) {
        var json = JSON.parse(menu_json);
        buildUnsavedList(json, ol);
      }
    }

    bind_ui_nested_sortable();

    $('.momentum-cms-pages-select').select2({
      placeholder: "Search for a Page",
      minimumInputLength: 1,
      ajax: {
        url: $('.momentum-cms-pages-select').attr('data-remote-url'),
        data: function (term, page) {
          return {
            q: term,
            page_limit: 10
          };
        },
        results: function (data, page) { // parse the results into the format expected by Select2.
          var results = [];
          $(data).each(function (index, element) {
            results.push({id: element.id, text: element.label, label: element.label, type: 'MomentumCms::Page' })
          });
          return {results: results};
        }
      }
    });

    $('.momentum-cms-menu-add-page').click(function (e) {
      e.preventDefault();

      var data = $('.momentum-cms-pages-select').select2('data');
      if (data) {
        var li = createLiNode(data);
        $('ol.ui-nested-sortable').append(li);
      }
    });

    $('.momentum-cms-menu-submit').click(function () {
      var hierarchy = $('ol.ui-nested-sortable').nestedSortable('toHierarchy', {startDepthCount: 0});
      $('.cms-admin-site-menus-json').val(JSON.stringify(hierarchy))
    });
  }

});


text:
/*!
 * \brief Provides implementations for all the functions that this library provides
 *
 * I'd like for the functions in this file to be a facade sort of thing, but idk if that will happen. These functions
 * look a lot like simple passthroughs.
 *
 * Although, many of them do things to convert from C-style things to C++-style things, so that's cool I guess
 *
 * The function in this file simply set data. Data is copied out of Minecraft objects. This might be a bit slow, but I
 * don't want to save a pointer that gets re-allocated by the JVM. I don't trust it enough (although maybe I should?)
 *
 * \author David
 */

#include "glad/glad.h"
#include "nova.h"
#include "../utils/export.h"
#include "../render/nova_renderer.h"
#include "../render/objects/textures/texture_manager.h"
#include "../data_loading/settings.h"
#include "../input/InputHandler.h"
using namespace nova;

#define TEXTURE_MANAGER nova_renderer::instance->get_texture_manager()
#define INPUT_HANDLER nova_renderer::instance->get_input_handler()
// runs in thread 5

NOVA_API void initialize() {
    nova_renderer::init();
}

NOVA_API void add_texture(mc_atlas_texture & texture, int texture_type) {
    TEXTURE_MANAGER.add_texture(
            texture,
            nova::texture_manager::texture_type::all_values()[texture_type]
    );
}

NOVA_API void reset_texture_manager() {
    TEXTURE_MANAGER.reset();
}

NOVA_API void add_texture_location(mc_texture_atlas_location location) {
    TEXTURE_MANAGER.add_texture_location(location);
}

NOVA_API int get_max_texture_size() {
    return TEXTURE_MANAGER.get_max_texture_size();
}

NOVA_API void execute_frame() {
    nova_renderer::instance->render_frame();
}

NOVA_API bool should_close() {
    return nova_renderer::instance->should_end();
}

NOVA_API void send_change_gui_screen_command(mc_set_gui_screen_command * set_gui_screen) {
    nova_renderer::instance->get_mesh_store().add_gui_geometry(set_gui_screen->screen);
}

NOVA_API void set_string_setting(const char * setting_name, const char * setting_value) {
    settings& settings = nova_renderer::instance->get_render_settings();
    settings.get_options()[setting_name] = setting_value;
    settings.update_config_changed();
}

NOVA_API struct mouse_button_event  get_next_mouse_button_event() {
	return INPUT_HANDLER.dequeue_mouse_button_event();
}

NOVA_API struct mouse_position_event  get_next_mouse_position_event() {
	return INPUT_HANDLER.dequeue_mouse_position_event();
}

NOVA_API struct key_press_event get_next_key_press_event()
{
	return INPUT_HANDLER.dequeue_key_press_event();
}

NOVA_API struct key_char_event get_next_key_char_event()
{
	return  INPUT_HANDLER.dequeue_key_char_event();
}


text:
package org.conqat.engine.graph.filters;

import java.util.HashSet;
import java.util.Set;

import org.conqat.engine.commons.ConQATPipelineProcessorBase;
import org.conqat.engine.graph.nodes.ConQATGraph;
import edu.uci.ics.jung.graph.impl.DirectedSparseEdge;

/**
 * Base class for filters that remove edges from {@link ConQATGraph}s.
 *
 * @author juergens
 * @author $Author: deissenb $
 * @version $Rev: 35147 $
 * @ConQAT.Rating GREEN Hash: 6F60D62248940009DFB5044146E1320E
 */
public abstract class EdgeFilterBase extends
		ConQATPipelineProcessorBase<ConQATGraph> {

	/**
	 * Applies the filter criteria provided by the template method
	 * {@link #isFiltered(DirectedSparseEdge)} to each edge in the graph.
	 */
	@Override
	protected void processInput(ConQATGraph graph) {
		// copy edge set as we remove edges
		Set<DirectedSparseEdge> edges = new HashSet<DirectedSparseEdge>(graph
				.getEdges());
		for (DirectedSparseEdge edge : edges) {
			if (isFiltered(edge)) {
				graph.getGraph().removeEdge(edge);
			}
		}
	}

	/**
	 * Template method that allows subclasses to provide filter criteria.
	 * <p>
	 * If this returns true, edge will be removed from the graph.
	 */
	protected abstract boolean isFiltered(DirectedSparseEdge edge);

}


text:
{-# LANGUAGE RecordWildCards #-}

module Main where

import Control.Monad
import Control.Monad.Primitive
import qualified Crypto.Hash.SHA1 as SHA1
import qualified Data.ByteString.Lazy as B
import qualified Data.Vector as V
import Data.Word
import System.Random.MWC

import NW.Random

main :: IO ()
main = do
	mapM_ warmupShow
		[ SeedEmpty
		, SeedManual [1..255]

		-- Different than [1..255], because we have 1 more value that gets read
		-- into the state.
		, SeedManual [1..256]

		-- Same as [1..256], because length is not 258, and first 256 values are
		-- the same.
		, SeedManual [1..257]

		-- Different than [1..256], because there are exactly 258 values.
		, SeedManual [1..258]

		-- Same as [1..256], because length is not 258, and first 256 values are
		-- the same.
		, SeedManual [1..259]
		, SeedToday
		]
	where
	warmupShow seed = do
		rng <- mkGen seed
		n <- warmup 100000 rng
		putStrLn $ show n
		putStrLn . show =<< roll 10 rng


text:
using System;

namespace Earth
{
    using System.Threading;
    using System.Threading.Tasks;

    using Messages.Events;

    using NServiceBus;

    public class WarehouseRaid : IWantToRunWhenBusStartsAndStops
    {
        private CancellationTokenSource tokenSource = new CancellationTokenSource();

        private Task task;

        public IBus Bus { get; set; }

        public void Start()
        {
            CancellationToken cancellationToken = this.tokenSource.Token;

            this.task = Task.Factory.StartNew(
                () =>
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        int numberOfOfficers = 1;

                        while (!cancellationToken.IsCancellationRequested)
                        {
                            Guid identification = Guid.NewGuid();

                            var policeOfficerDied = this.Bus.CreateInstance<PoliceOfficerDied>(
                                m =>
                                    {
                                        m.Identification = identification;
                                        m.Name = string.Format("Nick Walker the {0}th", numberOfOfficers++);
                                    });
                            this.Bus.Publish(policeOfficerDied);

                            this.Bus.Defer(TimeSpan.FromSeconds(10), policeOfficerDied);

                            cancellationToken.ThrowIfCancellationRequested();

                            Thread.Sleep(TimeSpan.FromSeconds(5));
                        }
                    },
                cancellationToken);
        }

        public void Stop()
        {
            this.tokenSource.Cancel();

            try
            {
                this.task.Wait();
            }
            catch (AggregateException exception)
            {
                exception.Handle(ex => ex is OperationCanceledException);
            }
        }
    }
}


text:
/**
 *
 */
package com.cheer.petstore.service;

import com.cheer.petstore.domain.Master;
import com.cheer.petstore.domain.Pet;

/**
 * @author Cheer
 * @date 2017年10月25日
 * @time 下午2:37:18
 */
public interface MasterService
{
    boolean login(Master master);

    boolean adoptPet(Pet pet);
}


text:
<?php

namespace kaluzki\JetBrains\LiveTemplate\Model;
use IteratorAggregate;
use ReflectionClass;
use SimpleXMLElement;

/**
 */
class XmlStore implements IteratorAggregate
{
    /**
     * @var SimpleXMLElement
     */
    protected $xml;

    /**
     * @var TemplateSet
     */
    protected $templateSet;

    /**
     * @param SimpleXMLElement $xml
     */
    public function __construct(SimpleXMLElement $xml)
    {
        $this->xml = $xml;
    }

    /**
     * @inheritdoc
     *
     * @return TemplateSet|Template[]
     */
    public function getIterator()
    {
        if (!$this->templateSet) {
            $this->templateSet = $this->toTemplateSet($this->xml);
        }
        return $this->templateSet;
    }

    /**
     * @param SimpleXMLElement $xml
     *
     * @return TemplateSet
     */
    protected function toTemplateSet(SimpleXMLElement $xml)
    {
        return new TemplateSet([
            'group'     => $this->attribute($xml, 'group'),
            'templates' => array_map([$this, 'toTemplate'], $xml->xpath('/templateSet/template'))
        ]);
    }

    /**
     * @param SimpleXMLElement $xml
     *
     * @return Template
     */
    protected function toTemplate(SimpleXMLElement $xml)
    {
        return new Template([
            'name'             => $this->attribute($xml, 'name'),
            'description'      => $this->attribute($xml, 'description'),
            'value'            => $this->attribute($xml, 'value'),
            'toReformat'       => $this->attribute($xml, 'toReformat') == 'true',
            'toShortenFQNames' => $this->attribute($xml, 'toShortenFQNames') != 'false',
            'variables'        => array_map([$this, 'toVariable'], $xml->xpath('variable')),
            'context'          => $this->toContext($xml->context),
            'shortcut'         => $this->attribute($xml, 'shortcut'),
            'deactivated'      => $this->attribute($xml, 'toReformat') == 'true',
        ]);
    }

    /**
     * @param SimpleXMLElement $xml
     *
     * @return Variable
     */
    protected function toVariable(SimpleXMLElement $xml)
    {
        return new Variable([
            'name'         => $this->attribute($xml, 'name'),
            'expression'   => $this->attribute($xml, 'expression'),
            'defaultValue' => $this->attribute($xml, 'defaultValue'),
            'alwaysStopAt' => $this->attribute($xml, 'alwaysStopAt') != 'false',
        ]);
    }

    /**
     * @param SimpleXMLElement $xml
     *
     * @return string[]
     */
    protected function toContext(SimpleXMLElement $xml)
    {
        static $supported = null;
        if (!$supported) {
            $supported = array_flip((new ReflectionClass(__NAMESPACE__ . '\ContextEnum'))->getConstants());
        }
        $context = [];
        foreach ($xml->xpath('option') as $option) {
            $name = $this->attribute($option, 'name');
            if (isset($supported[$name]) && $this->attribute($option, 'value') == 'true' ) {
                $context[] = $name;
            }
        }
        return array_unique($context);
    }

    /**
     * @param SimpleXMLElement $xml
     * @param string           $name
     *
     * @return string
     */
    protected function attribute(SimpleXMLElement $xml, $name)
    {
        return html_entity_decode((string)$xml[$name]);
    }
}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Button - Strong</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">

  <ion-app>

        <ion-header>
          <ion-toolbar>
            <ion-title>Button - Strong</ion-title>
          </ion-toolbar>
        </ion-header>

        <ion-content id="content" padding no-bounce>

<ion-button strong>Default</ion-button>

<ion-button strong fill="outline" color="secondary">Outline</ion-button>

<ion-button strong fill="clear">Clear</ion-button>

<ion-button strong expand="block" color="danger">Block</ion-button>

<ion-button strong expand="full" color="dark">Full</ion-button>

<ion-button strong shape="round">Strong</ion-button>

        </ion-content>

  </ion-app>


text: The following repository hosts the Gedder Alarm Android application.


text:
var parse = require('url').parse;
var bindKey = require('lodash').bindKey;

require('../app_switcher/app_switcher.less');
var DomLocationProvider = require('ui/domLocation');

require('ui/modules')
.get('kibana')
.directive('appSwitcher', function () {
  return {
    restrict: 'E',
    template: require('./app_switcher.html'),
    controllerAs: 'switcher',
    controller: function ($scope, Private) {
      var domLocation = Private(DomLocationProvider);

      // since we render this in an isolate scope we can't "require: ^chrome", but
      // rather than remove all helpfull checks we can just check here.
      if (!$scope.chrome || !$scope.chrome.getNavLinks) {
        throw new TypeError('appSwitcher directive requires the "chrome" config-object');
      }

      this.getNavLinks = bindKey($scope.chrome, 'getNavLinks');

      // links don't cause full-navigation events in certain scenarios
      // so we force them when needed
      this.ensureNavigation = function (event, app) {
        if (event.isDefaultPrevented() || event.altKey || event.metaKey || event.ctrlKey) {
          return;
        }

        var toParsed = parse(event.delegateTarget.href);
        var fromParsed = parse(domLocation.href);
        var sameProto = toParsed.protocol === fromParsed.protocol;
        var sameHost = toParsed.host === fromParsed.host;
        var samePath = toParsed.path === fromParsed.path;

        if (sameProto && sameHost && samePath) {
          toParsed.hash && domLocation.reload();

          // event.preventDefault() keeps the browser from seeing the new url as an update
          // and even setting window.location does not mimic that behavior, so instead
          // we use stopPropagation() to prevent angular from seeing the click and
          // starting a digest cycle/attempting to handle it in the router.
          event.stopPropagation();
        }
      };

    }
  };
});


text:
using LinqToDB.Mapping;

#pragma warning disable 1573, 1591
#nullable enable

namespace Cli.Default.Firebird
{
	[Table("InheritanceChild")]
	public class InheritanceChild
	{
		[Column("InheritanceChildId" , IsPrimaryKey = true)] public int     InheritanceChildId  { get; set; } // integer
		[Column("InheritanceParentId"                     )] public int     InheritanceParentId { get; set; } // integer
		[Column("TypeDiscriminator"                       )] public int?    TypeDiscriminator   { get; set; } // integer
		[Column("Name"                                    )] public string? Name                { get; set; } // varchar(50)
	}
}


text:
            {{ title }}

			 {{ firewallstatus_on }}

			Enabled

                         {{ firewallstatus_off }}

                        Disabled


text:
$(function()
{
	var successMsg = "Your message has been sent."; // Message shown on success.
	var failMsg = "Sorry it seems that our mail server is not responding, Sorry for the inconvenience!"; // Message shown on fail.

	$("input,textarea").jqBootstrapValidation(
    {
     	preventSubmit: true,
     	submitSuccess: function($form, event)
	 	{
			if(!$form.attr('action')) // Check form doesnt have action attribute
			{
				event.preventDefault(); // prevent default submit behaviour

				var processorFile = "./includes/"+$form.attr('id')+".php";
				var formData = {};

				$form.find("input, textarea, option:selected").each(function(e) // Loop over form objects build data object
				{
					var fieldData =  $(this).val();
					var fieldID =  $(this).attr('id');

					if($(this).is(':checkbox')) // Handle Checkboxes
					{
						fieldData = $(this).is(":checked");
					}
					else if($(this).is(':radio')) // Handle Radios
					{
						fieldData = $(this).val()+' = '+$(this).is(":checked");
					}
					else if($(this).is('option:selected')) // Handle Option Selects
					{
						fieldID = $(this).parent().attr('id');
					}

					formData[fieldID] = fieldData;
				});

				$.ajax({
		        	url: processorFile,
		    		type: "POST",
		    		data: formData,
		    		cache: false,
		    		success: function() // Success
		 			{
						$form.append("

<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>"+successMsg+"

");
		 	   		},
			   		error: function() // Fail
			   		{
						$form.append("

<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>"+failMsg+"

");
			   		},
					complete: function() // Clear
					{
						$form.trigger("reset");
					},
		   		});
			}
         },
         filter: function() // Handle hidden form elements
		 {
			 return $(this).is(":visible");
         },
	 });
});


text:
//
//  Account.m
//  weChat
//
//  Created by 天佑 on 16/3/26.
//  Copyright © 2016年 天佑. All rights reserved.
//

#import "Account.h"

#define kUserKey @"user"
#define kPwdKey @"pwd"
#define kLoginKey @"login"

static NSString *domain = @"youge.local";
static NSString *host = @"127.0.0.1";
static int port = 5222;

@implementation Account

+(instancetype)shareAccount{

    return [[self alloc]init];
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone{

    NSLog(@"%s",__func__);
    static Account *account;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (account == nil) {

            account = [super allocWithZone:zone];

            /** 从沙盒获取上次的用户登陆信息 */
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            account.loginUser = [defaults objectForKey:kUserKey];
            account.loginPwd = [defaults objectForKey:kPwdKey];
            account.login = [defaults boolForKey:kLoginKey];

        }

    });
    return account;
}

/** 保存数据到沙盒 */
- (void)saveToSandBox{

    /** 保存user pwd login */
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:self.loginUser forKey:kUserKey];
    [defaults setObject:self.loginPwd forKey:kPwdKey];
    [defaults setBool:self.isLogin forKey:kLoginKey];
    [defaults synchronize];

}

-(NSString *)domain{
    return domain;
}

-(NSString *)host{
    return host;
}

-(int)port{
    return port;
}
@end


text:
<?php

namespace Plugins\Content\Formathtml\Macros;

use Plugins\Content\Formathtml\Macro;

/**
 * Macro class for displaying an Iframe
 */
class Iframe extends Macro
{
	/**
	 * Returns description of macro, use, and accepted arguments
	 *
	 * @return     array
	 */
	public function description()
	{
		// use host for example, that way  its not block
		$host = 'https://' . \Request::getString('HTTP_HOST', '', 'server');

		$txt = array();
		$txt['wiki'] = 'Embeds an Iframe into the Page';
		$txt['html'] = '
Embeds an iframe into the page.

Examples:

[[Iframe(' . $host . ')]]

[[Iframe(' . $host . ', 640, 380)]] - width 640px, height 380px

Displays:

						';

		return $txt['html'];
	}

	/**
	 * Generate macro output
	 *
	 * @return     string
	 */
	public function render()
	{
		//get the args passed in
		$content = $this->args;

		// defaults
		$default_width = 640;
		$default_height = 380;

		// args will be null if the macro is called without parenthesis.
		if (!$content)
		{
			return '';
		}

		// split up the args
		$args = array_map('trim', explode(',', $content));
		$url  = $args[0];

		// did user pass width/height args
		$width  = (isset($args[1]) && $args[1] != '') ? $args[1] : $default_width;
		$height = (isset($args[2]) && $args[2] != '') ? $args[2] : $default_height;

		//return the emdeded youtube video
		return '';
	}
}


text:
package main

import "testing"

func TestProblem(t *testing.T) {
	expected := 104743
	got := problem()
	if got != expected {
		t.Errorf("oh no! expected: %i got: %i", expected, got)
	}
}


text:
Allows to create mock implementations of [`Log`](-unknown-), compatible to the "axLog" and "axGlobalLog"
injections.

## Contents

**Module Members**

- [create()](#create)

## Module Members

#### create()

Creates a log mock that does not actually log anywhere, but can be spied upon.

##### Returns

| Type | Description |
| ---- | ----------- |
| `AxLog` |  a fresh mock instance |


text:
require 'sugar-rails'
require 'jquery-form-rails'
require 'haml_coffee_assets'
require 'joosy'

require 'joosy/rails/version'
require 'joosy/rails/controller'
require 'joosy/rails/engine'
require 'joosy/rails/routing'


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

  <parent>
    <groupId>org.pac4j.jax-rs</groupId>
    <artifactId>parent</artifactId>
    <version>5.0.1-SNAPSHOT</version>
  </parent>
  <artifactId>testing</artifactId>

  <properties>
    <ws.rs-api.version>2.1.6</ws.rs-api.version>

    <assertj.version>3.23.1</assertj.version>
    <javassist.version>3.29.2-GA</javassist.version>
    <awaitility.version>4.2.0</awaitility.version>
    <objenesis.version>3.3</objenesis.version>
  </properties>

  <dependencies>
    <!-- dependencies provided by the implementations -->
    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>core</artifactId>
      <version>${project.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>jakarta.ws.rs</groupId>
      <artifactId>jakarta.ws.rs-api</artifactId>
      <version>${ws.rs-api.version}</version>
      <scope>provided</scope>
    </dependency>

    <!-- test dependencies -->
    <dependency>
      <groupId>org.pac4j</groupId>
      <artifactId>pac4j-http</artifactId>
      <version>${pac4j.version}</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
    </dependency>
    <dependency>
      <groupId>org.assertj</groupId>
      <artifactId>assertj-core</artifactId>
      <version>${assertj.version}</version>
    </dependency>
    <dependency>
      <groupId>org.javassist</groupId>
      <artifactId>javassist</artifactId>
      <version>${javassist.version}</version>
    </dependency>
    <dependency>
      <groupId>org.awaitility</groupId>
      <artifactId>awaitility</artifactId>
      <version>${awaitility.version}</version>
    </dependency>
    <dependency>
      <groupId>org.objenesis</groupId>
      <artifactId>objenesis</artifactId>
      <version>${objenesis.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-simple</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>jul-to-slf4j</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
  </dependencies>
</project>


text:
package com.datatorrent.contrib.hbase;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.hadoop.hbase.client.Put;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.supercsv.io.CsvListReader;
import org.supercsv.io.ICsvListReader;
import org.supercsv.prefs.CsvPreference;

import com.datatorrent.api.Context.OperatorContext;
import com.datatorrent.netlet.util.DTThrowable;
import com.datatorrent.lib.util.ReusableStringReader;

/**
 * Takes a configuration string which tells us about the position of the row, or column.  The incoming tuples are inserted accordingly.
 * <p>
 * @displayName HBase Csv Mapping Put
 * @category Output
 * @tags hbase, csv, put, String
 * @since 1.0.4
 */
public class HBaseCsvMappingPutOperator extends AbstractHBaseWindowPutOutputOperator<String> {
  private class ColDef {
    String colFam;
    String colName;
  }

  private static final transient Logger logger = LoggerFactory.getLogger(HBaseCsvMappingPutOperator.class);
  private transient Integer rowIndex;
  private transient Map<Integer, ColDef> colMap = new HashMap<Integer, ColDef>();
  private transient ICsvListReader lineListReader = null;
  private transient ReusableStringReader lineSr = new ReusableStringReader();
  private transient ArrayList<String> csvLineList = new ArrayList<String>();
  private String mappingString;

  public void setMappingString(String mappingString) {
    this.mappingString = mappingString;
  }

  @Override
  public Put operationPut(String t) throws IOException {
    return parseLine(t);
  }

  public void parseMapping() {
    ICsvListReader listReader = null;
    StringReader sr = null;
    ArrayList<String> csvList = new ArrayList<String>();
    try {
      sr = new StringReader(mappingString);
      listReader = new CsvListReader(sr,CsvPreference.STANDARD_PREFERENCE);
      csvList = (ArrayList<String>) listReader.read();
    } catch (IOException e) {
      logger.error("Cannot read the mapping string", e);
      DTThrowable.rethrow(e);
    } finally {
      try {
        sr.close();
        listReader.close();
      } catch (IOException e) {
        logger.error("Error closing Csv reader", e);
        DTThrowable.rethrow(e);
      }
    }
    for (int index = 0; index < csvList.size(); index++) {
      String value = csvList.get(index);
      if (value.equals("row"))
        rowIndex = index;
      else {
        ColDef c = new ColDef();
        c.colFam = value.substring(0, value.indexOf('.'));
        c.colName = value.substring(value.indexOf('.') + 1);
        colMap.put(index, c);
      }
    }
  }

  public Put parseLine(String s) {
    Put put = null;
    try {
      lineSr.open(s);
      csvLineList = (ArrayList<String>) lineListReader.read();
    } catch (IOException e) {
      logger.error("Cannot read the property string", e);
      DTThrowable.rethrow(e);
    }
    put = new Put(csvLineList.get(rowIndex).getBytes());
    for (Entry<Integer, ColDef> e : colMap.entrySet()) {
      String colValue = csvLineList.get(e.getKey());
      put.add(e.getValue().colFam.getBytes(),e.getValue().colName.getBytes(), colValue.getBytes());
    }

    csvLineList.clear();
    return put;
  }

  @Override
  public void setup(OperatorContext context) {
    super.setup(context);
    parseMapping();
    lineListReader = new CsvListReader(lineSr,
        CsvPreference.STANDARD_PREFERENCE);
  }

  @Override
  public void teardown() {
    super.teardown();
    try {
      lineSr.close();
      lineListReader.close();
    } catch (IOException e) {
      logger.error("Cannot close the readers", e);
      DTThrowable.rethrow(e);
    }
  }

}


text:
"""Parser for the SDM partition table at the beginning of /dev/nflasha"""
# Kernel source: fs/partitions/sdm_partition_table.h

import shutil

from ..io import *
from ..util import *

SdmPartitionTableHeader = Struct('SdmPartitionTableHeader', [
 ('magic', Struct.STR % 4),
 ('version', Struct.STR % 4),
 ('nPartition', Struct.INT32),
 ('...', 20),
])
sdmPartitionTableHeaderMagic = b'8246'
sdmPartitionTableHeaderVersion = b'1.00'

SdmPartition = Struct('SdmPartition', [
 ('start', Struct.INT32),
 ('size', Struct.INT32),
 ('type', Struct.INT32),
 ('flag', Struct.INT32),
])

def isPartitionTable(file):
 header = SdmPartitionTableHeader.unpack(file)
 return header and header.magic == sdmPartitionTableHeaderMagic

def readPartitionTable(file):
 header = SdmPartitionTableHeader.unpack(file)

 if header.magic != sdmPartitionTableHeaderMagic:
  raise Exception('Wrong magic')
 if header.version != sdmPartitionTableHeaderVersion:
  raise Exception('Wrong version')

 for i in range(header.nPartition):
  partition = SdmPartition.unpack(file, SdmPartitionTableHeader.size + i*SdmPartition.size)
  if partition.flag & 1:
   yield i+1, FilePart(file, partition.start, partition.size)

def writePartitions(partitions, outFile):
 sectorSize = 0x200

 outFile.write(SdmPartitionTableHeader.pack(
  magic = sdmPartitionTableHeaderMagic,
  version = sdmPartitionTableHeaderVersion,
  nPartition = len(partitions),
 ))
 outFile.write(b'\xff' * (sectorSize - SdmPartitionTableHeader.size))

 parts = []
 for f in partitions:
  o = outFile.tell()
  f.seek(0)
  shutil.copyfileobj(f, outFile)
  if outFile.tell() % sectorSize:
   outFile.write(b'\xff' * (sectorSize - outFile.tell() % sectorSize))
  parts.append((o, outFile.tell() - o))

 outFile.seek(SdmPartitionTableHeader.size)
 for o, s in parts:
  outFile.write(SdmPartition.pack(
   start = o,
   size = s,
   type = 1,
   flag = 0xffffffff,
  ))


text:
package com.bkav.training.week2.session11;

import com.bkav.training.week2.session2.Author;

public class TestBook {
	public static void main(String[] args) {
		// Declare and allocate an array of Authors
		Author[] authors = new Author[2];
		authors[0] = new Author("Tan Ah Teck", "AhTeck@somewhere.com", 'm');
		authors[1] = new Author("Paul Tan", "Paul@nowhere.com", 'm');

		// Declare and allocate a Book instance
		Book javaDummy = new Book("Java for Dummy", authors, 19.99, 99);
		System.out.println(javaDummy);  // toString()
		System.out.print("The authors are: ");
		javaDummy.printAuthors();
	}
}


text:
// jskeyword.cs
//
// Copyright 2010 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

namespace Baker.Text
{

    internal sealed class JsKeyword
    {
        private JsKeyword m_next;
        private JsToken m_token;
        private string m_name;
        private int m_length;

        private JsKeyword(JsToken token, string name)
            : this(token, name, null)
        {
        }

        private JsKeyword(JsToken token, string name, JsKeyword next)
        {
            m_name = name;
            m_token = token;
            m_length = m_name.Length;
            m_next = next;
        }

        /*internal bool Exists(string target)
        {
            JSKeyword keyword = this;
            while (keyword != null)
            {
                if (keyword.m_name == target)
                {
                    return true;
                }
                keyword = keyword.m_next;
            }
            return false;
        }*/

        internal static string CanBeIdentifier(JsToken keyword)
        {
            switch (keyword)
            {
                // always allowed
                case JsToken.Get: return "get";
                case JsToken.Set: return "set";

                // not in strict mode
                case JsToken.Implements: return "implements";
                case JsToken.Interface: return "interface";
                case JsToken.Let: return "let";
                case JsToken.Package: return "package";
                case JsToken.Private: return "private";
                case JsToken.Protected: return "protected";
                case JsToken.Public: return "public";
                case JsToken.Static: return "static";
                case JsToken.Yield: return "yield";

                // apparently never allowed for Chrome, so we want to treat it
                // differently, too
                case JsToken.Native: return "native";

                // no other tokens can be identifiers
                default: return null;
            }
        }

        internal JsToken GetKeyword(JsContext context, int wordLength)
        {
            return GetKeyword(context.Document.Source, context.StartPosition, wordLength);
        }

        internal JsToken GetKeyword(string source, int startPosition, int wordLength)
        {
            JsKeyword keyword = this;

        nextToken:
            while (null != keyword)
            {
                if (wordLength == keyword.m_length)
                {
                    // equal number of characters
                    // we know the first char has to match, so start with the second
                    for (int i = 1, j = startPosition + 1; i < wordLength; i++, j++)
                    {
                        char ch1 = keyword.m_name[i];
                        char ch2 = source[j];
                        if (ch1 == ch2)
                        {
                            // match -- continue
                            continue;
                        }
                        else if (ch2 < ch1)
                        {
                            // because the list is in order, if the character for the test
                            // is less than the character for the keyword we are testing against,
                            // then we know this isn't going to be in any other node
                            return JsToken.Identifier;
                        }
                        else
                        {
                            // must be greater than the current token -- try the next one
                            keyword = keyword.m_next;
                            goto nextToken;
                        }
                    }

                    // if we got this far, it was a complete match
                    return keyword.m_token;
                }
                else if (wordLength < keyword.m_length)
                {
                    // in word-length order first of all, so if the length of the test string is
                    // less than the length of the keyword node, this is an identifier
                    return JsToken.Identifier;
                }

                keyword = keyword.m_next;
            }
            return JsToken.Identifier;
        }

        // each list must in order or length first, shortest to longest.
        // for equal length words, in alphabetical order
        internal static JsKeyword[] InitKeywords()
        {
            JsKeyword[] keywords = new JsKeyword[26];
            // a
            // b
            keywords['b' - 'a'] = new JsKeyword(JsToken.Break, "break");
            // c
            keywords['c' - 'a'] = new JsKeyword(JsToken.Case, "case",
                new JsKeyword(JsToken.Catch, "catch",
                    new JsKeyword(JsToken.Class, "class",
                        new JsKeyword(JsToken.Const, "const",
                            new JsKeyword(JsToken.Continue, "continue")))));
            // d
            keywords['d' - 'a'] = new JsKeyword(JsToken.Do, "do",
                new JsKeyword(JsToken.Delete, "delete",
                    new JsKeyword(JsToken.Default, "default",
                        new JsKeyword(JsToken.Debugger, "debugger"))));
            // e
            keywords['e' - 'a'] = new JsKeyword(JsToken.Else, "else",
                new JsKeyword(JsToken.Enum, "enum",
                    new JsKeyword(JsToken.Export, "export",
                        new JsKeyword(JsToken.Extends, "extends"))));
            // f
            keywords['f' - 'a'] = new JsKeyword(JsToken.For, "for",
                new JsKeyword(JsToken.False, "false",
                    new JsKeyword(JsToken.Finally, "finally",
                        new JsKeyword(JsToken.Function, "function"))));
            // g
            keywords['g' - 'a'] = new JsKeyword(JsToken.Get, "get");
            // i
            keywords['i' - 'a'] = new JsKeyword(JsToken.If, "if",
                new JsKeyword(JsToken.In, "in",
                    new JsKeyword(JsToken.Import, "import",
                        new JsKeyword(JsToken.Interface, "interface",
                            new JsKeyword(JsToken.Implements, "implements",
                                new JsKeyword(JsToken.InstanceOf, "instanceof"))))));
            // l
            keywords['l' - 'a'] = new JsKeyword(JsToken.Let, "let");
            // n
            keywords['n' - 'a'] = new JsKeyword(JsToken.New, "new",
                new JsKeyword(JsToken.Null, "null",
                    new JsKeyword(JsToken.Native, "native")));
            // p
            keywords['p' - 'a'] = new JsKeyword(JsToken.Public, "public",
                new JsKeyword(JsToken.Package, "package",
                    new JsKeyword(JsToken.Private, "private",
                        new JsKeyword(JsToken.Protected, "protected"))));
            // r
            keywords['r' - 'a'] = new JsKeyword(JsToken.Return, "return");
            // s
            keywords['s' - 'a'] = new JsKeyword(JsToken.Set, "set",
                new JsKeyword(JsToken.Super, "super",
                    new JsKeyword(JsToken.Static, "static",
                        new JsKeyword(JsToken.Switch, "switch"))));
            // t
            keywords['t' - 'a'] = new JsKeyword(JsToken.Try, "try",
                new JsKeyword(JsToken.This, "this",
                    new JsKeyword(JsToken.True, "true",
                        new JsKeyword(JsToken.Throw, "throw",
                            new JsKeyword(JsToken.TypeOf, "typeof")))));
            // u
            // v
            keywords['v' - 'a'] = new JsKeyword(JsToken.Var, "var",
                new JsKeyword(JsToken.Void, "void"));
            // w
            keywords['w' - 'a'] = new JsKeyword(JsToken.With, "with",
                new JsKeyword(JsToken.While, "while"));
            // y
            keywords['y' - 'a'] = new JsKeyword(JsToken.Yield, "yield");

            return keywords;
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.design.widget.TabLayout.TabView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </android.support.design.widget.TabLayout.TabView>

</LinearLayout>


text:
define([
    // Includes all dependant libraries / files.
    'jquery',
    'underscore',
    'backbone',
    'feedhenry',
    'services/logout'

    ], function($, _, Backbone, $fh,logoutService) {
        // interface----------------------------------
        var store = {
            save	: _save, 	  // save a model to local storage
            load	: _load,	  // load a model from local storage
            clear	: _clear, 	  // clear a model from local storage
            clearAll: _clearAll   // wipe local storage
        };
        //Function to save in Local Storage Object
        function _save(modelName, model, callback){
            var model = model || {};

            localStorage.setItem(modelName, model);
            return callback(null,"true");
        };

        //Function to Load from Local Storage Object
        function _load(modelName, callback){

            var res = localStorage.getItem(modelName);      // Retrieve data from local storage.
            if(res) {
                return callback(true,res);
            }
            return callback(false ,null);
        };

        //Function to clear Local Storage Object
        function _clear(modelName, callback){
            logoutService.logoutUser(localStorage.getItem(modelName),function(err,res){
                localStorage.removeItem(modelName);
                Backbone.history.navigate('', {
                    trigger: true
                });
                return callback(null,true);
            });

            return callback(true);
        };

        // Clears whole local storage data.
        function _clearAll(callback){
           localStorage.clear();
            return true;
        };

        return store;

    });


text:
@interface RNNBasePresenterTest : XCTestCase

@property(nonatomic, strong) RNNBasePresenter *uut;
@property(nonatomic, strong) RNNNavigationOptions *options;
@property(nonatomic, strong) RNNComponentViewController *boundViewController;
@property(nonatomic, strong) id mockBoundViewController;

@end

@implementation RNNBasePresenterTest

- (void)setUp {
    [super setUp];
    self.uut = [[RNNBasePresenter alloc] initWithDefaultOptions:[[RNNNavigationOptions alloc] initEmptyOptions]];
    self.boundViewController = [RNNComponentViewController createWithComponentId:@"componentId" initialOptions:[RNNNavigationOptions emptyOptions]];
    self.mockBoundViewController = [OCMockObject partialMockForObject:self.boundViewController];
	[self.uut bindViewController:self.mockBoundViewController];
    self.options = [[RNNNavigationOptions alloc] initEmptyOptions];
}

- (void)tearDown {
    [super tearDown];
    [self.mockBoundViewController stopMocking];
    self.boundViewController = nil;
}

- (void)testApplyOptions_shouldSetTabBarItemBadgeOnlyWhenParentIsUITabBarController {
    [[self.mockBoundViewController reject] setTabBarItemBadge:[OCMArg any]];
    [self.uut applyOptions:self.options];
    [self.mockBoundViewController verify];
}

- (void)testApplyOptions_setTabBarItemBadgeShouldNotCalledOnUITabBarController {
    [self.uut bindViewController:self.mockBoundViewController];
    self.options.bottomTab.badge = [[Text alloc] initWithValue:@"badge"];
    [[self.mockBoundViewController reject] setTabBarItemBadge:[[RNNBottomTabOptions alloc] initWithDict:@{@"badge": @"badge"}]];
    [self.uut applyOptions:self.options];
    [self.mockBoundViewController verify];
}

- (void)testApplyOptions_setTabBarItemBadgeShouldWhenNoValue {
    [self.uut bindViewController:self.mockBoundViewController];
    self.options.bottomTab.badge = nil;
    [[self.mockBoundViewController reject] setTabBarItemBadge:[OCMArg any]];
    [self.uut applyOptions:self.options];
    [self.mockBoundViewController verify];
}

- (void)testGetPreferredStatusBarStyle_returnLightIfLight {
	self.boundViewController.options.statusBar.style = [[Text alloc] initWithValue:@"light"];

    XCTAssertEqual([_uut getStatusBarStyle], UIStatusBarStyleLightContent);
}

- (void)testGetPreferredStatusBarStyle_returnDark {
    self.boundViewController.options.statusBar.style = [[Text alloc] initWithValue:@"dark"];

    XCTAssertEqual([_uut getStatusBarStyle], UIStatusBarStyleDarkContent);
}

- (void)testGetPreferredStatusBarStyle_returnDefaultIfNil {
	self.boundViewController.options.statusBar.style = nil;
    XCTAssertEqual([_uut getStatusBarStyle], UIStatusBarStyleDefault);
}

- (void)testGetPreferredStatusBarStyle_considersDefaultOptions {
    RNNNavigationOptions * lightOptions = [[RNNNavigationOptions alloc] initEmptyOptions];
    lightOptions.statusBar.style = [[Text alloc] initWithValue:@"light"];
    [_uut setDefaultOptions:lightOptions];

    XCTAssertEqual([_uut getStatusBarStyle], UIStatusBarStyleLightContent);
}

- (void)testApplyOptionsOnInit_setSwipeToDismiss {
    self.options.modal.swipeToDismiss = [[Bool alloc] initWithBOOL:NO];
	XCTAssertFalse(_boundViewController.modalInPresentation);
    [self.uut applyOptionsOnInit:self.options];
	XCTAssertTrue(_boundViewController.modalInPresentation);
}

- (void)testHidesBottomBarWhenPushed_showsBar {
	_boundViewController.options.bottomTabs.visible = [[Bool alloc] initWithBOOL:NO];
	XCTAssertTrue(_boundViewController.hidesBottomBarWhenPushed);
}

- (void)testHidesBottomBarWhenPushed_hidesBar {
	_boundViewController.options.bottomTabs.visible = [[Bool alloc] initWithBOOL:YES];
	XCTAssertFalse(_boundViewController.hidesBottomBarWhenPushed);
}

- (void)testHidesBottomBarWhenPushed_resolveParentShowsBar {
	UINavigationController* nvc = [[UINavigationController alloc] initWithRootViewController:self.boundViewController];
	nvc.options = [RNNNavigationOptions emptyOptions];
	nvc.options.bottomTabs.visible = [[Bool alloc] initWithBOOL:NO];
	XCTAssertTrue(_boundViewController.hidesBottomBarWhenPushed);
}

- (void)testHidesBottomBarWhenPushed_resolveParentHidesBar {
	UINavigationController* nvc = [[UINavigationController alloc] initWithRootViewController:self.boundViewController];
	nvc.options = [RNNNavigationOptions emptyOptions];
	nvc.options.bottomTabs.visible = [[Bool alloc] initWithBOOL:YES];
	XCTAssertFalse(_boundViewController.hidesBottomBarWhenPushed);
}

- (void)testHidesBottomBarWhenPushed_resolveChildShowsBarBeforeParent {
	UINavigationController* nvc = [[UINavigationController alloc] initWithRootViewController:self.boundViewController];
	nvc.options = [RNNNavigationOptions emptyOptions];
	nvc.options.bottomTabs.visible = [[Bool alloc] initWithBOOL:NO];
	XCTAssertTrue(_boundViewController.hidesBottomBarWhenPushed);
}

- (void)testHidesBottomBarWhenPushed_resolveChildHidesBarBeforeParent {
	UINavigationController* nvc = [[UINavigationController alloc] initWithRootViewController:self.boundViewController];
	nvc.options = [RNNNavigationOptions emptyOptions];
	self.boundViewController.options.bottomTabs.visible = [[Bool alloc] initWithBOOL:NO];
	nvc.options.bottomTabs.visible = [[Bool alloc] initWithBOOL:YES];
	XCTAssertTrue(_boundViewController.hidesBottomBarWhenPushed);
}

@end


text:
package com.smorales.javalab.business.processor.creators;

import com.smorales.javalab.business.processor.boundary.SimpleNode;
import com.smorales.javalab.business.processor.boundary.rest.request.TreeNode;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class FileManagerCreators {

    public static TreeNode createValidTreeNode(String id) {
        TreeNode node = new TreeNode(id);
        node.setParentId("0");
        node.setIcon("fa-file-text-o");
        return node;
    }

    public static SimpleNode createValidSimpleNode(String id, String label, String parent) {
        return new SimpleNode(id, SimpleNode.Type.FILE, label, "", parent);
    }

    public static List<TreeNode> createNestedHierarchyOfNodes(TreeNode toFind) {
        TreeNode parent = new TreeNode("0");
        parent.setLabel("com.company.project");
        parent.setIcon("fa fa-th-large");
        parent.setParentId("1");
        parent.setChildren(Collections.singletonList(toFind));

        TreeNode grandParent = new TreeNode("1");
        grandParent.setLabel("src/main/java");
        grandParent.setExpandedIcon("fa-folder-open");
        grandParent.setCollapsedIcon("fa-folder");
        grandParent.setChildren(Collections.singletonList(parent));

        return Arrays.asList(new TreeNode("2"), new TreeNode("3"), new TreeNode("4"), grandParent, new TreeNode("5"));
    }

    public static List<SimpleNode> createSimpleListOfNodes(SimpleNode two) {
        SimpleNode zero = new SimpleNode("0", SimpleNode.Type.FOLDER, "com.company.project", "", "1");
        SimpleNode one = new SimpleNode("1", SimpleNode.Type.FOLDER, "src/main/java", "", null);
        return Arrays.asList(zero, one, two);
    }
}


text:
Web developer @Occitech

> #react, #react-native, #wordpress, #prestashop, #woocomerce.

## **Run project**

```shell
gatsby develop
```


text:
package ru.aoleynikov;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.concurrent.CopyOnWriteArrayList;

import javax.swing.text.StyledEditorKit.ForegroundAction;

/**
 * Start.
 * @author Anton Oleynikov
 * created on 23.08.2017
 */
public class StartFileFinder {

	/**
	 * Start program.
	 * @param args
	 */
	public static void main(String[] args) {
		ArrayList<String> exts = new ArrayList<>();
		//exts.add("xls");
		exts.add("xlsx"); // расширения
		exts.add("xls");

		//exts.add("txt");
		try(BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
			System.out.println("Write name of file:");
			ParallerSearch parallerSearch = new ParallerSearch("C://Users//oleynikov//Desktop//1С", reader.readLine(), exts);
			CopyOnWriteArrayList<String> result = parallerSearch.start();
			System.out.println("ssssssssssssssssssssssssssssss" + result.size());
			for (String iter : result) {
				System.out.println(iter);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}