text:
extern uint64_t start_section_text;
extern uint64_t end_section_text;
extern uint64_t start_section_data;
extern uint64_t end_section_data;
extern uint64_t start_section_rodata;
extern uint64_t end_section_rodata;
extern uint64_t start_section_bss;
extern uint64_t end_section_bss;

void startKernel64_BSPMODE(){
	//breakpoint en entry point de bsp
	//breakpoint();
}

void startKernel64_APMODE(){
	//breakpoint en entry point de ap
	//breakpoint();
	//estan deshabilitadas las interrupciones enmascarables!
	//habilito interrupciones
	//irq_sti();
}

void kernel_panic(const char* functionSender, const uint64_t lineError, const char* fileError, const char* message){
		__asm __volatile("xchg %%bx, %%bx" : :);
//	    console_set_panic_format();
//        console_clear();
//        console_printf("[KERNEL PANIC]: %s\n", message);
//
//        console_printf("\nFuncion que produjo el error:\t%s\n", functionSender);
//
//        console_printf("\nEstado de los registros:");
//        console_printf("\nRAX = %u", getRAX());
//        console_printf("\tRBX = %u", getRBX());
//        console_printf("\nRCX = %u", getRCX());
//        console_printf("\tRDX = %u", getRDX());
//        console_printf("\nRSI = %u", getRSI());
//        console_printf("\tRDI = %u", getRDI());
//        console_printf("\nRBP = %u", getRBP());
//        console_printf("\tRSP = %u", getRSP());
//        console_printf("\nR8 = %u", getR8());
//        console_printf("\tR9 = %u", getR9());
//        console_printf("\nR10 = %u", getR10());
//        console_printf("\tR11 = %u", getR11());
//        console_printf("\nR12 = %u", getR12());
//        console_printf("\tR13 = %u", getR13());
//        console_printf("\nR14 = %u", getR14());
//        console_printf("\tR15 = %u", getR15());
//        console_printf("\nRIP = %u", getRIP());
//        console_printf("\tCS = %u", getCS());
//        console_printf("\nDS = %u", getDS());
//        console_printf("\tES = %u", getES());
//        console_printf("\nFS = %u", getFS());
//        console_printf("\tGS = %u", getGS());
//        console_printf("\nSS = %u", getSS());
//        console_printf("\tCR0 = %u", getCR0());
//        console_printf("\nCR2 = %u", getCR2());
//        console_printf("\tCR3 = %u", getCR3());
//        console_printf("\nCR4 = %u", getCR4());
//        console_printf("\tRFLAGS = %u\n", getRFLAGS());
//
//        //info de como linkea todo en memoria
//        console_printf("section_text:                         [%u..%u)\n", &start_section_text, &end_section_text);
//        console_printf("ap_startup_code_page:         [%u..%u)\n", &ap_startup_code_page, &end_ap_startup_code_page);
//        console_printf("section_data:                         [%u..%u)\n", &start_section_data, &end_section_data);
//        console_printf("section_rodata:                 [%u..%u)\n", &start_section_rodata, &end_section_rodata);
//        console_printf("section_bss:                         [%u..%u)\n", &start_section_bss, &end_section_bss);
//
	    //console_hide_text_cursor();
	    haltCpu();
}


text:
body {
  margin: 0;
  padding: 0;
  font-family: "Open Sans", "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
}

redpajama_set_name: RedPajamaGithub


text:
package TestJavaClient;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.AbstractTableModel;

import com.ib.client.Order;
import com.ib.client.TagValue;

@SuppressWarnings("serial")
public class SmartComboRoutingParamsDlg extends JDialog {
    private Order m_order;

    private JTextField 		m_tag = new JTextField( "");
    private JTextField 		m_value = new JTextField( "");
    private JButton 		m_addParam = new JButton( "Add");
    private JButton	 	    m_removeParam = new JButton( "Remove");
    private JButton 		m_ok = new JButton( "OK");
    private JButton	 	    m_cancel = new JButton( "Cancel");

    private SmartComboRoutingParamModel 	m_paramModel = new SmartComboRoutingParamModel();
    private JTable 		    m_paramTable = new JTable(m_paramModel);
    private JScrollPane 	m_paramPane = new JScrollPane(m_paramTable);

    public SmartComboRoutingParamModel paramModel() { return m_paramModel; }

    public SmartComboRoutingParamsDlg( Order order, JDialog owner) {
        super( owner, true);

        m_order = order;

        setTitle( "Smart Combo Routing Parameters");

        // create smart combo routing params panel
        JPanel pParamList = new JPanel( new GridLayout( 0, 1, 10, 10) );
        pParamList.setBorder( BorderFactory.createTitledBorder( "Smart Combo Routing Parameters") );

        Vector<TagValue> smartComboRoutingParams = m_order.m_smartComboRoutingParams;
        if (smartComboRoutingParams != null) {
        	m_paramModel.smartComboRoutingParams().addAll(smartComboRoutingParams);
        }
        pParamList.add( m_paramPane);

        // create add/remove panel
        JPanel pParamListControl = new JPanel( new GridLayout( 0, 2, 10, 10) );
        pParamListControl.setBorder( BorderFactory.createTitledBorder( "Add / Remove") );
        pParamListControl.add( new JLabel( "Param:") );
        pParamListControl.add( m_tag);
        pParamListControl.add( new JLabel( "Value:") );
        pParamListControl.add( m_value);
        pParamListControl.add( m_addParam);
        pParamListControl.add( m_removeParam);

        // create button panel
        JPanel buttonPanel = new JPanel();
        buttonPanel.add( m_ok);
        buttonPanel.add( m_cancel);

        // create wrapper panel
        JPanel topPanel = new JPanel();
        topPanel.setLayout( new BoxLayout( topPanel, BoxLayout.Y_AXIS) );
        topPanel.add( pParamList);
        topPanel.add( pParamListControl);

        // create dlg box
        getContentPane().add( topPanel, BorderLayout.CENTER);
        getContentPane().add( buttonPanel, BorderLayout.SOUTH);

        // create action listeners
        m_addParam.addActionListener( new ActionListener() {
            public void actionPerformed( ActionEvent e) {
                onAddParam();
            }
        });
        m_removeParam.addActionListener( new ActionListener() {
            public void actionPerformed( ActionEvent e) {
                onRemoveParam();
            }
        });
        m_ok.addActionListener( new ActionListener() {
            public void actionPerformed( ActionEvent e) {
                onOk();
            }
        });
        m_cancel.addActionListener( new ActionListener() {
            public void actionPerformed( ActionEvent e) {
                onCancel();
            }
        });

        setSize(250, 600);
        centerOnOwner( this);
    }

     public void onAddParam() {
        try {
            String tag = m_tag.getText();
            String value = m_value.getText();

            m_paramModel.addParam( new TagValue(tag, value));
        }
        catch( Exception e) {
            reportError( "Error - ", e);
            return;
        }
    }

    public void onRemoveParam() {
        try {
            if ( m_paramTable.getSelectedRowCount() != 0 ) {
                int[] rows = m_paramTable.getSelectedRows();
                for ( int i=rows.length -1; i>=0 ; i-- ) {
                        m_paramModel.removeParam( rows[i]);
                }
            }
        }
        catch( Exception e) {
            reportError( "Error - ", e);
            return;
        }
    }

    void onOk() {
    	Vector<TagValue> smartComboRoutingParams = m_paramModel.smartComboRoutingParams();
    	m_order.m_smartComboRoutingParams = smartComboRoutingParams.isEmpty() ? null : smartComboRoutingParams;

        setVisible( false);
    }

    void onCancel() {
        setVisible( false);
    }

    void reportError( String msg, Exception e) {
        Main.inform( this, msg + " --" + e);
    }

    private static void centerOnOwner( Window window) {
        Window owner = window.getOwner();
        if( owner == null) {
            return;
        }
        int x = owner.getX() + ((owner.getWidth()  - window.getWidth())  / 2);
        int y = owner.getY() + ((owner.getHeight() - window.getHeight()) / 2);
        if( x < 0) x = 0;
        if( y < 0) y = 0;
        window.setLocation( x, y);
    }
}

@SuppressWarnings("serial")
class SmartComboRoutingParamModel extends AbstractTableModel {

    private Vector<TagValue> m_allData = new Vector<TagValue>();

    synchronized public void addParam( TagValue tagValue) {
        m_allData.add( tagValue);
        fireTableDataChanged();
    }

    synchronized public void removeParam( int index) {
        m_allData.remove( index);
        fireTableDataChanged();
    }

    synchronized public void reset() {
        m_allData.removeAllElements();
		fireTableDataChanged();
    }

    synchronized public int getRowCount() {
        return m_allData.size();
    }

    synchronized public int getColumnCount() {
        return 2;
    }

    synchronized public Object getValueAt(int r, int c) {
        TagValue tagValue = m_allData.get(r);

        switch (c) {
            case 0:
                return tagValue.m_tag;
            case 1:
                return tagValue.m_value;
            default:
                return "";
        }

    }

    public boolean isCellEditable(int r, int c) {
        return false;
    }

    public String getColumnName(int c) {
        switch (c) {
            case 0:
                return "Param";
            case 1:
                return "Value";
            default:
                return null;
        }
    }

    public Vector<TagValue> smartComboRoutingParams() {
        return m_allData;
    }
}


text:
/**
 * Module exports.
 */

module.exports = forwarded

/**
 * Get all addresses in the request, using the `X-Forwarded-For` header.
 *
 * @param {Object} req
 * @api public
 */

function forwarded(req) {
  if (!req) {
    throw new TypeError('argument req is required')
  }

  // simple header parsing
  var proxyAddrs = (req.headers['x-forwarded-for'] || '')
    .split(/ *, */)
    .filter(Boolean)
    .reverse()
  var socketAddr = req.connection.remoteAddress
  var addrs = [socketAddr].concat(proxyAddrs)

  // return all addresses
  return addrs
}


text:
/*
 *
 * Language Provider
 *
 * connects the redux state locale to the
 * IntlProvider component and i18n messages
 * loaded from `src/translations`.
 *
 */

import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { IntlProvider } from 'react-intl'

const LanguageProvider = ({ locale, messages, children }) => (
  <IntlProvider
    locale={locale}
    messages={messages[locale]}
  >
    {children}
  </IntlProvider>
)

LanguageProvider.propTypes = {
  children: PropTypes.element.isRequired,
  messages: PropTypes.object.isRequired,
  locale: PropTypes.string.isRequired
}

const mapStateToProps = ({ locale }) => (locale)

export default connect(mapStateToProps)(LanguageProvider)


text:
package com.google.cloud.dataflow.sdk.util;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

import com.google.api.client.util.BackOffUtils;
import com.google.api.client.util.Sleeper;
import com.google.api.services.dataflow.model.DataflowPackage;
import com.google.cloud.dataflow.sdk.util.gcsfs.GcsPath;
import com.google.common.collect.TreeTraverser;
import com.google.common.hash.Funnels;
import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;
import com.google.common.io.ByteStreams;
import com.google.common.io.CountingOutputStream;
import com.google.common.io.Files;

import com.fasterxml.jackson.core.Base64Variants;

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

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.channels.Channels;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/** Helper routines for packages. */
public class PackageUtil {
  private static final Logger LOG = LoggerFactory.getLogger(PackageUtil.class);
  /**
   * The initial interval to use between package staging attempts.
   */
  private static final long INITIAL_BACKOFF_INTERVAL_MS = 5000L;
  /**
   * The maximum number of attempts when staging a file.
   */
  private static final int MAX_ATTEMPTS = 5;

  /**
   * Creates a DataflowPackage containing information about how a classpath element should be
   * staged.
   *
   * @param classpathElement The local path for the classpath element.
   * @param stagingDirectory The base location in GCS for staged classpath elements.
   * @param overridePackageName If non-null, use the given value as the package name
   *                            instead of generating one automatically.
   * @return The package.
   */
  public static DataflowPackage createPackage(String classpathElement,
      GcsPath stagingDirectory, String overridePackageName) {
    try {
      File file = new File(classpathElement);
      String contentHash = computeContentHash(file);

      // Drop the directory prefixes, and form the filename + hash + extension.
      String uniqueName = getUniqueContentName(file, contentHash);

      GcsPath stagingPath = stagingDirectory.resolve(uniqueName);

      DataflowPackage target = new DataflowPackage();
      target.setName(overridePackageName != null ? overridePackageName : uniqueName);
      target.setLocation(stagingPath.toResourceName());
      return target;
    } catch (IOException e) {
      throw new RuntimeException("Package setup failure for " + classpathElement, e);
    }
  }

  /**
   * Transfers the classpath elements to GCS.
   *
   * @param gcsUtil GCS utility.
   * @param classpathElements The elements to stage onto GCS.
   * @param gcsStaging The path on GCS to stage the classpath elements to.
   * @return A list of cloud workflow packages, each representing a classpath element.
   */
  public static List<DataflowPackage> stageClasspathElementsToGcs(
      GcsUtil gcsUtil,
      Collection<String> classpathElements,
      GcsPath gcsStaging) {
    return stageClasspathElementsToGcs(gcsUtil, classpathElements, gcsStaging, Sleeper.DEFAULT);
  }

  // Visible for testing.
  static List<DataflowPackage> stageClasspathElementsToGcs(
      GcsUtil gcsUtil,
      Collection<String> classpathElements,
      GcsPath gcsStaging,
      Sleeper retrySleeper) {
    LOG.info("Uploading {} files from PipelineOptions.filesToStage to GCS to prepare for execution "
        + "in the cloud.", classpathElements.size());
    ArrayList<DataflowPackage> packages = new ArrayList<>();

    if (gcsStaging == null) {
      throw new IllegalArgumentException(
          "Can't stage classpath elements on GCS because no GCS location has been provided");
    }

    int numUploaded = 0;
    int numCached = 0;
    for (String classpathElement : classpathElements) {
      String packageName = null;
      if (classpathElement.contains("=")) {
        String[] components = classpathElement.split("=", 2);
        packageName = components[0];
        classpathElement = components[1];
      }

      DataflowPackage workflowPackage = createPackage(
          classpathElement, gcsStaging, packageName);

      packages.add(workflowPackage);
      GcsPath target = GcsPath.fromResourceName(workflowPackage.getLocation());

      // TODO: Should we attempt to detect the Mime type rather than
      // always using MimeTypes.BINARY?
      try {
        long remoteLength = gcsUtil.fileSize(target);
        if (remoteLength >= 0 && remoteLength == getClasspathElementLength(classpathElement)) {
          LOG.debug("Skipping classpath element already on gcs: {} at {}",
              classpathElement, target);
          numCached++;
          continue;
        }

        // Upload file, retrying on failure.
        AttemptBoundedExponentialBackOff backoff = new AttemptBoundedExponentialBackOff(
            MAX_ATTEMPTS,
            INITIAL_BACKOFF_INTERVAL_MS);
        while (true) {
          try {
            LOG.debug("Uploading classpath element {} to {}", classpathElement, target);
            try (WritableByteChannel writer = gcsUtil.create(target, MimeTypes.BINARY)) {
              copyContent(classpathElement, writer);
            }
            numUploaded++;
            break;
          } catch (IOException e) {
            if (!backoff.atMaxAttempts()) {
              LOG.warn("Upload attempt failed, sleeping before retrying staging of classpath: {}",
                  classpathElement, e);
              BackOffUtils.next(retrySleeper, backoff);
            } else {
              // Rethrow last error, to be included as a cause in the catch below.
              LOG.error("Upload failed, will NOT retry staging of classpath: {}",
                  classpathElement, e);
              throw e;
            }
          }
        }
      } catch (Exception e) {
        throw new RuntimeException("Could not stage classpath element: " + classpathElement, e);
      }
    }

    LOG.info("Uploading PipelineOptions.filesToStage complete: {} files newly uploaded, "
        + "{} files cached",
        numUploaded, numCached);

    return packages;
  }

  /**
   * If classpathElement is a file, then the files length is returned, otherwise the length
   * of the copied stream is returned.
   *
   * @param classpathElement The local path for the classpath element.
   * @return The length of the classpathElement.
   */
  private static long getClasspathElementLength(String classpathElement) throws IOException {
    File file = new File(classpathElement);
    if (file.isFile()) {
      return file.length();
    }

    CountingOutputStream countingOutputStream =
        new CountingOutputStream(ByteStreams.nullOutputStream());
    try (WritableByteChannel channel = Channels.newChannel(countingOutputStream)) {
      copyContent(classpathElement, channel);
    }
    return countingOutputStream.getCount();
  }

  /**
   * Returns a unique name for a file with a given content hash.
   *

   * Directory paths are removed. Example:
   *

   * dir="a/b/c/d", contentHash="f000" => d-f000.zip
   * file="a/b/c/d.txt", contentHash="f000" => d-f000.txt
   * file="a/b/c/d", contentHash="f000" => d-f000
   *

   */
  static String getUniqueContentName(File classpathElement, String contentHash) {
    String fileName = Files.getNameWithoutExtension(classpathElement.getAbsolutePath());
    String fileExtension = Files.getFileExtension(classpathElement.getAbsolutePath());
    if (classpathElement.isDirectory()) {
      return fileName + "-" + contentHash + ".zip";
    } else if (fileExtension.isEmpty()) {
      return fileName + "-" + contentHash;
    }
    return fileName + "-" + contentHash + "." + fileExtension;
  }

  /**
   * Computes a message digest of the file/directory contents, returning a base64 string that is
   * suitable for use in URLs.
   */
  private static String computeContentHash(File classpathElement) throws IOException {
    TreeTraverser<File> files = Files.fileTreeTraverser();
    Hasher hasher = Hashing.md5().newHasher();
    for (File currentFile : files.preOrderTraversal(classpathElement)) {
      String relativePath = relativize(currentFile, classpathElement);
      hasher.putString(relativePath, StandardCharsets.UTF_8);
      if (currentFile.isDirectory()) {
        hasher.putLong(-1L);
        continue;
      }
      hasher.putLong(currentFile.length());
      Files.asByteSource(currentFile).copyTo(Funnels.asOutputStream(hasher));
    }
    return Base64Variants.MODIFIED_FOR_URL.encode(hasher.hash().asBytes());
  }

  /**
   * Copies the contents of the classpathElement to the output channel.
   *

   * If the classpathElement is a directory, a Zip stream is constructed on the fly,
   * otherwise the file contents are copied as-is.
   *

   * The output channel is not closed.
   */
  private static void copyContent(String classpathElement, WritableByteChannel outputChannel)
      throws IOException {
    final File classpathElementFile = new File(classpathElement);
    if (classpathElementFile.isDirectory()) {
      zipDirectory(classpathElementFile, Channels.newOutputStream(outputChannel));
    } else {
      Files.asByteSource(classpathElementFile).copyTo(Channels.newOutputStream(outputChannel));
    }
  }

  /**
   * Zips an entire directory specified by the path.
   *
   * @param sourceDirectory the directory to read from. This directory and all
   *     subdirectories will be added to the zip-file. The path within the zip
   *     file is relative to the directory given as parameter, not absolute.
   * @param outputStream the stream to write the zip-file to. This method does not close
   *     outputStream.
   * @throws IOException the zipping failed, e.g. because the input was not
   *     readable.
   */
  private static void zipDirectory(
      File sourceDirectory,
      OutputStream outputStream) throws IOException {
    checkNotNull(sourceDirectory);
    checkNotNull(outputStream);
    checkArgument(
        sourceDirectory.isDirectory(),
        "%s is not a valid directory",
        sourceDirectory.getAbsolutePath());
    ZipOutputStream zos = new ZipOutputStream(outputStream);
    for (File file : sourceDirectory.listFiles()) {
      zipDirectoryInternal(file, "", zos);
    }
    zos.finish();
  }

  /**
   * Private helper function for zipping files. This one goes recursively
   * through the input directory and all of its subdirectories and adds the
   * single zip entries.
   *
   * @param inputFile the file or directory to be added to the zip file
   * @param directoryName the string-representation of the parent directory
   *     name. Might be an empty name, or a name containing multiple directory
   *     names separated by "/". The directory name must be a valid name
   *     according to the file system limitations.
   * @param zos the zipstream to write to
   * @throws IOException the zipping failed, e.g. because the output was not
   *     writeable.
   */
  private static void zipDirectoryInternal(
      File inputFile,
      String directoryName,
      ZipOutputStream zos) throws IOException {
    final String entryName;
    if ("".equals(directoryName)) {
      // no parent directories yet.
      entryName = inputFile.getName();
    } else {
      entryName = directoryName + "/" + inputFile.getName();
    }
    if (inputFile.isDirectory()) {
      // We are hitting a sub-directory. Start the recursion.
      // Add the empty entry for a subdirectory if we have no children files.
      // Don't add it if we have them, as this is incompatible with certain
      // implementations of unzip.
      if (inputFile.list().length == 0) {
        ZipEntry entry = new ZipEntry(entryName + "/");
        zos.putNextEntry(entry);
      } else {
        // loop through the directory content, and zip the files
        for (File file : inputFile.listFiles()) {
          zipDirectoryInternal(file, entryName, zos);
        }
      }
    } else {
      // Put the next zip-entry into the zipoutputstream.
      ZipEntry entry = new ZipEntry(entryName);
      zos.putNextEntry(entry);
      Files.asByteSource(inputFile).copyTo(zos);
    }
  }

  /**
   * Constructs a relative path between file and root.
   *

   * This function will attempt to use {@link java.nio.file.Path#relativize} and
   * will fallback to using {@link java.net.URI#relativize} in AppEngine.
   *
   * @param file The file for which the relative path is being constructed for.
   * @param root The root from which the relative path should be constructed.
   * @return The relative path between the file and root.
   */
  private static String relativize(File file, File root) {
    if (AppEngineEnvironment.IS_APP_ENGINE) {
      // AppEngine doesn't allow for java.nio.file.Path to be used so we rely on
      // using URIs, but URIs are broken for UNC paths, which AppEngine doesn't
      // use. See for more details: http://wiki.eclipse.org/Eclipse/UNC_Paths
      return root.toURI().relativize(file.toURI()).getPath();
    }
    return root.toPath().relativize(file.toPath()).toString();
  }
}


text:
<?php

namespace HotelBundle\ReservaBundle\Controller;

  use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  use Symfony\Component\HttpFoundation\Request;
  use HotelBundle\Entity\Reserva;
  use HotelBundle\Entity\Comanda;
  use HotelBundle\Entity\Client;
  use HotelBundle\Entity\User;
  use Symfony\Component\Form\Extension\Core\Type\TextType;
  use Symfony\Component\Form\Extension\Core\Type\SubmitType;
  use Symfony\Component\Form\Extension\Core\Type\DateType;
  use Symfony\Bridge\Doctrine\Form\Type\EntityType;

  class ComandaController extends Controller{

   public function indexAction(Request $request){
    $session = $request->getSession();

    $modalitat = 0;
    $habitacions = 0;
    $total = 0;

    $em = $this->getDoctrine()->getManager();

    if($session->has('arrayReserva')){

      $lineasComanda =$session->get('arrayReserva');
      $comanda = $session->get('comanda');
      $com = $em->getRepository('HotelBundle:Comanda');
      $preu = $com->calcularPreu($request,$comanda);
      $modalitat = $preu[0];
      $habitacions = $preu[1];
      $total = $preu[2];
    }else{
      $lineasComanda = array();
    }

    $clientRepository = $em->getRepository('HotelBundle:Client');
    $client = $clientRepository->retornaClient($this->container);

    return $this->render('HotelBundleReservaBundle:Default:veureComanda.html.twig', array(
      'arrayLinea' => $lineasComanda,
      'client' => $client,
      'totalModalitat' => $modalitat,
      'totalHabitacio' => $habitacions,
      'total' => $total
      ));

  }

  public function indexReservasAction(Request $request){
    $em = $this->getDoctrine()->getManager();
    $clientRepository = $em->getRepository('HotelBundle:Client');
    $client = $clientRepository->retornaClient($this->container);
    if ($client != null){
      $comandes = $this->getDoctrine()->getRepository('HotelBundle:Comanda')->findBy(array('client' => $client->getId()));

      return $this->render('HotelBundleReservaBundle:Default:veureComandes.html.twig', array(
        'arrayComanda' => $comandes
        ));
    }else{
      $comandes = array();
        $this->get('session')->getFlashBag()->add(
          'notice',array(
            'type' => 'warning',
            'msg' => 'Encara no tens cap reserva al teu nom!'
            ));
      return $this->render('HotelBundleReservaBundle:Default:veureComandes.html.twig', array(
        'arrayComanda' => $comandes
        ));
    }
  }

  public function veureReservaAction($id,Request $request){
    $session = $request->getSession();
    $em = $this->getDoctrine()->getManager();
    $clientRepository = $em->getRepository('HotelBundle:Client');
    $client = $clientRepository->retornaClient($this->container);
    $comanda = $this->getDoctrine()->getRepository('HotelBundle:Comanda')->findOneById($id);
    $reservas = $this->getDoctrine()->getRepository('HotelBundle:Reserva')->findBy(array('comanda' => $comanda->getId()));

    $com = $em->getRepository('HotelBundle:Comanda');
    $preu = $com->calcularPreu($request,$comanda);
    $modalitat = $preu[0];
    $habitacions = $preu[1];
    $total = $preu[2];

    return $this->render('HotelBundleReservaBundle:Default:veureReserva.html.twig', array(
      'comanda' => $comanda,
      'arrayReserva' => $reservas,
      'client' => $client,
      'totalModalitat' => $modalitat,
      'totalHabitacio' => $habitacions,
      'total' => $total
      ));

  }

  public function retornaUser(){
    return  $this->container->get('security.token_storage')->getToken()->getUser();
  }

    //creacio de reservas
  public function afegirLiniaAction(Request $request){
    $usuari =  $this->retornaUser();
    if($usuari == "anon."){
      return $this->redirect($this->generateurl('fos_user_security_login'));
    }else{
      $id =  $request->get('id');
      $modalitat =  $request->get('modalitat');
      $habitacio = $this->getDoctrine()->getRepository('HotelBundle:Habitacio')->findOneById($id);
      $modalitat = $this->getDoctrine()->getRepository('HotelBundle:Modalitat')->findOneById($modalitat);

      $session = $request->getSession();

    //CCCCCCCCCCCCCCCCCCCCCCCCCCCCC
    //TO-DO session comanda provisional.
      if(!$session->has('comanda')){
        $comanda = new Comanda();

        $dataInici =  new \DateTime($request->get('dataInici'));
        $dataFi =  new \DateTime($request->get('dataFi'));

        $comanda->setDataEntrada($dataInici);
        $comanda->setDataSortida($dataFi);

        $session->set('comanda',$comanda);
      }

      if($session->has('arrayReserva')){
        $arrayReserva = $session->get('arrayReserva');

      }else{
        $arrayReserva = array();
      }

      $valid = true;
      foreach ($arrayReserva as $reserva) {
        if($reserva->getHabitacio()->getId() == $id){
          $valid = false;
        }
      }

      if($valid){
        $reserva = new Reserva();
        $reserva->setHabitacio($habitacio);
        $reserva->setModalitat($modalitat);
        array_push($arrayReserva,$reserva);

        $arrayReserva = $session->set('arrayReserva', $arrayReserva);

        $this->get('session')->getFlashBag()->add(
          'notice',array(
            'type' => 'success',
            'msg' => 'S\'ha afegit l\'habitació'
            ));

        return $this->redirect($this->generateurl('hotel_bundle_reserva_comanda'));
      }else{
        $this->get('session')->getFlashBag()->add(
          'notice',array(
            'type' => 'warning',
            'msg' => 'Aquesta habitació ja la tenias reservada!'
            ));
        return $this->redirect($this->generateurl('hotel_bundle_reserva_llistaHabitacionsFrontend'));
      }
    }
  }

  public function eliminarLiniaAction($id, Request $request){

    $session = $request->getSession();

    if($session->has('arrayReserva')){
      $arrayReserva = $session->get('arrayReserva');
      foreach ($arrayReserva as $key => $reserva) {
        if ($reserva->getHabitacio()->getId() == $id){
          unset($arrayReserva[$key]);
        }
      }

    }else{
      $arrayReserva = array();
    }

    $arrayReserva = $session->set('arrayReserva', $arrayReserva);

    $this->get('session')->getFlashBag()->add(
      'notice',array(
        'type' => 'success',
        'msg' => 'S\'ha eliminat l\'habitació'
        ));

    return $this->redirect($this->generateurl('hotel_bundle_reserva_comanda'));

  }

  public function completarReservaAction(Request $request){
    $session = $request->getSession();
    $em = $this->getDoctrine()->getManager();
    $clientRepository = $em->getRepository('HotelBundle:Client');
    $client = $clientRepository->retornaClient($this->container);
    if ( $client == null ||$client->getNom()== null){
      return $this->redirect($this->generateurl('hotel_bundle_reserva_completarCliente'));
    }else{
      //completar reserva

      if($session->has('comanda')){
        $comanda = $session->get('comanda');
        $comanda->setClient($client);
        $dataInici = $comanda->getDataEntrada();
        $dataFi = $comanda->getDataSortida();

        $arrayReserva= $session->get('arrayReserva');

        //semafor
        $valid = true;
        $arrayFinal= array();
        foreach ($arrayReserva as $key => $reserva) {
          $reservaRepository = $em->getRepository('HotelBundle:Reserva');
          $habitacio = $this->getDoctrine()->getRepository('HotelBundle:Habitacio')->findOneById($reserva->getHabitacio()->getId());
          if (!$reservaRepository->comprovarHabitacioByDate($dataInici,$dataFi,$habitacio) )$valid = false;
            if($valid){
              array_push($arrayFinal, $reserva);
            }
            $valid = true;
          }

          if(count($arrayReserva) == count($arrayFinal)){
            $em->persist($comanda);
            foreach ($arrayFinal as $reserva) {
              $res = new Reserva();
              $habitacio = $this->getDoctrine()->getRepository('HotelBundle:Habitacio')->findOneById($reserva->getHabitacio()->getId());
              if (!is_null($reserva->getModalitat())){
                $modalitat = $this->getDoctrine()->getRepository('HotelBundle:Modalitat')->findOneById($reserva->getModalitat()->getId());
                $res->setModalitat($modalitat);
              }
              $res->setHabitacio($habitacio);
              $res->setComanda($comanda);
              $em->persist($res);
            }

            $em->flush();
            $session->remove('comanda');
            $session->remove('arrayReserva');

            $this->get('session')->getFlashBag()->add(
              'notice',array(
                'type' => 'success',
                'msg' => 'S\'ha completat la reserva!'
                ));
            return $this->redirect($this->generateurl('hotel_bundle_reserva_homepage_reservas'));

          }else{
            $this->get('session')->getFlashBag()->add(
              'notice',array(
                'type' => 'danger',
                'msg' => 'S\'han eliminat habitacions que ja estan reservades. Has tardat massa! Torna a intentar-ho!'
                ));
          }
          return $this->redirect($this->generateurl('hotel_bundle_reserva_homepage'));
        }else{
      //TO-DO crear/buscar comanda
         return $this->redirect($this->generateurl('hotel_bundle_reserva_homepage'));
       }
     }

   }

   public function fichaClienteAction(Request $request){
    $em = $this->getDoctrine()->getManager();
    $clientRepository = $em->getRepository('HotelBundle:Client');
    $client = $clientRepository->retornaClient($this->container);

    if ($client == null){
      $this->get('session')->getFlashBag()->add(
        'notice',array(
          'type' => 'info',
          'msg' => 'Necesitamos tus datos de cliente!'
          ));
      $client = new Client();
    }

    $form = $this->createFormBuilder($client)
    ->add('nom', TextType::class, array('label' => 'Nom','attr' => array(
      'class' => 'form-control'),
    'label_attr'=> array('class' => 'label_text spaceTop')))
    ->add('cognoms', TextType::class, array('label' => 'Cognoms','attr' => array(
      'class' => 'form-control'),
    'label_attr'=> array('class' => 'label_text spaceTop')))
    ->add('dataNaixament', DateType::class, array('label' => 'Data de Naixament',
      'widget' => 'single_text',
      'html5' => false,
      'format' => 'dd/MM/yyyy',
      'attr' => ['class' => 'js-datepicker form-control'],
      'label_attr'=> array('class' => 'label_text spaceTop')))
    ->add('nif', TextType::class, array('label' => 'NIF','attr' => array(
      'class' => 'form-control'),
    'label_attr'=> array('class' => 'label_text spaceTop')))
    ->add('save', SubmitType::class, array('label' => 'Guardar ficha de client' ,'attr' => array(
      'class' => 'btn btn-warning mt')))
    ->getForm();

    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
      $session = $request->getSession();

      $user = $this->retornaUser();

      if ($user != "anon." || $user != null){
        $client->setUser($user);
        $session->set('client',$client);

        $em = $this->getDoctrine()->getManager();
        $em->persist($client);
        $em->flush();
      }
      $this->get('session')->getFlashBag()->add(
        'notice',array(
          'type' => 'success',
          'msg' => 'S\'ha guardat l\'usuari'
          ));

      return $this->redirect($this->generateurl('hotel_bundle_reserva_acabarReserva'));

    };

    return $this->render('HotelBundleReservaBundle:Default:addObject.html.twig', array(
      'titol' => 'Dades de Client',
      'form' => $form->createView()
      ));
  }

    //edicio de reservas XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

  public function veureLlistaReservasAction(Request $request)
  {
   $comandes = $this->getDoctrine()->getRepository('HotelBundle:Comanda')->findAll();

   return $this->render('HotelBundleReservaBundle:Default:buscarComanda.html.twig', array(
    'titol' => 'Buscar comanda',
    'comandes' => $comandes
    ));

 }

 public function redirectBuscarReserva($codiComanda){

  $comanda = $this->getDoctrine()->getRepository('HotelBundle:Comanda')->findOneById($codiComanda);
  $client = $this->getDoctrine()->getRepository('HotelBundle:Client')->findOneById($comanda->getClient()->getId());
  $lineasComanda = $this->getDoctrine()->getRepository('HotelBundle:Reserva')->findBy(array('comanda' => $comanda->getId()));

  return $this->render('HotelBundleReservaBundle:Default:editarComanda.html.twig', array(
    'arrayLinea' => $lineasComanda , 'comanda' => $comanda, 'client' => $client
    ));
}

public function buscarReservaAction($id,Request $request){
  return $this->redirectBuscarReserva($id);
}

public function editarClientAction($idComanda, $id, Request $request){
  {
    $client = $this->getDoctrine()->getRepository('HotelBundle:Client')->findOneById($id);

    $form = $this->createFormBuilder($client)
    ->add('nom', TextType::class, array('label' => 'Nom','attr' => array(
      'class' => 'form-control'),
    'label_attr'=> array('class' => 'label_text spaceTop')))
    ->add('cognoms', TextType::class, array('label' => 'Cognoms','attr' => array(
      'class' => 'form-control'),
    'label_attr'=> array('class' => 'label_text spaceTop')))
    ->add('dataNaixament', DateType::class, array('label' => 'Data Naixement',
      'widget' => 'single_text',
      'html5' => false,
      'format' => 'dd/mm/yyyy',
      'attr' => ['class' => 'js-datepicker']))
    ->add('nif', TextType::class, array('label' => 'NIF','attr' => array(
      'class' => 'form-control'),
    'label_attr'=> array('class' => 'label_text spaceTop')))
    ->add('user', EntityType::class, array(
      'class' => 'HotelBundle:User',
      'label' => 'Usuari',
      'choice_label' => 'username',
      'multiple' => FALSE,
      'label_attr'=> array('class' => 'label_text spaceTop'),
      'attr' => array('class' => 'form-control selectRol')))
    ->add('save', SubmitType::class, array('label' => 'Editar Client',
      'attr' => array(
        'class' => 'btn btn-warning mt')))
    ->getForm();

    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
      $em = $this->getDoctrine()->getManager();
      $em->persist($client);
      $em->flush();

      $this->get('session')->getFlashBag()->add(
        'notice',array(
          'type' => 'success',
          'msg' => 'S\'ha editat el Client Correctament'
          ));
      return $this->redirectBuscarReserva($idComanda);
    };

    return $this->render('HotelBundleAdminBundle:Default:addObject.html.twig', array(
      'titol' => 'Editar Client',
      'form' => $form->createView()
      ));
  }
}

public function donarBaixaComandaAction($id,Request $request){
  $em = $this->getDoctrine()->getManager();
  $comanda = $this->getDoctrine()->getRepository('HotelBundle:Comanda')->findOneById($id);

  $com = $em->getRepository('HotelBundle:Comanda');
  $total = $com->calcularPreu($request,$comanda);

  $lineasComanda = $this->getDoctrine()->getRepository('HotelBundle:Reserva')->findBy(array('comanda' => $comanda->getId()));
  $em = $this->getDoctrine()->getManager();
  foreach ($lineasComanda as $reserva) {
    $em->remove($reserva);
  }
  $em->remove($comanda);
  $em->flush();

  $msg = "Reserva cancelada, es tornaran un total de: ".$total[2]."€ al client";
  $this->get('session')->getFlashBag()->add(
    'notice',array(
      'type' => 'success',
      'msg' => $msg
      ));
  return $this->redirect($this->generateurl('hotel_bundle_treballador_reserva_veureLlistaReservas'));
}

public function eliminarLineaAdminAction($idComanda,$id,Request $request)
{

  $lineaComanda = $this->getDoctrine()->getRepository('HotelBundle:Reserva')->findOneById($id);
  $reservas = $this->getDoctrine()->getRepository('HotelBundle:Reserva')->findBy(array('comanda' => $idComanda));

  if(count($reservas) == 1){
    return $this->donarBaixaComandaAction($idComanda, $request);
  } else{
    $comanda = $this->getDoctrine()->getRepository('HotelBundle:Comanda')->findOneById($idComanda);
    $em = $this->getDoctrine()->getManager();
    $com = $em->getRepository('HotelBundle:Comanda');
    $total = $com->calcularPreuLinea($request,$comanda,$id);

    $em = $this->getDoctrine()->getManager();
    $em->remove($lineaComanda);
    $em->flush();

    $msg = "Es tornaran un total de: ".$total."€ al client";
    $this->get('session')->getFlashBag()->add(
      'notice',array(
        'type' => 'success',
        'msg' => $msg
        ));
    return $this->redirectBuscarReserva($idComanda);

  }
}
}


text:
package gov.sandia.cognition.evaluator;

import gov.sandia.cognition.math.matrix.Vector;
import gov.sandia.cognition.math.matrix.mtj.Vector3;
import gov.sandia.cognition.util.ObjectUtil;
import junit.framework.TestCase;
import java.util.Random;

/**
 * Unit tests for AbstractStatefulEvaluatorTest.
 *
 * @author krdixon
 */
public class AbstractStatefulEvaluatorTest
    extends TestCase
{

    /**
     * Random number generator to use for a fixed random seed.
     */
    public final Random RANDOM = new Random( 1 );

    /**
     * Default tolerance of the regression tests, {@value}.
     */
    public final double TOLERANCE = 1e-5;

    /**
     * Tests for class AbstractStatefulEvaluatorTest.
     * @param testName Name of the test.
     */
    public AbstractStatefulEvaluatorTest(
        String testName)
    {
        super(testName);
    }

    public static class StatefulFunction
        extends AbstractStatefulEvaluator<Vector,Vector,Vector>
    {

        public StatefulFunction()
        {
            super();
        }

        public StatefulFunction(
            Vector state )
        {
            super( state );
        }

        public Vector createDefaultState()
        {
            return new Vector3(1.0,2.0,3.0);
        }

        public Vector evaluate(
            Vector input)
        {
            this.getState().plusEquals(input);
            return this.getState();
        }

    }

    public Vector createRandomInput()
    {
        return Vector3.createRandom(RANDOM);
    }

    public StatefulFunction createInstance()
    {
        return new StatefulFunction(this.createRandomInput());
    }

    /**
     * Tests the constructors of class AbstractStatefulEvaluatorTest.
     */
    public void testConstructors()
    {
        System.out.println( "Constructors" );

        StatefulFunction f = new StatefulFunction();
        assertEquals( f.createDefaultState(), f.getState() );

        Vector x = this.createRandomInput();
        f = new StatefulFunction( x );
        assertSame( x, f.getState() );

    }

    /**
     * Test of clone method, of class AbstractStatefulEvaluator.
     */
    public void testClone()
    {
        System.out.println("clone");

        StatefulFunction f = this.createInstance();
        StatefulFunction clone = (StatefulFunction) f.clone();
        System.out.println( "f:\n" + ObjectUtil.toString(f) );
        System.out.println( "clone:\n" + ObjectUtil.toString(clone) );
        assertNotNull( clone );
        assertNotSame( f, clone );
        assertNotNull( clone.getState() );
        assertNotSame( f.getState(), clone.getState() );
        assertEquals( f.getState(), clone.getState() );
        assertFalse( clone.getState().equals( clone.createDefaultState() ) );

        Vector originalState = f.getState().clone();
        assertEquals( originalState, f.getState() );
        assertEquals( originalState, clone.getState() );
        clone.getState().scaleEquals(RANDOM.nextDouble());
        assertEquals( originalState, f.getState() );
        assertFalse( originalState.equals( clone.getState() ) );

    }

    /**
     * evaluate(state)
     */
    public void testEvaluateState()
    {
        System.out.println( "evaluate(State)" );

        StatefulFunction f = this.createInstance();
        Vector defaultState = f.createDefaultState();
        f.resetState();
        Vector input = this.createRandomInput();
        Vector o1 = f.evaluate(input);
        Vector o2 = f.evaluate(input, defaultState );
        assertNotSame( o1, o2 );
        assertEquals( o1, o2 );

    }

    /**
     * Test of evaluate method, of class AbstractStatefulEvaluator.
     */
    public void testEvaluate()
    {
        System.out.println("evaluate");
        StatefulFunction f = this.createInstance();
        Vector originalState = f.getState().clone();
        f.evaluate(this.createRandomInput());
        assertFalse( originalState.equals( f.getState() ) );

    }

    /**
     * Test of getState method, of class AbstractStatefulEvaluator.
     */
    public void testGetState()
    {
        System.out.println("getState");
        StatefulFunction f = this.createInstance();
        assertNotNull( f.getState() );

    }

    /**
     * Test of setState method, of class AbstractStatefulEvaluator.
     */
    public void testSetState()
    {
        System.out.println("setState");
        StatefulFunction f = this.createInstance();
        Vector s = this.createRandomInput();
        f.setState(s);
        assertSame( s, f.getState() );

    }

    /**
     * Test of resetState method, of class AbstractStatefulEvaluator.
     */
    public void testResetState()
    {
        System.out.println("resetState");
        StatefulFunction f = this.createInstance();
        Vector v = f.createDefaultState();
        assertFalse( v.equals( f.getState() ) );
        f.resetState();
        assertEquals( v, f.getState() );

    }

}


text:
CABAL_OPTS = --hyperlink-source

build:
	cabal build

int-docs:
	cabal haddock \
	  $(CABAL_OPTS) \
	  --internal

haddock:
	cabal haddock \
	  $(CABAL_OPTS)

configure:
	cabal clean
	cabal configure --enable-tests --enable-library-coverage

test:
	cabal build
	cabal test

dist:
	cabal sdist

lint:
	@rm -f report.html
	hlint \
	  --cpp-define='MIN_VERSION_QuickCheck(a,b,c)=1' \
	  --cpp-define='MIN_VERSION_base(a,b,c)=1' \
	  --report -c Data tests

clean:
	cabal clean
	rm -rf dist
	rm -f report.html

.PHONY: build int-docs haddock configure test dist lint clean


text:
using namespace boost;
using namespace boost::python;
using namespace IECore;

namespace IECorePython
{

void bindDisplayDriverServer()
{
	using boost::python::arg;

	RunTimeTypedClass<DisplayDriverServer>()
		.def( init< int >( ( arg( "portNumber" ) = 0 ) ) )
		.def( "portNumber", &DisplayDriverServer::portNumber )
	;

}

} // namespace IECorePython


text:
package dk.brics.tajs.optimizer.dataflow;

import dk.brics.tajs.flowgraph.nodes.WriteVariableNode;
import dk.brics.tajs.util.Collections;

import java.util.Iterator;
import java.util.Set;

/**
 * Abstract state representing which variables have DEFINITELY been written at a particular program point.
 */
public class WriteVariableState implements DataflowState, Cloneable {

    private Set<WriteVariableNode> writeVariables = Collections.newSet();

    /**
     * Construct a new empty state.
     */
    public WriteVariableState() {

    }

    /**
     * Construct a new state with the given set of write variables.
     */
    public WriteVariableState(Set<WriteVariableNode> writeVariables) {
        this.writeVariables = Collections.newSet(writeVariables);
    }

    /**
     * Add a node to the set of write variables.
     */
    public void add(WriteVariableNode node) {
        writeVariables.add(node);
    }

    /**
     * Remove all write variable nodes with the given name.
     */
    public void remove(String varName) {
        Iterator<WriteVariableNode> iterator = writeVariables.iterator();
        while (iterator.hasNext()) {
            WriteVariableNode node = iterator.next();
            if (node.getVarName().equals(varName)) {
                iterator.remove();
            }
        }
    }

    /**
     * Returns a write variable node with the given name or null if none exists.
     */
    public WriteVariableNode get(String varName) {
        Set<WriteVariableNode> candidates = Collections.newSet();
        for (WriteVariableNode candidate : writeVariables) {
            if (candidate.getVarName().equals(varName)) {
                candidates.add(candidate);
            }
        }
        if (candidates.size() == 1) {
            return candidates.iterator().next();
        }
        return null;
    }

    public static WriteVariableState intersection(Set<WriteVariableState> states) {
        Set<WriteVariableNode> result = null;
        for (WriteVariableState state : states) {
            if (state == null) {
                return new WriteVariableState();
            } else if (result == null) {
                result = Collections.newSet(state.writeVariables);
            } else {
                result.retainAll(state.writeVariables);
            }
        }
        if (result == null) {
            return new WriteVariableState();
        }
        return new WriteVariableState(result);
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        Iterator<WriteVariableNode> iterator = writeVariables.iterator();
        while (iterator.hasNext()) {
            WriteVariableNode node = iterator.next();
            sb.append(node.getVarName());
            sb.append(" (");
            sb.append(node.getValueVar());
            sb.append(")");
            if (iterator.hasNext()) {
                sb.append(", ");
            }
        }
        return sb.toString();
    }

    @Override
    public WriteVariableState clone() {
        return new WriteVariableState(Collections.<WriteVariableNode>newSet(writeVariables));
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        WriteVariableState that = (WriteVariableState) o;

        if (writeVariables != null ? !writeVariables.equals(that.writeVariables) : that.writeVariables != null)
            return false;

        return true;
    }

    @Override
    public int hashCode() {
        return writeVariables != null ? writeVariables.hashCode() : 0;
    }

}


text:
package com.tricker.moneycalc2;

import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.LocationSource;
import com.tricker.moneycalc2.db.BaseDao;
import com.tricker.moneycalc2.db.TrickerDB;
import com.tricker.moneycalc2.model.Marry;
import com.tricker.moneycalc2.model.Project;
import com.tricker.moneycalc2.model.Sale;
import com.tricker.moneycalc2.util.Constant;
import com.tricker.moneycalc2.util.TrickerUtils;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Fragment;
//import android.support.v4.app.Fragment;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;

import static android.R.attr.format;
import static android.R.attr.fragment;
import static android.R.id.edit;
import static com.tricker.moneycalc2.R.id.editMoney1;
import static com.tricker.moneycalc2.R.id.editMoney2;
import static com.tricker.moneycalc2.R.id.editName;
import static com.tricker.moneycalc2.R.id.editRemark1;
import static com.tricker.moneycalc2.R.id.editState1;
import static com.tricker.moneycalc2.R.id.marry;
import static com.tricker.moneycalc2.R.string.date;

public class RecordFragment extends Fragment implements OnClickListener, LocationSource, AMapLocationListener, AdapterView.OnItemSelectedListener {
	private int type= -1;
	private TableLayout tableLayoutRent,tableLayoutMarry,tableSale;
	private EditText editDate, editMoney, editProject, editRemark,editName,editMoney1,editMoney2,editRemark1;
	private EditText editSaleDate,editSaleWeek,editSaleMoney,editSaleRemark;
	private Spinner editPercent, editState,editType,editState1,editSaleType;
	// private SimpleDateFormat format;
	private Button btnSave;
	private TextView txtLocation;
	private static boolean isEdit;
	private LocationManager locationManager;
	private String provider;
	private static final int SHOW_RESPONSE = 0;
	/**
	 * The fragment argument representing the section number for this fragment.
	 */
	private static final String ARG_SECTION_NUMBER = "section_number";

	// 声明mLocationOption对象
	public AMapLocationClientOption mLocationOption = null;

	/**
	 * 定位监听
	 */

	private OnLocationChangedListener mListener;
	private AMapLocationClient mlocationClient;
	public void setType(int type) {
		this.type = type;
	}

	/**
	 * Returns a new instance of this fragment for the given section number.
	 */
	public static RecordFragment newInstance(int sectionNumber, Cursor cursor,int type) {
		RecordFragment fragment = new RecordFragment();
		Bundle args = new Bundle();
		args.putInt(ARG_SECTION_NUMBER, sectionNumber);
		if (cursor != null) {// 说明是从查询界面点击回来的,需要修改
			isEdit = true;
			args.putInt("types", type);// type
			if(type==Constant.RENT){
				args.putInt("_id", cursor.getInt(cursor.getColumnIndex("_id")));// _id
				args.putString("project", cursor.getString(cursor.getColumnIndex("project")));// project
				args.putString("money", cursor.getString(cursor.getColumnIndex("money")));// money
				args.putString("date", cursor.getString(cursor.getColumnIndex("date")));// date
				args.putString("percent", cursor.getString(cursor.getColumnIndex("percent")));// percent
				args.putString("remark", cursor.getString(cursor.getColumnIndex("remark")));// remark
				args.putString("state", cursor.getString(cursor.getColumnIndex("state")));// state
			}else if(type==Constant.MARRY){
				args.putInt("_id", cursor.getInt(cursor.getColumnIndex("_id")));// _id
				args.putString("name", cursor.getString(cursor.getColumnIndex("name")));// project
				args.putString("payMoney", cursor.getString(cursor.getColumnIndex("payMoney")));// money
				args.putString("getMoney", cursor.getString(cursor.getColumnIndex("getMoney")));// date
				args.putString("remark", cursor.getString(cursor.getColumnIndex("remark")));// remark
				args.putString("state", cursor.getString(cursor.getColumnIndex("state")));// state
			}else if(type==Constant.SALE){
				args.putInt("_id", cursor.getInt(cursor.getColumnIndex("_id")));// _id
				args.putString("date", cursor.getString(cursor.getColumnIndex("date")));// project
				args.putString("week", cursor.getString(cursor.getColumnIndex("week")));// money
				args.putString("money", cursor.getString(cursor.getColumnIndex("money")));// date
				args.putString("remark", cursor.getString(cursor.getColumnIndex("remark")));// remark
				args.putString("type", cursor.getString(cursor.getColumnIndex("type")));// state
			}
		} else {
			isEdit = false;
		}
		fragment.setArguments(args);
		return fragment;
	}

	public RecordFragment() {
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_record, container, false);
		findViews(rootView);
		if (isEdit) {// 编辑
			setValues();
		}
		//利用安卓API加google地图定位,并不是非常准确,用高德地图代替
		/*locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
		List<String> providers = locationManager.getProviders(true);
		if (providers.contains(LocationManager.GPS_PROVIDER)) {
			provider = LocationManager.GPS_PROVIDER;
		} else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
			provider = LocationManager.NETWORK_PROVIDER;
		}else if(providers.contains(LocationManager.PASSIVE_PROVIDER)){
			provider = LocationManager.PASSIVE_PROVIDER;
		}
		else {
			TrickerUtils.showToast(getActivity(), "尚未开启任何定位服务!");
			provider=null;
		}
		if (provider != null) {
//			locationManager.setTestProviderEnabled("gps",true);
			Location location = locationManager.getLastKnownLocation(provider);
			if (location != null) {
				showLocation(location);
			}else{
				TrickerUtils.showToast(getActivity(), provider+"暂未获取到位置信息");
			}
			locationManager.requestLocationUpdates(provider, 5000, 1, locationListener);
		}*/

		mlocationClient = new AMapLocationClient(getActivity());
		mLocationOption = new AMapLocationClientOption();
		//设置定位监听
		mlocationClient.setLocationListener(this);
		//设置为高精度定位模式
		mLocationOption.setLocationMode(AMapLocationMode.Hight_Accuracy);

		mlocationClient.setLocationOption(mLocationOption);
		// 此方法为每隔固定时间会发起一次定位请求,为了减少电量消耗或网络流量消耗,
		// 注意设置合适的定位时间的间隔(最小间隔支持为2000ms),并且在合适时间调用stopLocation()方法来取消定位请求
		// 在定位结束后,在合适的生命周期调用onDestroy()方法
		// 在单次定位情况下,定位无论成功与否,都无需调用stopLocation()方法移除请求,定位sdk内部会移除
		mlocationClient.startLocation();
//		mLocationOption.setOnceLocation(false);
		AMapLocation amapLocation= mlocationClient.getLastKnownLocation();
		if (amapLocation != null
				&& amapLocation.getErrorCode() == 0) {
			txtLocation.setText("1:"+amapLocation.getAddress());
		}
		return rootView;
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		// 在activity执行onDestroy时执行mMapView.onDestroy(),实现地图生命周期管理
//		mapView.onDestroy();
		if (null != mlocationClient) {
			mlocationClient.onDestroy();
		}
		/*if (locationManager != null) {
			locationManager.removeUpdates(locationListener);
//			locationManager.setTestProviderEnabled("gps",false);
		}*/
	}
	@Override
	public void onResume() {
		super.onResume();
		// 在activity执行onResume时执行mMapView.onResume (),实现地图生命周期管理
//		mapView.onResume();
	}
	@Override
	public void onPause() {
		super.onPause();
		// 在activity执行onPause时执行mMapView.onPause (),实现地图生命周期管理
//		mapView.onPause();
		deactivate();
	}
	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		// 在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState
		// (outState),实现地图生命周期管理
//		mapView.onSaveInstanceState(outState);
	}

	/*private void showLocation(final Location location) {
		if (location == null) {
			TrickerUtils.showToast(getActivity(), "暂未获取到位置信息");
		}

		new Thread(new Runnable() {
			@Override
			public void run() {
				try {

					StringBuilder url = new StringBuilder();
					url.append("http://maps.google.cn/maps/api/geocode/json?latlng=");
					url.append(location.getLatitude()).append(",");
					url.append(location.getLongitude());
					url.append("&sensor=false");
					// TrickerUtils.showToast(getActivity(), url.toString());
					HttpURLConnection connection = null;
					URL uUrl = new URL(url.toString());
					connection = (HttpURLConnection) uUrl.openConnection();
					connection.setRequestMethod("GET");
					connection.setConnectTimeout(8000);
					connection.setReadTimeout(8000);
					InputStream in = connection.getInputStream();
					BufferedReader reader = new BufferedReader(new InputStreamReader(in));
					StringBuilder response = new StringBuilder();
					String line;
					while ((line = reader.readLine()) != null) {
						response.append(line);

					}
					// Log.e("tricker", response.toString());
					JSONObject json = new JSONObject(response.toString());
					JSONArray resultArray = json.getJSONArray("results");
					if (resultArray.length() > 0) {
						JSONObject subObject = resultArray.getJSONObject(0);
						String address = subObject.getString("formatted_address");
						Message message = new Message();
						message.what = SHOW_RESPONSE;
						message.obj = address;
						handler.sendMessage(message);
					}

				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
			}
		}).start();
	}*/

	// private Handler handler = new Handler(new Handler.Callback() {
	// @Override
	// public boolean handleMessage(Message msg) {
	// return false;
	// }
	// }) ;

	/*private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
//			TrickerUtils.showToast(getActivity(), "位置改变!");
			switch (msg.what) {
			case SHOW_RESPONSE:
				String response = msg.obj.toString();
				txtLocation.setText(response);
				break;

			default:
				break;
			}
		};
	};*/
	/*private LocationListener locationListener = new LocationListener() {

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onProviderEnabled(String provider) {
			Location location = locationManager.getLastKnownLocation(provider);
			if(location!=null){
				showLocation(location);
			}

		}

		@Override
		public void onProviderDisabled(String provider) {
			TrickerUtils.showToast(getActivity(), "你刚关闭了【"+provider+"】定位服务");
		}

		@Override
		public void onLocationChanged(Location location) {
			showLocation(location);

		}
	};*/

	private void setValues() {
		type=getArguments().getInt("types");
//		setVisible(type);
		editType.setSelection(type);
		editType.setEnabled(false);//编辑不允许修改类型
		if(type==Constant.RENT){
			editDate.setText(getArguments().getString("date"));
			editMoney.setText(getArguments().getString("money"));
			editProject.setText(getArguments().getString("project"));
			String percent = getArguments().getString("percent");
			String state = getArguments().getString("state");
			int position = 0;
			if (!TextUtils.isEmpty(percent) && percent.equals("1/2")) {
				position = 1;
			}
			editPercent.setSelection(position);
			editRemark.setText(getArguments().getString("remark"));

			position = 0;
			if (!TextUtils.isEmpty(state) && state.equals("已结算")) {
				position = 1;
			}
			editState.setSelection(position);
		}else if(type==Constant.MARRY){
			editName.setText(getArguments().getString("name"));
			editMoney1.setText(getArguments().getString("getMoney"));
			editMoney2.setText(getArguments().getString("payMoney"));
			editRemark1.setText(getArguments().getString("remark"));
			String state = getArguments().getString("state");
			int position = 0;
			if (!TextUtils.isEmpty(state) && state.equals("已结算")) {
				position = 1;
			}
			editState.setSelection(position);
		}else if(type==Constant.SALE){
			editSaleDate.setText(getArguments().getString("date"));
			editSaleMoney.setText(getArguments().getString("money"));
			editSaleWeek.setText(getArguments().getString("week"));
			editSaleRemark.setText(getArguments().getString("remark"));
			editSaleType.setSelection(TrickerUtils.getItemPosition(getArguments().getString("type")));
		}

		btnSave.setText("修改");
	}

	private void findViews(View rootView) {
		//rent
		editDate = (EditText) rootView.findViewById(R.id.editDate);
		editMoney = (EditText) rootView.findViewById(R.id.editMoney);
		editProject = (EditText) rootView.findViewById(R.id.editProject);
		editPercent = (Spinner) rootView.findViewById(R.id.editPercent);
		btnSave = (Button) rootView.findViewById(R.id.btnSave);
		editRemark = (EditText) rootView.findViewById(R.id.editRemark);
		editState = (Spinner) rootView.findViewById(R.id.editState);
		editType= (Spinner) rootView.findViewById(R.id.editType);
		txtLocation = (TextView) rootView.findViewById(R.id.txtLocation);
		tableLayoutRent = (TableLayout) rootView.findViewById(R.id.project);
		tableLayoutMarry = (TableLayout) rootView.findViewById(marry);
		tableSale = (TableLayout) rootView.findViewById(R.id.sale);
		btnSave.setText("保存");
		//marry
		editName = (EditText) rootView.findViewById(R.id.editName);
		editMoney1 = (EditText) rootView.findViewById(R.id.editMoney1);
		editMoney2 = (EditText) rootView.findViewById(R.id.editMoney2);
		editState1 = (Spinner) rootView.findViewById(R.id.editState1);
		editRemark1 = (EditText) rootView.findViewById(R.id.editRemark1);
		editType.setOnItemSelectedListener(this);
		//Sale
		editSaleDate= (EditText) rootView.findViewById(R.id.editSaleDate);
		editSaleWeek= (EditText) rootView.findViewById(R.id.editWeek);
		editSaleType= (Spinner) rootView.findViewById(R.id.editSaleType);
		editSaleMoney= (EditText) rootView.findViewById(R.id.editSaleMoney);
		editSaleRemark= (EditText) rootView.findViewById(R.id.editSaleRemark);

		if(!MyApplication.getUser().getName().equals("Tricker")){
			editType.setSelection(2);
//			editType.setClickable(false);
			editType.setEnabled(false);//设置不可编辑
			editSaleMoney.requestFocus();
		}
		editSaleDate.setText(TrickerUtils.getSystemDateTime());
		editSaleWeek.setText(TrickerUtils.getDayOfWeek());
		// format = new SimpleDateFormat("yyyy/MM/dd");
		// String date = format.format(Calendar.getInstance().getTime());
		editDate.setText(TrickerUtils.getSystemDate());
		editDate.setKeyListener(null);// 相当于设置不可编辑
		editDate.setOnClickListener(this);
		editSaleDate.setKeyListener(null);// 相当于设置不可编辑
		editSaleDate.setOnClickListener(this);
		btnSave.setOnClickListener(this);

		txtLocation.setOnClickListener(this);
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		//注释
//		((MainActivity) activity).onSectionAttached(getArguments().getInt(ARG_SECTION_NUMBER));
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.btnSave:
				saveData();
				break;
			case R.id.editDate:
				// selectDate();
				TrickerUtils.selectDate(getActivity(), editDate);
				break;
			case R.id.txtLocation:
				MainActivity mainActivity = (MainActivity) getActivity();
				//直接打开地图页
				mainActivity.getmNavigationDrawerFragment().selectItem(2);
				//改变标题
				mainActivity.onSectionAttached(3);
				mainActivity.restoreActionBar();
				break;
			case R.id.editSaleDate:
				DatePickerDialog.OnDateSetListener callback = new DatePickerDialog.OnDateSetListener() {
					@Override
					public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
						Date date = new Date(year-1900,month,dayOfMonth);

						String dateTime = TrickerUtils.getDateTimeFormat().format(date);
						editSaleDate.setText(dateTime);
						editSaleWeek.setText(TrickerUtils.getDayOfWeek(date));
					}
				};
				TrickerUtils.selectDate(getActivity(), editDate,callback);
				break;
			default:
				break;
		}
	}

	private void saveData() {
		BaseDao dao = new BaseDao(getActivity());
//		SQLiteDatabase db = dao.getWritableDatabase();
		//判断是保存房租还是份子钱
		if(editType.getSelectedItem().equals("房租")){
			String projectName = this.editProject.getText().toString();
			String money = this.editMoney.getText().toString();
			String editDate = this.editDate.getText().toString();
			String editPercent = this.editPercent.getSelectedItem().toString();
			String editRemark = this.editRemark.getText().toString();
			String editState = this.editState.getSelectedItem().toString();
			if (TextUtils.isEmpty(money)) {
				TrickerUtils.showToast(getActivity(), "金额不能为空!");
				return;
			}
			if (TextUtils.isEmpty(projectName)) {
				TrickerUtils.showToast(getActivity(), "项目不能为空!");
				return;
			}
			if (TextUtils.isEmpty(editPercent)) {
				TrickerUtils.showToast(getActivity(), "占比不能为空!");
				return;
			}
			Project project = new Project();
			project.setProject(projectName);
			project.setMoney(money);
			project.setDate(editDate);
			project.setPercent(editPercent);
			project.setRemark(editRemark);
			project.setState(editState);
			if (isEdit) {
				project.setId(getArguments().getInt("_id"));
				TrickerDB.getInstance(getActivity()).saveProject(project,true);
				// TrickerUtils.showToast(getActivity(), "修改成功!");
				MainActivity mainActivity = (MainActivity) getActivity();
				mainActivity.setType(this.type);
				mainActivity.getmNavigationDrawerFragment().selectItem(1);
			} else {
				TrickerDB.getInstance(getActivity()).saveProject(project);
				TrickerUtils.showToast(getActivity(), "保存成功!");
			}

		}else if(editType.getSelectedItem().equals("份子钱")){
			String name = this.editName.getText().toString();
			String money1 = this.editMoney1.getText().toString();
			String money2 = this.editMoney2.getText().toString();
			String editRemark1 = this.editRemark1.getText().toString();
			String editState1 = this.editState1.getSelectedItem().toString();
			if (TextUtils.isEmpty(money1)) {
				TrickerUtils.showToast(getActivity(), "获得金额不能为空!");
				return;
			}
			if (TextUtils.isEmpty(name)) {
				TrickerUtils.showToast(getActivity(), "姓名不能为空!");
				return;
			}
			Marry marry = new Marry();
			marry.setName(name);
			marry.setGetMoney(money1);
			marry.setPayMoney(money2);
			marry.setRemark(editRemark1);
			marry.setState(editState1);
			if (isEdit) {
				marry.setId(getArguments().getInt("_id"));
				TrickerDB.getInstance(getActivity()).saveMarry(marry,true);
				MainActivity mainActivity = (MainActivity) getActivity();
				mainActivity.setType(this.type);
				mainActivity.getmNavigationDrawerFragment().selectItem(1);
			} else {
				TrickerDB.getInstance(getActivity()).saveMarry(marry);
				TrickerUtils.showToast(getActivity(), "保存成功!");
			}
		}else if(editType.getSelectedItem().equals("销售额")){
			String date = this.editSaleDate.getText().toString();
			String week = this.editSaleWeek.getText().toString();
			String money = this.editSaleMoney.getText().toString();
			String remark = this.editSaleRemark.getText().toString();
			String type = this.editSaleType.getSelectedItem().toString();
			if (TextUtils.isEmpty(money)) {
				TrickerUtils.showToast(getActivity(), "金额不能为空!");
				return;
			}
			Sale sale = new Sale();
			sale.setDate(date);
			sale.setMoney(money);
			sale.setRemark(remark);
			sale.setType(type);
			sale.setWeek(week);
			if (isEdit) {
				sale.setId(getArguments().getInt("_id"));
				TrickerDB.getInstance(getActivity()).saveSale(sale,true);
				MainActivity mainActivity = (MainActivity) getActivity();
				mainActivity.setType(this.type);
				mainActivity.getmNavigationDrawerFragment().selectItem(1);
			} else {
				TrickerDB.getInstance(getActivity()).saveSale(sale);
				TrickerUtils.showToast(getActivity(), "保存成功!");
			}
		}

//		//无论修改和添加都需要备份当前的最新数据库(提取到增删改里)
//		File fromFile = new File(TrickerUtils.getPath(getActivity(), TrickerUtils.DATABASE_PATH));
//		File toFile = new File(Environment.getExternalStorageDirectory().getPath()+File.separator+"tricker"+File.separator+"tricker.db");
//		String result =TrickerUtils.copyfile(fromFile, toFile , true);
//		TrickerUtils.showToast(this,Environment.getExternalStorageDirectory().getPath());
//		TrickerUtils.showToast(this, result);
		// getActivity().finish();
	}

	/**
	 * 提取该方法到TrickerUtils
	 */
	/*
	 * private void selectDate() { int year =
	 * Calendar.getInstance().get(Calendar.YEAR); int month =
	 * Calendar.getInstance().get(Calendar.MONTH); int day =
	 * Calendar.getInstance().get(Calendar.DAY_OF_MONTH); String data
	 * =editDate.getText().toString(); if(!TextUtils.isEmpty(data)){ String
	 * strs[] =data.split("/"); year= Integer.parseInt(strs[0]); month=
	 * Integer.parseInt(strs[1])-1; day= Integer.parseInt(strs[2]); }
	 * OnDateSetListener callBack = new OnDateSetListener() {
	 *
	 * @Override public void onDateSet(DatePicker view, int year, int
	 * monthOfYear, int dayOfMonth) { String date = format.format(new
	 * Date(view.getCalendarView().getDate())); editDate.setText(date); } };
	 * DatePickerDialog dlg = new DatePickerDialog(getActivity(), callBack,
	 * year, month, day); dlg.show(); }
	 */

	@Override
	public void activate(OnLocationChangedListener listener) {
		mListener = listener;
		if (mlocationClient == null) {
			mlocationClient = new AMapLocationClient(getActivity());
			mLocationOption = new AMapLocationClientOption();
			//设置定位监听
			mlocationClient.setLocationListener(this);
			//设置为高精度定位模式
			mLocationOption.setLocationMode(AMapLocationMode.Hight_Accuracy);
			//设置定位参数
			mlocationClient.setLocationOption(mLocationOption);
			// 此方法为每隔固定时间会发起一次定位请求,为了减少电量消耗或网络流量消耗,
			// 注意设置合适的定位时间的间隔(最小间隔支持为2000ms),并且在合适时间调用stopLocation()方法来取消定位请求
			// 在定位结束后,在合适的生命周期调用onDestroy()方法
			// 在单次定位情况下,定位无论成功与否,都无需调用stopLocation()方法移除请求,定位sdk内部会移除
			mlocationClient.startLocation();
		}

	}

	@Override
	public void deactivate() {
		mListener = null;
		if (mlocationClient != null) {
			mlocationClient.stopLocation();
			mlocationClient.onDestroy();
		}
		mlocationClient = null;

	}

	@Override
	public void onLocationChanged(AMapLocation amapLocation) {
		if (mListener != null && amapLocation != null) {
			if (amapLocation != null
					&& amapLocation.getErrorCode() == 0) {
//				mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
				txtLocation.setText("2:"+amapLocation.getAddress());
			} else {
				String errText = "定位失败," + amapLocation.getErrorCode()+ ": " + amapLocation.getErrorInfo();
				Log.e("AmapErr",errText);
				TrickerUtils.showToast(getActivity(), errText);
			}
		}
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
		this.type = position;
//		TrickerUtils.showToast(getActivity(),"ss");
//		if(position==0){
//			setProjectVisible(true);
//		}else if(position==1){
//			setProjectVisible(false);
//		}
		setVisible(position);
	}

	private void setVisible(int type) {
		if(type== Constant.RENT){
			tableLayoutRent.setVisibility(View.VISIBLE);
			tableLayoutMarry.setVisibility(View.GONE);
			tableSale.setVisibility(View.GONE);
			editMoney.requestFocus();
		}else if(type==Constant.MARRY){
			tableLayoutRent.setVisibility(View.GONE);
			tableLayoutMarry.setVisibility(View.VISIBLE);
			tableSale.setVisibility(View.GONE);
			editName.requestFocus();
		}else if(type==Constant.SALE){
			tableLayoutRent.setVisibility(View.GONE);
			tableLayoutMarry.setVisibility(View.GONE);
			tableSale.setVisibility(View.VISIBLE);
			editSaleMoney.requestFocus();
		}

	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {

	}
}


text:
package com.intellij.ide.bookmarks.actions;

import com.intellij.ide.bookmarks.Bookmark;
import com.intellij.ide.bookmarks.BookmarkManager;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.LogicalPosition;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.editor.actionSystem.EditorAction;
import com.intellij.openapi.editor.actionSystem.EditorActionHandler;
import com.intellij.openapi.project.Project;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

abstract class GotoBookmarkActionBase extends EditorAction {
  protected GotoBookmarkActionBase(final boolean next) {
    super(new EditorActionHandler() {
      @Override
      public void execute(Editor editor, DataContext dataContext) {
        navigateToBookmark(dataContext, editor);
      }

      @Override
      public boolean isEnabled(Editor editor, DataContext dataContext) {
        return getBookmarkToGo(dataContext, editor) != null;
      }

      private void navigateToBookmark(DataContext dataContext, @Nonnull final Editor editor) {
        final Bookmark bookmark = getBookmarkToGo(dataContext, editor);
        if (bookmark == null) return;

        int line = bookmark.getLine();
        if (line >= editor.getDocument().getLineCount()) return;
        if (line < 0) line = 0;

        LogicalPosition pos = new LogicalPosition(line, 0);
        editor.getSelectionModel().removeSelection();
        editor.getCaretModel().removeSecondaryCarets();
        editor.getCaretModel().moveToLogicalPosition(pos);
        editor.getScrollingModel().scrollTo(new LogicalPosition(line, 0), ScrollType.CENTER);
      }

      @Nullable
      private Bookmark getBookmarkToGo(DataContext dataContext, Editor editor) {
        Project project = dataContext.getData(CommonDataKeys.PROJECT);
        if (project == null) return null;
        BookmarkManager manager = BookmarkManager.getInstance(project);
        return next ? manager.getNextBookmark(editor, true) : manager.getPreviousBookmark(editor, true);
      }
    });
  }

}


text:
package edu.gatech.gtri.typesafeconfigextensions.forwebapps;

import javax.servlet.ServletContext;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static edu.gatech.gtri.typesafeconfigextensions.internal.Check.checkNotNull;

/**
 * A path represented as the list of strings formed by splitting a
 * {@link ServletContext#getContextPath() servlet context path}
 * on {@code "/"}.
 */
public final class ServletContextPath {

    private final List<String> pathComponents;

    ServletContextPath(List<String> pathComponents) {
        this.pathComponents = checkNotNull(pathComponents);
    }

    public List<String> toList() {
        return Collections.unmodifiableList(pathComponents);
    }

    @Override
    public boolean equals(Object o) {

        if (this == o) {
            return true;
        }

        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        ServletContextPath that = (ServletContextPath) o;

        return pathComponents.equals(that.pathComponents);
    }

    @Override
    public int hashCode() {
        return pathComponents.hashCode();
    }

    @Override
    public String toString() {
        return String.format("ServletContextPath { %s }", pathString());
    }

    private String pathString() {

        if (pathComponents.isEmpty()) {
            return "(root)";
        }

        StringBuilder s = new StringBuilder();

        for (String component : pathComponents) {
            s.append("/").append(component);
        }

        return s.toString();
    }

    public static ServletContextPath
    fromServletContext(ServletContext servletContext) {

        return parse(servletContext.getContextPath());
    }

    public static ServletContextPath parse(String path) {

        List<String> parsed = new ArrayList<>();

        for (String s : path.split("/")) {
            if (!s.isEmpty()) {
                parsed.add(s);
            }
        }

        return new ServletContextPath(parsed);
    }
}


text:
imagist-ruby
============

A clone of placehold.it in Ruby


text:
<?php
declare(strict_types=1);

namespace Tests\Units\AmmitPhp\Ammit\UI\Resolver\Validator;

use AmmitPhp\Ammit\UI\Resolver\UIValidationEngine;
use mageekguy\atoum;

use AmmitPhp\Ammit\UI\Resolver\Validator\RawValueValidator as SUT;

class RawValueValidator extends atoum
{
    public static function getSutMethodNames(): array
    {
        $uiValidationEngine = UIValidationEngine::initialize();
        $sut = new SUT($uiValidationEngine);

        $methods = get_class_methods($sut);

        $methods = self::removeFromArray('__construct', $methods);
        $methods = self::removeFromArray('createUIValidationException', $methods);

        return $methods;
    }

    private static function removeFromArray(string $method, array $methods): array
    {
        if (($key = array_search($method, $methods)) !== false) {
            unset($methods[$key]);
        }

        return $methods;
    }
}


text: My ruby snippets, methods, etc


text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CacheCow.Common;
#if NET452
using System.Runtime.Caching;
#else
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
#endif

namespace CacheCow.Client
{
    public class InMemoryVaryHeaderStore : IVaryHeaderStore
    {
        private const string CacheName = "###_IVaryHeaderStore_###";
        private readonly ConcurrentDictionary<string, string[]> _varyHeaderCache = new ConcurrentDictionary<string, string[]>();
#if NET452
        private MemoryCache _cache = new MemoryCache(CacheName);
#else
        private MemoryCache _cache = new MemoryCache(Options.Create(new MemoryCacheOptions()));
#endif

        public bool TryGetValue(string uri, out IEnumerable<string> headers)
        {
            headers = (string[])_cache.Get(uri);
            return headers != null;
        }

        public void AddOrUpdate(string uri, IEnumerable<string> headers)
        {
            _cache.Set(uri, headers, DateTimeOffset.MaxValue);
        }

        public bool TryRemove(string uri)
        {
#if NET452
            return _cache.Remove(uri) != null;
#endif
            _cache.Remove(uri);
            return true;
        }

        public void Clear()
        {
            ((IDisposable)_cache).Dispose();
#if NET452
            _cache = new MemoryCache(CacheName);
#else
            _cache = new MemoryCache(Options.Create(new MemoryCacheOptions()));
#endif
        }

        public void Dispose()
        {
            _cache.Dispose();
        }
    }
}


text:
package org.jabref.gui.preferences.journals;

import javafx.animation.Interpolator;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.transformation.FilteredList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.paint.Color;
import javafx.util.Duration;

import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.preferences.AbstractPreferenceTabView;
import org.jabref.gui.preferences.PreferencesTab;
import org.jabref.gui.util.ColorUtil;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.gui.util.ValueTableCellFactory;
import org.jabref.logic.journals.JournalAbbreviationRepository;
import org.jabref.logic.l10n.Localization;

import com.airhacks.afterburner.views.ViewLoader;
import com.tobiasdiez.easybind.EasyBind;
import jakarta.inject.Inject;
import org.controlsfx.control.textfield.CustomTextField;

/**
 * This class controls the user interface of the journal abbreviations dialog. The UI elements and their layout are
 * defined in the FXML file.
 */
public class JournalAbbreviationsTab extends AbstractPreferenceTabView<JournalAbbreviationsTabViewModel> implements PreferencesTab {

    @FXML private Label loadingLabel;
    @FXML private ProgressIndicator progressIndicator;

    @FXML private TableView<AbbreviationViewModel> journalAbbreviationsTable;
    @FXML private TableColumn<AbbreviationViewModel, String> journalTableNameColumn;
    @FXML private TableColumn<AbbreviationViewModel, String> journalTableAbbreviationColumn;
    @FXML private TableColumn<AbbreviationViewModel, String> journalTableShortestUniqueAbbreviationColumn;
    @FXML private TableColumn<AbbreviationViewModel, String> actionsColumn;

    private FilteredList<AbbreviationViewModel> filteredAbbreviations;
    @FXML private ComboBox<AbbreviationsFileViewModel> journalFilesBox;

    @FXML private Button addAbbreviationButton;
    @FXML private Button removeAbbreviationListButton;

    @FXML private CustomTextField searchBox;
    @FXML private CheckBox useFJournal;

    @Inject private TaskExecutor taskExecutor;
    @Inject private JournalAbbreviationRepository abbreviationRepository;

    private Timeline invalidateSearch;

    public JournalAbbreviationsTab() {
        ViewLoader.view(this)
                  .root(this)
                  .load();
    }

    @FXML
    private void initialize() {
        viewModel = new JournalAbbreviationsTabViewModel(preferencesService, dialogService, taskExecutor, abbreviationRepository);

        filteredAbbreviations = new FilteredList<>(viewModel.abbreviationsProperty());

        setUpTable();
        setBindings();
        setAnimations();

        searchBox.setPromptText(Localization.lang("Search") + "...");
        searchBox.setLeft(IconTheme.JabRefIcons.SEARCH.getGraphicNode());
    }

    private void setUpTable() {
        journalTableNameColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
        journalTableNameColumn.setCellFactory(TextFieldTableCell.forTableColumn());

        journalTableAbbreviationColumn.setCellValueFactory(cellData -> cellData.getValue().abbreviationProperty());
        journalTableAbbreviationColumn.setCellFactory(TextFieldTableCell.forTableColumn());

        journalTableShortestUniqueAbbreviationColumn.setCellValueFactory(cellData -> cellData.getValue().shortestUniqueAbbreviationProperty());
        journalTableShortestUniqueAbbreviationColumn.setCellFactory(TextFieldTableCell.forTableColumn());

        actionsColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
        new ValueTableCellFactory<AbbreviationViewModel, String>()
                .withGraphic(name -> IconTheme.JabRefIcons.DELETE_ENTRY.getGraphicNode())
                .withTooltip(name -> Localization.lang("Remove journal '%0'", name))
                .withDisableExpression(item -> viewModel.isEditableAndRemovableProperty().not())
                .withVisibleExpression(item -> viewModel.isEditableAndRemovableProperty())
                .withOnMouseClickedEvent(item -> evt ->
                        viewModel.removeAbbreviation(journalAbbreviationsTable.getFocusModel().getFocusedItem()))
                .install(actionsColumn);
    }

    private void setBindings() {
        journalAbbreviationsTable.setItems(filteredAbbreviations);

        EasyBind.subscribe(journalAbbreviationsTable.getSelectionModel().selectedItemProperty(), newValue ->
                viewModel.currentAbbreviationProperty().set(newValue));
        EasyBind.subscribe(viewModel.currentAbbreviationProperty(), newValue ->
                journalAbbreviationsTable.getSelectionModel().select(newValue));

        journalTableNameColumn.editableProperty().bind(viewModel.isAbbreviationEditableAndRemovable());
        journalTableAbbreviationColumn.editableProperty().bind(viewModel.isAbbreviationEditableAndRemovable());
        journalTableShortestUniqueAbbreviationColumn.editableProperty().bind(viewModel.isAbbreviationEditableAndRemovable());

        removeAbbreviationListButton.disableProperty().bind(viewModel.isFileRemovableProperty().not());
        journalFilesBox.itemsProperty().bindBidirectional(viewModel.journalFilesProperty());
        journalFilesBox.valueProperty().bindBidirectional(viewModel.currentFileProperty());

        addAbbreviationButton.disableProperty().bind(viewModel.isEditableAndRemovableProperty().not());

        loadingLabel.visibleProperty().bind(viewModel.isLoadingProperty());
        progressIndicator.visibleProperty().bind(viewModel.isLoadingProperty());

        searchBox.textProperty().addListener((observable, previousText, searchTerm) -> {
            filteredAbbreviations.setPredicate(abbreviation -> searchTerm.isEmpty() || abbreviation.containsCaseIndependent(searchTerm));
        });

        useFJournal.selectedProperty().bindBidirectional(viewModel.useFJournalProperty());
    }

    private void setAnimations() {
        ObjectProperty<Color> flashingColor = new SimpleObjectProperty<>(Color.TRANSPARENT);
        StringProperty flashingColorStringProperty = createFlashingColorStringProperty(flashingColor);

        searchBox.styleProperty().bind(
                new SimpleStringProperty("-fx-control-inner-background: ").concat(flashingColorStringProperty).concat(";")
        );
        invalidateSearch = new Timeline(
                new KeyFrame(Duration.seconds(0), new KeyValue(flashingColor, Color.TRANSPARENT, Interpolator.LINEAR)),
                new KeyFrame(Duration.seconds(0.25), new KeyValue(flashingColor, Color.RED, Interpolator.LINEAR)),
                new KeyFrame(Duration.seconds(0.25), new KeyValue(searchBox.textProperty(), "", Interpolator.DISCRETE)),
                new KeyFrame(Duration.seconds(0.25), (ActionEvent event) -> {
                    addAbbreviationActions();
                }),
                new KeyFrame(Duration.seconds(0.5), new KeyValue(flashingColor, Color.TRANSPARENT, Interpolator.LINEAR))
        );
    }

    @FXML
    private void addList() {
        viewModel.addNewFile();
    }

    @FXML
    private void openList() {
        viewModel.openFile();
    }

    @FXML
    private void removeList() {
        viewModel.removeCurrentFile();
    }

    @FXML
    private void addAbbreviation() {
        if (!searchBox.getText().isEmpty()) {
            invalidateSearch.play();
        } else {
            addAbbreviationActions();
        }
    }

    private void addAbbreviationActions() {
        viewModel.addAbbreviation();
        selectNewAbbreviation();
        editAbbreviation();
    }

    private static StringProperty createFlashingColorStringProperty(final ObjectProperty<Color> flashingColor) {
        final StringProperty flashingColorStringProperty = new SimpleStringProperty();
        setColorStringFromColor(flashingColorStringProperty, flashingColor);
        flashingColor.addListener((observable, oldValue, newValue) -> setColorStringFromColor(flashingColorStringProperty, flashingColor));
        return flashingColorStringProperty;
    }

    private static void setColorStringFromColor(StringProperty colorStringProperty, ObjectProperty<Color> color) {
        colorStringProperty.set(ColorUtil.toRGBACode(color.get()));
    }

    @FXML
    private void editAbbreviation() {
        journalAbbreviationsTable.edit(
                journalAbbreviationsTable.getSelectionModel().getSelectedIndex(),
                journalTableNameColumn);
    }

    private void selectNewAbbreviation() {
        int lastRow = viewModel.abbreviationsCountProperty().get() - 1;
        journalAbbreviationsTable.scrollTo(lastRow);
        journalAbbreviationsTable.getSelectionModel().select(lastRow);
        journalAbbreviationsTable.getFocusModel().focus(lastRow, journalTableNameColumn);
    }

    @Override
    public String getTabName() {
        return Localization.lang("Journal abbreviations");
    }
}


text:
/** \file pantheios/extras/xhelpers/internal/common.hpp
 * [C++] Definition of common features header for the
 *   \ref group__library__pantheios_extras_xhelpers "Pantheios.Extras.xHelpers" library.
 */

#ifndef PANTHEIOS_EXTRAS_XHELPERS_INCL_PANTHEIOS_EXTRAS_XHELPERS_INTERNAL_HPP_COMMON
#define PANTHEIOS_EXTRAS_XHELPERS_INCL_PANTHEIOS_EXTRAS_XHELPERS_INTERNAL_HPP_COMMON

/* /////////////////////////////////////////////////////////////////////////
 * Version information
 */

#ifndef PANTHEIOS_DOCUMENTATION_SKIP_SECTION
# define PANTHEIOS_XHELPERS_EXTRAS_VER_PANTHEIOS_EXTRAS_XHELPERS_INTERNAL_HPP_COMMON_MAJOR      1
# define PANTHEIOS_XHELPERS_EXTRAS_VER_PANTHEIOS_EXTRAS_XHELPERS_INTERNAL_HPP_COMMON_MINOR      0
# define PANTHEIOS_XHELPERS_EXTRAS_VER_PANTHEIOS_EXTRAS_XHELPERS_INTERNAL_HPP_COMMON_REVISION   2
# define PANTHEIOS_XHELPERS_EXTRAS_VER_PANTHEIOS_EXTRAS_XHELPERS_INTERNAL_HPP_COMMON_EDIT       2
#endif /* !PANTHEIOS_DOCUMENTATION_SKIP_SECTION */

/* /////////////////////////////////////////////////////////////////////////
 * Includes
 */

#include <pantheios/extras/xhelpers/internal/common.h>

/* /////////////////////////////////////////////////////////////////////////
 * Compatibility checks
 */

#if defined(PANTHEIOS_NO_NAMESPACE)
# error Pantheios.Extras.xHelpers library does not (currently) support no-namespace operation
#endif /* !PANTHEIOS_NO_NAMESPACE */

/* /////////////////////////////////////////////////////////////////////////
 * Namespace
 */

/** The Pantheios root namespace - pantheios.
 *
 * This namespace is used by the Pantheios main library.
 * Pantheios.Extras.xHelpers elements are defined within
 * the pantheios::extras::xhelpers namespace.
 */
namespace pantheios
{
/** The Pantheios::Extras root namespace - pantheios::extras.
 *
 * This namespace is used to contain all Pantheios::Extras projects.
 * Pantheios.Extras.xHelpers elements are defined within
 * the pantheios::extras::xhelpers namespace.
 */
namespace extras
{
/** The namespace used by the Pantheios.Extras.xHelpers
 * library - pantheios::extras::xhelpers.
 */
namespace xhelpers
{

} // namespace xhelpers
} // namespace extras
} // namespace pantheios

/* /////////////////////////////////////////////////////////////////////////
 * Inclusion
 */

#ifdef STLSOFT_CF_PRAGMA_ONCE_SUPPORT
# pragma once
#endif /* STLSOFT_CF_PRAGMA_ONCE_SUPPORT */

/* ////////////////////////////////////////////////////////////////////// */

#endif /* !PANTHEIOS_EXTRAS_XHELPERS_INCL_PANTHEIOS_EXTRAS_XHELPERS_INTERNAL_HPP_COMMON */

/* ///////////////////////////// end of file //////////////////////////// */