text:
package org.jsimpledb.core;

import java.util.Arrays;
import java.util.List;
import java.util.NavigableMap;

import org.jsimpledb.kv.KVPairIterator;
import org.jsimpledb.util.ByteReader;

class MapFieldStorageInfo<K, V> extends ComplexFieldStorageInfo<NavigableMap<K, V>> {

    final SimpleFieldStorageInfo<K> keyField;
    final SimpleFieldStorageInfo<V> valueField;

    MapFieldStorageInfo(MapField<K, V> field) {
        super(field);
        this.keyField = field.keyField.toStorageInfo();
        this.valueField = field.valueField.toStorageInfo();
    }

    @Override
    public List<SimpleFieldStorageInfo<?>> getSubFields() {
        return Arrays.asList(this.keyField, this.valueField);
    }

    CoreIndex<K, ObjId> getKeyFieldIndex(Transaction tx) {
        return new CoreIndex<K, ObjId>(tx,
          new IndexView<K, ObjId>(this.keyField.storageId, this.keyField.fieldType, FieldTypeRegistry.OBJ_ID));
    }

    CoreIndex2<V, ObjId, K> getValueFieldIndex(Transaction tx) {
        return new CoreIndex2<V, ObjId, K>(tx,
          new Index2View<V, ObjId, K>(this.valueField.storageId,
           this.valueField.fieldType, FieldTypeRegistry.OBJ_ID, this.keyField.fieldType));
    }

    @Override
    CoreIndex<?, ObjId> getSimpleSubFieldIndex(Transaction tx, SimpleFieldStorageInfo<?> subField) {
        if (subField.equals(this.keyField))
            return this.getKeyFieldIndex(tx);
        if (subField.equals(this.valueField))
            return this.getValueFieldIndex(tx).asIndex();
        throw new RuntimeException("internal eror");
    }

    @Override
    void unreference(Transaction tx, int storageId, ObjId target, ObjId referrer, byte[] prefix) {
        final FieldTypeMap<?, ?> fieldMap = (FieldTypeMap<?, ?>)tx.readMapField(referrer, this.storageId, false);
        if (storageId == this.keyField.storageId)
            fieldMap.remove(target);
        else {
            assert storageId == this.valueField.storageId;
            for (KVPairIterator i = new KVPairIterator(tx.kvt, prefix); i.hasNext(); ) {
                final ByteReader reader = new ByteReader(i.next().getKey());
                reader.skip(prefix.length);
                fieldMap.remove(fieldMap.keyFieldType.read(reader));
            }
        }
    }

    public SimpleFieldStorageInfo<K> getKeyField() {
        return this.keyField;
    }

    public SimpleFieldStorageInfo<V> getValueField() {
        return this.valueField;
    }

// Object

    @Override
    public String toString() {
        return "map field with key " + this.keyField + " and value " + this.valueField;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this)
            return true;
        if (!super.equals(obj))
            return false;
        final MapFieldStorageInfo<?, ?> that = (MapFieldStorageInfo<?, ?>)obj;
        return this.keyField.equals(that.keyField) && this.valueField.equals(that.valueField);
    }

    @Override
    public int hashCode() {
        return super.hashCode() ^ this.keyField.hashCode() ^ this.valueField.hashCode();
    }
}


text:
#include "include/core/SkTypes.h"
#include "include/private/SkSLIRNode.h"
#include "include/private/SkSLModifiers.h"
#include "include/private/SkSLProgramElement.h"
#include "include/private/SkSLStatement.h"
#include "include/private/SkSLSymbol.h"
#include "include/private/SkStringView.h"
#include "src/sksl/SkSLAnalysis.h"
#include "src/sksl/SkSLCompiler.h"
#include "src/sksl/SkSLContext.h"
#include "src/sksl/SkSLModifiersPool.h"
#include "src/sksl/SkSLProgramSettings.h"
#include "src/sksl/ir/SkSLFunctionDeclaration.h"
#include "src/sksl/ir/SkSLFunctionDefinition.h"
#include "src/sksl/ir/SkSLFunctionPrototype.h"
#include "src/sksl/ir/SkSLSymbolTable.h"
#include "src/sksl/ir/SkSLVarDeclarations.h"
#include "src/sksl/ir/SkSLVariable.h"
#include "src/sksl/transform/SkSLProgramWriter.h"
#include "src/sksl/transform/SkSLTransform.h"

#include <cstdint>
#include <memory>
#include <string>
#include <string_view>
#include <utility>
#include <vector>

namespace SkSL {

class ProgramUsage;
enum class ProgramKind : int8_t;

static void strip_export_flag(Context& context,
                              const FunctionDeclaration* funcDecl,
                              SymbolTable* symbols) {
    // Remove `$export` from every overload of this function.
    Symbol* mutableSym = symbols->findMutable(funcDecl->name());
    while (mutableSym) {
        FunctionDeclaration* mutableDecl = &mutableSym->as<FunctionDeclaration>();

        Modifiers modifiers = mutableDecl->modifiers();
        modifiers.fFlags &= ~Modifiers::kExport_Flag;
        mutableDecl->setModifiers(context.fModifiersPool->add(modifiers));

        mutableSym = mutableDecl->mutableNextOverload();
    }
}

void Transform::RenamePrivateSymbols(Context& context,
                                     Module& module,
                                     ProgramUsage* usage,
                                     ProgramKind kind) {
    class SymbolRenamer : public ProgramWriter {
    public:
        SymbolRenamer(Context& context,
                      ProgramUsage* usage,
                      std::shared_ptr<SymbolTable> symbolBase,
                      ProgramKind kind)
                : fContext(context)
                , fUsage(usage)
                , fSymbolTableStack({std::move(symbolBase)})
                , fKind(kind) {}

        static std::string FindShortNameForSymbol(const Symbol* sym,
                                                  const SymbolTable* symbolTable,
                                                  std::string namePrefix) {
            static constexpr std::string_view kLetters[] = {
                    "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
                    "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
                    "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
                    "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};

            // Try any single-letter option.
            for (std::string_view letter : kLetters) {
                std::string name = namePrefix + std::string(letter);
                if (symbolTable->find(name) == nullptr) {
                    return name;
                }
            }

            // Try every two-letter option.
            for (std::string_view letterA : kLetters) {
                for (std::string_view letterB : kLetters) {
                    std::string name = namePrefix + std::string(letterA) + std::string(letterB);
                    if (symbolTable->find(name) == nullptr) {
                        return name;
                    }
                }
            }

            // We struck out. Somehow, all 2700 two-letter names have been claimed.
            SkDEBUGFAILF("Unable to find unique name for '%s'", std::string(sym->name()).c_str());
            return std::string(sym->name());
        }

        void minifyVariableName(const Variable* var) {
            // Some variables are associated with anonymous parameters--these don't have names and
            // aren't present in the symbol table. Their names are already empty so there's no way
            // to shrink them further.
            if (var->name().empty()) {
                return;
            }

            // Ensure that this variable is properly set up in the symbol table.
            SymbolTable* symbols = fSymbolTableStack.back().get();
            Symbol* mutableSym = symbols->findMutable(var->name());
            SkASSERTF(mutableSym != nullptr,
                      "symbol table missing '%.*s'", (int)var->name().size(), var->name().data());
            SkASSERTF(mutableSym == var,
                      "wrong symbol found for '%.*s'", (int)var->name().size(), var->name().data());

            // Look for a new name for this symbol.
            // Note: we always rename _every_ variable, even ones with single-letter names. This is
            // a safeguard: if we claimed a name like `i`, and then the program itself contained an
            // `i` later on, in a nested SymbolTable, the two names would clash. By always renaming
            // everything, we can ignore that problem.
            std::string shortName = FindShortNameForSymbol(var, symbols, "");
            SkASSERT(symbols->findMutable(shortName) == nullptr);

            // Update the symbol's name.
            const std::string* ownedName = symbols->takeOwnershipOfString(std::move(shortName));
            symbols->renameSymbol(mutableSym, *ownedName);
        }

        void minifyFunctionName(const FunctionDeclaration* funcDecl) {
            // Look for a new name for this function.
            std::string namePrefix = ProgramConfig::IsRuntimeEffect(fKind) ? "" : "$";
            SymbolTable* symbols = fSymbolTableStack.back().get();
            std::string shortName = FindShortNameForSymbol(funcDecl, symbols,
                                                           std::move(namePrefix));
            SkASSERT(symbols->findMutable(shortName) == nullptr);

            if (shortName.size() < funcDecl->name().size()) {
                // Update the function's name. (If the function has overloads, this will rename all
                // of them at once.)
                Symbol* mutableSym = symbols->findMutable(funcDecl->name());
                const std::string* ownedName = symbols->takeOwnershipOfString(std::move(shortName));
                symbols->renameSymbol(mutableSym, *ownedName);
            }
        }

        bool functionNameCanBeMinifiedSafely(const FunctionDeclaration& funcDecl) const {
            if (ProgramConfig::IsRuntimeEffect(fKind)) {
                // The only externally-accessible function in a runtime effect is main().
                return !funcDecl.isMain();
            } else {
                // We will only minify $private_functions, and only ones not marked as $export.
                return skstd::starts_with(funcDecl.name(), '$') &&
                       !(funcDecl.modifiers().fFlags & Modifiers::kExport_Flag);
            }
        }

        void minifyFunction(FunctionDefinition& def) {
            // If the function is private, minify its name.
            const FunctionDeclaration* funcDecl = &def.declaration();
            if (this->functionNameCanBeMinifiedSafely(*funcDecl)) {
                this->minifyFunctionName(funcDecl);
            }

            // Minify the names of each function parameter.
            Analysis::SymbolTableStackBuilder symbolTableStackBuilder(def.body().get(),
                                                                      &fSymbolTableStack);
            for (Variable* param : funcDecl->parameters()) {
                this->minifyVariableName(param);
            }
        }

        void minifyPrototype(FunctionPrototype& proto) {
            const FunctionDeclaration* funcDecl = &proto.declaration();
            if (funcDecl->definition()) {
                // This function is defined somewhere; this isn't just a loose prototype.
                return;
            }

            // Eliminate the names of each function parameter.
            // The parameter names aren't in the symbol table's name lookup map at all.
            // All we need to do is blank out their names.
            for (Variable* param : funcDecl->parameters()) {
                param->setName("");
            }
        }

        bool visitProgramElement(ProgramElement& elem) override {
            switch (elem.kind()) {
                case ProgramElement::Kind::kFunction:
                    this->minifyFunction(elem.as<FunctionDefinition>());
                    return INHERITED::visitProgramElement(elem);

               case ProgramElement::Kind::kFunctionPrototype:
                   this->minifyPrototype(elem.as<FunctionPrototype>());
                    return INHERITED::visitProgramElement(elem);

                default:
                    return false;
            }
        }

        bool visitStatementPtr(std::unique_ptr<Statement>& stmt) override {
            Analysis::SymbolTableStackBuilder symbolTableStackBuilder(stmt.get(),
                                                                      &fSymbolTableStack);
            if (stmt->is<VarDeclaration>()) {
                // Minify the variable's name.
                VarDeclaration& decl = stmt->as<VarDeclaration>();
                this->minifyVariableName(decl.var());
            }

            return INHERITED::visitStatementPtr(stmt);
        }

        Context& fContext;
        ProgramUsage* fUsage;
        std::vector<std::shared_ptr<SymbolTable>> fSymbolTableStack;
        ProgramKind fKind;
        using INHERITED = ProgramWriter;
    };

    // Rename local variables and private functions.
    SymbolRenamer renamer{context, usage, module.fSymbols, kind};
    for (std::unique_ptr<ProgramElement>& pe : module.fElements) {
        renamer.visitProgramElement(*pe);
    }

    // Strip off modifier `$export` from every function. (Only the minifier checks this flag, so we
    // can remove it without affecting the meaning of the code.)
    for (std::unique_ptr<ProgramElement>& pe : module.fElements) {
        if (pe->is<FunctionDefinition>()) {
            const FunctionDeclaration* funcDecl = &pe->as<FunctionDefinition>().declaration();
            if (funcDecl->modifiers().fFlags & Modifiers::kExport_Flag) {
                strip_export_flag(context, funcDecl, module.fSymbols.get());
            }
        }
    }
}

}  // namespace SkSL

redpajama_set_name: RedPajamaGithub


text:
package org.fusesource.lmdbjni;

import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

import java.io.IOException;
import java.util.Comparator;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;

public class ComparatorTest {
  static {
    Setup.setLmdbLibraryPath();
  }

  @Rule
  public TemporaryFolder tmp = new TemporaryFolder();

  Env env;
  Database db;
  byte[] data = new byte[] {1,2,3};

  @Before
  public void before() throws IOException {
    String path = tmp.newFolder().getCanonicalPath();
    env = new Env();
    env.setMapSize(16 * 4096);
    env.open(path);
    db = env.openDatabase();
  }

  @After
  public void after() {
    db.close();
    env.close();
  }

  @Test
  public void testSetComparatorAsc() {
    if (Util.isAndroid()) {
      return;
    }

    Transaction writeTransaction = env.createWriteTransaction();
    db.setComparator(writeTransaction, new Comparator<byte[]>() {
      @Override
      public int compare(byte[] key1, byte[] key2) {
        return (int) (Bytes.getLong(key1) - Bytes.getLong(key2));
      }
    });
    writeTransaction.commit();
    writeTransaction = env.createWriteTransaction();

    for (int i = 0; i < 1000; i++) {
      db.put(writeTransaction, Bytes.fromLong(i), Bytes.fromLong(i));
    }
    writeTransaction.commit();
    try (EntryIterator it = db.iterate(env.createReadTransaction()) ){
      long prev = -1;
      while(it.hasNext()) {
        if (prev == -1) {
          prev = Bytes.getLong(it.next().getKey());
        } else {
          long now = Bytes.getLong(it.next().getKey());
          assertThat((prev+1), is(now));
          prev = now;
        }
      }
    }
  }

  @Test
  public void testSetComparatorDesc() {
    if (Util.isAndroid()) {
      return;
    }
    Transaction writeTransaction = env.createWriteTransaction();
    db.setComparator(writeTransaction, new Comparator<byte[]>() {
      @Override
      public int compare(byte[] key1, byte[] key2) {
        return (int) (Bytes.getLong(key2) - Bytes.getLong(key1));
      }
    });
    writeTransaction.commit();
    writeTransaction = env.createWriteTransaction();

    for (int i = 0; i < 1000; i++) {
      db.put(writeTransaction, Bytes.fromLong(i), Bytes.fromLong(i));
    }
    writeTransaction.commit();
    try (EntryIterator it = db.iterate(env.createReadTransaction()) ){
      long prev = -1;
      while(it.hasNext()) {
        if (prev == -1) {
          prev = Bytes.getLong(it.next().getKey());
        } else {
          long now = Bytes.getLong(it.next().getKey());
          assertThat((prev-1), is(now));
          prev = now;
        }
      }
    }
  }

  @Test
  public void testSetDirectComparatorAsc() {
    if (Util.isAndroid()) {
      return;
    }
    Transaction writeTransaction = env.createWriteTransaction();
    db.setDirectComparator(writeTransaction, new Comparator<DirectBuffer>() {
      @Override
      public int compare(DirectBuffer key1, DirectBuffer key2) {
        return (int) (key1.getLong(0) - key2.getLong(0));
      }
    });
    writeTransaction.commit();
    writeTransaction = env.createWriteTransaction();

    for (int i = 0; i < 1000; i++) {
      db.put(writeTransaction, Bytes.fromLong(i), Bytes.fromLong(i));
    }
    writeTransaction.commit();
    try (EntryIterator it = db.iterate(env.createReadTransaction()) ){
      long prev = -1;
      while(it.hasNext()) {
        if (prev == -1) {
          prev = Bytes.getLong(it.next().getKey());
        } else {
          long now = Bytes.getLong(it.next().getKey());
          assertThat((prev+1), is(now));
          prev = now;
        }
      }
    }
  }

  @Test
  public void testSetDirectComparatorDesc() {
    if (Util.isAndroid()) {
      return;
    }
    Transaction writeTransaction = env.createWriteTransaction();
    db.setDirectComparator(writeTransaction, new Comparator<DirectBuffer>() {
      @Override
      public int compare(DirectBuffer key1, DirectBuffer key2) {
        return (int) (key2.getLong(0) - key1.getLong(0));
      }
    });
    writeTransaction.commit();
    writeTransaction = env.createWriteTransaction();

    for (int i = 0; i < 1000; i++) {
      db.put(writeTransaction, Bytes.fromLong(i), Bytes.fromLong(i));
    }
    writeTransaction.commit();
    try (EntryIterator it = db.iterate(env.createReadTransaction()) ){
      long prev = -1;
      while(it.hasNext()) {
        if (prev == -1) {
          prev = Bytes.getLong(it.next().getKey());
        } else {
          long now = Bytes.getLong(it.next().getKey());
          assertThat((prev-1), is(now));
          prev = now;
        }
      }
    }
  }
}


text:
#ifndef QMITK_QmitkAdaptiveRegionGrowingToolGUI_H
#define QMITK_QmitkAdaptiveRegionGrowingToolGUI_H

#include "itkImage.h"
#include "mitkDataStorage.h"
#include "mitkGeometry3D.h"
#include "mitkPointSet.h"

#include "qwidget.h"
#include "ui_QmitkAdaptiveRegionGrowingToolGUIControls.h"

#include <MitkSegmentationUIExports.h>

#include "QmitkToolGUI.h"

#include "mitkAdaptiveRegionGrowingTool.h"

class QmitkStdMultiWidget;
class DataNode;
class QmitkAdaptiveRegionGrowingToolGUIControls;

/*!
*
* \brief QmitkAdaptiveRegionGrowingToolGUI
*
* Adaptive Region Growing View class of the segmentation.
*
*/

class MITKSEGMENTATIONUI_EXPORT QmitkAdaptiveRegionGrowingToolGUI : public QmitkToolGUI
{
  Q_OBJECT

public:
  /**
   * @brief mitkClassMacro
   */
  mitkClassMacro(QmitkAdaptiveRegionGrowingToolGUI, QmitkToolGUI);

  itkFactorylessNewMacro(Self) itkCloneMacro(Self)

    QmitkAdaptiveRegionGrowingToolGUI(QWidget *parent = 0);

  /** \brief Method to create the connections for the component. This Method is obligatory even if no connections is
   * needed*/
  virtual void CreateConnections();

  ///** \brief Method to set the default data storage.*/
  virtual void SetDataStorage(mitk::DataStorage *dataStorage);

  /**
   * @brief Method to set the used multiwidget.
   * @param multiWidget
   */
  void SetMultiWidget(QmitkStdMultiWidget *multiWidget);

  /**
   * @brief Method to set the name of a data node.
   * @param labledSegmentation Name of the labeled segmentation
   * @param binaryImage Name of the binary image
   * @param surface Name of the surface
   */
  void SetDataNodeNames(std::string labledSegmentation,
                        std::string binaryImage,
                        /*std::string vesselTree,*/ std::string surface,
                        std::string maskedSegmentation);

  /**
   * @brief Method to enable/disable controls for region growing
   *
   * This method checks if a seed point is set and a segmentation exists.
   * @param enable/disable controls
   */
  void EnableControls(bool enable);

  /**
   * @brief Method to set the input image node
   * @param data node
   */
  void SetInputImageNode(mitk::DataNode *node);

  void Deactivated();
  void Activated();

  /**
  * @brief The created GUI from the .ui-File. This Attribute is obligatory
  */
  Ui::QmitkAdaptiveRegionGrowingToolGUIControls m_Controls;

protected slots:

  /**
   * @brief Method to start the segmentation
   *
   * This method is called, when the "Start Segmentation" button is clicked.
   */
  void RunSegmentation();

  /**
   * @brief Method to change the level window
   *
   * This method is called, when the level window slider is changed via the slider in the control widget
   * @param new value
   */
  void ChangeLevelWindow(double newValue);

  /**
   * @brief Method to increase the preview slider
   *
   * This method is called, when the + button is clicked and increases the value by 1
   */
  void IncreaseSlider();

  /**
   * @brief Method to decrease the preview slider
   *
   * This method is called, when the - button is clicked and decreases the value by 1
   */
  void DecreaseSlider();

  /**
   * @brief Method to confirm the preview segmentation
   *
   * This method is called, when the "Confirm Segmentation" button is clicked.
   */
  void ConfirmSegmentation();

  /**
   * @brief Method to switch the volume rendering on/off
   * @param on/off
   */
  void UseVolumeRendering(bool on);

  /**
   * @brief Method to set the lower threshold
   *
   * This method is called, when the minimum threshold slider has changed
   * @param lower threshold
   */
  void SetLowerThresholdValue(double lowerThreshold);

  /**
   * @brief Method to set upper threshold
   *
   * This Method is called, when the maximum threshold slider has changed
   * @param upper threshold
   */
  void SetUpperThresholdValue(double upperThreshold);

  /**
   * @brief Method to determine which tool to activate
   *
   * This method listens to the tool manager and activates this tool if requested otherwise disables this view
   */
  void OnNewToolAssociated(mitk::Tool *);

protected:
  mitk::AdaptiveRegionGrowingTool::Pointer m_RegionGrow3DTool;

  /** \brief Destructor. */
  virtual ~QmitkAdaptiveRegionGrowingToolGUI();

  // Pointer to the main widget to be able to reach the renderer
  QmitkStdMultiWidget *m_MultiWidget;

  mitk::DataStorage *m_DataStorage;

  mitk::DataNode::Pointer m_InputImageNode;

  /**
   * @brief Method to calculate parameter settings, when a seed point is set
   */
  void OnPointAdded();

private:
  std::string m_NAMEFORORGIMAGE;
  std::string m_NAMEFORLABLEDSEGMENTATIONIMAGE;
  std::string m_NAMEFORBINARYIMAGE;
  std::string m_NAMEFORSURFACE;
  std::string m_NAMEFORMASKEDSEGMENTATION;

  mitk::ScalarType m_LOWERTHRESHOLD; // Hounsfield value
  mitk::ScalarType m_UPPERTHRESHOLD; // Hounsfield value
  mitk::ScalarType m_SeedPointValueMean;

  void RemoveHelperNodes();

  int m_DetectedLeakagePoint;

  bool m_CurrentRGDirectionIsUpwards; // defines fixed threshold (true = LOWERTHRESHOLD fixed, false = UPPERTHRESHOLD
                                      // fixed)

  int m_SeedpointValue;
  bool m_SliderInitialized;
  bool m_UseVolumeRendering;
  bool m_UpdateSuggestedThreshold;
  float m_SuggestedThValue;

  long m_PointSetAddObserverTag;
  long m_PointSetMoveObserverTag;

  template <typename TPixel, unsigned int VImageDimension>
  void StartRegionGrowing(itk::Image<TPixel, VImageDimension> *itkImage,
                          mitk::BaseGeometry *imageGeometry,
                          mitk::PointSet::PointType seedPoint);

  template <typename TPixel, unsigned int VImageDimension>
  void ITKThresholding(itk::Image<TPixel, VImageDimension> *inputImage);

  void InitializeLevelWindow();

  void EnableVolumeRendering(bool enable);

  void UpdateVolumeRenderingThreshold(int thValue);
};

#endif


text:
import { Directive, ElementRef, Input } from '@angular/core';
import { Destroy } from '@deja-js/component/core';
import { Position, Rect } from '@deja-js/component/core/graphics';
import { filter, fromEvent, map, mergeWith, Observable, of, Subject, switchMap, take, takeUntil, tap } from 'rxjs';

import { IDragCursorInfos } from './mouse-drag-cursor-infos.interface';
import { DejaMouseDragDropService } from './mouse-dragdrop.service';
import { IDragDropContext } from './mouse-dragdrop-context.interface';

@Directive({
    selector: '[deja-mouse-draggable]'
})
export class DejaMouseDraggableDirective extends Destroy {
    private _context: IDejaMouseDraggableContext;

    @Input('deja-mouse-draggable')
    public set context(value: IDejaMouseDraggableContext) {
        this._context = value;
    }

    public get context(): IDejaMouseDraggableContext {
        return this._context;
    }

    public constructor(elementRef: ElementRef, dragDropService: DejaMouseDragDropService) {
        super();

        const element = elementRef.nativeElement as HTMLElement;

        const mouseLeaveEvent$ = fromEvent<MouseEvent>(element, 'mouseleave');
        const mouseEnterEvent$ = fromEvent<MouseEvent>(element, 'mouseenter');
        const mouseUpEvent$ = fromEvent<MouseEvent>(element.ownerDocument, 'mouseup');
        const mouseDownEvent$ = fromEvent<MouseEvent>(element, 'mousedown');
        const mouseMoveEvent$ = fromEvent<MouseEvent>(element.ownerDocument, 'mousemove');

        mouseEnterEvent$.pipe(
            filter(() => !dragDropService.isDragging),
            switchMap(() => mouseDownEvent$.pipe(
                filter(event => event.buttons === 1),
                // eslint-disable-next-line rxjs/no-unsafe-takeuntil
                takeUntil(mouseLeaveEvent$),
                switchMap(event => {
                    let target: HTMLElement;

                    const match = (el: HTMLElement): boolean => el.tagName === this.context.target.toUpperCase() || el.id === this.context.target.substr(1) || el.hasAttribute(this.context.target.substring(1, this.context.target.length - 1));

                    if (this.context) {
                        if (this.context.target) {
                            target = event.target as HTMLElement;
                            // eslint-disable-next-line no-loops/no-loops
                            while (target && !match(target)) {
                                target = target.parentElement;
                            }
                        } else {
                            target = element;
                        }

                        if (target && this.context.dragStart) {
                            // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
                            const dragContext = this.context.dragStart(target);
                            if (dragContext) {
                                // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
                                if (dragContext.subscribe) {
                                    const context$ = dragContext as Observable<IDragDropContext>;
                                    // Observable
                                    return context$.pipe(
                                        take(1),
                                        map((ddctx: IDragDropContext) => {
                                            dragDropService.context = ddctx;
                                            return ddctx && target; // Map to target if ddctx is defined
                                        })
                                    );
                                } else {
                                    // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
                                    dragDropService.context = dragContext;
                                    return of(target);
                                }
                            }
                        }
                    }
                    return of(null as HTMLElement);
                }),
                filter(target => !!target), // Start Drag if target is defined
                switchMap(target => {
                    dragDropService.dragging$.next(true);

                    const moveUp$ = new Subject<void>();

                    const enterWhileNotDragDropEvent$ = mouseEnterEvent$.pipe(
                        filter(event => event.buttons !== 1 && dragDropService.isDragging)
                    );

                    const kill$ = mouseUpEvent$.pipe(
                        mergeWith(enterWhileNotDragDropEvent$, moveUp$),
                        take(1),
                        tap(() => {
                            dragDropService.dragCursor$.next(null);
                            dragDropService.dragging$.next(false);
                        }));

                    return mouseMoveEvent$.pipe(
                        // eslint-disable-next-line rxjs/no-unsafe-takeuntil
                        takeUntil(kill$),
                        tap(ev => {
                            if (target && ev.buttons === 1) {
                                const bounds = new Rect(element.getBoundingClientRect());
                                const position = new Position(ev.pageX, ev.pageY);
                                const html = bounds.containsPoint(position) ? target.innerHTML : undefined;

                                // Post cursor infos to service
                                dragDropService.dragCursor$.next({
                                    position: position,
                                    html: html,
                                    originalHtml: target.innerHTML,
                                    width: target.offsetWidth,
                                    height: target.offsetHeight,
                                    className: this.context.className,
                                    originalEvent: ev
                                } as IDragCursorInfos);

                            } else {
                                moveUp$.next();
                            }

                            // ev.preventDefault();
                            return false;
                        })
                    );
                })
            )),
            takeUntil(this.destroyed$)
        ).subscribe();
    }
}

export interface IDejaMouseDraggableContext {
    target?: string; // Tagname or #id or [attribute]
    className?: string;
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    dragStart?: (element: HTMLElement) => any; // Return object or observable<object>
}


text:
July 24, 2018 17:35:03 Library.fmp12 - newLibraryStep3B_importLibraryIntoEmptiedLibrary -1-
libraryNewOrImport: newLibraryStep3B_importLibraryIntoEmptiedLibrary
#
#
#PURPOSE: This script is step 3B of a three step
#process for creating a copy of the current
#library file for use as a new empty library or
#as an upgrade library file.
#— Admin access required. —
# Step 1) Creates a copy of current library.
#A copy not a clone must be created because some
#records are neccessary to running the Library and
#are removed when cloning the Library.
#— Admin access required. —
# Step 2) When user opens the copy that this
#script creates, the createEmptyLibrary script
#erases the copy's records preparing it to
#become an empty library or an upgrade file
#of the library ready for sharing.
#— Regular user access —
# Step 3 A) Create new library name
#and node records and begin to use the library
#file as a new library, OR B) Import records
#from an older library and use library file as an
#upgrade library file.
#
#
#BEGIN STEP 3B: Upgrade (import) old library.
#
#Admin tasks.
Allow User Abort [ Off ]
Set Error Capture [ On ]
#
#Inform user crashing issue when importing.
Show Custom Dialog [ Message: "On some imports FileMaker crashes. So, makes sure you have a duplicate of this Empty Library
file before proceeding (cancel and duplicate if you don't)."; Default Button: "OK", Commit: "Yes"; Button 2: "cancel", Commit: "No" ]
If [ Get ( LastMessageChoice ) = 2 ]
Show Custom Dialog [ Message: "When you are ready to decide what to do with this empty library re-open it. This library will
now close."; Default Button: "OK", Commit: "Yes" ]
Close Window [ Current Window ]
Exit Script [ ]
End If
Show Custom Dialog [ Message: "Do not be discouraged if FileMaker crashes several times in a row. Eventually, it will work. Always
delete the crashed library, and use a fresh copy for your import."; Default Button: "OK", Commit: "Yes"; Button 2: "cancel", Commit:
"No" ]
If [ Get ( LastMessageChoice ) = 2 ]
Show Custom Dialog [ Message: "When you are ready to decide what to do with this empty library re-open it. This library will
now close."; Default Button: "OK", Commit: "Yes" ]
Close Window [ Current Window ]
Exit Script [ ]
End If
Show Custom Dialog [ Message: "If it does crash, delete the crashed library file, and try again."; Default Button: "OK", Commit: "Yes";
Button 2: "cancel", Commit: "No" ]
If [ Get ( LastMessageChoice ) = 2 ]
Show Custom Dialog [ Message: "When you are ready to decide what to do with this empty library re-open it. This library will
now close."; Default Button: "OK", Commit: "Yes" ]
Close Window [ Current Window ]
Exit Script [ ]
End If
#
#Get path of library that user wants to import
#files from by generating this code and
#cuting it using the computer's clipboard so
#it can be pasted by the library the user is now
#opening (the one they want to import files
#from).
Go to Layout [ "backup" (backup) ]
Delete All Records
[ No dialog ]
New Record/Request
Set Field [ backup::backup; "0update439asdkc;liasdu;irejf.as.dkfupea;lksdfa,sm.eupqoiwendssasdeawsrre5o983498woeirf" ]
#
#Cut instead of copy, saves the step of erasing
#this code from the current file, as the cut
#command both copies and erases the code.
Cut [ backup::backup ]
[ Select ]
Commit Records/Requests
[ Skip data entry validation; No dialog ]
#
#Ask the user what file they want to
#import from. Because it is an (unknown) file,
#the user will be prompted to select this file.
Go to Layout [ "defaultSetup" (aboutLibraryMain) ]
Open File [ <unknown> ]
#
#If the user cancels the file selection process,
#then exit this script, and close the library.
#The library cannot be used until the user
#either imports an old library's records into it
#or sets it up as a new library.
If [ Get (LastError) = 1 ]
Show Custom Dialog [ Message: "When you are ready to decide what to do with this empty library re-open it. This library will
now close."; Default Button: "OK", Commit: "Yes" ]
Close Window [ Current Window ]
Exit Script [ ]
End If
#
#Make sure the file the user selected to import
#from was opened and its filepath copied. If it
#was already open, then this script did not
#open it and its startDatabase script did not
#just run and insert this code, which would
#have resulted in its filepath being copied by
#the computer's clipboard. Thus the
#computer's clipboard will still contain the
#copy-filepath code, instead of the file's
#filepath.
Go to Layout [ "backup" (backup) ]
Paste [ backup::backup ]
[ Select; No style ]
If [ "0update439asdkc;liasdu;irejf.as.dkfupea;lksdfa,sm.eupqoiwendssasdeawsrre5o983498woeirf" = backup::backup ]
#
#Tell the user the import failed and how to
#succeed. Then restart the library to all the
#user to try again.
Show Custom Dialog [ Message: "Close the library whose records you wish to import and try the import process again."; Default
Button: "OK", Commit: "Yes" ]
Set Field [ backup::backup; "" ]
Commit Records/Requests
[ Skip data entry validation; No dialog ]
Perform Script [ "startDatabase" ]
Exit Script [ ]
End If
#
#If the computer's clipboard contains a
#filepath, then proceed with the import.
Set Variable [ $filepath; Value:backup::backup ]
#
#
#1) Import test section records.
Go to Layout [ "tableTestSectionFromTemplate" (testSectionCreatedFromATemplate) ]
Import Records [ Source: "$filepath"; Target: "testSectionCreatedFromATemplate"; Method: Add; Character Set: "Unicode"; Field
Mapping: Source field 1 import to testSectionCreatedFromATemplate::ktestSubjectNode
Source field 2 import to testSectionCreatedFromATemplate::ksectionTemplate
Source field 3 import to testSectionCreatedFromATemplate::_LtestSection
Source field 4 import to testSectionCreatedFromATemplate::name
Source field 5 import to testSectionCreatedFromATemplate::inUse
Source field 6 import to testSectionCreatedFromATemplate::order
Source field 7 import to testSectionCreatedFromATemplate::_number
Source field 8 import to testSectionCreatedFromATemplate::klibrary
Source field 9 import to testSectionCreatedFromATemplate::reportNumber
Source field 10 import to testSectionCreatedFromATemplate::kcreatorNode
Source field 12 import to testSectionCreatedFromATemplate::creationDate
Source field 13 import to testSectionCreatedFromATemplate::creationTime ]
[ No dialog ]
#
#
#2) Import test subsection records.
Go to Layout [ "tableTestSubsectionTemplates" (testSubsectionTemplate) ]
Import Records [ Source: "$filepath"; Target: "testSubsectionTemplate"; Method: Add; Character Set: "Unicode"; Field Mapping:
Source field 1 import to testSubsectionTemplate::_LtestSubsection
Source field 2 import to testSubsectionTemplate::ksubsectionGroup
Source field 3 import to testSubsectionTemplate::_number
Source field 4 import to testSubsectionTemplate::kcsections
Source field 5 import to testSubsectionTemplate::name
Source field 6 import to testSubsectionTemplate::order
Source field 7 import to testSubsectionTemplate::retire
Source field 8 import to testSubsectionTemplate::kgtestSubject
Source field 9 import to testSubsectionTemplate::gtestSectionNameGlobal
Source field 10 import to testSubsectionTemplate::gtestSubjectNameGlobal
Source field 11 import to testSubsectionTemplate::kgtestSection
Source field 12 import to testSubsectionTemplate::gprogressGlobal
Source field 13 import to testSubsectionTemplate::klibrary
Source field 14 import to testSubsectionTemplate::kgreportNumber
Source field 15 import to testSubsectionTemplate::mtestSubsection
Source field 16 import to testSubsectionTemplate::ktestItemGroup
Source field 17 import to testSubsectionTemplate::rule
Source field 18 import to testSubsectionTemplate::kcreatorNode
Source field 19 import to testSubsectionTemplate::kmodifierNode
Source field 20 import to testSubsectionTemplate::RecordModifyDate
Source field 21 import to testSubsectionTemplate::nameSpelling
Source field 22 import to testSubsectionTemplate::form ]
[ No dialog ]
#
#
#3) Import learn and test result records.
Go to Layout [ "tableTestLearn" (testlearn) ]
Import Records [ Source: "$filepath"; Target: "testlearn"; Method: Add; Character Set: "Unicode"; Field Mapping: Source field 1 import
to testlearn::_Ltestlearn
Source field 2 import to testlearn::ktestSubject
Source field 3 import to testlearn::_Number
Source field 4 import to testlearn::ktestSubsection
Source field 5 import to testlearn::note
Source field 6 import to testlearn::picture
Source field 7 import to testlearn::subsectionCustomName
Source field 8 import to testlearn::kcInUseOnReportSubsection
Source field 9 import to testlearn::ktestSection
Source field 10 import to testlearn::countOfALLSubsectionsTestResults
Source field 11 import to testlearn::checkboxCaption
Source field 12 import to testlearn::recordnumberglobal
Source field 13 import to testlearn::recordcountglobal
Source field 14 import to testlearn::countOfONESubsectionsTestResults
Source field 15 import to testlearn::rateORgradeTestResult
Source field 16 import to testlearn::kclibrary
Source field 17 import to testlearn::kshowReferencedMedia
Source field 18 import to testlearn::kreportNumber
Source field 19 import to testlearn::timestamp
Source field 21 import to testlearn::orderTestResult
Source field 22 import to testlearn::kcKeywordOther
Source field 23 import to testlearn::kNodeOther
Source field 24 import to testlearn::kcopyright
Source field 25 import to testlearn::kNodePrimary
Source field 26 import to testlearn::kKeywordPrimary
Source field 27 import to testlearn::OtherKeyWords
Source field 28 import to testlearn::NodeOthers
Source field 29 import to testlearn::URL
Source field 30 import to testlearn::kcreference
Source field 32 import to testlearn::filterFind
Source field 33 import to testlearn::kRecordCreatorNode
Source field 34 import to testlearn::kRecordModifierNode
Source field 35 import to testlearn::dateModify
Source field 36 import to testlearn::incomplete
Source field 38 import to testlearn::copyrightYear
Source field 39 import to testlearn::kcbrainstorm
Source field 40 import to testlearn::kgtestSection
Source field 41 import to testlearn::kctestSubsectionInfo
Source field 42 import to testlearn::orderTestInformation
Source field 43 import to testlearn::kctestResultCheckedItems
Source field 45 import to testlearn::brainstormCasePoint
Source field 48 import to testlearn::pictureThumbnail ]
[ No dialog ]
#
#
#4) Import about library records.
Go to Layout [ "tableAboutLibrary" (aboutLibrary) ]
Import Records [ Source: "$filepath"; Target: "aboutLibrary"; Method: Add; Character Set: "Unicode"; Field Mapping: Source field 1
import to aboutLibrary::_LaboutLibrary
Source field 2 import to aboutLibrary::_Number
Source field 3 import to aboutLibrary::URL
Source field 4 import to aboutLibrary::publicationDate
Source field 5 import to aboutLibrary::kcreatorNode
Source field 6 import to aboutLibrary::name
Source field 7 import to aboutLibrary::password
Source field 8 import to aboutLibrary::klibrary
Source field 9 import to aboutLibrary::version
Source field 13 import to aboutLibrary::creatorName
Source field 14 import to aboutLibrary::note ]
[ No dialog ]
#
#
#5) Import tag records.
Go to Layout [ "tableTag" (tagTable) ]
Import Records [ Source: "$filepath"; Target: "tagTable"; Method: Add; Character Set: "Unicode"; Field Mapping: Source field 1 import
to tagTable::kGroupOrTest
Source field 2 import to tagTable::_Ltag
Source field 3 import to tagTable::tag
Source field 4 import to tagTable::orderOrLock
Source field 5 import to tagTable::textStyleOrCreatorNodeFlag
Source field 6 import to tagTable::_Number
Source field 7 import to tagTable::match
Source field 8 import to tagTable::tagSpelling
Source field 9 import to tagTable::Kpicture1
Source field 10 import to tagTable::notesOrCopyright
Source field 11 import to tagTable::Ktitle1
Source field 12 import to tagTable::kfileORkTestItemCreatorNode
Source field 14 import to tagTable::Kpicture2
Source field 16 import to tagTable::Kpicture3
Source field 18 import to tagTable::Ktitle2
Source field 19 import to tagTable::Ktitle3
Source field 23 import to tagTable::kRecordCreatorNode
Source field 24 import to tagTable::notesForKeyandNodeTags ]
[ No dialog ]
#
#
#6) Import tag group records.
Go to Layout [ "tableTagGroup" (testSubsectionGroup) ]
Import Records [ Source: "$filepath"; Target: "testSubsectionGroup"; Method: Add; Character Set: "Unicode"; Field Mapping: Source
field 1 import to testSubsectionGroup::_Lgroup
Source field 2 import to testSubsectionGroup::_Number
Source field 3 import to testSubsectionGroup::match
Source field 4 import to testSubsectionGroup::name
Source field 5 import to testSubsectionGroup::klibrary
Source field 6 import to testSubsectionGroup::nameSpellingFORTestItemGroup
Source field 7 import to testSubsectionGroup::testReportPicture
Source field 8 import to testSubsectionGroup::ReportCaptionORLibraryCreatorName
Source field 9 import to testSubsectionGroup::URLOrCopyrightORUserLibraryVersion
Source field 10 import to testSubsectionGroup::orderOrLibraryType
Source field 11 import to testSubsectionGroup::nameSpellingEXCEPTForTestItemGroup
Source field 12 import to testSubsectionGroup::kRecordCreatorNode
Source field 13 import to testSubsectionGroup::versionNumber ]
[ No dialog ]
#
#
#7) Import reference records.
#Make sure no locked reference copyright
#records are currently found, so that after the
#import when locked records are deleted, they
#are duplicates from the just imported library.
Go to Layout [ "tableReference" (reference) ]
Omit Multiple Records [ 999 ]
[ No dialog ]
Import Records [ Source: "$filepath"; Target: "reference"; Method: Add; Character Set: "Unicode"; Field Mapping: Source field 1 import
to reference::_Number
Source field 2 import to reference::_Lreference
Source field 3 import to reference::ktestSubject
Source field 4 import to reference::ktest
Source field 5 import to reference::kclibrary
Source field 6 import to reference::knodePrimary
Source field 7 import to reference::publicationYearOrStuffOrderNumber
Source field 8 import to reference::URL
Source field 9 import to reference::URLdate
Source field 10 import to reference::Title
Source field 11 import to reference::kpublication
Source field 12 import to reference::volumeNumber
Source field 13 import to reference::PubDate
Source field 14 import to reference::pageNumberRange
Source field 15 import to reference::kpublisher
Source field 16 import to reference::OrginalCitation
Source field 17 import to reference::kcopyrightType
Source field 18 import to reference::kCopyright
Source field 19 import to reference::kmedium
Source field 20 import to reference::kkeywordOther
Source field 21 import to reference::kkeywordPrimary
Source field 22 import to reference::thoughtsNotesEtc
Source field 23 import to reference::kfolderpath
Source field 24 import to reference::fileName
Source field 26 import to reference::referenceNodes
Source field 27 import to reference::CopyrightYear
Source field 28 import to reference::kcopyrightHolder
Source field 29 import to reference::referenceDump
Source field 30 import to reference::knodeOther
Source field 31 import to reference::NodeOthers
Source field 32 import to reference::OtherKeyWords
Source field 33 import to reference::referenceNodesOLD
Source field 34 import to reference::filterFind
Source field 35 import to reference::picture
Source field 36 import to reference::kfileLocation
Source field 37 import to reference::rights
Source field 38 import to reference::mFileFolderMainXorOther
Source field 39 import to reference::kcitation
Source field 40 import to reference::incomplete
Source field 41 import to reference::lock
Source field 43 import to reference::kcreatorNode
Source field 44 import to reference::kmodifierNode
Source field 45 import to reference::modifyDate
Source field 47 import to reference::TimeRange
Source field 48 import to reference::createDate
Source field 49 import to reference::showInLearn
Source field 50 import to reference::publicLibraryLinks
Source field 51 import to reference::DOI
Source field 52 import to reference::issueNumber
Source field 53 import to reference::publisherLocation
Source field 54 import to reference::publicationTitle
Source field 55 import to reference::compilationEditors
Source field 56 import to reference::kisWhat
Source field 57 import to reference::kisON
Source field 58 import to reference::compilationNumberOfEditors
Source field 59 import to reference::publicationYearMonthRange
Source field 60 import to reference::ISBN
Source field 61 import to reference::pubDateOther
Source field 62 import to reference::bookChapter
Source field 63 import to reference::letterDate
Source field 64 import to reference::compilationAbbr
Source field 65 import to reference::emailRecipient
Source field 66 import to reference::conferenceIntroWords
Source field 67 import to reference::conferenceTitle
Source field 68 import to reference::conferenceSubTitle
Source field 69 import to reference::conferenceLocation
Source field 70 import to reference::conferenceDate
Source field 71 import to reference::otherIsOn
Source field 72 import to reference::GovernmentDocInfo
Source field 73 import to reference::governmentAuthor
Source field 74 import to reference::ISSN
Source field 75 import to reference::publisherTypeAlternative
Source field 76 import to reference::copyrightOtherHolder
Source field 77 import to reference::publisherTypeOther
Source field 78 import to reference::pageNumberOther
Source field 79 import to reference::dissertationThesisUniversity
Source field 83 import to reference::showMedia
Source field 84 import to reference::showMediaCode
Source field 85 import to reference::PictureFileSize
Source field 87 import to reference::pictureSourceSpeedLimit
Source field 88 import to reference::pictureThumbnail
Source field 91 import to reference::otherIsWhat ]
[ No dialog ]
#
#Now delete the imported lock copyright
#records, to insure the latests locked
#copyright records already in this file remain
#the only ones.
If [ Get (FoundCount) ≠ 0 ]
Sort Records [ Keep records in sorted order; Specified Sort Order: reference::lock; descending ]
[ Restore; No dialog ]
Go to Record/Request/Page
[ First ]
Loop
If [ reference::lock = "lock" ]
Delete Record/Request
[ No dialog ]
End If
Exit Loop If [ reference::lock ≠ "lock" ]
Exit Loop If [ Get (FoundCount) = 0 ]
End Loop
End If
#
#
#8) Import report records.
Go to Layout [ "tableReport" (report) ]
Import Records [ Source: "$filepath"; Target: "report"; Method: Add; Character Set: "Unicode"; Field Mapping: Source field 1 import to
report::_Lreport
Source field 2 import to report::_Number
Source field 3 import to report::ktestSubject
Source field 4 import to report::kTestSubjectSection
Source field 5 import to report::general_info
Source field 6 import to report::ktestSubsection
Source field 7 import to report::kRecommendation1
Source field 8 import to report::order
Source field 9 import to report::Picture
Source field 10 import to report::kRecommendation2
Source field 11 import to report::kgeneralSpecificItemRecommendationID
Source field 12 import to report::kTag1
Source field 13 import to report::kTestSubjectSection2
Source field 14 import to report::kTestSubjectSection3
Source field 15 import to report::kTestSubjectSection4
Source field 16 import to report::kTestSubjectSection5
Source field 17 import to report::PictureCaptionInsteadOfPicture
Source field 18 import to report::note
Source field 19 import to report::textPhotoRow1
Source field 20 import to report::pagenumberItem
Source field 21 import to report::CurrentRecord
Source field 22 import to report::kTag2
Source field 23 import to report::kTag3
Source field 24 import to report::kTag4
Source field 25 import to report::pagenumberTheme
Source field 26 import to report::TOC
Source field 27 import to report::TOCnumbers
Source field 28 import to report::ReportCover
Source field 29 import to report::ReportPDFtitle
Source field 30 import to report::kreportNumber
Source field 31 import to report::klibrary
Source field 32 import to report::kRecordCreatorNode
Source field 33 import to report::kRecordModifierNode
Source field 34 import to report::RecordModifyDate
Source field 35 import to report::kcopyright
Source field 36 import to report::textPhotoRow2 ]
[ No dialog ]
#
#
#9) Import TEMP records.
Go to Layout [ "tableTemp" (TEMP) ]
Show All Records
Delete All Records
[ No dialog ]
Import Records [ Source: "$filepath"; Target: "TEMP"; Method: Add; Character Set: "Unicode"; Field Mapping: Source field 1 import to
TEMP::theme
Source field 2 import to TEMP::klibrary
Source field 3 import to TEMP::userLibraryName
Source field 4 import to TEMP::testSubsectionNameForSubject
Source field 5 import to TEMP::orderLocation
Source field 6 import to TEMP::orderMod1
Source field 7 import to TEMP::orderMod2
Source field 8 import to TEMP::reportNumber
Source field 9 import to TEMP::ktestItemSubsection
Source field 10 import to TEMP::ktestItemSubsectionOLD
Source field 11 import to TEMP::TimeStamp
Source field 12 import to TEMP::ktestSection
Source field 13 import to TEMP::ktestSubsection
Source field 14 import to TEMP::showFavorites
Source field 15 import to TEMP::kabout
Source field 16 import to TEMP::mtestSubsection
Source field 17 import to TEMP::DeleteMessageInTempWindow1
Source field 18 import to TEMP::mSwitch
Source field 19 import to TEMP::pageNumber
Source field 21 import to TEMP::import
Source field 22 import to TEMP::theme Copy
Source field 23 import to TEMP::newEvidenceListWindow
Source field 24 import to TEMP::EvidenceItemNameAndNumber
Source field 25 import to TEMP::sortKey
Source field 26 import to TEMP::sortNode
Source field 27 import to TEMP::sortPublisher
Source field 28 import to TEMP::sortMedium
Source field 29 import to TEMP::sortPath
Source field 30 import to TEMP::tagName
Source field 31 import to TEMP::testSubsectionName
Source field 32 import to TEMP::sortPublication
Source field 33 import to TEMP::sortCopyright
Source field 34 import to TEMP::sortCite
Source field 35 import to TEMP::layoutRtagN
Source field 36 import to TEMP::layoutRtagK
Source field 37 import to TEMP::layoutLtagK
Source field 38 import to TEMP::layoutLtagN
Source field 39 import to TEMP::sortRef
Source field 40 import to TEMP::DetailmoreORLessLayout
Source field 41 import to TEMP::kdefaultNodePrimary
Source field 42 import to TEMP::kdefaultCopyright
Source field 43 import to TEMP::kdefaultNodeOther
Source field 44 import to TEMP::DEFAULTNodeOtherNames
Source field 46 import to TEMP::DefaultmoreORLessLayoutNode
Source field 47 import to TEMP::layoutLmain
Source field 48 import to TEMP::sortBrainstorm
Source field 49 import to TEMP::tempListNode
Source field 50 import to TEMP::TLBrainstormSort
Source field 51 import to TEMP::TLTestSort
Source field 52 import to TEMP::sortTestSubsection
Source field 53 import to TEMP::kdefaultNodeTestSubject
Source field 55 import to TEMP::sortTestSection
Source field 56 import to TEMP::pulldownAttribute
Source field 57 import to TEMP::testHideFormTextItemsFTs
Source field 58 import to TEMP::userLocationName
Source field 59 import to TEMP::kctagTest
Source field 61 import to TEMP::mtestSection
Source field 62 import to TEMP::kcsubsectionSections
Source field 63 import to TEMP::sortTestItem
Source field 64 import to TEMP::mTestItemGroup
Source field 65 import to TEMP::addTestItemGroup
Source field 66 import to TEMP::ktestSubsectionName
Source field 67 import to TEMP::filePathLibraryToSwitchTo
Source field 68 import to TEMP::DEFAULTNodePrimaryName
Source field 69 import to TEMP::textORcheck
Source field 70 import to TEMP::mTag
Source field 71 import to TEMP::duplicateOtherKeywords
Source field 72 import to TEMP::kcbrainstorm
Source field 74 import to TEMP::primaryNodeIsLocked
Source field 75 import to TEMP::nodeLockedShow
Source field 76 import to TEMP::paste
Source field 77 import to TEMP::mCopyright
Source field 79 import to TEMP::Help
Source field 80 import to TEMP::helpName
Source field 81 import to TEMP::InventoryLibraryYN
Source field 82 import to TEMP::DEFAULTNodeTestSubjectName
Source field 83 import to TEMP::Message
Source field 84 import to TEMP::layoutLtagR
Source field 85 import to TEMP::layoutLtagL
Source field 86 import to TEMP::ReferenceFolder
Source field 88 import to TEMP::HelpRepetitionNumber
Source field 89 import to TEMP::HelpMessage
Source field 92 import to TEMP::textDateIntialTime
Source field 93 import to TEMP::DEFAULTSectionName
Source field 94 import to TEMP::kdefaultSectionTemplate
Source field 95 import to TEMP::passwordCheck
Source field 96 import to TEMP::userLibraryMainOrBranch
Source field 97 import to TEMP::DEFAULTprimaryNodeCopyrightGroup
Source field 98 import to TEMP::kdefaultTestSubjectCopyright
Source field 99 import to TEMP::ReferenceDump
Source field 100 import to TEMP::kdefaultNodePrimaryCreator
Source field 101 import to TEMP::primaryNodesCreatorNodeIsLocked
Source field 103 import to TEMP::copyrightCreatorsName
Source field 104 import to TEMP::testSubjectNodeIsLocked
Source field 105 import to TEMP::testSubsectionHideTextItems
Source field 106 import to TEMP::DeleteMessageInTempWindow2
Source field 107 import to TEMP::layoutTmain
Source field 109 import to TEMP::testAndReportMainWindowHeader
Source field 110 import to TEMP::testItemMenuShowTheWordLock
Source field 111 import to TEMP::userLibraryVersionNumber ]
[ No dialog ]
#
#
#Erase codes that trigger new
#library creation script steps.
Go to Layout [ "backup" (backup) ]
Delete All Records
[ No dialog ]
New Record/Request
Set Field [ backup::backup; "" ]
Set Field [ backup::newLibrary; "" ]
#
#Complete import by restarting the library,
#loading up the imported data, telling the
#user to pick themselves as the primary node,
#and to select the copyright for new records.
# This variable will trigger these final steps
#found at the end of startDatabase script.
Set Variable [ $$import; Value:1 ]
Perform Script [ "startDatabase" ]
#
#END STEP 3B: Upgrade (import) old library.
#
#


text:
package com.guitar.db;

import static org.junit.Assert.assertEquals;

import java.util.Date;
import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.guitar.db.model.Manufacturer;
import com.guitar.db.repository.ManufacturerJpaRepository;
import com.guitar.db.repository.ManufacturerRepository;

@ContextConfiguration(locations={"classpath:com/guitar/db/applicationTests-context.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class ManufacturerPersistenceTests {
	@Autowired
	private ManufacturerRepository manufacturerRepository;

	@Autowired
	private ManufacturerJpaRepository manufacturerJpaRepository;

	@Test
	public void testGetManufacturersFoundedBeforeDate() throws Exception {
		List<Manufacturer> mans = manufacturerRepository.getManufacturersFoundedBeforeDate(new Date());
		assertEquals(2, mans.size());
	}

	@Test
	public void testGetManufacturersJpaFoundedBeforeDate() throws Exception {
		List<Manufacturer> mans = manufacturerJpaRepository.findByFoundedDateBefore(new Date());
		assertEquals(2, mans.size());
	}

	@Test
	public void testGetManufactureByName() throws Exception {
		Manufacturer m = manufacturerRepository.getManufacturerByName("Fender");
		assertEquals("Fender Musical Instruments Corporation", m.getName());
	}

	@Test
	public void testGetManufacturersThatSellModelsOfType() throws Exception {
		List<Manufacturer> mans = manufacturerRepository.getManufacturersThatSellModelsOfType("Semi-Hollow Body Electric");
		assertEquals(1, mans.size());
	}
}


text:
package se.l4.silo.index.basic;

import org.eclipse.collections.api.list.ListIterable;

import se.l4.silo.index.FieldLimit;
import se.l4.silo.index.FieldSort;
import se.l4.silo.index.FieldSortBuilder;
import se.l4.silo.index.LimitableQuery;
import se.l4.silo.index.Matcher;
import se.l4.silo.index.Query;
import se.l4.silo.internal.BasicIndexQueryImpl;

/**
 * Simple query abilities that run on top of indexed fields.
 *
 * @param <T>
 */
public interface BasicIndexQuery<T>
	extends Query<T, T, BasicIndexResult<T>>, LimitableQuery
{
	/**
	 * Get fields that are being limited.
	 *
	 * @return
	 */
	ListIterable<FieldLimit<?>> getLimits();

	/**
	 * Get fields that are being sorted on.
	 *
	 * @return
	 */
	ListIterable<FieldSort> getSortOrder();

	/**
	 * Get if the default sort is ascending or not.
	 *
	 * @return
	 */
	boolean isAscendingDefaultSort();

	/**
	 * Start building a new query on field index.
	 *
	 * @param <T>
	 *   type to query
	 * @param index
	 *   name of the index being queried
	 * @param type
	 *   reference to the type being queried
	 * @return
	 *   builder for query
	 */
	static <T> Builder<T> create(String index, Class<T> type)
	{
		return BasicIndexQueryImpl.create(index);
	}

	/**
	 * Builder used to create queries on standard field indexes.
	 */
	interface Builder<T>
		extends LimitableQuery.Builder<Builder<T>>
	{
		/**
		 * Add a pre-built {@link FieldLimit} to this query.
		 *
		 * @param limit
		 * @return
		 */
		Builder<T> add(FieldLimit<?> limit);

		/**
		 * Limit the given field in a fluent way.
		 *
		 * @param name
		 *   the name of the field
		 * @return
		 *   builder that can be used to define how the field is to be
		 *   matched
		 */
		BasicFieldLimitBuilder<Builder<T>, Object> field(String name);

		/**
		 * Limit the given field in a fluent way.
		 *
		 * @param field
		 *   the field to limit
		 * @return
		 *   builder that can be used to define how the field is to be
		 *   matched
		 */
		<V> BasicFieldLimitBuilder<Builder<T>, V> field(BasicFieldRef<V> field);

		/**
		 * Limit the given field using a pre-built matcher.
		 *
		 * @param name
		 *   the name of the field
		 * @param matcher
		 *   the matcher that should be used to limit the field
		 * @return
		 *   copy of builder with field limit added
		 */
		Builder<T> field(String name, Matcher<?> matcher);

		/**
		 * Limit the given field using a pre-built matcher.
		 *
		 * @param field
		 *   the field to limit
		 * @param matcher
		 *   the matcher that should be used to limit the field
		 * @return
		 *   copy of builder with field limit added
		 */
		<V> Builder<T> field(BasicFieldRef<V> field, Matcher<V> matcher);

		/**
		 * Sort on the given field, specifying ascending or descending order
		 * in a fluent way.
		 *
		 * @param name
		 *   the name of the field
		 * @return
		 *   builder that can be used to define the sort order
		 */
		FieldSortBuilder<Builder<T>> sort(String name);

		/**
		 * Sort on the given field and direction.
		 *
		 * @param sort
		 * @return
		 */
		Builder<T> sort(FieldSort sort);

		/**
		 * Indicate the default sort should be reversed.
		 *
		 * @return
		 */
		Builder<T> defaultSort(boolean ascending);

		/**
		 * Build instance of {@link BasicIndexQuery}.
		 *
		 * @return
		 */
		BasicIndexQuery<T> build();
	}
}


text:
<?php

namespace PaulMaxwell\StudentsAccountingBundle\Entity;

use Doctrine\ORM\Mapping;

/**
 * @Mapping\Entity
 * @Mapping\Table(name="ls_person")
 */
class Person
{

    /**
     * @Mapping\Column(type="integer")
     * @Mapping\Id
     * @Mapping\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @Mapping\Column(name="name_last", type="string", length=64)
     */
    protected $nameLast;

    /**
     * @Mapping\Column(name="name_first", type="string", length=64)
     */
    protected $nameFirst;

    /**
     * @Mapping\Column(name="name_patronymic", type="string", length=64)
     */
    protected $namePatronymic;

    /**
     * @Mapping\Column(name="date_of_birth", type="date")
     */
    protected $dateOfBirth;

    /**
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param \DateTime $dateOfBirth
     */
    public function setDateOfBirth($dateOfBirth)
    {
        $this->dateOfBirth = $dateOfBirth;
    }

    /**
     * @return \DateTime
     */
    public function getDateOfBirth()
    {
        return $this->dateOfBirth;
    }

    /**
     * @param string $nameFirst
     */
    public function setNameFirst($nameFirst)
    {
        $this->nameFirst = $nameFirst;
    }

    /**
     * @return string
     */
    public function getNameFirst()
    {
        return $this->nameFirst;
    }

    /**
     * @param string $nameLast
     */
    public function setNameLast($nameLast)
    {
        $this->nameLast = $nameLast;
    }

    /**
     * @return string
     */
    public function getNameLast()
    {
        return $this->nameLast;
    }

    /**
     * @param string $namePatronymic
     */
    public function setNamePatronymic($namePatronymic)
    {
        $this->namePatronymic = $namePatronymic;
    }

    /**
     * @return string
     */
    public function getNamePatronymic()
    {
        return $this->namePatronymic;
    }

}


text:
import json

from .test_base import Base, BaseTestCase
from .test_fixtures import Account

from .resource import CollectionResource, SingleResource

class AccountCollectionResource(CollectionResource):
    model = Account
    default_sort = ['id']

class AccountResource(SingleResource):
    model = Account

class GetOnlyAccountCollectionResource(CollectionResource):
    model   = Account
    methods = ['GET']

class GetOnlyAccountResource(SingleResource):
    model   = Account
    methods = ['GET']

class PostOnlyAccountCollectionResource(CollectionResource):
    model   = Account
    methods = ['POST']

class PostOnlyAccountResource(SingleResource):
    model   = Account
    methods = ['POST']

class PutOnlyAccountCollectionResource(CollectionResource):
    model   = Account
    methods = ['PUT']

class PutOnlyAccountResource(SingleResource):
    model   = Account
    methods = ['PUT']

class PatchOnlyAccountCollectionResource(CollectionResource):
    model   = Account
    methods = ['PATCH']

class PatchOnlyAccountResource(SingleResource):
    model   = Account
    methods = ['PATCH']

class DeleteOnlyAccountCollectionResource(CollectionResource):
    model   = Account
    methods = ['DELETE']

class DeleteOnlyAccountResource(SingleResource):
    model   = Account
    methods = ['DELETE']

class MethodTest(BaseTestCase):
    def create_test_resources(self):
        self.app.add_route('/accounts', AccountCollectionResource(self.db_engine))
        self.app.add_route('/accounts/{id}', AccountResource(self.db_engine))
        self.app.add_route('/getonly-accounts', GetOnlyAccountCollectionResource(self.db_engine))
        self.app.add_route('/getonly-accounts/{id}', GetOnlyAccountResource(self.db_engine))
        self.app.add_route('/postonly-accounts', PostOnlyAccountCollectionResource(self.db_engine))
        self.app.add_route('/postonly-accounts/{id}', PostOnlyAccountResource(self.db_engine))
        self.app.add_route('/putonly-accounts', PutOnlyAccountCollectionResource(self.db_engine))
        self.app.add_route('/putonly-accounts/{id}', PutOnlyAccountResource(self.db_engine))
        self.app.add_route('/patchonly-accounts', PatchOnlyAccountCollectionResource(self.db_engine))
        self.app.add_route('/patchonly-accounts/{id}', PatchOnlyAccountResource(self.db_engine))
        self.app.add_route('/deleteonly-accounts', DeleteOnlyAccountCollectionResource(self.db_engine))
        self.app.add_route('/deleteonly-accounts/{id}', DeleteOnlyAccountResource(self.db_engine))

    def test_get(self):
        response, = self.simulate_request('/accounts', method='POST', body=json.dumps({'id': 1, 'name': 'Bob'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertCreated(response)

        response, = self.simulate_request('/accounts', method='GET', headers={'Accept': 'application/json'})
        self.assertOK(response, {'data': [{'id': 1, 'name': 'Bob', 'owner': None}]})
        response, = self.simulate_request('/accounts/1', method='GET', headers={'Accept': 'application/json'})
        self.assertOK(response, {'data': {'id': 1, 'name': 'Bob', 'owner': None}})

        response, = self.simulate_request('/getonly-accounts', method='GET', headers={'Accept': 'application/json'})
        self.assertOK(response, {'data': [{'id': 1, 'name': 'Bob', 'owner': None}]})
        response, = self.simulate_request('/getonly-accounts/1', method='GET', headers={'Accept': 'application/json'})
        self.assertOK(response, {'data': {'id': 1, 'name': 'Bob', 'owner': None}})

        response = self.simulate_request('/postonly-accounts', method='GET', headers={'Accept': 'application/json'})
        self.assertMethodNotAllowed(response)
        response = self.simulate_request('/postonly-accounts/1', method='GET', headers={'Accept': 'application/json'})
        self.assertMethodNotAllowed(response)

        response = self.simulate_request('/putonly-accounts', method='GET', headers={'Accept': 'application/json'})
        self.assertMethodNotAllowed(response)
        response = self.simulate_request('/putonly-accounts/1', method='GET', headers={'Accept': 'application/json'})
        self.assertMethodNotAllowed(response)

        response = self.simulate_request('/patchonly-accounts', method='GET', headers={'Accept': 'application/json'})
        self.assertMethodNotAllowed(response)
        response = self.simulate_request('/patchonly-accounts/1', method='GET', headers={'Accept': 'application/json'})
        self.assertMethodNotAllowed(response)

        response = self.simulate_request('/deleteonly-accounts', method='GET', headers={'Accept': 'application/json'})
        self.assertMethodNotAllowed(response)
        response = self.simulate_request('/deleteonly-accounts/1', method='GET', headers={'Accept': 'application/json'})
        self.assertMethodNotAllowed(response)

    def test_post(self):
        response, = self.simulate_request('/accounts', method='POST', body=json.dumps({'id': 1, 'name': 'Bob'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertCreated(response)
        response = self.simulate_request('/accounts/1', method='POST', body=json.dumps({'id': 1, 'name': 'Bob'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertMethodNotAllowed(response)
        response = self.simulate_request('/getonly-accounts', method='POST', body=json.dumps({'id': 3, 'name': 'Jack'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertMethodNotAllowed(response)
        response = self.simulate_request('/getonly-accounts/1', method='POST', body=json.dumps({'id': 3, 'name': 'Jack'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertMethodNotAllowed(response)
        response, = self.simulate_request('/postonly-accounts', method='POST', body=json.dumps({'id': 2, 'name': 'Jim'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertCreated(response)
        response = self.simulate_request('/postonly-accounts/1', method='POST', body=json.dumps({'id': 2, 'name': 'Jim'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertMethodNotAllowed(response)
        response = self.simulate_request('/putonly-accounts', method='POST', body=json.dumps({'id': 3, 'name': 'Jack'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertMethodNotAllowed(response)
        response = self.simulate_request('/putonly-accounts/1', method='POST', body=json.dumps({'id': 3, 'name': 'Jack'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertMethodNotAllowed(response)
        response = self.simulate_request('/patchonly-accounts', method='POST', body=json.dumps({'id': 3, 'name': 'Jack'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertMethodNotAllowed(response)
        response = self.simulate_request('/patchonly-accounts/1', method='POST', body=json.dumps({'id': 3, 'name': 'Jack'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertMethodNotAllowed(response)
        response = self.simulate_request('/deleteonly-accounts', method='POST', body=json.dumps({'id': 3, 'name': 'Jack'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertMethodNotAllowed(response)
        response = self.simulate_request('/deleteonly-accounts/1', method='POST', body=json.dumps({'id': 3, 'name': 'Jack'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertMethodNotAllowed(response)

        response, = self.simulate_request('/accounts', method='GET', headers={'Accept': 'application/json'})
        self.assertOK(response, {'data': [{'id': 1, 'name': 'Bob', 'owner': None}, {'id': 2, 'name': 'Jim', 'owner': None}]})
        response, = self.simulate_request('/accounts/1', method='GET', headers={'Accept': 'application/json'})
        self.assertOK(response, {'data': {'id': 1, 'name': 'Bob', 'owner': None}})

    def test_put(self):
        response, = self.simulate_request('/accounts', method='POST', body=json.dumps({'id': 1, 'name': 'Bob'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertCreated(response)

        response = self.simulate_request('/accounts', method='PUT', body=json.dumps({'id': 1, 'name': 'Bob'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertMethodNotAllowed(response)
        response = self.simulate_request('/accounts/1', method='PUT', body=json.dumps({'id': 1, 'name': 'Jim'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertOK(response)

        response, = self.simulate_request('/accounts/1', method='GET', headers={'Accept': 'application/json'})
        self.assertOK(response, {'data': {'id': 1, 'name': 'Jim', 'owner': None}})

        response = self.simulate_request('/getonly-accounts', method='PUT', body=json.dumps({'id': 1, 'name': 'Alice'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertMethodNotAllowed(response)
        response = self.simulate_request('/getonly-accounts/1', method='PUT', body=json.dumps({'id': 1, 'name': 'Alice'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertMethodNotAllowed(response)
        response = self.simulate_request('/postonly-accounts', method='PUT', body=json.dumps({'id': 1, 'name': 'Alice'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertMethodNotAllowed(response)
        response = self.simulate_request('/postonly-accounts/1', method='PUT', body=json.dumps({'id': 1, 'name': 'Alice'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertMethodNotAllowed(response)
        response = self.simulate_request('/putonly-accounts', method='PUT', body=json.dumps({'id': 1, 'name': 'Alice'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertMethodNotAllowed(response)
        response = self.simulate_request('/putonly-accounts/1', method='PUT', body=json.dumps({'id': 1, 'name': 'Jack'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertOK(response)
        response = self.simulate_request('/patchonly-accounts', method='PUT', body=json.dumps({'id': 1, 'name': 'Alice'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertMethodNotAllowed(response)
        response = self.simulate_request('/patchonly-accounts/1', method='PUT', body=json.dumps({'id': 1, 'name': 'Alice'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertMethodNotAllowed(response)
        response = self.simulate_request('/deleteonly-accounts', method='PUT', body=json.dumps({'id': 1, 'name': 'Alice'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertMethodNotAllowed(response)
        response = self.simulate_request('/deleteonly-accounts/1', method='PUT', body=json.dumps({'id': 1, 'name': 'Alice'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertMethodNotAllowed(response)

        response, = self.simulate_request('/accounts/1', method='GET', headers={'Accept': 'application/json'})
        self.assertOK(response, {'data': {'id': 1, 'name': 'Jack', 'owner': None}})

    def test_patch(self):
        response, = self.simulate_request('/accounts', method='POST', body=json.dumps({'id': 1, 'name': 'Bob'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertCreated(response)

        response = self.simulate_request('/accounts', method='PATCH', body=json.dumps({'patches': [{'op': 'add', 'path': '/', 'value': {'id': 2, 'name': 'Jane'}}]}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertOK(response)

        response, = self.simulate_request('/accounts', method='GET', headers={'Accept': 'application/json'})
        self.assertOK(response, {'data': [{'id': 1, 'name': 'Bob', 'owner': None}, {'id': 2, 'name': 'Jane', 'owner': None}]})

        response = self.simulate_request('/accounts/1', method='PATCH', body=json.dumps({'id': 1, 'name': 'Jim'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertOK(response)

        response, = self.simulate_request('/accounts/1', method='GET', headers={'Accept': 'application/json'})
        self.assertOK(response, {'data': {'id': 1, 'name': 'Jim', 'owner': None}})

        response = self.simulate_request('/getonly-accounts', method='PATCH', body=json.dumps({'id': 1, 'name': 'Alice'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertMethodNotAllowed(response)
        response = self.simulate_request('/getonly-accounts/1', method='PATCH', body=json.dumps({'id': 1, 'name': 'Alice'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertMethodNotAllowed(response)
        response = self.simulate_request('/postonly-accounts', method='PATCH', body=json.dumps({'id': 1, 'name': 'Alice'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertMethodNotAllowed(response)
        response = self.simulate_request('/postonly-accounts/1', method='PATCH', body=json.dumps({'id': 1, 'name': 'Alice'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertMethodNotAllowed(response)
        response = self.simulate_request('/putonly-accounts', method='PATCH', body=json.dumps({'id': 1, 'name': 'Alice'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertMethodNotAllowed(response)
        response = self.simulate_request('/putonly-accounts/1', method='PATCH', body=json.dumps({'id': 1, 'name': 'Alice'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertMethodNotAllowed(response)
        response = self.simulate_request('/patchonly-accounts', method='PATCH', body=json.dumps({'patches': [{'op': 'add', 'path': '/', 'value': {'id': 3, 'name': 'Dan'}}]}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertOK(response)
        response = self.simulate_request('/patchonly-accounts/1', method='PATCH', body=json.dumps({'id': 1, 'name': 'Jack'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertOK(response)
        response = self.simulate_request('/deleteonly-accounts', method='PATCH', body=json.dumps({'id': 1, 'name': 'Alice'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertMethodNotAllowed(response)
        response = self.simulate_request('/deleteonly-accounts/1', method='PATCH', body=json.dumps({'id': 1, 'name': 'Alice'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertMethodNotAllowed(response)

        response, = self.simulate_request('/accounts', method='GET', headers={'Accept': 'application/json'})
        self.assertOK(response, {'data': [{'id': 1, 'name': 'Jack', 'owner': None}, {'id': 2, 'name': 'Jane', 'owner': None}, {'id': 3, 'name': 'Dan', 'owner': None}]})

    def test_delete(self):
        response, = self.simulate_request('/accounts', method='POST', body=json.dumps({'id': 1, 'name': 'Bob'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertCreated(response)
        response, = self.simulate_request('/accounts', method='POST', body=json.dumps({'id': 2, 'name': 'Jim'}), headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertCreated(response)

        response = self.simulate_request('/accounts', method='DELETE', headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertMethodNotAllowed(response)
        response = self.simulate_request('/accounts/1', method='DELETE', headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertOK(response)

        response, = self.simulate_request('/accounts', method='GET', headers={'Accept': 'application/json'})
        self.assertOK(response, {'data': [{'id': 2, 'name': 'Jim', 'owner': None}]})

        response = self.simulate_request('/getonly-accounts', method='DELETE', headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertMethodNotAllowed(response)
        response = self.simulate_request('/getonly-accounts/2', method='DELETE', headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertMethodNotAllowed(response)
        response = self.simulate_request('/postonly-accounts', method='DELETE', headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertMethodNotAllowed(response)
        response = self.simulate_request('/postonly-accounts/2', method='DELETE', headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertMethodNotAllowed(response)
        response = self.simulate_request('/putonly-accounts', method='DELETE', headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertMethodNotAllowed(response)
        response = self.simulate_request('/putonly-accounts/2', method='DELETE', headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertMethodNotAllowed(response)
        response = self.simulate_request('/patchonly-accounts', method='DELETE', headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertMethodNotAllowed(response)
        response = self.simulate_request('/patchonly-accounts/2', method='DELETE', headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertMethodNotAllowed(response)
        response = self.simulate_request('/deleteonly-accounts', method='DELETE', headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertMethodNotAllowed(response)

        response, = self.simulate_request('/accounts', method='GET', headers={'Accept': 'application/json'})
        self.assertOK(response, {'data': [{'id': 2, 'name': 'Jim', 'owner': None}]})

        response = self.simulate_request('/deleteonly-accounts/2', method='DELETE', headers={'Accept': 'application/json', 'Content-Type': 'application/json'})
        self.assertOK(response)

        response, = self.simulate_request('/accounts', method='GET', headers={'Accept': 'application/json'})
        self.assertOK(response, {'data': []})


text:
namespace LccWebParts {

    export interface IWebPartService {     // WebPart interface
        GetWebPartProperties(string): ng.IPromise<IWebPartProperties | IError>;
        GetWebPartProperty(webPartId: string, propertyName: string);
        SaveWebPartProperties(string, any): ng.IPromise<void | IError>;
        SaveWebPartProperty(webPartId: string, propertyName: string, object: any): ng.IPromise<void | IError>;
        IsPageInEditMode(): boolean;
        IsWebPartInEditMode(string): boolean;
    }
}


text:
/*	$NetBSD: line_wrap.c,v 1.1.1.1 2009/06/23 10:09:00 tron Exp $	*/

/*++
/* NAME
/*	line_wrap 3
/* SUMMARY
/*	wrap long lines upon output
/* SYNOPSIS
/*	#include <line_wrap.h>
/*
/*	void	line_wrap(string, len, indent, output_fn, context)
/*	const char *buf;
/*	int	len;
/*	int	indent;
/*	void	(*output_fn)(const char *str, int len, int indent, char *context);
/*	char	*context;
/* DESCRIPTION
/*	The \fBline_wrap\fR routine outputs the specified string via
/*	the specified output function, and attempts to keep output lines
/*	shorter than the specified length. The routine does not attempt to
/*	break long words that do not fit on a single line. Upon output,
/*	trailing whitespace is stripped.
/*
/* Arguments
/* .IP string
/*	The input, which cannot contain any newline characters.
/* .IP len
/*	The desired maximal output line length.
/* .IP indent
/*	The desired amount of indentation of the second etc. output lines
/*	with respect to the first output line. A negative indent causes
/*	only the first line to be indented; a positive indent causes all
/*	but the first line to be indented. A zero count causes no indentation.
/* .IP output_fn
/*	The output function that is called with as arguments a string
/*	pointer, a string length, a non-negative indentation count, and
/*	application context. A typical implementation looks like this:
/* .sp
/* .nf
/* .na
void print(const char *str, int len, int indent, char *context)
{
    VSTREAM *fp = (VSTREAM *) context;

    vstream_fprintf(fp, "%*s%.*s", indent, "", len, str);
}
/* .fi
/* .ad
/* .IP context
/*	Application context that is passed on to the output function.
/*	For example, a VSTREAM pointer, or a structure that contains
/*	a VSTREAM pointer.
/* BUGS
/*	No tab expansion and no backspace processing.
/* LICENSE
/* .ad
/* .fi
/*	The Secure Mailer license must be distributed with this software.
/* AUTHOR(S)
/*	Wietse Venema
/*	IBM T.J. Watson Research
/*	P.O. Box 704
/*	Yorktown Heights, NY 10598, USA
/*--*/

/* System library. */

#include <sys_defs.h>
#include <string.h>
#include <ctype.h>

/* Utility library. */

#include <line_wrap.h>

/* line_wrap - wrap long lines upon output */

void    line_wrap(const char *str, int len, int indent, LINE_WRAP_FN output_fn,
		          char *context)
{
    const char *start_line;
    const char *word;
    const char *next_word;
    const char *next_space;
    int     line_len;
    int     curr_len;
    int     curr_indent;

    if (indent < 0) {
	curr_indent = -indent;
	curr_len = len + indent;
    } else {
	curr_indent = 0;
	curr_len = len;
    }

    /*
     * At strategic positions, output what we have seen, after stripping off
     * trailing blanks.
     */
    for (start_line = word = str; word != 0; word = next_word) {
	next_space = word + strcspn(word, " \t");
	if (word > start_line) {
	    if (next_space - start_line > curr_len) {
		line_len = word - start_line;
		while (line_len > 0 && ISSPACE(start_line[line_len - 1]))
		    line_len--;
		output_fn(start_line, line_len, curr_indent, context);
		while (*word && ISSPACE(*word))
		    word++;
		if (start_line == str) {
		    curr_indent += indent;
		    curr_len -= indent;
		}
		start_line = word;
	    }
	}
	next_word = *next_space ? next_space + 1 : 0;
    }
    line_len = strlen(start_line);
    while (line_len > 0 && ISSPACE(start_line[line_len - 1]))
	line_len--;
    output_fn(start_line, line_len, curr_indent, context);
}


text: <body>More utility classes</body>


text:
<!doctype html>

		<meta charset="utf-8">

		<title>reveal.js - The HTML Presentation Framework</title>

		<meta name="description" content="A framework for easily creating beautiful presentations using HTML">
		<meta name="author" content="Hakim El Hattab">

		<meta name="apple-mobile-web-app-capable" content="yes" />
		<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">

		<link rel="stylesheet" href="css/reveal.css">
		<link rel="stylesheet" href="css/theme/black.css" id="theme">
        <link rel="stylesheet" href="css/extras.css">

		<link rel="stylesheet" href="lib/css/zenburn.css">

CRM Webhooks Implementation

Outline

Serverless Applications

Project Introduction

Why not Wall-e?

Project Architecture

AWS API Gateway

AWS Lambda

Stack Integration

What is Serverless?

	An application is said to be serverless when it runs in stateless compute containers that are event-triggered, ephemeral (may only last for one invocation), and fully managed by a 3rd party.

	Serverless applications are easy to manage, they provide high availability and perform at any scale.

Serverless in AWS

Project Introduction

                        Why we did what

Exact Target? Vero? Webhooks?

                                    Exact Target, our current CRM provider

                                    Vero, our other CRM provider

                                    Migrate already?!

                                    The Webhooks

                                            POST requests on every event (sent, delivered, clicked, bounced...)

                                            Integrations with Segment, GA, or custom

                                            Used for push notifications through wall-e

Exact Target? Vero? Webhooks?

Why not Wall-e?

                            Receives too many requests

                            Adds must complexity, used as a proxy

                            It's not its responsibility anyway

Project Architecture

The initial idea

Kinesis x MySQL

Kinesis

How to produce/consume data from kinesis?

How to organize events in S3?

Save money :)

MySQL

DW alredy has a MySQL Resource

Easier for DW to query

The final solution

AWS API Gateway

AWS API Gateway

                                Serverless API

                                        No framework, no coding, no config, no troubles

                                        Auto Scalable

                                The configuration

                                        No resources, 1 POST Method

                                        Lambda Integration

                                        API key passed through to Lambda

                                        Method / Integration Response

                                        Custom Domain Names

AWS Lambda

                            Responsibilities

                                    Validates incoming requests

                                    Adds an event to bob queue (if event is a push request)

                                    Adds the event to MySQL

AWS Lambda

                            Configuration

VPC

Subnets

Security Group

aws lambda

                            lambda code

Written in python2.7

Hosted in s3

Code sample

def producer_handler(event, context):
    ... api key validation ...

    worker = CrmWorker()
    responses = worker.produce(body, [
        get_resque_producer(),
        get_mysql_producer()
    ])
    print responses
    return responses

aws lambda

                            lambda code

Response sample

{
	'responses': [
	  'Job Pushed to redis, user id 1234, subject subejct, redis response: 2.',
	  'Data produced to mysql successfully'
	],
	'start_time': '2017-02-09 23:25:12',
	'stop_time': '2017-02-09 23:25:12',
	'event': {
        ...
	}
}

Stack Integration

How to deploy lambda functions

Stack integration

Continuous Integration

Deployment Strategy

Thank you for your attention

                                Repos

                                CRM Microservice Repo

                                Cloudformation Repo

Documentation

                                AWS API Gateway

                                AWS Lambda

                                Cloudformation


text:
extern "C" {
#endif

typedef struct XboxLiveAppConfig
{
    uint32_t titleId;
    PCSTR scid;
    PCSTR environment;
    PCSTR sandbox;
} XboxLiveAppConfig;

XSAPI_DLLEXPORT XSAPI_RESULT XBL_CALLING_CONV
GetXboxLiveAppConfigSingleton(
    _Out_ XboxLiveAppConfig const** ppConfig
    );

#if defined(__cplusplus)
} // end extern "C"
#endif // defined(__cplusplus)


text:
package test;

/**
 * Created by sventschui on 10.05.15.
 */
public class TestResponsePojoOne {

    protected String foobar;

    protected TestResponsePojoOneInner inner;

    public String getFoobar() {
        return foobar;
    }

    public void setFoobar(String foobar) {
        this.foobar = foobar;
    }

    public TestResponsePojoOneInner getInner() {
        return inner;
    }

    public void setInner(TestResponsePojoOneInner inner) {
        this.inner = inner;
    }

    private class TestResponsePojoOneInner {
    }
}


text:
package org.jsimpledb.util;

import com.google.common.base.Function;
import com.google.common.base.Preconditions;

/**
 * A {@link Function} that casts objects to some type.
 */
public class CastFunction<T> implements Function<Object, T> {

    protected final Class<T> type;

    /**
     * Constructor.
     *
     * @param type desired type
     * @throws IllegalArgumentException if {@code type} is null
     */
     public CastFunction(Class<T> type) {
        Preconditions.checkArgument(type != null, "null type");
        this.type = type;
    }

    @Override
    public T apply(Object obj) {
        if (obj == null)
            return null;
        try {
            return this.type.cast(obj);
        } catch (ClassCastException e) {
            throw this.handleFailure(obj, e);
        }
    }

    /**
     * Generate an exception to throw when a cast failure occurs.
     *
     * <p>
     * The implementation in {@link CastFunction} just throws {@code e}.
     * </p>
     *
     * @param obj object on which cast failed
     * @param e resulting exception
     * @return exception to throw
     */
    protected RuntimeException handleFailure(Object obj, ClassCastException e) {
        return e;
    }
}


text:
package org.openmhealth.shimmer.common.domain.parameters;

import java.util.List;
import java.util.Optional;

/**
 * @author Chris Schaefbauer
 */
public class ListRequestParameter<T> extends RequestParameter<List<T>> {

    List<T> defaultValues;
    String listDelineator;
    List<T> allowableValues;

    public Optional<List<T>> getDefaultValues() {
        return Optional.ofNullable(defaultValues);
    }

    public void setDefaultValues(List<T> defaultValues) {
        this.defaultValues = defaultValues;
    }

    public String getListDelineator() {
        return listDelineator;
    }

    public void setListDelineator(String listDelineator) {
        this.listDelineator = listDelineator;
    }

    public Optional<List<T>> getAllowableValues() {
        return Optional.ofNullable(allowableValues);
    }

    public void setAllowableValues(List<T> allowableValues) {
        this.allowableValues = allowableValues;
    }

}