text:
from PySide import QtCore, QtGui
from tools.modified.androguard.core import androconf
from tools.modified.androguard.gui.helpers import class2func, method2func, classdot2func, classdot2class, proto2methodprotofunc
from tools.modified.androguard.gui.renamewindow import RenameDialog
from tools.modified.androguard.gui.xrefwindow import XrefDialogMethod, XrefDialogField

PYGMENTS = True
try:
    from qtconsole.pygments_highlighter import PygmentsHighlighter
    from pygments.lexers import JavaLexer
except:
    PYGMENTS = False

import os

BINDINGS_NAMES = [
    'NAME_PACKAGE', 'NAME_PROTOTYPE', 'NAME_SUPERCLASS', 'NAME_INTERFACE',
    'NAME_FIELD', 'NAME_METHOD_PROTOTYPE', 'NAME_ARG', 'NAME_CLASS_ASSIGNMENT',
    'NAME_PARAM', 'NAME_BASE_CLASS', 'NAME_METHOD_INVOKE', 'NAME_CLASS_NEW',
    'NAME_CLASS_INSTANCE', 'NAME_VARIABLE', 'NAME_CLASS_EXCEPTION'
]

class SourceDocument(QtGui.QTextDocument):
    '''QTextDocument associated with the SourceWindow.'''

    def __init__(self, parent=None, lines=[]):
        super(SourceDocument, self).__init__(parent)
        self.parent = parent

        # Set font to be fixed-width
        font = self.defaultFont()
        font.setFamily("Courier New")
        self.setDefaultFont(font)

        cursor = QtGui.QTextCursor(self) # position=0x0
        state = 0
        self.binding = {}

        # save the cursor position before each interesting element
        for section, L in lines:
            for t in L:
                if t[0] in BINDINGS_NAMES:
                    self.binding[cursor.position()] = t
                cursor.insertText(t[1])

class SourceWindow(QtGui.QTextEdit):
    '''Each tab is implemented as a Source Window class.
       Attributes:
        mainwin: MainWindow
        path: class FQN
        title: last part of the class FQN
        class_item: ClassDefItem i.e. class.java object for which we create the tab
    '''

    def __init__(self, parent=None, win=None, current_class=None, current_title=None, current_filename=None, current_digest=None, session=None):
        super(SourceWindow, self).__init__(parent)
        androconf.debug("New source tab for: %s" % current_class)

        self.mainwin = win
        self.session = session
        self.current_class = current_class
        self.current_title = current_title
        self.current_filename = current_filename
        self.current_digest = current_digest

        self.title = current_title

        self.setReadOnly(True)

        self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.CustomContextMenuHandler)

        self.cursorPositionChanged.connect(self.cursor_position_changed)

    def browse_to_method(self, method):
        '''Scroll to the right place were the method is.

           TODO: implement it, because does not work for now.
        '''

        #TODO: we need to find a way to scroll to the right place because
        #      moving the cursor is not enough. Indeed if it is already in the window
        #      it does not do nothing

        #TODO: idea, highlight the method in the screen so we do not have to search for it

        androconf.debug("Browsing to %s -> %s" % (self.current_class, method))

        # debug
#        if False:
#            for k, v in self.doc.infoBlocks.items():
#                print k
#                print v
#                print "-"*10

    def reload_java_sources(self):
        '''Reload completely the sources by asking Androguard
           to decompile it again. Useful when:
            - an element has been renamed to propagate the info
            - the current tab is changed because we do not know what user
              did since then, so we need to propagate previous changes as well
        '''

        androconf.debug("Getting sources for %s" % self.current_class)

        lines = []
        lines.append(("COMMENTS", [("COMMENT", "/*\n * filename:%s\n * digest:%s\n */\n" % (self.current_filename, self.current_digest))]))
        lines.extend(self.current_class.get_source_ext())

        #TODO: delete doc when tab is closed? not deleted by "self" :(
        if hasattr(self, "doc"):
            del self.doc
        self.doc = SourceDocument(parent=self, lines=lines)
        self.setDocument(self.doc)

        #No need to save hightlighter. highlighBlock will automatically be called
        #because we passed the QTextDocument to QSyntaxHighlighter constructor
        if PYGMENTS:
            PygmentsHighlighter(self.doc, lexer=JavaLexer())
        else:
            androconf.debug("Pygments is not present !")

    def display_bytecodes(self):
        androconf.debug("Display bytecodes for %s" % self.current_class)
        self.mainwin.openBytecodeWindow(self.current_class)

    @QtCore.Slot()
    def cursor_position_changed(self):
        '''Used to detect when cursor change position and to auto select word
           underneath it'''
        androconf.debug("cursor_position_changed")

        cur = self.textCursor()
        androconf.debug(cur.position())
        androconf.debug(cur.selectedText())
        if len(cur.selectedText()) == 0:
            cur.select(QtGui.QTextCursor.SelectionType.WordUnderCursor)
            self.setTextCursor(cur)
            androconf.debug("cursor: %s" % cur.selectedText())
        else:
            androconf.debug("cursor: no selection %s" % cur.selectedText())

    def keyPressEvent(self, event):
        '''Keyboard shortcuts'''
        key = event.key()
        if key == QtCore.Qt.Key_X:
            self.actionXref()
        elif key == QtCore.Qt.Key_G:
            self.actionGoto()
        elif key == QtCore.Qt.Key_X:
            self.actionXref()
        elif key == QtCore.Qt.Key_I:
            self.actionInfo()
        elif key == QtCore.Qt.Key_R:
            self.reload_java_sources()
        elif key == QtCore.Qt.Key_B:
            self.display_bytecodes()

    def CustomContextMenuHandler(self, pos):
        menu = QtGui.QMenu(self)
        menu.addAction(QtGui.QAction("Xref ...", self,
                statusTip="List the references where this element is used",
                triggered=self.actionXref))
        menu.addAction(QtGui.QAction("Go to...", self,
                statusTip="Go to element definition",
                triggered=self.actionGoto))
        menu.addAction(QtGui.QAction("Rename...", self,
                statusTip="Rename an element (class, method, ...)",
                triggered=self.actionRename))
        menu.addAction(QtGui.QAction("Info...", self,
                statusTip="Display info of an element (anything useful in the document)",
                triggered=self.actionInfo))
        menu.addAction(QtGui.QAction("Reload sources...", self,
                statusTip="Reload sources (needed when renaming changed other tabs)",
                triggered=self.reload_java_sources))
        menu.addAction(QtGui.QAction("Open bytecodes...", self,
                statusTip="",
                triggered=self.display_bytecodes))
        menu.exec_(QtGui.QCursor.pos())

    def actionXref(self):
        cursor = self.textCursor()
        start = cursor.selectionStart()
        end = cursor.selectionEnd()
        selection = cursor.selectedText()
        androconf.debug("Xref asked for '%s' (%d, %d)" % (selection, start, end))

        if start not in self.doc.binding.keys():
            self.mainwin.showStatus("Xref not available. No info for: '%s'." % selection)
            return

        class_ = None
        method_ = None
        t = self.doc.binding[start]
        print t

        if t[0] == 'NAME_METHOD_PROTOTYPE':
            method_ = t[1]
            if method_ == self.title:
                method_ = 'init'

            proto_ = t[2].method.proto

            method_class_name = self.current_class.get_name()
            method_name = method_
            method_proto = proto_
            current_analysis = self.session.get_analysis(self.current_class)

            androconf.debug("Found corresponding method: %s %s %s in source file: %s" % (method_class_name, method_name, method_proto, self.current_filename))

            class_analysis = current_analysis.get_class_analysis(self.current_class.get_name())
            if not class_analysis:
                self.mainwin.showStatus("No xref returned (no class_analysis object).")
                return

            method_analysis = class_analysis.get_method_analysis(current_analysis.get_method_by_name(method_class_name, method_name, method_proto))
            print method_analysis
            if not method_analysis:
                self.mainwin.showStatus("No xref returned (no method_analysis object).")
                return

            xwin = XrefDialogMethod(parent=self.mainwin, win=self.mainwin, current_class=self.current_class, class_analysis=class_analysis, method_analysis=method_analysis)
            xwin.show()
        elif t[0] == 'NAME_FIELD':
            field_ = t[3]

            current_analysis = self.session.get_analysis(self.current_class)
            class_analysis = current_analysis.get_class_analysis(self.current_class.get_name())
            if not class_analysis:
                self.mainwin.showStatus("No xref returned (no class_analysis object).")
                return

            field_analysis = class_analysis.get_field_analysis(field_)
            print field_analysis
            if not field_analysis:
                self.mainwin.showStatus("No xref returned (no field_analysis object).")
                return

            xwin = XrefDialogField(parent=self.mainwin, win=self.mainwin, current_class=self.current_class, class_analysis=class_analysis, field_analysis=field_analysis)
            xwin.show()
        else:
            self.mainwin.showStatus("No xref returned.")
            return

        #elif t[0] == 'NAME_METHOD_INVOKE':
        #    class_, method_ = t[2].split(' -> ')
        #    if class_ == 'this':
        #        class_ = self.current_class
        #    else:
        #        class_ = classdot2class(class_)
        #elif t[0] == 'NAME_PROTOTYPE':
        #    class_ = classdot2class(t[2] + '.' + t[1])
        #else:
        #    self.mainwin.showStatus("Xref not available. Info ok: '%s' but object not supported." % selection)
        #    return

    def actionRename(self):
        cursor = self.textCursor()
        start = cursor.selectionStart()
        end = cursor.selectionEnd()
        selection = cursor.selectedText()
        androconf.debug("Rename asked for '%s' (%d, %d)" % (selection, start, end))

        if start not in self.doc.binding.keys():
            self.mainwin.showStatus("Rename not available. No info for: '%s'." % selection)
            return

        # Double check if we support the renaming for the type of
        # object before poping a new window to the user
        t = self.doc.binding[start]
        if t[0] == 'NAME_METHOD_PROTOTYPE':
            class_ = self.current_class
            method_ = t[1]
            if method_ == self.title:
                method_ = 'init'
            androconf.debug("Found corresponding method: %s -> %s in source file: %s" % (class_, method_, self.current_filename))
        elif t[0] == 'NAME_METHOD_INVOKE':
            class_, method_ = t[2].split(' -> ')
            if class_ == 'this':
                class_ = self.current_class
            androconf.debug("Found corresponding method: %s -> %s in source file: %s" % (class_, method_, self.current_filename))
        elif t[0] == 'NAME_PROTOTYPE':
            class_ = t[2] + '.' + t[1]
            androconf.debug("Found corresponding class: %s in source file: %s" % (class_, self.current_filename))
        elif t[0] == 'NAME_FIELD':
            field_ = t[1]
            androconf.debug("Found corresponding field: %s in source file: %s" % (field_, self.current_filename))
        else:
            self.mainwin.showStatus("Rename not available. Info ok: '%s' but object not supported." % selection)
            return

        rwin = RenameDialog(parent=self, win=self.mainwin, element=selection, info=(start, end))
        rwin.show()

    def actionGoto(self):
        cursor = self.textCursor()
        start = cursor.selectionStart()
        end = cursor.selectionEnd()
        selection = cursor.selectedText()
        androconf.debug("Goto asked for '%s' (%d, %d)" % (selection, start, end))

        if start not in self.doc.binding.keys():
            self.mainwin.showStatus("Goto not available. No info for: '%s'." % selection)
            return

        t = self.doc.binding[start]
        if t[0] == 'NAME_METHOD_INVOKE':
            class_, method_ = t[2].split(' -> ')
            if class_ == 'this':
                class_ = self.path
            else:
                class_ = classdot2class(class_)
        else:
            self.mainwin.showStatus("Goto not available. Info ok: '%s' but object not supported." % selection)
            return

        androconf.debug("Found corresponding method: %s -> %s in source file: %s" % (class_, method_, self.path))

        if not self.mainwin.doesClassExist(class_):
            self.mainwin.showStatus("Goto not available. Class: %s not in database." % class_)
            return

        self.mainwin.openSourceWindow(class_, method=method_)

    def actionInfo(self):
        cursor = self.textCursor()
        start = cursor.selectionStart()
        end = cursor.selectionEnd()
        androconf.debug("actionInfo asked for (%d, %d)" % (start, end))

        if start in self.doc.binding.keys():
            self.mainwin.showStatus('%s at position: (%d, %d)' % (str(self.doc.binding[start]), start, end))
        else:
            self.mainwin.showStatus("No info available.")

    def method_name_exist(self, meth_name):
        '''Check if there is already a meth_name method in the current class
           It is useful before allowing to rename a method to check name does
           not already exist.
        '''

        methods = self.current_class.get_methods()
        for m in methods:
            if m.name == meth_name:
                return True
        return False

    def field_name_exist(self, field_name):
        '''Check if there is already a field_name field in the current class
           It is useful before allowing to rename a field to check name does
           not already exist.
        '''

        fields = self.class_item.get_fields()
        for f in fields:
            if f.name == field_name:
                return True
        return False

    def renameElement(self, oldname, newname, info):
        '''Called back after a user chose a new name for an element.
        '''

        androconf.debug("Renaming %s into %s in %s" % (oldname, newname, self.current_filename))
        start, end = info
        try:
            t = self.doc.binding[start]
        except:
            self.mainwin.showStatus("Unexpected error in renameElement")
            return

        # Determine type of the to-be-renamed element and Androguard internal objects
        type_ = None
        if t[0] == 'NAME_METHOD_PROTOTYPE': # method definition in a class
            method_ = t[1]
            if method_ == self.title:
                method_ = 'init'

            proto_ = t[2].method.proto
            androconf.debug("Found: class=%s, method=%s, proto=%s" % (self.current_class, method_, proto_))
            type_ = "METHOD"
        elif t[0] == 'NAME_METHOD_INVOKE': # method call in a method
            class_, method_ = t[2].split(' -> ')
            class_ = classdot2class(class_)
            if class_ == 'this':
                class_ = self.path
            proto_ = proto2methodprotofunc("".join(t[3]) + t[4])
            androconf.debug("Found: class=%s, method=%s, proto=%s" % (class_, method_, proto_))
            type_ = "METHOD"
        elif t[0] == 'NAME_PROTOTYPE': # class definition on top of a class
            class_ = t[2] + '.' + t[1]
            package_ = t[2]
            androconf.debug("Found: package=%s, class=%s" % (package_, class_))
            type_ = "CLASS"
        elif t[0] == 'NAME_FIELD':
            field_item = t[3]
            type_ = "FIELD"
        else:
            self.mainwin.showStatus("Rename not available. Info found: '%s' but object not supported." % selection)
            return

        # Do the actual renaming
        if type_ == "METHOD":
            if self.method_name_exist(newname):
                self.mainwin.showStatus("Method name already exist")
                return

            method_class_name = self.current_class.get_name()
            method_name = method_
            method_proto = proto_
            current_analysis = self.session.get_analysis(self.current_class)

            method_item = current_analysis.get_method_by_name(method_class_name, method_name, method_proto)
            if not method_item:
                self.mainwin.showStatus("Impossible to find the method")
                return

            method_item.set_name(str(newname)) #unicode to ascii
        elif type_ == "CLASS":
            newname_class = classdot2class(package_ + '.' + newname)
            self.mainwin.showStatus("New name: %s" % newname_class)
            class_item = self.current_class #getattr(self.mainwin.d, classdot2func(class_))
            class_item.set_name(str(newname_class)) #unicode to ascii
            self.mainwin.updateDockWithTree()
        elif type_ == 'FIELD':
            if self.field_name_exist(newname):
                self.mainwin.showStatus("Field name already exist")
                return
            field_item.set_name(str(newname))
        else:
            self.mainwin.showStatus("Unsupported type: %s" % str(type_))
            return
        self.reload_java_sources()


text:
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/imageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="top"
    android:contentDescription="@string/imageView"
    android:src="@drawable/ic_launcher" >

</ImageView>

redpajama_set_name: RedPajamaGithub


text:
package org.apache.hadoop.hive.ql.parse.repl.dump.events;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.api.NotificationEvent;
import org.apache.hadoop.hive.metastore.messaging.AddPartitionMessage;
import org.apache.hadoop.hive.metastore.messaging.EventMessage;
import org.apache.hadoop.hive.metastore.messaging.PartitionFiles;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.metadata.Partition;
import org.apache.hadoop.hive.ql.metadata.Table;
import org.apache.hadoop.hive.ql.parse.EximUtil;
import org.apache.hadoop.hive.ql.parse.repl.DumpType;
import org.apache.hadoop.hive.ql.parse.repl.dump.Utils;

import java.io.File;
import java.util.Iterator;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

class AddPartitionHandler extends AbstractEventHandler {
  protected AddPartitionHandler(NotificationEvent notificationEvent) {
    super(notificationEvent);
  }

  @Override
  EventMessage eventMessage(String stringRepresentation) {
    return deserializer.getAddPartitionMessage(stringRepresentation);
  }

  @Override
  public void handle(Context withinContext) throws Exception {
    LOG.info("Processing#{} ADD_PARTITION message : {}", fromEventId(), eventMessageAsJSON);

    // We do not dump partitions during metadata only bootstrap dump (See TableExport
    // .getPartitions(), for bootstrap dump we pass tableSpec with TABLE_ONLY set.). So don't
    // dump partition related events for metadata-only dump.
    if (withinContext.hiveConf.getBoolVar(HiveConf.ConfVars.REPL_DUMP_METADATA_ONLY)) {
      return;
    }

    AddPartitionMessage apm = (AddPartitionMessage) eventMessage;
    org.apache.hadoop.hive.metastore.api.Table tobj = apm.getTableObj();
    if (tobj == null) {
      LOG.debug("Event#{} was a ADD_PTN_EVENT with no table listed", fromEventId());
      return;
    }

    final Table qlMdTable = new Table(tobj);
    if (!Utils.shouldReplicate(withinContext.replicationSpec, qlMdTable, true,
            withinContext.getTablesForBootstrap(), withinContext.oldReplScope,  withinContext.hiveConf)) {
      return;
    }

    Iterable<org.apache.hadoop.hive.metastore.api.Partition> ptns = apm.getPartitionObjs();
    if ((ptns == null) || (!ptns.iterator().hasNext())) {
      LOG.debug("Event#{} was an ADD_PTN_EVENT with no partitions", fromEventId());
      return;
    }

    Iterable<Partition> qlPtns = StreamSupport.stream(ptns.spliterator(), true).map(
        input -> {
          if (input == null) {
            return null;
          }
          try {
            return new Partition(qlMdTable, input);
          } catch (HiveException e) {
            throw new IllegalArgumentException(e);
          }
        }).collect(Collectors.toList());

    Path metaDataPath = new Path(withinContext.eventRoot, EximUtil.METADATA_NAME);
    EximUtil.createExportDump(
        metaDataPath.getFileSystem(withinContext.hiveConf),
        metaDataPath,
        qlMdTable,
        qlPtns,
        withinContext.replicationSpec,
        withinContext.hiveConf);

    boolean copyAtLoad = withinContext.hiveConf.getBoolVar(HiveConf.ConfVars.REPL_RUN_DATA_COPY_TASKS_ON_TARGET);
    Iterator<PartitionFiles> partitionFilesIter = apm.getPartitionFilesIter().iterator();

    // We expect one to one mapping between partitions and file iterators. For external table, this
    // list would be empty. So, it is enough to check hasNext outside the loop.
    if (partitionFilesIter.hasNext()) {
      for (Partition qlPtn : qlPtns) {
        Iterable<String> files = partitionFilesIter.next().getFiles();
        if (files != null) {
          if (copyAtLoad) {
            // encoded filename/checksum of files, write into _files
            Path ptnDataPath = new Path(withinContext.eventRoot, EximUtil.DATA_PATH_NAME + File.separator
                    + qlPtn.getName());
            writeEncodedDumpFiles(withinContext, files, ptnDataPath);
          } else {
            for (String file : files) {
              writeFileEntry(qlMdTable, qlPtn, file, withinContext);
            }
          }
        }
      }
    }
    withinContext.createDmd(this).write();
  }

  @Override
  public DumpType dumpType() {
    return DumpType.EVENT_ADD_PARTITION;
  }
}


text:
/*PLEASE DO NOT EDIT THIS CODE*/
/*This code was generated using the UMPLE 1.21.0.4666 modeling language!*/

import java.util.*;

// line 22 "MailOrderSystemClientOrder.ump"
// line 67 "MailOrderSystemClientOrder.ump"
public class ClientOrderLineItem
{

  //------------------------
  // MEMBER VARIABLES
  //------------------------

  //ClientOrderLineItem Attributes
  private String numberOrdered;
  private String pricePerUnitCharged;

  //ClientOrderLineItem Associations
  private List<ShipmentLineItem> shipmentLineItems;
  private OrderFromClient orderFromClient;
  private Product product;

  //------------------------
  // CONSTRUCTOR
  //------------------------

  public ClientOrderLineItem(String aNumberOrdered, String aPricePerUnitCharged, OrderFromClient aOrderFromClient, Product aProduct)
  {
    numberOrdered = aNumberOrdered;
    pricePerUnitCharged = aPricePerUnitCharged;
    shipmentLineItems = new ArrayList<ShipmentLineItem>();
    boolean didAddOrderFromClient = setOrderFromClient(aOrderFromClient);
    if (!didAddOrderFromClient)
    {
      throw new RuntimeException("Unable to create clientOrderLineItem due to orderFromClient");
    }
    boolean didAddProduct = setProduct(aProduct);
    if (!didAddProduct)
    {
      throw new RuntimeException("Unable to create clientOrderLineItem due to product");
    }
  }

  //------------------------
  // INTERFACE
  //------------------------

  public boolean setNumberOrdered(String aNumberOrdered)
  {
    boolean wasSet = false;
    numberOrdered = aNumberOrdered;
    wasSet = true;
    return wasSet;
  }

  public boolean setPricePerUnitCharged(String aPricePerUnitCharged)
  {
    boolean wasSet = false;
    pricePerUnitCharged = aPricePerUnitCharged;
    wasSet = true;
    return wasSet;
  }

  public String getNumberOrdered()
  {
    return numberOrdered;
  }

  public String getPricePerUnitCharged()
  {
    return pricePerUnitCharged;
  }

  public ShipmentLineItem getShipmentLineItem(int index)
  {
    ShipmentLineItem aShipmentLineItem = shipmentLineItems.get(index);
    return aShipmentLineItem;
  }

  public List<ShipmentLineItem> getShipmentLineItems()
  {
    List<ShipmentLineItem> newShipmentLineItems = Collections.unmodifiableList(shipmentLineItems);
    return newShipmentLineItems;
  }

  public int numberOfShipmentLineItems()
  {
    int number = shipmentLineItems.size();
    return number;
  }

  public boolean hasShipmentLineItems()
  {
    boolean has = shipmentLineItems.size() > 0;
    return has;
  }

  public int indexOfShipmentLineItem(ShipmentLineItem aShipmentLineItem)
  {
    int index = shipmentLineItems.indexOf(aShipmentLineItem);
    return index;
  }

  public OrderFromClient getOrderFromClient()
  {
    return orderFromClient;
  }

  public Product getProduct()
  {
    return product;
  }

  public static int minimumNumberOfShipmentLineItems()
  {
    return 0;
  }

  public ShipmentLineItem addShipmentLineItem(String aNumShipped, ShipmentToClient aShipmentToClient)
  {
    return new ShipmentLineItem(aNumShipped, this, aShipmentToClient);
  }

  public boolean addShipmentLineItem(ShipmentLineItem aShipmentLineItem)
  {
    boolean wasAdded = false;
    if (shipmentLineItems.contains(aShipmentLineItem)) { return false; }
    ClientOrderLineItem existingClientOrderLineItem = aShipmentLineItem.getClientOrderLineItem();
    boolean isNewClientOrderLineItem = existingClientOrderLineItem != null && !this.equals(existingClientOrderLineItem);
    if (isNewClientOrderLineItem)
    {
      aShipmentLineItem.setClientOrderLineItem(this);
    }
    else
    {
      shipmentLineItems.add(aShipmentLineItem);
    }
    wasAdded = true;
    return wasAdded;
  }

  public boolean removeShipmentLineItem(ShipmentLineItem aShipmentLineItem)
  {
    boolean wasRemoved = false;
    //Unable to remove aShipmentLineItem, as it must always have a clientOrderLineItem
    if (!this.equals(aShipmentLineItem.getClientOrderLineItem()))
    {
      shipmentLineItems.remove(aShipmentLineItem);
      wasRemoved = true;
    }
    return wasRemoved;
  }

  public boolean addShipmentLineItemAt(ShipmentLineItem aShipmentLineItem, int index)
  {
    boolean wasAdded = false;
    if(addShipmentLineItem(aShipmentLineItem))
    {
      if(index < 0 ) { index = 0; }
      if(index > numberOfShipmentLineItems()) { index = numberOfShipmentLineItems() - 1; }
      shipmentLineItems.remove(aShipmentLineItem);
      shipmentLineItems.add(index, aShipmentLineItem);
      wasAdded = true;
    }
    return wasAdded;
  }

  public boolean addOrMoveShipmentLineItemAt(ShipmentLineItem aShipmentLineItem, int index)
  {
    boolean wasAdded = false;
    if(shipmentLineItems.contains(aShipmentLineItem))
    {
      if(index < 0 ) { index = 0; }
      if(index > numberOfShipmentLineItems()) { index = numberOfShipmentLineItems() - 1; }
      shipmentLineItems.remove(aShipmentLineItem);
      shipmentLineItems.add(index, aShipmentLineItem);
      wasAdded = true;
    }
    else
    {
      wasAdded = addShipmentLineItemAt(aShipmentLineItem, index);
    }
    return wasAdded;
  }

  public boolean setOrderFromClient(OrderFromClient aOrderFromClient)
  {
    boolean wasSet = false;
    if (aOrderFromClient == null)
    {
      return wasSet;
    }

    OrderFromClient existingOrderFromClient = orderFromClient;
    orderFromClient = aOrderFromClient;
    if (existingOrderFromClient != null && !existingOrderFromClient.equals(aOrderFromClient))
    {
      existingOrderFromClient.removeClientOrderLineItem(this);
    }
    orderFromClient.addClientOrderLineItem(this);
    wasSet = true;
    return wasSet;
  }

  public boolean setProduct(Product aProduct)
  {
    boolean wasSet = false;
    if (aProduct == null)
    {
      return wasSet;
    }

    Product existingProduct = product;
    product = aProduct;
    if (existingProduct != null && !existingProduct.equals(aProduct))
    {
      existingProduct.removeClientOrderLineItem(this);
    }
    product.addClientOrderLineItem(this);
    wasSet = true;
    return wasSet;
  }

  public void delete()
  {
    for(int i=shipmentLineItems.size(); i > 0; i--)
    {
      ShipmentLineItem aShipmentLineItem = shipmentLineItems.get(i - 1);
      aShipmentLineItem.delete();
    }
    OrderFromClient placeholderOrderFromClient = orderFromClient;
    this.orderFromClient = null;
    placeholderOrderFromClient.removeClientOrderLineItem(this);
    Product placeholderProduct = product;
    this.product = null;
    placeholderProduct.removeClientOrderLineItem(this);
  }

  public String toString()
  {
	  String outputString = "";
    return super.toString() + "["+
            "numberOrdered" + ":" + getNumberOrdered()+ "," +
            "pricePerUnitCharged" + ":" + getPricePerUnitCharged()+ "]" + System.getProperties().getProperty("line.separator") +
            "  " + "orderFromClient = "+(getOrderFromClient()!=null?Integer.toHexString(System.identityHashCode(getOrderFromClient())):"null") + System.getProperties().getProperty("line.separator") +
            "  " + "product = "+(getProduct()!=null?Integer.toHexString(System.identityHashCode(getProduct())):"null")
     + outputString;
  }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Controllers — Python Rest Api Framework 0.1 documentation</title>

    <link rel="stylesheet" href="_static/default.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="top" title="Python Rest Api Framework 0.1 documentation" href="index.html" />
    <link rel="next" title="Authentication and Authorization" href="authentication.html" />
    <link rel="prev" title="Datastore" href="datastore.html" />

Navigation

          index

          modules |

          next |

          previous |

Python Rest Api Framework 0.1 documentation »

Controllers¶

Controller manage the dialogue between the request and the
datastore. Controller handle all the request related stuff:

Pagination

Authentication

Authorization

Rate-Limit

Authorized verbs

Mandatory Arguments¶

When creating a controller, some arguments are mandatory. It define
how your controller should handle requests.

list_verbs: list_verbs will tell your controller wich verbs are
allowed at the root of your ressource. [“GET”, “POST”] for a read
and write API, and only [“GET”] for a read-only API

unique_verbs: unique verbs tell your controller wich verbs are
allowed at the unique identifier endpoint of your ressource
(/ressource_name/<unique_id>). [“GET”, “PUT”, “DELETE”] fa read and
write API, [“GET”] for a read-only API.

Optionals parameters¶

Optionals parameters make your api able to manage special features
like Pagination, Authentication, Authorization and Rate-Limit. They
each depend on your own implementation.

Exemples:

controller = {
    "list_verbs": ["GET", "POST"],
    "unique_verbs": ["GET", "PUT", "DELETE"],
    "options": {"pagination": Pagination(20)}
    }

This will create:

a read and write API (GET and POST on the root URL, GET, PUT and
DELETE on the detail URL)

with a pagination of 20 results max because of the optional
pagination parameter. Results will be paginated using the offset and
count keyword (see <tt class="xref doc docutils literal">pagination</tt>) to get more on this topic.

Table Of Contents

Controllers

Mandatory Arguments

Optionals parameters

Previous topic

Datastore

Next topic

Authentication and Authorization

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          modules |

          next |

          previous |

Python Rest Api Framework 0.1 documentation »

        © Copyright 2013, Yohann Gabory.
      Created using Sphinx 1.2b3.


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- From: file:/usr/local/google/buildbot/repo_clients/https___googleplex-android.googlesource.com_a_platform_manifest.git/mnc-supportlib-release/frameworks/support/v7/cardview/res/values/colors.xml -->
    <eat-comment/>
    <color name="cardview_dark_background">#FF202020</color>
    <color name="cardview_light_background">#FFFAFAFA</color>
    <color name="cardview_shadow_end_color">#03000000</color>
    <color name="cardview_shadow_start_color">#37000000</color>
    <declare-styleable name="CardView"><attr format="color" name="cardBackgroundColor"/><attr format="dimension" name="cardCornerRadius"/><attr format="dimension" name="cardElevation"/><attr format="dimension" name="cardMaxElevation"/><attr format="boolean" name="cardUseCompatPadding"/><attr format="boolean" name="cardPreventCornerOverlap"/><attr format="dimension" name="contentPadding"/><attr format="dimension" name="contentPaddingLeft"/><attr format="dimension" name="contentPaddingRight"/><attr format="dimension" name="contentPaddingTop"/><attr format="dimension" name="contentPaddingBottom"/></declare-styleable>
    <!-- From: file:/usr/local/google/buildbot/repo_clients/https___googleplex-android.googlesource.com_a_platform_manifest.git/mnc-supportlib-release/frameworks/support/v7/cardview/res/values/dimens.xml -->
    <eat-comment/>
    <dimen name="cardview_compat_inset_shadow">1dp</dimen>
    <dimen name="cardview_default_elevation">2dp</dimen>
    <dimen name="cardview_default_radius">2dp</dimen>
    <!-- From: file:/usr/local/google/buildbot/repo_clients/https___googleplex-android.googlesource.com_a_platform_manifest.git/mnc-supportlib-release/frameworks/support/v7/cardview/res/values/styles.xml -->
    <eat-comment/>
    <style name="CardView">
        <item name="cardBackgroundColor">@color/cardview_light_background</item>
        <item name="cardCornerRadius">@dimen/cardview_default_radius</item>
        <item name="cardElevation">@dimen/cardview_default_elevation</item>
        <item name="cardMaxElevation">@dimen/cardview_default_elevation</item>
        <item name="cardUseCompatPadding">false</item>
        <item name="cardPreventCornerOverlap">true</item>
    </style>
    <style name="CardView.Dark">
        <item name="cardBackgroundColor">@color/cardview_dark_background</item>
    </style>
    <style name="CardView.Light">
        <item name="cardBackgroundColor">@color/cardview_light_background</item>
    </style>
</resources>


text:
$(document).ready(function(){
    // Code Here
});


text:
package com.arpnetworking.commons.jackson.databind.module;

import com.arpnetworking.commons.jackson.databind.deser.ThreadLocalBuilderBeanDeserializerModifier;
import com.arpnetworking.commons.jackson.databind.introspect.BuilderAnnotationIntrospector;
import com.fasterxml.jackson.databind.introspect.AnnotationIntrospectorPair;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
import com.fasterxml.jackson.databind.module.SimpleModule;

/**
 * Jackson Module for injecting JsonDeserialize annotations configured to use a model
 * classes internal {@link com.arpnetworking.commons.builder.Builder} class.
 *
 * Dependencies:
 *

 *
com.fasterxml.jackson.core:jackson-databind

 *

 *
 * @author Gil Markham (gil at groupon dot com)
 * @author Ville Koskela (ville dot koskela at inscopemetrics dot io)
 */
public class BuilderModule extends SimpleModule {

    @Override
    public void setupModule(final SetupContext context) {
        super.setupModule(context);
        context.addBeanDeserializerModifier(new ThreadLocalBuilderBeanDeserializerModifier());
        context.insertAnnotationIntrospector(
                new AnnotationIntrospectorPair(
                        new JacksonAnnotationIntrospector(),
                        new BuilderAnnotationIntrospector()));
    }

    private static final long serialVersionUID = 3669894622411029788L;
}


text:
using System.Collections.Generic;
using System.Threading.Tasks;
using EasyRbac.Domain.Relations;

namespace EasyRbac.Reponsitory.BaseRepository
{
    public interface IUserRoleRelationRepository : IRepository<UserRoleRelation>
    {
        Task<List<long>> GetUserIdsAsync(long roleId);

        Task DeleteRelAsync(long roleId, params long[] ids);
    }
}


text:
@implementation NSSet (X)

- (NSDictionary *)indexedDictionary
{
    NSMutableDictionary *ret = NSMutableDictionary.new;
    NSUInteger i = 0;

    for (id object in self.allObjects)
        ret[@(i++).stringValue] = object;

    return ret;
}

@end


text:
package com.tiny.demo.firstlinecode.ui.presenter;

import com.tiny.demo.firstlinecode.BuildConfig;
import com.tiny.demo.firstlinecode.R;
import com.tiny.demo.firstlinecode.common.utils.ResUtils;
import com.tiny.demo.firstlinecode.ui.contract.OptionalResortContract;
import com.tiny.demo.firstlinecode.ui.model.OptionalResortModel;

import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;

/**
 * Created by tiny on 17/6/5.
 */

public class OptionalResortPresenter implements OptionalResortContract.IPresenter {
    OptionalResortContract.IView iView;
    OptionalResortContract.IModel iModel;

    public OptionalResortPresenter(OptionalResortContract.IView iView) {
        this.iView = iView;
        iModel = new OptionalResortModel();
    }

    @Override
    public void getDataFromNet(final Map<String, String> params) {
        iModel.getNetData(params, new Observer<ResponseBody>() {

            @Override
            public void onSubscribe(Disposable d) {
                iView.showLoadingDialog();
            }

            @Override
            public void onNext(ResponseBody responseBody) {
                iView.sendResultToView(responseBody, params);
                iView.dismissLoadingDialog();
            }

            @Override
            public void onError(Throwable e) {
                if (e != null) {
                    e.printStackTrace();
                }
                iView.dismissLoadingDialog();
                iView.showErrorMsg(BuildConfig.DEBUG ? e.toString()
                        : ResUtils.getStringResource(R.string.request_data_error));
            }

            @Override
            public void onComplete() {

            }
        });
    }
}


text:
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;

namespace Microsoft.DotNet.Scripts
{
    /// <summary>
    /// Holds the configuration information for the update-dependencies script.
    /// </summary>
    /// <remarks>
    /// The following Environment Variables are required by this script:
    ///
    /// GITHUB_USER - The user to commit the changes as.
    /// GITHUB_EMAIL - The user's email to commit the changes as.
    /// GITHUB_PASSWORD - The password/personal access token of the GitHub user.
    ///
    /// The following Environment Variables can optionally be specified:
    ///
    /// DOTNET_VERSION_URL - The Url to the root of the version information (this is combined with the fragments bellow) (ex. "https://raw.githubusercontent.com/dotnet/versions/master/build-info")
    /// ROSLYN_VERSION_FRAGMENT - The fragment to combine with DOTNET_VERSION_URL to get the current dotnet/roslyn package versions. (ex. "dotnet/roslyn/netcore1.0")
    /// CORESETUP_VERSION_FRAGMENT - The fragment to combine with DOTNET_VERSION_URL to get the current dotnet/core-setup package versions. (ex. "dotnet/core-setup/master")
    /// GITHUB_ORIGIN_OWNER - The owner of the GitHub fork to push the commit and create the PR from. (ex. "dotnet-bot")
    /// GITHUB_UPSTREAM_OWNER - The owner of the GitHub base repo to create the PR to. (ex. "dotnet")
    /// GITHUB_PROJECT - The repo name under the ORIGIN and UPSTREAM owners. (ex. "cli")
    /// GITHUB_UPSTREAM_BRANCH - The branch in the GitHub base repo to create the PR to. (ex. "master");
    /// GITHUB_PULL_REQUEST_NOTIFICATIONS - A semi-colon ';' separated list of GitHub users to notify on the PR.
    /// </remarks>
    public class Config
    {
        public static Config Instance { get; } = new Config();

        private Lazy<string> _userName = new Lazy<string>(() => GetEnvironmentVariable("GITHUB_USER"));
        private Lazy<string> _email = new Lazy<string>(() => GetEnvironmentVariable("GITHUB_EMAIL"));
        private Lazy<string> _password = new Lazy<string>(() => GetEnvironmentVariable("GITHUB_PASSWORD"));

        private Lazy<string> _dotNetVersionUrl = new Lazy<string>(() => GetEnvironmentVariable("DOTNET_VERSION_URL", "https://raw.githubusercontent.com/dotnet/versions/master/build-info"));
        private Lazy<string> _roslynVersionFragment = new Lazy<string>(() => GetEnvironmentVariable("ROSLYN_VERSION_FRAGMENT", "dotnet/roslyn/netcore1.0"));
        private Lazy<string> _coreSetupVersionFragment = new Lazy<string>(() => GetEnvironmentVariable("CORESETUP_VERSION_FRAGMENT", "dotnet/core-setup/master"));
        private Lazy<string> _gitHubUpstreamOwner = new Lazy<string>(() => GetEnvironmentVariable("GITHUB_UPSTREAM_OWNER", "dotnet"));
        private Lazy<string> _gitHubProject = new Lazy<string>(() => GetEnvironmentVariable("GITHUB_PROJECT", "cli"));
        private Lazy<string> _gitHubUpstreamBranch = new Lazy<string>(() => GetEnvironmentVariable("GITHUB_UPSTREAM_BRANCH", "master"));
        private Lazy<string[]> _gitHubPullRequestNotifications = new Lazy<string[]>(() =>
                                                GetEnvironmentVariable("GITHUB_PULL_REQUEST_NOTIFICATIONS", "")
                                                    .Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
        private Config()
        {
        }

        public string UserName => _userName.Value;
        public string Email => _email.Value;
        public string Password => _password.Value;
        public string DotNetVersionUrl => _dotNetVersionUrl.Value;
        public string RoslynVersionFragment => _roslynVersionFragment.Value;
        public string CoreSetupVersionFragment => _coreSetupVersionFragment.Value;
        public string GitHubUpstreamOwner => _gitHubUpstreamOwner.Value;
        public string GitHubProject => _gitHubProject.Value;
        public string GitHubUpstreamBranch => _gitHubUpstreamBranch.Value;
        public string[] GitHubPullRequestNotifications => _gitHubPullRequestNotifications.Value;

        private static string GetEnvironmentVariable(string name, string defaultValue = null)
        {
            string value = Environment.GetEnvironmentVariable(name);
            if (value == null)
            {
                value = defaultValue;
            }

            if (value == null)
            {
                throw new InvalidOperationException($"Can't find environment variable '{name}'.");
            }

            return value;
        }
    }
}


text:
import { BufferGeometry } from '../core/BufferGeometry.js';
import { Float32BufferAttribute } from '../core/BufferAttribute.js';
import { Vector2 } from '../math/Vector2.js';
import { Vector3 } from '../math/Vector3.js';

class RingGeometry extends BufferGeometry {

	constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {

		super();

		this.type = 'RingGeometry';

		this.parameters = {
			innerRadius: innerRadius,
			outerRadius: outerRadius,
			thetaSegments: thetaSegments,
			phiSegments: phiSegments,
			thetaStart: thetaStart,
			thetaLength: thetaLength
		};

		thetaSegments = Math.max( 3, thetaSegments );
		phiSegments = Math.max( 1, phiSegments );

		// buffers

		const indices = [];
		const vertices = [];
		const normals = [];
		const uvs = [];

		// some helper variables

		let radius = innerRadius;
		const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
		const vertex = new Vector3();
		const uv = new Vector2();

		// generate vertices, normals and uvs

		for ( let j = 0; j <= phiSegments; j ++ ) {

			for ( let i = 0; i <= thetaSegments; i ++ ) {

				// values are generate from the inside of the ring to the outside

				const segment = thetaStart + i / thetaSegments * thetaLength;

				// vertex

				vertex.x = radius * Math.cos( segment );
				vertex.y = radius * Math.sin( segment );

				vertices.push( vertex.x, vertex.y, vertex.z );

				// normal

				normals.push( 0, 0, 1 );

				// uv

				uv.x = ( vertex.x / outerRadius + 1 ) / 2;
				uv.y = ( vertex.y / outerRadius + 1 ) / 2;

				uvs.push( uv.x, uv.y );

			}

			// increase the radius for next row of vertices

			radius += radiusStep;

		}

		// indices

		for ( let j = 0; j < phiSegments; j ++ ) {

			const thetaSegmentLevel = j * ( thetaSegments + 1 );

			for ( let i = 0; i < thetaSegments; i ++ ) {

				const segment = i + thetaSegmentLevel;

				const a = segment;
				const b = segment + thetaSegments + 1;
				const c = segment + thetaSegments + 2;
				const d = segment + 1;

				// faces

				indices.push( a, b, d );
				indices.push( b, c, d );

			}

		}

		// build geometry

		this.setIndex( indices );
		this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
		this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
		this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );

	}

	static fromJSON( data ) {

		return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );

	}

}

export { RingGeometry };


text:
import { Field, DataFrame, DataFrameDTO, FieldDTO, FieldType } from '../types/dataFrame';
import { QueryResultMeta } from '../types/data';
import { guessFieldTypeFromValue, guessFieldTypeForField, toDataFrameDTO } from './processDataFrame';
import { isString } from 'lodash';
import { makeFieldParser } from '../utils/fieldParser';
import { MutableVector, Vector } from '../types/vector';
import { ArrayVector } from '../vector/ArrayVector';
import { FunctionalVector } from '../vector/FunctionalVector';

export type MutableField<T = any> = Field<T, MutableVector<T>>;

type MutableVectorCreator = (buffer?: any[]) => MutableVector;

export const MISSING_VALUE: any = undefined; // Treated as connected in new graph panel

export class MutableDataFrame<T = any> extends FunctionalVector<T> implements DataFrame, MutableVector<T> {
  name?: string;
  refId?: string;
  meta?: QueryResultMeta;
  fields: MutableField[] = [];

  private first: Vector = new ArrayVector();
  private creator: MutableVectorCreator;

  constructor(source?: DataFrame | DataFrameDTO, creator?: MutableVectorCreator) {
    super();

    // This creates the underlying storage buffers
    this.creator = creator
      ? creator
      : (buffer?: any[]) => {
          return new ArrayVector(buffer);
        };

    // Copy values from
    if (source) {
      const { name, refId, meta, fields } = source;
      if (name) {
        this.name = name;
      }
      if (refId) {
        this.refId = refId;
      }
      if (meta) {
        this.meta = meta;
      }
      if (fields) {
        for (const f of fields) {
          this.addField(f);
        }
      }
    }

    // Get Length to show up if you use spread
    Object.defineProperty(this, 'length', {
      enumerable: true,
      get: () => {
        return this.first.length;
      },
    });
  }

  // Defined for Vector interface
  get length() {
    return this.first.length;
  }

  addFieldFor(value: any, name?: string): MutableField {
    return this.addField({
      name: name || '', // Will be filled in
      type: guessFieldTypeFromValue(value),
    });
  }

  addField(f: Field | FieldDTO, startLength?: number): MutableField {
    let buffer: any[] | undefined = undefined;

    if (f.values) {
      if (Array.isArray(f.values)) {
        buffer = f.values as any[];
      } else {
        buffer = (f.values as Vector).toArray();
      }
    }

    let type = f.type;

    if (!type && ('time' === f.name || 'Time' === f.name)) {
      type = FieldType.time;
    } else {
      if (!type && buffer && buffer.length) {
        type = guessFieldTypeFromValue(buffer[0]);
      }
      if (!type) {
        type = FieldType.other;
      }
    }

    // Make sure it has a name
    let name = f.name;
    if (!name) {
      name = `Field ${this.fields.length + 1}`;
    }

    const field: MutableField = {
      ...f,
      name,
      type,
      config: f.config || {},
      values: this.creator(buffer),
    };

    if (type === FieldType.other) {
      type = guessFieldTypeForField(field);
      if (type) {
        field.type = type;
      }
    }

    this.fields.push(field);
    this.first = this.fields[0].values;

    // Make sure the field starts with a given length
    if (startLength) {
      while (field.values.length < startLength) {
        field.values.add(MISSING_VALUE);
      }
    } else {
      this.validate();
    }

    return field;
  }

  validate() {
    // Make sure all arrays are the same length
    const length = this.fields.reduce((v: number, f) => {
      return Math.max(v, f.values.length);
    }, 0);

    // Add empty elements until everything matches
    for (const field of this.fields) {
      while (field.values.length !== length) {
        field.values.add(MISSING_VALUE);
      }
    }
  }

  /**
   * Reverse all values
   */
  reverse() {
    for (const f of this.fields) {
      f.values.reverse();
    }
  }

  /**
   * This will add each value to the corresponding column
   */
  appendRow(row: any[]) {
    // Add any extra columns
    for (let i = this.fields.length; i < row.length; i++) {
      this.addField({
        name: `Field ${i + 1}`,
        type: guessFieldTypeFromValue(row[i]),
      });
    }

    // The first line may change the field types
    if (this.length < 1) {
      for (let i = 0; i < this.fields.length; i++) {
        const f = this.fields[i];
        if (!f.type || f.type === FieldType.other) {
          f.type = guessFieldTypeFromValue(row[i]);
        }
      }
    }

    for (let i = 0; i < this.fields.length; i++) {
      const f = this.fields[i];
      let v = row[i];
      if (f.type !== FieldType.string && isString(v)) {
        if (!f.parse) {
          f.parse = makeFieldParser(v, f);
        }
        v = f.parse(v);
      }
      f.values.add(v);
    }
  }

  /**
   * Add values from an object to corresponding fields. Similar to appendRow but does not create new fields.
   */
  add(value: T) {
    // Will add one value for every field
    const obj = value as any;
    for (const field of this.fields) {
      let val = obj[field.name];

      if (field.type !== FieldType.string && isString(val)) {
        if (!field.parse) {
          field.parse = makeFieldParser(val, field);
        }
        val = field.parse(val);
      }

      if (val === undefined) {
        val = MISSING_VALUE;
      }

      field.values.add(val);
    }
  }

  set(index: number, value: T) {
    if (index > this.length) {
      throw new Error('Unable ot set value beyond current length');
    }

    const obj = (value as any) || {};
    for (const field of this.fields) {
      field.values.set(index, obj[field.name]);
    }
  }

  /**
   * Get an object with a property for each field in the DataFrame
   */
  get(idx: number): T {
    const v: any = {};
    for (const field of this.fields) {
      v[field.name] = field.values.get(idx);
    }
    return v as T;
  }

  /**
   * The simplified JSON values used in JSON.stringify()
   */
  toJSON() {
    return toDataFrameDTO(this);
  }
}


text:
package chicm;

/**
 * Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
 * @author chicm
 *
 */
public class ReverseInteger {
  public int reverse(int x) {
    int y = 0;
    for(;;) {
        int a = x % 10;
        x /= 10;
        y = y * 10 + a;
        if (x == 0)
            break;
    }
    return y;
}
}


text:
import unittest

import file_manager

class FileManagerTest(unittest.TestCase):
  def testMakeArchivedFilename(self):
    fm = file_manager.FileManager()
    self.assertEquals(".foo.bak", fm._archived_file("foo"))
    self.assertEquals("bar/.foo.bak", fm._archived_file("bar/foo"))
    self.assertEquals("/bar/.foo.bak", fm._archived_file("/bar/foo"))
    self.assertEquals(".foo.html.bak", fm._archived_file("foo.html"))

  def testArchiveAlreadyArchived(self):
    class MockEnv:
      def __init__(self):
        self.called_rename = False

      def CheckPath(self, path):
        # Pretend we've already archived this file
        assert path == ".foo.bak"
        return True

      def RenameFile(self, src, dest):
        self.called_rename = True

    env = MockEnv()
    fm = file_manager.FileManager(env=env)
    fm.archive("foo")
    self.assertFalse(env.called_rename)

  def testArchiveMovesStuff(self):
    class MockEnv:
      def __init__(self):
        self.rename_args = None

      def MoveFile(self, src, dest):
        self.rename_args = src, dest

      def CheckPath(self, path):
        # Pretend we HAVEN'T already archived this file
        assert path == ".foo.bak"
        return False

    env = MockEnv()
    fm = file_manager.FileManager(env=env)
    fm.archive("foo")
    self.assertEquals(("foo", ".foo.bak"), env.rename_args)

  def testReadUnarchived(self):
    class MockEnv:
      def __init__(self):
        self.called_read = False

      def ReadFile(self, file):
        assert file == "foo"
        self.called_read = True
        return "file content"

    env = MockEnv()
    fm = file_manager.FileManager(env=env)
    self.assertEquals("file content", fm.read("foo"))
    self.assertTrue(env.called_read)

  def testReadArchived(self):
    class MockEnv:
      def __init__(self):
        self.called_read = False

      def CheckPath(self, file):
        # Pretend we've already archived this file
        assert file == ".foo.bak"
        return True

      def ReadFile(self, file):
        assert file == ".foo.bak"  # We'll read the archive if it exists.
        self.called_read = True
        return "file content"

    env = MockEnv()
    fm = file_manager.FileManager(env=env)
    fm.archive("foo")
    self.assertEquals("file content", fm.read("foo"))
    self.assertTrue(env.called_read)

  def testDiff(self):
    class MockEnv:
      def __init__(self):
        pass
      def ReadFile(self, file):
        assert file == "foo"
        return "Original contents"
      def CheckPath(self, file):
        assert file == "foo"
        return True

    env=MockEnv()
    fm = file_manager.FileManager(env=env)
    fm.save("foo", "New contents")
    expected = ("M foo\n"
                "--- foo \n"
                "+++ foo \n"
                "@@ -1,1 +1,1 @@\n"
                "-Original contents\n"
                "+New contents\n")
    self.assertEquals(expected, fm.show_diff())

  def testDiffNew(self):
    class MockEnv:
      def __init__(self):
        pass
      def ReadFile(self, file):
        assert False, "This method should never be called!"
      def CheckPath(self, file):
        assert file == "foo"
        return False
    env = MockEnv()
    fm = file_manager.FileManager(env=env)
    fm.save("foo", "clobbered!")
    expected = "A foo\n"
    self.assertEquals(expected, fm.show_diff())

  def testCommitDirectoryExists(self):
    test = self
    class MockEnv:
      def __init__(self):
        pass

      def CheckPath(self, path):
        test.assertEquals(".", path)
        return True

      def WriteFile(self, path, contents):
        assert path == "foo"
        assert contents == "contents"

    env = MockEnv()
    fm = file_manager.FileManager(env=env)
    fm.save("foo", "contents")
    fm.commit()

  def testCommitDirectoryDoesntExist(self):
    class MockEnv:
      def __init__(self):
        self.called_mkdir = False

      def CheckPath(self, path):
        assert path == "dir"
        return False

      def WriteFile(self, path, contents):
        assert path == "dir/foo"
        assert contents == "contents"

      def MakeDir(self, path):
        assert path == "dir"
        self.called_mkdir = True
        return True

    env = MockEnv()
    fm = file_manager.FileManager(env=env)
    fm.save("dir/foo", "contents")
    fm.commit()
    self.assertTrue(env.called_mkdir)

if __name__ == '__main__':
  unittest.main()


text:
package org.apache.solr.client.solrj.request;

import static org.apache.solr.common.params.CommonParams.JAVABIN_MIME;
import static org.apache.solr.common.params.CommonParams.JSON_MIME;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.solr.client.solrj.ResponseParser;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.response.V2Response;
import org.apache.solr.common.MapWriter;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.JavaBinCodec;
import org.apache.solr.common.util.Utils;

public class V2Request extends SolrRequest<V2Response> implements MapWriter {
  // only for debugging purposes
  public static final ThreadLocal<AtomicLong> v2Calls = new ThreadLocal<>();
  static final Pattern COLL_REQ_PATTERN = Pattern.compile("/(c|collections)/([^/]+)/(?!shards)");
  private Object payload;
  private SolrParams solrParams;
  public final boolean useBinary;
  private String collection;
  private String mimeType;
  private boolean forceV2 = false;
  private boolean isPerCollectionRequest = false;
  private ResponseParser parser;

  private V2Request(METHOD m, String resource, boolean useBinary) {
    super(m, resource);
    Matcher matcher = COLL_REQ_PATTERN.matcher(getPath());
    if (matcher.find()) {
      this.collection = matcher.group(2);
      isPerCollectionRequest = true;
    }
    this.useBinary = useBinary;
  }

  public boolean isForceV2() {
    return forceV2;
  }

  @Override
  public SolrParams getParams() {
    return solrParams;
  }

  @Override
  public RequestWriter.ContentWriter getContentWriter(String s) {
    if (v2Calls.get() != null) v2Calls.get().incrementAndGet();
    if (payload == null) return null;
    if (payload instanceof String) {
      return new RequestWriter.StringPayloadContentWriter((String) payload, JSON_MIME);
    }
    return new RequestWriter.ContentWriter() {
      @Override
      public void write(OutputStream os) throws IOException {
        if (payload instanceof ByteBuffer) {
          ByteBuffer b = (ByteBuffer) payload;
          os.write(b.array(), b.arrayOffset(), b.limit());
          return;
        }
        if (payload instanceof InputStream) {
          ((InputStream) payload).transferTo(os);
          return;
        }
        if (useBinary) {
          new JavaBinCodec().marshal(payload, os);
        } else {
          Utils.writeJson(payload, os, false);
        }
      }

      @Override
      public String getContentType() {
        if (mimeType != null) return mimeType;
        return useBinary ? JAVABIN_MIME : JSON_MIME;
      }
    };
  }

  public boolean isPerCollectionRequest() {
    return isPerCollectionRequest;
  }

  @Override
  public String getCollection() {
    return collection;
  }

  @Override
  protected V2Response createResponse(SolrClient client) {
    return new V2Response();
  }

  @Override
  public void writeMap(EntryWriter ew) throws IOException {
    ew.put("method", getMethod().toString());
    ew.put("path", getPath());
    ew.putIfNotNull("params", solrParams);
    ew.putIfNotNull("command", payload);
  }

  @Override
  public ResponseParser getResponseParser() {
    if (parser != null) return parser;
    return super.getResponseParser();
  }

  @Override
  public String getRequestType() {
    return SolrRequestType.ADMIN.toString();
  }

  public static class Builder {
    private String resource;
    private METHOD method = METHOD.GET;
    private Object payload;
    private SolrParams params;
    private boolean useBinary = false;

    private boolean forceV2EndPoint = false;
    private ResponseParser parser;
    private String mimeType;

    /**
     * Create a Builder object based on the provided resource. The default method is GET.
     *
     * @param resource resource of the request for example "/collections" or "/cores/core-name"
     */
    public Builder(String resource) {
      if (!resource.startsWith("/")) resource = "/" + resource;
      this.resource = resource;
    }

    public Builder withMethod(METHOD m) {
      this.method = m;
      return this;
    }

    public Builder POST() {
      this.method = METHOD.POST;
      return this;
    }

    public Builder GET() {
      this.method = METHOD.GET;
      return this;
    }

    public Builder PUT() {
      this.method = METHOD.PUT;
      return this;
    }

    public Builder DELETE() {
      this.method = METHOD.DELETE;
      return this;
    }

    /** Only for testing. It's always true otherwise */
    public Builder forceV2(boolean flag) {
      forceV2EndPoint = flag;
      return this;
    }

    /**
     * Set payload for request.
     *
     * @param payload as UTF-8 String
     * @return builder object
     */
    public Builder withPayload(String payload) {
      if (payload != null) {
        this.payload = payload;
      }
      return this;
    }

    public Builder withPayload(Object payload) {
      this.payload = payload;
      return this;
    }

    public Builder withParams(SolrParams params) {
      this.params = params;
      return this;
    }

    public Builder useBinary(boolean flag) {
      this.useBinary = flag;
      return this;
    }

    public Builder withResponseParser(ResponseParser parser) {
      this.parser = parser;
      return this;
    }

    public Builder withMimeType(String mimeType) {
      this.mimeType = mimeType;
      return this;
    }

    public V2Request build() {
      V2Request v2Request = new V2Request(method, resource, useBinary);
      v2Request.solrParams = params;
      v2Request.payload = payload;
      v2Request.forceV2 = forceV2EndPoint;
      v2Request.mimeType = mimeType;
      v2Request.parser = parser;
      return v2Request;
    }
  }
}


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

/// <summary>
/// Transaction repository is used to process payments and returns.
///
/// Use this if you want to collect payments with credit cards, Interac, or with tokens using the Legato service.
///
/// Each transaction returns a PaymentResponse that holds the transaction's information, including the payment ID when creating a payment.
/// This Payment ID is used for returns.
///
/// Usage:
///
///  Gateway bambora = new Gateway () {
/// 	MerchantId = 300200578,
/// 	ApiKey = "4BaD82D9197b4cc4b70a221911eE9f70",
/// 	ApiVersion = "1"
///  };
///
///  PaymentResponse response = bambora.Payments.MakePayment (
/// 	new CardPaymentRequest {
/// 		Amount = 100.00,
/// 		OrderNumber = orderNum++.ToString(),
/// 		Card = new Card {
/// 			Name = "John Doe",
/// 			Number = "5100000010001004",
/// 			ExpiryMonth = "12",
/// 			ExpiryYear = "18",
/// 			Cvd = "123"
/// 		}
/// 	}
///  );
///
/// </summary>

namespace Bambora.NA.SDK
{
	public class PaymentsAPI
	{
		private Configuration _configuration;
		private IWebCommandExecuter _webCommandExecuter = new WebCommandExecuter ();

		public Configuration Configuration {
			set { _configuration = value; }
		}

		public IWebCommandExecuter WebCommandExecuter {
			set { _webCommandExecuter = value; }
		}

		/// <summary>
		/// Make a credit card payment.
		/// </summary>
		/// <returns>he payment result</returns>
		/// <param name="paymentRequest">Payment request.</param>
		public PaymentResponse MakePayment(PaymentRequest paymentRequest) {

			Gateway.ThrowIfNullArgument (paymentRequest, "paymentRequest");

			string url = BamboraUrls.BasePaymentsUrl
							.Replace("{v}", String.IsNullOrEmpty(_configuration.Version) ? "v1" : "v"+_configuration.Version)
	   					    .Replace("{p}", String.IsNullOrEmpty(_configuration.Platform) ? "www" : _configuration.Platform);

			HttpsWebRequest req = new HttpsWebRequest () {
				MerchantId = _configuration.MerchantId,
				Passcode = _configuration.PaymentsApiPasscode,
				WebCommandExecutor = _webCommandExecuter
			};

			string response = req.ProcessTransaction (HttpMethod.Post, url, paymentRequest);

			return JsonConvert.DeserializeObject<PaymentResponse>(response);

		}

		/// <summary>
		/// Return a previous payment made through Bambora
		/// </summary>
		/// <returns>The payment result</returns>
		/// <param name="paymentId">Payment identifier.</param>
		/// <param name="returnRequest">Return request.</param>
		public PaymentResponse Return(string paymentId, ReturnRequest returnRequest) {

			Gateway.ThrowIfNullArgument (returnRequest, "returnRequest");
			Gateway.ThrowIfNullArgument (paymentId, "paymentId");

			string url = BamboraUrls.ReturnsUrl
				.Replace("{v}", String.IsNullOrEmpty(_configuration.Version) ? "v1" : "v"+_configuration.Version)
				.Replace("{p}", String.IsNullOrEmpty(_configuration.Platform) ? "www" : _configuration.Platform)
				.Replace("{id}", String.IsNullOrEmpty(paymentId) ? "" : paymentId);

			HttpsWebRequest req = new HttpsWebRequest () {
				MerchantId = _configuration.MerchantId,
				Passcode = _configuration.PaymentsApiPasscode,
				WebCommandExecutor = _webCommandExecuter
			};
			returnRequest.MerchantId = _configuration.MerchantId.ToString();

			string response = req.ProcessTransaction (HttpMethod.Post, url, returnRequest);
			Console.WriteLine (response);
			return JsonConvert.DeserializeObject<PaymentResponse>(response);

		}

		/// <summary>
		/// Return a previous card payment that was not made through Bambora. Use this if you would like to
		/// return a payment but that payment was performed on another gateway.
		///
		/// You must have this capability enabled on your account by calling Bambora support. It is dangerous to
		/// have it enabled as the API will not check if you have a transaction ID.
		/// </summary>
		/// <returns>The return result</returns>
		/// <param name="returnRequest">Return request.</param>
		/// <param name="adjId">Reference the transaction identification number (trnId) from the original purchase</param>
		public PaymentResponse UnreferencedReturn(UnreferencedCardReturnRequest returnRequest) {

			Gateway.ThrowIfNullArgument (returnRequest, "returnRequest");

			string url = BamboraUrls.ReturnsUrl
				.Replace("{v}", String.IsNullOrEmpty(_configuration.Version) ? "v1" : "v"+_configuration.Version)
				.Replace("{p}", String.IsNullOrEmpty(_configuration.Platform) ? "www" : _configuration.Platform)
				.Replace("{id}", "0"); // uses ID 0 since there is no existing payment ID for this transaction

			HttpsWebRequest req = new HttpsWebRequest () {
				MerchantId = _configuration.MerchantId,
				Passcode = _configuration.PaymentsApiPasscode,
				WebCommandExecutor = _webCommandExecuter
			};
			returnRequest.MerchantId = _configuration.MerchantId.ToString();

			string response = req.ProcessTransaction (HttpMethod.Post, url, returnRequest);
			return JsonConvert.DeserializeObject<PaymentResponse>(response);
		}

		/// <summary>
		/// Return a previous swipe payment that was not made through Bambora. Use this if you would like to
		/// return a payment but that payment was performed on another payment service.
		///
		/// You must have this capability enabled on your account by calling Bambora support. It is dangerous to
		/// have it enabled as the API will not check if you have a transaction ID.
		/// </summary>
		/// <returns>The return result</returns>
		/// <param name="returnRequest">Return request.</param>
		public PaymentResponse UnreferencedReturn(UnreferencedSwipeReturnRequest returnRequest) {

			Gateway.ThrowIfNullArgument (returnRequest, "returnRequest");

			string url = BamboraUrls.ReturnsUrl
				.Replace("{v}", String.IsNullOrEmpty(_configuration.Version) ? "v1" : "v"+_configuration.Version)
				.Replace("{p}", String.IsNullOrEmpty(_configuration.Platform) ? "www" : _configuration.Platform)
				.Replace("{id}", "0"); // uses ID 0 since there is no existing payment ID for this transaction

			HttpsWebRequest req = new HttpsWebRequest () {
				MerchantId = _configuration.MerchantId,
				Passcode = _configuration.PaymentsApiPasscode,
				WebCommandExecutor = _webCommandExecuter
			};
			returnRequest.MerchantId = _configuration.MerchantId.ToString();

			string response = req.ProcessTransaction (HttpMethod.Post, url, returnRequest);
			return JsonConvert.DeserializeObject<PaymentResponse>(response);
		}

		/// <summary>
		/// Void the specified paymentId.
		///
		/// Voids generally need to occur before end of business on the same day that the transaction was processed.
		///
		/// Voids are used to cancel a transaction before the item is registered against a customer credit card account.
		/// Cardholders will never see a voided transaction on their credit card statement. As a result, voids can only
		/// be attempted on the same day as the original transaction. After the end of day (roughly 11:59 pm EST/EDT),
		/// void requests will be rejected from the API if attempted.
		/// </summary>
		/// <returns>The return result</returns>
		/// <param name="paymentId">Payment identifier from a previous transaction.</param>
		public PaymentResponse Void(string paymentId, decimal amount) {

			Gateway.ThrowIfNullArgument (paymentId, "paymentId");

			string url = BamboraUrls.VoidsUrl
				.Replace("{v}", String.IsNullOrEmpty(_configuration.Version) ? "v1" : "v"+_configuration.Version)
				.Replace("{p}", String.IsNullOrEmpty(_configuration.Platform) ? "www" : _configuration.Platform)
				.Replace("{id}", paymentId);

			HttpsWebRequest req = new HttpsWebRequest () {
				MerchantId = _configuration.MerchantId,
				Passcode = _configuration.PaymentsApiPasscode,
				WebCommandExecutor = _webCommandExecuter
			};

			var VoidPayment = new
			{
				merchant_id = _configuration.MerchantId,
				amount = amount
			};

			string response = req.ProcessTransaction (HttpMethod.Post, url, VoidPayment);
			Console.WriteLine (response);
			return JsonConvert.DeserializeObject<PaymentResponse>(response);
		}

		/// <summary>
		/// Pre-authorize a payment. Use this if you want to know if a customer has sufficient funds
		/// before processing a payment. A real-world example of this is pre-authorizing at the gas pump
		/// for $100 before you fill up, then end up only using $60 of gas; the customer is only charged
		/// $60. The final payment is used with PreAuthCompletion().
		/// </summary>
		/// <returns>The response, in particular the payment ID that is needed to complete the purchase.</returns>
		/// <param name="paymentRequest">Payment request.</param>
		public PaymentResponse PreAuth(CardPaymentRequest paymentRequest) {

			Gateway.ThrowIfNullArgument (paymentRequest, "paymentRequest");

			paymentRequest.Card.Complete = false; // false to make it a pre-auth

			return PreAuthInternal (paymentRequest);
		}

		/// <summary>
		/// Pre-authorize a payment. Use this if you want to know if a customer has sufficient funds
		/// before processing a payment. A real-world example of this is pre-authorizing at the gas pump
		/// for $100 before you fill up, then end up only using $60 of gas; the customer is only charged
		/// $60. The final payment is used with PreAuthCompletion().
		///
		/// The PreAuth is used with tokenized payments with a token generated from the Legato Javascript service.
		/// </summary>
		/// <returns>The response, in particular the payment ID that is needed to complete the purchase.</returns>
		/// <param name="paymentRequest">Payment request.</param>
		public PaymentResponse PreAuth(TokenPaymentRequest paymentRequest) {

			Gateway.ThrowIfNullArgument (paymentRequest, "paymentRequest");

			paymentRequest.Token.Complete = false;

			return PreAuthInternal (paymentRequest);
		}

		/// <summary>
		/// Pre-authorize a payment. Use this if you want to know if a customer has sufficient funds
		/// before processing a payment. A real-world example of this is pre-authorizing at the gas pump
		/// for $100 before you fill up, then end up only using $60 of gas; the customer is only charged
		/// $60. The final payment is used with PreAuthCompletion().
		///
		/// The PreAuth is used with tokenized payments with a token generated from the Legato Javascript service.
		/// </summary>
		/// <returns>The response, in particular the payment ID that is needed to complete the purchase.</returns>
		/// <param name="paymentRequest">Payment request.</param>
		public PaymentResponse PreAuth(ProfilePaymentRequest paymentRequest) {

			Gateway.ThrowIfNullArgument (paymentRequest, "paymentRequest");

			paymentRequest.PaymentProfile.Complete = false;

			return PreAuthInternal (paymentRequest);
		}

		/// <summary>
		/// Internal handling of the Pre-auth requests after the 'complete' parameter
		/// has been modified on the various PaymentRequest objects.
		/// </summary>
		/// <returns>The auth.</returns>
		/// <param name="paymentRequest">Payment request.</param>
		private PaymentResponse PreAuthInternal(PaymentRequest paymentRequest) {

			string url = BamboraUrls.BasePaymentsUrl
				.Replace ("{v}", String.IsNullOrEmpty (_configuration.Version) ? "v1" : "v" + _configuration.Version)
				.Replace ("{p}", String.IsNullOrEmpty (_configuration.Platform) ? "www" : _configuration.Platform);

			HttpsWebRequest req = new HttpsWebRequest () {
				MerchantId = _configuration.MerchantId,
				Passcode = _configuration.PaymentsApiPasscode,
				WebCommandExecutor = _webCommandExecuter
			};

			string response = req.ProcessTransaction (HttpMethod.Post, url, paymentRequest);
			return JsonConvert.DeserializeObject<PaymentResponse>(response);
		}

		/// <summary>
		/// Push the actual payment through after a pre-authorization.
		///
		/// Example:
		/// Pre-authorize at the gas pump for $100 using Pre-Authorization request. Card is approved for $100 but not charged.
		/// Consumer fills up with $60 worth of gas. Run the Pre-Auth-Completion request to process the actual
		/// payment for $60.
		///
		/// </summary>
		/// <returns>Response to the payment</returns>
		/// <param name="paymentId">Payment identifier obtained from the Pre-Auth request.</param>
		/// <param name="amount">Amount to process</param>
		public PaymentResponse PreAuthCompletion(string paymentId, decimal amount) {

			PaymentRequest pr = new PaymentRequest ();
			pr.Amount = amount;

			return PreAuthCompletion (paymentId, pr);
		}

		/// <summary>
		/// Push the actual payment through after a pre-authorization.
		///
		/// Example:
		/// Pre-authorize at the gas pump for $100 using Pre-Authorization request. Card is approved for $100 but not charged.
		/// Consumer fills up with $60 worth of gas. Run the Pre-Auth-Completion request to process the actual
		/// payment for $60.
		///
		/// </summary>
		/// <returns>Response to the payment</returns>
		/// <param name="paymentId">Payment identifier obtained from the Pre-Auth request.</param>
		/// <param name="amount">Amount to process</param>
		/// <param name="orderNumber">Optional order number</param>
		public PaymentResponse PreAuthCompletion(string paymentId, PaymentRequest paymentRequest) {

			Gateway.ThrowIfNullArgument (paymentId, "paymentId");

			string url = BamboraUrls.PreAuthCompletionsUrl
				.Replace("{v}", String.IsNullOrEmpty(_configuration.Version) ? "v1" : "v"+_configuration.Version)
				.Replace("{p}", String.IsNullOrEmpty(_configuration.Platform) ? "www" : _configuration.Platform)
				.Replace("{id}", paymentId);

			HttpsWebRequest req = new HttpsWebRequest () {
				MerchantId = _configuration.MerchantId,
				Passcode = _configuration.PaymentsApiPasscode,
				WebCommandExecutor = _webCommandExecuter
			};

			string response = req.ProcessTransaction (HttpMethod.Post, url, paymentRequest);
			return JsonConvert.DeserializeObject<PaymentResponse>(response);
		}

	}
}


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

package ugia.io.androidbeautytreatment.util;

import ugia.io.androidbeautytreatment.model.Contact;

/**
 * Ghost data provider utils that simulates a source of information.
 * <p/>
 * Created by joseluisugia on 18/11/15.
 */
public class Poets {

    public static Contact[] generate() {

        return new Contact[] {

                new Contact("Pio Baroja", "123", true),
                new Contact("Miguel Hernandez", "456", false),
                new Contact("Miguel de Cervantes", "789", false),
                new Contact("Juan Ramón Jimenez", "101", true),
                new Contact("Miguel de Unamuno", "112", true),
                new Contact("Antonio Machado", "175", false),
                new Contact("Federico García Lorca", "623", false),
                new Contact("Ramiro de Maeztu", "999", true),
                new Contact("Ramón María del Valle-Inclán", "747", false),
                new Contact("Ángel Ganivet", "622", false),
                new Contact("Enrique de Mesa", "278", true),
                new Contact("Azorín", "345", false)
        };
    }

}


text:
namespace Mordor {
namespace PQ {

struct Exception : virtual ::Mordor::Exception
{
    Exception(const std::string &message)
        : m_message(message)
    {}
    Exception()
    {}
    ~Exception() throw () {}

    const char *what() const throw () { return m_message.c_str(); }
private:
    std::string m_message;
};

#define DEFINE_MORDOR_PQ_EXCEPTION(Exception, Base)                             \
struct Exception : Base                                                         \
{                                                                               \
    Exception()                                                                 \
    {}                                                                          \
    Exception(const std::string &message)                                       \
        : Base(message)                                                         \
    {}                                                                          \
};

DEFINE_MORDOR_PQ_EXCEPTION(ConnectionException, Exception);

DEFINE_MORDOR_PQ_EXCEPTION(DataException, Exception);
DEFINE_MORDOR_PQ_EXCEPTION(ArraySubscriptError, DataException);
DEFINE_MORDOR_PQ_EXCEPTION(CharacterNotInRepertoireException, DataException);
DEFINE_MORDOR_PQ_EXCEPTION(OverflowException, DataException);
DEFINE_MORDOR_PQ_EXCEPTION(DivisionByZeroException, DataException);
DEFINE_MORDOR_PQ_EXCEPTION(AssignmentError, DataException);
DEFINE_MORDOR_PQ_EXCEPTION(EscapeCharacterConflictException, DataException);
DEFINE_MORDOR_PQ_EXCEPTION(InvalidArgumentException, DataException);
DEFINE_MORDOR_PQ_EXCEPTION(NullValueNotAllowedException, DataException);

DEFINE_MORDOR_PQ_EXCEPTION(IntegrityConstraintViolationException, Exception)
DEFINE_MORDOR_PQ_EXCEPTION(RestrictViolationException, IntegrityConstraintViolationException)
DEFINE_MORDOR_PQ_EXCEPTION(NotNullViolationException, IntegrityConstraintViolationException)
DEFINE_MORDOR_PQ_EXCEPTION(ForeignKeyViolationException, IntegrityConstraintViolationException)
DEFINE_MORDOR_PQ_EXCEPTION(UniqueViolationException, IntegrityConstraintViolationException)
DEFINE_MORDOR_PQ_EXCEPTION(CheckViolationException, IntegrityConstraintViolationException)

DEFINE_MORDOR_PQ_EXCEPTION(InvalidTransactionStateException, Exception);
DEFINE_MORDOR_PQ_EXCEPTION(ActiveTransactionException, InvalidTransactionStateException);
DEFINE_MORDOR_PQ_EXCEPTION(BranchTransactionAlreadyActiveException, InvalidTransactionStateException);
DEFINE_MORDOR_PQ_EXCEPTION(HeldCursorRequiresSameIsolationLevelException, InvalidTransactionStateException);
DEFINE_MORDOR_PQ_EXCEPTION(InappropriateAccessModeForBranchTransactionException, InvalidTransactionStateException);
DEFINE_MORDOR_PQ_EXCEPTION(InappropriateIsolationLevelForBranchTransactionException, InvalidTransactionStateException);
DEFINE_MORDOR_PQ_EXCEPTION(NoActiveTransactionForBranchException, InvalidTransactionStateException);
DEFINE_MORDOR_PQ_EXCEPTION(ReadOnlyTransactionException, InvalidTransactionStateException);
DEFINE_MORDOR_PQ_EXCEPTION(SchemaAndDataStatementMixingNotSupportedException, InvalidTransactionStateException);
DEFINE_MORDOR_PQ_EXCEPTION(NoActiveTransactionException, InvalidTransactionStateException);
DEFINE_MORDOR_PQ_EXCEPTION(InFailedTransactionException, InvalidTransactionStateException);

DEFINE_MORDOR_PQ_EXCEPTION(TransactionRollbackException, Exception);
DEFINE_MORDOR_PQ_EXCEPTION(TransactionIntegrityConstraintViolationException, TransactionRollbackException);
DEFINE_MORDOR_PQ_EXCEPTION(SerializationFailureException, TransactionRollbackException);
DEFINE_MORDOR_PQ_EXCEPTION(StatementCompletionUnknownException, TransactionRollbackException);
DEFINE_MORDOR_PQ_EXCEPTION(DeadlockDetectedException, TransactionRollbackException);

DEFINE_MORDOR_PQ_EXCEPTION(AccessRuleViolationException, Exception);
DEFINE_MORDOR_PQ_EXCEPTION(SyntaxError, AccessRuleViolationException);
DEFINE_MORDOR_PQ_EXCEPTION(InsufficientPrivilegeException, AccessRuleViolationException);
DEFINE_MORDOR_PQ_EXCEPTION(CannotCoerceException, AccessRuleViolationException);
DEFINE_MORDOR_PQ_EXCEPTION(GroupingError, SyntaxError);
DEFINE_MORDOR_PQ_EXCEPTION(WindowingError, SyntaxError);
DEFINE_MORDOR_PQ_EXCEPTION(InvalidRecursionException, SyntaxError);
DEFINE_MORDOR_PQ_EXCEPTION(InvalidForeignKeyException, AccessRuleViolationException);
DEFINE_MORDOR_PQ_EXCEPTION(InvalidNameException, SyntaxError);
DEFINE_MORDOR_PQ_EXCEPTION(NameTooLongException, SyntaxError);
DEFINE_MORDOR_PQ_EXCEPTION(ReservedNameException, SyntaxError);
DEFINE_MORDOR_PQ_EXCEPTION(DatatypeMismatchException, AccessRuleViolationException);
DEFINE_MORDOR_PQ_EXCEPTION(IndeterminateDatatypeException, AccessRuleViolationException);
DEFINE_MORDOR_PQ_EXCEPTION(WrongObjectTypeException, AccessRuleViolationException);
DEFINE_MORDOR_PQ_EXCEPTION(UndefinedColumnException, AccessRuleViolationException);
DEFINE_MORDOR_PQ_EXCEPTION(UndefinedFunctionException, AccessRuleViolationException);
DEFINE_MORDOR_PQ_EXCEPTION(UndefinedTableException, AccessRuleViolationException);
DEFINE_MORDOR_PQ_EXCEPTION(UndefinedParameterException, AccessRuleViolationException);
DEFINE_MORDOR_PQ_EXCEPTION(UndefinedObjectException, AccessRuleViolationException);
DEFINE_MORDOR_PQ_EXCEPTION(DuplicateColumnException, AccessRuleViolationException);
DEFINE_MORDOR_PQ_EXCEPTION(DuplicateCursorException, AccessRuleViolationException);
DEFINE_MORDOR_PQ_EXCEPTION(DuplicateDatabaseException, AccessRuleViolationException);
DEFINE_MORDOR_PQ_EXCEPTION(DuplicateFunctionException, AccessRuleViolationException);
DEFINE_MORDOR_PQ_EXCEPTION(DuplicatePreparedStatementException, AccessRuleViolationException);
DEFINE_MORDOR_PQ_EXCEPTION(DuplicateSchemaException, AccessRuleViolationException);
DEFINE_MORDOR_PQ_EXCEPTION(DuplicateTableException, AccessRuleViolationException);
DEFINE_MORDOR_PQ_EXCEPTION(DuplicateAliasException, AccessRuleViolationException);
DEFINE_MORDOR_PQ_EXCEPTION(DuplicateObjectException, AccessRuleViolationException);
DEFINE_MORDOR_PQ_EXCEPTION(AmbiguousColumnException, AccessRuleViolationException);
DEFINE_MORDOR_PQ_EXCEPTION(AmbiguousFunctionException, AccessRuleViolationException);
DEFINE_MORDOR_PQ_EXCEPTION(AmbiguousParameterException, AccessRuleViolationException);
DEFINE_MORDOR_PQ_EXCEPTION(AmbiguousAliasException, AccessRuleViolationException);
DEFINE_MORDOR_PQ_EXCEPTION(InvalidColumnReferenceException, AccessRuleViolationException);
DEFINE_MORDOR_PQ_EXCEPTION(InvalidColumnDefinitionException, AccessRuleViolationException);
DEFINE_MORDOR_PQ_EXCEPTION(InvalidCursorDefinitionException, AccessRuleViolationException);
DEFINE_MORDOR_PQ_EXCEPTION(InvalidDatabaseDefinitionException, AccessRuleViolationException);
DEFINE_MORDOR_PQ_EXCEPTION(InvalidFunctionDefinitionException, AccessRuleViolationException);
DEFINE_MORDOR_PQ_EXCEPTION(InvalidPreparedStatementDefinitionException, AccessRuleViolationException);
DEFINE_MORDOR_PQ_EXCEPTION(InvalidSchemaDefinitionException, AccessRuleViolationException);
DEFINE_MORDOR_PQ_EXCEPTION(InvalidTableDefinitionException, AccessRuleViolationException);
DEFINE_MORDOR_PQ_EXCEPTION(InvalidObjectDefinitionException, AccessRuleViolationException);

DEFINE_MORDOR_PQ_EXCEPTION(InsufficientResourcesException, Exception);
DEFINE_MORDOR_PQ_EXCEPTION(DiskFullException, InsufficientResourcesException);
DEFINE_MORDOR_PQ_EXCEPTION(OutOfMemoryException, InsufficientResourcesException);
DEFINE_MORDOR_PQ_EXCEPTION(TooManyConnectionsException, InsufficientResourcesException);

DEFINE_MORDOR_PQ_EXCEPTION(ProgramLimitExceededException, Exception);
DEFINE_MORDOR_PQ_EXCEPTION(StatementTooComplexException, ProgramLimitExceededException);
DEFINE_MORDOR_PQ_EXCEPTION(TooManyColumnsException, ProgramLimitExceededException);
DEFINE_MORDOR_PQ_EXCEPTION(TooManyArgumentsException, ProgramLimitExceededException);

DEFINE_MORDOR_PQ_EXCEPTION(OperatorInterventionException, Exception);
DEFINE_MORDOR_PQ_EXCEPTION(QueryCanceledException, OperatorInterventionException);
DEFINE_MORDOR_PQ_EXCEPTION(AdminShutdownException, OperatorInterventionException);
DEFINE_MORDOR_PQ_EXCEPTION(CrashShutdownException, OperatorInterventionException);
DEFINE_MORDOR_PQ_EXCEPTION(CannotConnectNowException, OperatorInterventionException);

DEFINE_MORDOR_PQ_EXCEPTION(SystemError, Exception);
DEFINE_MORDOR_PQ_EXCEPTION(IOError, SystemError);
DEFINE_MORDOR_PQ_EXCEPTION(UndefinedFileException, SystemError);
DEFINE_MORDOR_PQ_EXCEPTION(DuplicateFileException, SystemError);

DEFINE_MORDOR_PQ_EXCEPTION(ConfigFileError, Exception);
DEFINE_MORDOR_PQ_EXCEPTION(LockFileExistsException, ConfigFileError);

DEFINE_MORDOR_PQ_EXCEPTION(InternalError, Exception);
DEFINE_MORDOR_PQ_EXCEPTION(DataCorruptedException, InternalError);
DEFINE_MORDOR_PQ_EXCEPTION(IndexCorruptedException, InternalError);

DEFINE_MORDOR_PQ_EXCEPTION(ListenWithoutRegisteredChannels, Exception);

void throwException(PGconn *conn);
void throwException(PGresult *result);

}}

#endif


text:
body{
	width: 100%;
}

.row-section {
	margin-left: 1rem;
}
.row:not(:first-child) {
	margin-top: 2rem;
}
input.validation-success,
select.validation-success,
textarea.validation-success {
	color: #468847;
	background-color: #DFF0D8;
}

text.enabled{
	color: black;
}

text.disabled{
	color: #CCCCCC;
}

input.validation-error,
select.validation-error,
textarea.validation-error {
	color: #B94A48;
	background-color: #F2DEDE;
}

.half{
	float: left;
	width: 40%;
	padding: 1rem;
}
.half1{
	background-color: aqua;
}
.half2{
	background-color: aquamarine;
}


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

using System;
using System.Web.UI.WebControls;

using DotNetNuke.Framework;
using DotNetNuke.Services.Localization;
using DotNetNuke.Services.Personalization;

#endregion

namespace DotNetNuke.UI.UserControls
{
    /// -----------------------------------------------------------------------------
    /// <summary>
    ///   LocaleSelectorControl is a user control that provides all the server code to manage
    ///   localisation selection
    /// </summary>
    /// -----------------------------------------------------------------------------
    public abstract class LocaleSelectorControl : UserControlBase
    {
        #region "Controls"

        protected DropDownList ddlPortalDefaultLanguage;
        protected Literal litStatus;
        protected RadioButtonList rbViewType;

        #endregion

        private string MyFileName = "LocaleSelectorControl.ascx";
        private string _ViewType = "";

        private CultureDropDownTypes DisplayType
        {
            get
            {
                switch (ViewType)
                {
                    case "NATIVE":
                        return CultureDropDownTypes.NativeName;
                    case "ENGLISH":
                        return CultureDropDownTypes.EnglishName;
                    default:
                        return CultureDropDownTypes.NativeName;
                }
            }
        }

        private string ViewType
        {
            get
            {
                if (string.IsNullOrEmpty(_ViewType))
                {
                    _ViewType = Convert.ToString(Personalization.GetProfile("LanguageEnabler", string.Format("ViewType{0}", PortalSettings.PortalId)));
                }
                if (string.IsNullOrEmpty(_ViewType))
                {
                    _ViewType = "NATIVE";
                }
                return _ViewType;
            }
        }

        #region "Public Methods"

        public void BindDefaultLanguageSelector()
        {
            if (Page.IsPostBack == false)
            {
                Localization.LoadCultureDropDownList(ddlPortalDefaultLanguage, DisplayType, PortalSettings.DefaultLanguage, true);
            }
        }

        #endregion

        #region "Public properties"

        public string CultureCode
        {
            get
            {
                return ddlPortalDefaultLanguage.SelectedValue;
            }
        }

        #endregion

        #region "Event Handlers"

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            rbViewType.SelectedIndexChanged += rbViewType_SelectedIndexChanged;

            if (!Page.IsPostBack)
            {
                ListItem item = default(ListItem);

                item = new ListItem(Localization.GetString("NativeName.Text", Localization.GetResourceFile(this, MyFileName)), "NATIVE");
                rbViewType.Items.Add(item);
                if (ViewType == "NATIVE")
                {
                    item.Selected = true;
                }
                item = new ListItem(Localization.GetString("EnglishName.Text", Localization.GetResourceFile(this, MyFileName)), "ENGLISH");
                rbViewType.Items.Add(item);
                if (ViewType == "ENGLISH")
                {
                    item.Selected = true;
                }
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            if (Visible)
            {
                BindDefaultLanguageSelector();
            }
        }

        private void rbViewType_SelectedIndexChanged(object sender, EventArgs e)
        {
            _ViewType = rbViewType.SelectedValue;
        }

        #endregion
    }
}