text:
package eaa.chapter12.associationtablemapping;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import eaa.support.ApplicationException;

public class EmployeeMapper extends AbstractMapper<Employee> {

	public static final String COLUMNS = " id, first_name, last_name ";
	public static final String TABLE = "employees";

	private static final String UPDATE_STATEMENT = "UPDATE " + TABLE + " SET " +
			" first_name=?, last_name=? WHERE id = ? ";

	protected String table() {
		return TABLE;
	}

	protected String findStatement() {
		// THIS DOES *** NOT *** WORK IF THE EMPLOYEE HAS NO SKILLS
		return "SELECT e.id,e.first_name,e.last_name,s.id,s.name " +
		 	   "FROM employees e, skills s, employees_skills es " +
		       "WHERE es.employee_id = e.id " +
		       "and es.skill_id = s.id " +
		       "and e.id = ? ";
	}

	protected String insertStatement() {
		return "INSERT INTO " + TABLE + " (" + COLUMNS + ") VALUES (?,?,?)";
	}

	public Employee find( long id ) {
		return abstractFind(id);
	}

	public List<Employee> find() {
		Connection c = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			c = openConnection();

			stmt = c.prepareStatement( "SELECT " + COLUMNS + " FROM " + TABLE );
			rs = stmt.executeQuery();

			return loadAll( rs );
		} catch ( SQLException ex ) {
			throw new ApplicationException(ex);
		} finally {
			releaseConnection( c, stmt, rs );
		}
	}

	public void update( Connection c, Employee person ) {
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			stmt = c.prepareStatement( UPDATE_STATEMENT );

			stmt.setString( 1, person.getFirstName() );
			stmt.setString( 2, person.getLastName() );
			stmt.setLong(   2, person.getId() );
			stmt.executeUpdate();

			preDelete( c, person );
			postInsert( c, person );

		} catch ( SQLException ex ) {
			throw new ApplicationException(ex);
		} finally {
			release( stmt, rs );
		}
	}

	@Override
	protected void postInsert( Connection c, Employee person ) throws SQLException {
		PreparedStatement stmt = null;
		for ( Skill skill : person.getSkills() ) {
			stmt = c.prepareStatement("INSERT INTO employees_skills (employee_id,skill_id) VALUES(?,?)");
			stmt.setLong( 1, person.getId() );
			stmt.setLong( 2, skill.getId() );
			stmt.executeUpdate();
		}
	}

	@Override
	protected void preDelete( Connection c, Employee person ) throws SQLException {
		PreparedStatement stmt = c.prepareStatement("DELETE FROM employees_skills WHERE employee_id=?");
		stmt.setLong( 1, person.getId() );
		stmt.executeUpdate();
	}

	@Override
	protected Employee doLoad(long id, ResultSet rs) throws SQLException {
		String first_name = rs.getString( 2 );
		String last_name = rs.getString( 3 );
		Employee e = new Employee( id, first_name, last_name );
		long skill_id = rs.getLong( 4 );
		String skill_name  = rs.getString( 5 );
		e.getSkills().add( new Skill( skill_id, skill_name ) );

		while( rs.next() ) {
			skill_id = rs.getLong( 4 );
			skill_name  = rs.getString( 5 );
			e.getSkills().add( new Skill( skill_id, skill_name ) );
		}

		return e;
	}

	protected void prepareInsert( PreparedStatement stmt, Employee person ) throws SQLException {
		stmt.setLong( 1, person.getId() );
		stmt.setString( 2, person.getFirstName() );
		stmt.setString( 2, person.getLastName() );
	}

}


text:
link: ggg_ggg_ggg_ggg_gg
lines: 3
---
John 15:13<br>
Greater love hath no man than this, that a man lay down his life for his friends.

redpajama_set_name: RedPajamaGithub


text:
package io.oasp.gastronomy.restaurant.general.common.api.builders;

public interface P<T> {

  public void apply(T target);
}


text:
class Solution:
    # @param {ListNode} head
    # @param {integer} n
    # @return {ListNode}
    def removeNthFromEnd(self, head, n):
        if not head or not head.next:
            return None

        fast = head
        for i in range(0, n):
            fast = fast.next

        if not fast:
            return head.next

        slow = head
        while fast.next:
            fast = fast.next
            slow = slow.next

        slow.next = slow.next.next

        return head


text:
package us.kbase.userandjobstate.jobstate;

import static us.kbase.common.utils.StringUtils.checkString;
import static us.kbase.common.utils.StringUtils.checkMaxLenAndNonEmpty;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class JobResults {

	private List<JobResult> results = null;
	private String workspaceurl = null;
	private List<String> workspaceids = null;
	private String shockurl = null;
	private List<String> shocknodes = null;

	public final static int MAX_LEN_URL = 1000;
	public final static int MAX_LEN_ID = 1000;

	@SuppressWarnings("unused")
	private JobResults() {} //for jongo

	public JobResults(
			final List<JobResult> results,
			final String workspaceurl,
			final List<String> workspaceids,
			final String shockurl,
			final List<String> shocknodes) {
		super();
		checkMaxLenAndNonEmpty(workspaceurl, "workspaceurl", MAX_LEN_URL);
		checkMaxLenAndNonEmpty(shockurl, "shockurl", MAX_LEN_URL);
		if (workspaceids != null) {
			for (final String id: workspaceids) {
				checkString(id, "workspaceid", MAX_LEN_ID);
			}
		}
		if (shocknodes != null) {
			for (final String id: shocknodes) {
				checkString(id, "shocknode", MAX_LEN_ID);
			}
		}
		this.results = makeImmutable(results);
		this.workspaceurl = workspaceurl;
		this.workspaceids = makeImmutable(workspaceids);
		this.shockurl = shockurl;
		this.shocknodes = makeImmutable(shocknodes);
	}

	private static <T> List<T> makeImmutable(final List<T> l) {
		if (l == null) {
			return null;
		}
		return Collections.unmodifiableList(
				new LinkedList<T>(l));
	}

	public List<JobResult> getResults() {
		return results;
	}

	public String getWorkspaceurl() {
		return workspaceurl;
	}

	public List<String> getWorkspaceids() {
		return workspaceids;
	}

	public String getShockurl() {
		return shockurl;
	}

	public List<String> getShocknodes() {
		return shocknodes;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((results == null) ? 0 : results.hashCode());
		result = prime * result
				+ ((shocknodes == null) ? 0 : shocknodes.hashCode());
		result = prime * result
				+ ((shockurl == null) ? 0 : shockurl.hashCode());
		result = prime * result
				+ ((workspaceids == null) ? 0 : workspaceids.hashCode());
		result = prime * result
				+ ((workspaceurl == null) ? 0 : workspaceurl.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		JobResults other = (JobResults) obj;
		if (results == null) {
			if (other.results != null)
				return false;
		} else if (!results.equals(other.results))
			return false;
		if (shocknodes == null) {
			if (other.shocknodes != null)
				return false;
		} else if (!shocknodes.equals(other.shocknodes))
			return false;
		if (shockurl == null) {
			if (other.shockurl != null)
				return false;
		} else if (!shockurl.equals(other.shockurl))
			return false;
		if (workspaceids == null) {
			if (other.workspaceids != null)
				return false;
		} else if (!workspaceids.equals(other.workspaceids))
			return false;
		if (workspaceurl == null) {
			if (other.workspaceurl != null)
				return false;
		} else if (!workspaceurl.equals(other.workspaceurl))
			return false;
		return true;
	}

}


text:
package com.blackypaw.mc.i18n;

import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerLoginEvent;

import java.util.Locale;

/**
 * Internal helper. Used to resolve a player's locale as soon as possible.
 *
 * @author BlackyPaw
 * @version 1.0
 */
class PlayerLoginListener implements Listener {

	private I18NSpigotImpl i18n;

	/**
	 * Constructs a new player login listener.
	 *
	 * @param i18n The I18N instance
	 */
	public PlayerLoginListener( I18NSpigotImpl i18n ) {
		this.i18n = i18n;
	}

	/**
	 * Catches player logins as soon as possible by having the lowest priority possible.
	 *
	 * @param event The player login event
	 */
	@EventHandler( priority = EventPriority.LOWEST, ignoreCancelled = true )
	public void onPlayerLogin( PlayerLoginEvent event ) {
		Player player = event.getPlayer();
		Locale locale = this.i18n.getLocaleResolver().resolveLocale( player.getUniqueId() );
		this.i18n.storeLocale( player.getUniqueId(), locale );
	}

}


text:
using System.Diagnostics;
using Exortech.NetReflector;
using ThoughtWorks.CruiseControl.Core;
using ThoughtWorks.CruiseControl.Core.Util;

namespace CCNet.NetBuildQueue.Plugin
{
	[ReflectorType("netBuildStart")]
	public class NetBuildStart : NetBuildPlugin, ITask
	{
		public void Run(IIntegrationResult result)
		{
			if (m_queue == null)
			{
				Init(result.ProjectName);
			}

			result.BuildProgressInformation.SignalStartRunTask($"Starting build '{result.Label}' for '{m_itemCode}'...");

			var sw = Stopwatch.StartNew();
			m_queue.StartBuild(m_itemCode, result.Label);
			sw.Stop();

			Log.Info($"[NETBUILD] Build '{result.Label}' for '{m_itemCode}' started in {sw.ElapsedMilliseconds} ms.");
		}
	}
}


text:
@class BITUpdateManager, UIViewController;

@protocol BITUpdateManagerDelegate <NSObject>

@optional
- (UIViewController *)viewControllerForUpdateManager:(BITUpdateManager *)arg1;
- (BOOL)updateManagerShouldSendUsageData:(BITUpdateManager *)arg1;
- (void)didDisplayExpiryAlertForUpdateManager:(BITUpdateManager *)arg1;
- (BOOL)shouldDisplayExpiryAlertForUpdateManager:(BITUpdateManager *)arg1;
@end


text:
require 'deject'
require 'fileutils'
require 'prodder/pg'
require 'prodder/git'

module Prodder
  class Project
    SeedConfigFileMissing = Class.new(StandardError) do
      attr_reader :filename
      def initialize(filename); @filename = filename; end
    end

    Deject self
    dependency(:pg)  { |project| Prodder::PG.new(project.db_credentials) }
    dependency(:git) { |project| Prodder::Git.new(project.local_git_path, project.git_origin) }

    attr_reader :name, :workspace

    def initialize(name, workspace, definition)
      @name = name
      @workspace = workspace
      @defn = definition
    end

    def init
      git.clone_or_remote_update
    end

    def dump
      FileUtils.mkdir_p File.dirname(structure_file_name)
      pg.dump_structure db_credentials['name'], structure_file_name,
                        exclude_tables: excluded_tables, exclude_schemas: excluded_schemas

      FileUtils.mkdir_p File.dirname(settings_file_name)
      pg.dump_settings db_credentials['name'], settings_file_name

      FileUtils.mkdir_p File.dirname(seed_file_name)
      pg.dump_tables db_credentials['name'], seed_tables, seed_file_name

      # must split the structure file to allow data to be loaded after tables
      # being created but before triggers and foreign keys are created. this
      # facilitates validation during loading, yet avoids extra overhead and
      # false errors
      if separate_quality_checks?
        contents = File.readlines(structure_file_name)
        rgx = /^\-\- .* Type: INDEX; |^\-\- .* Type: TRIGGER; |^\-\- .* Type: FK CONSTRAINT; /
        structure, *quality = contents.slice_before(rgx).to_a

        File.open(quality_check_file_name, 'w') { |f| f.write(quality.join) }
        File.open(structure_file_name, 'w') { |f| f.write(structure.join) }
      end

      if dump_permissions?
        FileUtils.mkdir_p File.dirname(permissions_file_name)
        pg.dump_permissions db_credentials['name'], permissions_file_name, included_users: included_users,
                            exclude_tables: excluded_tables, exclude_schemas: excluded_schemas

      end
    end

    def commit
      return unless git.dirty?
      git.add structure_file_name
      git.add seed_file_name
      git.add quality_check_file_name if separate_quality_checks?
      git.add permissions_file_name if dump_permissions?
      git.add settings_file_name
      git.commit "Auto-commit by prodder", @defn['git']['author']
    end

    def push
      if git.fast_forward?
        git.push
      else
        raise Prodder::Git::NotFastForward.new(git_origin)
      end
    end

    def nothing_to_push?
      git.remote_update
      git.no_new_commits?
    end

    def db_credentials
      @defn['db']
    end

    def permissions
      @defn['permissions']
    end

    def local_git_path
      workspace
    end

    def git_origin
      @defn['git']['origin']
    end

    def structure_file_name
      File.join workspace, @defn['structure_file']
    end

    def settings_file_name
      File.join workspace, 'db/settings.sql'
    end

    def seed_file_name
      File.join workspace, @defn['seed_file']
    end

    def quality_check_file_name
      File.join workspace, @defn['quality_check_file']
    end

    def permissions_file_name
      File.join workspace, permissions['file']
    end

    def separate_quality_checks?
      @defn.key? 'quality_check_file'
    end

    def dump_permissions?
      @defn.key?('permissions') && permissions.key?('file')
    end

    def excluded_schemas
      db_credentials['exclude_schemas'] || []
    end

    def excluded_tables
      db_credentials['exclude_tables'] || []
    end

    def included_users
      permissions['included_users'] || []
    end

    def seed_tables
      value = db_credentials['tables']
      return value unless value.is_a?(String)

      path = File.join(workspace, value)
      raise SeedConfigFileMissing.new(File.join(name, value)) unless File.exist?(path)
      YAML.load IO.read(path)
    end
  end
end


text:
package openmarker.tea.parsetree;

import openmarker.tea.compiler.SourceInfo;

/**
 * Standard no-op expression.  Where most expressions are expected to generate
 * some type of data, a no-op expression has no impact and expects another
 * expression to generate the data for it.
 */
public class NoOpExpression extends Expression {

    private static final long serialVersionUID = 1L;

    public NoOpExpression(SourceInfo info) {
        super(info);
    }

}


text:
package fi.csc.microarray.client.visualisation.methods;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;

import javax.swing.SwingUtilities;

import org.jfree.chart.ChartMouseEvent;
import org.jfree.chart.ChartMouseListener;
import org.jfree.chart.entity.ChartEntity;
import org.jfree.chart.entity.EntityCollection;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.plot.PlotState;
import org.jfree.util.ObjectUtilities;

import fi.csc.microarray.constants.VisualConstants;
import fi.csc.microarray.databeans.DataBean;

public class VenndiPlot extends Plot implements ChartMouseListener, Cloneable, Serializable {

	public class VennDataset {
		private String[][] idsBySection;
		private List<DataBean> datasets;
		private Map<DataBean, Map<String, Integer>> indexMaps;

		/**
		 * Two dimensional table of indetifiers. First dimension has to be 7 and obey the order
		 * listed in enum VenndiPlot.AREAS. Other dimension lists all the identifiers for those
		 * areas.
		 *
		 * @param idsBySection
		 * @param ids
		 */
		public VennDataset (String[][] idsBySection, List<DataBean> datas, Map<DataBean, Map<String, Integer>> indexMaps2){
			this.idsBySection = idsBySection;
			this.datasets = datas;
			this.indexMaps = indexMaps2;
		}

		public int getCount(VenndiPlot.AREAS area){
			return idsBySection[area.ordinal()].length;
		}

		public String getDatasetName(AREAS area) {
			if( area.ordinal() < datasets.size()){
				return datasets.get(area.ordinal()).getName();
			}
			return "";
		}

		public List<DataBean> getDataBeans(){
			return datasets;
		}

		public Collection<String> getIdentifiers(AREAS areas) {
			return Arrays.asList(idsBySection[areas.ordinal()]);
		}

		public Map<DataBean, Set<Integer>> getIndexes(AREAS area){

			Map<DataBean, Set<Integer>> indexes = new HashMap<DataBean, Set<Integer>>();

			for(DataBean data : datasets){
				indexes.put(data, new HashSet<Integer>());

				for(String id : getIdentifiers(area)){
					indexes.get(data).add(indexMaps.get(data).get(id));
				}
			}

			return indexes;
		}
	}

	private static final long serialVersionUID = 1L;

	/** The cell information text is drawn with this font. */
    private Font descriptionFont;

	private VennDataset dataset;

	private Area[] areas = new Area[7];
	private Set<Area> selected = new HashSet<Area>();

	private VennDiagram visualisation;

    /** The resourceBundle for the localization. */
    protected static ResourceBundle localizationResources
        = ResourceBundle.getBundle("org.jfree.chart.plot.LocalizationBundle");

    public VenndiPlot(String[][] idTable, List<DataBean> datas, Map<DataBean, Map<String, Integer>> indexMaps, VennDiagram parent) throws NullPointerException {
    	this.dataset = new VennDataset(idTable, datas, indexMaps);

        this.visualisation = parent;

        //Fill variable areas to be able to mark selections from the application
        updateAreas(new Rectangle(), null);
    }

    public List<String> getSelected() {

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

    	for (int i = 0; i < areas.length; i++){
    		if (selected.contains(areas[i])){
    			selectedIds.addAll(dataset.getIdentifiers(AREAS.values()[i]));
    		}
    	}

    	return selectedIds;
    }

    public void setSelected(Collection<String> selectedIds){
    	selected.clear();

    	if(selectedIds != null){
    		for (AREAS area : AREAS.values()){
    			if (selectedIds.containsAll(dataset.getIdentifiers(area)) &&
    					dataset.getCount(area) > 0){
    				selected.add(areas[area.ordinal()]);
    			}
    		}
    	}
    }

    public VennDataset getDataset() {
        return this.dataset;
    }

    public String getPlotType() {
        //return localizationResources.getString("VennDiagram");
    	return "VennDiagram";
    }

    /**
     * Returns the font used for cell descriptions.
     *
     * @return Description font.
     */
    public Font getDescriptionFont() {
        return this.descriptionFont;
    }

    public enum AREAS { A, B, C, AB, AC, BC, ABC };

    /**
     * Draws the plot on a Java2D graphics device (such as the screen or
     * a printer).
     *
     * @param g2  the graphics device.
     * @param area  the area within which the plot should be drawn.
     * @param anchor  the anchor point (null permitted).
     * @param parentState  the state from the parent plot, if there is one
     * (null permitted.)
     * @param info  collects info about the drawing (null permitted).
     * @throws NullPointerException  if g2 or area is null.
     */
    @Override
    public void draw(java.awt.Graphics2D g2, java.awt.geom.Rectangle2D area,
            java.awt.geom.Point2D anchor, PlotState parentState,
            PlotRenderingInfo info) {

        // adjust for insets...
        this.getInsets().trim(area);

        if (info != null) {
            info.setPlotArea(area);
            info.setDataArea(area);
        }

        //this.setBackgroundPaint(Color.black);

        drawBackground(g2, area);
        drawOutline(g2, area);

        Shape savedClip = g2.getClip();
        g2.clip(area);
/*
        Composite originalComposite = g2.getComposite();		public Collection<String> getIdentifiers(AREAS areas) {
			return Arrays.asList(datas[areas.ordinal()]);
		}
        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
                getForegroundAlpha()));
*/
        drawVenn(g2, area, info);

        g2.setClip(savedClip);
   //   g2.setComposite(originalComposite);

        drawOutline(g2, area);
    }

    private void drawVenn(Graphics2D g2, java.awt.geom.Rectangle2D area,
            PlotRenderingInfo info) {

    	updateAreas(area, info);

   	      	Color[] colors = {
   			VisualConstants.CATEGORY_COLORS[4],
   			VisualConstants.CATEGORY_COLORS[5],
   			VisualConstants.CATEGORY_COLORS[7],
   			new Color(222, 98, 39),
   			new Color(115, 127, 107),
   			new Color(107, 88, 117),
   			VisualConstants.CATEGORY_COLORS[10]
   	};

//    	  //Little bit different colors
//    	  	Color[] colors = {
//    			VisualConstants.CATEGORY_COLORS[4],
//    			VisualConstants.CATEGORY_COLORS[5],
//    			VisualConstants.CATEGORY_COLORS[7],
//    			VisualConstants.CATEGORY_COLORS[3],
//    			VisualConstants.CATEGORY_COLORS[6],
//    			new Color(147, 147, 147),
//    			VisualConstants.CATEGORY_COLORS[10]
//    	};

   	     g2.setFont(g2.getFont().deriveFont(g2.getFont().getSize2D() * 0.8f));

    	for ( int i = 0; i < areas.length; i++){
    		Shape shape = areas[i];
    		if(shape != null){
    			if(selected.contains(shape)){

    				Color c = new Color(colors[i].getRed(), colors[i].getGreen(), colors[i].getBlue(), 200);

    				g2.setPaint(c);
    				g2.fill(shape);
    				g2.setPaint(Color.black);
    				g2.setStroke(new BasicStroke(3));
    				g2.draw(shape);
    				g2.setFont(g2.getFont().deriveFont(Font.BOLD));

    			} else {

    				Color c = new Color(colors[i].getRed(), colors[i].getGreen(), colors[i].getBlue(), 255);

    				g2.setPaint(c);
    				g2.fill(shape);
    				g2.setPaint(Color.black);
    				g2.setStroke(new BasicStroke(1));
    				g2.draw(shape);
    				g2.setFont(g2.getFont().deriveFont(Font.PLAIN));
    			}

    			g2.setPaint(Color.black);
    			String str = "" + dataset.getCount(AREAS.values()[i]);

    			int x = (int)shape.getBounds().getCenterX() -
    				SwingUtilities.computeStringWidth(g2.getFontMetrics(), str) / 2;

    			int y = (int)shape.getBounds().getCenterY() + g2.getFontMetrics().getHeight() / 2;

    			g2.drawString(str, x, y);

    			str = dataset.getDatasetName(AREAS.values()[i]);

    			x = (int)shape.getBounds().getCenterX() -
				SwingUtilities.computeStringWidth(g2.getFontMetrics(), str) / 2;

    			y += g2.getFontMetrics().getHeight();

    			g2.drawString(str, x, y);
    		}
    	}
    }

    private void updateAreas(Rectangle2D area, PlotRenderingInfo info){

    	double r = area.getHeight() < area.getWidth() ? (int)area.getHeight()/4 : (int)area.getWidth()/4;

    	//Distance of circle center from the area center
    	double d = r * 0.7;

    	//Components of the d in angle of 30 degrees
    	double dx = d * Math.cos(Math.PI / 6);
    	double dy = d * Math.sin(Math.PI / 6);

    	Area[] circles = new Area[3];
    	circles[AREAS.A.ordinal()] = new Area(new Ellipse2D.Double(area.getCenterX() - r, 		area.getCenterY() - d - r, 2*r, 2*r));
    	circles[AREAS.B.ordinal()] = new Area(new Ellipse2D.Double(area.getCenterX() - dx - r, 	area.getCenterY() + dy - r, 2*r, 2*r));
    	circles[AREAS.C.ordinal()] = new Area(new Ellipse2D.Double(area.getCenterX() + dx - r, 	area.getCenterY() + dy - r, 2*r, 2*r));

    	if(areas[0] == null){
    		for (int i = 0; i < areas.length; i++){
    			areas[i] = new Area();
    		}
    	} else {
    		for (Area a : areas){
    			a.reset();
    		}
    	}

    	areas[AREAS.A.ordinal()].add(circles[AREAS.A.ordinal()]);
    	areas[AREAS.A.ordinal()].subtract(circles[AREAS.B.ordinal()]);
    	areas[AREAS.A.ordinal()].subtract(circles[AREAS.C.ordinal()]);

    	areas[AREAS.B.ordinal()].add(circles[AREAS.B.ordinal()]);
    	areas[AREAS.B.ordinal()].subtract(circles[AREAS.A.ordinal()]);
    	areas[AREAS.B.ordinal()].subtract(circles[AREAS.C.ordinal()]);

    	areas[AREAS.C.ordinal()].add(circles[AREAS.C.ordinal()]);
    	areas[AREAS.C.ordinal()].subtract(circles[AREAS.A.ordinal()]);
    	areas[AREAS.C.ordinal()].subtract(circles[AREAS.B.ordinal()]);

    	areas[AREAS.AB.ordinal()].add(circles[AREAS.A.ordinal()]);
    	areas[AREAS.AB.ordinal()].intersect(circles[AREAS.B.ordinal()]);
    	areas[AREAS.AB.ordinal()].subtract(circles[AREAS.C.ordinal()]);

    	areas[AREAS.BC.ordinal()].add(circles[AREAS.B.ordinal()]);
    	areas[AREAS.BC.ordinal()].subtract(circles[AREAS.A.ordinal()]);
    	areas[AREAS.BC.ordinal()].intersect(circles[AREAS.C.ordinal()]);

    	areas[AREAS.AC.ordinal()].add(circles[AREAS.C.ordinal()]);
    	areas[AREAS.AC.ordinal()].intersect(circles[AREAS.A.ordinal()]);
    	areas[AREAS.AC.ordinal()].subtract(circles[AREAS.B.ordinal()]);

    	areas[AREAS.ABC.ordinal()].add(circles[AREAS.A.ordinal()]);
    	areas[AREAS.ABC.ordinal()].intersect(circles[AREAS.B.ordinal()]);
    	areas[AREAS.ABC.ordinal()].intersect(circles[AREAS.C.ordinal()]);

    	if(info != null){
    		for(Area shape : areas){
    			createEntity(shape, info);
    		}
    	}
    }

    /**
     * Implements the ChartMouseListener interface. This
     * method does nothing.
     *
     * @param event  the mouse event.
     */
    public void chartMouseMoved(ChartMouseEvent event) {
        ;
    }

    public void chartMouseClicked(ChartMouseEvent e) {

    	if(e.getEntity() != null){
    		for(Area shape : areas){
    			//if(shape.contains(e.getTrigger().getPoint())){
    			if(shape.equals(e.getEntity().getArea())){

    				if(!e.getTrigger().isControlDown()){
    					selected.clear();
    				}
    				if(selected.contains(shape)){
    					selected.remove(shape);
    				} else {
    					selected.add(shape);
    				}
    			}
    		}
    	} else {
    		selected.clear();
    	}

    	setSelectedForList(true);
    }

	public void setSelectedForList(boolean dispatchEvent){

    	List<String> ids = new ArrayList<String>();
    	// The rowSelectionManager needs row indexes
    	Map<DataBean, Set<Integer>> indexes = new HashMap<DataBean, Set<Integer>>();

    	// Due to multiple datas the row indexes are meaningful only within one specific data
    	for(int i = 0; i < areas.length; i++){
    		if(selected.contains(areas[i])){
    			ids.addAll(dataset.getIdentifiers(AREAS.values()[i]));
    			Map<DataBean, Set<Integer>> map = dataset.getIndexes(AREAS.values()[i]);
    			for(DataBean data: map.keySet()){
    				if(!indexes.containsKey(data)){
    					indexes.put(data, new HashSet<Integer>());
    				}

    				indexes.get(data).addAll(map.get(data));
    			}
    		}
    	}

		visualisation.setSelectedListContent(ids, indexes, this, dispatchEvent);
	}

    /**
     * Tests this plot for equality with an arbitrary object.  Note that the
     * plot's dataset is NOT included in the test for equality.
     *
     * @param obj  the object to test against (null permitted).
     *
     * @return true or false.
     */
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
        if (!(obj instanceof VenndiPlot)) {
            return false;
        }
        VenndiPlot that = (VenndiPlot) obj;

//        if (!ObjectUtilities.equal(this.urlGenerator, that.urlGenerator)) {
//            return false;
//        }

        if (!ObjectUtilities.equal(this.descriptionFont,
                that.descriptionFont)) {
            return false;
        }

        // can't find any difference...
        return true;
    }

    /**
     * Provides serialization support.
     *
     * @param stream  the output stream.
     *
     * @throws IOException  if there is an I/O error.
     * @throws NullPointerException  if stream is null.
     */
    private void writeObject(ObjectOutputStream stream) throws IOException {
        stream.defaultWriteObject();
    }

    /**
     * Provides serialization support.
     *
     * @param stream  the input stream.
     *
     * @throws IOException  if there is an I/O error.
     * @throws ClassNotFoundException  if there is a classpath problem.
     * @throws NullPointerException  if stream is null.
     */
    private void readObject(ObjectInputStream stream)
        throws IOException, ClassNotFoundException {
        stream.defaultReadObject();
    }

    private void createEntity(Shape shape, PlotRenderingInfo info) {

        if (info != null) {
            EntityCollection entities = info.getOwner().getEntityCollection();
            if (entities != null) {

                entities.add(
                        new ChartEntity(shape));
            }
        }
    }
}


text:
Technical specifications for each web service.

### [Service](/docs/en/api_reference/services)
Web Services supported in Sponsored Search API

### [Data Objects](/docs/en/api_reference/data)
This chapter explains data objects (entities) which are newly added or changed in Sponsored Search API.

### [Appendix](/docs/en/api_reference/appendix)
Province Code, Report Fields, Value Constraints, SOAP faults,and Editorial Reason Text are shown here.


text:
package com.daimajia.androidanimations.library.rotating_entrances;

import android.view.View;

import com.daimajia.androidanimations.library.BaseViewAnimator;
import com.nineoldandroids.animation.ObjectAnimator;

public class RotateInDownLeftAnimator extends BaseViewAnimator {
    @Override
    public void prepare(View target) {
        float x = target.getPaddingLeft();
        float y = target.getHeight() - target.getPaddingBottom();
        getAnimatorAgent().playTogether(
                ObjectAnimator.ofFloat(target, "rotation", -90, 0),
                ObjectAnimator.ofFloat(target, "alpha", 0, 1),
                ObjectAnimator.ofFloat(target, "pivotX", x, x),
                ObjectAnimator.ofFloat(target, "pivotY", y, y)
        );
    }
}


text:
#ifndef _INTEL_DVO_H
#define _INTEL_DVO_H

#include <linux/i2c.h>
#include <drm/drmP.h>
#include <drm/drm_crtc.h>
#include "intel_drv.h"

struct intel_dvo_device {
	const char *name;
	int type;
	/* DVOA/B/C output register */
	u32 dvo_reg;
	/* GPIO register used for i2c bus to control this device */
	u32 gpio;
	int slave_addr;

	const struct intel_dvo_dev_ops *dev_ops;
	void *dev_priv;
	struct i2c_adapter *i2c_bus;
};

struct intel_dvo_dev_ops {
	/*
	 * Initialize the device at startup time.
	 * Returns NULL if the device does not exist.
	 */
	bool (*init)(struct intel_dvo_device *dvo,
		     struct i2c_adapter *i2cbus);

	/*
	 * Called to allow the output a chance to create properties after the
	 * RandR objects have been created.
	 */
	void (*create_resources)(struct intel_dvo_device *dvo);

	/*
	 * Turn on/off output.
	 *
	 * Because none of our dvo drivers support an intermediate power levels,
	 * we don't expose this in the interfac.
	 */
	void (*dpms)(struct intel_dvo_device *dvo, bool enable);

	/*
	 * Callback for testing a video mode for a given output.
	 *
	 * This function should only check for cases where a mode can't
	 * be supported on the output specifically, and not represent
	 * generic CRTC limitations.
	 *
	 * \return MODE_OK if the mode is valid, or another MODE_* otherwise.
	 */
	int (*mode_valid)(struct intel_dvo_device *dvo,
			  struct drm_display_mode *mode);

	/*
	 * Callback to adjust the mode to be set in the CRTC.
	 *
	 * This allows an output to adjust the clock or even the entire set of
	 * timings, which is used for panels with fixed timings or for
	 * buses with clock limitations.
	 */
	bool (*mode_fixup)(struct intel_dvo_device *dvo,
			   const struct drm_display_mode *mode,
			   struct drm_display_mode *adjusted_mode);

	/*
	 * Callback for preparing mode changes on an output
	 */
	void (*prepare)(struct intel_dvo_device *dvo);

	/*
	 * Callback for committing mode changes on an output
	 */
	void (*commit)(struct intel_dvo_device *dvo);

	/*
	 * Callback for setting up a video mode after fixups have been made.
	 *
	 * This is only called while the output is disabled.  The dpms callback
	 * must be all that's necessary for the output, to turn the output on
	 * after this function is called.
	 */
	void (*mode_set)(struct intel_dvo_device *dvo,
			 struct drm_display_mode *mode,
			 struct drm_display_mode *adjusted_mode);

	/*
	 * Probe for a connected output, and return detect_status.
	 */
	enum drm_connector_status (*detect)(struct intel_dvo_device *dvo);

	/*
	 * Probe the current hw status, returning true if the connected output
	 * is active.
	 */
	bool (*get_hw_state)(struct intel_dvo_device *dev);

	/**
	 * Query the device for the modes it provides.
	 *
	 * This function may also update MonInfo, mm_width, and mm_height.
	 *
	 * \return singly-linked list of modes or NULL if no modes found.
	 */
	struct drm_display_mode *(*get_modes)(struct intel_dvo_device *dvo);

	/**
	 * Clean up driver-specific bits of the output
	 */
	void (*destroy) (struct intel_dvo_device *dvo);

	/**
	 * Debugging hook to dump device registers to log file
	 */
	void (*dump_regs)(struct intel_dvo_device *dvo);
};

extern struct intel_dvo_dev_ops sil164_ops;
extern struct intel_dvo_dev_ops ch7xxx_ops;
extern struct intel_dvo_dev_ops ivch_ops;
extern struct intel_dvo_dev_ops tfp410_ops;
extern struct intel_dvo_dev_ops ch7017_ops;
extern struct intel_dvo_dev_ops ns2501_ops;

#endif /* _INTEL_DVO_H */


text:
 /*
  *   LOCATION:    see http://www.boost.org for most recent version.
  *   FILE         regex_fwd.cpp
  *   VERSION      see <boost/version.hpp>
  *   DESCRIPTION: Forward declares boost::basic_regex<> and
  *                associated typedefs.
  */

#ifndef BOOST_REGEX_FWD_HPP_INCLUDED
#define BOOST_REGEX_FWD_HPP_INCLUDED

#ifndef BOOST_REGEX_CONFIG_HPP
#include <boost/regex/config.hpp>
#endif

//
// define BOOST_REGEX_NO_FWD if this
// header doesn't work!
//
#ifdef BOOST_REGEX_NO_FWD
#  ifndef BOOST_RE_REGEX_HPP
#     include <boost/regex.hpp>
#  endif
#else

namespace boost{

template <class charT>
class cpp_regex_traits;
template <class charT>
struct c_regex_traits;
template <class charT>
class w32_regex_traits;

#ifdef BOOST_REGEX_USE_WIN32_LOCALE
template <class charT, class implementationT = w32_regex_traits<charT> >
struct regex_traits;
#elif defined(BOOST_REGEX_USE_CPP_LOCALE)
template <class charT, class implementationT = cpp_regex_traits<charT> >
struct regex_traits;
#else
template <class charT, class implementationT = c_regex_traits<charT> >
struct regex_traits;
#endif

template <class charT, class traits = regex_traits<charT> >
class basic_regex;

typedef basic_regex<char, regex_traits<char> > regex;
#ifndef BOOST_NO_WREGEX
typedef basic_regex<wchar_t, regex_traits<wchar_t> > wregex;
#endif

} // namespace boost

#endif  // BOOST_REGEX_NO_FWD

#endif


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

    <dimen name="fab_size">80dp</dimen>

</resources>


text:
package org.orgama.server.config;

import com.google.inject.BindingAnnotation;
import com.google.inject.Inject;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;

/**
 * Constants
 * @author kguthrie
 */
public class ServerSideConstants {

	/************ Binding annotations for application configurations *********/

	@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
	public static @interface SessionCookieName {}

	@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
	public static @interface AuthSessionKey {}

	@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
	public static @interface AuthInitializationKey {}

	@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
	public static @interface SessionLifetimeMillis {}

	/************* Default constants for Auth System ****************/
	private static final String DEFAULT_SESSION_COOKIE_NAME = "OGX";
	private static final String DEFAULT_AUTH_SESSION_KEY = "auth-session";
	private static final String DEFAULT_AUTH_INITIALIZATION_KEY =
			"auth-initialization";
	private static final Long DEFAULT_SESSION_LIFETIME_MILLIS =
			30L * 24L * 60L * 60L * 1000L; //30 days

	private String sessionCookieName = DEFAULT_SESSION_COOKIE_NAME;
	private String authSessionKey = DEFAULT_AUTH_SESSION_KEY;
	private String authInitializationKey = DEFAULT_AUTH_INITIALIZATION_KEY;
	private Long sessionLifetimeMillis = DEFAULT_SESSION_LIFETIME_MILLIS;

	/**
	 * @return the sessionCookieName
	 */
	public String getSessionCookieName() {
		return sessionCookieName;
	}

	/**
	 * @param sessionCookieName the sessionCookieName to set
	 */
	@Inject(optional = true)
	void setSessionCookieName(@SessionCookieName String sessionCookieName) {
		this.sessionCookieName = sessionCookieName;
	}

	/**
	 * @return the authSessionKey
	 */
	public String getAuthSessionKey() {
		return authSessionKey;
	}

	/**
	 * @param authSessionKey the authSessionKey to set
	 */
	@Inject(optional = true)
	void setAuthSessionKey(@AuthSessionKey String authSessionKey) {
		this.authSessionKey = authSessionKey;
	}

	/**
	 * @return the authInitializationKey
	 */
	public String getAuthInitializationKey() {
		return authInitializationKey;
	}

	/**
	 * @param authInitializationKey the authInitializationKey to set
	 */
	@Inject(optional = true)
	void setAuthInitializationKey(
			@AuthInitializationKey String authInitializationKey) {
		this.authInitializationKey = authInitializationKey;
	}

	/**
	 * @return the sessionLifetimeMillis
	 */
	public Long getSessionLifetimeMillis() {
		return sessionLifetimeMillis;
	}

	/**
	 * @param sessionLifetimeMillis the sessionLifetimeMillis to set
	 */
	@Inject(optional = true)
	void setSessionLifetimeMillis(
			@SessionLifetimeMillis Long sessionLifetimeMillis) {
		this.sessionLifetimeMillis = sessionLifetimeMillis;
	}
}


text:
using cwchat.Server.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace cwchat.Server.Controllers
{
    public class ValuesController : ApiController
    {
        DB db = new DB();

        // GET api/values
        public IEnumerable<MessageModel> Get()
        {
            return db.Messages;
        }

        // POST api/values
        public void Post([FromBody]MessageModel value)
        {
            if(ModelState.IsValid)
            {
                value.Date = DateTime.Now;

                db.Messages.Add(value);
                db.SaveChanges();
            }
        }
    }
}


text:
$.components.register("dropify", {
  mode: "default",
  defaults: {}
});


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.06.02 at 04:25:47 PM CEST
//

package org.w3._2001.xmlschema;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 * restricted max/min
 *
 *
Java class for narrowMaxMin complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="narrowMaxMin">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}localElement">
 *       <sequence>
 *         <element ref="{http://www.w3.org/2001/XMLSchema}annotation" minOccurs="0"/>
 *         <choice minOccurs="0">
 *           <element name="simpleType" type="{http://www.w3.org/2001/XMLSchema}localSimpleType"/>
 *           <element name="complexType" type="{http://www.w3.org/2001/XMLSchema}localComplexType"/>
 *         </choice>
 *         <group ref="{http://www.w3.org/2001/XMLSchema}identityConstraint" maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *       <attribute name="minOccurs" default="1">
 *         <simpleType>
 *           <restriction base="{http://www.w3.org/2001/XMLSchema}nonNegativeInteger">
 *             <enumeration value="0"/>
 *             <enumeration value="1"/>
 *           </restriction>
 *         </simpleType>
 *       </attribute>
 *       <attribute name="maxOccurs" default="1">
 *         <simpleType>
 *           <restriction base="{http://www.w3.org/2001/XMLSchema}allNNI">
 *             <enumeration value="0"/>
 *             <enumeration value="1"/>
 *           </restriction>
 *         </simpleType>
 *       </attribute>
 *       <anyAttribute processContents='lax' namespace='##other'/>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "narrowMaxMin")
public class NarrowMaxMin
    extends LocalElement
{

}


text:
<?php

namespace AppBundle\Command;

use AppBundle\Entity\Sprint;
use AppBundle\Repository\SprintRepository;
use Doctrine\ORM\NoResultException;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * @author Romain Kuzniak <romain.kuzniak@turn-it-up.org>
 */
class CloseSprintCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this->setName('agility-board:close-sprint')
            ->setDescription('Close sprint');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        try {
            /** @var SprintRepository $repository */
            $repository = $this->getContainer()->get('doctrine')->getRepository('AppBundle:Sprint');

            $sprint = $repository->findSprintToClose();
            foreach ($sprint->getIssues() as $issue) {
                if ('DONE' === $issue->getStatus()) {
                    $issue->setClosedAt(new \DateTime());
                    $issue->setStatus('CLOSE');
                } else {
                    $sprint->removeIssue($issue);
                }
            }
            $sprint->setEffectiveClosedAt(new \DateTime());
            $sprint->setStatus('CLOSE');

            $this->getContainer()->get('doctrine')->getManager()->flush();

            $output->writeln('Close Sprint: ' . $sprint->getId());

        } catch (NoResultException $nre) {
            $output->writeln('None');
        }
    }
}


text:
using UnityEngine;
using System.Collections;

[System.Serializable]
public class LegItem : GameItem
{

    //Head item advanced stats
    private float defense;
    private float strength;
    private float endurance;
    private float crit;
    private int reqLevel;

    public LegItem(string itemName, int goldWorth, float defense, float endurance, float strength, float crit) : base(itemName, goldWorth)
    {
        SetDefense(defense);
        SetStrength(strength);
        SetEndurance(endurance);
        SetCrit(crit);
        SetReqLevel((int)Mathf.Max(Mathf.Max(defense, endurance), Mathf.Max(strength, crit)));
    }

    //LegItem constructor 1 arg
    public LegItem(int level)
    {
        SetItemName(RandomName());
        SetDefense(Random.Range(0, level+1));
        SetStrength(Random.Range(0, level+1));
        SetEndurance(Random.Range(0, level+1));
        SetCrit(Random.Range(0, level+1));
        SetReqLevel((int)Mathf.Max(Mathf.Max(defense, endurance), Mathf.Max(strength, crit)));
        SetGoldWorth(Random.Range(1, GetReqLevel()));
    }

    //methods
    public override string RandomName()
    {
        string[] first = { "Golden ", "Thick ", "Strong ", "Metal ", "Leather ", "Chain Mail ", "Wool ", "Scrappy ", "Worn ", "Used ", "Plate ", "Steel ", "Great " };
        string[] second = { "Legs ", "Leg Armor ", "Leggings ", "Greaves ", "Legguards ", "Kilt ", "Breeches ", "Legwraps ", "Britches ", "Lower Robe ", "Skirt "};
        string name = string.Concat(first[Random.Range(0, first.Length - 1)], second[Random.Range(0, second.Length - 1)]);
        return name;
    }

    //getters
    public float GetDefense()
    {
        return this.defense;
    }
    public float GetStrength()
    {
        return this.strength;
    }
    public float GetEndurance()
    {
        return this.endurance;
    }
    public float GetCrit()
    {
        return this.crit;
    }
    public int GetReqLevel()
    {
        return this.reqLevel;
    }

    //setters
    public void SetDefense(float defense)
    {
        this.defense = defense;
    }
    public void SetStrength(float strength)
    {
        this.strength = strength;
    }
    public void SetEndurance(float endurance)
    {
        this.endurance = endurance;
    }
    public void SetCrit(float crit)
    {
        this.crit = crit;
    }
    public void SetReqLevel(int reqLevel)
    {
        this.reqLevel = reqLevel;
    }
}


text:
/**************************************************************************
 * Stack map generation
 *************************************************************************/

    /** An entry in the stack map. */
    static class StackMapFrame {
		int pc;
		Type[] locals;
		Type[] stack;
    }

    /** A buffer of cldc stack map entries. */
    StackMapFrame[] stackMapBuffer = null;

    /** A buffer of compressed StackMapTable entries. */
    StackMapTableFrame[] stackMapTableBuffer = null;
    int stackMapBufferSize = 0;

    /** The last PC at which we generated a stack map. */
    int lastStackMapPC = -1;

    /** The last stack map frame in StackMapTable. */
    StackMapFrame lastFrame = null;

    /** The stack map frame before the last one. */
    StackMapFrame frameBeforeLast = null;

    /** Emit a stack map entry.  */
    public void emitStackMap() {
		try {//我加上的
		DEBUG.P(this,"emitStackMap()");
		DEBUG.P("needStackMap="+needStackMap);

		int pc = curPc();
		if (!needStackMap) return;

		DEBUG.P("pc="+pc);
		DEBUG.P("stackMap="+stackMap);

        switch (stackMap) {
            case CLDC:
                emitCLDCStackMap(pc, getLocalsSize());
                break;
            case JSR202:
                emitStackMapFrame(pc, getLocalsSize());
                break;
            default:
                throw new AssertionError("Should have chosen a stackmap format");
		}
		// DEBUG code follows
		if (debugCode) state.dump(pc);

		}finally{//我加上的
		DEBUG.P(0,this,"emitStackMap()");
		}
    }

    private int getLocalsSize() {
        int nextLocal = 0;
		for (int i=max_locals-1; i>=0; i--) {
			if (state.defined.isMember(i) && lvar[i] != null) {
				//如果一个居部变量是long或double类型,它占用两个数组项,
				//但这个居部变量在居部变量数组中实际只存放在索引号较低的那一项中,
				//另一项留空,但不能被其他居部变量占用
				nextLocal = i + width(lvar[i].sym.erasure(types));
				break;
			}
		}
        return nextLocal;
    }

    /** Emit a CLDC stack map frame. */
    void emitCLDCStackMap(int pc, int localsSize) {
		if (lastStackMapPC == pc) {
			// drop existing stackmap at this offset
			stackMapBuffer[--stackMapBufferSize] = null;
		}
		lastStackMapPC = pc;

		if (stackMapBuffer == null) {
			stackMapBuffer = new StackMapFrame[20];
		} else if (stackMapBuffer.length == stackMapBufferSize) {
			StackMapFrame[] newStackMapBuffer =
			new StackMapFrame[stackMapBufferSize << 1];
			System.arraycopy(stackMapBuffer, 0, newStackMapBuffer,
					 0, stackMapBufferSize);
			stackMapBuffer = newStackMapBuffer;
		}
		StackMapFrame frame =
			stackMapBuffer[stackMapBufferSize++] = new StackMapFrame();
		frame.pc = pc;

		frame.locals = new Type[localsSize];
		for (int i=0; i<localsSize; i++) {
			if (state.defined.isMember(i) && lvar[i] != null) {
				Type vtype = lvar[i].sym.type;
				if (!(vtype instanceof UninitializedType))
					vtype = types.erasure(vtype);
				frame.locals[i] = vtype;
			}
		}
		frame.stack = new Type[state.stacksize];
		for (int i=0; i<state.stacksize; i++)
			frame.stack[i] = state.stack[i];
    }

    void emitStackMapFrame(int pc, int localsSize) {
        if (lastFrame == null) {
            // first frame
            lastFrame = getInitialFrame();
        } else if (lastFrame.pc == pc) {
			// drop existing stackmap at this offset
			stackMapTableBuffer[--stackMapBufferSize] = null;
            lastFrame = frameBeforeLast;
            frameBeforeLast = null;
		}

        StackMapFrame frame = new StackMapFrame();
        frame.pc = pc;

		int localCount = 0;
		Type[] locals = new Type[localsSize];
        for (int i=0; i<localsSize; i++, localCount++) {
            if (state.defined.isMember(i) && lvar[i] != null) {
                Type vtype = lvar[i].sym.type;
				if (!(vtype instanceof UninitializedType))
					vtype = types.erasure(vtype);
				locals[i] = vtype;
				if (width(vtype) > 1) i++;
            }
		}
		frame.locals = new Type[localCount];
		for (int i=0, j=0; i<localsSize; i++, j++) {
            assert(j < localCount);
			frame.locals[j] = locals[i];
            if (width(locals[i]) > 1) i++;
		}

		int stackCount = 0;
		for (int i=0; i<state.stacksize; i++) {
            if (state.stack[i] != null) {
                stackCount++;
			}
		}
		frame.stack = new Type[stackCount];
		stackCount = 0;
		for (int i=0; i<state.stacksize; i++) {
            if (state.stack[i] != null) {
                frame.stack[stackCount++] = state.stack[i];
			}
		}

        if (stackMapTableBuffer == null) {
			stackMapTableBuffer = new StackMapTableFrame[20];
		} else if (stackMapTableBuffer.length == stackMapBufferSize) {
			StackMapTableFrame[] newStackMapTableBuffer =
			new StackMapTableFrame[stackMapBufferSize << 1];
			System.arraycopy(stackMapTableBuffer, 0, newStackMapTableBuffer,
							0, stackMapBufferSize);
			stackMapTableBuffer = newStackMapTableBuffer;
		}
		stackMapTableBuffer[stackMapBufferSize++] =
                StackMapTableFrame.getInstance(frame, lastFrame.pc, lastFrame.locals, types);

        frameBeforeLast = lastFrame;
        lastFrame = frame;
    }

    StackMapFrame getInitialFrame() {
        StackMapFrame frame = new StackMapFrame();
        List<Type> arg_types = ((MethodType)meth.externalType(types)).argtypes;
        int len = arg_types.length();
        int count = 0;
        if (!meth.isStatic()) {
            Type thisType = meth.owner.type;
            frame.locals = new Type[len+1];
            if (meth.isConstructor() && thisType != syms.objectType) {
                frame.locals[count++] = UninitializedType.uninitializedThis(thisType);
            } else {
                frame.locals[count++] = types.erasure(thisType);
            }
        } else {
            frame.locals = new Type[len];
        }
        for (Type arg_type : arg_types) {
            frame.locals[count++] = types.erasure(arg_type);
        }
        frame.pc = -1;
        frame.stack = null;
        return frame;
    }


text:
<!doctype html>

     <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
     <link href="https://fonts.googleapis.com/css?family=Kaushan+Script" rel="stylesheet" type="text/css">
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
      <meta charset="utf-8">
       <title>Damien Klementik | CỒdi n Camp - Promo 1 </title>
     <link rel="stylesheet" href="style.css">

       Còdi n Camp

Promo #1

Biographie

Objectifs

Projets

A propos de moi

NOM:Klementik

Prénom:Damien

Ville:Mende

Age:28ans

Compte github:dklementik

Biographie

J'aime le sport venant de Béziers obligatoirement je pratique le Rugby depuis tout petit.
           J'ai beaucoup voyagé fait pas mal de petit boulot et compte bien sur la formation Còdi
          n camp pour me perfectionner dans le milieu du dévelopement web.

Objectif après Còdi n Camp

Réussir mon projet de devenir développeur web et d'intégrer une web agency ou de me mettre en indépendant selon les compétences que j'aurais acquis pendant la formation.

 Projets

 Réalisé

 Mettre un répertoire sous git

 Encours

CV en ligne

 Loisir

 Rugby

 Ski

 Vin

    </form>

            Copyright © - Còdi n Camp - 2015 -


text:
Rails.application.routes.draw do
  clc = ComponentLibrary.configuration
  get ':root_path/', to: 'library#index', as: 'components', constraints: lambda { |request|
    clc.root_paths.any? { |root_path| request.original_fullpath.include?(root_path)}
  }
  get ':root_path/*path', to: 'library#show', as: 'component', constraints: lambda { |request|
      clc.root_paths.any? { |root_path| request.original_fullpath.include?(root_path) }
  }
end


text:
package org.consumersunion.stories.server.notification_channel;

import org.consumersunion.stories.common.client.service.datatransferobject.ProfileSummary;
import org.consumersunion.stories.common.shared.model.Subscription;
import org.consumersunion.stories.common.shared.model.SystemEntity;

import com.google.common.base.MoreObjects;

/**
 * Encapsulates a {@link org.consumersunion.stories.common.shared.model.Subscription} and related data :
 * the associated {@link org.consumersunion.stories.common.client.service.datatransferobject.ProfileSummary} and
 * related {@link org.consumersunion.stories.common.shared.model.SystemEntity}
 */
public class SubscriptionSummary {
    private final Subscription subscription;
    private final ProfileSummary profileSummary;
    private final SystemEntity systemEntity;

    public SubscriptionSummary(
            Subscription subscription,
            ProfileSummary profileSummary,
            SystemEntity systemEntity) {
        this.subscription = subscription;
        this.profileSummary = profileSummary;
        this.systemEntity = systemEntity;
    }

    public static Builder builder() {
        return new Builder();
    }

    public Subscription getSubscription() {
        return subscription;
    }

    public ProfileSummary getProfileSummary() {
        return profileSummary;
    }

    public SystemEntity getSystemEntity() {
        return systemEntity;
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
                .add("subscription", subscription)
                .add("profileSummary", profileSummary)
                .add("systemEntity", systemEntity)
                .toString();
    }

    public static class Builder {
        private Subscription subscription;
        private ProfileSummary profileSummary;
        private SystemEntity systemEntity;

        private Builder() {
        }

        public Builder subscription(Subscription subscription) {
            this.subscription = subscription;
            return this;
        }

        public Builder profileSummary(ProfileSummary profileSummary) {
            this.profileSummary = profileSummary;
            return this;
        }

        public Builder systemEntity(SystemEntity systemEntity) {
            this.systemEntity = systemEntity;
            return this;
        }

        public SubscriptionSummary build() {
            return new SubscriptionSummary(subscription, profileSummary, systemEntity);
        }
    }
}


text:
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using BarCampCV.Web.App_Start;

namespace BarCampCV.Web
{
    public class MvcApplication : HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}


text:
var MemoryLogger = require('./lib/logger'),
	logger = new MemoryLogger();

var exportMethods = [
	'run',
	'stop',
	'setLogDir',
	'setMaxLogSize'
];

for (var i = 0; i < exportMethods.length; i++) {
	(function(method) {
		module.exports[method] = function() {
			return logger[method].apply(logger, arguments);
		};
	}) (exportMethods[i]);
}


text:
package app.horses.camera;

import android.Manifest;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.annotation.ColorRes;
import android.support.annotation.IntDef;
import android.support.annotation.StringRes;
import android.support.v4.content.ContextCompat;
import android.util.Log;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

import app.horses.camera.ui.activity.GetActivity;
import app.horses.camera.ui.activity.TakeActivity;
import app.horses.camera.util.CameraException;
import app.horses.camera.util.Constants;
import app.horses.camera.util.Methods;

import static app.horses.camera.util.Constants.REQUEST_TAKE;

/**
 * @author Brian Salvattore
 */
public class CameraManager {

    private static final String TAG = CameraManager.class.getSimpleName();
    private CallbackManager callbackManager;

    public static final int FORMAT_JPG = Constants.FORMAT_JPG;
    public static final int FORMAT_PNG = Constants.FORMAT_PNG;
    public static final int FORMAT_WEBP = Constants.FORMAT_WEBP;

    private static CameraManager instance;

    private Builder builder;

    public static CameraManager getInstance() {
        return instance;
    }

    public CameraManager(Builder builder) {
        this.builder = builder;
        Methods.init(builder.application);
    }

    public static void init(Application application) {
        instance = new Builder(application)
                /*.setPackageName(CameraManager.class.getPackage().getName())
                .setPrimaryColor(R.color.defaultColor)*/
                .build();
    }

    public static void openCamera(Activity activity) {

        activity.startActivityForResult(new Intent(activity, TakeActivity.class), REQUEST_TAKE);
    }

    public static void openCamera(Activity activity,String path) {
        Intent intent=new Intent(activity, TakeActivity.class);
        intent.putExtra(Constants.EXTRA_FOLDER_PATH,path);
        activity.startActivityForResult(intent, REQUEST_TAKE);
    }

    public static void init(CameraManager cameraManager) {
        instance = cameraManager;
    }

    public Builder getBuilder() {
        return builder;
    }

    public static Application getApplication() {
        return instance.builder.application;
    }

    @ColorRes
    public static  int getColorPrimary() {
        return instance.builder.primaryColor;
    }

    public static boolean isCropSquare() {
        return instance.builder.cropSquare;
    }

    public static boolean isCropView() {
        return instance.builder.cropView;
    }

    public static boolean isGallery() {
        return instance.builder.gallery;
    }

    public static boolean isFrontCamera() {
        return instance.builder.frontCamera;
    }

    public static boolean isFlash() {
        return instance.builder.flash;
    }

    public static int getQuality() {
        return instance.builder.quality;
    }

    @Format
    public static int getFormat() {
        return instance.builder.format;
    }

    public static void openCamera2(Activity activity) {

        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED) {
            CallbackManager.getCallback().onFailureCamera(new CameraException("permission denied for camera"));
            return;
        }
        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
            CallbackManager.getCallback().onFailureCamera(new CameraException("permission denied for storage"));
            return;
        }

        activity.startActivityForResult(new Intent(activity, GetActivity.class), REQUEST_TAKE);
    }

    @IntDef({FORMAT_JPG, FORMAT_PNG, FORMAT_WEBP})
    @Retention(RetentionPolicy.SOURCE)
    @interface Format {
    }

    @SuppressWarnings("WeakerAccess")
    public static class Builder {

        protected String packageName = CameraManager.class.getPackage().getName();
        protected int primaryColor = 0;

        protected boolean cropSquare = false;
        protected boolean gallery = false;
        protected boolean frontCamera = false;
        protected boolean cropView = false;
        protected boolean flash = false;

        protected int quality = 100;
        protected int format = CameraManager.FORMAT_JPG;

        protected Application application;

        public Builder(Application application) {
            this.application = application;
        }

        public Builder setPackageName(@StringRes int packageName) {
            this.packageName = application.getText(packageName).toString();
            return this;
        }

        public Builder setPackageName(String packageName) {
            this.packageName = packageName;
            return this;
        }

        public Builder setPrimaryColor(@ColorRes int primaryColor) {
            this.primaryColor = primaryColor;
            return this;
        }

        public Builder enableCropSquare(boolean cropSquare) {
            this.cropSquare = cropSquare;
            return this;
        }

        public Builder enableGallery(boolean gallery) {
            this.gallery = gallery;
            return this;
        }

        public Builder enableFrontCamera(boolean frontCamera) {
            this.frontCamera = frontCamera;
            return this;
        }

        public Builder enableFlash(boolean flash) {
            this.flash = flash;
            return this;
        }

        public Builder setQuality(int quality) {
            this.quality = quality;
            return this;
        }

        public Builder setFormat(@Format int format) {
            this.format = format;
            return this;
        }

        public Builder enableCropView(boolean cropView) {
            this.cropView = cropView;
            return this;
        }

        public CameraManager build() {
            return new CameraManager(this);
        }
    }
}


text:
NS_ASSUME_NONNULL_BEGIN

@interface MDGCDTimer : NSObject

+ (NSString *)addTimer:(NSString * _Nullable)timerID
           toContainer:(id _Nullable)container
                 queue:(dispatch_queue_t _Nullable)queue
              duration:(NSTimeInterval)duration
           immediately:(BOOL)immediately
                 block:(void (^)(NSString *timerID))block;

+ (NSString *)cancelTimer:(NSString *)timerID
            fromContainer:(id _Nullable)container;

@end

NS_ASSUME_NONNULL_END


text:
def largest_integer(list_of_nums)
  # Your code goes here!
  if list_of_nums.empty?
    return nil
  else
    sorted = list_of_nums.sort
    return sorted.last
  end
end


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

import java.util.Date;

import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;

/**
 * A simple WS for unit test purpose
 *
 * @author Esteban Robles Luna
 */
@WebService
public interface WebServiceMock {

  /**
   * Increase the counter in 1
   */
  void inc() throws MaxValueReachedFault;

  /**
   * Returns the current count
   *
   * @return the count
   */
  @WebResult(name = "count")
  int getCount();

  /**
   * Resets the counter to 0
   */
  void reset();

  /**
   * Sets the counter to value
   *
   * @param value
   *          the value of the new counter
   */
  void setTo(@WebParam(name = "value") int value);

  /**
   * Returns a formated string composed of prefix + current count + suffix
   *
   * @param prefix
   *          the prefix
   * @param suffix
   *          the suffix
   * @return the formated string
   */
  @WebResult(name = "prettyPrint")
  String prettyPrintCount(@WebParam(name = "prefix") String prefix, @WebParam(name = "suffix") String suffix);

  /**
   * Sets the current data structure
   *
   * @param str
   *          the new string of data structure
   * @param date
   *          the new date of data structure
   */
  void setDataStructure(@WebParam(name = "eltStr") String str, @WebParam(name = "eltDate") Date date);

  /**
   * Returns the current data structure
   *
   * @return the current data structure
   */
  @WebResult(name = "currentStructure")
  WebServiceDataStructure getDataStructure();

  @WebResult
  String noNameResult(@WebParam(name = "prefix") String prefix, @WebParam(name = "suffix") String suffix);

  @WebResult(name = "static")
  String reservedWordAsName(@WebParam(name = "prefix") String prefix, @WebParam(name = "suffix") String suffix);
}


text:
import unittest
from v1pysdk.string_utils import split_attribute

class TestStringUtils(unittest.TestCase):
    def test_split_attribute(self):
        self.assertEquals(['[testing]]'],split_attribute('[testing]]'))
        self.assertEquals(['[[testing]'],split_attribute('[[testing]'))
        self.assertEquals(['testing','a','sentence','is','difficult'],split_attribute('testing.a.sentence.is.difficult'))
        self.assertEquals(['testing','[a.sentence]','is','difficult'],split_attribute('testing.[a.sentence].is.difficult'))
        self.assertEquals(['testing[.a.sentence]','is', 'difficult'],split_attribute('testing[.a.sentence].is.difficult'))
        self.assertEquals(['testing','a[.sentence.]is','difficult'],split_attribute('testing.a[.sentence.]is.difficult'))
        self.assertEquals(['testing','a','sentence','is','difficult]'],split_attribute('testing.a.sentence.is.difficult]'))
        self.assertEquals(['testing', 'a','sentence','is',']difficult'],split_attribute('testing.a.sentence.is.]difficult'))
        self.assertEquals(['[testing.a.sentence.is]','difficult'],split_attribute('[testing.a.sentence.is].difficult'))
        self.assertEquals(['[testing.][a.sentence.is.difficult]'],split_attribute('[testing.][a.sentence.is.difficult]'))
        self.assertEquals(['[testing]','[a]','[sentence]','[is]','[difficult]'],
                          split_attribute('[testing].[a].[sentence].[is].[difficult]'))
        self.assertEquals(['testing','[[a.sentence.]is]','difficult'],
                          split_attribute('testing.[[a.sentence.]is].difficult'))
        self.assertEquals(["History[Status.Name='Done']"],split_attribute("History[Status.Name='Done']"))
        self.assertEquals(["ParentMeAndUp[Scope.Workitems.@Count='2']"],
                          split_attribute("ParentMeAndUp[Scope.Workitems.@Count='2']") )
        self.assertEquals(["Owners","OwnedWorkitems[ChildrenMeAndDown=$]","@DistinctCount"],
                          split_attribute("Owners.OwnedWorkitems[ChildrenMeAndDown=$].@DistinctCount") )
        self.assertEquals(["Workitems[ParentAndUp[Scope=$].@Count='1']"],
                          split_attribute("Workitems[ParentAndUp[Scope=$].@Count='1']") )
        self.assertEquals(["RegressionPlan","RegressionSuites[AssetState!='Dead']","TestSets[AssetState!='Dead']","Environment", "@DistinctCount"]
                          ,split_attribute("RegressionPlan.RegressionSuites[AssetState!='Dead'].TestSets[AssetState!='Dead'].Environment.@DistinctCount") )
        self.assertEquals(["Scope","ChildrenMeAndDown","Workitems:Story[ChildrenMeAndDown.ToDo.@Sum!='0.0']","Estimate","@Sum"]
                          ,split_attribute("Scope.ChildrenMeAndDown.Workitems:Story[ChildrenMeAndDown.ToDo.@Sum!='0.0'].Estimate.@Sum") )

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


text:
<?php

namespace Oro\Bundle\SecurityBundle\Tests\Unit\Search;

use Oro\Bundle\SearchBundle\Query\Query;
use Oro\Bundle\SecurityBundle\Search\AclHelper;

class AclHelperTest extends \PHPUnit_Framework_TestCase
{
    /** @var AclHelper */
    protected $aclHelper;

    /** @var \PHPUnit_Framework_MockObject_MockObject */
    protected $mappingProvider;

    /** @var \PHPUnit_Framework_MockObject_MockObject */
    protected $securityFacade;

    /** @var \PHPUnit_Framework_MockObject_MockObject */
    protected $ownershipDataBuilder;

    /** @var array */
    protected $mappings = [
        'Oro\Test\Entity\User'      => [
            'alias'        => 'testUser',
            'aclCondition' => [null, null, null, null] // no access
        ],
        'Oro\Test\Entity\Product'   => [
            'alias'        => 'testProduct',
            'aclCondition' => [] // full access
        ],
        'Oro\Test\Entity\Price'     => [
            'alias'        => 'testPrice',
            'aclCondition' => [
                'owner',
                null // full access
            ]
        ],
        'Oro\Test\Entity\OrderItem' => [
            'alias'        => 'testOrderItem',
            'aclCondition' => [
                'owner',
                [] // no access
            ]
        ],
        'Oro\Test\Entity\Category'  => [
            'alias'        => 'testCategory',
            'aclCondition' => [
                'owner',
                [3]
            ]
        ],
        'Oro\Test\Entity\Order'     => [
            'alias'        => 'testOrder',
            'aclCondition' => [
                'owner',
                [3, 5, 4, 6]
            ]
        ],
    ];

    public function setUp()
    {
        $this->mappingProvider = $this->getMockBuilder('Oro\Bundle\SearchBundle\Provider\SearchMappingProvider')
            ->disableOriginalConstructor()
            ->getMock();

        $this->securityFacade = $this->getMockBuilder('Oro\Bundle\SecurityBundle\SecurityFacade')
            ->disableOriginalConstructor()
            ->getMock();

        $this->ownershipDataBuilder = $this
            ->getMockBuilder('Oro\Bundle\SecurityBundle\ORM\Walker\OwnershipConditionDataBuilder')
            ->disableOriginalConstructor()
            ->getMock();

        $this->aclHelper = new AclHelper($this->mappingProvider, $this->securityFacade, $this->ownershipDataBuilder);
    }

    /**
     * @dataProvider applyTestCases
     *
     * @param mixed  $from
     * @param string $expectedQuery
     */
    public function testApply($from, $expectedQuery)
    {
        $mappings = $this->mappings;

        $this->mappingProvider->expects($this->any())
            ->method('getEntitiesListAliases')
            ->willReturnCallback(
                function () use ($mappings) {
                    $result = [];
                    foreach ($mappings as $className => $mapping) {
                        $result[$className] = $mapping['alias'];
                    }

                    return $result;
                }
            );
        $this->mappingProvider->expects($this->any())
            ->method('getEntityClass')
            ->willReturnCallback(
                function ($alias) use ($mappings) {
                    foreach ($mappings as $className => $mapping) {
                        if ($mapping['alias'] == $alias) {
                            return $className;
                        }
                    }

                    return null;
                }
            );

        $this->securityFacade->expects($this->any())
            ->method('getOrganizationId')
            ->willReturn(1);

        $this->ownershipDataBuilder->expects($this->any())
            ->method('getAclConditionData')
            ->willReturnCallback(
                function ($class) use ($mappings) {
                    foreach ($mappings as $className => $mapping) {
                        if ($class === $className) {
                            return $mapping['aclCondition'];
                        }
                    }

                    return null;
                }
            );

        $query = new Query();
        $query->from($from);
        $this->aclHelper->apply($query);
        $this->assertEquals($expectedQuery, $query->getStringQuery());
    }

    public function applyTestCases()
    {
        return [
            'select from *'             => [
                '*',
                'from testProduct, testPrice, testOrderItem, testCategory, testOrder where '
                . '((integer testProduct_owner >= 0 or integer testPrice_owner >= 0 or integer '
                . 'testOrderItem_owner = 0 or integer testCategory_owner = 3 or integer testOrder_owner '
                . 'in (3, 5, 4, 6)) and integer organization in (1, 0))'
            ],
            'select with unknown alias' => [
                ['testProduct', 'badAlias'],
                'from testProduct where ((integer testProduct_owner >= 0) and integer organization in (1, 0))'
            ]
        ];
    }
}


text:
<?php

// ensure we get report on all possible php errors
error_reporting(-1);

define('YII_ENABLE_ERROR_HANDLER', false);
define('YII_DEBUG', true);
$_SERVER['SCRIPT_NAME'] = '/' . __DIR__;
$_SERVER['SCRIPT_FILENAME'] = __FILE__;

require_once(__DIR__ . '/../vendor/autoload.php');
require_once(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');

Yii::setAlias('@miloschumanunit/highcharts', __DIR__);

date_default_timezone_set('UTC');


text:
<?php

namespace MagdKudama\Phatic\DependencyInjection;

use MagdKudama\Phatic\Collection\ExtensionCollection;
use MagdKudama\Phatic\DependencyInjection\Compiler\CommandPass;
use MagdKudama\Phatic\DependencyInjection\Compiler\EventSubscriberPass;
use MagdKudama\Phatic\DependencyInjection\Compiler\ProcessorPass;
use MagdKudama\Phatic\DependencyInjection\Compiler\ViewExtensionPass;
use MagdKudama\Phatic\DependencyInjection\Configuration;
use MagdKudama\Phatic\Exception\DependencyNotSatisfiedException;
use MagdKudama\Phatic\Exception\UndefinedClassException;
use MagdKudama\Phatic\Extension;
use MagdKudama\Phatic\Utils;
use Symfony\Component\Config\Definition\Processor;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use ReflectionClass;
use InvalidArgumentException;

class PhaticExtension
{
    const INTERFACE_TO_IMPLEMENT = 'MagdKudama\Phatic\Extension';

    /** @var Processor */
    private $processor;

    /** @var Configuration */
    private $configuration;

    /** @var ExtensionCollection */
    private $extensions;

    private $systemConfig;
    private $resultsDirectory;

    public function __construct($systemConfig, $resultsDirectory)
    {
        $this->processor = new Processor();
        $this->configuration = new Configuration();
        $this->extensions = new ExtensionCollection();
        $this->systemConfig = $systemConfig;
        $this->resultsDirectory = $resultsDirectory;
    }

    public function load(array $configs, ContainerBuilder $container)
    {
        $arrayConfig = [
            'config_file' => $this->systemConfig,
            'app_directory' => $this->resultsDirectory,
            'site_directory' => $this->resultsDirectory . 'site/',
            'assets_path' => $this->resultsDirectory . 'site/_assets/',
            'layouts_path' => $this->resultsDirectory . 'site/_pages/_layouts/',
            'posts_path' => $this->resultsDirectory . 'site/_posts/',
            'results_path' => $this->resultsDirectory . 'site/result/',
            'pages_path' => $this->resultsDirectory . 'site/_pages/',
            'system_directory' => Utils::getSystemDirectory(),
            'boot_directory' => Utils::getBootDirectory() . 'bootstrap/site/'
        ];

        $container->setParameter('phatic.app_config', $arrayConfig);

        $extensionsConfigs = [];
        if (isset($configs['config']['extensions'])) {
            foreach ($configs['config']['extensions'] as $extensionLocator => $extensionConfig) {
                if (!class_exists($extensionLocator)) {
                    throw new UndefinedClassException("Class {$extensionLocator} does not exist");
                }
                $refClass = new ReflectionClass($extensionLocator);
                if (!$refClass->implementsInterface(self::INTERFACE_TO_IMPLEMENT)) {
                    throw new InvalidArgumentException("Extensions must implement interface " . self::INTERFACE_TO_IMPLEMENT);
                }

                $this->extensions->addByFqn($extensionLocator);
                $extensionsConfigs[$extensionLocator] = $extensionConfig;
            }
        }

        $tree = $this->configuration->getConfigTree($this->extensions);
        $this->processor->process($tree, $configs);

        $loader = new YamlFileLoader(
            $container,
            new FileLocator(__DIR__ . '/../Config')
        );
        $loader->load('services.yml');

        /** @var Extension $extension */
        foreach ($this->extensions as $extension) {
            if (null !== $extension->getExtensionDependency()) {
                if (!$this->extensions->findByName($extension->getExtensionDependency())) {
                    $message = sprintf("Extension %s requires extension %s", get_class($extension), $extension->getExtensionDependency());
                    throw new DependencyNotSatisfiedException($message);
                }
            }

            $config = ($extensionsConfigs[get_class($extension)]) ? $extensionsConfigs[get_class($extension)] : [];
            $extension->load($config, $container);
        }

        $this->addCompilerPasses($container);
    }

    protected function addCompilerPasses(ContainerBuilder $container)
    {
        $container->addCompilerPass(new CommandPass());
        $container->addCompilerPass(new ViewExtensionPass());
        $container->addCompilerPass(new ProcessorPass());
        $container->addCompilerPass(new EventSubscriberPass());
    }

    /** @return ExtensionCollection */
    public function getExtensionCollection()
    {
        return $this->extensions;
    }
}


text:
package net.bytebuddy.pool;

import net.bytebuddy.test.utility.ObjectPropertyAssertion;
import org.junit.Test;
import org.objectweb.asm.Type;

import java.util.Arrays;
import java.util.Iterator;

import static org.mockito.Mockito.when;

public class TypePoolLazyObjectPropertiesTest {

    @Test
    public void testObjectProperties() throws Exception {
        ObjectPropertyAssertion.of(TypePool.LazyTypeDescription.FieldToken.class).apply();
        ObjectPropertyAssertion.of(TypePool.LazyTypeDescription.MethodToken.class).apply();
        final Iterator<Integer> iterator = Arrays.asList(1, 2).iterator();
        ObjectPropertyAssertion.of(TypePool.LazyTypeDescription.MethodToken.ParameterToken.class).create(new ObjectPropertyAssertion.Creator<Integer>() {
            @Override
            public Integer create() {
                return iterator.next();
            }
        }).apply();
        ObjectPropertyAssertion.of(TypePool.LazyTypeDescription.AnnotationToken.class).apply();
        ObjectPropertyAssertion.of(TypePool.LazyTypeDescription.AnnotationValue.Trivial.class).apply();
        ObjectPropertyAssertion.of(TypePool.LazyTypeDescription.AnnotationValue.ForAnnotation.class).apply();
        ObjectPropertyAssertion.of(TypePool.LazyTypeDescription.AnnotationValue.ForEnumeration.class).apply();
        ObjectPropertyAssertion.of(TypePool.LazyTypeDescription.AnnotationValue.ForComplexArray.class).apply();
        ObjectPropertyAssertion.of(TypePool.LazyTypeDescription.AnnotationValue.ForType.class)
                .refine(new ObjectPropertyAssertion.Refinement<Type>() {
                    @Override
                    public void apply(Type mock) {
                        when(mock.getClassName()).thenReturn("" + System.identityHashCode(mock));
                    }
                }).apply();
        ObjectPropertyAssertion.of(TypePool.LazyTypeDescription.AnnotationValue.Loaded.State.class).apply();
    }

    @Test
    public void testInvocationHandlerObjectProperties() throws Exception {
        ObjectPropertyAssertion.of(TypePool.LazyTypeDescription.AnnotationInvocationHandler.class).create(new ObjectPropertyAssertion.Creator<Class<?>>() {
            @Override
            public Class<?> create() {
                return Object.class;
            }
        }).applyMutable();
    }

    @Test
    public void testDeclarationContextObjectProperties() throws Exception {
        ObjectPropertyAssertion.of(TypePool.LazyTypeDescription.DeclarationContext.DeclaredInType.class).apply();
        ObjectPropertyAssertion.of(TypePool.LazyTypeDescription.DeclarationContext.DeclaredInMethod.class).apply();
        ObjectPropertyAssertion.of(TypePool.LazyTypeDescription.DeclarationContext.SelfDeclared.class).apply();
    }
}


text:
package org.apache.rave.portal.model.conversion;

import org.apache.rave.model.ModelConverter;
import org.apache.rave.model.ActivityStreamsMediaLink;
import org.apache.rave.portal.model.JpaActivityStreamsMediaLink;
import org.springframework.stereotype.Component;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import java.util.UUID;

import static org.apache.rave.persistence.jpa.util.JpaUtil.getSingleResult;

@Component
public class JpaActivityStreamsMediaLinkConverter implements ModelConverter<ActivityStreamsMediaLink, JpaActivityStreamsMediaLink> {
    @PersistenceContext
    private EntityManager manager;

    @Override
    public JpaActivityStreamsMediaLink convert(ActivityStreamsMediaLink source) {
        if(source != null && source.getId() == null) {
            source.setId(source.getUrl() == null ? UUID.randomUUID().toString() : source.getUrl());
        }
        return source instanceof JpaActivityStreamsMediaLink ? (JpaActivityStreamsMediaLink) source : createEntity(source);
    }

    @Override
    public Class<ActivityStreamsMediaLink> getSourceType() {
        return ActivityStreamsMediaLink.class;
    }

    private JpaActivityStreamsMediaLink createEntity(ActivityStreamsMediaLink source) {
        JpaActivityStreamsMediaLink converted = null;
        if (source != null) {
            TypedQuery<JpaActivityStreamsMediaLink> query = manager.createNamedQuery(JpaActivityStreamsMediaLink.FIND_BY_ID, JpaActivityStreamsMediaLink.class);
            query.setParameter("id", source.getId());
            converted = getSingleResult(query.getResultList());

            if (converted == null) {
                converted = new JpaActivityStreamsMediaLink();
            }
            updateProperties(source, converted);
        }
        return converted;
    }

    private void updateProperties(ActivityStreamsMediaLink source, JpaActivityStreamsMediaLink converted) {
        converted.setDuration(source.getDuration());
        converted.setHeight(source.getHeight());
        converted.setWidth(source.getWidth());
        converted.setUrl(source.getUrl());
    }
}


text:
2021-07-12: Development Meeting
===============================

Kacper, Mike L, Craig, Mike H

Agenda
------

* Updates
* DERIVA integration/BDBag import [name=Craig]
    * MH: Goal is to implement what's in the proposal
        * Register data from DERIVA
        * Publish/export to DERIVA
        * Bag is the most reasonable, also useful for others
* Recorded run alternatives [name=Craig]

Updates
-------

* Kacper
    * Fixed minor inconsistency in RunStatus (wt_versioning#31)
    * Reviews

* Mike L
    * Migration to angular9 (and upcoming migration to ang12)
    * PR to fix the post-migration blank page error
        * Default LogLevel is now `Error` (need to revisit the numerical order once things are stable)
        * Circular dependency after refactoring
            * only seems to happen with `--prod`
        * Change `env.js` to `env.json`, read via HTTP(S) instead of `<script>` tags

* Craig
    * Recorded run draft
    * PR reviews
    * Upcoming
        * C2Metadata wrap up...
        * Webpage updates
        * MATLAB support announcement

* Mike H