text:
package cryogen;

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.stage.WindowEvent;

import java.awt.font.ShapeGraphicAttribute;
import java.io.IOException;
import java.net.URL;
import java.util.Optional;
import java.util.ResourceBundle;

public class Criterions implements Initializable
{
	//Instance Variables
	private Stage currentStage;
	private SharedMemoryRepository memory;
	//GUI Variables
	@FXML private AnchorPane anchorPane;
	@FXML private Button btnContinue;
	@FXML private TextField txtCriterion1;
	@FXML private TextField txtCriterion2;
	@FXML private TextField txtCriterion3;
	@FXML private TextField txtCriterion4;
	@FXML private TextField txtCriterion5;
	@FXML private TextField txtCriterion6;
	@FXML private TextField txtCriterion7;
	@FXML private TextField txtCriterion8;
	@FXML private TextField txtCriterion9;
	@FXML private Slider sldCriterion1;
	@FXML private Slider sldCriterion2;
	@FXML private Slider sldCriterion3;
	@FXML private Slider sldCriterion4;
	@FXML private Slider sldCriterion5;
	@FXML private Slider sldCriterion6;
	@FXML private Slider sldCriterion7;
	@FXML private Slider sldCriterion8;
	@FXML private Slider sldCriterion9;

	/**
	 * Default Constructor
	 */
	public Criterions()
	{
		setMemory(new SharedMemoryRepository());
	}

	/**
	 * Initialize method for GUI
	 * @param location
	 * @param resources
	 */
	@Override
	public void initialize(URL location, ResourceBundle resources)
	{

	}

	/**
	 * Initialize method for GUI
	 * @param currentStage
	 */
	void initialize(Stage currentStage)
	{
		SharedMemoryRepository.setStage(currentStage);
		setCurrentStage(currentStage);
		setMemory(new SharedMemoryRepository(getCurrentStage()));
		getCurrentStage().setOnCloseRequest(getMemory().confirmCloseEventHandler);//Set default close event
		//txtProjectCount.requestFocus();
		//mnuLaF_BreathDark_Clicked(new ActionEvent());
	}

	private void setCurrentStage(Stage stage)
	{
		this.currentStage = stage;
	}

	private Stage getCurrentStage()
	{
		return this.currentStage;
	}

	public void setMemory(SharedMemoryRepository memory)
	{
		this.memory = memory;
	}

	public SharedMemoryRepository getMemory()
	{
		return this.memory;
	}

	/**
	 * Move on to criterions window
	 */
	@FXML
	protected void btnContinue_Clicked(ActionEvent event)
	{
		try
		{
			//TODO: Replace hardcode with dynamically scalable criterions
			int cN, cV;
			cN = cV = 0;

			//Traverse through all components inside/on anchorPane
			for (Node node : anchorPane.getChildren())
				//System.out.println("Id: " + node.getId());
				if (node instanceof TextField && !((TextField)node).getText().equals(""))
					SharedMemoryRepository.setCriterion_names(cN++, ((TextField)node).getText());
				else if (node instanceof Slider)
					SharedMemoryRepository.setCriterion_values(cV++, ((int) ((Slider) node).getValue()));

			SharedMemoryRepository.setCriterion_count(cN);
			SharedMemoryRepository.init_project_criterion_values();

			FXMLLoader loader       = new FXMLLoader(getClass().getResource("CriterionIterator.fxml"));
			Stage      cross_window = new Stage(StageStyle.DECORATED);//
			cross_window.setResizable(false);
			cross_window.setTitle("CROSS 1.0 - " + SharedMemoryRepository.getCriterion_names()[SharedMemoryRepository.getCriterion_iterator()]);
			cross_window.setScene(new Scene((Pane) loader.load()));
			//CriterionIterator criterions = new CriterionIterator(laf, 0, projectCount, criterionCount, criterionNames, criterionValues);
//			cross_window.getScene().getStylesheets().add(getClass().getResource(SharedMemoryRepository.getLaF()).toExternalForm());

			CriterionIterator criterions = loader.<CriterionIterator>getController();
			criterions.initialize(cross_window);

			cross_window.show();
			((Node) (event.getSource())).getScene().getWindow().hide();//Hide Previous Window
		}
		catch (NumberFormatException nfex)
		{
			nfex.printStackTrace();
			getMemory().handleException(nfex);
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
			getMemory().handleException(ex);
		}
	}

	/**
	 * Event handler to view user manual
	 * @param event
	 */
	@FXML
	protected void mnuHelp_UserManual_Clicked(ActionEvent event)
	{
		SharedMemoryRepository.showManual();
	}

	@FXML
	protected void mnuFile_Preferences_Clicked(ActionEvent event)
	{
		getMemory().showPreferences();
	}

	@FXML
	protected void mnuFile_Exit_Clicked(ActionEvent event)
	{
		getMemory().exit();
	}

	/**
	 * Method to prompt before exit
	 * Exits application with 0 error code if user prompt is confirmed else application continues
	 */
	public EventHandler<WindowEvent> confirmCloseEventHandler = event ->
	{
		Alert  closeConfirmation = new Alert(Alert.AlertType.CONFIRMATION, "Are you sure you want to exit?");
		Button exitButton        = (Button) closeConfirmation.getDialogPane().lookupButton(ButtonType.OK);
		exitButton.setText("Exit");
		closeConfirmation.setHeaderText("Confirm Exit");
		closeConfirmation.initModality(Modality.APPLICATION_MODAL);
		closeConfirmation.initOwner(getCurrentStage());
		DialogPane dialogPane = closeConfirmation.getDialogPane();
		dialogPane.getStylesheets().add(getClass().getResource(SharedMemoryRepository.getLaF()).toExternalForm());
		dialogPane.getStyleClass().add("dlgDefault");
		Optional<ButtonType> closeResponse = closeConfirmation.showAndWait();
		if (!ButtonType.OK.equals(closeResponse.get()))
			event.consume();
	};

	/**
	 * Event handler to view user manual
	 * @param event
	 */
	@FXML
	protected void mnuHelp_License_Clicked(ActionEvent event)
	{
		SharedMemoryRepository.showLicense();
	}
}


text:
import wx
import Interface
from os.path import join, dirname, abspath

"""
Start LINEViewer and open the GUI
"""

class StartLINEViewer(wx.App):

    """Calls LINEViewer Splash Screen"""

    def OnInit(self):
        LINEViewerSplash = LINEViewerSplashScreen()
        LINEViewerSplash.Show()
        return True

class LINEViewerSplashScreen(wx.SplashScreen):

    """Opens LINEViewer Splash Screen and after exit starts LINEViewer"""

    def __init__(self, parent=None):
        logopath = join(
            dirname(abspath(__file__)), 'static', 'LINEViewer_logo.png')
        aBitmap = wx.Image(name=logopath).ConvertToBitmap()
        splashStyle = wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT
        splashDuration = 1000
        wx.SplashScreen.__init__(self, aBitmap, splashStyle,
                                 splashDuration, parent)
        self.Bind(wx.EVT_CLOSE, self.OnExit)
        wx.Yield()

    def OnExit(self, event):
        self.Hide()
        MyFrame = Interface.MainFrame()
        MyFrame.Show(True)
        event.Skip()

redpajama_set_name: RedPajamaGithub


text:
#region Copyright (c) 2002-2003, James W. Newkirk, Michael C. Two, Alexei A. Vorontsov, Charlie Poole, Philip A. Craig

#endregion

using System;
using System.Collections.Specialized;

namespace NUnit.Util
{
	/// <summary>
	/// Originally, we used the same ProjectConfig class for both
	/// NUnit and Visual Studio projects. Since we really do very
	/// little with VS Projects, this class has been created to
	/// hold the name and the collection of assembly paths.
	/// </summary>
	public class VSProjectConfig
	{
		private string name;

		private StringCollection assemblies = new StringCollection();

		public VSProjectConfig( string name )
		{
			this.name = name;
		}

		public string Name
		{
			get { return name; }
		}

		public StringCollection Assemblies
		{
			get { return assemblies; }
		}
	}
}


text:
"""

None
"""

class Solution:
    def minMeetingRooms(self, intervals: List[List[int]]) -> int:
        from collections import Counter
        start = Counter([interval[0] for interval in intervals])
        end = Counter([interval[1] for interval in intervals])
        nums = set(start.keys()).union(set(end.keys()))
        mm = 0
        curr = 0
        for n in sorted(nums):
            if n in end:
                curr -= end[n]
            if n in start:
                curr += start[n]
            mm = max(mm, curr)
        return mm


text:
<?php

namespace Rocketeer\Dummies\Strategies;

use Rocketeer\Abstracts\Strategies\AbstractStrategy;

class FailingStrategy extends AbstractStrategy
{
    public function fire()
    {
        return false;
    }
}


text:
package edu.ur.ir.item;

import java.io.Serializable;
import java.util.List;
import java.util.Set;

import edu.ur.ir.file.IrFile;
import edu.ur.ir.person.Contributor;
import edu.ur.ir.person.ContributorType;
import edu.ur.ir.person.PersonName;
import edu.ur.ir.user.IrUser;

public interface ItemService extends Serializable{

	/**
	 * Delete the versioned item from persisten storage.
	 *
	 * @param versionedItem - versioned item to remove
	 */
	public void deleteVersionedItem(VersionedItem versionedItem);

	/**
	 * Get a versioned item by id.
	 *
	 * @param id - id to get the versioned item for.
	 * @param lock - upgrade the lock on the versioned item.
	 *
	 * @return - the versioned item if found otherwise null.
	 */
	public VersionedItem getVersionedItem(Long id, boolean lock);

	/**
	 * Save the item file
	 *
	 * @param itemFile - item file to be saved
	 */
	public void saveItemFile(ItemFile itemFile);

	/**
	 * Delete item file
	 *
	 * @param itemFile - item file to be deleted
	 */
	public void deleteItemFile(ItemFile itemFile);

	/**
	 * Get the count of items using this file
	 *
	 * @param irFile irFile used by item
	 */
	public Long getItemFileCount(IrFile irFile);

	/**
	 * Get all item files uses the specified ir file.
	 *
	 * @param irFile - ir file being used
	 * @return the list of item files being used.
	 */
	public List<ItemFile> getItemFilesWithIrFile(IrFile irFile);

	/**
	 * Deletes the IrFiles that are not used by any item and PersonalFiles
	 *
	 * @param irFileIds Set of ir file ids to be deleted
	 *
	 */
	public void deleteUnUsedIrFiles(Set<Long> irFileIds);

	/**
	 * Delete the item.
	 *
	 * @param item  Item to be deleted
	 *
	 */
	public void deleteItem(GenericItem item);

	/**
	 * Save item
	 *
	 * @param item
	 */
	public void makePersistent(GenericItem item);

	/**
	 * Get the item with the specified id.
	 *
	 * @param id - id to get the generic item for.
	 * @param lock - upgrade the lock on the generic item.
	 *
	 * @return - the generic item if found otherwise null.
	 */
	public GenericItem getGenericItem(Long id, boolean lock);

	/**
	 * Get the item file with the specified id.
	 *
	 * @param id - id to get the item file for.
	 * @param lock - upgrade the lock on the item file.
	 *
	 * @return - the item file if found otherwise null.
	 */
	public ItemFile getItemFile(Long id, boolean lock);

	/**
	 * Get the list of items owned by an user
	 *
	 * @param user - User owning the items
	 * @return list of Items
	 */
	public List<GenericItem> getAllItemsForUser(IrUser user);

	/**
	 * Get all versioned items for a user.
	 *
	 * @param user - user who owns the versioned items
	 * @return - the versioned items owned by this user.
	 */
	public List<VersionedItem> getAllVersionedItemsForUser(IrUser user);

	/**
	 * Number of items using the given person name as contributor
	 *
	 * @param contributor used by items
	 * @return Number of items
	 */
	public Long getItemCountByContributor(Contributor contributor);

	/**
	 * Number of items having the person as contributor for the specified name
	 *
	 * @see edu.ur.ir.item.ItemService#getItemCountByContributor(PersonName)
	 */
	public Long getItemCountByPersonName(PersonName personName);

	/**
	 * Delete external publiched item dataa
	 *
	 * @param externalPublishedItem data to be deleted
	 */
	public void deleteExternalPublishedItem(ExternalPublishedItem externalPublishedItem);

	/**
	 * Get the count of item version using this generic item
	 *
	 * @param item GenericItem to be searched for in item version
	 *
	 * @return Count of Item version containing the given generic Item
	 */
	public Long getItemVersionCount(GenericItem item);

	/**
	 * Get the item version with the specified id.
	 *
	 * @param id - id to get the item version for.
	 * @param lock - upgrade the lock on the item version.
	 *
	 * @return - the item version if found otherwise null.
	 */
	public ItemVersion getItemVersion(Long id, boolean lock);

	/**
	 * Get a count of items that have the specified contributor type.
	 *
	 * @param contributorType - the contributor type to check
	 * @return count of the number of items that have the specified contributor type.
	 */
	public Long getContributorTypeCount(ContributorType contributorType);
}


text:
BEGIN;

ALTER TABLE artifacts_v2.artifacts
DROP COLUMN job_id;

COMMIT;


text:
/*
 * @(#)MmeNsvcFr.java        1.0 09/12/14
 *
 * This file has been auto-generated by JNC, the
 * Java output format plug-in of pyang.
 * Origin: module "hcta-epc", revision: "2014-09-18".
 */

package hctaEpc.mmeSgsn.interface_.gb;

import Element;

import Epc;

import JNCException;

import Leaf;

import YangUInt16;

import com.tailf.jnc.YangElement;
import com.tailf.jnc.YangString;

/**
 * This class represents an element from
 * the namespace http://hitachi-cta.com/ns/epc
 * generated to "src/hctaEpc/mmeSgsn/interface_/gb/mme-nsvc-fr"
 * <p>
 * See line 391 in
 * gtlConfig.yang
 *
 * @version 1.0 2014-12-09
 * @author Auto Generated
 */
public class MmeNsvcFr extends YangElement {

    private static final long serialVersionUID = 1L;

    /**
     * Constructor for an empty MmeNsvcFr object.
     */
    public MmeNsvcFr() {
        super(Epc.NAMESPACE, "mme-nsvc-fr");
    }

    /**
     * Constructor for an initialized MmeNsvcFr object,
     *
     * @param nseIdValue Key argument of child.
     * @param nsvcIdValue Key argument of child.
     */
    public MmeNsvcFr(YangUInt16 nseIdValue, YangUInt16 nsvcIdValue)
            throws JNCException {
        super(Epc.NAMESPACE, "mme-nsvc-fr");
        Leaf nseId = new Leaf(Epc.NAMESPACE, "nse-id");
        nseId.setValue(nseIdValue);
        insertChild(nseId, childrenNames());
        Leaf nsvcId = new Leaf(Epc.NAMESPACE, "nsvc-id");
        nsvcId.setValue(nsvcIdValue);
        insertChild(nsvcId, childrenNames());
    }

    /**
     * Constructor for an initialized MmeNsvcFr object,
     * with String keys.
     * @param nseIdValue Key argument of child.
     * @param nsvcIdValue Key argument of child.
     */
    public MmeNsvcFr(String nseIdValue, String nsvcIdValue) throws JNCException {
        super(Epc.NAMESPACE, "mme-nsvc-fr");
        Leaf nseId = new Leaf(Epc.NAMESPACE, "nse-id");
        nseId.setValue(new YangUInt16(nseIdValue));
        insertChild(nseId, childrenNames());
        Leaf nsvcId = new Leaf(Epc.NAMESPACE, "nsvc-id");
        nsvcId.setValue(new YangUInt16(nsvcIdValue));
        insertChild(nsvcId, childrenNames());
    }

    /**
     * Constructor for an initialized MmeNsvcFr object,
     * with keys of built in Java types.
     * @param nseIdValue Key argument of child.
     * @param nsvcIdValue Key argument of child.
     */
    public MmeNsvcFr(int nseIdValue, int nsvcIdValue) throws JNCException {
        super(Epc.NAMESPACE, "mme-nsvc-fr");
        Leaf nseId = new Leaf(Epc.NAMESPACE, "nse-id");
        nseId.setValue(new YangUInt16(nseIdValue));
        insertChild(nseId, childrenNames());
        Leaf nsvcId = new Leaf(Epc.NAMESPACE, "nsvc-id");
        nsvcId.setValue(new YangUInt16(nsvcIdValue));
        insertChild(nsvcId, childrenNames());
    }

    /**
     * Clones this object, returning an exact copy.
     * @return A clone of the object.
     */
    public MmeNsvcFr clone() {
        MmeNsvcFr copy;
        try {
            copy = new MmeNsvcFr(getNseIdValue().toString(), getNsvcIdValue().toString());
        } catch (JNCException e) {
            copy = null;
        }
        return (MmeNsvcFr)cloneContent(copy);
    }

    /**
     * Clones this object, returning a shallow copy.
     * @return A clone of the object. Children are not included.
     */
    public MmeNsvcFr cloneShallow() {
        MmeNsvcFr copy;
        try {
            copy = new MmeNsvcFr(getNseIdValue().toString(), getNsvcIdValue().toString());
        } catch (JNCException e) {
            copy = null;
        }
        return (MmeNsvcFr)cloneShallowContent(copy);
    }

    /**
     * @return An array with the identifiers of any key children
     */
    public String[] keyNames() {
        return new String[] {
            "nse-id",
            "nsvc-id",
        };
    }

    /**
     * @return An array with the identifiers of any children, in order.
     */
    public String[] childrenNames() {
        return new String[] {
            "nse-id",
            "nsvc-id",
            "dlci",
            "fr-tunnel",
            "remote-port",
            "nsvl-group",
            "nsvl",
        };
    }

    /* Access methods for leaf child: "nse-id". */

    /**
     * Gets the value for child leaf "nse-id".
     * @return The value of the leaf.
     */
    public YangUInt16 getNseIdValue() throws JNCException {
        return (YangUInt16)getValue("nse-id");
    }

    /**
     * Sets the value for child leaf "nse-id",
     * using instance of generated typedef class.
     * @param nseIdValue The value to set.
     * @param nseIdValue used during instantiation.
     */
    public void setNseIdValue(YangUInt16 nseIdValue) throws JNCException {
        setLeafValue(Epc.NAMESPACE,
            "nse-id",
            nseIdValue,
            childrenNames());
    }

    /**
     * Sets the value for child leaf "nse-id",
     * using Java primitive values.
     * @param nseIdValue used during instantiation.
     */
    public void setNseIdValue(int nseIdValue) throws JNCException {
        setNseIdValue(new YangUInt16(nseIdValue));
    }

    /**
     * Sets the value for child leaf "nse-id",
     * using a String value.
     * @param nseIdValue used during instantiation.
     */
    public void setNseIdValue(String nseIdValue) throws JNCException {
        setNseIdValue(new YangUInt16(nseIdValue));
    }

    /**
     * This method is used for creating a subtree filter.
     * The added "nse-id" leaf will not have a value.
     */
    public void addNseId() throws JNCException {
        setLeafValue(Epc.NAMESPACE,
            "nse-id",
            null,
            childrenNames());
    }

    /* Access methods for leaf child: "nsvc-id". */

    /**
     * Gets the value for child leaf "nsvc-id".
     * @return The value of the leaf.
     */
    public YangUInt16 getNsvcIdValue() throws JNCException {
        return (YangUInt16)getValue("nsvc-id");
    }

    /**
     * Sets the value for child leaf "nsvc-id",
     * using instance of generated typedef class.
     * @param nsvcIdValue The value to set.
     * @param nsvcIdValue used during instantiation.
     */
    public void setNsvcIdValue(YangUInt16 nsvcIdValue) throws JNCException {
        setLeafValue(Epc.NAMESPACE,
            "nsvc-id",
            nsvcIdValue,
            childrenNames());
    }

    /**
     * Sets the value for child leaf "nsvc-id",
     * using Java primitive values.
     * @param nsvcIdValue used during instantiation.
     */
    public void setNsvcIdValue(int nsvcIdValue) throws JNCException {
        setNsvcIdValue(new YangUInt16(nsvcIdValue));
    }

    /**
     * Sets the value for child leaf "nsvc-id",
     * using a String value.
     * @param nsvcIdValue used during instantiation.
     */
    public void setNsvcIdValue(String nsvcIdValue) throws JNCException {
        setNsvcIdValue(new YangUInt16(nsvcIdValue));
    }

    /**
     * This method is used for creating a subtree filter.
     * The added "nsvc-id" leaf will not have a value.
     */
    public void addNsvcId() throws JNCException {
        setLeafValue(Epc.NAMESPACE,
            "nsvc-id",
            null,
            childrenNames());
    }

    /* Access methods for optional leaf child: "dlci". */

    /**
     * Gets the value for child leaf "dlci".
     * @return The value of the leaf.
     */
    public YangUInt16 getDlciValue() throws JNCException {
        return (YangUInt16)getValue("dlci");
    }

    /**
     * Sets the value for child leaf "dlci",
     * using instance of generated typedef class.
     * @param dlciValue The value to set.
     * @param dlciValue used during instantiation.
     */
    public void setDlciValue(YangUInt16 dlciValue) throws JNCException {
        setLeafValue(Epc.NAMESPACE,
            "dlci",
            dlciValue,
            childrenNames());
    }

    /**
     * Sets the value for child leaf "dlci",
     * using Java primitive values.
     * @param dlciValue used during instantiation.
     */
    public void setDlciValue(int dlciValue) throws JNCException {
        setDlciValue(new YangUInt16(dlciValue));
    }

    /**
     * Sets the value for child leaf "dlci",
     * using a String value.
     * @param dlciValue used during instantiation.
     */
    public void setDlciValue(String dlciValue) throws JNCException {
        setDlciValue(new YangUInt16(dlciValue));
    }

    /**
     * Unsets the value for child leaf "dlci".
     */
    public void unsetDlciValue() throws JNCException {
        delete("dlci");
    }

    /**
     * This method is used for creating a subtree filter.
     * The added "dlci" leaf will not have a value.
     */
    public void addDlci() throws JNCException {
        setLeafValue(Epc.NAMESPACE,
            "dlci",
            null,
            childrenNames());
    }

    /**
     * Marks the leaf "dlci" with operation "replace".
     */
    public void markDlciReplace() throws JNCException {
        markLeafReplace("dlci");
    }

    /**
     * Marks the leaf "dlci" with operation "merge".
     */
    public void markDlciMerge() throws JNCException {
        markLeafMerge("dlci");
    }

    /**
     * Marks the leaf "dlci" with operation "create".
     */
    public void markDlciCreate() throws JNCException {
        markLeafCreate("dlci");
    }

    /**
     * Marks the leaf "dlci" with operation "delete".
     */
    public void markDlciDelete() throws JNCException {
        markLeafDelete("dlci");
    }

    /* Access methods for optional leaf child: "fr-tunnel". */

    /**
     * Gets the value for child leaf "fr-tunnel".
     * @return The value of the leaf.
     */
    public YangString getFrTunnelValue() throws JNCException {
        return (YangString)getValue("fr-tunnel");
    }

    /**
     * Sets the value for child leaf "fr-tunnel",
     * using instance of generated typedef class.
     * @param frTunnelValue The value to set.
     * @param frTunnelValue used during instantiation.
     */
    public void setFrTunnelValue(YangString frTunnelValue) throws JNCException {
        setLeafValue(Epc.NAMESPACE,
            "fr-tunnel",
            frTunnelValue,
            childrenNames());
    }

    /**
     * Sets the value for child leaf "fr-tunnel",
     * using a String value.
     * @param frTunnelValue used during instantiation.
     */
    public void setFrTunnelValue(String frTunnelValue) throws JNCException {
        setFrTunnelValue(new YangString(frTunnelValue));
    }

    /**
     * Unsets the value for child leaf "fr-tunnel".
     */
    public void unsetFrTunnelValue() throws JNCException {
        delete("fr-tunnel");
    }

    /**
     * This method is used for creating a subtree filter.
     * The added "fr-tunnel" leaf will not have a value.
     */
    public void addFrTunnel() throws JNCException {
        setLeafValue(Epc.NAMESPACE,
            "fr-tunnel",
            null,
            childrenNames());
    }

    /**
     * Marks the leaf "fr-tunnel" with operation "replace".
     */
    public void markFrTunnelReplace() throws JNCException {
        markLeafReplace("frTunnel");
    }

    /**
     * Marks the leaf "fr-tunnel" with operation "merge".
     */
    public void markFrTunnelMerge() throws JNCException {
        markLeafMerge("frTunnel");
    }

    /**
     * Marks the leaf "fr-tunnel" with operation "create".
     */
    public void markFrTunnelCreate() throws JNCException {
        markLeafCreate("frTunnel");
    }

    /**
     * Marks the leaf "fr-tunnel" with operation "delete".
     */
    public void markFrTunnelDelete() throws JNCException {
        markLeafDelete("frTunnel");
    }

    /* Access methods for optional leaf child: "remote-port". */

    /**
     * Gets the value for child leaf "remote-port".
     * @return The value of the leaf.
     */
    public YangUInt16 getRemotePortValue() throws JNCException {
        return (YangUInt16)getValue("remote-port");
    }

    /**
     * Sets the value for child leaf "remote-port",
     * using instance of generated typedef class.
     * @param remotePortValue The value to set.
     * @param remotePortValue used during instantiation.
     */
    public void setRemotePortValue(YangUInt16 remotePortValue)
            throws JNCException {
        setLeafValue(Epc.NAMESPACE,
            "remote-port",
            remotePortValue,
            childrenNames());
    }

    /**
     * Sets the value for child leaf "remote-port",
     * using Java primitive values.
     * @param remotePortValue used during instantiation.
     */
    public void setRemotePortValue(int remotePortValue) throws JNCException {
        setRemotePortValue(new YangUInt16(remotePortValue));
    }

    /**
     * Sets the value for child leaf "remote-port",
     * using a String value.
     * @param remotePortValue used during instantiation.
     */
    public void setRemotePortValue(String remotePortValue) throws JNCException {
        setRemotePortValue(new YangUInt16(remotePortValue));
    }

    /**
     * Unsets the value for child leaf "remote-port".
     */
    public void unsetRemotePortValue() throws JNCException {
        delete("remote-port");
    }

    /**
     * This method is used for creating a subtree filter.
     * The added "remote-port" leaf will not have a value.
     */
    public void addRemotePort() throws JNCException {
        setLeafValue(Epc.NAMESPACE,
            "remote-port",
            null,
            childrenNames());
    }

    /**
     * Marks the leaf "remote-port" with operation "replace".
     */
    public void markRemotePortReplace() throws JNCException {
        markLeafReplace("remotePort");
    }

    /**
     * Marks the leaf "remote-port" with operation "merge".
     */
    public void markRemotePortMerge() throws JNCException {
        markLeafMerge("remotePort");
    }

    /**
     * Marks the leaf "remote-port" with operation "create".
     */
    public void markRemotePortCreate() throws JNCException {
        markLeafCreate("remotePort");
    }

    /**
     * Marks the leaf "remote-port" with operation "delete".
     */
    public void markRemotePortDelete() throws JNCException {
        markLeafDelete("remotePort");
    }

    /* Access methods for optional leaf child: "nsvl-group". */

    /**
     * Gets the value for child leaf "nsvl-group".
     * @return The value of the leaf.
     */
    public YangUInt16 getNsvlGroupValue() throws JNCException {
        return (YangUInt16)getValue("nsvl-group");
    }

    /**
     * Sets the value for child leaf "nsvl-group",
     * using instance of generated typedef class.
     * @param nsvlGroupValue The value to set.
     * @param nsvlGroupValue used during instantiation.
     */
    public void setNsvlGroupValue(YangUInt16 nsvlGroupValue)
            throws JNCException {
        setLeafValue(Epc.NAMESPACE,
            "nsvl-group",
            nsvlGroupValue,
            childrenNames());
    }

    /**
     * Sets the value for child leaf "nsvl-group",
     * using Java primitive values.
     * @param nsvlGroupValue used during instantiation.
     */
    public void setNsvlGroupValue(int nsvlGroupValue) throws JNCException {
        setNsvlGroupValue(new YangUInt16(nsvlGroupValue));
    }

    /**
     * Sets the value for child leaf "nsvl-group",
     * using a String value.
     * @param nsvlGroupValue used during instantiation.
     */
    public void setNsvlGroupValue(String nsvlGroupValue) throws JNCException {
        setNsvlGroupValue(new YangUInt16(nsvlGroupValue));
    }

    /**
     * Unsets the value for child leaf "nsvl-group".
     */
    public void unsetNsvlGroupValue() throws JNCException {
        delete("nsvl-group");
    }

    /**
     * This method is used for creating a subtree filter.
     * The added "nsvl-group" leaf will not have a value.
     */
    public void addNsvlGroup() throws JNCException {
        setLeafValue(Epc.NAMESPACE,
            "nsvl-group",
            null,
            childrenNames());
    }

    /**
     * Marks the leaf "nsvl-group" with operation "replace".
     */
    public void markNsvlGroupReplace() throws JNCException {
        markLeafReplace("nsvlGroup");
    }

    /**
     * Marks the leaf "nsvl-group" with operation "merge".
     */
    public void markNsvlGroupMerge() throws JNCException {
        markLeafMerge("nsvlGroup");
    }

    /**
     * Marks the leaf "nsvl-group" with operation "create".
     */
    public void markNsvlGroupCreate() throws JNCException {
        markLeafCreate("nsvlGroup");
    }

    /**
     * Marks the leaf "nsvl-group" with operation "delete".
     */
    public void markNsvlGroupDelete() throws JNCException {
        markLeafDelete("nsvlGroup");
    }

    /* Access methods for optional leaf child: "nsvl". */

    /**
     * Gets the value for child leaf "nsvl".
     * @return The value of the leaf.
     */
    public YangUInt16 getNsvlValue() throws JNCException {
        return (YangUInt16)getValue("nsvl");
    }

    /**
     * Sets the value for child leaf "nsvl",
     * using instance of generated typedef class.
     * @param nsvlValue The value to set.
     * @param nsvlValue used during instantiation.
     */
    public void setNsvlValue(YangUInt16 nsvlValue) throws JNCException {
        setLeafValue(Epc.NAMESPACE,
            "nsvl",
            nsvlValue,
            childrenNames());
    }

    /**
     * Sets the value for child leaf "nsvl",
     * using Java primitive values.
     * @param nsvlValue used during instantiation.
     */
    public void setNsvlValue(int nsvlValue) throws JNCException {
        setNsvlValue(new YangUInt16(nsvlValue));
    }

    /**
     * Sets the value for child leaf "nsvl",
     * using a String value.
     * @param nsvlValue used during instantiation.
     */
    public void setNsvlValue(String nsvlValue) throws JNCException {
        setNsvlValue(new YangUInt16(nsvlValue));
    }

    /**
     * Unsets the value for child leaf "nsvl".
     */
    public void unsetNsvlValue() throws JNCException {
        delete("nsvl");
    }

    /**
     * This method is used for creating a subtree filter.
     * The added "nsvl" leaf will not have a value.
     */
    public void addNsvl() throws JNCException {
        setLeafValue(Epc.NAMESPACE,
            "nsvl",
            null,
            childrenNames());
    }

    /**
     * Marks the leaf "nsvl" with operation "replace".
     */
    public void markNsvlReplace() throws JNCException {
        markLeafReplace("nsvl");
    }

    /**
     * Marks the leaf "nsvl" with operation "merge".
     */
    public void markNsvlMerge() throws JNCException {
        markLeafMerge("nsvl");
    }

    /**
     * Marks the leaf "nsvl" with operation "create".
     */
    public void markNsvlCreate() throws JNCException {
        markLeafCreate("nsvl");
    }

    /**
     * Marks the leaf "nsvl" with operation "delete".
     */
    public void markNsvlDelete() throws JNCException {
        markLeafDelete("nsvl");
    }

    /**
     * Support method for addChild.
     * Adds a child to this object.
     *
     * @param child The child to add
     */
    public void addChild(Element child) {
        super.addChild(child);
    }

}


text:
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Cloud.AIPlatform.V1.Schema.Predict.Instance {

  /// Holder for reflection information generated from google/cloud/aiplatform/v1/schema/predict/instance/text_sentiment.proto
  public static partial class TextSentimentReflection {

    #region Descriptor
    /// File descriptor for google/cloud/aiplatform/v1/schema/predict/instance/text_sentiment.proto
    public static pbr::FileDescriptor Descriptor {
      get { return descriptor; }
    }
    private static pbr::FileDescriptor descriptor;

    static TextSentimentReflection() {
      byte[] descriptorData = global::System.Convert.FromBase64String(
          string.Concat(
            "Ckdnb29nbGUvY2xvdWQvYWlwbGF0Zm9ybS92MS9zY2hlbWEvcHJlZGljdC9p",
            "bnN0YW5jZS90ZXh0X3NlbnRpbWVudC5wcm90bxIyZ29vZ2xlLmNsb3VkLmFp",
            "cGxhdGZvcm0udjEuc2NoZW1hLnByZWRpY3QuaW5zdGFuY2UaHGdvb2dsZS9h",
            "cGkvYW5ub3RhdGlvbnMucHJvdG8iRQofVGV4dFNlbnRpbWVudFByZWRpY3Rp",
            "b25JbnN0YW5jZRIPCgdjb250ZW50GAEgASgJEhEKCW1pbWVfdHlwZRgCIAEo",
            "CULhAgo2Y29tLmdvb2dsZS5jbG91ZC5haXBsYXRmb3JtLnYxLnNjaGVtYS5w",
            "cmVkaWN0Lmluc3RhbmNlQiRUZXh0U2VudGltZW50UHJlZGljdGlvbkluc3Rh",
            "bmNlUHJvdG9QAVpaZ29vZ2xlLmdvbGFuZy5vcmcvZ2VucHJvdG8vZ29vZ2xl",
            "YXBpcy9jbG91ZC9haXBsYXRmb3JtL3YxL3NjaGVtYS9wcmVkaWN0L2luc3Rh",
            "bmNlO2luc3RhbmNlqgIyR29vZ2xlLkNsb3VkLkFJUGxhdGZvcm0uVjEuU2No",
            "ZW1hLlByZWRpY3QuSW5zdGFuY2XKAjJHb29nbGVcQ2xvdWRcQUlQbGF0Zm9y",
            "bVxWMVxTY2hlbWFcUHJlZGljdFxJbnN0YW5jZeoCOEdvb2dsZTo6Q2xvdWQ6",
            "OkFJUGxhdGZvcm06OlYxOjpTY2hlbWE6OlByZWRpY3Q6Okluc3RhbmNlYgZw",
            "cm90bzM="));
      descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
          new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, },
          new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
            new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.AIPlatform.V1.Schema.Predict.Instance.TextSentimentPredictionInstance), global::Google.Cloud.AIPlatform.V1.Schema.Predict.Instance.TextSentimentPredictionInstance.Parser, new[]{ "Content", "MimeType" }, null, null, null, null)
          }));
    }
    #endregion

  }
  #region Messages
  ///
  /// Prediction input format for Text Sentiment.
  ///
  public sealed partial class TextSentimentPredictionInstance : pb::IMessage<TextSentimentPredictionInstance>
  #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
      , pb::IBufferMessage
  #endif
  {
    private static readonly pb::MessageParser<TextSentimentPredictionInstance> _parser = new pb::MessageParser<TextSentimentPredictionInstance>(() => new TextSentimentPredictionInstance());
    private pb::UnknownFieldSet _unknownFields;
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public static pb::MessageParser<TextSentimentPredictionInstance> Parser { get { return _parser; } }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public static pbr::MessageDescriptor Descriptor {
      get { return global::Google.Cloud.AIPlatform.V1.Schema.Predict.Instance.TextSentimentReflection.Descriptor.MessageTypes[0]; }
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    pbr::MessageDescriptor pb::IMessage.Descriptor {
      get { return Descriptor; }
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public TextSentimentPredictionInstance() {
      OnConstruction();
    }

    partial void OnConstruction();

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public TextSentimentPredictionInstance(TextSentimentPredictionInstance other) : this() {
      content_ = other.content_;
      mimeType_ = other.mimeType_;
      _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public TextSentimentPredictionInstance Clone() {
      return new TextSentimentPredictionInstance(this);
    }

    /// Field number for the "content" field.
    public const int ContentFieldNumber = 1;
    private string content_ = "";
    ///
    /// The text snippet to make the predictions on.
    ///
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public string Content {
      get { return content_; }
      set {
        content_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
      }
    }

    /// Field number for the "mime_type" field.
    public const int MimeTypeFieldNumber = 2;
    private string mimeType_ = "";
    ///
    /// The MIME type of the text snippet. The supported MIME types are listed
    /// below.
    /// - text/plain
    ///
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public string MimeType {
      get { return mimeType_; }
      set {
        mimeType_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
      }
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public override bool Equals(object other) {
      return Equals(other as TextSentimentPredictionInstance);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public bool Equals(TextSentimentPredictionInstance other) {
      if (ReferenceEquals(other, null)) {
        return false;
      }
      if (ReferenceEquals(other, this)) {
        return true;
      }
      if (Content != other.Content) return false;
      if (MimeType != other.MimeType) return false;
      return Equals(_unknownFields, other._unknownFields);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public override int GetHashCode() {
      int hash = 1;
      if (Content.Length != 0) hash ^= Content.GetHashCode();
      if (MimeType.Length != 0) hash ^= MimeType.GetHashCode();
      if (_unknownFields != null) {
        hash ^= _unknownFields.GetHashCode();
      }
      return hash;
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public override string ToString() {
      return pb::JsonFormatter.ToDiagnosticString(this);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public void WriteTo(pb::CodedOutputStream output) {
    #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
      output.WriteRawMessage(this);
    #else
      if (Content.Length != 0) {
        output.WriteRawTag(10);
        output.WriteString(Content);
      }
      if (MimeType.Length != 0) {
        output.WriteRawTag(18);
        output.WriteString(MimeType);
      }
      if (_unknownFields != null) {
        _unknownFields.WriteTo(output);
      }
    #endif
    }

    #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
      if (Content.Length != 0) {
        output.WriteRawTag(10);
        output.WriteString(Content);
      }
      if (MimeType.Length != 0) {
        output.WriteRawTag(18);
        output.WriteString(MimeType);
      }
      if (_unknownFields != null) {
        _unknownFields.WriteTo(ref output);
      }
    }
    #endif

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public int CalculateSize() {
      int size = 0;
      if (Content.Length != 0) {
        size += 1 + pb::CodedOutputStream.ComputeStringSize(Content);
      }
      if (MimeType.Length != 0) {
        size += 1 + pb::CodedOutputStream.ComputeStringSize(MimeType);
      }
      if (_unknownFields != null) {
        size += _unknownFields.CalculateSize();
      }
      return size;
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public void MergeFrom(TextSentimentPredictionInstance other) {
      if (other == null) {
        return;
      }
      if (other.Content.Length != 0) {
        Content = other.Content;
      }
      if (other.MimeType.Length != 0) {
        MimeType = other.MimeType;
      }
      _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public void MergeFrom(pb::CodedInputStream input) {
    #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
      input.ReadRawMessage(this);
    #else
      uint tag;
      while ((tag = input.ReadTag()) != 0) {
        switch(tag) {
          default:
            _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
            break;
          case 10: {
            Content = input.ReadString();
            break;
          }
          case 18: {
            MimeType = input.ReadString();
            break;
          }
        }
      }
    #endif
    }

    #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
      uint tag;
      while ((tag = input.ReadTag()) != 0) {
        switch(tag) {
          default:
            _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
            break;
          case 10: {
            Content = input.ReadString();
            break;
          }
          case 18: {
            MimeType = input.ReadString();
            break;
          }
        }
      }
    }
    #endif

  }

  #endregion

}

#endregion Designer generated code


text:
layout: post

title:  'Saving JSON responses to your model in Scala'
date:   2016-01-05 20:00:00
image:  json-logo.png
image_alt: 'JSON logo'

tags: [tutorials, scala, json, play-framework]
---
If you deal with external APIs (like Twitter, Facebook, Intercom, Github, and many others) on a regular basis there's a big chance that you have already dealt with [JSON](http://www.json.org/) answers before.

*JSON* (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages.

JSON is built on two structures:

* A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
* An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

A JSON object can be as simple as

~~~json
{
  "key": "value"
}
~~~

containing just a simple key and value pair - in the limit, it could also be an empty set of key-values pair - or as complex as one wishes it:

~~~json
{
  "widget" : {
    "debug" : "on",
    "window" : {
      "title" : "Sample Konfabulator Widget",
      "name" : "main_window",
      "width" : 500,
      "height" : 500
    },
    "image" : {
      "src" : "Images/Sun.png",
      "name" : "sun1",
      "hOffset" : 250,
      "vOffset" : 250,
      "alignment" : "center"
    },
    "text" : {
      "data" : "Click Here",
      "size" : 36,
      "style" : "bold",
      "name" : "text1",
      "hOffset" : 250,
      "vOffset" : 100,
      "alignment" : "center",
      "onMouseUp" : "sun1.opacity = (sun1.opacity / 100) * 90;"
    }
  }
}
~~~

There are [many other examples available](http://json.org/example.html).

## Scala and JSON

In most cases you will want to access and save information contained on the JSON document. [Play](https://www.playframework.com/) provides a very complete library for dealing with JSON objects, [Play JSON](https://www.playframework.com/documentation/2.4.x/ScalaJson).

> Note: If you are not including Play on your dependencies you can just include Play Json with

> `libraryDependencies += "com.typesafe.play" % "play-json_2.11" % "2.4.6"`

For this example we will use [GitHub API](https://developer.github.com/v3/). If you access [my user endpoint](https://api.github.com/users/pedrorijo91) you will get information about my user, in JSON. You should get something like:

~~~json
{
  "login": "pedrorijo91",
  "id": 1999050,
  "avatar_url": "https://avatars.githubusercontent.com/u/1999050?v=3",
  "gravatar_id": "",
  "url": "https://api.github.com/users/pedrorijo91",
  "html_url": "https://github.com/pedrorijo91",
  "followers_url": "https://api.github.com/users/pedrorijo91/followers",
  "following_url": "https://api.github.com/users/pedrorijo91/following{/other_user}",
  "gists_url": "https://api.github.com/users/pedrorijo91/gists{/gist_id}",
  "starred_url": "https://api.github.com/users/pedrorijo91/starred{/owner}{/repo}",
  "subscriptions_url": "https://api.github.com/users/pedrorijo91/subscriptions",
  "organizations_url": "https://api.github.com/users/pedrorijo91/orgs",
  "repos_url": "https://api.github.com/users/pedrorijo91/repos",
  "events_url": "https://api.github.com/users/pedrorijo91/events{/privacy}",
  "received_events_url": "https://api.github.com/users/pedrorijo91/received_events",
  "type": "User",
  "site_admin": false,
  "name": "Pedro Rijo",
  "company": "Codacy",
  "blog": "http://pedrorijo.com/",
  "location": "Lisbon, Portugal",
  "email": null,
  "hireable": true,
  "bio": null,
  "public_repos": 35,
  "public_gists": 4,
  "followers": 23,
  "following": 62,
  "created_at": "2012-07-18T14:34:35Z",
  "updated_at": "2016-01-05T00:02:37Z"
}
~~~

Now let's parse it. Suppose this answer is saved in a value named `jsonString`, then all you need to do is:

~~~scala
import play.api.libs.json.Json
val jsonObject = Json.parse(jsonString)
~~~

and you will get the JSON object, ready to be easily queried. The easiest way to access fields is using the `'\'` operator.
For instance, to get the `login` field you just need to write:

~~~scala
val login = jsonObject \ "login"
~~~

and you will get a `JsValue` with the value `pedrorijo91`. You can now convert this to a `String`, or any other type, using:

~~~scala
login.as[String]
~~~

> Note: when testing, it may be useful to experiment on the sbt console, and when saving the JSON strings in a value, the [triple quote](http://www.scala-lang.org/old/node/5514) may be handy

## Saving JSON documents to model objects

That was the first part. What about saving the information? You probably want to map it to domain objects. The easiest way is to use `case classes`.

Imagine that some API returned the following answer:

~~~json
{
  "username": "pedrorijo91",
  "friends": 100,
  "enemies": 10,
  "isAlive": "true"
}
~~~

and you have the following model:

~~~scala
case class User(username: String, friends: Int, enemies: Int, isAlive: Boolean)
~~~

To easily convert your JSON object to an `User`, add the companion object with an implicit formatter:

~~~scala
case class User(username: String, friends: Int, enemies: Int, isAlive: Boolean)

object User {
  implicit val userJsonFormat = Json.format[User]
}
~~~

Now, if you simply do:

~~~scala
val jsonString = """ {"username":"pedrorijo91","friends":100,"enemies":10,"isAlive":"true"} """
val jsonObject = Json.parse(jsonString)
jsonObject.as[User]
~~~

You will get an `User` with the expected fields defined. You can get to know more on the [official documentation](https://www.playframework.com/documentation/2.4.x/ScalaJson#JsValue-to-a-model)

> Note, actually you just need `Json.reads[User]` on the companion object. The `format` allows you to also write a model as JSON directly.

## Life ain't perfect

Unfortunately, some APIs we deal with, are not as nice. Suppose that instead of a `isAlive` field, the JSON had an `is_alive` field. Then the mapping between JSON and our model wouldn't be direct as before.

There are two alternatives:

1.  Adapt the case class

    Instead of a a `isAlive` we can name the class field `is_alive`

    ~~~scala
    case class User(username: String, friends: Int, enemies: Int, is_alive: Boolean)
    ~~~

    This creates an awful field accessor (`is_alive`). One solution may be to hide that accessor, creating a wrapper. Add the `private` qualifier and create a wrapper method:

    ~~~scala
    case class User(username: String, friends: Int, enemies: Int, private val is_alive: Boolean) {
      def isAlive: Boolean = is_alive
    }
    ~~~

2.  Create a custom Reads on the companion object

    ~~~scala
    case class User(username: String, friends: Int, enemies: Int, isAlive: Boolean)

    object User {

      import play.api.libs.functional.syntax._
      import play.api.libs.json._

      implicit val userReads: Reads[User] = (
          (JsPath \ "username").read[String] and
          (JsPath \ "friends").read[Int] and
          (JsPath \ "enemies").read[Int] and
          (JsPath \ "is_alive").read[Boolean]
        ) (User.apply _)
    }
    ~~~

    This custom Reads maps each JSON field to the case class constructor, allowing you to keep a nice case class, while creating instances directly from JSON objects.

Yet another problem, what about APIs returning JSON with optional fields? What if the `isAlive` field is not always present? Then the solution would be to use `readNullable` and make the field optional:

~~~scala
case class User(username: String, friends: Int, enemies: Int, isAlive: Option[Boolean])

object User {

  import play.api.libs.functional.syntax._
  import play.api.libs.json._

  implicit val userReads: Reads[User] = (
      (JsPath \ "username").read[String] and
      (JsPath \ "friends").read[Int] and
      (JsPath \ "enemies").read[Int] and
      (JsPath \ "is_alive").readNullable[Boolean]
    ) (User.apply _)
}
~~~

Now you can map JSON answers to your model and deal with that information with all the benefits Scala provides.

What about you? Do you have any other technique for dealing with JSON in Scala?

## Follow up

If you want to see more advanced features, check out the follow up on [Saving JSON to Scala model - Part 2]({{ site.url }}/blog/scala-json-part2)

Also, checkout the source code at [GitHub](https://github.com/pedrorijo91/scala-play-json-examples) if you have any doubt.


text:
package depoi.austral.services.impl;

import java.util.List;

import depoi.austral.dao.IBetUnitDataDao;
import depoi.austral.dao.interfaces.IBetDao2;
import depoi.austral.dao.interfaces.IUserDao;
import depoi.austral.model.Tournament;
import depoi.austral.model.User;
import depoi.austral.model.jdo.BetUnitData;
import depoi.austral.model.other.BetUnit;
import depoi.austral.services.BetService;

public class BetServiceImpl implements BetService {
	IBetUnitDataDao betUnitDataDao;
	private IBetDao2 betDao;
	private IUserDao userDao;

	@Override
	public void add(BetUnit betUnit) throws Exception {
		betDao.add(betUnit);
	}

	@Override
	public List<BetUnit> forUserInTournament(User user, Tournament tournament)
			throws Exception {
		return betDao.forUserInTournament(user, tournament);
	}

	@Override
	public void modify(Long id, BetUnit newParams) throws Exception {
		betDao.modify(id, newParams);
	}

	public IBetDao2 getBetDao() {
		return betDao;
	}

	public void setBetDao(IBetDao2 betDao) {
		this.betDao = betDao;
	}

	@Override
	public BetUnit getById(Long id) throws Exception {
		return betDao.getById(id);
	}

	@Override
	public boolean canBetUser(BetUnit betUnit, User user) throws Exception {
		// TODO Auto-generated method stub
		BetUnit betUnitTemp = betDao.getById(betUnit.getId());

		String userMail = user.getMail();

		boolean answer = false;

		if (betUnitTemp != null) {
			BetUnitData betUnitData = betUnitDataDao.getById(betUnit.getId());
			String otherMail = betUnitData.getUserMail();
			boolean check = (otherMail.compareTo(userMail) == 0);
			if (check) {
				answer = true;
			}
		}
		return answer;
	}

	public IBetUnitDataDao getBetUnitDataDao() {
		return betUnitDataDao;
	}

	public void setBetUnitDataDao(IBetUnitDataDao betUnitDataDao) {
		this.betUnitDataDao = betUnitDataDao;
	}

	public IUserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(IUserDao userDao) {
		this.userDao = userDao;
	}

}


text:
from django import template
from django_lifestream import utils

register = template.Library()

def simple_lifestream(context):
	tpl = template.loader.get_template('django_lifestream/tags/simple_lifestream_entry.html')
	entries = utils.load_entries()
	compiled_entries = ''.join([tpl.render({'entry':entry}) for entry in entries])
	return {
		'entries':compiled_entries,
	}

register.inclusion_tag('django_lifestream/tags/simple_lifestream.html',takes_context=True)(simple_lifestream)


text:
from __future__ import unicode_literals

import json

from gratipay.testing import Harness
from gratipay.testing.billing import PaydayMixin

class Tests(Harness, PaydayMixin):

    def test_paydays_json_gives_paydays(self):
        self.start_payday()
        self.make_participant("alice")

        response = self.client.GET("/about/paydays.json")
        paydays = json.loads(response.body)
        assert paydays[0]['nusers'] == 0


text:
<?php

class Google_Service_Prediction_AnalyzeDataDescription extends Google_Collection
{
  protected $collection_key = 'features';
  protected $featuresType = 'Google_Service_Prediction_AnalyzeDataDescriptionFeatures';
  protected $featuresDataType = 'array';
  protected $outputFeatureType = 'Google_Service_Prediction_AnalyzeDataDescriptionOutputFeature';
  protected $outputFeatureDataType = '';

  public function setFeatures($features)
  {
    $this->features = $features;
  }
  public function getFeatures()
  {
    return $this->features;
  }
  public function setOutputFeature(Google_Service_Prediction_AnalyzeDataDescriptionOutputFeature $outputFeature)
  {
    $this->outputFeature = $outputFeature;
  }
  public function getOutputFeature()
  {
    return $this->outputFeature;
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
	xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
                        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">

	<!-- DO NOT FORGET THE SESSIONFILTER! The SessionFilter also handles security
		and incoming calls.  -->

	<!-- Default authentication manager -->
	<http auto-config="true">
        <csrf disabled="true"/>
        <headers disabled="true" />

		<intercept-url pattern="/services/*"
			access="IS_AUTHENTICATED_ANONYMOUSLY" />
		<session-management>
			<concurrency-control
				max-sessions="1" error-if-maximum-exceeded="true" />
		</session-management>

	</http>

	<authentication-manager>
		<authentication-provider>
			<user-service>
				<user name="bullhornadmin" password="mrtoad"
					authorities="ROLE_ADMIN" />
			</user-service>
		</authentication-provider>
	</authentication-manager>

</beans:beans>


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:background="@color/colorWhite"
              android:orientation="vertical">
    <RelativeLayout android:layout_width="match_parent"
                    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/dm030"
        android:layout_marginTop="@dimen/dm030"
        android:orientation="horizontal">
        <ImageView
            android:id="@+id/iv_myself_subscribe_public_img"
            android:layout_width="@dimen/dm130"
            android:layout_height="@dimen/dm130"
            android:layout_marginLeft="@dimen/dm018"
            android:src="@drawable/public_img"/>
        <LinearLayout
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="match_parent"
            android:layout_marginLeft="@dimen/dm025"
            android:orientation="vertical">
            <TextView
                android:id="@+id/tv_myself_subscribe_public_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/dm002"
                android:text="炒股指南"
                android:textColor="@color/titleText"
                android:textSize="@dimen/dm028"/>
            <TextView
                android:id="@+id/tv_myself_subscribe_public_from"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/dm010"
                android:text="中方信富首席工作室"
                android:textColor="@color/colorText"
                android:textSize="@dimen/dm024"/>
            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/dm010"
                android:orientation="horizontal">
                <TextView
                    android:id="@+id/tv_myself_subscribe_public_day"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="2017/04/01"
                    android:textColor="@color/colorText"
                    android:textSize="@dimen/dm024"/>
            </LinearLayout>
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginRight="@dimen/dm020"
            android:orientation="vertical">
            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/dm007"
                android:layout_gravity="right"
                android:orientation="horizontal">
                <TextView
                    android:id="@+id/tv_myself_subscribe_public_count"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="1468"
                    android:textColor="@color/colorTitle"
                    android:textSize="@dimen/dm022"/>
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="@dimen/dm010"
                    android:text="人参与"
                    android:textColor="@color/titleTextGray"
                    android:textSize="@dimen/dm022"/>
            </LinearLayout>
            <TextView
                android:id="@+id/tv_myself_subscribe_public_money"
                android:layout_width="wrap_content"
                android:layout_gravity="right"
                android:layout_marginTop="@dimen/dm050"
                android:gravity="center"
                android:layout_height="wrap_content"
                android:text="¥299元"
                android:textColor="@color/colorTitle"
                android:textSize="@dimen/dm028"/>
        </LinearLayout>
    </LinearLayout>
    </RelativeLayout>

</LinearLayout>


text:
using namespace luabind;

template <typename T>
struct CWrapperBase : public T, public luabind::wrap_base {
	typedef T inherited;
	typedef CWrapperBase<T>	self_type;

	DEFINE_LUA_WRAPPER_METHOD_R2P1_V1(net_Export, NET_Packet)
	DEFINE_LUA_WRAPPER_METHOD_R2P1_V1(net_Import, NET_Packet)
	DEFINE_LUA_WRAPPER_METHOD_V0(clear)
};

#pragma optimize("s",on)
void game_PlayerState::script_register(lua_State *L)
{
	typedef CWrapperBase<game_PlayerState> WrapType;
	typedef game_PlayerState BaseType;

	module(L)
		[
			luabind::class_<game_PlayerState, WrapType>("game_PlayerState")
			.def(	constructor<>())
			.def_readwrite("team",				&BaseType::team)
			.def_readwrite("kills",				&BaseType::m_iRivalKills)
			.def_readwrite("deaths",			&BaseType::m_iDeaths)
			.def_readwrite("money_for_round",	&BaseType::money_for_round)
			.def_readwrite("flags",				&BaseType::flags__)
			.def_readwrite("ping",				&BaseType::ping)
			.def_readwrite("GameID",			&BaseType::GameID)
//.			.def_readwrite("Skip",				&BaseType::Skip)
			.def_readwrite("lasthitter",		&BaseType::lasthitter)
			.def_readwrite("lasthitweapon",		&BaseType::lasthitweapon)
			.def_readwrite("skin",				&BaseType::skin)
			.def_readwrite("RespawnTime",		&BaseType::RespawnTime)
			.def_readwrite("money_delta",		&BaseType::money_delta)

			.def_readwrite("pItemList",			&BaseType::pItemList)
			.def_readwrite("LastBuyAcount",		&BaseType::LastBuyAcount)
			.def("testFlag",					&BaseType::testFlag)
			.def("setFlag",						&BaseType::setFlag)
			.def("resetFlag",					&BaseType::resetFlag)
			.def("getName",						&BaseType::getName)
			.def("setName",						&BaseType::setName)
			.def("clear",						&BaseType::clear, &WrapType::clear_static)
			.def("net_Export",					&BaseType::net_Export, &WrapType::net_Export_static)
			.def("net_Import",					&BaseType::net_Import, &WrapType::net_Import_static)

		];
}

void game_GameState::script_register(lua_State *L)
{

	module(L)
		[
			luabind::class_< game_GameState, DLL_Pure >("game_GameState")
			.def(	constructor<>())

			.def_readwrite("type",				&game_GameState::m_type)
			.def_readonly("round",				&game_GameState::m_round)
			.def_readonly("start_time",			&game_GameState::m_start_time)

			.def("Type",						&game_GameState::Type)
			.def("Phase",						&game_GameState::Phase)
			.def("Round",						&game_GameState::Round)
			.def("StartTime",					&game_GameState::StartTime)
		];

}


text:
<?php

use Phalcon\Mvc\Application;

/**
 * Handle the request
 */
$application = new \Phalcon\Mvc\Application($di);

/**
 * Register application modules
 */
if (isset($modules) && !empty($modules)) {
    $application->registerModules($modules);
}

echo $application->handle()->getContent();


text:
package com.facebook.react.views.view;

import javax.annotation.Nullable;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.view.animation.Animation;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import com.facebook.infer.annotation.Assertions;
import com.facebook.react.common.annotations.VisibleForTesting;
import com.facebook.react.touch.ReactHitSlopView;
import com.facebook.react.touch.ReactInterceptingViewGroup;
import com.facebook.react.touch.OnInterceptTouchEventListener;
import com.facebook.react.uimanager.*;
import com.facebook.react.uimanager.ReactClippingViewGroupHelper;

/**
 * Backing for a React View. Has support for borders, but since borders aren't common, lazy
 * initializes most of the storage needed for them.
 */
public class ReactViewGroup extends ViewGroup implements
    ReactInterceptingViewGroup, com.facebook.react.uimanager.ReactClippingViewGroup, ReactPointerEventsView, ReactHitSlopView {

  private static final int ARRAY_CAPACITY_INCREMENT = 12;
  private static final int DEFAULT_BACKGROUND_COLOR = Color.TRANSPARENT;
  private static final LayoutParams sDefaultLayoutParam = new ViewGroup.LayoutParams(0, 0);
  /* should only be used in {@link #updateClippingToRect} */
  private static final Rect sHelperRect = new Rect();

  /**
   * This listener will be set for child views when removeClippedSubview property is enabled. When
   * children layout is updated, it will call {@link #updateSubviewClipStatus} to notify parent
   * view about that fact so that view can be attached/detached if necessary.
   *
   * TODO(7728005): Attach/detach views in batch - once per frame in case when multiple children
   * update their layout.
   */
  private static final class ChildrenLayoutChangeListener implements OnLayoutChangeListener {

    private final ReactViewGroup mParent;

    private ChildrenLayoutChangeListener(ReactViewGroup parent) {
      mParent = parent;
    }

    @Override
    public void onLayoutChange(
        View v,
        int left,
        int top,
        int right,
        int bottom,
        int oldLeft,
        int oldTop,
        int oldRight,
        int oldBottom) {
      if (mParent.getRemoveClippedSubviews()) {
        mParent.updateSubviewClipStatus(v);
      }
    }
  }

  // Following properties are here to support the option {@code removeClippedSubviews}. This is a
  // temporary optimization/hack that is mainly applicable to the large list of images. The way
  // it's implemented is that we store an additional array of children in view node. We selectively
  // remove some of the views (detach) from it while still storing them in that additional array.
  // We override all possible add methods for {@link ViewGroup} so that we can control this process
  // whenever the option is set. We also override {@link ViewGroup#getChildAt} and
  // {@link ViewGroup#getChildCount} so those methods may return views that are not attached.
  // This is risky but allows us to perform a correct cleanup in {@link NativeViewHierarchyManager}.
  private boolean mRemoveClippedSubviews = false;
  private @Nullable View[] mAllChildren = null;
  private int mAllChildrenCount;
  private @Nullable Rect mClippingRect;
  private @Nullable Rect mHitSlopRect;
  private PointerEvents mPointerEvents = PointerEvents.AUTO;
  private @Nullable ChildrenLayoutChangeListener mChildrenLayoutChangeListener;
  private @Nullable ReactViewBackgroundDrawable mReactBackgroundDrawable;
  private @Nullable OnInterceptTouchEventListener mOnInterceptTouchEventListener;
  private boolean mNeedsOffscreenAlphaCompositing = false;

  public ReactViewGroup(Context context) {
    super(context);
  }

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    MeasureSpecAssertions.assertExplicitMeasureSpec(widthMeasureSpec, heightMeasureSpec);

    setMeasuredDimension(
        MeasureSpec.getSize(widthMeasureSpec),
        MeasureSpec.getSize(heightMeasureSpec));
  }

  @Override
  protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    // No-op since UIManagerModule handles actually laying out children.
  }

  @Override
  public void requestLayout() {
    // No-op, terminate `requestLayout` here, UIManagerModule handles laying out children and
    // `layout` is called on all RN-managed views by `NativeViewHierarchyManager`
  }

  @Override
  public void setBackgroundColor(int color) {
    if (color == Color.TRANSPARENT && mReactBackgroundDrawable == null) {
      // don't do anything, no need to allocate ReactBackgroundDrawable for transparent background
    } else {
      getOrCreateReactViewBackground().setColor(color);
    }
  }

  @Override
  public void setBackground(Drawable drawable) {
    throw new UnsupportedOperationException(
        "This method is not supported for ReactViewGroup instances");
  }

  public void setTranslucentBackgroundDrawable(@Nullable Drawable background) {
    // it's required to call setBackground to null, as in some of the cases we may set new
    // background to be a layer drawable that contains a drawable that has been previously setup
    // as a background previously. This will not work correctly as the drawable callback logic is
    // messed up in AOSP
    super.setBackground(null);
    if (mReactBackgroundDrawable != null && background != null) {
      LayerDrawable layerDrawable =
          new LayerDrawable(new Drawable[] {mReactBackgroundDrawable, background});
      super.setBackground(layerDrawable);
    } else if (background != null) {
      super.setBackground(background);
    }
  }

  @Override
  public void setOnInterceptTouchEventListener(OnInterceptTouchEventListener listener) {
    mOnInterceptTouchEventListener = listener;
  }

  @Override
  public boolean onInterceptTouchEvent(MotionEvent ev) {
    if (mOnInterceptTouchEventListener != null &&
        mOnInterceptTouchEventListener.onInterceptTouchEvent(this, ev)) {
      return true;
    }
    // We intercept the touch event if the children are not supposed to receive it.
    if (mPointerEvents == PointerEvents.NONE || mPointerEvents == PointerEvents.BOX_ONLY) {
      return true;
    }
    return super.onInterceptTouchEvent(ev);
  }

  @Override
  public boolean onTouchEvent(MotionEvent ev) {
    // We do not accept the touch event if this view is not supposed to receive it.
    if (mPointerEvents == PointerEvents.NONE || mPointerEvents == PointerEvents.BOX_NONE) {
      return false;
    }
    // The root view always assumes any view that was tapped wants the touch
    // and sends the event to JS as such.
    // We don't need to do bubbling in native (it's already happening in JS).
    // For an explanation of bubbling and capturing, see
    // http://javascript.info/tutorial/bubbling-and-capturing#capturing
    return true;
  }

  /**
   * We override this to allow developers to determine whether they need offscreen alpha compositing
   * or not. See the documentation of needsOffscreenAlphaCompositing in View.js.
   */
  @Override
  public boolean hasOverlappingRendering() {
    return mNeedsOffscreenAlphaCompositing;
  }

  /**
   * See the documentation of needsOffscreenAlphaCompositing in View.js.
   */
  public void setNeedsOffscreenAlphaCompositing(boolean needsOffscreenAlphaCompositing) {
    mNeedsOffscreenAlphaCompositing = needsOffscreenAlphaCompositing;
  }

  public void setBorderWidth(int position, float width) {
    getOrCreateReactViewBackground().setBorderWidth(position, width);
  }

  public void setBorderColor(int position, float rgb, float alpha) {
    getOrCreateReactViewBackground().setBorderColor(position, rgb, alpha);
  }

  public void setBorderRadius(float borderRadius) {
    getOrCreateReactViewBackground().setRadius(borderRadius);
  }

  public void setBorderRadius(float borderRadius, int position) {
    getOrCreateReactViewBackground().setRadius(borderRadius, position);
  }

  public void setBorderStyle(@Nullable String style) {
    getOrCreateReactViewBackground().setBorderStyle(style);
  }

  @Override
  public void setRemoveClippedSubviews(boolean removeClippedSubviews) {
    if (removeClippedSubviews == mRemoveClippedSubviews) {
      return;
    }
    mRemoveClippedSubviews = removeClippedSubviews;
    if (removeClippedSubviews) {
      mClippingRect = new Rect();
      com.facebook.react.uimanager.ReactClippingViewGroupHelper
        .calculateClippingRect(this, mClippingRect);
      mAllChildrenCount = getChildCount();
      int initialSize = Math.max(12, mAllChildrenCount);
      mAllChildren = new View[initialSize];
      mChildrenLayoutChangeListener = new ChildrenLayoutChangeListener(this);
      for (int i = 0; i < mAllChildrenCount; i++) {
        View child = getChildAt(i);
        mAllChildren[i] = child;
        child.addOnLayoutChangeListener(mChildrenLayoutChangeListener);
      }
      updateClippingRect();
    } else {
      // Add all clipped views back, deallocate additional arrays, remove layoutChangeListener
      Assertions.assertNotNull(mClippingRect);
      Assertions.assertNotNull(mAllChildren);
      Assertions.assertNotNull(mChildrenLayoutChangeListener);
      for (int i = 0; i < mAllChildrenCount; i++) {
        mAllChildren[i].removeOnLayoutChangeListener(mChildrenLayoutChangeListener);
      }
      getDrawingRect(mClippingRect);
      updateClippingToRect(mClippingRect);
      mAllChildren = null;
      mClippingRect = null;
      mAllChildrenCount = 0;
      mChildrenLayoutChangeListener = null;
    }
  }

  @Override
  public boolean getRemoveClippedSubviews() {
    return mRemoveClippedSubviews;
  }

  @Override
  public void getClippingRect(Rect outClippingRect) {
    outClippingRect.set(mClippingRect);
  }

  @Override
  public void updateClippingRect() {
    if (!mRemoveClippedSubviews) {
      return;
    }

    Assertions.assertNotNull(mClippingRect);
    Assertions.assertNotNull(mAllChildren);

    ReactClippingViewGroupHelper.calculateClippingRect(this, mClippingRect);
    updateClippingToRect(mClippingRect);
  }

  private void updateClippingToRect(Rect clippingRect) {
    Assertions.assertNotNull(mAllChildren);
    int clippedSoFar = 0;
    for (int i = 0; i < mAllChildrenCount; i++) {
      updateSubviewClipStatus(clippingRect, i, clippedSoFar);
      if (mAllChildren[i].getParent() == null) {
        clippedSoFar++;
      }
    }
  }

  private void updateSubviewClipStatus(Rect clippingRect, int idx, int clippedSoFar) {
    View child = Assertions.assertNotNull(mAllChildren)[idx];
    sHelperRect.set(child.getLeft(), child.getTop(), child.getRight(), child.getBottom());
    boolean intersects = clippingRect
        .intersects(sHelperRect.left, sHelperRect.top, sHelperRect.right, sHelperRect.bottom);
    boolean needUpdateClippingRecursive = false;
    // We never want to clip children that are being animated, as this can easily break layout :
    // when layout animation changes size and/or position of views contained inside a listview that
    // clips offscreen children, we need to ensure that, when view exits the viewport, final size
    // and position is set prior to removing the view from its listview parent.
    // Otherwise, when view gets re-attached again, i.e when it re-enters the viewport after scroll,
    // it won't be size and located properly.
    Animation animation = child.getAnimation();
    boolean isAnimating = animation != null && !animation.hasEnded();
    if (!intersects && child.getParent() != null && !isAnimating) {
      // We can try saving on invalidate call here as the view that we remove is out of visible area
      // therefore invalidation is not necessary.
      super.removeViewsInLayout(idx - clippedSoFar, 1);
      needUpdateClippingRecursive = true;
    } else if (intersects && child.getParent() == null) {
      super.addViewInLayout(child, idx - clippedSoFar, sDefaultLayoutParam, true);
      invalidate();
      needUpdateClippingRecursive = true;
    } else if (intersects) {
      // If there is any intersection we need to inform the child to update its clipping rect
      needUpdateClippingRecursive = true;
    }
    if (needUpdateClippingRecursive) {
      if (child instanceof com.facebook.react.uimanager.ReactClippingViewGroup) {
        // we don't use {@link sHelperRect} until the end of this loop, therefore it's safe
        // to call this method that may write to the same {@link sHelperRect} object.
        com.facebook.react.uimanager.ReactClippingViewGroup
          clippingChild = (com.facebook.react.uimanager.ReactClippingViewGroup) child;
        if (clippingChild.getRemoveClippedSubviews()) {
          clippingChild.updateClippingRect();
        }
      }
    }
  }

  private void updateSubviewClipStatus(View subview) {
    if (!mRemoveClippedSubviews || getParent() == null) {
      return;
    }

    Assertions.assertNotNull(mClippingRect);
    Assertions.assertNotNull(mAllChildren);

    // do fast check whether intersect state changed
    sHelperRect.set(subview.getLeft(), subview.getTop(), subview.getRight(), subview.getBottom());
    boolean intersects = mClippingRect
        .intersects(sHelperRect.left, sHelperRect.top, sHelperRect.right, sHelperRect.bottom);

    // If it was intersecting before, should be attached to the parent
    boolean oldIntersects = (subview.getParent() != null);

    if (intersects != oldIntersects) {
      int clippedSoFar = 0;
      for (int i = 0; i < mAllChildrenCount; i++) {
        if (mAllChildren[i] == subview) {
          updateSubviewClipStatus(mClippingRect, i, clippedSoFar);
          break;
        }
        if (mAllChildren[i].getParent() == null) {
          clippedSoFar++;
        }
      }
    }
  }

  @Override
  protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    if (mRemoveClippedSubviews) {
      updateClippingRect();
    }
  }

  @Override
  protected void onAttachedToWindow() {
    super.onAttachedToWindow();
    if (mRemoveClippedSubviews) {
      updateClippingRect();
    }
  }

  @Override
  public PointerEvents getPointerEvents() {
    return mPointerEvents;
  }

  @Override
  protected void dispatchSetPressed(boolean pressed) {
    // Prevents the ViewGroup from dispatching the pressed state
    // to it's children.
  }

  /*package*/ void setPointerEvents(PointerEvents pointerEvents) {
    mPointerEvents = pointerEvents;
  }

  /*package*/ int getAllChildrenCount() {
    return mAllChildrenCount;
  }

  /*package*/ View getChildAtWithSubviewClippingEnabled(int index) {
    return Assertions.assertNotNull(mAllChildren)[index];
  }

  /*package*/ void addViewWithSubviewClippingEnabled(View child, int index) {
    addViewWithSubviewClippingEnabled(child, index, sDefaultLayoutParam);
  }

  /*package*/ void addViewWithSubviewClippingEnabled(View child, int index, LayoutParams params) {
    Assertions.assertCondition(mRemoveClippedSubviews);
    Assertions.assertNotNull(mClippingRect);
    Assertions.assertNotNull(mAllChildren);
    addInArray(child, index);
    // we add view as "clipped" and then run {@link #updateSubviewClipStatus} to conditionally
    // attach it
    int clippedSoFar = 0;
    for (int i = 0; i < index; i++) {
      if (mAllChildren[i].getParent() == null) {
        clippedSoFar++;
      }
    }
    updateSubviewClipStatus(mClippingRect, index, clippedSoFar);
    child.addOnLayoutChangeListener(mChildrenLayoutChangeListener);
  }

  /*package*/ void removeViewWithSubviewClippingEnabled(View view) {
    Assertions.assertCondition(mRemoveClippedSubviews);
    Assertions.assertNotNull(mClippingRect);
    Assertions.assertNotNull(mAllChildren);
    view.removeOnLayoutChangeListener(mChildrenLayoutChangeListener);
    int index = indexOfChildInAllChildren(view);
    if (mAllChildren[index].getParent() != null) {
      int clippedSoFar = 0;
      for (int i = 0; i < index; i++) {
        if (mAllChildren[i].getParent() == null) {
          clippedSoFar++;
        }
      }
      super.removeViewsInLayout(index - clippedSoFar, 1);
    }
    removeFromArray(index);
  }

  /*package*/ void removeAllViewsWithSubviewClippingEnabled() {
    Assertions.assertCondition(mRemoveClippedSubviews);
    Assertions.assertNotNull(mAllChildren);
    for (int i = 0; i < mAllChildrenCount; i++) {
      mAllChildren[i].removeOnLayoutChangeListener(mChildrenLayoutChangeListener);
    }
    removeAllViewsInLayout();
    mAllChildrenCount = 0;
  }

  private int indexOfChildInAllChildren(View child) {
    final int count = mAllChildrenCount;
    final View[] children = Assertions.assertNotNull(mAllChildren);
    for (int i = 0; i < count; i++) {
      if (children[i] == child) {
        return i;
      }
    }
    return -1;
  }

  private void addInArray(View child, int index) {
    View[] children = Assertions.assertNotNull(mAllChildren);
    final int count = mAllChildrenCount;
    final int size = children.length;
    if (index == count) {
      if (size == count) {
        mAllChildren = new View[size + ARRAY_CAPACITY_INCREMENT];
        System.arraycopy(children, 0, mAllChildren, 0, size);
        children = mAllChildren;
      }
      children[mAllChildrenCount++] = child;
    } else if (index < count) {
      if (size == count) {
        mAllChildren = new View[size + ARRAY_CAPACITY_INCREMENT];
        System.arraycopy(children, 0, mAllChildren, 0, index);
        System.arraycopy(children, index, mAllChildren, index + 1, count - index);
        children = mAllChildren;
      } else {
        System.arraycopy(children, index, children, index + 1, count - index);
      }
      children[index] = child;
      mAllChildrenCount++;
    } else {
      throw new IndexOutOfBoundsException("index=" + index + " count=" + count);
    }
  }

  // This method also sets the child's mParent to null
  private void removeFromArray(int index) {
    final View[] children = Assertions.assertNotNull(mAllChildren);
    final int count = mAllChildrenCount;
    if (index == count - 1) {
      children[--mAllChildrenCount] = null;
    } else if (index >= 0 && index < count) {
      System.arraycopy(children, index + 1, children, index, count - index - 1);
      children[--mAllChildrenCount] = null;
    } else {
      throw new IndexOutOfBoundsException();
    }
  }

  @VisibleForTesting
  public int getBackgroundColor() {
    if (getBackground() != null) {
      return ((ReactViewBackgroundDrawable) getBackground()).getColor();
    }
    return DEFAULT_BACKGROUND_COLOR;
  }

  private ReactViewBackgroundDrawable getOrCreateReactViewBackground() {
    if (mReactBackgroundDrawable == null) {
      mReactBackgroundDrawable = new ReactViewBackgroundDrawable();
      Drawable backgroundDrawable = getBackground();
      super.setBackground(null);  // required so that drawable callback is cleared before we add the
                                  // drawable back as a part of LayerDrawable
      if (backgroundDrawable == null) {
        super.setBackground(mReactBackgroundDrawable);
      } else {
        LayerDrawable layerDrawable =
            new LayerDrawable(new Drawable[] {mReactBackgroundDrawable, backgroundDrawable});
        super.setBackground(layerDrawable);
      }
    }
    return mReactBackgroundDrawable;
  }

  @Override
  public @Nullable Rect getHitSlopRect() {
    return mHitSlopRect;
  }

  public void setHitSlopRect(@Nullable Rect rect) {
    mHitSlopRect = rect;
  }

}


text:
'use strict';

var _bluebird = require( 'bluebird' );

var _bluebird2 = _interopRequireDefault( _bluebird );

var _set = require( 'babel-runtime/core-js/set' );

var _set2 = _interopRequireDefault( _set );

var _ = require( '../../' );

var _2 = _interopRequireDefault( _ );

function _interopRequireDefault( obj ) {
    return obj && obj.__esModule ? obj : {default: obj};
}

/**
 * Created by Aaron on 7/17/2015.
 */

function makeSet( length ) {
    var res = new Array( length );
    var i = -1;

    while( ++i < length ) {
        res[i] = i;
    }

    return new _set2.default( res );
}

suite( 'very short iterables (Set of 2 elements)', function() {
    set( 'delay', 0 );
    set( 'mintime', 1750 );

    var bluebird_version = function() {
        var ref = (0, _bluebird.coroutine)( function* () {
            return yield makeSet( 2 ).values();
        } );
        return function bluebird_version() {
            return ref.apply( this, arguments );
        };
    }();

    bench( 'bluebird-co', function( next ) {
        bluebird_version().then( next, console.error );
    } );
} );

suite( 'short iterables (Set of 10 elements)', function() {
    set( 'delay', 0 );
    set( 'mintime', 1750 );

    var bluebird_version = function() {
        var ref = (0, _bluebird.coroutine)( function* () {
            return yield makeSet( 10 ).values();
        } );
        return function bluebird_version() {
            return ref.apply( this, arguments );
        };
    }();

    bench( 'bluebird-co', function( next ) {
        bluebird_version().then( next, console.error );
    } );
} );

suite( 'long iterables (Set of 2000 elements)', function() {
    set( 'delay', 0 );
    set( 'mintime', 1750 );

    var bluebird_version = function() {
        var ref = (0, _bluebird.coroutine)( function* () {
            return yield makeSet( 2000 ).values();
        } );
        return function bluebird_version() {
            return ref.apply( this, arguments );
        };
    }();

    bench( 'bluebird-co', function( next ) {
        bluebird_version().then( next, console.error );
    } );
} );

suite( 'huge iterables (Set of 10000 elements)', function() {
    set( 'delay', 0 );
    set( 'mintime', 1750 );

    var bluebird_version = function() {
        var ref = (0, _bluebird.coroutine)( function* () {
            return yield makeSet( 10000 ).values();
        } );
        return function bluebird_version() {
            return ref.apply( this, arguments );
        };
    }();

    bench( 'bluebird-co', function( next ) {
        bluebird_version().then( next, console.error );
    } );
} );


text:
// Type definitions for imagemin-zopfli 7.0
// Project: https://github.com/imagemin/imagemin-zopfli
// Definitions by: Marius Metzger <https://github.com/crushedpixel>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

import { Plugin } from 'imagemin';

declare function imageminZopfli(options?: imageminZopfli.Options): Plugin;

declare namespace imageminZopfli {
    interface Options {
        /** Convert 16-bit per channel images to 8-bit per channel. */
        '8bit'?: boolean;

        /**
         * Remove colors behind alpha channel 0.
         * No visual difference, removes hidden information.
         */
        transparent?: boolean;

        /**
         * The number of iterations, more iterations makes it slower
         * but provides slightly better compression.
         * Default: 15 for small files, 5 for large files.
         */
        iterations?: number;

        /**
         * Compress more: use more iterations (depending on file size).
         */
        more?: boolean;
    }
}

export = imageminZopfli;


text:
double HML_TestFunction_Wave(double x)
{
/*
Функция одной переменных: волна.
Тестовая функция вещественной оптимизации.
Входные параметры:
 x - вещественная переменная.
Возвращаемое значение:
 Значение тестовой функции в точке (x).
*/
double VHML_Result;
VHML_Result = (exp(-x*x)+0.01*cos(200*x));
return VHML_Result;
}


text:
import { Badge, Button, Modal, Space } from "antd"
import React from "react"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome/index.js"
import { faExclamationTriangle } from "@fortawesome/free-solid-svg-icons/faExclamationTriangle"
import { faBolt } from "@fortawesome/free-solid-svg-icons/faBolt"
import { ErrorMessage } from "./gdocsValidation.js"
import { GdocsDiff } from "./GdocsDiff.js"
import { OwidArticleType } from "@ourworldindata/utils"

export const GdocsSaveButtons = ({
    published,
    originalGdoc,
    gdoc,
    errors,
    hasErrors,
    hasWarnings,
    hasChanges,
    isLightningUpdate,
    doPublish,
}: {
    published: boolean
    originalGdoc: OwidArticleType | undefined
    gdoc: OwidArticleType
    errors: ErrorMessage[] | undefined
    hasErrors: boolean
    hasWarnings: boolean
    hasChanges: boolean
    isLightningUpdate: boolean
    setDiffOpen: (open: boolean) => void
    doPublish: VoidFunction
}) => {
    const confirmPublish = async () => {
        const styleDiff = hasChanges
            ? { style: { "overflow-y": "auto", maxHeight: "50vh" } }
            : {}
        const widthModal = hasChanges ? { width: "80vw" } : {}
        const centeredModal = hasChanges ? { centered: true } : {}

        Modal.confirm({
            title: `Are you sure you want to publish ${
                hasChanges ? "these changes" : "this article"
            }?`,
            content: (
                <>
                    {published && (

                            <GdocsDiff
                                originalGdoc={originalGdoc}
                                gdoc={gdoc}
                            />

                    )}
                    {hasWarnings && (

                            {errors?.map((error, i) => (

                                    <FontAwesomeIcon
                                        icon={faExclamationTriangle}
                                        color="#faad14"
                                    />{" "}
                                    {error.message}

                            ))}

                    )}
                </>
            ),
            okType: hasWarnings ? "danger" : "primary",
            okText: "Publish now",
            cancelText: "Cancel",
            onOk: doPublish,
            maskClosable: true,
            ...centeredModal,
            ...widthModal,
        })
    }

    const badgeProps =
        hasWarnings && !hasErrors
            ? {
                  count: (
                      <FontAwesomeIcon
                          icon={faExclamationTriangle}
                          className="warning"
                      />
                  ),
              }
            : {}

    return (
        <>
            <Space>
                <Badge {...badgeProps}>
                    {/* #gdocsvalidationclient: prevent saving published articles with errors */}
                    <Button
                        disabled={hasErrors || (published && !hasChanges)}
                        type="primary"
                        onClick={confirmPublish}
                    >
                        {!published ? (
                            "Publish"
                        ) : isLightningUpdate ? (
                            <>
                                <FontAwesomeIcon icon={faBolt} /> Republish
                            </>
                        ) : (
                            "Republish"
                        )}
                    </Button>
                </Badge>
            </Space>
        </>
    )
}


text:
package com.blinkbox.books.auth.server.api

import com.blinkbox.books.auth.server.ClientList
import com.blinkbox.books.auth.server.sso.{SsoTokenElevation, SsoTokenStatus}
import spray.http.CacheDirectives.`no-store`
import spray.http.HttpHeaders.{RawHeader, `Cache-Control`}
import spray.http.{OAuth2BearerToken, StatusCodes}

class ClientListSpecs extends ApiSpecBase {

  "The service" should "return a client list for an SSO user with a critically elevated access token" in {
    Get("/clients") ~> addCredentials(OAuth2BearerToken(env.tokenInfoA1.access_token)) ~> route ~> check {
      status should equal(StatusCodes.OK)
      jsonResponseAs[ClientList] should equal(ClientList(List(env.clientInfoA1, env.clientInfoA2)))
    }
  }

  it should "return a client list for a non-SSO user's client" in {
    Get("/clients") ~> addCredentials(OAuth2BearerToken(env.tokenInfoA1WithoutSSO.access_token)) ~> route ~> check {
      status should equal(StatusCodes.OK)
      jsonResponseAs[ClientList] should equal(ClientList(List(env.clientInfoA1, env.clientInfoA2)))
    }
  }

  it should "return an uncacheable response" in {
    Get("/clients") ~> addCredentials(OAuth2BearerToken(env.tokenInfoA1.access_token)) ~> route ~> check {
      header[`Cache-Control`] should equal(Some(`Cache-Control`(`no-store` :: Nil)))
      header("Pragma") should equal(Some(RawHeader("Pragma", "no-cache")))
    }
  }

  it should "return a 401 with no error code if no access token is supplied" in {
    shouldBeUnauthorisedWithMissingAccessToken(Get("/clients"), route)
  }

  it should "return a 401 with an invalid token error code if an invalid access token is supplied" in {
    shouldBeUnauthorisedWithInvalidAccessToken(Get("/clients"), route)
  }

}