text:
package com.example.dinamico_android;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.R.bool;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

public class Filiador extends Activity implements OnClickListener, OnCheckedChangeListener{

	Button anadirPaciente, btn1, btnEnviarTodo, btnMostrar,btnRecibirTodo;
	LectorJSon2 lector;
	Builder dialogo1;
	View v;
	EditText txtNombre, txtNTarjeta, txtEdad;
	RadioGroup rGroup1;
	RadioButton rbtn1, rbtn2, checkeado;
	String nombre = "", nTarjeta = "", sexo = "", edad = "",tas="",fr="",gcs="";
	JSONArray jar;
	EnviarDatos enviarDatos;
	String servidor, respuestaRequest, request;
	JSONObject job;
	String id;
	int idPaciente;
	Api api;
	JSONArray arrayPacientes;

	public boolean isNumeric(String string) throws IllegalArgumentException
	{
	   boolean isnumeric = false;

	   if (string != null && !string.equals(""))
	   {
	      isnumeric = true;
	      char chars[] = string.toCharArray();

	      for(int d = 0; d < chars.length; d++)
	      {
	         isnumeric &= Character.isDigit(chars[d]);

	         if(!isnumeric)
	         break;
	      }
	   }
	   return isnumeric;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.filiador);

		Bundle bundle = getIntent().getExtras();	//Recoger el extra que trae el Intent
		servidor = bundle.getString("Servidor");
		//Toast.makeText(getBaseContext(), servidor, Toast.LENGTH_SHORT).show();

		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
	    StrictMode.setThreadPolicy(policy);

		lector = new LectorJSon2();

		anadirPaciente = (Button)findViewById(R.id.btnAnadirPaciente);
		btnEnviarTodo = (Button)findViewById(R.id.btnEnviarTodo);
		btnMostrar = (Button)findViewById(R.id.btnMostrar);
		btnRecibirTodo = (Button)findViewById(R.id.btnRecibirTodo);
		btnEnviarTodo.setOnClickListener(this);
		anadirPaciente.setOnClickListener(this);
		btnMostrar.setOnClickListener(this);
		btnRecibirTodo.setOnClickListener(this);

		lector.cargar();
		jar = lector.getJar();

		try{
			api=new Api();
			arrayPacientes=api.recibirTodosLosPacientes(servidor);
			lector.guardar(arrayPacientes);
		} catch (Exception e){
			Toast.makeText(getBaseContext(), "Error:" + Log.getStackTraceString(e), Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {

		case R.id.btnAnadirPaciente:
			showDialog(0);
			break;

		case R.id.btn1:
			rGroup1.clearCheck();
			sexo = "";
			break;

		case R.id.btnEnviarTodo:
			lector.cargar();
			jar = lector.getJar();
			if(jar == null)
			{
				Toast.makeText(getBaseContext(), "No hay pacientes añadidos", Toast.LENGTH_SHORT).show();
			}
			else
			{
				for(int i=0;i<jar.length();i++)
				{
					try {
						lector.setNumPaciente(i);
						lector.cargar();
						jar = lector.getJar();
						job = jar.getJSONObject(i);
						id = job.getString("Id");
					} catch (JSONException e2) {
						// TODO Auto-generated catch block
						e2.printStackTrace();
					}

					if(id.equals(""))
					{
						try {
							idPaciente=-1;
							request = "json=" + jar.getJSONObject(i).toString();
							request += "&version=" + job.getString("Version");
							request += "&id=0";
							enviarDatos = new EnviarDatos();
							try {
								respuestaRequest = enviarDatos.makeRequest(request, (servidor + "/filiador"));
								//En respuestaRequest tendremos el ID que devemos asignar a ese paciente.
								//Codigo para asignar ID al paciente
								respuestaRequest = respuestaRequest.replaceAll("\\r|\\n", "");
								if (this.isNumeric(respuestaRequest)){
									idPaciente = Integer.parseInt(respuestaRequest);
								}else{
									Toast.makeText(getBaseContext(), "Error en la respuesta del servidor", Toast.LENGTH_SHORT).show();
								}

								lector.setId(idPaciente + "");	//Asignamos el id que nos ha devuelto el servidor al paciente
								lector.guardarJSon();		//Guardo el JSON

								actualizar(i);			//Llamo a la funcion actualizar(int i) para que mande los datos y el server
														//haga un UPDATE.

							} catch (Exception e) {
								e.printStackTrace();
							}
						} catch (JSONException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					}
					else
					{}
				}
			Toast.makeText(getBaseContext(), "Pacientes enviados correctamente", Toast.LENGTH_SHORT).show();
			}
			break;

		case R.id.btnRecibirTodo:
			try{
				arrayPacientes=api.recibirTodosLosPacientes(servidor);
				lector.guardar(arrayPacientes);
			} catch (Exception e){
				Toast.makeText(getBaseContext(), "Error:" + Log.getStackTraceString(e), Toast.LENGTH_SHORT).show();
			}
			break;

		case R.id.btnMostrar:
			try{
				lector.cargar();
				jar = lector.getJar();
				for(int i=0;i<jar.length();i++)
				{
					try {
					JSONObject hola = jar.getJSONObject(i);
						Toast.makeText(getBaseContext(), "Nombre de : " + i + " " + hola.getString("Nombre"), Toast.LENGTH_SHORT).show();
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			} catch (NullPointerException e){
				Toast.makeText(getBaseContext(), "No hay pacientes para mostrar", Toast.LENGTH_SHORT).show();
			} catch (Exception e){
				Toast.makeText(getBaseContext(), "Error:" + Log.getStackTraceString(e), Toast.LENGTH_SHORT).show();
			}

			break;
		}
	}

	@Override
	protected Dialog onCreateDialog(int id, Bundle args) {
		// TODO Auto-generated method stub
		switch(id)
		{
		case 0:
			v = LayoutInflater.from(getBaseContext()).inflate(R.layout.anadirpaciente, null);

			dialogo1 = new AlertDialog.Builder(this);
	        dialogo1.setTitle("Añadir paciente");
	        dialogo1.setView(v);

	        txtNombre = (EditText)v.findViewById(R.id.txtNombre);
	        txtNTarjeta = (EditText)v.findViewById(R.id.txtNTarjeta);
	        txtEdad = (EditText)v.findViewById(R.id.txtEdad);

	        rbtn1 = (RadioButton)v.findViewById(R.id.rbtn1);
	        rbtn2 = (RadioButton)v.findViewById(R.id.rbtn2);
	        rGroup1 = (RadioGroup)v.findViewById(R.id.rGroup1);
	        btn1 = (Button)v.findViewById(R.id.btn1);
	        rGroup1.setOnCheckedChangeListener(this);
	        btn1.setOnClickListener(this);

	        dialogo1.setCancelable(false);
	        dialogo1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialogo1, int id) {
	            	aceptar();
	            }
	        });
	        dialogo1.setNegativeButton("Salir", new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialogo1, int id) {
	            	dialogo1.dismiss();
	            }
	        });
	        dialogo1.show();
			break;
		}
		return super.onCreateDialog(id, args);
	}

	public void aceptar()
	{
		if(txtNombre.getText().toString().equals("") && txtEdad.getText().toString().equals("")
				&& txtNTarjeta.getText().toString().equals("") && sexo.equals(""))
		{
			return;
		}
		lector.cargar();
		int numPaciente = lector.comprobarNumPaciente();
		String nControl = numPaciente + "";
		nombre = txtNombre.getText().toString();
		nTarjeta = txtNTarjeta.getText().toString();
		edad = txtEdad.getText().toString();

		//Poner a "" todas las variables para que el paciente que a�ades no tenga los valores de un paciente anterior
		lector.resetearVariables();	//Original

		lector.setNumPaciente(numPaciente);
		//lector.resetearVariables();	//Prueba
		lector.setnControl(nControl);

		lector.setNombre(nombre);
		lector.setnTarjeta(nTarjeta);
		lector.setSexo(sexo);
		lector.setEdad(edad);

		lector.guardarJSon();
		lector.cargar();
		sexo = "";
	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		// TODO Auto-generated method stub
		if (checkedId <= 0) {
		} else {
			switch (group.getId()) {
			case R.id.rGroup1:
				checkeado = (RadioButton)v.findViewById(checkedId);
				sexo = checkeado.getText().toString();
				break;
			}
		}
	}

	public void actualizar(int i)
	{
		//Metodo que despues de asignarle el ID devuelto por el servidor a cada paciente lo vuelve a enviar
		//para que en el servidor haga un UPDATE que tenga el ID que le paso yo y guarde el JSON y la version.
		LectorJSon2 hola = new LectorJSon2(i);
		hola.cargar();
		JSONArray arrayJson = hola.getJar();
		try {
			JSONObject objectJson = arrayJson.getJSONObject(i);
			String segundoEnvio = "json=" + arrayJson.getJSONObject(i).toString();
			segundoEnvio += "&version=" + objectJson.getString("Version");
			segundoEnvio += "&id=" + objectJson.getString("Id");

			String mierda = enviarDatos.makeRequest(segundoEnvio, (servidor + "/filiador"));
		}
		catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}


text:
<?php

namespace Knp\Bundle\MenuBundle\Tests\DependencyInjection\Compiler;

use Knp\Bundle\MenuBundle\DependencyInjection\Compiler\MenuBuilderPass;

class MenuBuilderPassTest extends \PHPUnit_Framework_TestCase
{
    private $containerBuilder;
    private $definition;
    private $builderDefinition;

    /**
     * @var MenuBuilderPass
     */
    private $pass;

    protected function setUp()
    {
        $this->containerBuilder = $this->prophesize('Symfony\Component\DependencyInjection\ContainerBuilder');
        $this->definition = $this->prophesize('Symfony\Component\DependencyInjection\Definition');
        $this->builderDefinition = $this->prophesize('Symfony\Component\DependencyInjection\Definition');
        $this->pass = new MenuBuilderPass();

        $this->containerBuilder->getDefinition('knp_menu.menu_provider.builder_service')->willReturn($this->definition);
        $this->containerBuilder->getDefinition('id')->willReturn($this->builderDefinition);

        $this->builderDefinition->isPublic()->willReturn(true);
        $this->builderDefinition->isAbstract()->willReturn(false);
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage Abstract services cannot be registered as menu builders but "id" is.
     */
    public function testFailsWhenServiceIsAbstract()
    {
        $this->builderDefinition->isAbstract()->willReturn(true);
        $this->containerBuilder->findTaggedServiceIds('knp_menu.menu_builder')->willReturn(array('id' => array(array('alias' => 'foo'))));

        $this->pass->process($this->containerBuilder->reveal());
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage Menu builder services must be public but "id" is a private service.
     */
    public function testFailsWhenServiceIsPrivate()
    {
        $this->builderDefinition->isPublic()->willReturn(false);
        $this->containerBuilder->findTaggedServiceIds('knp_menu.menu_builder')->willReturn(array('id' => array(array('alias' => 'foo'))));

        $this->pass->process($this->containerBuilder->reveal());
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage The alias is not defined in the "knp_menu.menu_builder" tag for the service "id"
     */
    public function testFailsWhenAliasIsMissing()
    {
        $this->containerBuilder->findTaggedServiceIds('knp_menu.menu_builder')->willReturn(array('id' => array(array('alias' => ''))));

        $this->pass->process($this->containerBuilder->reveal());
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage The method is not defined in the "knp_menu.menu_builder" tag for the service "id"
     */
    public function testFailsWhenMethodIsMissing()
    {
        $this->containerBuilder->findTaggedServiceIds('knp_menu.menu_builder')->willReturn(array('id' => array(array('alias' => 'foo'))));

        $this->pass->process($this->containerBuilder->reveal());
    }

    public function testReplaceArgument()
    {
        $this->containerBuilder->getDefinition('id1')->willReturn($this->builderDefinition);
        $this->containerBuilder->getDefinition('id2')->willReturn($this->builderDefinition);

        $taggedServiceIds = array(
            'id1' => array(array('alias' => 'foo', 'method' => 'fooMenu'), array('alias' => 'bar', 'method' => 'bar')),
            'id2' => array(array('alias' => 'foo', 'method' => 'fooBar'), array('alias' => 'baz', 'method' => 'bar')),
        );
        $this->containerBuilder->findTaggedServiceIds('knp_menu.menu_builder')->willReturn($taggedServiceIds);

        $menuBuilders = array(
            'foo' => array('id2', 'fooBar'),
            'bar' => array('id1', 'bar'),
            'baz' => array('id2', 'bar'),
        );
        $this->definition->replaceArgument(1, $menuBuilders)->shouldBeCalled();

        $this->pass->process($this->containerBuilder->reveal());
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.twosigma.beakerx.kernel.magic.command;

import com.twosigma.beakerx.kernel.magic.command.MavenJarResolver.Dependency;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class PomFactory {

  public String createPom(String pathToMavenRepo, List<Dependency> dependencies, Map<String, String> repos) throws IOException {
    InputStream pom = getClass().getClassLoader().getResourceAsStream(MavenJarResolver.POM_XML);
    String pomAsString = IOUtils.toString(pom, StandardCharsets.UTF_8);
    pomAsString = configureOutputDir(pathToMavenRepo, pomAsString);
    pomAsString = configureDependencies(dependencies, pomAsString);
    pomAsString = configureRepos(repos, pomAsString);
    return pomAsString;
  }

  private String configureDependencies(List<Dependency> dependencies, String pomAsString) {
    for (Dependency dependency : dependencies) {
      pomAsString = configureDependency(dependency, pomAsString);
    }
    return pomAsString;
  }

  private String configureDependency(Dependency dependency, String pomAsString) {
    return pomAsString.replace(
            "</dependencies>",
            "  <dependency>\n" +
                    "    <groupId>" + dependency.groupId + "</groupId>\n" +
                    "    <artifactId>" + dependency.artifactId + "</artifactId>\n" +
                    "    <version>" + dependency.version + "</version>\n" +
                    "    <type>" + dependency.type + "</type>\n" +
                    "  </dependency>\n" +
                    "</dependencies>");
  }

  private String configureOutputDir(String pathToMavenRepo, String pomAsString) {
    String absolutePath = new File(pathToMavenRepo).getAbsolutePath();
    return pomAsString.replace(
            "<outputDirectory>pathToNotebookJars</outputDirectory>",
            "<outputDirectory>" + absolutePath + "</outputDirectory>");
  }

  private String configureRepos(Map<String, String> repos, String pomAsString) {
    for (Entry<String, String> entry : repos.entrySet()) {
      pomAsString = configureRepos(pomAsString, entry.getKey(), entry.getValue());
    }
    return pomAsString;
  }

  private String configureRepos(String pomAsString, String name, String url) {
    String repoPattern = "" +
            "<repository>\n" +
            "    <id>%s</id>\n" +
            "    <url>%s</url>\n" +
            "</repository>\n";

    return pomAsString.replace("</repositories>", String.format(repoPattern, name, url) + "</repositories>");
  }
}


text:
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import GridSearchCV
from sklearn import datasets

from sklearn_evaluation.plot import grid_search

iris = datasets.load_iris()

parameters = {
    'n_estimators': [1, 10, 50, 100],
    'criterion': ['gini', 'entropy'],
    'max_features': ['sqrt', 'log2'],
}

est = RandomForestClassifier()
clf = GridSearchCV(est, parameters, cv=5)

X, y = datasets.make_classification(1000, 10, n_informative=5, class_sep=0.7)
clf.fit(X, y)

# changing numeric parameter without any restrictions
# in the rest of the parameter set
grid_search(clf.cv_results_, change='n_estimators')
plt.show()

# you can also use bars
grid_search(clf.cv_results_, change='n_estimators', kind='bar')
plt.show()

# changing a categorical variable without any constraints
grid_search(clf.cv_results_, change='criterion')
plt.show()

# bar
grid_search(clf.cv_results_, change='criterion', kind='bar')
plt.show()

# varying a numerical parameter but constraining
# the rest of the parameter set
grid_search(clf.cv_results_, change='n_estimators',
            subset={'max_features': 'sqrt', 'criterion': 'gini'},
            kind='bar')
plt.show()

# same as above but letting max_features to have two values
grid_search(clf.cv_results_, change='n_estimators',
            subset={'max_features': ['sqrt', 'log2'], 'criterion': 'gini'},
            kind='bar')
plt.show()

# varying two parameters - you can only show this as a
# matrix so the kind parameter will be ignored
grid_search(clf.cv_results_, change=('n_estimators', 'criterion'),
            subset={'max_features': 'sqrt'})
plt.show()


text:
package iso20022

// Other parties information.
type OtherParties11 struct {

	// Party, either an individual or organisation, whose assets are being invested.
	Investor *PartyIdentification37Choice `xml:"Invstr,omitempty"`

	// Foreign Financial Institution which has been authorised by local authorities to act as account management institution in the country.
	QualifiedForeignIntermediary *PartyIdentification43Choice `xml:"QlfdFrgnIntrmy,omitempty"`

	// Identification of the stock exchange to which transaction reporting will be done.
	StockExchange *PartyIdentification43Choice `xml:"StockXchg,omitempty"`

	// Institution to which a trade must be reported.
	TradeRegulator *PartyIdentification43Choice `xml:"TradRgltr,omitempty"`

	// Party responsible for the administration of a tri-party collateral transaction including collateral allocation, marking to market and substitution of collateral.
	TripartyAgent *PartyIdentification43Choice `xml:"TrptyAgt,omitempty"`
}

func (o *OtherParties11) AddInvestor() *PartyIdentification37Choice {
	o.Investor = new(PartyIdentification37Choice)
	return o.Investor
}

func (o *OtherParties11) AddQualifiedForeignIntermediary() *PartyIdentification43Choice {
	o.QualifiedForeignIntermediary = new(PartyIdentification43Choice)
	return o.QualifiedForeignIntermediary
}

func (o *OtherParties11) AddStockExchange() *PartyIdentification43Choice {
	o.StockExchange = new(PartyIdentification43Choice)
	return o.StockExchange
}

func (o *OtherParties11) AddTradeRegulator() *PartyIdentification43Choice {
	o.TradeRegulator = new(PartyIdentification43Choice)
	return o.TradeRegulator
}

func (o *OtherParties11) AddTripartyAgent() *PartyIdentification43Choice {
	o.TripartyAgent = new(PartyIdentification43Choice)
	return o.TripartyAgent
}


text:
const path = require('path')
const fs = require('fs')
const yaml = require('js-yaml')

class Loader {
  constructor (customPath = null) {
    this.customPath = customPath
  }

  moduleRepo () {
    return this.customPath || process.env.BEATLAB_HOME || path.join(process.cwd(), 'modules')
  }

  loadModuleManifest (moduleName) {
    const moduleFullPath = this.resolveModulePath(moduleName)
    const manifestPath = path.join(moduleFullPath, 'module.yml')

    if (!fs.existsSync(manifestPath)) throw new Error(`Module not found: /"${moduleName}/".`)

    const readFile = (path) => fs.readFileSync(path, 'utf-8').toString()
    const manifest = yaml.safeLoad(readFile(manifestPath), 'utf8')

    manifest.moduleName = moduleName

    return manifest
  }

  resolveModulePath (moduleName) {
    return path.join(this.moduleRepo(), moduleName)
  }

  resolveSlidePath (moduleName, slideName) {
    const moduleFullPath = this.resolveModulePath(moduleName)
    const slideFullPath = path.join(moduleFullPath, slideName)
    if (!fs.existsSync(slideFullPath)) throw new Error('Slide not found.')
    return slideFullPath
  }
}

module.exports = Loader


text:
package edu.pdx.spi.verticles;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.Objects;
import java.util.Optional;

import static edu.pdx.spi.ChannelNames.ALL_ALERTS;
import static edu.pdx.spi.ChannelNames.STREAM_RESTART;

public class SstoreConnector extends AbstractVerticle {
  Socket socket;
  InputStream inputStream;
  OutputStream outputStream;
  PrintWriter socketWriter;
  BufferedReader socketReader;
  EventBus eb;
  String host;
  int port;
  boolean reconnecting;

  @Override
  public void start() {
    eb = vertx.eventBus();
    host = this.config().getString("sstoreClientHost");
    port = this.config().getInteger("sstoreClientPort");
    reconnecting = true;
    openSocket(host, port);
    retryOpen();

    eb.consumer("sstore", msg -> {
      JsonObject jmsg = (JsonObject)msg.body();
      String queryType = jmsg.getString("query");
      Optional<JsonObject> outMsg;
      //long startTime = System.nanoTime();
      outMsg = !reconnecting ? query(jmsg.getString("query"), jmsg.getString("id")) : Optional.empty();
      //long endTime = System.nanoTime();
      //System.out.println("Query took " + (endTime-startTime)/1000000 + " ms.");
      if (outMsg.isPresent() && !queryType.equals("alert")) {
        // Send to specific channels for web.
        eb.publish(jmsg.getString("channel"), outMsg.get());
      } else if (outMsg.isPresent()) {
        eb.publish(jmsg.getString("channel"), outMsg.get());
        eb.publish(ALL_ALERTS, outMsg.get());
      }
    });
  }

  private void openSocket(String hostname, int port) {
    try {
      if (Objects.nonNull(socket)) {
        socket.close();
      }
      socket = new Socket(hostname, port);
      socket.setSoTimeout(5000);
      System.out.println("Connected to S-Store client.");
      reconnecting = false;
      eb.publish(STREAM_RESTART, System.currentTimeMillis());
    } catch (UnknownHostException e) {
      throw new RuntimeException("Error resolving S-Store client hostname: " + e.getMessage());
    } catch (IOException e) {
      System.out.println("Connection refused to S-Store client. Trying again in 1 second.");
      reconnecting = false;
    }

    try {
      inputStream = socket.getInputStream();
      outputStream = socket.getOutputStream();
    } catch (IOException e) {
      throw new RuntimeException("Error getting input/output stream from socket: " + e.getMessage());
    }

    socketWriter = new PrintWriter(outputStream, true);
    socketReader = new BufferedReader(new InputStreamReader(inputStream));
  }

  private void retryOpen() {
    if (!socket.isConnected() && !reconnecting) {
      reconnecting = true;
      vertx.setPeriodic(5000, h -> {
        openSocket(host, port);
        if (socket.isConnected()) {
          vertx.cancelTimer(h);
        }
      });
    }
  }

  private Optional<JsonObject> query(String type, String userId) {
    JsonObject resp;
    String queryText;
    // Figure out which query to run.
    //TODO: Fix this for more query types once they are added.
    if (!type.equals("alert")) {
      // Handle a waveform request.
      //TODO: What proc should we be calling here?
      //TODO: Fix these constants once the extra data is there.
      JsonArray args = new JsonArray().add(type).add(Integer.valueOf(userId));
      queryText = new JsonObject().put("proc", "GetSingleWaveform").put("args", args).encode();
    } else {
      // Handle alerts
      JsonArray args = new JsonArray().add(Integer.valueOf(userId));
      queryText = new JsonObject().put("proc", "GetRecentAlerts").put("args", args).encode();
    }
    socketWriter.println(queryText);

    try {
      JsonObject response = new JsonObject(socketReader.readLine());
      if (!type.equals("alert")) {
        // Sort the timestamps. Temp solution until s-store returns the data presorted.
        Collections.sort(response.getJsonArray("data").getList(), comp);
        resp = response;
      } else {
        resp = response.getJsonArray("data").getList().isEmpty() ? null : response;
      }
    } catch (IOException e) {
      reconnecting = true;
      openSocket(host, port);
      retryOpen();
      System.out.println("Error reading from socket: " + e.getMessage());
      resp = null;
    } catch (ClassCastException e) {
      resp = null;
    }
    catch (Exception e) {
      reconnecting = true;
      openSocket(host, port);
      retryOpen();
      System.out.println("Some error: " + e);
      resp = null;
    }

    return Optional.ofNullable(resp);
  }
  Comparator<LinkedHashMap<String, Object>> comp = (o1, o2) -> Integer.compare((Integer)o1.get("TS"), (Integer)o2.get("TS"));
}


text:
package org.webinos.api.gallery;

import org.meshpoint.anode.bridge.Env;
import org.meshpoint.anode.java.Base;
import org.webinos.api.PendingOperation;

public abstract class GalleryManager extends Base {
	private static short classId = Env.getInterfaceId(GalleryManager.class);
	protected GalleryManager() { super(classId); }

	public static final int AUDIO_TYPE = 0;
	public static final int VIDEO_TYPE = 1;
	public static final int IMAGE_TYPE = 2;
	public static final int SORT_BY_FILENAME = 3;
	public static final int SORT_BY_FILEDATE = 4;
	public static final int SORT_BY_MEDIATYPE = 5;
	public static final int SORT_BY_TITLE = 6;
	public static final int SORT_BY_AUTHOR = 7;
	public static final int SORT_BY_ALBUM = 8;
	public static final int SORT_BY_DATE = 9;
	public static final int SORT_BY_ASCENDING = 10;
	public static final int SORT_BY_DESCENDING = 11;

	public int length;

	public abstract PendingOperation find (String[] fields, GalleryFindCB successCB, GalleryErrorCB errorCB, GalleryFindOptions options);
	public abstract PendingOperation getGalleries (GalleryInfoCB successCB, GalleryErrorCB errorCB);
}


text:
#include "config.h"
#include "DragController.h"

#include "HTMLAnchorElement.h"
#include "SVGAElement.h"

#if ENABLE(DRAG_SUPPORT)
#include "CachedImage.h"
#include "CachedResourceLoader.h"
#include "DataTransfer.h"
#include "Document.h"
#include "DocumentFragment.h"
#include "DragActions.h"
#include "DragClient.h"
#include "DragData.h"
#include "DragImage.h"
#include "DragState.h"
#include "Editing.h"
#include "Editor.h"
#include "EditorClient.h"
#include "ElementAncestorIterator.h"
#include "EventHandler.h"
#include "FloatRect.h"
#include "FocusController.h"
#include "FrameLoadRequest.h"
#include "FrameLoader.h"
#include "FrameSelection.h"
#include "FrameView.h"
#include "HTMLAttachmentElement.h"
#include "HTMLImageElement.h"
#include "HTMLInputElement.h"
#include "HTMLParserIdioms.h"
#include "HTMLPlugInElement.h"
#include "HitTestRequest.h"
#include "HitTestResult.h"
#include "Image.h"
#include "ImageOrientation.h"
#include "MainFrame.h"
#include "MoveSelectionCommand.h"
#include "Page.h"
#include "Pasteboard.h"
#include "PlatformKeyboardEvent.h"
#include "PluginDocument.h"
#include "PluginViewBase.h"
#include "Position.h"
#include "RenderAttachment.h"
#include "RenderFileUploadControl.h"
#include "RenderImage.h"
#include "RenderView.h"
#include "ReplaceSelectionCommand.h"
#include "ResourceRequest.h"
#include "SecurityOrigin.h"
#include "Settings.h"
#include "ShadowRoot.h"
#include "StyleProperties.h"
#include "Text.h"
#include "TextEvent.h"
#include "VisiblePosition.h"
#include "markup.h"

#if ENABLE(DATA_INTERACTION)
#include "SelectionRect.h"
#endif

#include <wtf/CurrentTime.h>
#include <wtf/RefPtr.h>
#include <wtf/SetForScope.h>
#endif

#if ENABLE(DATA_DETECTION)
#include "DataDetection.h"
#endif

namespace WebCore {

bool isDraggableLink(const Element& element)
{
    if (is<HTMLAnchorElement>(element)) {
        auto& anchorElement = downcast<HTMLAnchorElement>(element);
        if (!anchorElement.isLiveLink())
            return false;
#if ENABLE(DATA_DETECTION)
        return !DataDetection::isDataDetectorURL(anchorElement.href());
#else
        return true;
#endif
    }
    if (is<SVGAElement>(element))
        return element.isLink();
    return false;
}

#if ENABLE(DRAG_SUPPORT)

static PlatformMouseEvent createMouseEvent(const DragData& dragData)
{
    bool shiftKey = false;
    bool ctrlKey = false;
    bool altKey = false;
    bool metaKey = false;

    PlatformKeyboardEvent::getCurrentModifierState(shiftKey, ctrlKey, altKey, metaKey);

    return PlatformMouseEvent(dragData.clientPosition(), dragData.globalPosition(),
                              LeftButton, PlatformEvent::MouseMoved, 0, shiftKey, ctrlKey, altKey,
                              metaKey, WallTime::now(), ForceAtClick, NoTap);
}

DragController::DragController(Page& page, DragClient& client)
    : m_page(page)
    , m_client(client)
    , m_numberOfItemsToBeAccepted(0)
    , m_dragHandlingMethod(DragHandlingMethod::None)
    , m_dragDestinationAction(DragDestinationActionNone)
    , m_dragSourceAction(DragSourceActionNone)
    , m_didInitiateDrag(false)
    , m_sourceDragOperation(DragOperationNone)
{
}

DragController::~DragController()
{
    m_client.dragControllerDestroyed();
}

static RefPtr<DocumentFragment> documentFragmentFromDragData(const DragData& dragData, Frame& frame, Range& context, bool allowPlainText, bool& chosePlainText)
{
    chosePlainText = false;

    Document& document = context.ownerDocument();
    if (dragData.containsCompatibleContent()) {
        if (auto fragment = frame.editor().webContentFromPasteboard(*Pasteboard::createForDragAndDrop(dragData), context, allowPlainText, chosePlainText))
            return fragment;

        if (dragData.containsURL(DragData::DoNotConvertFilenames)) {
            String title;
            String url = dragData.asURL(DragData::DoNotConvertFilenames, &title);
            if (!url.isEmpty()) {
                auto anchor = HTMLAnchorElement::create(document);
                anchor->setHref(url);
                if (title.isEmpty()) {
                    // Try the plain text first because the url might be normalized or escaped.
                    if (dragData.containsPlainText())
                        title = dragData.asPlainText();
                    if (title.isEmpty())
                        title = url;
                }
                anchor->appendChild(document.createTextNode(title));
                auto fragment = document.createDocumentFragment();
                fragment->appendChild(anchor);
                return WTFMove(fragment);
            }
        }
    }
    if (allowPlainText && dragData.containsPlainText()) {
        chosePlainText = true;
        return createFragmentFromText(context, dragData.asPlainText()).ptr();
    }

    return nullptr;
}

#if !PLATFORM(IOS)

DragOperation DragController::platformGenericDragOperation()
{
    return DragOperationMove;
}

#endif

bool DragController::dragIsMove(FrameSelection& selection, const DragData& dragData)
{
    const VisibleSelection& visibleSelection = selection.selection();
    return m_documentUnderMouse == m_dragInitiator && visibleSelection.isContentEditable() && visibleSelection.isRange() && !isCopyKeyDown(dragData);
}

void DragController::clearDragCaret()
{
    m_page.dragCaretController().clear();
}

void DragController::dragEnded()
{
    m_dragInitiator = nullptr;
    m_didInitiateDrag = false;
    m_documentUnderMouse = nullptr;
    clearDragCaret();

    m_client.dragEnded();
}

DragOperation DragController::dragEntered(const DragData& dragData)
{
    return dragEnteredOrUpdated(dragData);
}

void DragController::dragExited(const DragData& dragData)
{
    auto& mainFrame = m_page.mainFrame();
    if (mainFrame.view())
        mainFrame.eventHandler().cancelDragAndDrop(createMouseEvent(dragData), Pasteboard::createForDragAndDrop(dragData), dragData.draggingSourceOperationMask(), dragData.containsFiles());
    mouseMovedIntoDocument(nullptr);
    if (m_fileInputElementUnderMouse)
        m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
    m_fileInputElementUnderMouse = nullptr;
}

DragOperation DragController::dragUpdated(const DragData& dragData)
{
    return dragEnteredOrUpdated(dragData);
}

inline static bool dragIsHandledByDocument(DragController::DragHandlingMethod dragHandlingMethod)
{
    if (dragHandlingMethod == DragController::DragHandlingMethod::None)
        return false;

    if (dragHandlingMethod == DragController::DragHandlingMethod::PageLoad)
        return false;

    return true;
}

bool DragController::performDragOperation(const DragData& dragData)
{
    SetForScope<bool> isPerformingDrop(m_isPerformingDrop, true);
    TemporarySelectionChange ignoreSelectionChanges(m_page.focusController().focusedOrMainFrame(), std::nullopt, TemporarySelectionOptionIgnoreSelectionChanges);

    m_documentUnderMouse = m_page.mainFrame().documentAtPoint(dragData.clientPosition());

    ShouldOpenExternalURLsPolicy shouldOpenExternalURLsPolicy = ShouldOpenExternalURLsPolicy::ShouldNotAllow;
    if (m_documentUnderMouse)
        shouldOpenExternalURLsPolicy = m_documentUnderMouse->shouldOpenExternalURLsPolicyToPropagate();

    if ((m_dragDestinationAction & DragDestinationActionDHTML) && dragIsHandledByDocument(m_dragHandlingMethod)) {
        m_client.willPerformDragDestinationAction(DragDestinationActionDHTML, dragData);
        Ref<MainFrame> mainFrame(m_page.mainFrame());
        bool preventedDefault = false;
        if (mainFrame->view())
            preventedDefault = mainFrame->eventHandler().performDragAndDrop(createMouseEvent(dragData), Pasteboard::createForDragAndDrop(dragData), dragData.draggingSourceOperationMask(), dragData.containsFiles());
        if (preventedDefault) {
            clearDragCaret();
            m_documentUnderMouse = nullptr;
            return true;
        }
    }

    if ((m_dragDestinationAction & DragDestinationActionEdit) && concludeEditDrag(dragData)) {
        m_client.didConcludeEditDrag();
        m_documentUnderMouse = nullptr;
        clearDragCaret();
        return true;
    }

    m_documentUnderMouse = nullptr;
    clearDragCaret();

    if (operationForLoad(dragData) == DragOperationNone)
        return false;

    auto urlString = dragData.asURL();
    if (urlString.isEmpty())
        return false;

    m_client.willPerformDragDestinationAction(DragDestinationActionLoad, dragData);
    m_page.mainFrame().loader().load(FrameLoadRequest(m_page.mainFrame(), { urlString }, shouldOpenExternalURLsPolicy));
    return true;
}

void DragController::mouseMovedIntoDocument(Document* newDocument)
{
    if (m_documentUnderMouse == newDocument)
        return;

    // If we were over another document clear the selection
    if (m_documentUnderMouse)
        clearDragCaret();
    m_documentUnderMouse = newDocument;
}

DragOperation DragController::dragEnteredOrUpdated(const DragData& dragData)
{
    mouseMovedIntoDocument(m_page.mainFrame().documentAtPoint(dragData.clientPosition()));

    m_dragDestinationAction = dragData.dragDestinationAction();
    if (m_dragDestinationAction == DragDestinationActionNone) {
        clearDragCaret(); // FIXME: Why not call mouseMovedIntoDocument(nullptr)?
        return DragOperationNone;
    }

    DragOperation dragOperation = DragOperationNone;
    m_dragHandlingMethod = tryDocumentDrag(dragData, m_dragDestinationAction, dragOperation);
    if (m_dragHandlingMethod == DragHandlingMethod::None && (m_dragDestinationAction & DragDestinationActionLoad)) {
        dragOperation = operationForLoad(dragData);
        if (dragOperation != DragOperationNone)
            m_dragHandlingMethod = DragHandlingMethod::PageLoad;
    }

    updateSupportedTypeIdentifiersForDragHandlingMethod(m_dragHandlingMethod, dragData);
    return dragOperation;
}

static HTMLInputElement* asFileInput(Node& node)
{
    if (!is<HTMLInputElement>(node))
        return nullptr;

    auto* inputElement = &downcast<HTMLInputElement>(node);

    // If this is a button inside of the a file input, move up to the file input.
    if (inputElement->isTextButton() && is<ShadowRoot>(inputElement->treeScope().rootNode())) {
        auto& host = *downcast<ShadowRoot>(inputElement->treeScope().rootNode()).host();
        inputElement = is<HTMLInputElement>(host) ? &downcast<HTMLInputElement>(host) : nullptr;
    }

    return inputElement && inputElement->isFileUpload() ? inputElement : nullptr;
}

// This can return null if an empty document is loaded.
static Element* elementUnderMouse(Document* documentUnderMouse, const IntPoint& p)
{
    Frame* frame = documentUnderMouse->frame();
    float zoomFactor = frame ? frame->pageZoomFactor() : 1;
    LayoutPoint point(p.x() * zoomFactor, p.y() * zoomFactor);

    HitTestResult result(point);
    documentUnderMouse->renderView()->hitTest(HitTestRequest(), result);

    Node* node = result.innerNode();
    while (node && !is<Element>(*node))
        node = node->parentNode();
    if (node)
        node = node->deprecatedShadowAncestorNode();

    return downcast<Element>(node);
}

#if !ENABLE(DATA_INTERACTION)

void DragController::updateSupportedTypeIdentifiersForDragHandlingMethod(DragHandlingMethod, const DragData&) const
{
}

#endif

DragController::DragHandlingMethod DragController::tryDocumentDrag(const DragData& dragData, DragDestinationAction actionMask, DragOperation& dragOperation)
{
    if (!m_documentUnderMouse)
        return DragHandlingMethod::None;

    if (m_dragInitiator && !m_documentUnderMouse->securityOrigin().canReceiveDragData(m_dragInitiator->securityOrigin()))
        return DragHandlingMethod::None;

    bool isHandlingDrag = false;
    if (actionMask & DragDestinationActionDHTML) {
        isHandlingDrag = tryDHTMLDrag(dragData, dragOperation);
        // Do not continue if m_documentUnderMouse has been reset by tryDHTMLDrag.
        // tryDHTMLDrag fires dragenter event. The event listener that listens
        // to this event may create a nested message loop (open a modal dialog),
        // which could process dragleave event and reset m_documentUnderMouse in
        // dragExited.
        if (!m_documentUnderMouse)
            return DragHandlingMethod::None;
    }

    // It's unclear why this check is after tryDHTMLDrag.
    // We send drag events in tryDHTMLDrag and that may be the reason.
    RefPtr<FrameView> frameView = m_documentUnderMouse->view();
    if (!frameView)
        return DragHandlingMethod::None;

    if (isHandlingDrag) {
        clearDragCaret();
        return DragHandlingMethod::NonDefault;
    }

    if ((actionMask & DragDestinationActionEdit) && canProcessDrag(dragData)) {
        if (dragData.containsColor()) {
            dragOperation = DragOperationGeneric;
            return DragHandlingMethod::SetColor;
        }

        IntPoint point = frameView->windowToContents(dragData.clientPosition());
        Element* element = elementUnderMouse(m_documentUnderMouse.get(), point);
        if (!element)
            return DragHandlingMethod::None;

        HTMLInputElement* elementAsFileInput = asFileInput(*element);
        if (m_fileInputElementUnderMouse != elementAsFileInput) {
            if (m_fileInputElementUnderMouse)
                m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
            m_fileInputElementUnderMouse = elementAsFileInput;
        }

        if (!m_fileInputElementUnderMouse)
            m_page.dragCaretController().setCaretPosition(m_documentUnderMouse->frame()->visiblePositionForPoint(point));
        else
            clearDragCaret();

        Frame* innerFrame = element->document().frame();
        dragOperation = dragIsMove(innerFrame->selection(), dragData) ? DragOperationMove : DragOperationCopy;
        m_numberOfItemsToBeAccepted = 0;

        unsigned numberOfFiles = dragData.numberOfFiles();
        if (m_fileInputElementUnderMouse) {
            if (m_fileInputElementUnderMouse->isDisabledFormControl())
                m_numberOfItemsToBeAccepted = 0;
            else if (m_fileInputElementUnderMouse->multiple())
                m_numberOfItemsToBeAccepted = numberOfFiles;
            else if (numberOfFiles > 1)
                m_numberOfItemsToBeAccepted = 0;
            else
                m_numberOfItemsToBeAccepted = 1;

            if (!m_numberOfItemsToBeAccepted)
                dragOperation = DragOperationNone;
            m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(m_numberOfItemsToBeAccepted);
        } else {
            // We are not over a file input element. The dragged item(s) will only
            // be loaded into the view the number of dragged items is 1.
            m_numberOfItemsToBeAccepted = numberOfFiles != 1 ? 0 : 1;
        }

        if (m_fileInputElementUnderMouse)
            return DragHandlingMethod::UploadFile;

        if (m_page.dragCaretController().isContentRichlyEditable())
            return DragHandlingMethod::EditRichText;

        return DragHandlingMethod::EditPlainText;
    }

    // We are not over an editable region. Make sure we're clearing any prior drag cursor.
    clearDragCaret();
    if (m_fileInputElementUnderMouse)
        m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
    m_fileInputElementUnderMouse = nullptr;
    return DragHandlingMethod::None;
}

DragSourceAction DragController::delegateDragSourceAction(const IntPoint& rootViewPoint)
{
    m_dragSourceAction = m_client.dragSourceActionMaskForPoint(rootViewPoint);
    return m_dragSourceAction;
}

DragOperation DragController::operationForLoad(const DragData& dragData)
{
    Document* document = m_page.mainFrame().documentAtPoint(dragData.clientPosition());

    bool pluginDocumentAcceptsDrags = false;

    if (is<PluginDocument>(document)) {
        const Widget* widget = downcast<PluginDocument>(*document).pluginWidget();
        const PluginViewBase* pluginView = is<PluginViewBase>(widget) ? downcast<PluginViewBase>(widget) : nullptr;

        if (pluginView)
            pluginDocumentAcceptsDrags = pluginView->shouldAllowNavigationFromDrags();
    }

    if (document && (m_didInitiateDrag || (is<PluginDocument>(*document) && !pluginDocumentAcceptsDrags) || document->hasEditableStyle()))
        return DragOperationNone;
    return dragOperation(dragData);
}

static bool setSelectionToDragCaret(Frame* frame, VisibleSelection& dragCaret, RefPtr<Range>& range, const IntPoint& point)
{
    Ref<Frame> protector(*frame);
    frame->selection().setSelection(dragCaret);
    if (frame->selection().selection().isNone()) {
        dragCaret = frame->visiblePositionForPoint(point);
        frame->selection().setSelection(dragCaret);
        range = dragCaret.toNormalizedRange();
    }
    return !frame->selection().isNone() && frame->selection().selection().isContentEditable();
}

bool DragController::dispatchTextInputEventFor(Frame* innerFrame, const DragData& dragData)
{
    ASSERT(m_page.dragCaretController().hasCaret());
    String text = m_page.dragCaretController().isContentRichlyEditable() ? emptyString() : dragData.asPlainText();
    Element* target = innerFrame->editor().findEventTargetFrom(m_page.dragCaretController().caretPosition());
    // FIXME: What guarantees target is not null?
    auto event = TextEvent::createForDrop(innerFrame->document()->domWindow(), text);
    target->dispatchEvent(event);
    return !event->defaultPrevented();
}

bool DragController::concludeEditDrag(const DragData& dragData)
{
    RefPtr<HTMLInputElement> fileInput = m_fileInputElementUnderMouse;
    if (m_fileInputElementUnderMouse) {
        m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
        m_fileInputElementUnderMouse = nullptr;
    }

    if (!m_documentUnderMouse)
        return false;

    IntPoint point = m_documentUnderMouse->view()->windowToContents(dragData.clientPosition());
    Element* element = elementUnderMouse(m_documentUnderMouse.get(), point);
    if (!element)
        return false;
    RefPtr<Frame> innerFrame = element->document().frame();
    ASSERT(innerFrame);

    if (m_page.dragCaretController().hasCaret() && !dispatchTextInputEventFor(innerFrame.get(), dragData))
        return true;

    if (dragData.containsColor()) {
        Color color = dragData.asColor();
        if (!color.isValid())
            return false;
        RefPtr<Range> innerRange = innerFrame->selection().toNormalizedRange();
        if (!innerRange)
            return false;
        RefPtr<MutableStyleProperties> style = MutableStyleProperties::create();
        style->setProperty(CSSPropertyColor, color.serialized(), false);
        if (!innerFrame->editor().shouldApplyStyle(style.get(), innerRange.get()))
            return false;
        m_client.willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
        innerFrame->editor().applyStyle(style.get(), EditActionSetColor);
        return true;
    }

    if (dragData.containsFiles() && fileInput) {
        // fileInput should be the element we hit tested for, unless it was made
        // display:none in a drop event handler.
        ASSERT(fileInput == element || !fileInput->renderer());
        if (fileInput->isDisabledFormControl())
            return false;

        return fileInput->receiveDroppedFiles(dragData);
    }

    if (!m_page.dragController().canProcessDrag(dragData))
        return false;

    VisibleSelection dragCaret = m_page.dragCaretController().caretPosition();
    RefPtr<Range> range = dragCaret.toNormalizedRange();
    RefPtr<Element> rootEditableElement = innerFrame->selection().selection().rootEditableElement();

    // For range to be null a WebKit client must have done something bad while
    // manually controlling drag behaviour
    if (!range)
        return false;

    ResourceCacheValidationSuppressor validationSuppressor(range->ownerDocument().cachedResourceLoader());
    auto& editor = innerFrame->editor();
    bool isMove = dragIsMove(innerFrame->selection(), dragData);
    if (isMove || dragCaret.isContentRichlyEditable()) {
        bool chosePlainText = false;
        RefPtr<DocumentFragment> fragment = documentFragmentFromDragData(dragData, *innerFrame, *range, true, chosePlainText);
        if (!fragment || !editor.shouldInsertFragment(*fragment, range.get(), EditorInsertAction::Dropped))
            return false;

        m_client.willPerformDragDestinationAction(DragDestinationActionEdit, dragData);

        if (editor.client() && editor.client()->performTwoStepDrop(*fragment, *range, isMove))
            return true;

        if (isMove) {
            // NSTextView behavior is to always smart delete on moving a selection,
            // but only to smart insert if the selection granularity is word granularity.
            bool smartDelete = editor.smartInsertDeleteEnabled();
            bool smartInsert = smartDelete && innerFrame->selection().granularity() == WordGranularity && dragData.canSmartReplace();
            MoveSelectionCommand::create(fragment.releaseNonNull(), dragCaret.base(), smartInsert, smartDelete)->apply();
        } else {
            if (setSelectionToDragCaret(innerFrame.get(), dragCaret, range, point)) {
                ReplaceSelectionCommand::CommandOptions options = ReplaceSelectionCommand::SelectReplacement | ReplaceSelectionCommand::PreventNesting;
                if (dragData.canSmartReplace())
                    options |= ReplaceSelectionCommand::SmartReplace;
                if (chosePlainText)
                    options |= ReplaceSelectionCommand::MatchStyle;
                ReplaceSelectionCommand::create(*m_documentUnderMouse, fragment.releaseNonNull(), options, EditActionInsertFromDrop)->apply();
            }
        }
    } else {
        String text = dragData.asPlainText();
        if (text.isEmpty() || !editor.shouldInsertText(text, range.get(), EditorInsertAction::Dropped))
            return false;

        m_client.willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
        RefPtr<DocumentFragment> fragment = createFragmentFromText(*range, text);
        if (!fragment)
            return false;

        if (editor.client() && editor.client()->performTwoStepDrop(*fragment, *range, isMove))
            return true;

        if (setSelectionToDragCaret(innerFrame.get(), dragCaret, range, point))
            ReplaceSelectionCommand::create(*m_documentUnderMouse, fragment.get(), ReplaceSelectionCommand::SelectReplacement | ReplaceSelectionCommand::MatchStyle | ReplaceSelectionCommand::PreventNesting, EditActionInsertFromDrop)->apply();
    }

    if (rootEditableElement) {
        if (Frame* frame = rootEditableElement->document().frame())
            frame->eventHandler().updateDragStateAfterEditDragIfNeeded(*rootEditableElement);
    }

    return true;
}

bool DragController::canProcessDrag(const DragData& dragData)
{
    IntPoint point = m_page.mainFrame().view()->windowToContents(dragData.clientPosition());
    HitTestResult result = HitTestResult(point);
    if (!m_page.mainFrame().contentRenderer())
        return false;

    result = m_page.mainFrame().eventHandler().hitTestResultAtPoint(point, HitTestRequest::ReadOnly | HitTestRequest::Active);

    if (!result.innerNonSharedNode())
        return false;

    DragData::DraggingPurpose dragPurpose = DragData::DraggingPurpose::ForEditing;
    if (asFileInput(*result.innerNonSharedNode()))
        dragPurpose = DragData::DraggingPurpose::ForFileUpload;

    if (!dragData.containsCompatibleContent(dragPurpose))
        return false;

    if (dragPurpose == DragData::DraggingPurpose::ForFileUpload)
        return true;

    if (is<HTMLPlugInElement>(*result.innerNonSharedNode())) {
        if (!downcast<HTMLPlugInElement>(result.innerNonSharedNode())->canProcessDrag() && !result.innerNonSharedNode()->hasEditableStyle())
            return false;
    } else if (!result.innerNonSharedNode()->hasEditableStyle())
        return false;

    if (m_didInitiateDrag && m_documentUnderMouse == m_dragInitiator && result.isSelected())
        return false;

    return true;
}

static DragOperation defaultOperationForDrag(DragOperation srcOpMask)
{
    // This is designed to match IE's operation fallback for the case where
    // the page calls preventDefault() in a drag event but doesn't set dropEffect.
    if (srcOpMask == DragOperationEvery)
        return DragOperationCopy;
    if (srcOpMask == DragOperationNone)
        return DragOperationNone;
    if (srcOpMask & DragOperationMove)
        return DragOperationMove;
    if (srcOpMask & DragOperationGeneric)
        return DragController::platformGenericDragOperation();
    if (srcOpMask & DragOperationCopy)
        return DragOperationCopy;
    if (srcOpMask & DragOperationLink)
        return DragOperationLink;

    // FIXME: Does IE really return "generic" even if no operations were allowed by the source?
    return DragOperationGeneric;
}

bool DragController::tryDHTMLDrag(const DragData& dragData, DragOperation& operation)
{
    ASSERT(m_documentUnderMouse);
    Ref<MainFrame> mainFrame(m_page.mainFrame());
    RefPtr<FrameView> viewProtector = mainFrame->view();
    if (!viewProtector)
        return false;

    DragOperation sourceOperation = dragData.draggingSourceOperationMask();
    auto targetResponse = mainFrame->eventHandler().updateDragAndDrop(createMouseEvent(dragData), [&dragData]() { return Pasteboard::createForDragAndDrop(dragData); }, sourceOperation, dragData.containsFiles());
    if (!targetResponse.accept)
        return false;

    if (!targetResponse.operation)
        operation = defaultOperationForDrag(sourceOperation);
    else if (!(sourceOperation & targetResponse.operation.value())) // The element picked an operation which is not supported by the source
        operation = DragOperationNone;
    else
        operation = targetResponse.operation.value();

    return true;
}

static bool imageElementIsDraggable(const HTMLImageElement& image, const Frame& sourceFrame)
{
    if (sourceFrame.settings().loadsImagesAutomatically())
        return true;

    auto* renderer = image.renderer();
    if (!is<RenderImage>(renderer))
        return false;

    auto* cachedImage = downcast<RenderImage>(*renderer).cachedImage();
    return cachedImage && !cachedImage->errorOccurred() && cachedImage->imageForRenderer(renderer);
}

Element* DragController::draggableElement(const Frame* sourceFrame, Element* startElement, const IntPoint& dragOrigin, DragState& state) const
{
    state.type = (sourceFrame->selection().contains(dragOrigin)) ? DragSourceActionSelection : DragSourceActionNone;
    if (!startElement)
        return nullptr;
#if ENABLE(ATTACHMENT_ELEMENT)
    if (is<HTMLAttachmentElement>(startElement)) {
        auto selection = sourceFrame->selection().selection();
        bool isSingleAttachmentSelection = selection.start() == Position(startElement, Position::PositionIsBeforeAnchor) && selection.end() == Position(startElement, Position::PositionIsAfterAnchor);
        bool isAttachmentElementInCurrentSelection = false;
        if (auto selectedRange = selection.toNormalizedRange()) {
            auto compareResult = selectedRange->compareNode(*startElement);
            isAttachmentElementInCurrentSelection = !compareResult.hasException() && compareResult.releaseReturnValue() == Range::NODE_INSIDE;
        }

        if (!isAttachmentElementInCurrentSelection || isSingleAttachmentSelection) {
            state.type = DragSourceActionAttachment;
            return startElement;
        }
    }
#endif

    for (auto* element = startElement; element; element = element->parentOrShadowHostElement()) {
        auto* renderer = element->renderer();
        if (!renderer)
            continue;

        EUserDrag dragMode = renderer->style().userDrag();
        if ((m_dragSourceAction & DragSourceActionDHTML) && dragMode == DRAG_ELEMENT) {
            state.type = static_cast<DragSourceAction>(state.type | DragSourceActionDHTML);
            return element;
        }
        if (dragMode == DRAG_AUTO) {
            if ((m_dragSourceAction & DragSourceActionImage)
                && is<HTMLImageElement>(*element)
                && imageElementIsDraggable(downcast<HTMLImageElement>(*element), *sourceFrame)) {
                state.type = static_cast<DragSourceAction>(state.type | DragSourceActionImage);
                return element;
            }
            if ((m_dragSourceAction & DragSourceActionLink) && isDraggableLink(*element)) {
                state.type = static_cast<DragSourceAction>(state.type | DragSourceActionLink);
                return element;
            }
#if ENABLE(ATTACHMENT_ELEMENT)
            if ((m_dragSourceAction & DragSourceActionAttachment)
                && is<HTMLAttachmentElement>(*element)
                && downcast<HTMLAttachmentElement>(*element).file()) {
                state.type = static_cast<DragSourceAction>(state.type | DragSourceActionAttachment);
                return element;
            }
#endif
        }
    }

    // We either have nothing to drag or we have a selection and we're not over a draggable element.
    return (state.type & DragSourceActionSelection) ? startElement : nullptr;
}

static CachedImage* getCachedImage(Element& element)
{
    RenderObject* renderer = element.renderer();
    if (!is<RenderImage>(renderer))
        return nullptr;
    auto& image = downcast<RenderImage>(*renderer);
    return image.cachedImage();
}

static Image* getImage(Element& element)
{
    CachedImage* cachedImage = getCachedImage(element);
    // Don't use cachedImage->imageForRenderer() here as that may return BitmapImages for cached SVG Images.
    // Users of getImage() want access to the SVGImage, in order to figure out the filename extensions,
    // which would be empty when asking the cached BitmapImages.
    return (cachedImage && !cachedImage->errorOccurred()) ?
        cachedImage->image() : nullptr;
}

static void selectElement(Element& element)
{
    RefPtr<Range> range = element.document().createRange();
    range->selectNode(element);
    element.document().frame()->selection().setSelection(VisibleSelection(*range, DOWNSTREAM));
}

static IntPoint dragLocForDHTMLDrag(const IntPoint& mouseDraggedPoint, const IntPoint& dragOrigin, const IntPoint& dragImageOffset, bool isLinkImage)
{
    // dragImageOffset is the cursor position relative to the lower-left corner of the image.
#if PLATFORM(MAC)
    // We add in the Y dimension because we are a flipped view, so adding moves the image down.
    const int yOffset = dragImageOffset.y();
#else
    const int yOffset = -dragImageOffset.y();
#endif

    if (isLinkImage)
        return IntPoint(mouseDraggedPoint.x() - dragImageOffset.x(), mouseDraggedPoint.y() + yOffset);

    return IntPoint(dragOrigin.x() - dragImageOffset.x(), dragOrigin.y() + yOffset);
}

static FloatPoint dragImageAnchorPointForSelectionDrag(Frame& frame, const IntPoint& mouseDraggedPoint)
{
    IntRect draggingRect = enclosingIntRect(frame.selection().selectionBounds());

    float x = (mouseDraggedPoint.x() - draggingRect.x()) / (float)draggingRect.width();
    float y = (mouseDraggedPoint.y() - draggingRect.y()) / (float)draggingRect.height();

    return FloatPoint { x, y };
}

static IntPoint dragLocForSelectionDrag(Frame& src)
{
    IntRect draggingRect = enclosingIntRect(src.selection().selectionBounds());
    int xpos = draggingRect.maxX();
    xpos = draggingRect.x() < xpos ? draggingRect.x() : xpos;
    int ypos = draggingRect.maxY();
#if PLATFORM(COCOA)
    // Deal with flipped coordinates on Mac
    ypos = draggingRect.y() > ypos ? draggingRect.y() : ypos;
#else
    ypos = draggingRect.y() < ypos ? draggingRect.y() : ypos;
#endif
    return IntPoint(xpos, ypos);
}

bool DragController::startDrag(Frame& src, const DragState& state, DragOperation srcOp, const PlatformMouseEvent& dragEvent, const IntPoint& dragOrigin, HasNonDefaultPasteboardData hasData)
{
    if (!src.view() || !src.contentRenderer() || !state.source)
        return false;

    Ref<Frame> protector(src);
    HitTestResult hitTestResult = src.eventHandler().hitTestResultAtPoint(dragOrigin, HitTestRequest::ReadOnly | HitTestRequest::Active);

    // FIXME(136836): Investigate whether all elements should use the containsIncludingShadowDOM() path here.
    bool includeShadowDOM = false;
#if ENABLE(VIDEO)
    includeShadowDOM = state.source->isMediaElement();
#endif
    bool sourceContainsHitNode;
    if (!includeShadowDOM)
        sourceContainsHitNode = state.source->contains(hitTestResult.innerNode());
    else
        sourceContainsHitNode = state.source->containsIncludingShadowDOM(hitTestResult.innerNode());

    if (!sourceContainsHitNode) {
        // The original node being dragged isn't under the drag origin anymore... maybe it was
        // hidden or moved out from under the cursor. Regardless, we don't want to start a drag on
        // something that's not actually under the drag origin.
        return false;
    }

    URL linkURL = hitTestResult.absoluteLinkURL();
    URL imageURL = hitTestResult.absoluteImageURL();
#if ENABLE(ATTACHMENT_ELEMENT)
    URL attachmentURL = hitTestResult.absoluteAttachmentURL();
    m_draggingAttachmentURL = URL();
#endif

    IntPoint mouseDraggedPoint = src.view()->windowToContents(dragEvent.position());

    m_draggingImageURL = URL();
    m_sourceDragOperation = srcOp;

    DragImage dragImage;
    IntPoint dragLoc(0, 0);
    IntPoint dragImageOffset(0, 0);

    ASSERT(state.dataTransfer);

    DataTransfer& dataTransfer = *state.dataTransfer;
    if (state.type == DragSourceActionDHTML) {
        dragImage = DragImage { dataTransfer.createDragImage(dragImageOffset) };
        // We allow DHTML/JS to set the drag image, even if its a link, image or text we're dragging.
        // This is in the spirit of the IE API, which allows overriding of pasteboard data and DragOp.
        if (dragImage) {
            dragLoc = dragLocForDHTMLDrag(mouseDraggedPoint, dragOrigin, dragImageOffset, !linkURL.isEmpty());
            m_dragOffset = dragImageOffset;
        }
    }

    if (state.type == DragSourceActionSelection || !imageURL.isEmpty() || !linkURL.isEmpty()) {
        // Selection, image, and link drags receive a default set of allowed drag operations that
        // follows from:
        // http://trac.webkit.org/browser/trunk/WebKit/mac/WebView/WebHTMLView.mm?rev=48526#L3430
        m_sourceDragOperation = static_cast<DragOperation>(m_sourceDragOperation | DragOperationGeneric | DragOperationCopy);
    }

    ASSERT(state.source);
    Element& element = *state.source;

    bool mustUseLegacyDragClient = hasData == HasNonDefaultPasteboardData::Yes || m_client.useLegacyDragClient();

    IntRect dragImageBounds;
    Image* image = getImage(element);
    if (state.type == DragSourceActionSelection) {
        PasteboardWriterData pasteboardWriterData;

        if (hasData == HasNonDefaultPasteboardData::No) {
            if (src.selection().selection().isNone()) {
                // The page may have cleared out the selection in the dragstart handler, in which case we should bail
                // out of the drag, since there is no content to write to the pasteboard.
                return false;
            }

            // FIXME: This entire block is almost identical to the code in Editor::copy, and the code should be shared.
            RefPtr<Range> selectionRange = src.selection().toNormalizedRange();
            ASSERT(selectionRange);

            src.editor().willWriteSelectionToPasteboard(selectionRange.get());

            if (enclosingTextFormControl(src.selection().selection().start())) {
                if (mustUseLegacyDragClient)
                    dataTransfer.pasteboard().writePlainText(src.editor().selectedTextForDataTransfer(), Pasteboard::CannotSmartReplace);
                else {
                    PasteboardWriterData::PlainText plainText;
                    plainText.canSmartCopyOrDelete = false;
                    plainText.text = src.editor().selectedTextForDataTransfer();
                    pasteboardWriterData.setPlainText(WTFMove(plainText));
                }
            } else {
                if (mustUseLegacyDragClient) {
#if PLATFORM(COCOA) || PLATFORM(GTK)
                    src.editor().writeSelectionToPasteboard(dataTransfer.pasteboard());
#else
                    // FIXME: Convert all other platforms to match Mac and delete this.
                    dataTransfer.pasteboard().writeSelection(*selectionRange, src.editor().canSmartCopyOrDelete(), src, IncludeImageAltTextForDataTransfer);
#endif
                } else {
#if PLATFORM(COCOA)
                    src.editor().writeSelection(pasteboardWriterData);
#endif
                }
            }

            src.editor().didWriteSelectionToPasteboard();
        }
        m_client.willPerformDragSourceAction(DragSourceActionSelection, dragOrigin, dataTransfer);
        if (!dragImage) {
            TextIndicatorData textIndicator;
            dragImage = DragImage { dissolveDragImageToFraction(createDragImageForSelection(src, textIndicator), DragImageAlpha) };
            if (textIndicator.contentImage)
                dragImage.setIndicatorData(textIndicator);
            dragLoc = dragLocForSelectionDrag(src);
            m_dragOffset = IntPoint(dragOrigin.x() - dragLoc.x(), dragOrigin.y() - dragLoc.y());
        }

        if (!dragImage)
            return false;

        if (mustUseLegacyDragClient) {
            doSystemDrag(WTFMove(dragImage), dragLoc, dragOrigin, src, state);
            return true;
        }

        DragItem dragItem;
        dragItem.imageAnchorPoint = dragImageAnchorPointForSelectionDrag(src, mouseDraggedPoint);
        dragItem.image = WTFMove(dragImage);
        dragItem.data = WTFMove(pasteboardWriterData);

        beginDrag(WTFMove(dragItem), src, dragOrigin, mouseDraggedPoint, dataTransfer, DragSourceActionSelection);

        return true;
    }

    if (!src.document()->securityOrigin().canDisplay(linkURL)) {
        src.document()->addConsoleMessage(MessageSource::Security, MessageLevel::Error, "Not allowed to drag local resource: " + linkURL.stringCenterEllipsizedToLength());
        return false;
    }

    if (!imageURL.isEmpty() && image && !image->isNull() && (m_dragSourceAction & DragSourceActionImage)) {
        // We shouldn't be starting a drag for an image that can't provide an extension.
        // This is an early detection for problems encountered later upon drop.
        ASSERT(!image->filenameExtension().isEmpty());
        if (hasData == HasNonDefaultPasteboardData::No) {
            m_draggingImageURL = imageURL;
            if (element.isContentRichlyEditable())
                selectElement(element);
            declareAndWriteDragImage(dataTransfer, element, !linkURL.isEmpty() ? linkURL : imageURL, hitTestResult.altDisplayString());
        }

        m_client.willPerformDragSourceAction(DragSourceActionImage, dragOrigin, dataTransfer);

        if (!dragImage)
            doImageDrag(element, dragOrigin, hitTestResult.imageRect(), src, m_dragOffset, state);
        else {
            // DHTML defined drag image
            doSystemDrag(WTFMove(dragImage), dragLoc, dragOrigin, src, state);
        }

        return true;
    }

    if (!linkURL.isEmpty() && (m_dragSourceAction & DragSourceActionLink)) {
        PasteboardWriterData pasteboardWriterData;

        String textContentWithSimplifiedWhiteSpace = hitTestResult.textContent().simplifyWhiteSpace();

        if (hasData == HasNonDefaultPasteboardData::No) {
            // Simplify whitespace so the title put on the dataTransfer resembles what the user sees
            // on the web page. This includes replacing newlines with spaces.
            if (mustUseLegacyDragClient)
                src.editor().copyURL(linkURL, textContentWithSimplifiedWhiteSpace, dataTransfer.pasteboard());
            else
                pasteboardWriterData.setURL(src.editor().pasteboardWriterURL(linkURL, textContentWithSimplifiedWhiteSpace));
        } else {
            // Make sure the pasteboard also contains trustworthy link data
            // but don't overwrite more general pasteboard types.
            PasteboardURL pasteboardURL;
            pasteboardURL.url = linkURL;
            pasteboardURL.title = hitTestResult.textContent();
            dataTransfer.pasteboard().writeTrustworthyWebURLsPboardType(pasteboardURL);
        }

        const VisibleSelection& sourceSelection = src.selection().selection();
        if (sourceSelection.isCaret() && sourceSelection.isContentEditable()) {
            // a user can initiate a drag on a link without having any text
            // selected.  In this case, we should expand the selection to
            // the enclosing anchor element
            Position pos = sourceSelection.base();
            Node* node = enclosingAnchorElement(pos);
            if (node)
                src.selection().setSelection(VisibleSelection::selectionFromContentsOfNode(node));
        }

        m_client.willPerformDragSourceAction(DragSourceActionLink, dragOrigin, dataTransfer);
        if (!dragImage) {
            TextIndicatorData textIndicator;
            dragImage = DragImage { createDragImageForLink(element, linkURL, textContentWithSimplifiedWhiteSpace, textIndicator, src.settings().fontRenderingMode(), m_page.deviceScaleFactor()) };
            if (dragImage) {
                m_dragOffset = dragOffsetForLinkDragImage(dragImage.get());
                dragLoc = IntPoint(dragOrigin.x() + m_dragOffset.x(), dragOrigin.y() + m_dragOffset.y());
                dragImage = DragImage { platformAdjustDragImageForDeviceScaleFactor(dragImage.get(), m_page.deviceScaleFactor()) };
                if (textIndicator.contentImage)
                    dragImage.setIndicatorData(textIndicator);
            }
        }

        if (mustUseLegacyDragClient) {
            doSystemDrag(WTFMove(dragImage), dragLoc, dragOrigin, src, state);
            return true;
        }

        DragItem dragItem;
        dragItem.imageAnchorPoint = dragImage ? anchorPointForLinkDragImage(dragImage.get()) : FloatPoint();
        dragItem.image = WTFMove(dragImage);
        dragItem.data = WTFMove(pasteboardWriterData);

        beginDrag(WTFMove(dragItem), src, dragOrigin, mouseDraggedPoint, dataTransfer, DragSourceActionSelection);

        return true;
    }

#if ENABLE(ATTACHMENT_ELEMENT)
    if (is<HTMLAttachmentElement>(element) && m_dragSourceAction & DragSourceActionAttachment) {
        auto* attachmentRenderer = downcast<HTMLAttachmentElement>(element).attachmentRenderer();
        if (!attachmentRenderer)
            return false;

        src.editor().setIgnoreSelectionChanges(true);
        auto previousSelection = src.selection().selection();
        if (hasData == HasNonDefaultPasteboardData::No) {
            selectElement(element);
            if (!attachmentURL.isEmpty()) {
                // Use the attachment URL specified by the file attribute to populate the pasteboard.
                m_draggingAttachmentURL = attachmentURL;
                declareAndWriteAttachment(dataTransfer, element, attachmentURL);
            } else if (src.editor().client()) {
#if PLATFORM(COCOA)
                // Otherwise, if no file URL is specified, call out to the injected bundle to populate the pasteboard with data.
                auto& editor = src.editor();
                editor.willWriteSelectionToPasteboard(src.selection().toNormalizedRange().get());
                editor.writeSelectionToPasteboard(dataTransfer.pasteboard());
                editor.didWriteSelectionToPasteboard();
#endif
            }
        }

        m_client.willPerformDragSourceAction(DragSourceActionAttachment, dragOrigin, dataTransfer);

        if (!dragImage) {
            TextIndicatorData textIndicator;
            attachmentRenderer->setShouldDrawBorder(false);
            dragImage = DragImage { dissolveDragImageToFraction(createDragImageForSelection(src, textIndicator), DragImageAlpha) };
            attachmentRenderer->setShouldDrawBorder(true);
            if (textIndicator.contentImage)
                dragImage.setIndicatorData(textIndicator);
            dragLoc = dragLocForSelectionDrag(src);
            m_dragOffset = IntPoint(dragOrigin.x() - dragLoc.x(), dragOrigin.y() - dragLoc.y());
        }
        doSystemDrag(WTFMove(dragImage), dragLoc, dragOrigin, src, state);
        src.selection().setSelection(previousSelection);
        src.editor().setIgnoreSelectionChanges(false);
        return true;
    }
#endif

    if (state.type == DragSourceActionDHTML && dragImage) {
        ASSERT(m_dragSourceAction & DragSourceActionDHTML);
        m_client.willPerformDragSourceAction(DragSourceActionDHTML, dragOrigin, dataTransfer);
        doSystemDrag(WTFMove(dragImage), dragLoc, dragOrigin, src, state);
        return true;
    }

    return false;
}

void DragController::doImageDrag(Element& element, const IntPoint& dragOrigin, const IntRect& layoutRect, Frame& frame, IntPoint& dragImageOffset, const DragState& state)
{
    IntPoint mouseDownPoint = dragOrigin;
    DragImage dragImage;
    IntPoint scaledOrigin;

    if (!element.renderer())
        return;

    ImageOrientationDescription orientationDescription(element.renderer()->shouldRespectImageOrientation(), element.renderer()->style().imageOrientation());

    Image* image = getImage(element);
    if (image && shouldUseCachedImageForDragImage(*image) && (dragImage = DragImage { createDragImageFromImage(image, element.renderer() ? orientationDescription : ImageOrientationDescription()) })) {
        dragImage = DragImage { fitDragImageToMaxSize(dragImage.get(), layoutRect.size(), maxDragImageSize()) };
        IntSize fittedSize = dragImageSize(dragImage.get());

        dragImage = DragImage { platformAdjustDragImageForDeviceScaleFactor(dragImage.get(), m_page.deviceScaleFactor()) };
        dragImage = DragImage { dissolveDragImageToFraction(dragImage.get(), DragImageAlpha) };

        // Properly orient the drag image and orient it differently if it's smaller than the original.
        float scale = fittedSize.width() / (float)layoutRect.width();
        float dx = scale * (layoutRect.x() - mouseDownPoint.x());
        float originY = layoutRect.y();
#if PLATFORM(COCOA)
        // Compensate for accursed flipped coordinates in Cocoa.
        originY += layoutRect.height();
#endif
        float dy = scale * (originY - mouseDownPoint.y());
        scaledOrigin = IntPoint((int)(dx + 0.5), (int)(dy + 0.5));
    } else {
        if (CachedImage* cachedImage = getCachedImage(element)) {
            dragImage = DragImage { createDragImageIconForCachedImageFilename(cachedImage->response().suggestedFilename()) };
            if (dragImage)
                scaledOrigin = IntPoint(DragIconRightInset - dragImageSize(dragImage.get()).width(), DragIconBottomInset);
        }
    }

    if (!dragImage)
        return;

    dragImageOffset = mouseDownPoint + scaledOrigin;
    doSystemDrag(WTFMove(dragImage), dragImageOffset, dragOrigin, frame, state);
}

void DragController::beginDrag(DragItem dragItem, Frame& frame, const IntPoint& mouseDownPoint, const IntPoint& mouseDraggedPoint, DataTransfer& dataTransfer, DragSourceAction dragSourceAction)
{
    ASSERT(!m_client.useLegacyDragClient());

    m_didInitiateDrag = true;
    m_dragInitiator = frame.document();

    // Protect this frame and view, as a load may occur mid drag and attempt to unload this frame
    Ref<MainFrame> mainFrameProtector(m_page.mainFrame());
    RefPtr<FrameView> viewProtector = mainFrameProtector->view();

    auto mouseDownPointInRootViewCoordinates = viewProtector->rootViewToContents(frame.view()->contentsToRootView(mouseDownPoint));
    auto mouseDraggedPointInRootViewCoordinates = viewProtector->rootViewToContents(frame.view()->contentsToRootView(mouseDraggedPoint));

    m_client.beginDrag(WTFMove(dragItem), frame, mouseDownPointInRootViewCoordinates, mouseDraggedPointInRootViewCoordinates, dataTransfer, dragSourceAction);

    // DragClient::beginDrag can cause the drag controller to be deleted.
    if (!mainFrameProtector->page())
        return;

    // FIXME: This shouldn't be needed.
    cleanupAfterSystemDrag();
}

void DragController::doSystemDrag(DragImage image, const IntPoint& dragLoc, const IntPoint& eventPos, Frame& frame, const DragState& state)
{
    m_didInitiateDrag = true;
    m_dragInitiator = frame.document();
    // Protect this frame and view, as a load may occur mid drag and attempt to unload this frame
    Ref<MainFrame> frameProtector(m_page.mainFrame());
    RefPtr<FrameView> viewProtector = frameProtector->view();

    DragItem item;
    item.image = WTFMove(image);
    item.sourceAction = state.type;

    auto eventPositionInRootViewCoordinates = frame.view()->contentsToRootView(eventPos);
    auto dragLocationInRootViewCoordinates = frame.view()->contentsToRootView(dragLoc);
    item.eventPositionInContentCoordinates = viewProtector->rootViewToContents(eventPositionInRootViewCoordinates);
    item.dragLocationInContentCoordinates = viewProtector->rootViewToContents(dragLocationInRootViewCoordinates);
    item.eventPositionInWindowCoordinates = frame.view()->contentsToWindow(item.eventPositionInContentCoordinates);
    item.dragLocationInWindowCoordinates = frame.view()->contentsToWindow(item.dragLocationInContentCoordinates);
    if (auto element = state.source) {
        auto dataTransferImageElement = state.dataTransfer->dragImageElement();
        if (state.type == DragSourceActionDHTML) {
            // If the drag image has been customized, fall back to positioning the preview relative to the drag event location.
            IntSize dragPreviewSize;
            if (dataTransferImageElement)
                dragPreviewSize = dataTransferImageElement->boundsInRootViewSpace().size();
            else {
                dragPreviewSize = dragImageSize(item.image.get());
                if (auto* page = frame.page())
                    dragPreviewSize.scale(1 / page->deviceScaleFactor());
            }
            item.dragPreviewFrameInRootViewCoordinates = { dragLocationInRootViewCoordinates, WTFMove(dragPreviewSize) };
        } else {
            // We can position the preview using the bounds of the drag source element.
            item.dragPreviewFrameInRootViewCoordinates = element->boundsInRootViewSpace();
        }

        RefPtr<Element> link;
        if (element->isLink())
            link = element;
        else {
            for (auto& currentElement : elementLineage(element.get())) {
                if (currentElement.isLink()) {
                    link = &currentElement;
                    break;
                }
            }
        }
        if (link) {
            auto titleAttribute = link->attributeWithoutSynchronization(HTMLNames::titleAttr);
            item.title = titleAttribute.isEmpty() ? link->innerText() : titleAttribute.string();
            item.url = frame.document()->completeURL(stripLeadingAndTrailingHTMLSpaces(link->getAttribute(HTMLNames::hrefAttr)));
        }
    }
    m_client.startDrag(WTFMove(item), *state.dataTransfer, frameProtector.get());
    // DragClient::startDrag can cause our Page to dispear, deallocating |this|.
    if (!frameProtector->page())
        return;

    cleanupAfterSystemDrag();
}

// Manual drag caret manipulation
void DragController::placeDragCaret(const IntPoint& windowPoint)
{
    mouseMovedIntoDocument(m_page.mainFrame().documentAtPoint(windowPoint));
    if (!m_documentUnderMouse)
        return;
    Frame* frame = m_documentUnderMouse->frame();
    FrameView* frameView = frame->view();
    if (!frameView)
        return;
    IntPoint framePoint = frameView->windowToContents(windowPoint);

    m_page.dragCaretController().setCaretPosition(frame->visiblePositionForPoint(framePoint));
}

bool DragController::shouldUseCachedImageForDragImage(const Image& image) const
{
#if ENABLE(DATA_INTERACTION)
    UNUSED_PARAM(image);
    return true;
#else
    return image.size().height() * image.size().width() <= MaxOriginalImageArea;
#endif
}

#endif // ENABLE(DRAG_SUPPORT)

} // namespace WebCore


text:
module ReportsKit
  module Reports
    module Data
      class PopulateTwoDimensions
        attr_accessor :serieses, :dimension, :second_dimension, :sparse_serieses_dimension_keys_values

        def initialize(sparse_serieses_dimension_keys_values)
          self.serieses = sparse_serieses_dimension_keys_values.keys
          self.dimension = serieses.first.dimensions[0]
          self.second_dimension = serieses.first.dimensions[1]
          self.sparse_serieses_dimension_keys_values = sparse_serieses_dimension_keys_values
        end

        def perform
          serieses_populated_dimension_keys_values
        end

        private

        def serieses_populated_dimension_keys_values
          serieses_dimension_keys_values = {}
          secondary_keys_sums = Hash.new(0)
          serieses_populated_primary_keys_secondary_keys_values.each do |series, primary_keys_secondary_keys_values|
            primary_keys_secondary_keys_values.each do |primary_key, secondary_keys_values|
              secondary_keys_values.each do |secondary_key, value|
                secondary_keys_sums[secondary_key] += value
              end
            end
          end
          sorted_secondary_keys = secondary_keys_sums.sort_by(&:last).reverse.map(&:first)
          serieses_populated_primary_keys_secondary_keys_values.each do |series, primary_key_secondary_keys_values|
            serieses_dimension_keys_values[series] = {}
            primary_key_secondary_keys_values.each do |primary_key, secondary_keys_values|
              secondary_keys_values = secondary_keys_values.sort_by { |key, _| sorted_secondary_keys.index(key) }
              secondary_keys_values.each do |secondary_key, value|
                dimension_key = [primary_key, secondary_key]
                serieses_dimension_keys_values[series][dimension_key] = value
                secondary_keys_sums[secondary_key] += value
              end
            end
          end
          serieses_dimension_keys_values
        end

        def serieses_populated_primary_keys_secondary_keys_values
          @populated_dimension_keys_values ||= begin
            serieses_populated_primary_keys_secondary_keys_values = {}
            serieses.each do |series|
              serieses_populated_primary_keys_secondary_keys_values[series] = {}
              primary_keys.each do |primary_key|
                serieses_populated_primary_keys_secondary_keys_values[series][primary_key] = {}
                secondary_keys.each do |secondary_key|
                  value = serieses_primary_keys_secondary_keys_values[series][primary_key].try(:[], secondary_key) || 0
                  serieses_populated_primary_keys_secondary_keys_values[series][primary_key][secondary_key] = value
                end
              end
            end
            serieses_populated_primary_keys_secondary_keys_values
          end
        end

        def serieses_primary_keys_secondary_keys_values
          @serieses_primary_keys_secondary_keys_values ||= begin
            serieses_primary_keys_secondary_keys_values = {}
            sparse_serieses_dimension_keys_values.each do |series, dimension_keys_values|
              serieses_primary_keys_secondary_keys_values[series] = {}
              dimension_keys_values.each do |(primary_key, secondary_key), value|
                primary_key = primary_key.to_date if primary_key.is_a?(Time)
                secondary_key = secondary_key.to_date if secondary_key.is_a?(Time)
                serieses_primary_keys_secondary_keys_values[series][primary_key] ||= {}
                serieses_primary_keys_secondary_keys_values[series][primary_key][secondary_key] = value
              end
            end
            serieses_primary_keys_secondary_keys_values
          end
        end

        def dimension_keys
          @dimension_keys ||= sparse_serieses_dimension_keys_values.values.map(&:keys).reduce(&:+).uniq
        end

        def primary_keys
          @primary_keys ||= begin
            keys = Utils.populate_sparse_keys(dimension_keys.map(&:first).uniq, dimension: dimension)
            unless dimension.configured_by_time?
              limit = dimension.dimension_instances_limit
              keys = keys.first(limit) if limit
            end
            keys
          end
        end

        def secondary_keys
          @secondary_keys ||= begin
            keys = Utils.populate_sparse_keys(dimension_keys.map(&:last).uniq, dimension: second_dimension)
            limit = second_dimension.dimension_instances_limit
            keys = keys.first(limit) if limit
            keys
          end
        end
      end
    end
  end
end


text:
package TestFilter::in_str_sandwich;

# this test verifies whether the filter can pre-insert data (using
# context) and post-insert data (using the seen_eos flag)

use strict;
use warnings FATAL => 'all';

use Apache2::RequestRec ();
use Apache2::RequestIO ();
use Apache2::Filter ();

use TestCommon::Utils ();

use Apache2::Const -compile => qw(OK M_POST);

sub handler {
    my $filter = shift;

    my $ctx = $filter->ctx;

    unless ($ctx) {
        $filter->print("HEADER\n");
        $filter->ctx(1);
    }

    while ($filter->read(my $buffer, 1024)) {
        #warn "FILTER READ: $buffer\n";
        $filter->print($buffer);
    }

    if ($filter->seen_eos) {
        $filter->print("TAIL\n");
    }

    return Apache2::Const::OK;
}

sub response {
    my $r = shift;

    $r->content_type('text/plain');

    if ($r->method_number == Apache2::Const::M_POST) {
        my $data = TestCommon::Utils::read_post($r);
        #warn "HANDLER READ: $data\n";
        $r->print($data);
    }

    return Apache2::Const::OK;
}
1;
__DATA__
SetHandler modperl
PerlModule          TestFilter::in_str_sandwich
PerlResponseHandler TestFilter::in_str_sandwich::response


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Testing</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="css/normalize.css">
    <link rel="stylesheet" href="css/main.css">

Send email with automatic video link for nutritionist consultation

<form action="https://trim-webbing-611.appspot.com/_ah/api/nuses/v1/sessions" method="post" name="myform">
    <input name="firstName" value="Thommy"/>
    <input name="lastName" value="Bommen"/>
    <input name="email" value="thommy.bommen@gmail.com"/>
    <input name="appointment" value="2014-07-14 13:00Z"/>

</form>
<input type="button" onclick="generateEmailForm(document.myform)" value="send emails"/>


text:
<?php

/**
 * twoinchopenreelvideo actions.
 *
 * @package    mediaSCORE
 * @subpackage twoinchopenreelvideo
 * @author     Nouman Tayyab
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class twoinchopenreelvideoActions extends sfActions
{

	/**
	 * List all TwoInchOpenReelVideo
	 *
	 * @param sfWebRequest $request
	 */
	public function executeIndex(sfWebRequest $request)
	{
		$this->two_inch_open_reel_videos = Doctrine_Core::getTable('TwoInchOpenReelVideo')
		->createQuery('a')
		->execute();
	}

	/**
	 * TwoInchOpenReelVideo detail of specific record
	 *
	 * @param sfWebRequest $request
	 */
	public function executeShow(sfWebRequest $request)
	{
		$this->two_inch_open_reel_video = Doctrine_Core::getTable('TwoInchOpenReelVideo')->find(array($request->getParameter('id')));
		$this->forward404Unless($this->two_inch_open_reel_video);
	}

	/**
	 * TwoInchOpenReelVideo form
	 *
	 * @param sfWebRequest $request
	 */
	public function executeNew(sfWebRequest $request)
	{
		$this->form = new TwoInchOpenReelVideoForm();
	}

	/**
	 * TwoInchOpenReelVideo Post form process
	 *
	 * @param sfWebRequest $request
	 */
	public function executeCreate(sfWebRequest $request)
	{
		$this->forward404Unless($request->isMethod(sfRequest::POST));

		$this->form = new TwoInchOpenReelVideoForm();

		$this->processForm($request, $this->form);

		$this->setTemplate('new');
	}

	/**
	 * TwoInchOpenReelVideo edit form
	 *
	 * @param sfWebRequest $request
	 */
	public function executeEdit(sfWebRequest $request)
	{
		$this->forward404Unless($two_inch_open_reel_video = Doctrine_Core::getTable('TwoInchOpenReelVideo')->find(array($request->getParameter('id'))), sprintf('Object two_inch_open_reel_video does not exist (%s).', $request->getParameter('id')));
		$this->form = new TwoInchOpenReelVideoForm($two_inch_open_reel_video);
		$reelSize = explode(',', $two_inch_open_reel_video->getReelSize());

		$this->form->setDefault('reelSize', $reelSize);
	}

	/**
	 * TwoInchOpenReelVideo Post edit form process
	 *
	 * @param sfWebRequest $request
	 */
	public function executeUpdate(sfWebRequest $request)
	{
		$this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
		$this->forward404Unless($two_inch_open_reel_video = Doctrine_Core::getTable('FormatType')->find(array($request->getParameter('id'))), sprintf('Object two_inch_open_reel_video does not exist (%s).', $request->getParameter('id')));

		$two_inch_open_reel_video->setType(33);
		$two_inch_open_reel_video->save();
		$two_inch_open_reel_video = Doctrine_Core::getTable('TwoInchOpenReelVideo')->find(array($request->getParameter('id')));
		$this->form = new TwoInchOpenReelVideoForm($two_inch_open_reel_video);

		$validateForm = $this->processForm($request, $this->form);

		if ($validateForm && isset($validateForm['form']) && $validateForm['form'] == true)
		{
			echo $validateForm['id'];
			exit;
		}
		else
		{
			$this->setTemplate('edit');
		}
	}

	/**
	 * TwoInchOpenReelVideo Delete form
	 *
	 * @param sfWebRequest $request
	 */
	public function executeDelete(sfWebRequest $request)
	{
		$request->checkCSRFProtection();

		$this->forward404Unless($two_inch_open_reel_video = Doctrine_Core::getTable('TwoInchOpenReelVideo')->find(array($request->getParameter('id'))), sprintf('Object two_inch_open_reel_video does not exist (%s).', $request->getParameter('id')));
		$two_inch_open_reel_video->delete();

		$this->redirect('twoinchopenreelvideo/index');
	}

	/**
	 * Process and validate form
	 *
	 * @param sfWebRequest $request
	 * @param sfForm $form
	 * @return boolean if form is not validated
	 * @return integer if form is validated then return id
	 */
	protected function processForm(sfWebRequest $request, sfForm $form)
	{
		$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
		if ($form->isValid())
		{
			$two_inch_open_reel_video = $form->save();
			$saveReturnId = array('form' => true, 'id' => $two_inch_open_reel_video->getId());
			return $saveReturnId;
		}
		return false;
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="connectexception">无法连接到网络</string>
    <string name="unknownhostexception">连接远程地址失败</string>
    <string name="socketexception">网络连接出错,请重试</string>
    <string name="sockettimeoutexception">连接超时,请重试</string>
    <string name="nullpointerexception">抱歉,远程服务出错了</string>
    <string name="nullmessageexception">抱歉,程序出错了</string>
    <string name="clientprotocolexception">http请求参数错误</string>

</resources>


text:
ACCEPTED

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

#### Published in
Fl. crypt. Germ. (Nürnberg) 2: 289 (1833)

#### Original name
Oncocladium flavum Wallr., 1833

### Remarks
null


text:
! { dg-do run }
! PR 15234
! tests for passing arrays of assumed length characters
program strarray_6
character(5), dimension(:), allocatable :: c
n = 3
allocate(c(-1:n-2))
c = "BLUBB"
call foo(c)
call bar(c,n)
deallocate(c)
contains
subroutine foo(x)
  character (len = *), dimension(:) :: x
  if (any (x .ne. "BLUBB")) CALL abort()
end subroutine foo
end

subroutine bar(x,n)
  character (len = *), dimension(n) :: x
  if (any (x .ne. "BLUBB")) CALL abort()
end subroutine bar


text:
from LEDfuncs import*
import collections	# For using millisecond function
from time import sleep

class Mood(object):
	def __init__(self,valence,arousal):
		self.valence = valence
		self.arousal = arousal

# Set Global Variables
mood = Mood(60,60)		# Set default values
# Define colors
Red = (250,50,0)
Orange = (220,125,0)
Blue = (0,0,250)
Yellow = (250,200,0)

def genColor(mood):
	"""This function takes in mood, a class valence and arousel levels (1-100) and returns nothing. It does however generate a unique color
	and displays this color on an 8x8 matrix."""
	#~ print(mood.valence, mood.arousal)
	if mood.valence < 50 and mood.arousal > 50:
		# Describes Exuberance
		return Red
	if mood.valence > 50 and mood.arousal > 50:
		# Describes Anxious/Frantic
		return Orange
	if mood.valence > 50 and mood.arousal < 50:
		# Describes Depression
		return Blue
	if mood.valence < 50 and mood.arousal < 50:
		# Describes Contentment
		return Yellow

def genMood(mood = Mood(50,50), key = None,rhythm = None,dynamic = None,tempo= None):
	"""Takes in a string (key) and 3 integers (rythIntensity, dynamic, tempo). Returns a tuple of arousal and valence levels."""

	# Set dummy variables for each component's respective contribution to valence (stress, x) and arousal (energy, y)
	keyValence = 0
	keyArousal = 0
	rythmArousal = 0
	# Analyze musical keys (based on Charpentier's Regles de Composition ca. 1682, biteyourownelbow.com/keychar.htm)
	if any([key == 'Cma', key == 'Dma', key == 'Emi', key == 'Gma', key == 'Gmi']):	# Exuberance: gay, warlike, joyous, effeminate, amorous, plaintiff, serious and magnificent
		keyValence = 25
		keyArousal = 75
	if any([key == 'Ama', key == 'Bmi', key == 'Bbma']):	# Contentment: joyful and pastoral, solitary and melecholny, magnificant & joyful
		keyValence = 25
		keyArousal = 25
	if any([key == 'Dmi', key == 'Ebma', key == 'Ema', key == 'Fma', key == 'Bma']):	# Anxious/Frantic: serious and pious, quarrelsome and boisterous, furious and quick-tempered subjecteds, harsh and plaintiff
		keyValence = 75
		keyArousal = 75
	if any([key == 'Fmi', key == 'B', key == 'Ami', key == 'Bbmi']):	# Depression: obscure and plaintiff, tender and plaintiff, obscure and terrible
		keyValence = 75
		keyArousal = 25

	# Analyze rythmic intensity
	if rhythm > 50:
		rythmArousal = 80	# to return arousal average >50
	if rhythm < 50:
		rythmArousal = 20 # to return arousal average < 50

	# Calculate valence and arousal as averages
	mood.valence = keyValence
	mood.arousal = (keyArousal + rythmArousal)/2
	return mood


text:
import React, {Component, PropTypes} from 'react';

export default class GenderToggle extends Component {

	render() {
		const styles = require('./GenderToggle.scss');
		return(

    			<input type={this.checkbox} name={this.onoffswitch} class={this.onoffswitchCheckbox} id={this.myonoffswitch} checked />

		);
	}

}