text:
/*
 * Copyright (C) 2002,
 *
 * Arjuna Technologies Limited,
 * Newcastle upon Tyne,
 * Tyne and Wear,
 * UK.
 *
 * $Id: ContextFactoryImple.java,v 1.16.4.1 2005/11/22 10:36:21 kconner Exp $
 */

package com.arjuna.mwlabs.wst11.at;

import com.arjuna.mw.wsas.exceptions.NoActivityException;
import com.arjuna.mw.wsas.exceptions.SystemException;
import com.arjuna.mw.wscf11.model.twophase.CoordinatorManagerFactory;
import com.arjuna.mw.wscf.model.twophase.api.CoordinatorManager;
import com.arjuna.mw.wstx.logging.wstxLogger;
import com.arjuna.mwlabs.wscf.coordinator.LocalFactory;
import com.arjuna.mwlabs.wscf.model.twophase.arjunacore.ATCoordinator;
import com.arjuna.mwlabs.wscf.model.twophase.arjunacore.CoordinatorControl;
import com.arjuna.mwlabs.wscf.model.twophase.arjunacore.CoordinatorServiceImple;
import com.arjuna.mwlabs.wscf.model.twophase.arjunacore.subordinate.SubordinateATCoordinator;
import com.arjuna.mwlabs.wscf.utils.ContextProvider;
import com.arjuna.mwlabs.wst11.at.context.ArjunaContextImple;
import com.arjuna.mwlabs.wst11.at.participants.CleanupSynchronization;
import com.arjuna.webservices11.util.PrivilegedServiceRegistryFactory;
import com.arjuna.webservices11.wsat.AtomicTransactionConstants;
import com.arjuna.webservices11.wsat.processors.ParticipantProcessor;
import com.arjuna.webservices11.wsarj.InstanceIdentifier;
import com.arjuna.webservices11.wscoor.CoordinationConstants;
import com.arjuna.webservices11.ServiceRegistry;
import com.arjuna.wsc11.ContextFactory;
import com.arjuna.wsc11.ContextFactoryMapper;
import com.arjuna.wsc11.RegistrationCoordinator;
import com.arjuna.wsc11.messaging.MessageId;
import com.arjuna.wsc.InvalidCreateParametersException;
import com.arjuna.wsc.InvalidProtocolException;
import com.arjuna.wst.Volatile2PCParticipant;
import com.arjuna.wst.Durable2PCParticipant;
import com.arjuna.wst11.messaging.engines.ParticipantEngine;
import com.arjuna.wst11.stub.SubordinateVolatile2PCStub;
import com.arjuna.wst11.stub.SubordinateDurable2PCStub;
import org.oasis_open.docs.ws_tx.wscoor._2006._06.CoordinationContext;
import org.oasis_open.docs.ws_tx.wscoor._2006._06.CoordinationContextType;
import org.oasis_open.docs.ws_tx.wscoor._2006._06.Expires;

import javax.xml.ws.wsaddressing.W3CEndpointReference;
import javax.xml.ws.wsaddressing.W3CEndpointReferenceBuilder;
import javax.xml.namespace.QName;

@ContextProvider(coordinationType = ArjunaContextImple.coordinationType,
        serviceType = ArjunaContextImple.serviceType,
        contextImplementation = ArjunaContextImple.class)
public class ContextFactoryImple implements ContextFactory, LocalFactory
{
	public ContextFactoryImple()
	{
		try
		{
			_coordManager = CoordinatorManagerFactory.coordinatorManager();

            _theRegistrar = new RegistrarImple();

            // install the factory for the mapper to locate

            ContextFactoryMapper.getMapper().addContextFactory(ArjunaContextImple.coordinationType, this);
        }
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
	}

	/**
	 * Called when a context factory is added to a context factory mapper. This
	 * method will be called multiple times if the context factory is added to
	 * multiple context factory mappers or to the same context mapper with
	 * different protocol identifiers.
	 *
	 * @param coordinationTypeURI
	 *            the coordination type uri
	 */
	public void install(final String coordinationTypeURI)
	{
	}

	/**
	 * Creates a coordination context.
	 *
	 * @param coordinationTypeURI
	 *            the coordination type uri
	 * @param expires
	 *            the expire date/time for the returned context, can be null
	 * @param currentContext
	 *            the current context, can be null
	 *
	 * @return the created coordination context
	 *
	 * @throws com.arjuna.wsc.InvalidCreateParametersException
	 *             if a parameter passed is invalid this activity identifier.
	 *
	 */

	public CoordinationContext create (final String coordinationTypeURI, final Long expires,
            final CoordinationContextType currentContext, final boolean isSecure)
			throws InvalidCreateParametersException
	{
		if (coordinationTypeURI.equals(AtomicTransactionConstants.WSAT_PROTOCOL))
		{
			try
			{
                if (currentContext == null) {
				// make sure no transaction is currently associated

				_coordManager.suspend();

				final int timeout ;
                if (expires == null)
                {
                    timeout = 0 ;
                }
                else
                {
                    final long timeoutVal = expires.longValue() ;
                    timeout = (timeoutVal > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int)timeoutVal) ;
                }

				_coordManager.begin(ArjunaContextImple.serviceType, timeout);

                final ArjunaContextImple arjunaContext = ArjunaContextImple.getContext() ;
                final ServiceRegistry serviceRegistry = PrivilegedServiceRegistryFactory.getInstance().getServiceRegistry();
                final String registrationCoordinatorURI = serviceRegistry.getServiceURI(CoordinationConstants.REGISTRATION_SERVICE_NAME, isSecure) ;

                final CoordinationContext coordinationContext = new CoordinationContext() ;
                coordinationContext.setCoordinationType(coordinationTypeURI);
                CoordinationContextType.Identifier identifier = new CoordinationContextType.Identifier();
                identifier.setValue("urn:"+arjunaContext.getTransactionIdentifier());
                coordinationContext.setIdentifier(identifier) ;
                final int transactionExpires = arjunaContext.getTransactionExpires();
                if (transactionExpires > 0)
                {
                    Expires expiresInstance = new Expires();
                    expiresInstance.setValue(transactionExpires);
                    coordinationContext.setExpires(expiresInstance);
                }
                W3CEndpointReference registrationCoordinator = getRegistrationCoordinator(registrationCoordinatorURI, arjunaContext);
                coordinationContext.setRegistrationService(registrationCoordinator) ;

				/*
				 * Now add the registrar for this specific coordinator to the
				 * mapper.
				 */

				_coordManager.enlistSynchronization(new CleanupSynchronization(_coordManager.identifier().toString(), _theRegistrar));

				/*
				 * TODO Uughh! This does a suspend for us! Left over from original
				 * WS-AS stuff.
				 *
				 * TODO
				 * REFACTOR, REFACTOR, REFACTOR.
				 */

				_theRegistrar.associate();

				return coordinationContext;
                } else {
                    // we need to create a subordinate transaction and register it as both a durable and volatile
                    // participant with the registration service defined in the current context

                    SubordinateATCoordinator subTx = (SubordinateATCoordinator) createSubordinate();
                    // hmm, need to create wrappers here as the subTx is in WSCF which only knows
                    // about WSAS and WS-C and the participant is in WS-T
                    String vtppid = subTx.getVolatile2PhaseId();
                    String dtppid = subTx.getDurable2PhaseId();
                    Volatile2PCParticipant vtpp = new SubordinateVolatile2PCStub(subTx);
                    Durable2PCParticipant dtpp = new SubordinateDurable2PCStub(subTx);
                    final String messageId = MessageId.getMessageId() ;
                    W3CEndpointReference participant;
                    W3CEndpointReference coordinator;
                    participant= getParticipant(vtppid, isSecure);
                    coordinator = RegistrationCoordinator.register(currentContext, messageId, participant, AtomicTransactionConstants.WSAT_SUB_PROTOCOL_VOLATILE_2PC) ;
                    ParticipantProcessor.getProcessor().activateParticipant(new ParticipantEngine(vtpp, vtppid, coordinator), vtppid) ;
                    participant= getParticipant(dtppid, isSecure);
                    coordinator = RegistrationCoordinator.register(currentContext, messageId, participant, AtomicTransactionConstants.WSAT_SUB_PROTOCOL_DURABLE_2PC) ;
                    ParticipantProcessor.getProcessor().activateParticipant(new ParticipantEngine(dtpp, dtppid, coordinator), dtppid) ;

                    // ok now create the context
                    final ServiceRegistry serviceRegistry = PrivilegedServiceRegistryFactory.getInstance().getServiceRegistry();
                    final String registrationCoordinatorURI = serviceRegistry.getServiceURI(CoordinationConstants.REGISTRATION_SERVICE_NAME, isSecure) ;

                    final CoordinationContext coordinationContext = new CoordinationContext() ;
                    coordinationContext.setCoordinationType(coordinationTypeURI);
                    CoordinationContextType.Identifier identifier = new CoordinationContextType.Identifier();
                    String txId = subTx.get_uid().stringForm();
                    identifier.setValue("urn:" + txId);
                    coordinationContext.setIdentifier(identifier) ;
                    Expires expiresInstance = currentContext.getExpires();
                    final long transactionExpires = (expiresInstance != null ? expiresInstance.getValue() : 0);
                    if (transactionExpires > 0)
                    {
                        expiresInstance = new Expires();
                        expiresInstance.setValue(transactionExpires);
                        coordinationContext.setExpires(expiresInstance);
                    }
                    W3CEndpointReference registrationCoordinator = getRegistrationCoordinator(registrationCoordinatorURI, txId);
                    coordinationContext.setRegistrationService(registrationCoordinator) ;

                    // now associate the tx id with the sub transaction

                    _theRegistrar.associate(subTx);
                    return coordinationContext;
                }
			}
			catch (NoActivityException ex)
			{
				ex.printStackTrace();

				throw new InvalidCreateParametersException();
			}
			catch (SystemException ex)
			{
				ex.printStackTrace();
            }
			catch (com.arjuna.mw.wsas.exceptions.WrongStateException ex)
			{
				ex.printStackTrace();

				throw new InvalidCreateParametersException();
			}
			catch (Exception ex)
			{
				// TODO handle properly

				ex.printStackTrace();
			}
		}
		else {
            wstxLogger.i18NLogger.warn_mwlabs_wst_at_Context11FactoryImple_1(AtomicTransactionConstants.WSAT_PROTOCOL, coordinationTypeURI);

            throw new InvalidCreateParametersException(
                    wstxLogger.i18NLogger.get_mwlabs_wst_at_Context11FactoryImple_3()
                            + " < "
                            + AtomicTransactionConstants.WSAT_PROTOCOL
                            + ", "
                            + coordinationTypeURI + " >");
        }

		return null;
	}

    /**
     * class used to return data required to manage a bridged to subordinate transaction
     */
    public class BridgeTxData
    {
        public CoordinationContext context;
        public SubordinateATCoordinator coordinator;
        public String identifier;
    }

    /**
     * create a bridged to subordinate WS-AT 1.1 transaction, associate it with the registrar and create and return
     * a coordination context for it. n.b. this is a private, behind-the-scenes method for use by the JTA-AT
     * transaction bridge code.
     * @param subordinateType a unique string which groups subordinates for the benefit of their parent tx/app and
     * allows them to be identified and retrieved as a group during recovery
     * @param expires the timeout for the bridged to AT transaction
     * @param isSecure true if the registration cooridnator URL should use a secure address, otherwise false.
     * @return a coordination context for the bridged to transaction
     */
    public BridgeTxData createBridgedTransaction (String subordinateType, final Long expires, final boolean isSecure)
    {
        // we must have a type and it must not be the AT-AT subordinate type
        if (subordinateType == null || SubordinateATCoordinator.SUBORDINATE_TX_TYPE_AT_AT.equals(subordinateType)) {
            return null;
        }
        // we need to create a subordinate transaction and register it as both a durable and volatile
        // participant with the registration service defined in the current context

        SubordinateATCoordinator subTx = null;
        try {
            subTx = (SubordinateATCoordinator) createSubordinate(subordinateType);
        } catch (NoActivityException e) {
            // will not happen
            return null;
        } catch (InvalidProtocolException e) {
            // will not happen
            return null;
        } catch (SystemException e) {
            // may happen
            return null;
        }

        // ok now create the context

        final ServiceRegistry serviceRegistry = PrivilegedServiceRegistryFactory.getInstance().getServiceRegistry();
        final String registrationCoordinatorURI = serviceRegistry.getServiceURI(CoordinationConstants.REGISTRATION_SERVICE_NAME, isSecure) ;

        final CoordinationContext coordinationContext = new CoordinationContext() ;
        coordinationContext.setCoordinationType(AtomicTransactionConstants.WSAT_PROTOCOL);
        CoordinationContextType.Identifier identifier = new CoordinationContextType.Identifier();
        String txId = subTx.get_uid().stringForm();
        identifier.setValue("urn:" + txId);
        coordinationContext.setIdentifier(identifier) ;
        if (expires != null && expires.longValue() > 0)
        {
            Expires expiresInstance = new Expires();
            expiresInstance.setValue(expires);
            coordinationContext.setExpires(expiresInstance);
        }
        W3CEndpointReference registrationCoordinator = getRegistrationCoordinator(registrationCoordinatorURI, txId);
        coordinationContext.setRegistrationService(registrationCoordinator) ;

        // now associate the tx id with the sub transaction

        try {
            _theRegistrar.associate(subTx);
        } catch (Exception e) {
            // will not happen
        }
        BridgeTxData bridgeTxData = new BridgeTxData();
        bridgeTxData.context = coordinationContext;
        bridgeTxData.coordinator = subTx;
        bridgeTxData.identifier = txId;

        return bridgeTxData;
    }

    private W3CEndpointReference getParticipant(final String id, final boolean isSecure)
    {
        final QName serviceName = AtomicTransactionConstants.PARTICIPANT_SERVICE_QNAME;
        final QName endpointName = AtomicTransactionConstants.PARTICIPANT_PORT_QNAME;
        final ServiceRegistry serviceRegistry = PrivilegedServiceRegistryFactory.getInstance().getServiceRegistry();
        final String address = serviceRegistry.getServiceURI(AtomicTransactionConstants.PARTICIPANT_SERVICE_NAME, isSecure);
        W3CEndpointReferenceBuilder builder = new W3CEndpointReferenceBuilder();
        builder.serviceName(serviceName);
        builder.endpointName(endpointName);
        builder.address(address);
        InstanceIdentifier.setEndpointInstanceIdentifier(builder, id);
        return builder.build();
    }

    private static W3CEndpointReference getRegistrationCoordinator(String registrationCoordinatorURI, ArjunaContextImple arjunaContext)
    {
        String identifier = arjunaContext.getTransactionIdentifier();
        return getRegistrationCoordinator(registrationCoordinatorURI, identifier);
    }

    private static W3CEndpointReference getRegistrationCoordinator(String registrationCoordinatorURI, String identifier)
    {
        final W3CEndpointReferenceBuilder builder = new W3CEndpointReferenceBuilder();
        builder.serviceName(CoordinationConstants.REGISTRATION_SERVICE_QNAME);
        builder.endpointName(CoordinationConstants.REGISTRATION_ENDPOINT_QNAME);
        // strictly we shouldn't need to set the address because we are in the same web app as the
        // coordinator but we have to as the W3CEndpointReference implementation is incomplete
        builder.address(registrationCoordinatorURI);
        InstanceIdentifier.setEndpointInstanceIdentifier(builder, identifier);
        W3CEndpointReference registrationCoordinator = builder.build();
        return registrationCoordinator;
    }

    /**
	 * Called when a context factory is removed from a context factory mapper.
	 * This method will be called multiple times if the context factory is
	 * removed from multiple context factory mappers or from the same context
	 * factory mapper with different coordination type uris.
	 *
	 * @param coordinationTypeURI
	 *            the coordination type uri
	 */

	public void uninstall (final String coordinationTypeURI)
	{
		// we don't use this as one implementation is registered per type
	}

    public final Object createSubordinate () throws NoActivityException, InvalidProtocolException, SystemException
    {
        return createSubordinate(SubordinateATCoordinator.SUBORDINATE_TX_TYPE_AT_AT);
    }

	public final Object createSubordinate (String subordinateType) throws NoActivityException, InvalidProtocolException, SystemException
	{
		try
		{
			CoordinatorServiceImple coordManager = (CoordinatorServiceImple) _coordManager;
			CoordinatorControl theControl = coordManager.coordinatorControl();
			ATCoordinator subordinateTransaction = theControl.createSubordinate(subordinateType);

			/*
			 * Now add the registrar for this specific coordinator to the
			 * mapper.
			 */

			subordinateTransaction.enlistSynchronization(new CleanupSynchronization(subordinateTransaction.get_uid().stringForm(), _theRegistrar));

			_theRegistrar.associate(subordinateTransaction);

			return subordinateTransaction;
		}
		catch (Exception ex)
		{
			throw new SystemException(ex.toString());
		}
	}

	public final RegistrarImple registrar ()
	{
		return _theRegistrar;
	}

	private CoordinatorManager _coordManager;
	private RegistrarImple _theRegistrar;

}


text:
package gnu.java.awt.peer.swing;

import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.TextArea;
import java.awt.event.ComponentEvent;
import java.awt.event.FocusEvent;
import java.awt.event.HierarchyEvent;
import java.awt.event.InputMethodEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.im.InputMethodRequests;
import java.awt.peer.TextAreaPeer;

import javax.swing.JComponent;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JViewport;
import javax.swing.text.BadLocationException;

public class SwingTextAreaPeer
    extends SwingComponentPeer
    implements TextAreaPeer
{

  /**
   * A spezialized Swing scroller used to hold the textarea.
   *
   * @author Roman Kennke (kennke@aicas.com)
   */
  private class SwingScrollPane
    extends JScrollPane
    implements SwingComponent
  {

    SwingTextArea textArea;

    SwingScrollPane(SwingTextArea textArea)
    {
      super(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
            JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

      this.textArea = textArea;
    }

    /**
     * Returns this label.
     *
     * @return this
     */
    public JComponent getJComponent()
    {
      return this;
    }

    /**
     * Handles mouse events by forwarding it to
     * processMouseEvent().
     *
     * @param ev the mouse event
     */
    public void handleMouseEvent(MouseEvent ev)
    {
      JViewport viewPort = getViewport();
      if(viewPort.contains(ev.getPoint()))
        {
          ev.setSource(textArea);
          textArea.dispatchEvent(ev);
        }
      else
        {
          ev.setSource(this);
          this.dispatchEvent(ev);
        }
    }

    /**
     * Force lightweight mouse dispatching.
     */
    public boolean isLightweight()
    {
      return false;
    }

    /**
     * Handles mouse motion events by forwarding it to
     * processMouseMotionEvent().
     *
     * @param ev the mouse motion event
     */
    public void handleMouseMotionEvent(MouseEvent ev)
    {
      textArea.processMouseMotionEvent(ev);
    }

    /**
     * Handles key events by forwarding it to processKeyEvent().
     *
     * @param ev the mouse event
     */
    public void handleKeyEvent(KeyEvent ev)
    {
      textArea.processKeyEvent(ev);
    }

    /**
     * Handles focus events by forwarding it to
     * processFocusEvent().
     *
     * @param ev the Focus event
     */
    public void handleFocusEvent(FocusEvent ev)
    {
      textArea.processFocusEvent(ev);
    }

    /**
     * Overridden so that this method returns the correct value even without a
     * peer.
     *
     * @return the screen location of the button
     */
    public Point getLocationOnScreen()
    {
      return SwingTextAreaPeer.this.getLocationOnScreen();
    }

    /**
     * Overridden so that the isShowing method returns the correct value for the
     * swing button, even if it has no peer on its own.
     *
     * @return true if the button is currently showing,
     *         false otherwise
     */
    public boolean isShowing()
    {
      boolean retVal = false;
      if (SwingTextAreaPeer.this.awtComponent != null)
        retVal = SwingTextAreaPeer.this.awtComponent.isShowing();
      return retVal;
    }

    /**
     * Overridden, so that the Swing button can create an Image without its
     * own peer.
     *
     * @param w the width of the image
     * @param h the height of the image
     *
     * @return an image
     */
    public Image createImage(int w, int h)
    {
      return SwingTextAreaPeer.this.createImage(w, h);
    }

    public Graphics getGraphics()
    {
      return SwingTextAreaPeer.this.getGraphics();
    }

    public Container getParent()
    {
      Container par = null;
      if (SwingTextAreaPeer.this.awtComponent != null)
        par = SwingTextAreaPeer.this.awtComponent.getParent();
      return par;
    }

    public void requestFocus() {
        SwingTextAreaPeer.this.requestFocus(awtComponent, false, true, 0);
    }

    public boolean requestFocus(boolean temporary) {
        return SwingTextAreaPeer.this.requestFocus(awtComponent, temporary,
                                                   true, 0);
    }

  }

  private class SwingTextArea extends JTextArea
  {
    /**
     * Make this method accessible in this Package.
     */
    protected final void processComponentKeyEvent(KeyEvent e)
    {
      super.processComponentKeyEvent(e);
    }

    /**
     * Make this method accessible in this Package.
     */
    protected final void processMouseMotionEvent(MouseEvent ev)
    {
      super.processMouseMotionEvent(ev);
    }

    /**
     * Make this method accessible in this Package.
     */
    protected final void processComponentEvent(ComponentEvent e)
    {
      super.processComponentEvent(e);
    }

    /**
     * Make this method accessible in this Package.
     */
    protected final void processFocusEvent(FocusEvent e)
    {
      super.processFocusEvent(e);
    }

    /**
     * Make this method accessible in this Package.
     */
    protected final void processHierarchyBoundsEvent(HierarchyEvent e)
    {
      super.processHierarchyBoundsEvent(e);
    }

    /**
     * Make this method accessible in this Package.
     */
    protected final void processHierarchyEvent(HierarchyEvent e)
    {
      super.processHierarchyEvent(e);
    }

    /**
     * Make this method accessible in this Package.
     */
    protected final void processInputMethodEvent(InputMethodEvent e)
    {
      super.processInputMethodEvent(e);
    }

    /**
     * Make this method accessible in this Package.
     */
    protected final void processMouseEvent(MouseEvent e)
    {
      super.processMouseEvent(e);
    }

    /**
     * Make this method accessible in this Package.
     */
    protected final void processMouseWheelEvent(MouseWheelEvent e)
    {
      super.processMouseWheelEvent(e);
    }

    /**
     * Make this method accessible in this Package.
     */
    protected final void processKeyEvent(KeyEvent e)
    {
      super.processKeyEvent(e);
    }

    public void requestFocus() {
      SwingTextAreaPeer.this.requestFocus(awtComponent, false, true, 0);
    }

    public boolean requestFocus(boolean temporary) {
      return SwingTextAreaPeer.this.requestFocus(awtComponent, temporary,
                                                 true, 0);
    }
  }

  /**
   * The actual JTextArea.
   */
  private SwingTextArea jTextArea;

  public SwingTextAreaPeer(TextArea textArea)
  {
    super();
    jTextArea = new SwingTextArea();
    SwingScrollPane swingArea = new SwingScrollPane(jTextArea);
    init(textArea, swingArea);

    JViewport viewport = new JViewport()
      {
        public Image createImage(int width, int height)
        {
          return awtComponent.createImage(width, height);
        }
      };

    viewport.setView(jTextArea);
    swingArea.setViewport(viewport);
    // Pull over the text from the text area.
    setText(textArea.getText());

    // Pull over the number of rows and columns
    // if non were set use default values
    int columns = textArea.getColumns();
    int rows = textArea.getRows();

    if(columns == 0 && rows == 0)
      {
        columns = 25;
        textArea.setColumns(columns);
        rows = 5;
        textArea.setRows(rows);
      }

    jTextArea.setColumns(columns);
    jTextArea.setRows(rows);
  }

  public Dimension getMinimumSize(int rows, int cols)
  {
    return jTextArea.getMinimumSize();
  }

  public Dimension getPreferredSize(int rows, int cols)
  {
    return jTextArea.getPreferredSize();
  }

  public void insert(String text, int pos)
  {
    jTextArea.insert(text, pos);
  }

  public void insertText(String text, int pos)
  {
    jTextArea.insert(text, pos);
  }

  public Dimension minimumSize()
  {
    return jTextArea.getMinimumSize();
  }

  public Dimension preferredSize()
  {
    return jTextArea.getPreferredSize();
  }

  public Dimension minimumSize(int rows, int cols)
  {
      return jTextArea.getMinimumSize();
  }

  public Dimension preferredSize(int rows, int cols)
  {
      return jTextArea.getPreferredSize();
  }

  public void replaceRange(String text, int start, int end)
  {
    jTextArea.replaceRange(text, start, end);
  }

  public void replaceText(String text, int start, int end)
  {
    jTextArea.replaceRange(text, start, end);
  }

  public long filterEvents(long filter)
  {
    // TODO Auto-generated method stub
    return 0;
  }

  public int getCaretPosition()
  {
    return jTextArea.getCaretPosition();
  }

  public Rectangle getCharacterBounds(int pos)
  {
    Rectangle r;
    try
      {
        return jTextArea.modelToView(pos);
      }
    catch (BadLocationException ex)
      {
        r = null;
      }
    return r;
  }

  public int getIndexAtPoint(int x, int y)
  {
    return jTextArea.viewToModel(new Point(x, y));
  }

  public InputMethodRequests getInputMethodRequests()
  {
    // TODO Auto-generated method stub
    return null;
  }

  public int getSelectionEnd()
  {
    return jTextArea.getSelectionEnd();
  }

  public int getSelectionStart()
  {
    return jTextArea.getSelectionStart();
  }

  public String getText()
  {
    return jTextArea.getText();
  }

  public void select(int start, int end)
  {
    jTextArea.select(start, end);
  }

  public void setCaretPosition(int pos)
  {
    jTextArea.setCaretPosition(pos);
  }

  public void setEditable(boolean editable)
  {
    jTextArea.setEditable(editable);
  }

  public void setText(String text)
  {
    jTextArea.setText(text);
  }

  public void reshape(int x, int y, int width, int height)
  {
    if (swingComponent != null)
      {
        swingComponent.getJComponent().setBounds(x, y, width, height);
        swingComponent.getJComponent().validate();
      }
  }

}

redpajama_set_name: RedPajamaGithub


text:
package edu.gatech.cs4261.summer2015.livejudging.Support;

import android.app.DialogFragment;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.ProgressBar;

import edu.gatech.cs4261.summer2015.livejudging.Objects.JudgeEvent;
import edu.gatech.cs4261.summer2015.livejudging.R;

/**
 * A simple {@link Fragment} subclass.
 */
public class MapDialogFragment extends DialogFragment
{
    private ImageView map_iv;
    private JudgeEvent judgeEvent;
    private ProgressBar loading_pb;

    public MapDialogFragment()
    {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)
    {
        View v = inflater.inflate(R.layout.fragment_map_dialog, container, false);
        getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE); // Prevents title white space
        map_iv = (ImageView) v.findViewById(R.id.map_iv);
        loading_pb = (ProgressBar) v.findViewById(R.id.loading_pb);
        return v;
    }

    @Override
    public void onStart()
    {
        super.onStart();

        judgeEvent = getArguments().getParcelable("judgeEvent");
        if(judgeEvent.getEvent().getMap() == null)
        {
            map_iv.setImageResource(R.drawable.ic_empty_map);
            loading_pb.setVisibility(View.GONE);
        }
        else
        {
            new Adapters.BitmapWorker(null, map_iv, loading_pb).execute(judgeEvent.getEvent().getMap());
        }
    }
}


text:
+++
categories = ["Swift"]
comments = false
date = "2016-05-27T19:34:45-08:00"
draft = false
showpagemeta = true
showcomments = true
tags = ["swift","function"]
title = "Static vs Class vs Global Functions in Swift"
description = "A short description on Static vs Class vs Global Functions in Swift"
+++

Almost every projects contains Utility Functions. With the introduction of Swift, there are multiple ways to write such functions.
Static Functions
Static functions are invoked by the class itself, not by an instance. This makes it simple to invoke utility functions without having to manage an object to do that work for you.
```swift
class AppUtils {
    static func appUtility() {
    }
}
```
We can access static function as `AppUtils.appUtility()`
Static functions can not be overridden.
Class Functions
Class functions (not instance methods) are also static functions but they are dynamically dispatched and can be overridden by subclasses unlike static functions.
```swift
class AppUtils{
    class func appUtility(){
        println("In AppUtils")
    }
}
class AppOtherUtils: AppUtils{
    override class func appUtility(){
        println("In AppOtherUtils")
    }
}
```
We can access them similar to static functions as `AppUtils.appUtility()` and `AppOtherUtils.appUtility()`.
static is same as class final.
Global Functions
But then you can also just do a stand alone function in Swift which is not within a class and access it anywhere in the project. The global functions can be kept in a separate file that we can import into any project as per requirement.
```swift
func appUtility() {
}
```
We can just access them as `appUtility()` anywhere in the project. If you have method with same name as of global function, then access global function with `MyAppName.appUtility()`.

In case of static functions, if we access one of the static member, entire class gets loaded in memory. But in case of global function, only that particular function will be loaded in memory.
So, which one is better to use?

It is largly subjective why we pick one over another. Some prefer static method approach as a form of namespacing. For example, using the static method approach also allows us to have a method `ClassA.appUtility()` and a method named `ClassB.appUtility()`, which is useful while developing a library or framework.

Global functions are more modular and factor out single tasks for a single function - a good global utility function that does exactly one thing and does it perfectly can also sometimes be abstracted or made generic and used in other context as well.
We can just create a AppUtility.swift file and put all the utility functions in it. Later this file can be used across multiple projects.


text:
id FEMRepresentationRootForKeyPath(id representation, NSString *keyPath) {
    if (keyPath.length > 0) {
        return [representation valueForKeyPath:keyPath];
    }

    return representation;
}

void _FEMRepresentationCollectPresentedPrimaryKeys(id, FEMMapping *, NSDictionary *);

void _FEMRepresentationCollectObjectPrimaryKeys(NSDictionary *object, FEMMapping *mapping, NSDictionary *container) {
    if (mapping.primaryKey) {
        FEMAttribute *primaryKeyMapping = mapping.primaryKeyAttribute;
        id primaryKeyValue = FEMRepresentationValueForAttribute(object, primaryKeyMapping);
        if (primaryKeyValue && primaryKeyValue != NSNull.null) {
            NSMutableSet *set = container[mapping.entityName];
            [set addObject:primaryKeyValue];
        }
    }

    for (FEMRelationship *relationship in mapping.relationships) {
        id relationshipRepresentation = FEMRepresentationRootForKeyPath(object, relationship.keyPath);
        if (relationshipRepresentation && relationshipRepresentation != NSNull.null) {
            _FEMRepresentationCollectPresentedPrimaryKeys(relationshipRepresentation, relationship.mapping, container);
        }
    }
}

void _FEMRepresentationCollectPresentedPrimaryKeys(id representation, FEMMapping *mapping, NSDictionary *container) {
    if ([representation isKindOfClass:NSArray.class]) {
        for (id object in (id<NSFastEnumeration>)representation) {
            _FEMRepresentationCollectObjectPrimaryKeys(object, mapping, container);
        }
    } else if ([representation isKindOfClass:NSDictionary.class] || [representation isKindOfClass:[NSNumber class]] || [representation isKindOfClass:[NSString class]]) {
        _FEMRepresentationCollectObjectPrimaryKeys(representation, mapping, container);
    } else {
        NSCAssert(
            NO,
            @"Expected container classes: NSArray, NSDictionary, NSNumber or NSString. Got:%@",
            NSStringFromClass([representation class])
        );
    }
};
NSDictionary *FEMRepresentationCollectPresentedPrimaryKeys(id representation, FEMMapping *mapping) {
    FEMMappingApply(mapping, ^(FEMMapping *object) {
        NSCParameterAssert(object.entityName != nil);
    });

    NSMutableDictionary *output = [[NSMutableDictionary alloc] init];
    for (NSString *name in FEMMappingCollectUsedEntityNames(mapping)) {
        output[name] = [[NSMutableSet alloc] init];
    }

    id root = FEMRepresentationRootForKeyPath(representation, mapping.rootPath);
    _FEMRepresentationCollectPresentedPrimaryKeys(root, mapping, output);

    return output;
}

id FEMRepresentationValueForAttribute(id representation, FEMAttribute *attribute) {
    id value = attribute.keyPath ? [representation valueForKeyPath:attribute.keyPath] : representation;
    // nil is a valid value for missing keys. therefore attribute is discarded
    if (value != nil) {
        // if by mistake nil returned we still have to map it to the NSNull to indicate missing value
        return [attribute mapValue:value] ?: [NSNull null];
    }

    return value;
}


text:
int CScanner::ScannerTag_GetPropertyValue	(LPCTSTR szPropertyName, WCHAR* szPropertyValue)
{
	int iRetVal = TRUE;
	if (cmp(szPropertyName, L"enabled"))
	{
		if (m_bScannerOpen && m_bScannerEnabled && m_szCurrentlyOpenScanner)
			iRetVal = ProcessDecoderPropertyForReturn(m_szCurrentlyOpenScanner, szPropertyValue);
	}
	else if (cmp(szPropertyName, L"EnumScannerEvent"))
	{
		if (m_szEventEnumScanners)
			iRetVal = ProcessDecoderPropertyForReturn(m_szEventEnumScanners, szPropertyValue);
		else
			iRetVal = ProcessDecoderPropertyForReturn(L"", szPropertyValue);
	}
	else if (cmp(szPropertyName, L"BluetoothStatusEvent"))
	{
		if (m_szEventBluetoothStatus)
			iRetVal = ProcessDecoderPropertyForReturn(m_szEventBluetoothStatus, szPropertyValue);
		else
			iRetVal = ProcessDecoderPropertyForReturn(L"", szPropertyValue);
	}
	else if (cmp(szPropertyName, L"DecodeEvent"))
	{
		if (m_szEventDecode)
			iRetVal = ProcessDecoderPropertyForReturn(m_szEventDecode, szPropertyValue);
		else
			iRetVal = ProcessDecoderPropertyForReturn(L"", szPropertyValue);
	}
	else if (cmp(szPropertyName, L"DeviceCapabilitiesEvent"))
	{
		if (m_szEventDeviceCapabilities)
			iRetVal = ProcessDecoderPropertyForReturn(m_szEventDeviceCapabilities, szPropertyValue);
		else
			iRetVal = ProcessDecoderPropertyForReturn(L"", szPropertyValue);
	}
	else if (cmp(szPropertyName, L"AutoEnter"))
	{
		if (m_bAutoEnter)
			iRetVal = ProcessDecoderPropertyForReturn(L"true", szPropertyValue);
		else
			iRetVal = ProcessDecoderPropertyForReturn(L"false", szPropertyValue);
	}
	else if (cmp(szPropertyName, L"AutoTab"))
	{
		if (m_bAutoTab)
			iRetVal = ProcessDecoderPropertyForReturn(L"true", szPropertyValue);
		else
			iRetVal = ProcessDecoderPropertyForReturn(L"false", szPropertyValue);
	}
	return iRetVal;
}

int CScanner::ScannerBeeper_GetPropertyValue(LPCTSTR szPropertyName, WCHAR* szPropertyValue)
{
	int iRetVal = -1;
	if (cmp(szPropertyName, L"decodeVolume"))
	{
		iRetVal = ProcessDecoderPropertyForReturn(
			m_decodeNotifier->GetDecodeVolume(), szPropertyValue);
	}
	else if (cmp(szPropertyName, L"decodeDuration"))
	{
		iRetVal = ProcessDecoderPropertyForReturn(
			m_decodeNotifier->GetDecodeDuration(), szPropertyValue);
	}
	else if (cmp(szPropertyName, L"successfulDecodeFrequency"))
	{
		iRetVal = ProcessDecoderPropertyForReturn(
			m_decodeNotifier->GetSuccessfulDecodeFrequency(), szPropertyValue);
	}
	else if (cmp(szPropertyName, L"invalidDecodeFrequency"))
	{
		iRetVal = ProcessDecoderPropertyForReturn(
			m_decodeNotifier->GetInvalidDecodeFrequency(), szPropertyValue);
	}
	else if (cmp(szPropertyName, L"successfulDecodeSound"))
	{
		if (m_decodeNotifier->GetSuccessfulDecodeSound())
			iRetVal = ProcessDecoderPropertyForReturn(
				m_decodeNotifier->GetSuccessfulDecodeSound(), szPropertyValue);
		else
			iRetVal = ProcessDecoderPropertyForReturn(L"", szPropertyValue);
	}
	else if (cmp(szPropertyName, L"invalidDecodeSound"))
	{
		if (m_decodeNotifier->GetInvalidDecodeSound())
			iRetVal = ProcessDecoderPropertyForReturn(
				m_decodeNotifier->GetInvalidDecodeSound(), szPropertyValue);
		else
			iRetVal = ProcessDecoderPropertyForReturn(L"", szPropertyValue);
	}

	return iRetVal;
}

int CScanner::ScannerReaderTag_GetPropertyValue(LPCTSTR szPropertyName, WCHAR* szPropertyValue)
{
	int iRetVal = -1;
	READER_PARAMS readerParams;
	RetrieveScannerParameters(&readerParams);
	if (cmp(szPropertyName, L"RasterMode"))
	{
		//  Note - Raster Mode Cyclone is no longer mentioned in the EMDK help file
		if (readerParams.ReaderSpecific.laser_specific.dwRasterMode == RASTER_MODE_NONE)
			iRetVal = ProcessDecoderPropertyForReturn(L"none", szPropertyValue);
		else if (readerParams.ReaderSpecific.laser_specific.dwRasterMode == RASTER_MODE_OPEN_ALWAYS)
			iRetVal = ProcessDecoderPropertyForReturn(L"openAlways", szPropertyValue);
		else if (readerParams.ReaderSpecific.laser_specific.dwRasterMode == RASTER_MODE_SMART)
			iRetVal = ProcessDecoderPropertyForReturn(L"smart", szPropertyValue);
		else if (readerParams.ReaderSpecific.laser_specific.dwRasterMode == RASTER_MODE_CYCLONE)
			iRetVal = ProcessDecoderPropertyForReturn(L"cyclone", szPropertyValue);
		else
			iRetVal = -1;
	}
	else if (cmp(szPropertyName, L"AimType"))
	{
		if (readerParams.ReaderSpecific.laser_specific.dwAimType == AIM_TYPE_TRIGGER)
			iRetVal = ProcessDecoderPropertyForReturn(L"trigger", szPropertyValue);
		else if (readerParams.ReaderSpecific.laser_specific.dwAimType == AIM_TYPE_TIMED_HOLD)
			iRetVal = ProcessDecoderPropertyForReturn(L"timedHold", szPropertyValue);
		else if (readerParams.ReaderSpecific.laser_specific.dwAimType == AIM_TYPE_TIMED_RELEASE)
			iRetVal = ProcessDecoderPropertyForReturn(L"timedRelease", szPropertyValue);
		else if (readerParams.ReaderSpecific.laser_specific.dwAimType == AIM_TYPE_PRESENTATION)
			iRetVal = ProcessDecoderPropertyForReturn(L"presentation", szPropertyValue);
		else if (readerParams.ReaderSpecific.laser_specific.dwAimType == AIM_TYPE_PRESS_AND_RELEASE)
			iRetVal = ProcessDecoderPropertyForReturn(L"pressAndRelease", szPropertyValue);
		else if (readerParams.ReaderSpecific.laser_specific.dwAimType == AIM_TYPE_CONTINUOUS_READ)
			iRetVal = ProcessDecoderPropertyForReturn(L"continuousRead", szPropertyValue);
		else
			iRetVal = -1;
	}
	else if (cmp(szPropertyName, L"AimMode"))
	{
		if (readerParams.ReaderSpecific.laser_specific.dwAimMode == AIM_MODE_NONE)
			iRetVal = ProcessDecoderPropertyForReturn(L"none", szPropertyValue);
		else if (readerParams.ReaderSpecific.laser_specific.dwAimMode == AIM_MODE_DOT)
			iRetVal = ProcessDecoderPropertyForReturn(L"dot", szPropertyValue);
		else if (readerParams.ReaderSpecific.laser_specific.dwAimMode == AIM_MODE_SLAB)
			iRetVal = ProcessDecoderPropertyForReturn(L"slab", szPropertyValue);
		else if (readerParams.ReaderSpecific.laser_specific.dwAimMode == AIM_MODE_RETICLE)
			iRetVal = ProcessDecoderPropertyForReturn(L"reticle", szPropertyValue);
		else
			iRetVal = -1;
	}
	else if (cmp(szPropertyName, L"LinearSecurityLevel"))
	{
		if (readerParams.ReaderSpecific.laser_specific.dwLinearSecurityLevel == SECURITY_REDUNDANCY_AND_LENGTH)
			iRetVal = ProcessDecoderPropertyForReturn(L"redundancyAndLength", szPropertyValue);
		else if (readerParams.ReaderSpecific.laser_specific.dwLinearSecurityLevel == SECURITY_SHORT_OR_CODABAR)
			iRetVal = ProcessDecoderPropertyForReturn(L"shortOrCodabar", szPropertyValue);
		else if (readerParams.ReaderSpecific.laser_specific.dwLinearSecurityLevel == SECURITY_LONG_AND_SHORT)
			iRetVal = ProcessDecoderPropertyForReturn(L"longAndShort", szPropertyValue);
		else if (readerParams.ReaderSpecific.laser_specific.dwLinearSecurityLevel == SECURITY_ALL_TWICE)
			iRetVal = ProcessDecoderPropertyForReturn(L"allTwice", szPropertyValue);
		else if (readerParams.ReaderSpecific.laser_specific.dwLinearSecurityLevel == SECURITY_ALL_THRICE)
			iRetVal = ProcessDecoderPropertyForReturn(L"allThrice", szPropertyValue);
		else
			iRetVal = -1;
	}
	else if (cmp(szPropertyName, L"DBPMode"))
	{
		if (readerParams.ReaderSpecific.laser_specific.dwDBPMode == DBP_NORMAL)
			iRetVal = ProcessDecoderPropertyForReturn(L"normal", szPropertyValue);
		else if (readerParams.ReaderSpecific.laser_specific.dwDBPMode == DBP_COMPOSITE)
			iRetVal = ProcessDecoderPropertyForReturn(L"composite", szPropertyValue);
		else
			iRetVal = -1;
	}
	else if (cmp(szPropertyName, L"FocusMode"))
	{
		if (readerParams.ReaderSpecific.imager_specific.dwFocusMode == FOCUS_MODE_FIXED)
			iRetVal = ProcessDecoderPropertyForReturn(L"fixed", szPropertyValue);
		else if (readerParams.ReaderSpecific.imager_specific.dwFocusMode == FOCUS_MODE_AUTO)
			iRetVal = ProcessDecoderPropertyForReturn(L"auto", szPropertyValue);
		else
			iRetVal = -1;
	}
	else if (cmp(szPropertyName, L"PicklistMode"))
	{
		if (readerParams.ReaderSpecific.imager_specific.dwPicklistModeEx == PICKLIST_DISABLED)
			iRetVal = ProcessDecoderPropertyForReturn(L"disabled", szPropertyValue);
		else if (readerParams.ReaderSpecific.imager_specific.dwPicklistModeEx == PICKLIST_HARDWARE_RETICLE)
			iRetVal = ProcessDecoderPropertyForReturn(L"hardwareReticle", szPropertyValue);
		else if (readerParams.ReaderSpecific.imager_specific.dwPicklistModeEx == PICKLIST_SOFTWARE_RETICLE)
			iRetVal = ProcessDecoderPropertyForReturn(L"softwareReticle", szPropertyValue);
		else
			iRetVal = -1;
	}
	else if (cmp(szPropertyName, L"IlluminationMode"))
	{
		if (readerParams.ReaderSpecific.imager_specific.dwIlluminationMode == ILLUMINATION_AUTO)
			iRetVal = ProcessDecoderPropertyForReturn(L"auto", szPropertyValue);
		else if (readerParams.ReaderSpecific.imager_specific.dwIlluminationMode == ILLUMINATION_ALWAYS_ON)
			iRetVal = ProcessDecoderPropertyForReturn(L"alwaysOn", szPropertyValue);
		else if (readerParams.ReaderSpecific.imager_specific.dwIlluminationMode == ILLUMINATION_ALWAYS_OFF)
			iRetVal = ProcessDecoderPropertyForReturn(L"alwaysOff", szPropertyValue);
		else
			iRetVal = -1;
	}
	else if (cmp(szPropertyName, L"ViewfinderMode"))
	{
		if (readerParams.ReaderSpecific.imager_specific.dwVFMode == VIEWFINDER_MODE_ENABLED)
			iRetVal = ProcessDecoderPropertyForReturn(L"enabled", szPropertyValue);
		else if (readerParams.ReaderSpecific.imager_specific.dwVFMode == VIEWFINDER_MODE_DISABLED)
			iRetVal = ProcessDecoderPropertyForReturn(L"disabled", szPropertyValue);
		else if (readerParams.ReaderSpecific.imager_specific.dwVFMode == VIEWFINDER_MODE_STATIC_RETICLE)
			iRetVal = ProcessDecoderPropertyForReturn(L"staticReticle", szPropertyValue);
		else if (readerParams.ReaderSpecific.imager_specific.dwVFMode == VIEWFINDER_MODE_DYNAMIC_RETICLE)
			iRetVal = ProcessDecoderPropertyForReturn(L"dynamicReticle", szPropertyValue);
		else
			iRetVal = -1;
	}
	else if (cmp(szPropertyName, L"ViewfinderFeedback"))
	{
		if (readerParams.ReaderSpecific.imager_specific.dwVFFeedback == VIEWFINDER_FEEDBACK_ENABLED)
			iRetVal = ProcessDecoderPropertyForReturn(L"enabled", szPropertyValue);
		else if (readerParams.ReaderSpecific.imager_specific.dwVFFeedback == VIEWFINDER_FEEDBACK_DISABLED)
			iRetVal = ProcessDecoderPropertyForReturn(L"disabled", szPropertyValue);
		else if (readerParams.ReaderSpecific.imager_specific.dwVFFeedback == VIEWFINDER_FEEDBACK_RETICLE)
			iRetVal = ProcessDecoderPropertyForReturn(L"reticle", szPropertyValue);
		else
			iRetVal = -1;
	}
	else if (cmp(szPropertyName, L"Inverse1DMode"))
	{
		if (readerParams.ReaderSpecific.imager_specific.dwInverse1DMode == INVERSE_ENABLE)
			iRetVal = ProcessDecoderPropertyForReturn(L"enabled", szPropertyValue);
		else if (readerParams.ReaderSpecific.imager_specific.dwInverse1DMode == INVERSE_DISABLE)
			iRetVal = ProcessDecoderPropertyForReturn(L"disabled", szPropertyValue);
		else if (readerParams.ReaderSpecific.imager_specific.dwInverse1DMode == INVERSE_AUTO)
			iRetVal = ProcessDecoderPropertyForReturn(L"auto", szPropertyValue);
		else
			iRetVal = -1;
	}
	else if (cmp(szPropertyName, L"TimedAimDuration"))
	{
		iRetVal = ProcessDecoderPropertyForReturn(
			readerParams.ReaderSpecific.laser_specific.dwAimDuration, szPropertyValue);
	}
	else if (cmp(szPropertyName, L"NarrowBeam"))
	{
		Log(SCANNER_LOG_INFO, L"NarrowBeam has been deprecated, please use BeamWidth in preference",
			_T(__FUNCTION__), __LINE__);
		if (readerParams.ReaderSpecific.laser_specific.bNarrowBeam)
			iRetVal = ProcessDecoderPropertyForReturn(L"true", szPropertyValue);
		else
			iRetVal = ProcessDecoderPropertyForReturn(L"false", szPropertyValue);
	}
	else if (cmp(szPropertyName, L"BeamWidth"))
	{
		if (readerParams.ReaderSpecific.laser_specific.dwBeamWidth == BEAM_WIDTH_NORMAL)
			iRetVal = ProcessDecoderPropertyForReturn(L"normal", szPropertyValue);
		else if (readerParams.ReaderSpecific.laser_specific.dwBeamWidth == BEAM_WIDTH_NARROW)
			iRetVal = ProcessDecoderPropertyForReturn(L"narrow", szPropertyValue);
		else if (readerParams.ReaderSpecific.laser_specific.dwBeamWidth == BEAM_WIDTH_WIDE)
			iRetVal = ProcessDecoderPropertyForReturn(L"wide", szPropertyValue);
		else
			iRetVal = -1;
	}
	else if (cmp(szPropertyName, L"ScanTimeout"))
	{
		iRetVal = ProcessDecoderPropertyForReturn(
			readerParams.ReaderSpecific.laser_specific.dwBeamTimer, szPropertyValue);
	}
	else if (cmp(szPropertyName, L"KlasseEins"))
	{
		if (readerParams.ReaderSpecific.laser_specific.bKlasseEinsEnable)
			iRetVal = ProcessDecoderPropertyForReturn(L"true", szPropertyValue);
		else
			iRetVal = ProcessDecoderPropertyForReturn(L"false", szPropertyValue);
	}
	else if (cmp(szPropertyName, L"BidirectionalRedundancy"))
	{
		if (readerParams.ReaderSpecific.laser_specific.bBidirRedundancy)
			iRetVal = ProcessDecoderPropertyForReturn(L"true", szPropertyValue);
		else
			iRetVal = ProcessDecoderPropertyForReturn(L"false", szPropertyValue);
	}
	else if (cmp(szPropertyName, L"RasterHeight"))
	{
		iRetVal = ProcessDecoderPropertyForReturn(
			readerParams.ReaderSpecific.laser_specific.dwRasterHeight, szPropertyValue);
	}
	else if (cmp(szPropertyName, L"SameSymbolTimeout"))
	{
		iRetVal = ProcessDecoderPropertyForReturn(
			readerParams.ReaderSpecific.imager_specific.dwSameSymbolTimeout, szPropertyValue);
	}
	else if (cmp(szPropertyName, L"DifferentSymbolTimeout"))
	{
		iRetVal = ProcessDecoderPropertyForReturn(
			readerParams.ReaderSpecific.imager_specific.dwDifferentSymbolTimeout, szPropertyValue);
	}
	else if (cmp(szPropertyName, L"PoorQuality1DMode"))
	{
		if (readerParams.ReaderSpecific.imager_specific.bPoorQuality1DMode)
			iRetVal = ProcessDecoderPropertyForReturn(L"true", szPropertyValue);
		else
			iRetVal = ProcessDecoderPropertyForReturn(L"false", szPropertyValue);
	}
	else if (cmp(szPropertyName, L"DPMMode"))
	{
		if (readerParams.ReaderSpecific.imager_specific.dwDPMMode == DPM_ENABLED)
			iRetVal = ProcessDecoderPropertyForReturn(L"true", szPropertyValue);
		else
			iRetVal = ProcessDecoderPropertyForReturn(L"false", szPropertyValue);
	}
	else if (cmp(szPropertyName, L"ViewfinderX"))
	{
		iRetVal = ProcessDecoderPropertyForReturn(
			readerParams.ReaderSpecific.imager_specific.rVFPosition.left, szPropertyValue);
	}
	else if (cmp(szPropertyName, L"ViewfinderY"))
	{
		iRetVal = ProcessDecoderPropertyForReturn(
			readerParams.ReaderSpecific.imager_specific.rVFPosition.top, szPropertyValue);
	}
	else if (cmp(szPropertyName, L"ViewfinderWidth"))
	{
		iRetVal = ProcessDecoderPropertyForReturn(
			(readerParams.ReaderSpecific.imager_specific.rVFPosition.right -
			readerParams.ReaderSpecific.imager_specific.rVFPosition.left), szPropertyValue);
	}
	else if (cmp(szPropertyName, L"ViewfinderHeight"))
	{
		iRetVal = ProcessDecoderPropertyForReturn(
			(readerParams.ReaderSpecific.imager_specific.rVFPosition.top -
			readerParams.ReaderSpecific.imager_specific.rVFPosition.bottom), szPropertyValue);
	}
	else if (cmp(szPropertyName, L"ViewfinderFeedbackTime"))
	{
		iRetVal = ProcessDecoderPropertyForReturn(
			readerParams.ReaderSpecific.imager_specific.dwVFFeedbackTime, szPropertyValue);
	}
	else if (cmp(szPropertyName, L"AdaptiveScanning"))
	{
		if (readerParams.ReaderSpecific.laser_specific.dwAdaptiveScanning == ADAPTIVE_SCANNING_ENABLE)
			iRetVal = ProcessDecoderPropertyForReturn(L"true", szPropertyValue);
		else
			iRetVal = ProcessDecoderPropertyForReturn(L"false", szPropertyValue);
	}
	else if (cmp(szPropertyName, L"ScanType"))
	{
		if (m_currentScanType == SCAN_TYPE_FOREGROUND)
			iRetVal = ProcessDecoderPropertyForReturn(L"foreground", szPropertyValue);
		else if (m_currentScanType == SCAN_TYPE_BACKGROUND)
			iRetVal = ProcessDecoderPropertyForReturn(L"background", szPropertyValue);
		else if (m_currentScanType == SCAN_TYPE_MONITOR)
			iRetVal = ProcessDecoderPropertyForReturn(L"monitor", szPropertyValue);
		else
			iRetVal = -1;
	}
	else if (cmp(szPropertyName, L"dataBufferSize"))
	{
		iRetVal = ProcessDecoderPropertyForReturn(m_iDataBufferSize, szPropertyValue);
	}
	else if (cmp(szPropertyName, L"BarcodeDataFormat"))
	{
		if (m_bufferFormat == BUFFER_TEXT)
			iRetVal = ProcessDecoderPropertyForReturn(L"text", szPropertyValue);
		else if (m_bufferFormat == BUFFER_RAW_DATA)
			iRetVal = ProcessDecoderPropertyForReturn(L"binary", szPropertyValue);
		else
			iRetVal = -1;
	}
	return iRetVal;
}

int CScanner::ScannerBluetoothTag_GetPropertyValue(LPCTSTR szPropertyName, WCHAR* szPropertyValue)
{
	int iRetVal = -1;
	INTERFACE_PARAMS interfaceParams;
	RetrieveScannerInterfaceParameters(&interfaceParams);
	if (cmp(szPropertyName, L"ConnectionIdleTimeout"))
	{
		iRetVal = ProcessDecoderPropertyForReturn(
				interfaceParams.InterfaceSpecific.SsiSpecific.dwConnectionIdleTimeout
				, szPropertyValue);
	}
	else if (cmp(szPropertyName, L"DisconnectBTOnDisable"))
	{
		if (interfaceParams.InterfaceSpecific.SsiSpecific.bBTDisconnectOnExit)
			iRetVal = ProcessDecoderPropertyForReturn(L"true", szPropertyValue);
		else
			iRetVal = ProcessDecoderPropertyForReturn(L"false", szPropertyValue);
	}
	else if (cmp(szPropertyName, L"displayBTAddressBarcodeOnEnable"))
	{
		if (m_iDisplayBTPairBarcode)
			iRetVal = ProcessDecoderPropertyForReturn(L"true", szPropertyValue);
		else
			iRetVal = ProcessDecoderPropertyForReturn(L"false", szPropertyValue);
	}
	else if (cmp(szPropertyName, L"enableTimeout"))
	{
		iRetVal = ProcessDecoderPropertyForReturn(m_dwEnableTimeout, szPropertyValue);
	}
	return iRetVal;
}


text:
<!DOCTYPE html>

        <title>Data Dictionary</title>

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
		<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
		<link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Lato" />
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <link rel="shortcut icon" href="img/favicon.ico">
        <link rel="stylesheet" href="css/data_dictionary.css">
		<link rel="stylesheet" href="css/loading.css">

                        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                            Toggle navigation

                        </button>
                        (current)

About

Data Dictionary

Explore Variables

Explore Neighborhoods

Explore Composite Indicators

Data Stories

Learn About The Data

Login/Sign Up

DATA DICTIONARY

SORT DATASETS:
                        <input type="radio"  ng-model="inputBtnValue" ng-value="1"  ng-change="sort(inputBtnValue)" > By Policy Area
                        <input type="radio"  ng-model="inputBtnValue" ng-value="2" ng-change="sort(inputBtnValue)"  > Alphabetically

DATASETS

VARIABLES

VARIABLE DEFINITION

SOURCE

YEARS AVAILABLE

{{a}}

                                {{b.dataset}}

                                {{b['variable']}}

                                {{b['variabledefinition']}}

                                {{b['datasource']}}

                                {{b['yearsavailable']}}

                                            <button type="button" class="close" data-dismiss="modal">×</button>

Download Data for {{ newVar }}

                                            <select class="form-control" id="sel1"  style="background-color:#0c343d;color:white;width:25%;margin:auto;" ng-model="modelSelectedYear" ng-options="d.year for d in yearss" >
                                                <option value="" disabled>Select a Value</option>
                                            </select>

                                            Download

                                            <button type="button" class="btn btn-default" data-dismiss="modal" style="color: #0c343d; font-weight:  bold; background-color:#d9ead3;border: 2px solid #0c343d; letter-spacing:1px;">Cancel</button>

                            {{c.dataset}}

                            {{c['variable']}}

                            {{c['variabledefinition']}}

                            {{c['datasource']}}

                            {{c['yearsavailable']}}

                                        <button type="button" class="close" data-dismiss="modal">×</button>

Download Data for {{ newVar }}

                                        <select class="form-control" id="sel2"  style="background-color:#0c343d;color:white;width:25%;margin:auto;" ng-model="modelSelectedYear" ng-options="d.year for d in yearss" >
                                            <option value="" disabled>Select a Value</option>
                                        </select>

                                        Download

                                        <button type="button" class="btn btn-default" data-dismiss="modal" style="color: #0c343d; font-weight: bold; background-color:#d9ead3;border: 2px solid #0c343d; letter-spacing:1px;">Cancel</button>


text:
/*****************************************************************************
 *
 *  ParentSelection.h - Interface to Parent Selection System
 *
 *
 ****************************************************************************/

#pragma once

#include "ProxyConfig.h"
#include "ControlBase.h"
#include "ControlMatcher.h"
#include "records/P_RecProcess.h"
#include "tscore/ConsistentHash.h"
#include "tscore/Tokenizer.h"
#include "tscore/ink_apidefs.h"
#include "HostStatus.h"

#include <algorithm>
#include <vector>

#define MAX_PARENTS 64
#define DEFAULT_PARENT_WEIGHT 1.0

struct RequestData;
struct matcher_line;
struct ParentResult;
struct OverridableHttpConfigParams;
class ParentRecord;
class ParentSelectionStrategy;

enum ParentResultType {
  PARENT_UNDEFINED,
  PARENT_DIRECT,
  PARENT_SPECIFIED,
  PARENT_AGENT,
  PARENT_FAIL,
};

static const char *ParentResultStr[] = {"PARENT_UNDEFINED", "PARENT_DIRECT", "PARENT_SPECIFIED", "PARENT_AGENT", "PARENT_FAIL"};

enum ParentRR_t {
  P_NO_ROUND_ROBIN = 0,
  P_STRICT_ROUND_ROBIN,
  P_HASH_ROUND_ROBIN,
  P_CONSISTENT_HASH,
  P_LATCHED_ROUND_ROBIN,
  P_UNDEFINED
};

enum ParentRetry_t {
  PARENT_RETRY_NONE               = 0,
  PARENT_RETRY_SIMPLE             = 1,
  PARENT_RETRY_UNAVAILABLE_SERVER = 2,
  // both simple and unavailable server retry
  PARENT_RETRY_BOTH = 3
};

struct UnavailableServerResponseCodes {
  UnavailableServerResponseCodes(char *val);
  ~UnavailableServerResponseCodes(){};

  bool
  contains(int code)
  {
    return binary_search(codes.begin(), codes.end(), code);
  }

private:
  std::vector<int> codes;
};

struct SimpleRetryResponseCodes {
  SimpleRetryResponseCodes(char *val);
  ~SimpleRetryResponseCodes(){};

  bool
  contains(int code)
  {
    return binary_search(codes.begin(), codes.end(), code);
  }

private:
  std::vector<int> codes;
};

// struct pRecord
//
//    A record for an individual parent
//
struct pRecord : ATSConsistentHashNode {
public:
  char hostname[MAXDNAME + 1];
  int port;
  std::atomic<time_t> failedAt = 0;
  std::atomic<int> failCount   = 0;
  int32_t upAt;
  const char *scheme; // for which parent matches (if any)
  int idx;
  float weight;
  char hash_string[MAXDNAME + 1];
};

typedef ControlMatcher<ParentRecord, ParentResult> P_table;

// class ParentRecord : public ControlBase
//
//   A record for a configuration line in the parent.config
//    file
//
class ParentRecord : public ControlBase
{
public:
  ~ParentRecord();

  Result Init(matcher_line *line_info);
  bool DefaultInit(char *val);
  void UpdateMatch(ParentResult *result, RequestData *rdata);

  void Print() const;

  pRecord *parents           = nullptr;
  pRecord *secondary_parents = nullptr;
  int num_parents            = 0;
  int num_secondary_parents  = 0;

  bool
  bypass_ok() const
  {
    return go_direct;
  }

  const char *scheme = nullptr;
  // private:
  void PreProcessParents(const char *val, const int line_num, char *buf, size_t len);
  const char *ProcessParents(char *val, bool isPrimary);
  bool ignore_query                                                  = false;
  uint32_t rr_next                                                   = 0;
  bool go_direct                                                     = true;
  bool parent_is_proxy                                               = true;
  ParentSelectionStrategy *selection_strategy                        = nullptr;
  UnavailableServerResponseCodes *unavailable_server_retry_responses = nullptr;
  SimpleRetryResponseCodes *simple_server_retry_responses            = nullptr;
  ParentRetry_t parent_retry                                         = PARENT_RETRY_NONE;
  int max_simple_retries                                             = 1;
  int max_unavailable_server_retries                                 = 1;
  int secondary_mode                                                 = 1;
  bool ignore_self_detect                                            = false;
};

// If the parent was set by the external customer api,
//   our HttpRequestData structure told us what parent to
//   use and we are only called to preserve clean interface
//   between HttpTransact & the parent selection code.  The following
ParentRecord *const extApiRecord = (ParentRecord *)0xeeeeffff;

// used here to set the number of ATSConsistentHashIter's
// used in NextHopSelectionStrategy to limit the host group
// size as well, group size is one to one with the number of rings
constexpr const uint32_t MAX_GROUP_RINGS = 5;

struct ParentResult {
  ParentResult() { reset(); }
  // For outside consumption
  ParentResultType result;
  const char *hostname;
  const char *url;
  int port;
  bool retry;
  bool chash_init[MAX_GROUP_RINGS] = {false};
  TSHostStatus first_choice_status = TSHostStatus::TS_HOST_STATUS_INIT;
  bool do_not_cache_response       = false;

  void
  reset()
  {
    ink_zero(*this);
    line_number           = -1;
    result                = PARENT_UNDEFINED;
    mapWrapped[0]         = false;
    mapWrapped[1]         = false;
    do_not_cache_response = false;
  }

  bool
  is_api_result() const
  {
    return rec == extApiRecord;
  }

  // Do we have some result?
  bool
  is_some() const
  {
    if (rec == nullptr) {
      // If we don't have a result, we either haven't done a parent
      // lookup yet (PARENT_UNDEFINED), or the lookup didn't match
      // anything (PARENT_DIRECT).
      ink_assert(result == PARENT_UNDEFINED || result == PARENT_DIRECT);
      return false;
    }

    return true;
  }

  bool
  parent_is_proxy() const
  {
    // Parents set by the TSHttpTxnParentProxySet API are always considered proxies rather than origins.
    return is_api_result() ? true : rec->parent_is_proxy;
  }

  unsigned
  retry_type() const
  {
    return is_api_result() ? PARENT_RETRY_NONE : rec->parent_retry;
  }

  unsigned
  max_retries(ParentRetry_t method) const
  {
    // There's no API for specifying the retries, so you get 0.
    if (is_api_result()) {
      return 0;
    }

    switch (method) {
    case PARENT_RETRY_NONE:
      return 0;
    case PARENT_RETRY_SIMPLE:
      return rec->max_simple_retries;
    case PARENT_RETRY_UNAVAILABLE_SERVER:
      return rec->max_unavailable_server_retries;
    case PARENT_RETRY_BOTH:
      return std::max(rec->max_unavailable_server_retries, rec->max_simple_retries);
    }

    return 0;
  }

  bool
  response_is_retryable(ParentRetry_t retry_type, HTTPStatus response_code) const
  {
    Debug("parent_select", "In response_is_retryable, code: %d, type: %d", response_code, retry_type);
    if (retry_type == PARENT_RETRY_BOTH) {
      Debug("parent_select", "Saw retry both");
      return (rec->unavailable_server_retry_responses->contains(response_code) ||
              rec->simple_server_retry_responses->contains(response_code));
    } else if (retry_type == PARENT_RETRY_UNAVAILABLE_SERVER) {
      Debug("parent_select", "Saw retry unavailable server");
      return rec->unavailable_server_retry_responses->contains(response_code);
    } else if (retry_type == PARENT_RETRY_SIMPLE) {
      Debug("parent_select", "Saw retry simple retry");
      return rec->simple_server_retry_responses->contains(response_code);
    } else {
      return false;
    }
  }

  bool
  bypass_ok() const
  {
    if (is_api_result()) {
      return false;
    } else {
      // Caller should check for a valid result beforehand.
      ink_assert(result != PARENT_UNDEFINED);
      ink_assert(is_some());
      return rec->bypass_ok();
    }
  }

  void
  print()
  {
    printf("ParentResult - hostname: %s, port: %d, retry: %s, line_number: %d, last_parent: %d, start_parent: %d, wrap_around: %s, "
           "last_lookup: %d, result: %s\n",
           hostname, port, (retry) ? "true" : "false", line_number, last_parent, start_parent, (wrap_around) ? "true" : "false",
           last_lookup, ParentResultStr[result]);
  }

private:
  // Internal use only
  //   Not to be modified by HTTP
  int line_number;
  ParentRecord *rec;
  uint32_t last_parent;
  uint32_t start_parent;
  uint32_t last_group;
  bool wrap_around;
  bool mapWrapped[2];
  // state for consistent hash.
  int last_lookup;
  ATSConsistentHashIter chashIter[MAX_GROUP_RINGS];

  friend class NextHopSelectionStrategy;
  friend class NextHopRoundRobin;
  friend class NextHopConsistentHash;
  friend class ParentConsistentHash;
  friend class ParentRoundRobin;
  friend class ParentConfigParams;
  friend class ParentRecord;
  friend class ParentSelectionStrategy;
};

struct ParentSelectionPolicy {
  int32_t ParentRetryTime;
  int32_t ParentEnable;
  int32_t FailThreshold;
  ParentSelectionPolicy();
};

//
// API definition.
class ParentSelectionStrategy
{
public:
  int max_retriers = 0;

  ParentSelectionStrategy() { REC_ReadConfigInteger(max_retriers, "proxy.config.http.parent_proxy.max_trans_retries"); }
  //
  // Return the pRecord.
  virtual pRecord *getParents(ParentResult *result) = 0;
  // void selectParent(bool firstCall, ParentResult *result, RequestData *rdata, unsigned int fail_threshold, unsigned int
  // retry_time)
  //
  // The implementation parent lookup.
  //
  virtual void selectParent(bool firstCall, ParentResult *result, RequestData *rdata, unsigned int fail_threshold,
                            unsigned int retry_time) = 0;

  // uint32_t numParents(ParentResult *result);
  //
  // Returns the number of parent records in a strategy.
  //
  virtual uint32_t numParents(ParentResult *result) const = 0;
  void markParentDown(ParentResult *result, unsigned int fail_threshold, unsigned int retry_time);
  void markParentUp(ParentResult *result);

  // virtual destructor.
  virtual ~ParentSelectionStrategy(){};
};

class ParentConfigParams : public ConfigInfo
{
public:
  explicit ParentConfigParams(P_table *_parent_table);
  ~ParentConfigParams() override;

  bool apiParentExists(HttpRequestData *rdata);
  void findParent(HttpRequestData *rdata, ParentResult *result, unsigned int fail_threshold, unsigned int retry_time);
  void nextParent(HttpRequestData *rdata, ParentResult *result, unsigned int fail_threshold, unsigned int retry_time);
  bool parentExists(HttpRequestData *rdata);

  // implementation of functions from ParentSelectionStrategy.
  void
  selectParent(bool firstCall, ParentResult *result, RequestData *rdata, unsigned int fail_threshold, unsigned int retry_time)
  {
    if (!result->is_api_result()) {
      ink_release_assert(result->rec->selection_strategy != nullptr);
      return result->rec->selection_strategy->selectParent(firstCall, result, rdata, fail_threshold, retry_time);
    }
  }

  void
  markParentDown(ParentResult *result, unsigned int fail_threshold, unsigned int retry_time)
  {
    if (!result->is_api_result()) {
      ink_release_assert(result->rec->selection_strategy != nullptr);
      result->rec->selection_strategy->markParentDown(result, fail_threshold, retry_time);
    }
  }

  void
  markParentUp(ParentResult *result)
  {
    if (!result->is_api_result()) {
      ink_release_assert(result != nullptr);
      result->rec->selection_strategy->markParentUp(result);
    }
  }

  uint32_t
  numParents(ParentResult *result)
  {
    if (result->is_api_result()) {
      return 1;
    } else {
      ink_release_assert(result->rec->selection_strategy != nullptr);
      return result->rec->selection_strategy->numParents(result);
    }
  }

  P_table *parent_table;
  ParentRecord *DefaultParent;
  ParentSelectionPolicy policy;
};

class HttpRequestData;

struct ParentConfig {
public:
  static void startup();
  static void reconfigure();
  static void print();
  static void set_parent_table(P_table *pTable, ParentRecord *rec, int num_elements);

  static ParentConfigParams *
  acquire()
  {
    return (ParentConfigParams *)configProcessor.get(ParentConfig::m_id);
  }

  static void
  release(ParentConfigParams *strategy)
  {
    configProcessor.release(ParentConfig::m_id, strategy);
  }

  static int m_id;
};

// Helper Functions
ParentRecord *createDefaultParent(char *val);

// Unit Test Functions
void show_result(ParentResult *aParentResult);
void br(HttpRequestData *h, const char *os_hostname, sockaddr const *dest_ip = nullptr); // short for build request
int verify(ParentResult *r, ParentResultType e, const char *h, int p);

/*
  For supporting multiple Socks servers, we essentially use the
  ParentSelection infrastructure. Only the initialization is different.
  If needed, we will have to implement most of the functions in
  ParentSection.cc for Socks as well. For right now we will just use
  ParentSelection

  All the members in ParentConfig are static. Right now
  we will duplicate the code for these static functions.
*/
struct SocksServerConfig {
  static void startup();
  static void reconfigure();
  static void print();

  static ParentConfigParams *
  acquire()
  {
    return (ParentConfigParams *)configProcessor.get(SocksServerConfig::m_id);
  }
  static void
  release(ParentConfigParams *params)
  {
    configProcessor.release(SocksServerConfig::m_id, params);
  }

  static int m_id;
};


text:
layout: post
title: SQLite3
---

SQLite3 je výbornou volbou pro malé a střední projekty, které potřebují databázi. Jak vypadá základní zacházení s touto databází?

# Základní přehled

SQLite3 je plnohodnotná databáze, která se použitím příliš neliší od [MySQL](https://cs.wikipedia.org/wiki/MySQL) či [PostgreSQL](https://postgres.cz/wiki/PostgreSQL). Často se ale podceňuje, ačkoliv nabízí plně podporované SQL dotazy, potřebu jediného souboru, velikost 1 GB dat pro jednu řádku i přes 100 TB pro jednu databázi. Ve zkratce je SQLite rychlá, spolehlivá a jednoduchá na použití.

Výhoda je i v univerzálnosti - podpora pro SQLite je vestavěná nejen v PHP, ale i v C, C++, Go, Javě, JavaScriptu, Pythonu, Ruby a dalších. Tuto databázi využívá například Android, v prohlížeče Chrome a Firefox nebo Apple Mail. Navíc je platformě agnostická - když data naplníš na iOS, na Windows je bez problémů zase přečteš.

Zajímavou vlastností je absence typů. V SQLite lze sloupečky natypovat, databázi v zásadě ale nevadí, když do `INTEGER` vložíš text. Na toto chování pozor, většinou není od kodéra zamýšlené a může skrývat další bugy.

Celý zdrojový kód je k [dispozici online](https://www.sqlite.org/src/doc/trunk/README.md) a lze použít bez jakýkoliv dalších omezení.

## První použití

Základní připojení databáze mohlo vypadat nějak takto:

```php

<?php

$db = new SQLite3('databaseName.sqlite');

$results = $db->query('SELECT bar FROM foo');
while ($row = $results->fetchArray()) {
    var_dump($row);
}

```

## Použití s PDO

Verze připojení při použití PDO:

```php

<?php

$db = new PDO('sqlite:databaseName.sqlite');

$results = $db->query('SELECT bar FROM foo');
foreach ($results as $row) {
    var_dump($row);
}

```

## Registrace do DI kontejneru

Jak vypadá zaregistrování databáze do DI:

```php
<?php

$container['db'] = function ($c) {
	$db = $c['settings']['db'];
	$pdo = new PDO('sqlite:databaseName.sqlite');

	return $pdo;
};

```

Tento příklad je převzaný pro [framework Slim](https://www.slimframework.com/), který interně používá DI [Pimple](https://pimple.symfony.com/).

# Odkazy

Nejlepší web pro SQLite je [SQLite.org](https://sqlite.org), který funguje i jako místo pro dokumentaci. Organizace W3 nabízí pro SQLite i [tutoriál](https://www.w3resource.com/sqlite/). Na [xojo.com](https://blog.xojo.com/2017/10/03/sqlite-rocks-let-us-tell-you-why/) se dozvíš, proč na SQLite nedají dopustit. A internet je plný návodů a příkladů, neváhejte použít [Google](https://www.google.com/) :)

# Too Long, Didn't Read?

SQLite3 je databázový systém, který se dá pohodlně použít pro malé projekty. V PHP má nativní podporu a jde používat jednoduše bez dalších PHP rozšíření.


text:
<meta charset="UTF-8">
<title>RNAG.component1 - </title>
<link rel="stylesheet" href="../../style.css">

com.epimorphics.android.myrivers.data / RNAG / component1

component1

@NotNull fun component1(): java.lang.Stringelement name

Property

element - element name


text:
@extends('layouts.app')

@section('content')

THIS IS HOME PAGE FOR COMPANIES ONLY

@endsection


text:
from django.contrib.auth.decorators import permission_required
from django.core.urlresolvers import reverse
from django.forms import ModelForm
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.shortcuts import get_object_or_404
from django.template import RequestContext
from django.utils.translation import ugettext_lazy as _
from django.views.decorators.http import require_POST

# lfs imports
import lfs.core.utils
from lfs.catalog.models import DeliveryTime
from lfs.catalog.models import Product

class DeliveryTimeAddForm(ModelForm):
    """Form to edit add a delivery time.
    """
    class Meta:
        model = DeliveryTime
        fields = ("min", "max", "unit")

class DeliveryTimeForm(ModelForm):
    """Form to edit a delivery time.
    """
    class Meta:
        model = DeliveryTime

@permission_required("core.manage_shop", login_url="/login/")
def manage_delivery_times(request):
    """Dispatches to the first delivery time or to the form to add a delivery
    time (if there is no delivery time yet).
    """
    try:
        delivery_time = DeliveryTime.objects.all()[0]
        url = reverse("lfs_manage_delivery_time", kwargs={"id": delivery_time.id})
    except IndexError:
        url = reverse("lfs_manage_add_delivery_time")

    return HttpResponseRedirect(url)

@permission_required("core.manage_shop", login_url="/login/")
def manage_delivery_time(request, id, template_name="manage/delivery_times/base.html"):
    """Provides a form to edit the delivery time with the passed id.
    """
    delivery_time = get_object_or_404(DeliveryTime, pk=id)
    if request.method == "POST":
        form = DeliveryTimeForm(instance=delivery_time, data=request.POST, files=request.FILES)
        if form.is_valid():
            new_delivery_time = form.save()
            return lfs.core.utils.set_message_cookie(
                url=reverse("lfs_manage_delivery_time", kwargs={"id": id}),
                msg=_(u"Delivery time has been saved."),
            )
    else:
        form = DeliveryTimeForm(instance=delivery_time)

    return render_to_response(template_name, RequestContext(request, {
        "delivery_time": delivery_time,
        "delivery_times": DeliveryTime.objects.all(),
        "form": form,
        "current_id": int(id),
    }))

@permission_required("core.manage_shop", login_url="/login/")
def add_delivery_time(request, template_name="manage/delivery_times/add.html"):
    """Provides a form to add a new delivery time.
    """
    if request.method == "POST":
        form = DeliveryTimeAddForm(data=request.POST)
        if form.is_valid():
            delivery_time = form.save()

            return lfs.core.utils.set_message_cookie(
                url=reverse("lfs_manage_delivery_time", kwargs={"id": delivery_time.id}),
                msg=_(u"Delivery time has been added."),
            )

    else:
        form = DeliveryTimeAddForm()

    return render_to_response(template_name, RequestContext(request, {
        "form": form,
        "delivery_times": DeliveryTime.objects.all(),
        "next": request.REQUEST.get("next", request.META.get("HTTP_REFERER")),
    }))

@permission_required("core.manage_shop", login_url="/login/")
@require_POST
def delete_delivery_time(request, id):
    """Deletes the delivery time with passed id.
    """
    # Remove the delivery time from all products delivery
    for product in Product.objects.filter(delivery_time=id):
        product.delivery_time = None
        product.save()

    # Remove the delivery time from all products order_time
    for product in Product.objects.filter(order_time=id):
        product.order_time = None
        product.save()

    delivery_time = get_object_or_404(DeliveryTime, pk=id)
    delivery_time.delete()

    return lfs.core.utils.set_message_cookie(
        url=reverse("lfs_manage_delivery_times"),
        msg=_(u"Delivery time has been deleted."),
    )


text:
package org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.debugpoint.impl;

import static org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.utils.ESBDebuggerConstants.ESB_SKIPPOINT_ACTION_ID;
import static org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.utils.ESBDebuggerConstants.ESB_SKIPPOINT_COMMAND_LABEL;
import static org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.utils.ESBDebuggerConstants.ESB_SKIPPOINT_COMMAND_TOOL_TIP;
import static org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.utils.ESBDebuggerConstants.SKIP_POINT_LABEL;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.emf.edit.domain.IEditingDomainProvider;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.gef.EditPart;
import org.eclipse.gmf.runtime.common.ui.action.AbstractActionHandler;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PlatformUI;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.Activator;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.AbstractMediator;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.configure.ConfigureEsbNodeAction;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.exception.ESBDebuggerException;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.utils.ESBDebuggerUtil;
import org.wso2.developerstudio.eclipse.logging.core.IDeveloperStudioLog;
import org.wso2.developerstudio.eclipse.logging.core.Logger;

/**
 * A {@link AbstractActionHandler} used to hook-up action for set and clear skip
 * points in esb design view editor.
 */
public class ESBSkipPointAction extends ConfigureEsbNodeAction {

    private static IDeveloperStudioLog log = Logger.getLog(Activator.PLUGIN_ID);

    public ESBSkipPointAction(IWorkbenchPart part) {
        super(part);
        super.init();
        setId(ESB_SKIPPOINT_ACTION_ID);
        setText(ESB_SKIPPOINT_COMMAND_LABEL);
        setToolTipText(ESB_SKIPPOINT_COMMAND_TOOL_TIP);
        ISharedImages workbenchImages = PlatformUI.getWorkbench().getSharedImages();
        setHoverImageDescriptor(workbenchImages.getImageDescriptor(ISharedImages.IMG_ETOOL_PRINT_EDIT));
        setImageDescriptor(workbenchImages.getImageDescriptor(ISharedImages.IMG_ETOOL_PRINT_EDIT));
        setDisabledImageDescriptor(workbenchImages.getImageDescriptor(ISharedImages.IMG_ETOOL_PRINT_EDIT_DISABLED));
    }

    /**
     * Utility method for retrieving the currently selected {@link EditPart}.
     *
     * @return current selected {@link EditPart} or null if multiple edit parts
     *         or no edit parts are selected.
     */
    @Override
    protected EditPart getSelectedEditPart() {
        IStructuredSelection selection = getStructuredSelection();
        if (selection.size() == 1) {
            Object selectedEP = selection.getFirstElement();
            if (selectedEP instanceof EditPart) {
                return (EditPart) selectedEP;
            }
        }
        return null;
    }

    /**
     * Utility method for calculating the editing domain.
     *
     * @return editing domain for this action.
     */
    @Override
    protected TransactionalEditingDomain getEditingDomain() {
        IWorkbenchPart part = getWorkbenchPart();

        if (part != null) {
            IEditingDomainProvider edProvider = (IEditingDomainProvider) part.getAdapter(IEditingDomainProvider.class);

            if (edProvider != null) {
                EditingDomain domain = edProvider.getEditingDomain();

                if (domain instanceof TransactionalEditingDomain) {
                    return (TransactionalEditingDomain) domain;
                }
            }
        }
        return null;
    }

    /**
     * This method performs the action when click the menu item Toggle Skip
     * Point
     */
    @Override
    protected void doRun(IProgressMonitor progressMonitor) {
        ESBDebuggerUtil.updateModifiedDebugPoints(false);
        EditPart selectedEP = getSelectedEditPart();
        if (selectedEP instanceof AbstractMediator && ESBDebugPointTarget.canToggleDiagramDebugpoints(selectedEP)) {
            try {
                ESBDebugPointTarget.toggleDiagramDebugpoints((AbstractMediator) selectedEP, SKIP_POINT_LABEL);
            } catch (CoreException | ESBDebuggerException e) {
                log.error("Error while registering the skip point" + e.getMessage(), e);
            }
        }

    }
}


text:
using ASPNETCoreIdentitySample.Entities.Identity;

namespace ASPNETCoreIdentitySample.ViewModels.Identity.Emails;

public class UserProfileUpdateNotificationViewModel : EmailsBase
{
    public User User { set; get; }
}


text:
cask "bootstrap-studio" do
  version "5.6.3"
  sha256 "7285011ef7a626f38ec87f578676e2fc007f817771c3c5d292b3746e7f56c752"

  url "https://bootstrapstudio.io/releases/desktop/#{version}/Bootstrap%20Studio.dmg"
  name "Bootstrap Studio"
  desc "Design and prototype websites using the Bootstrap framework"
  homepage "https://bootstrapstudio.io/"

  livecheck do
    url "https://bootstrapstudio.io/pages/releases/"
    regex(/Version\s*(\d+(?:\.\d+)+)/i)
  end

  auto_updates true
  depends_on macos: ">= :yosemite"

  app "Bootstrap Studio.app"

  zap trash: [
    "~/Library/Application Support/bstudio",
    "~/Library/Application Support/CrashReporter/Bootstrap Studio*",
    "~/Library/Caches/bg.zine.bootstrapstudio",
    "~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/bg.zine.bootstrapstudio.sfl2",
    "~/Library/Caches/bg.zine.bootstrapstudio.ShipIt",
    "~/Library/Preferences/ByHost/bg.zine.bootstrapstudio.ShipIt.*",
    "~/Library/Preferences/bg.zine.bootstrapstudio.helper.plist",
    "~/Library/Preferences/bg.zine.bootstrapstudio.plist",
    "~/Library/Saved Application State/bg.zine.bootstrapstudio.savedState",
  ]
end


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>br.com.ufpi.useskill</groupId>
  <artifactId>SPMF</artifactId>
  <version>0.0.1</version>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <resources>
      <resource>
        <directory>src</directory>
        <excludes>
          <exclude>**/*.java</exclude>
        </excludes>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.6</source>
          <target>1.6</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>


text:
//
//  Copyright (C) 2016 Tobias Lensing, Marcus Tillmanns
//  http://icedcoffee-framework.org
//
//  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.
//

#import <Foundation/Foundation.h>
#import "ICUpdatable.h"

@class ICNode;
@class ICAnimation;

typedef enum _ICSchedulerPriority {
    kICSchedulerPriority_Default,
    kICSchedulerPriority_High,
    kICSchedulerPriority_Low,
} ICSchedulerPriority;

/**
 @brief A scheduler used for continuously updating animated objects in a scene

 A scheduler continuously updates registered objects for animation purposes.
 Schedulers work in collaboration with host view controllers to issue pending updates to
 registered objects.

 Note that ICScheduler updates will only work as expected if the host view
 controller's ICHostViewController:frameUpdateMode is set to ICFrameUpdateModeSynchronized.
 Scenes usnig host view controllers that update their host view frame on demand should
 use NSTimer to perform updates.
 */
@interface ICScheduler : NSObject {
@protected
    NSMutableArray *_targets;
    NSMutableArray *_targetsWithLowPriority;
    NSMutableArray *_targetsWithHighPriority;
    NSMutableDictionary *_animations;
}

#pragma mark - Accessing the Current Scheduler
/** @name Accessing the Current Scheduler */

/**
 @brief Returns the scheduler for the current host view controller

 This method internally retrieves the current host view controller for the current thread by calling
 ICHostViewController::currentHostViewController and then returns a reference to the current
 scheduler as stored in the ICHostViewController::scheduler property.

 Note that this method is thread-safe while all other methods of this class are not.
 */
+ (id)currentScheduler;

#pragma mark - Scheduling Updates
/** @name Scheduling Update */

/**
 @brief Schedule a frame-wise update for the given target

 This method schedules frame-wise updates for the given target with default priority.

 @param target An object implementing the ICUpdatable protocol. The object will be retained
 by this method.

 @sa unscheduleUpdateForTarget:withPriority:
 */
- (void)scheduleUpdateForTarget:(id<ICUpdatable>)target;

/**
 @brief Schedule a frame-wise update for the given target with the specified priority

 This method schedules frame-wise updates for the given target with the specified priority.

 Each time the host view draws its scene, the target will receive an ICUpdatable::update: message.
 The messages are dispatched after the host view's OpenGL context has been locked and before the
 actual scene contents are drawn.

 @param target An object implementing the ICUpdatable protocol. The object will be retained
 by this method.

 @param priority A ICSchedulerPriority value indicating the priority of the updatable target.

 @remarks The scheduled update message will only be dispatched continuously when the respective
 ICHostViewController object that draws the scene is set to synchronized frame update mode. See
 ICHostViewController::frameUpdateMode.

 @exception Raises an NSInvalidArgumentException if target is nil or if priority is not a valid
 ICSchedulerPriority enumerated value.

 @sa unscheduleUpdateForTarget:
 */
- (void)scheduleUpdateForTarget:(id<ICUpdatable>)target withPriority:(ICSchedulerPriority)priority;

/**
 @brief Unschedule a previously scheduled update for the given target

 @param target An object that was previously scheduled for updates. The object will be released
 by this method.
 */
- (void)unscheduleUpdateForTarget:(id<ICUpdatable>)target;

/**
 @brief Called by the framework to update the scheduler internally

 Enumerates all targets added to the scheduler and dispatches an ICUpdatable::update: message
 to each of them, starting with targets scheduled with high priority and ending with targets
 scheduled with low priority.
 */
- (void)update:(icTime)dt;

#pragma mark - Managing Animations
/** @name Managing Animations */

/**
 @brief Returns all animations for the given node
 */
- (NSArray *)animationsForNode:(ICNode *)node;

/**
 @brief Adds the given animation for the specified node to the receiver
 */
- (void)addAnimation:(ICAnimation *)animation forNode:(ICNode *)node;

/**
 @brief Removes the given animation for the specified node from the receiver
 */
- (void)removeAnimation:(ICAnimation *)animation forNode:(ICNode *)node;

@end