text:
package com.amazonaws.services.ec2.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *

 * Describes a network interface attachment.
 *

 *
 * @see AWS API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class InstanceNetworkInterfaceAttachment implements Serializable, Cloneable {

    /**
     *

     * The time stamp when the attachment initiated.
     *

     */
    private java.util.Date attachTime;
    /**
     *

     * The ID of the network interface attachment.
     *

     */
    private String attachmentId;
    /**
     *

     * Indicates whether the network interface is deleted when the instance is terminated.
     *

     */
    private Boolean deleteOnTermination;
    /**
     *

     * The index of the device on the instance for the network interface attachment.
     *

     */
    private Integer deviceIndex;
    /**
     *

     * The attachment state.
     *

     */
    private String status;

    /**
     *

     * The time stamp when the attachment initiated.
     *

     *
     * @param attachTime
     *        The time stamp when the attachment initiated.
     */

    public void setAttachTime(java.util.Date attachTime) {
        this.attachTime = attachTime;
    }

    /**
     *

     * The time stamp when the attachment initiated.
     *

     *
     * @return The time stamp when the attachment initiated.
     */

    public java.util.Date getAttachTime() {
        return this.attachTime;
    }

    /**
     *

     * The time stamp when the attachment initiated.
     *

     *
     * @param attachTime
     *        The time stamp when the attachment initiated.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public InstanceNetworkInterfaceAttachment withAttachTime(java.util.Date attachTime) {
        setAttachTime(attachTime);
        return this;
    }

    /**
     *

     * The ID of the network interface attachment.
     *

     *
     * @param attachmentId
     *        The ID of the network interface attachment.
     */

    public void setAttachmentId(String attachmentId) {
        this.attachmentId = attachmentId;
    }

    /**
     *

     * The ID of the network interface attachment.
     *

     *
     * @return The ID of the network interface attachment.
     */

    public String getAttachmentId() {
        return this.attachmentId;
    }

    /**
     *

     * The ID of the network interface attachment.
     *

     *
     * @param attachmentId
     *        The ID of the network interface attachment.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public InstanceNetworkInterfaceAttachment withAttachmentId(String attachmentId) {
        setAttachmentId(attachmentId);
        return this;
    }

    /**
     *

     * Indicates whether the network interface is deleted when the instance is terminated.
     *

     *
     * @param deleteOnTermination
     *        Indicates whether the network interface is deleted when the instance is terminated.
     */

    public void setDeleteOnTermination(Boolean deleteOnTermination) {
        this.deleteOnTermination = deleteOnTermination;
    }

    /**
     *

     * Indicates whether the network interface is deleted when the instance is terminated.
     *

     *
     * @return Indicates whether the network interface is deleted when the instance is terminated.
     */

    public Boolean getDeleteOnTermination() {
        return this.deleteOnTermination;
    }

    /**
     *

     * Indicates whether the network interface is deleted when the instance is terminated.
     *

     *
     * @param deleteOnTermination
     *        Indicates whether the network interface is deleted when the instance is terminated.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public InstanceNetworkInterfaceAttachment withDeleteOnTermination(Boolean deleteOnTermination) {
        setDeleteOnTermination(deleteOnTermination);
        return this;
    }

    /**
     *

     * Indicates whether the network interface is deleted when the instance is terminated.
     *

     *
     * @return Indicates whether the network interface is deleted when the instance is terminated.
     */

    public Boolean isDeleteOnTermination() {
        return this.deleteOnTermination;
    }

    /**
     *

     * The index of the device on the instance for the network interface attachment.
     *

     *
     * @param deviceIndex
     *        The index of the device on the instance for the network interface attachment.
     */

    public void setDeviceIndex(Integer deviceIndex) {
        this.deviceIndex = deviceIndex;
    }

    /**
     *

     * The index of the device on the instance for the network interface attachment.
     *

     *
     * @return The index of the device on the instance for the network interface attachment.
     */

    public Integer getDeviceIndex() {
        return this.deviceIndex;
    }

    /**
     *

     * The index of the device on the instance for the network interface attachment.
     *

     *
     * @param deviceIndex
     *        The index of the device on the instance for the network interface attachment.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public InstanceNetworkInterfaceAttachment withDeviceIndex(Integer deviceIndex) {
        setDeviceIndex(deviceIndex);
        return this;
    }

    /**
     *

     * The attachment state.
     *

     *
     * @param status
     *        The attachment state.
     * @see AttachmentStatus
     */

    public void setStatus(String status) {
        this.status = status;
    }

    /**
     *

     * The attachment state.
     *

     *
     * @return The attachment state.
     * @see AttachmentStatus
     */

    public String getStatus() {
        return this.status;
    }

    /**
     *

     * The attachment state.
     *

     *
     * @param status
     *        The attachment state.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see AttachmentStatus
     */

    public InstanceNetworkInterfaceAttachment withStatus(String status) {
        setStatus(status);
        return this;
    }

    /**
     *

     * The attachment state.
     *

     *
     * @param status
     *        The attachment state.
     * @see AttachmentStatus
     */

    public void setStatus(AttachmentStatus status) {
        withStatus(status);
    }

    /**
     *

     * The attachment state.
     *

     *
     * @param status
     *        The attachment state.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see AttachmentStatus
     */

    public InstanceNetworkInterfaceAttachment withStatus(AttachmentStatus status) {
        this.status = status.toString();
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getAttachTime() != null)
            sb.append("AttachTime: ").append(getAttachTime()).append(",");
        if (getAttachmentId() != null)
            sb.append("AttachmentId: ").append(getAttachmentId()).append(",");
        if (getDeleteOnTermination() != null)
            sb.append("DeleteOnTermination: ").append(getDeleteOnTermination()).append(",");
        if (getDeviceIndex() != null)
            sb.append("DeviceIndex: ").append(getDeviceIndex()).append(",");
        if (getStatus() != null)
            sb.append("Status: ").append(getStatus());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof InstanceNetworkInterfaceAttachment == false)
            return false;
        InstanceNetworkInterfaceAttachment other = (InstanceNetworkInterfaceAttachment) obj;
        if (other.getAttachTime() == null ^ this.getAttachTime() == null)
            return false;
        if (other.getAttachTime() != null && other.getAttachTime().equals(this.getAttachTime()) == false)
            return false;
        if (other.getAttachmentId() == null ^ this.getAttachmentId() == null)
            return false;
        if (other.getAttachmentId() != null && other.getAttachmentId().equals(this.getAttachmentId()) == false)
            return false;
        if (other.getDeleteOnTermination() == null ^ this.getDeleteOnTermination() == null)
            return false;
        if (other.getDeleteOnTermination() != null && other.getDeleteOnTermination().equals(this.getDeleteOnTermination()) == false)
            return false;
        if (other.getDeviceIndex() == null ^ this.getDeviceIndex() == null)
            return false;
        if (other.getDeviceIndex() != null && other.getDeviceIndex().equals(this.getDeviceIndex()) == false)
            return false;
        if (other.getStatus() == null ^ this.getStatus() == null)
            return false;
        if (other.getStatus() != null && other.getStatus().equals(this.getStatus()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getAttachTime() == null) ? 0 : getAttachTime().hashCode());
        hashCode = prime * hashCode + ((getAttachmentId() == null) ? 0 : getAttachmentId().hashCode());
        hashCode = prime * hashCode + ((getDeleteOnTermination() == null) ? 0 : getDeleteOnTermination().hashCode());
        hashCode = prime * hashCode + ((getDeviceIndex() == null) ? 0 : getDeviceIndex().hashCode());
        hashCode = prime * hashCode + ((getStatus() == null) ? 0 : getStatus().hashCode());
        return hashCode;
    }

    @Override
    public InstanceNetworkInterfaceAttachment clone() {
        try {
            return (InstanceNetworkInterfaceAttachment) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
<?php

namespace Backend\Modules\FormBuilderMailer\Engine;

use Backend\Core\Engine\Model as BackendModel;
use Backend\Core\Engine\Language as BL;
use Backend\Modules\FormBuilder\Engine\Model as BackendFormBuilderModel;
use Common\Mailer;
use SpoonDatabase;

/**
 * In this file we store all generic functions that we will be using in the Form Builder Mailer module
 *
 * @author webleads <fork@webleads.nl>
 */
class Model
{
    const MODULE_NAME = 'FormBuilderMailer';

    /**
     * @param $params
     */
    public static function afterFormSubmission($params)
    {
        $formId = isset($params['form_id']) ? $params['form_id'] : null;
        if ($formId) {
            $dataId = isset($params['data_id']) ? $params['data_id'] : null;
            if ($dataId) {
                $visitorId = isset($params['visitorId']) ? $params['visitorId'] : null;
                if ($visitorId) {
                    $postedFields = isset($params['fields']) ? $params['fields'] : null;
                    if ($postedFields) {
                        $form = BackendFormBuilderModel::get($formId);
                        if (!empty($form)) {
                            if (isset($form['method']) && $form['method'] == 'database_email') {
                                foreach ($postedFields as $field) {
                                    $value = isset($field['value']) ? unserialize($field['value']) : null;
                                    if ($value) {
                                        if (filter_var($value, FILTER_VALIDATE_EMAIL)) {
                                            self::mailEndUser($value, $postedFields, $form, $dataId);
                                            return;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * @param $email
     * @param $postedFields
     * @param $form
     * @param $dataId
     */
    public static function mailEndUser($email, $postedFields, $form, $dataId)
    {
        $field_info = '';
        foreach ($postedFields as $field) {
            $label = isset($field['label']) ? $field['label'] : '';
            $value = isset($field['value']) ? unserialize($field['value']) : '';
            $field_info .= $label . ': ' . $value . "\n";
        }

        $title = sprintf(BL::getLabel('Subject', self::MODULE_NAME), $form['name']);
        $data = array(
            'title' => $title,
            'fields' => $field_info,
        );

        $translations = array(
            'ReceivedData',
            'Greetings',
        );
        foreach ($translations as $translation) {
            $data[$translation] = BL::getLabel($translation, self::MODULE_NAME);
        }

        /** @var $mailer Mailer */
        $mailer = BackendModel::get('mailer');
        if ($mailer) {
            // @TODO remove this when https://github.com/forkcms/forkcms/issues/716 is fixed.
            define('FRONTEND_LANGUAGE', SITE_DEFAULT_LANGUAGE); // work around

            $result = $mailer->addEmail(
                $title,
                BACKEND_MODULES_PATH . '/'.self::MODULE_NAME.'/Layout/Templates/Mails/Notification.tpl',
                $data,
                $email
            );
        }
        $useLog = BackendModel::getModuleSetting(self::MODULE_NAME, 'log', true);
        if ($useLog) {
            $logger = BackendModel::get('logger');
            if ($logger) {
                $logger->notice(sprintf('Sending email to %s, status %s', $email, ($result ? 'OK' : 'FAILED')), $data);
            }
        }
        $addExtraData = BackendModel::getModuleSetting(self::MODULE_NAME, 'add_data', true);
        $error = BL::getLabel('Error', self::MODULE_NAME);
        $success = BL::getLabel('OK', self::MODULE_NAME);
        if ($addExtraData) {
            $label = BL::getLabel('DataLabel', self::MODULE_NAME);
            $item = array(
                'data_id' => $dataId,
                'label' => $label,
                'value' => serialize($email . ' - ' . ($result ? $success : $error)),
            );
            /** @var $db SpoonDatabase */
            $db = BackendModel::getContainer()->get('database');
            $db->insert('forms_data_fields', $item);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division

from apps.home.training.types import (FlatPageTrainingStep,
                                      ViewTrainingStep, TrainingGateway,
                                      Quiz, Question, SingleAnswer,
                                      MultipleAnswer)
from apps.home.training import routes as r

# This package attempts to keep all the particulars of training encapsulated,
# such that you can modify how things are wired together in this file without
# digging into the implementation. There are some key exceptions to this:
# * apps.home.urls - imports from this file, gets url params
# * apps.core.models
#   - the user class does a delayed import for a convenience method
#   - the user class has carefully named booleans corresponding
#     to training steps. modify with care.

getting_started = FlatPageTrainingStep('getting_started',
                                       'Getting Started', '20 minutes')
the_mapping_method = FlatPageTrainingStep('the_mapping_method',
                                          'The Mapping Method', '20 minutes')
tree_data = FlatPageTrainingStep('tree_data',
                                 'Tree Data', '20 minutes')
tree_surroundings = FlatPageTrainingStep('tree_surroundings',
                                         'Tree Surroundings', '40 minutes')

intro_quiz = ViewTrainingStep(r.intro_quiz,
                              'intro_quiz',
                              'Intro Quiz', '30 minutes')

groups_to_follow = ViewTrainingStep(r.groups_to_follow,
                                    'groups_to_follow',
                                    'Groups To Follow', '5 minutes')

training_summary = TrainingGateway('training_summary',
                                   r.training_list_page,
                                   [getting_started,
                                    the_mapping_method,
                                    tree_data,
                                    tree_surroundings,
                                    intro_quiz,
                                    groups_to_follow])

# The keys represent the quiz_slug part of urls.
quizzes = {
    'intro_quiz': Quiz(
        title='Introduction Quiz',
        passing_score=2,
        questions=(
            Question(
                text='Lorem ipsum dolor sit amet, consectetur '
                     'adipiscing elit?',
                answer=MultipleAnswer(0, 2),
                choices=('Answer A', 'Answer B', 'Answer C')),
            Question(
                text='Lorem ipsum dolor sit amet, consectetur '
                     'adipiscing elit?',
                answer=SingleAnswer(1),
                choices=('Answer A', 'Answer B', 'Answer C')),
            Question(
                text='Lorem ipsum dolor sit amet, consectetur '
                     'adipiscing elit?',
                answer=SingleAnswer(2),
                choices=('Answer A', 'Answer B', 'Answer C')),
        )
    )
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.shaman.sve;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JPanel;
import javax.swing.SpinnerNumberModel;
import javax.swing.Timer;
import javax.swing.undo.UndoableEditSupport;
import org.shaman.sve.model.Project;
import org.shaman.sve.player.Player;

/**
 *
 * @author Sebastian
 */
public class MainPanel extends javax.swing.JPanel implements PropertyChangeListener {
	private static final Logger LOG = Logger.getLogger(MainPanel.class.getName());

	private Project project;
	private Player player;
	private UndoableEditSupport undoSupport;
	private Selections selections;
	private Timer timer;

	private FrameTime currentTime;

	/**
	 * Creates new form MainPanel
	 */
	public MainPanel() {
		initComponents();
		timer = new Timer(1000 / 25, new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				contentPanel.repaint();
			}
		});
		timer.setRepeats(true);
		timer.start();
	}

	public void setProject(Project project) {
		this.project = project;
		project.addPropertyChangeListener(this);
		currentTime = new FrameTime(project.getFramerate());
		timer.setDelay(1000 / project.getFramerate());
	}

	public void setUndoSupport(UndoableEditSupport undoSupport) {
		this.undoSupport = undoSupport;
	}

	public void setSelections(Selections selections) {
		this.selections = selections;
	}

	public void setPlayer(Player player) {
		this.player = player;
		player.addPropertyChangeListener(this);
		setTotalTime(project.getLength());
		setCurrentTime(project.getTime());
	}

	private void setPlaying(boolean playing) {
		playButton.setEnabled(!playing);
		timeSpinner.setEnabled(!playing);
		timeSlider.setEnabled(!playing);
		aSpinner.setEnabled(!playing);
		gotoAButton.setEnabled(!playing);
//		setAButton.setEnabled(!playing);
		bSpinner.setEnabled(!playing);
		gotoBButton.setEnabled(!playing);
//		setBButton.setEnabled(!playing);
	}

	/**
	 * Sets the total time in the UI
	 */
	private void setTotalTime(FrameTime msec) {
		LOG.log(Level.INFO, "set total time to {0} ms", msec);
		//check current time
		boolean fireTimeChange = false;
		if (currentTime.compareTo(msec) > 0) {
			currentTime.fromMillis(0);
			fireTimeChange = true;
		}

		timeLabel.setText("/ "+msec+" s");
		timeSpinner.setModel(currentTime.getSpinnerModel(new FrameTime(project.getFramerate()).fromMillis(0), msec));
		aSpinner.setModel(project.getMarkerA().getSpinnerModel(new FrameTime(project.getFramerate()).fromMillis(0), msec));
		bSpinner.setModel(project.getMarkerB().getSpinnerModel(new FrameTime(project.getFramerate()).fromMillis(0), msec));
		timeSlider.setMinimum(0);
		timeSlider.setMaximum(msec.toMillis());
		timeSlider.setValue(currentTime.toMillis());

		if (fireTimeChange) {
			changeCurrentTime(currentTime);
		}
	}

	/**
	 * Sets the current time in the UI
	 */
	private void setCurrentTime(FrameTime msec) {
		if (msec == currentTime) return;
		currentTime = msec;
		timeSpinner.setValue(msec);
		timeSlider.setValue(msec.toMillis());
//		LOG.log(Level.INFO, "set current time to {0} ms", msec);
	}

	/**
	 * Sends the current time to the player
	 * @param time
	 */
	private void changeCurrentTime(FrameTime time) {
		project.setTime(time);
		if (player != null) {
			player.setTime(time);
		}
		LOG.log(Level.INFO, "change current time to {0} ms", time);
	}

	private void paintContent(Graphics2D g) {
		if (player == null || project == null) {
			return;
		}
		if (player.isRecording()) {
			return;
		}
		//transform graphics to view the whole screen
		int sw = contentPanel.getWidth();
		int sh = contentPanel.getHeight();
		int pw = project.getWidth();
		int ph = project.getHeight();
		float scale = Math.min(sw / (float) pw, sh / (float) ph);
		pw *= scale;
		ph *= scale;
		int ox = (sw - pw) / 2;
		int oy = (sh - ph) / 2;
		AffineTransform at = g.getTransform();
		g.translate(ox, oy);
		g.scale(scale, scale);

		//send to player
		player.draw(g);

		//reset transform
		g.setTransform(at);
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        contentPanel = new ContentPanel();
        playButton = new javax.swing.JButton();
        stopButton = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        timeSpinner = new javax.swing.JSpinner();
        timeLabel = new javax.swing.JLabel();
        timeSlider = new javax.swing.JSlider();
        jLabel2 = new javax.swing.JLabel();
        aSpinner = new javax.swing.JSpinner();
        setAButton = new javax.swing.JButton();
        gotoAButton = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        bSpinner = new javax.swing.JSpinner();
        setBButton = new javax.swing.JButton();
        gotoBButton = new javax.swing.JButton();

        setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        setMinimumSize(new java.awt.Dimension(400, 300));

        javax.swing.GroupLayout contentPanelLayout = new javax.swing.GroupLayout(contentPanel);
        contentPanel.setLayout(contentPanelLayout);
        contentPanelLayout.setHorizontalGroup(
            contentPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        contentPanelLayout.setVerticalGroup(
            contentPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 336, Short.MAX_VALUE)
        );

        playButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/shaman/sve/icons/play16.png"))); // NOI18N
        playButton.setToolTipText("Play");
        playButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                playEvent(evt);
            }
        });

        stopButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/shaman/sve/icons/stop16.png"))); // NOI18N
        stopButton.setToolTipText("Stop");
        stopButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                stopEvent(evt);
            }
        });

        jLabel1.setText(" time:");

        timeSpinner.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(0), Integer.valueOf(0), null, Integer.valueOf(10)));
        timeSpinner.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                timeSpinnerChanged(evt);
            }
        });

        timeLabel.setText("/ 0 s");

        timeSlider.setMajorTickSpacing(1000);
        timeSlider.setMinorTickSpacing(10);
        timeSlider.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                timeSliderChanged(evt);
            }
        });

        jLabel2.setText("A:");

        aSpinner.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(0), Integer.valueOf(0), null, Integer.valueOf(10)));
        aSpinner.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                aSpinnerChanged(evt);
            }
        });

        setAButton.setText("Set");
        setAButton.setToolTipText("Sets the first marker");
        setAButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                setAEvent(evt);
            }
        });

        gotoAButton.setText("GoTo");
        gotoAButton.setToolTipText("go to marker A");
        gotoAButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                gotoAEvent(evt);
            }
        });

        jLabel3.setText("B:");

        bSpinner.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(0), Integer.valueOf(0), null, Integer.valueOf(10)));
        bSpinner.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                bSpinnerChanged(evt);
            }
        });

        setBButton.setText("Set");
        setBButton.setToolTipText("Sets the first marker");
        setBButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                setBButtonsetAEvent(evt);
            }
        });

        gotoBButton.setText("GoTo");
        gotoBButton.setToolTipText("go to marker A");
        gotoBButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                gotoBButtongotoAEvent(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(contentPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(aSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(setAButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(gotoAButton)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(bSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(setBButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(gotoBButton)
                        .addGap(0, 91, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(playButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(stopButton)
                        .addGap(2, 2, 2)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(timeSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(timeLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(timeSlider, javax.swing.GroupLayout.DEFAULT_SIZE, 228, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(contentPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(playButton)
                    .addComponent(stopButton)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(timeSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(timeLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(timeSlider, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(aSpinner)
                    .addComponent(setAButton)
                    .addComponent(gotoAButton)
                    .addComponent(jLabel3)
                    .addComponent(bSpinner)
                    .addComponent(setBButton)
                    .addComponent(gotoBButton)))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void playEvent(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_playEvent
		player.setTime(project.getTime());
		player.start(false);
    }//GEN-LAST:event_playEvent

    private void stopEvent(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stopEvent
        if (player.isPlaying()) {
			player.stop();
		} else if (currentTime.toMillis() != 0) {
			FrameTime ft = new FrameTime(project.getFramerate());
			setCurrentTime(ft);
			changeCurrentTime(ft);
		}
    }//GEN-LAST:event_stopEvent

    private void timeSpinnerChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_timeSpinnerChanged
        FrameTime ft = (FrameTime) timeSpinner.getValue();
		if (ft.equals(currentTime)) {
			return;
		}
		currentTime = ft;
		timeSlider.setValue(ft.toMillis());
		changeCurrentTime(ft);
    }//GEN-LAST:event_timeSpinnerChanged

    private void timeSliderChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_timeSliderChanged
        int msec = timeSlider.getValue();
		FrameTime ft = new FrameTime(project.getFramerate()).fromMillis(msec);
		if (ft.equals(currentTime)) return;
		currentTime = ft;
		timeSpinner.setValue(ft);
		changeCurrentTime(ft);
    }//GEN-LAST:event_timeSliderChanged

    private void aSpinnerChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_aSpinnerChanged
        FrameTime ft = (FrameTime) aSpinner.getValue();
		if (ft.equals(project.getMarkerA())) {
			return;
		}
		project.setMarkerA(ft);
    }//GEN-LAST:event_aSpinnerChanged

    private void setAEvent(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_setAEvent
        project.setMarkerA(project.getTime().clone());
    }//GEN-LAST:event_setAEvent

    private void gotoAEvent(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_gotoAEvent
        changeCurrentTime(project.getMarkerA().clone());
    }//GEN-LAST:event_gotoAEvent

    private void bSpinnerChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_bSpinnerChanged
        FrameTime ft = (FrameTime) bSpinner.getValue();
		if (ft.equals(project.getMarkerB())) {
			return;
		}
		project.setMarkerB(ft);
    }//GEN-LAST:event_bSpinnerChanged

    private void setBButtonsetAEvent(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_setBButtonsetAEvent
        project.setMarkerB(project.getTime().clone());
    }//GEN-LAST:event_setBButtonsetAEvent

    private void gotoBButtongotoAEvent(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_gotoBButtongotoAEvent
        changeCurrentTime(project.getMarkerB().clone());
    }//GEN-LAST:event_gotoBButtongotoAEvent

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JSpinner aSpinner;
    private javax.swing.JSpinner bSpinner;
    private javax.swing.JPanel contentPanel;
    private javax.swing.JButton gotoAButton;
    private javax.swing.JButton gotoBButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JButton playButton;
    private javax.swing.JButton setAButton;
    private javax.swing.JButton setBButton;
    private javax.swing.JButton stopButton;
    private javax.swing.JLabel timeLabel;
    private javax.swing.JSlider timeSlider;
    private javax.swing.JSpinner timeSpinner;
    // End of variables declaration//GEN-END:variables

	@Override
	public void propertyChange(PropertyChangeEvent evt) {
		if (evt.getSource() == project) {
			if (player.isRecording()) {
				return;
			}
			switch (evt.getPropertyName()) {
				case Project.PROP_LENGTH:
					setTotalTime(project.getLength());
					break;
				case Project.PROP_TIME:
					setCurrentTime(project.getTime());
					break;
				case Project.PROP_MARKER_A:
					aSpinner.setValue(project.getMarkerA().clone());
					break;
				case Project.PROP_MARKER_B:
					bSpinner.setValue(project.getMarkerB().clone());
			}
		} else if (evt.getSource() == player) {
			switch (evt.getPropertyName()) {
				case Player.PROP_PLAYING:
					setPlaying((boolean) evt.getNewValue());
					break;
			}
		}
	}

	private class ContentPanel extends JPanel {

		@Override
		public void paint(Graphics g) {
			paintComponent(g);
			paintBorder(g);
			paintContent((Graphics2D) g);
		}

	}
}


text:
using Foundation;
using System;
using System.Collections.Generic;
using UIKit;

namespace UICatalog
{
    public partial class PickerViewController : UIViewController, IUIPickerViewDataSource, IUIPickerViewDelegate
    {
        public PickerViewController (IntPtr handle) : base (handle) { }

        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // Show that a given row is selected. This is off by default.
            pickerView.ShowSelectionIndicator = true;
            ConfigurePickerView();
        }

        private void ConfigurePickerView()
        {
            // Set the default selected rows (the desired rows to initially select will vary from app to app).
            var selectedRows = new Dictionary<ColorComponent, int>
            {
                { ColorComponent.Red, 13 },
                { ColorComponent.Green, 41 },
                { ColorComponent.Blue, 24 }
            };

            // kvp - means KeyValuePair
            foreach (var kvp in selectedRows)
            {
                var selectedRow = kvp.Value;
                var colorComponent = (int)kvp.Key;

                // Note that the delegate method on UIPickerViewDelegate is not triggered when manually
                // calling UIPickerView.selectRow(:inComponent:animated:). To do this, we fire off delegate
                // method manually.
                pickerView.Select(selectedRow, colorComponent, true);
                Selected(pickerView, selectedRow, colorComponent);
            }
        }

        #region IUIPickerViewDelegate

        [Export("pickerView:attributedTitleForRow:forComponent:")]
        public NSAttributedString GetAttributedTitle(UIPickerView pickerView, nint row, nint component)
        {
            var colorValue = row * RGB.Offset;

            var value = colorValue / RGB.Max;
            var redColorComponent = RGB.Min;
            var greenColorComponent = RGB.Min;
            var blueColorComponent = RGB.Min;

            switch ((ColorComponent)(int)component)
            {
                case ColorComponent.Red:
                    redColorComponent = value;
                    break;

                case ColorComponent.Green:
                    greenColorComponent = value;
                    break;

                case ColorComponent.Blue:
                    blueColorComponent = value;
                    break;

                default:
                    throw new InvalidOperationException("Invalid row/component combination for picker view.");
            }

            // Set the foreground color for the entire attributed string.
            var foregroundColor = new UIColor(redColorComponent, greenColorComponent, blueColorComponent, 1f);
            var attributes = new UIStringAttributes { ForegroundColor = foregroundColor};
            return new NSAttributedString($"{colorValue}", attributes);
        }

        [Export("pickerView:didSelectRow:inComponent:")]
        public void Selected(UIPickerView pickerView, nint row, nint component)
        {
            var colorComponentValue = RGB.Offset * row / RGB.Max;
            var color = colorView.BackgroundColor;
            color.GetRGBA(out nfloat red, out nfloat green, out nfloat blue, out nfloat alpha);

            switch ((ColorComponent)(int)component)
            {
                case ColorComponent.Red:
                    color = new UIColor(colorComponentValue, green, blue, alpha);
                    break;

                case ColorComponent.Green:
                    color = new UIColor(red, colorComponentValue, blue, alpha);
                    break;

                case ColorComponent.Blue:
                    color = new UIColor(red, green, colorComponentValue, alpha);
                    break;
            }

            colorView.BackgroundColor = color;
        }

        #endregion

        #region IUIPickerViewDataSource

        public nint GetComponentCount(UIPickerView pickerView)
        {
            return Enum.GetValues(typeof(ColorComponent)).Length;
        }

        public nint GetRowsInComponent(UIPickerView pickerView, nint component)
        {
            return (int)RGB.Max / (int)RGB.Offset + 1;
        }

        #endregion

        /* helpers */

        enum ColorComponent
        {
            Red,
            Green,
            Blue
        }

        struct RGB
        {
            public const float Max = 255f;
            public const float Min = 0f;
            public const float Offset = 5f;
        }
    }
}


text:
(function () {
    'use strict';
    angular.module('d3', []).factory('d3Service', d3Service);
    d3Service.$inject = ['$document', '$q', '$rootScope'];
    function d3Service($document, $q, $rootScope) {
        var d = $q.defer();
        function onScriptLoad() {
            // Load client in the browser
            $rootScope.$apply(function () {
                d.resolve(window.d3);
            });
        }
        // Create a script tag with d3 as the source
        // and call our onScriptLoad callback when it
        // has been loaded
        var scriptTag = $document[0].createElement('script');
        scriptTag.type = 'text/javascript';
        scriptTag.async = true;
        scriptTag.src = 'http://d3js.org/d3.v3.min.js';
        scriptTag.onreadystatechange = function () {
            if (this.readyState == 'complete')
                onScriptLoad();
        };
        scriptTag.onload = onScriptLoad;
        var s = $document[0].getElementsByTagName('body')[0];
        s.appendChild(scriptTag);
        return {
            d3: function () {
                return d.promise;
            }
        };
    }
})();
//# sourceMappingURL=d3.factory.js.map


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta name="copyright" content="(C) Copyright 2005" />
<meta name="DC.rights.owner" content="(C) Copyright 2005" />
<meta content="public" name="security" />
<meta content="index,follow" name="Robots" />
<meta http-equiv="PICS-Label" content='(PICS-1.1 "http://www.icra.org/ratingsv02.html" l gen true r (cz 1 lz 1 nz 1 oz 1 vz 1) "http://www.rsac.org/ratingsv01.html" l gen true r (n 0 s 0 v 0 l 0) "http://www.classify.org/safesurf/" l gen true r (SS~~000 1))' />
<meta content="reference" name="DC.Type" />
<meta name="DC.Title" content="VALUES Expressão" />
<meta content="VALUES expressão" name="DC.subject" />
<meta content="VALUES expressão" name="keywords" />
<meta scheme="URI" name="DC.Relation" content="crefsqlj39374.html" />
<meta scheme="URI" name="DC.Relation" content="crefsqlj22771.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj81859.html" />
<meta scheme="URI" name="DC.Relation" content="crefsqlj95081.html" />
<meta scheme="URI" name="DC.Relation" content="crefsqlj80721.html" />
<meta scheme="URI" name="DC.Relation" content="crefsqljrenamestatements.html" />
<meta scheme="URI" name="DC.Relation" content="crefsqlj35312.html" />
<meta scheme="URI" name="DC.Relation" content="rrefcallprocedure.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj13590.html" />
<meta scheme="URI" name="DC.Relation" content="rrefdeclaretemptable.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj35981.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj31783.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj21583.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj32654.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj14854.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj35034.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj40774.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj29840.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj18922.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj40506.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj13658.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj21571.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj57522.html" />
<meta scheme="URI" name="DC.Relation" content="rrefscalarsubquery.html" />
<meta scheme="URI" name="DC.Relation" content="rrefselectexpression.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj41360.html" />
<meta scheme="URI" name="DC.Relation" content="rreftableexpression.html" />
<meta scheme="URI" name="DC.Relation" content="rreftablesubquery.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj26498.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj33602.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj15309.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj87167.html" />
<meta content="XHTML" name="DC.Format" />
<meta content="rrefsqlj11277" name="DC.Identifier" />
<meta content="pt-br" name="DC.Language" />
<link href="commonltr.css" type="text/css" rel="stylesheet" />
<title>VALUES Expressão</title>

VALUES Expressão

"VALUES Expressão" permite construir uma linha ou uma tabela a partir de
valores.
A instrução VALUES é utilizada quando não existe uma cláusula FROM.
Esta construção pode ser utilizada em todos os locais onde uma consulta pode
ser utilizada e, portanto, pode ser utilizada como uma instrução que retorna
um ResultSet, dentro de expressões e instruções sempre que uma
subconsulta for permitida, e como fonte de valores para a instrução INSERT.

Sintaxe

{
    VALUES ( Valor {, Valor }* )
        [ , ( Valor {, Valor }* ) ]* |
    VALUES Valor [ , Valor ]* |
 }

A primeira forma constrói linhas com várias colunas.
A segunda forma constrói linhas com uma única coluna, com cada expressão sendo
o valor da coluna da linha.

A palavra chave DEFAULT é permitida somente quando a expressão VALUES está
em uma instrução INSERT.
A especificação de DEFAULT para a coluna insere o valor padrão da coluna na
coluna.
Outra forma de inserir o valor padrão na coluna é omitir a coluna na lista
de colunas, e somente inserir valores nas outras colunas da tabela.

-- 3 linhas de 1 coluna
VALUES (1),(2),(3);

-- 3 linhas de 1 coluna
VALUES 1, 2, 3;

-- 1 linha de 3 colunas
VALUES (1, 2, 3);

-- 3 linhas de 2 colunas
VALUES (1,21),(2,22),(3,23);

-- construção de uma tabela derivada
VALUES ('laranja', 'laranja'), ('maçã', 'vermelha'),
('banana', 'amarela')

-- Inserir dois novos departamentos na tabela DEPARTAMENTOS
-- utilizando uma instrução, mas não atribuir gerente
-- aos novos departamentos.
INSERT INTO DEPARTAMENTOS (NUM_DEP, NOME_DEP, ADMRDEPT)
  VALUES ('B11', 'COMPRAS', 'B01'),
    ('E41', 'ADMINISTRAÇÃO DE BANCO DE DADOS', 'E01')

-- inserir uma linha com valor DEFAULT para a coluna PROJ_PRINC
INSERT INTO PROJETO (NUM_PROJ, NOME_PROJ, NUM_DEP, EMP_RESP,
    PROJ_DATA_INÍCIO, PROJ_PRINC)
VALUES ('PL2101', 'ENSURE COMPAT PLAN', 'B01', '000020',
    CURRENT_DATE, DEFAULT);

-- utilização de função nativa
VALUES CURRENT_DATE

-- obter o valor a partir de uma expressão arbitrária
VALUES (3*29, 26.0E0/3)

-- obter o valor retornado por uma função nativa
VALUES CHAR(1)

Valor

Tópico pai: Instruções

Conceitos relacionados

Interação com o sistema de dependências

Instruções CREATE

Instruções DROP

Instruções RENAME

Instruções SET

Referências relacionadas

Instrução ALTER TABLE

CALL (PROCEDIMENTO)

Cláusula CONSTRAINT

Instrução DECLARE GLOBAL TEMPORARY TABLE

Instrução DELETE

Cláusula FOR UPDATE

Cláusula FROM

Cláusula GROUP BY

Cláusula HAVING

INNER JOIN

Instrução INSERT

Operação JOIN

LEFT OUTER JOIN

Instrução LOCK TABLE

Cláusula ORDER BY

Consulta

RIGHT OUTER JOIN

SubconsultaEscalar

ExpressãoSeleção

Instrução SELECT

ExpressãoTabela

SubconsultaTabela

Instrução UPDATE

Cláusula WHERE

Cláusula WHERE CURRENT OF


text:
def current_user
  @user ||= User.find(session[:user_id]) if session[:user_id]
end

def redirect_guests
  redirect '/' unless current_user
end


text:
id: tile
title: Tile
---

import Props from './props/tile.md'

Tiles like Cards, are a convenient way to display related content about a single
subject.

> This component was inspired from [Shoutem UI](https://github.com/shoutem/ui)
> by [Shoutem](https://github.com/shoutem). Check out
> [Shoutem](http://shoutem.github.io/) if you haven't already!

## Usage

### Featured Tile

![screen shot 2017-01-15 at 9 50 15 pm](https://cloud.githubusercontent.com/assets/6476108/21969491/beea4630-db6c-11e6-8913-7cc8813e35d6.png)

```js
import { Tile } from 'react-native-elements';

<Tile
  imageSrc={require('./img/path')}
  title="Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolores dolore exercitationem"
  featured
  caption="Some Caption Text"
/>;
```

### Featured Tile with Icon

![screen shot 2017-01-15 at 9 50 22 pm](https://cloud.githubusercontent.com/assets/6476108/21969581/6004e408-db6d-11e6-9379-556a0c5e967a.png)

```js
import { Tile } from 'react-native-elements';

<Tile
  imageSrc={require('./img/path')}
  icon={{ name: 'play-circle', type: 'font-awesome' }}
  featured
/>;
```

### Tile with Icon

![screen shot 2017-01-15 at 9 50 34 pm](https://cloud.githubusercontent.com/assets/6476108/21969683/fce073f0-db6d-11e6-8d03-6e42c15627a9.png)

```js
import { Tile } from 'react-native-elements';

<Tile
  imageSrc={require('./img/path')}
  title="Lorem ipsum dolor sit amet, consectetur"
  icon={{ name: 'play-circle', type: 'font-awesome' }} // optional
  contentContainerStyle={{ height: 70 }}
>
  <View
    style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-between' }}
  >
    <Text>Caption</Text>
    <Text>Caption</Text>
  </View>
</Tile>;
```

---

<Props />

---


text:
#include "SkXfermodeImageFilter.h"
#include "SkCanvas.h"
#include "SkDevice.h"
#include "SkColorPriv.h"
#include "SkFlattenableBuffers.h"
#include "SkXfermode.h"
#if SK_SUPPORT_GPU
#include "GrContext.h"
#include "effects/GrSimpleTextureEffect.h"
#include "SkGr.h"
#include "SkImageFilterUtils.h"
#endif

///////////////////////////////////////////////////////////////////////////////

SkXfermodeImageFilter::SkXfermodeImageFilter(SkXfermode* mode,
                                             SkImageFilter* background,
                                             SkImageFilter* foreground,
                                             const CropRect* cropRect)
  : INHERITED(background, foreground, cropRect), fMode(mode) {
    SkSafeRef(fMode);
}

SkXfermodeImageFilter::~SkXfermodeImageFilter() {
    SkSafeUnref(fMode);
}

SkXfermodeImageFilter::SkXfermodeImageFilter(SkFlattenableReadBuffer& buffer)
  : INHERITED(2, buffer) {
    fMode = buffer.readXfermode();
}

void SkXfermodeImageFilter::flatten(SkFlattenableWriteBuffer& buffer) const {
    this->INHERITED::flatten(buffer);
    buffer.writeFlattenable(fMode);
}

bool SkXfermodeImageFilter::onFilterImage(Proxy* proxy,
                                            const SkBitmap& src,
                                            const SkMatrix& ctm,
                                            SkBitmap* dst,
                                            SkIPoint* offset) {
    SkBitmap background = src, foreground = src;
    SkImageFilter* backgroundInput = getInput(0);
    SkImageFilter* foregroundInput = getInput(1);
    SkIPoint backgroundOffset = SkIPoint::Make(0, 0);
    if (backgroundInput &&
        !backgroundInput->filterImage(proxy, src, ctm, &background, &backgroundOffset)) {
        return false;
    }
    SkIPoint foregroundOffset = SkIPoint::Make(0, 0);
    if (foregroundInput &&
        !foregroundInput->filterImage(proxy, src, ctm, &foreground, &foregroundOffset)) {
        return false;
    }

    SkIRect bounds, foregroundBounds;
    background.getBounds(&bounds);
    bounds.offset(backgroundOffset);
    foreground.getBounds(&foregroundBounds);
    foregroundBounds.offset(foregroundOffset);
    bounds.join(foregroundBounds);
    if (!applyCropRect(&bounds, ctm)) {
        return false;
    }

    SkAutoTUnref<SkBaseDevice> device(proxy->createDevice(bounds.width(), bounds.height()));
    if (NULL == device.get()) {
        return false;
    }
    SkCanvas canvas(device);
    canvas.translate(SkIntToScalar(-bounds.left()), SkIntToScalar(-bounds.top()));
    SkPaint paint;
    paint.setXfermodeMode(SkXfermode::kSrc_Mode);
    canvas.drawBitmap(background, SkIntToScalar(backgroundOffset.fX),
                      SkIntToScalar(backgroundOffset.fY), &paint);
    paint.setXfermode(fMode);
    canvas.drawBitmap(foreground, SkIntToScalar(foregroundOffset.fX),
                      SkIntToScalar(foregroundOffset.fY), &paint);
    canvas.clipRect(SkRect::Make(foregroundBounds), SkRegion::kDifference_Op);
    paint.setColor(SK_ColorTRANSPARENT);
    canvas.drawPaint(paint);
    *dst = device->accessBitmap(false);
    offset->fX = bounds.left();
    offset->fY = bounds.top();
    return true;
}

#if SK_SUPPORT_GPU

bool SkXfermodeImageFilter::filterImageGPU(Proxy* proxy,
                                           const SkBitmap& src,
                                           const SkMatrix& ctm,
                                           SkBitmap* result,
                                           SkIPoint* offset) {
    SkBitmap background;
    SkIPoint backgroundOffset = SkIPoint::Make(0, 0);
    if (!SkImageFilterUtils::GetInputResultGPU(getInput(0), proxy, src, ctm, &background,
                                               &backgroundOffset)) {
        return false;
    }
    GrTexture* backgroundTex = background.getTexture();
    SkBitmap foreground;
    SkIPoint foregroundOffset = SkIPoint::Make(0, 0);
    if (!SkImageFilterUtils::GetInputResultGPU(getInput(1), proxy, src, ctm, &foreground,
                                               &foregroundOffset)) {
        return false;
    }
    GrTexture* foregroundTex = foreground.getTexture();
    GrContext* context = foregroundTex->getContext();

    GrEffectRef* xferEffect = NULL;

    GrTextureDesc desc;
    desc.fFlags = kRenderTarget_GrTextureFlagBit | kNoStencil_GrTextureFlagBit;
    desc.fWidth = src.width();
    desc.fHeight = src.height();
    desc.fConfig = kSkia8888_GrPixelConfig;

    GrAutoScratchTexture ast(context, desc);
    SkAutoTUnref<GrTexture> dst(ast.detach());

    GrContext::AutoRenderTarget art(context, dst->asRenderTarget());

    SkXfermode::Coeff sm, dm;
    if (!SkXfermode::AsNewEffectOrCoeff(fMode, &xferEffect, &sm, &dm, backgroundTex)) {
        return false;
    }

    SkMatrix foregroundMatrix = GrEffect::MakeDivByTextureWHMatrix(foregroundTex);
    foregroundMatrix.preTranslate(SkIntToScalar(backgroundOffset.fX-foregroundOffset.fX),
                                  SkIntToScalar(backgroundOffset.fY-foregroundOffset.fY));

    SkRect srcRect;
    src.getBounds(&srcRect);
    if (NULL != xferEffect) {
        GrPaint paint;
        paint.addColorTextureEffect(foregroundTex, foregroundMatrix);
        paint.addColorEffect(xferEffect)->unref();
        context->drawRect(paint, srcRect);
    } else {
        GrPaint backgroundPaint;
        SkMatrix backgroundMatrix = GrEffect::MakeDivByTextureWHMatrix(backgroundTex);
        backgroundPaint.addColorTextureEffect(backgroundTex, backgroundMatrix);
        context->drawRect(backgroundPaint, srcRect);

        GrPaint foregroundPaint;
        foregroundPaint.setBlendFunc(sk_blend_to_grblend(sm), sk_blend_to_grblend(dm));
        foregroundPaint.addColorTextureEffect(foregroundTex, foregroundMatrix);
        context->drawRect(foregroundPaint, srcRect);
    }
    offset->fX = backgroundOffset.fX;
    offset->fY = backgroundOffset.fY;
    return SkImageFilterUtils::WrapTexture(dst, src.width(), src.height(), result);
}

#endif


text:
<?php

/* core/themes/stable/templates/content-edit/filter-guidelines.html.twig */
class __TwigTemplate_bb93bc2e64228c40286b16147ffe21b30ccb295de6f3dd12cc316bfb46b193bd extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $tags = array();
        $filters = array();
        $functions = array();

        try {
            $this->env->getExtension('sandbox')->checkSecurity(
                array(),
                array(),
                array()
            );
        } catch (Twig_Sandbox_SecurityError $e) {
            $e->setTemplateFile($this->getTemplateName());

            if ($e instanceof Twig_Sandbox_SecurityNotAllowedTagError && isset($tags[$e->getTagName()])) {
                $e->setTemplateLine($tags[$e->getTagName()]);
            } elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFilterError && isset($filters[$e->getFilterName()])) {
                $e->setTemplateLine($filters[$e->getFilterName()]);
            } elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFunctionError && isset($functions[$e->getFunctionName()])) {
                $e->setTemplateLine($functions[$e->getFunctionName()]);
            }

            throw $e;
        }

        // line 20
        echo "
env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["attributes"]) ? $context["attributes"] : null), "html", null, true));
        echo ">

";
        // line 21
        echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute((isset($context["format"]) ? $context["format"] : null), "label", array()), "html", null, true));
        echo "

  ";
        // line 22
        echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["tips"]) ? $context["tips"] : null), "html", null, true));
        echo "

";
    }

    public function getTemplateName()
    {
        return "core/themes/stable/templates/content-edit/filter-guidelines.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  52 => 22,  48 => 21,  43 => 20,);
    }

    public function getSource()
    {
        return "{#
/**
 * @file
 * Theme override for guidelines for a text format.
 *
 * Available variables:
 * - format: Contains information about the current text format, including the
 *   following:
 *   - name: The name of the text format, potentially unsafe and needs to be
 *     escaped.
 *   - format: The machine name of the text format, e.g. 'basic_html'.
 * - attributes: HTML attributes for the containing element.
 * - tips: Descriptions and a CSS ID in the form of 'module-name/filter-id'
 *   (only used when 'long' is TRUE) for each filter in one or more text
 *   formats.
 *
 * @see template_preprocess_filter_tips()
 */
#}

{{ format.label }}

  {{ tips }}

";
    }
}


text:
var path = require('path');
var defaultExtname = require('default-extname');
var defExt = defaultExtname();

var utils = {
    smartyMerge: function (rootObj, newObj, isNumParse) {
        newObj = newObj || {};
        var tempObj = {};
        for (var i in rootObj) {
            tempObj[i] = rootObj[i];
            if (i in newObj) {
                var temp = newObj[i];
                var parseVal = parseFloat(temp, 10);
                if (isNumParse && !isNaN(parseVal)) {
                    temp = parseVal;
                }
                tempObj[i] = temp;
            }
        }
        return tempObj;
    },

    merge: function (rootObj, newObj) {
        rootObj = rootObj || {};
        newObj = newObj || {};
        for (var i in newObj) {
            if (newObj.hasOwnProperty(i)) {
                rootObj[i] = newObj[i];
            }
        }

        return rootObj;
    },

    strToPureRegStr: function (str) {
        return str.replace(/[-.\\[\]$+*^()?|:=!{},]/g, function (item) {
            return '\\' + item;
        });
    },

    regGenerator: function (keyword) {
        /**
         * $1: startSym
         * $2: keyword
         * $3: 『" or '』
         * $4: path
         */
        return new RegExp(['([^0-9a-zA-Z\\-_]|\\s+|^)(', keyword, ')\\((\'|")\\s*([^"\'*:><?\\|]+)\\3\\s*\\)(;??)'].join(''), 'g');
    },

    buildError: function (filePath, msg) {
        msg = msg || 'Not Found';
        return {
            file: filePath,
            content: '// ' + msg,
            error: true
        };
    },

    fixFilePath: function (fPath) {
        fPath = defExt.resolveFilePath(fPath);
        var newExtname = path.extname(fPath);
        return {
            path: fPath,
            extname: newExtname
        };
    },

    // 仅在解析文件内容中的依赖时使用
    resolvePath: function (currentFilePath, anotherPathParam, cwd, baseDir) {
        anotherPathParam = defExt.resolveFilePath(anotherPathParam);
        var currentFilePathDir = path.dirname(currentFilePath);
        var newFilePath;
        if (path.isAbsolute(anotherPathParam)) {
            newFilePath = path.join(cwd, baseDir, anotherPathParam);
        }
        else {
            newFilePath = path.resolve(currentFilePathDir, anotherPathParam);
        }
        var extname = path.extname(newFilePath);

        return {
            dir: path.dirname(newFilePath),
            file: path.basename(newFilePath),
            filePath: newFilePath,
            extname: extname
        };
    },

    // 解析依赖
    resolveCombine: function (fileGroup) {
        var groupMap = {};
        fileGroup.forEach(function (fileInfo) {
            groupMap[fileInfo.filePath] = fileInfo;
        });

        var combinedMap = {};
        var resolveOrder = [];
        var resolveUnit = function (fileInfo) {
            if (fileInfo.dependencies.length) {
                fileInfo.dependencies.forEach(function (depFileInfo) {
                    resolveUnit(groupMap[depFileInfo.filePath]);
                });
            }
            if (!combinedMap[fileInfo.filePath]) {
                combinedMap[fileInfo.filePath] = true;
                resolveOrder.push(fileInfo);
            }
        };
        fileGroup.forEach(function (fileInfo) {
            resolveUnit(fileInfo);
        });

        return resolveOrder;
    },

    unikey: function (len) {
        len = len || 9;
        var result = '';
        for(; result.length < len; result += Math.random().toString(36).substr(2));
        return result.substr(0, len);
    },

    notFoundMsg: function (filePath) {
        return '/*Not Found: ' + filePath + '*/';
    },

    notFoundErr: function (filePath, referPath) {
        return new Error('Can not find module ' + filePath + (referPath ? (' from ' + referPath + '.') : '.'));
    },

    // 预处理参数
    preParseParam: function (pathParam, baseDir) {
        pathParam = path.join(baseDir, pathParam);
        return defExt.resolveFilePath(pathParam);
    },

    mdwFilePath: function (filePath, cwd) {
        filePath = defExt.resolveFilePath(filePath);
        if (filePath.indexOf(cwd) === -1) {
            filePath = path.join(cwd, filePath);
        }
        return filePath;
    }
};

module.exports = utils;


text:
namespace {
const int kListenBacklog = 5;
}  // namespace

namespace content {

P2PSocketHostTcpServer::P2PSocketHostTcpServer(IPC::Sender* message_sender,
                                               int socket_id,
                                               P2PSocketType client_type)
    : P2PSocketHost(message_sender, socket_id),
      client_type_(client_type),
      socket_(new net::TCPServerSocket(NULL, net::NetLog::Source())),
      accept_callback_(base::Bind(&P2PSocketHostTcpServer::OnAccepted,
                                  base::Unretained(this))) {
}

P2PSocketHostTcpServer::~P2PSocketHostTcpServer() {
  STLDeleteContainerPairSecondPointers(accepted_sockets_.begin(),
                                       accepted_sockets_.end());

  if (state_ == STATE_OPEN) {
    DCHECK(socket_.get());
    socket_.reset();
  }
}

bool P2PSocketHostTcpServer::Init(const net::IPEndPoint& local_address,
                                  const P2PHostAndIPEndPoint& remote_address) {
  DCHECK_EQ(state_, STATE_UNINITIALIZED);

  int result = socket_->Listen(local_address, kListenBacklog);
  if (result < 0) {
    LOG(ERROR) << "Listen() failed: " << result;
    OnError();
    return false;
  }

  result = socket_->GetLocalAddress(&local_address_);
  if (result < 0) {
    LOG(ERROR) << "P2PSocketHostTcpServer::Init(): can't to get local address: "
               << result;
    OnError();
    return false;
  }
  VLOG(1) << "Local address: " << local_address_.ToString();

  state_ = STATE_OPEN;
  message_sender_->Send(new P2PMsg_OnSocketCreated(id_, local_address_));
  DoAccept();
  return true;
}

void P2PSocketHostTcpServer::OnError() {
  socket_.reset();

  if (state_ == STATE_UNINITIALIZED || state_ == STATE_OPEN)
    message_sender_->Send(new P2PMsg_OnError(id_));

  state_ = STATE_ERROR;
}

void P2PSocketHostTcpServer::DoAccept() {
  while (true) {
    int result = socket_->Accept(&accept_socket_, accept_callback_);
    if (result == net::ERR_IO_PENDING) {
      break;
    } else {
      HandleAcceptResult(result);
    }
  }
}

void P2PSocketHostTcpServer::HandleAcceptResult(int result) {
  if (result < 0) {
    if (result != net::ERR_IO_PENDING)
      OnError();
    return;
  }

  net::IPEndPoint address;
  if (accept_socket_->GetPeerAddress(&address) != net::OK) {
    LOG(ERROR) << "Failed to get address of an accepted socket.";
    accept_socket_.reset();
    return;
  }
  AcceptedSocketsMap::iterator it = accepted_sockets_.find(address);
  if (it != accepted_sockets_.end())
    delete it->second;

  accepted_sockets_[address] = accept_socket_.release();
  message_sender_->Send(
      new P2PMsg_OnIncomingTcpConnection(id_, address));
}

void P2PSocketHostTcpServer::OnAccepted(int result) {
  HandleAcceptResult(result);
  if (result == net::OK)
    DoAccept();
}

void P2PSocketHostTcpServer::Send(const net::IPEndPoint& to,
                                  const std::vector<char>& data,
                                  const talk_base::PacketOptions& options,
                                  uint64 packet_id) {
  NOTREACHED();
  OnError();
}

P2PSocketHost* P2PSocketHostTcpServer::AcceptIncomingTcpConnection(
    const net::IPEndPoint& remote_address, int id) {
  AcceptedSocketsMap::iterator it = accepted_sockets_.find(remote_address);
  if (it == accepted_sockets_.end())
    return NULL;

  net::StreamSocket* socket = it->second;
  accepted_sockets_.erase(it);

  scoped_ptr<P2PSocketHostTcpBase> result;
  if (client_type_ == P2P_SOCKET_TCP_CLIENT) {
    result.reset(new P2PSocketHostTcp(message_sender_, id, client_type_, NULL));
  } else {
    result.reset(
        new P2PSocketHostStunTcp(message_sender_, id, client_type_, NULL));
  }
  if (!result->InitAccepted(remote_address, socket))
    return NULL;
  return result.release();
}

bool P2PSocketHostTcpServer::SetOption(P2PSocketOption option,
                                       int value) {
  // Currently we don't have use case tcp server sockets are used for p2p.
  return false;
}

}  // namespace content


text:
import { Record } from 'immutable';

export const NodeDefinitionRecord = Record({
  _id: null,
  type: null,             // nodeが参照するものがなにかを表す。page, branch, finisherのいずれか
  refId: null,            // nodeが参照するpage, branch, finisherのid
  nextNodeId: null,       // 次に遷移するnodeのid。typeが'branch'の場合は条件によってbranchの条件が優先される
});

/** Nodeの定義 */
export default class NodeDefinition extends NodeDefinitionRecord {
  getId() {
    return this.get('_id');
  }

  getType() {
    return this.get('type');
  }

  isPage() {
    return this.get('type') === 'page';
  }

  isBranch() {
    return this.get('type') === 'branch';
  }

  isFinisher() {
    return this.get('type') === 'finisher';
  }

  getRefId() {
    return this.get('refId');
  }

  getNextNodeId() {
    return this.get('nextNodeId');
  }
}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using Xunit;

namespace System.Linq.Expressions.Tests
{
    public static class MemberAccessTests
    {
        [Fact]
        public static void CheckMemberAccessStructInstanceFieldTest()
        {
            Expression<Func<int>> e =
                Expression.Lambda<Func<int>>(
                    Expression.Field(
                        Expression.Constant(new FS() { II = 42 }),
                        "II"),
                    Enumerable.Empty<ParameterExpression>());
            Func<int> f = e.Compile();

            Assert.Equal(42, f());
        }

        [Fact]
        public static void CheckMemberAccessStructStaticFieldTest()
        {
            FS.SI = 42;
            try
            {
                Expression<Func<int>> e =
                    Expression.Lambda<Func<int>>(
                        Expression.Field(
                            null,
                            typeof(FS),
                            "SI"),
                        Enumerable.Empty<ParameterExpression>());
                Func<int> f = e.Compile();

                Assert.Equal(42, f());
            }
            finally
            {
                FS.SI = 0;
            }
        }

        [Fact]
        public static void CheckMemberAccessStructConstFieldTest()
        {
            Expression<Func<int>> e =
                Expression.Lambda<Func<int>>(
                    Expression.Field(
                        null,
                        typeof(FS),
                        "CI"),
                    Enumerable.Empty<ParameterExpression>());
            Func<int> f = e.Compile();

            Assert.Equal(42, f());
        }

        [Fact]
        public static void CheckMemberAccessStructStaticReadOnlyFieldTest()
        {
            Expression<Func<int>> e =
                Expression.Lambda<Func<int>>(
                    Expression.Field(
                        null,
                        typeof(FS),
                        "RI"),
                    Enumerable.Empty<ParameterExpression>());
            Func<int> f = e.Compile();

            Assert.Equal(42, f());
        }

        [Fact]
        public static void CheckMemberAccessStructInstancePropertyTest()
        {
            Expression<Func<int>> e =
                Expression.Lambda<Func<int>>(
                    Expression.Property(
                        Expression.Constant(new PS() { II = 42 }),
                        "II"),
                    Enumerable.Empty<ParameterExpression>());
            Func<int> f = e.Compile();

            Assert.Equal(42, f());
        }

        [Fact]
        public static void CheckMemberAccessStructStaticPropertyTest()
        {
            PS.SI = 42;
            try
            {
                Expression<Func<int>> e =
                    Expression.Lambda<Func<int>>(
                        Expression.Property(
                            null,
                            typeof(PS),
                            "SI"),
                        Enumerable.Empty<ParameterExpression>());
                Func<int> f = e.Compile();

                Assert.Equal(42, f());
            }
            finally
            {
                PS.SI = 0;
            }
        }

        [Fact]
        public static void CheckMemberAccessClassInstanceFieldTest()
        {
            Expression<Func<int>> e =
                Expression.Lambda<Func<int>>(
                    Expression.Field(
                        Expression.Constant(new FC() { II = 42 }),
                        "II"),
                    Enumerable.Empty<ParameterExpression>());
            Func<int> f = e.Compile();

            Assert.Equal(42, f());
        }

        [Fact]
        public static void CheckMemberAccessClassStaticFieldTest()
        {
            FC.SI = 42;
            try
            {
                Expression<Func<int>> e =
                    Expression.Lambda<Func<int>>(
                        Expression.Field(
                            null,
                            typeof(FC),
                            "SI"),
                        Enumerable.Empty<ParameterExpression>());
                Func<int> f = e.Compile();

                Assert.Equal(42, f());
            }
            finally
            {
                FC.SI = 0;
            }
        }

        [Fact]
        public static void CheckMemberAccessClassConstFieldTest()
        {
            Expression<Func<int>> e =
                Expression.Lambda<Func<int>>(
                    Expression.Field(
                        null,
                        typeof(FC),
                        "CI"),
                    Enumerable.Empty<ParameterExpression>());
            Func<int> f = e.Compile();

            Assert.Equal(42, f());
        }

        [Fact]
        public static void CheckMemberAccessClassStaticReadOnlyFieldTest()
        {
            Expression<Func<int>> e =
                Expression.Lambda<Func<int>>(
                    Expression.Field(
                        null,
                        typeof(FC),
                        "RI"),
                    Enumerable.Empty<ParameterExpression>());
            Func<int> f = e.Compile();

            Assert.Equal(42, f());
        }

        [Fact]
        public static void CheckMemberAccessClassInstancePropertyTest()
        {
            Expression<Func<int>> e =
                Expression.Lambda<Func<int>>(
                    Expression.Property(
                        Expression.Constant(new PC() { II = 42 }),
                        "II"),
                    Enumerable.Empty<ParameterExpression>());
            Func<int> f = e.Compile();

            Assert.Equal(42, f());
        }

        [Fact]
        public static void CheckMemberAccessClassStaticPropertyTest()
        {
            PC.SI = 42;
            try
            {
                Expression<Func<int>> e =
                    Expression.Lambda<Func<int>>(
                        Expression.Property(
                            null,
                            typeof(PC),
                            "SI"),
                        Enumerable.Empty<ParameterExpression>());
                Func<int> f = e.Compile();

                Assert.Equal(42, f());
            }
            finally
            {
                PC.SI = 0;
            }
        }

        [Fact] // [Issue(3217, "https://github.com/dotnet/corefx/issues/3217")]
        public static void CheckMemberAccessClassInstanceFieldNullReferenceTest()
        {
            Expression<Func<int>> e =
                Expression.Lambda<Func<int>>(
                    Expression.Field(
                        Expression.Constant(null, typeof(FC)),
                        "II"),
                    Enumerable.Empty<ParameterExpression>());
            Func<int> f = e.Compile();

            Assert.Throws<NullReferenceException>(() => f());
        }

        [Fact] // [Issue(3217, "https://github.com/dotnet/corefx/issues/3217")]
        public static void CheckMemberAccessClassInstanceFieldAssignNullReferenceTest()
        {
            Expression<Func<int>> e =
                Expression.Lambda<Func<int>>(
                    Expression.Assign(
                        Expression.Field(
                            Expression.Constant(null, typeof(FC)),
                            "II"),
                        Expression.Constant(1)),
                    Enumerable.Empty<ParameterExpression>());
            Func<int> f = e.Compile();

            Assert.Throws<NullReferenceException>(() => f());
        }

        [Fact] // [Issue(3217, "https://github.com/dotnet/corefx/issues/3217")]
        public static void CheckMemberAccessClassInstancePropertyNullReferenceTest()
        {
            Expression<Func<int>> e =
                Expression.Lambda<Func<int>>(
                    Expression.Property(
                        Expression.Constant(null, typeof(PC)),
                        "II"),
                    Enumerable.Empty<ParameterExpression>());
            Func<int> f = e.Compile();

            Assert.Throws<NullReferenceException>(() => f());
        }

        [Fact] // [Issue(3217, "https://github.com/dotnet/corefx/issues/3217")]
        public static void CheckMemberAccessClassInstanceIndexerNullReferenceTest()
        {
            Expression<Func<int>> e =
                Expression.Lambda<Func<int>>(
                    Expression.Property(
                        Expression.Constant(null, typeof(PC)),
                        "Item",
                        Expression.Constant(1)),
                    Enumerable.Empty<ParameterExpression>());
            Func<int> f = e.Compile();

            Assert.Throws<NullReferenceException>(() => f());
        }

        [Fact] // [Issue(3217, "https://github.com/dotnet/corefx/issues/3217")]
        public static void CheckMemberAccessClassInstanceIndexerAssignNullReferenceTest()
        {
            Expression<Func<int>> e =
                Expression.Lambda<Func<int>>(
                    Expression.Assign(
                        Expression.Property(
                            Expression.Constant(null, typeof(PC)),
                            "Item",
                            Expression.Constant(1)),
                        Expression.Constant(1)),
                    Enumerable.Empty<ParameterExpression>());
            Func<int> f = e.Compile();

            Assert.Throws<NullReferenceException>(() => f());
        }
    }
}


text:
#pragma once

#include <string>

#include <boost/filesystem.hpp>

namespace color_coded
{
  namespace conf
  {
    namespace fs = boost::filesystem;

    inline fs::directory_iterator find_file(fs::path const &dir, std::string const &file)
    {
      static fs::directory_iterator const end;
      return std::find_if
      (
          fs::directory_iterator{ dir }, end,
          [&](fs::directory_entry const &e)
          { return e.path().filename().string() == file; }
      );
    }

    /* From the current directory, search for a .color_coded file for the
     * current filetype first, then for a non-typed .color_coded. If neither
     * is found, move to the parent directory. Repeat until /. */
    inline std::string find(fs::path file, std::string const &filetype)
    {
      fs::path curr{ file.parent_path() };
      static fs::directory_iterator const end;

      static auto constexpr file_name(".color_coded");
      auto const typed_file_name(std::string{ file_name } + "_" + filetype);
      std::string const flag_files[] {typed_file_name, file_name};

      while(true)
      {

        for(auto const &file : flag_files)
        {
          auto const dir_it(find_file(curr, file));
          if(dir_it != end)
          { return dir_it->path().string(); }
        }

        /* We may have hit /. */
        if(!fs::canonical(curr).has_parent_path())
        { return {}; }

        curr /= "..";
      }
      return {};
    }
  }
}


text:
package org.onehippo.forge.exdocpicker.impl.field;

import java.io.Serializable;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.StringResourceModel;
import org.onehippo.forge.exdocpicker.api.ExternalDocumentCollection;
import org.onehippo.forge.exdocpicker.api.ExternalDocumentServiceContext;
import org.onehippo.forge.exdocpicker.api.ExternalDocumentServiceFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TextSearchExternalDocumentFieldBrowserDialog extends ExternalDocumentFieldBrowserDialog {

    private static final long serialVersionUID = 1L;

    private static Logger log = LoggerFactory.getLogger(TextSearchExternalDocumentFieldBrowserDialog.class);

    public TextSearchExternalDocumentFieldBrowserDialog(IModel<String> titleModel,
                                                        final ExternalDocumentServiceContext extDocServiceContext,
                                                        final ExternalDocumentServiceFacade<Serializable> exdocService,
                                                        IModel<ExternalDocumentCollection<Serializable>> model) {
        super(titleModel, extDocServiceContext, exdocService, model);

        final TextField<String> searchText = new TextField<String>("search-input", new PropertyModel<String>(this, "searchQuery"));
        searchText.setOutputMarkupId(true);
        add(setFocus(searchText));

        //Search button
        AjaxButton searchButton = new AjaxButton("search-button", new StringResourceModel("search.button", this, null)) {
            private static final long serialVersionUID = 1L;

            @Override
            protected void onSubmit(AjaxRequestTarget ajaxRequestTarget, Form<?> form) {
                searchExternalDocumentsBySearchQuery();
                ajaxRequestTarget.add(TextSearchExternalDocumentFieldBrowserDialog.this);
            }
        };

        add(searchButton);
    }
}


text:
package org.hisp.dhis.common;

/**
 * Marker interface for marking an object to not be treated as a id object (even
 * if the class itself implements id object), this object will not be treated as
 * normal metadata (no refs etc) but instead need to be contained in the entity
 * that owns it.
 * <p>
 * Embedded objects should also always be implemented as cascade="delete-all-orphan".
 *
 * @author Morten Olav Hansen <mortenoh@gmail.com>
 */
public interface EmbeddedObject
{
}


text:
<?php

$this->setProperty('channel_num',(int)$params['VALUE']);


text:
import variables as v
import pygame as py
import traceback

changeCallers = []
debuger = None

def change(rect):
    """Adds a rect to the changes list.

    Args:
        rect (pygame.Rect): The rect to add to the changes list
    """
    if type(rect) != py.Rect:
        raise TypeError(str(rect) + " is not a Rect object")
    rect = rect.copy().inflate(2, 2)
    v.changes.append(rect)
    #changeCallers.append(''.join(traceback.format_stack()))

def getChangeCaller(index):
    print(changeCallers[index])

def updateDisplay():
    from guiItems import debug
    global debuger
    debuger = debug()
    change(py.Rect(0, 0, 1280, 720))
    flags = 0
    size = (640, 360)
    if v.fullscreen:
        flags = flags|py.FULLSCREEN
        size = (1280, 720)
    """if v.hwsurface:
        flags = flags|py.HWSURFACE
    if v.doublebuf:
        flags = flags|py.DOUBLEBUF"""
    v.display = py.display.set_mode(size, flags)
    v.windowWidth, v.windowHeight = size

def refresh():
    """Updates the display"""
    #oldChanges = list(v.oldChanges)
    #v.oldChanges = [r.copy() for r in v.changes]
    if v.debug:
        debuger.update()

    for event in v.events:
        if event.type == py.KEYDOWN:
            if event.key == py.K_F11:
                v.fullscreen = not v.fullscreen
                if v.fullscreen:
                    v.display = py.display.set_mode((1280, 720), py.FULLSCREEN|py.HWSURFACE|py.DOUBLEBUF)
                    v.windowHeight = 720
                    v.windowWidth = 1280
                else:
                    v.display = py.display.set_mode((640, 360))
                    v.windowHeight = 360
                    v.windowWidth = 640
                change(py.Rect(0, 0, 1280, 720))
            if event.key == py.K_f:
                change(py.Rect(0, 0, 1280, 720))
    if (v.windowWidth, v.windowHeight) == (1280, 720):
        v.display.blit(v.screen, (0, 0))
    else:
        screen_rect = py.Rect(0, 0, v.windowWidth, v.windowHeight)
        image_rect = py.Rect(0, 0, 1280, 720)
        fit_to_rect = image_rect.fit(screen_rect)
        fit_to_rect.center = screen_rect.center
        if True: #smooth scale
            py.transform.smoothscale(v.screen, fit_to_rect.size, v.display)
        else:
            py.transform.scale(v.screen, fit_to_rect.size, v.display)

        for c in v.changes:
            c.x /= 2
            c.y /= 2
            c.width /= 2
            c.height /= 2

    changes = v.changes + v.oldChanges
    v.oldChanges = v.changes
    if (v.windowWidth, v.windowHeight) != (1280, 720):
        scale = ((1280, 720)[0]/fit_to_rect[2], (1280, 720)[1]/fit_to_rect[3])
        x,y = py.mouse.get_pos()
        v.mouse_pos = (int((x - fit_to_rect[0])*scale[0]), int((y - fit_to_rect[1])*scale[1]))
    else:
        v.mouse_pos = py.mouse.get_pos()

    if py.key.get_pressed()[py.K_r]: # highlight updated areas
        for c in changes:
            py.draw.rect(v.display, (255, 0, 0), c, 3)

    py.display.update(changes)
    v.changes = []
    global changeCallers
    changeCallers = []


text:
@implementation FKFlickrFavoritesRemove

- (BOOL) needsLogin {
    return YES;
}

- (BOOL) needsSigning {
    return YES;
}

- (FKPermission) requiredPerms {
    return 1;
}

- (NSString *) name {
    return @"flickr.favorites.remove";
}

- (BOOL) isValid:(NSError **)error {
    BOOL valid = YES;
	NSMutableString *errorDescription = [[NSMutableString alloc] initWithString:@"You are missing required params: "];
	if(!self.photo_id) {
		valid = NO;
		[errorDescription appendString:@"'photo_id', "];
	}

	if(error != NULL) {
		if(!valid) {
			NSDictionary *userInfo = @{NSLocalizedDescriptionKey: errorDescription};
			*error = [NSError errorWithDomain:FKFlickrKitErrorDomain code:FKErrorInvalidArgs userInfo:userInfo];
		}
	}
    return valid;
}

- (NSDictionary *) args {
    NSMutableDictionary *args = [NSMutableDictionary dictionary];
	if(self.photo_id) {
		[args setValue:self.photo_id forKey:@"photo_id"];
	}

    return [args copy];
}

- (NSString *) descriptionForError:(NSInteger)error {
    switch(error) {
		case FKFlickrFavoritesRemoveError_PhotoNotInFavorites:
			return @"Photo not in favorites";
		case FKFlickrFavoritesRemoveError_CannotRemovePhotoFromThatUsersFavorites:
			return @"Cannot remove photo from that user's favorites";
		case FKFlickrFavoritesRemoveError_UserNotFound:
			return @"User not found";
		case FKFlickrFavoritesRemoveError_SSLIsRequired:
			return @"SSL is required";
		case FKFlickrFavoritesRemoveError_InvalidSignature:
			return @"Invalid signature";
		case FKFlickrFavoritesRemoveError_MissingSignature:
			return @"Missing signature";
		case FKFlickrFavoritesRemoveError_LoginFailedOrInvalidAuthToken:
			return @"Login failed / Invalid auth token";
		case FKFlickrFavoritesRemoveError_UserNotLoggedInOrInsufficientPermissions:
			return @"User not logged in / Insufficient permissions";
		case FKFlickrFavoritesRemoveError_InvalidAPIKey:
			return @"Invalid API Key";
		case FKFlickrFavoritesRemoveError_ServiceCurrentlyUnavailable:
			return @"Service currently unavailable";
		case FKFlickrFavoritesRemoveError_WriteOperationFailed:
			return @"Write operation failed";
		case FKFlickrFavoritesRemoveError_FormatXXXNotFound:
			return @"Format \"xxx\" not found";
		case FKFlickrFavoritesRemoveError_MethodXXXNotFound:
			return @"Method \"xxx\" not found";
		case FKFlickrFavoritesRemoveError_InvalidSOAPEnvelope:
			return @"Invalid SOAP envelope";
		case FKFlickrFavoritesRemoveError_InvalidXMLRPCMethodCall:
			return @"Invalid XML-RPC Method Call";
		case FKFlickrFavoritesRemoveError_BadURLFound:
			return @"Bad URL found";

		default:
			return @"Unknown error code";
    }
}

@end


text:
class RESO::ContactStatusAssignment < RESO::ParentChildAssignment
end


text:
<?php

class Artigo extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->helpers(['form', 'array', 'formaters']);
        $this->load->model('Artigo_Model', 'artigo');
        $this->load->model('Autor_Model', 'autor');
        $this->load->model('Tags_Model', 'tags');
        $this->load->model('Artigos_Tags_Model', 'artigos_tags');
    }

    /**
     * Lista os artigos
     *
     */
    public function index()
    {
        $resultado = $this->artigo->all('array');
        $this->load->view('admin/artigo/index', compact('resultado'));
    }

    /**
     * Exibe formulario para criar novo artigo
     *
     */
    public function create()
    {
        $dados = (object) array(
            'autores' => formated_dropdown($this->autor->all(array('id', 'autor as name'))),
            'all_tags' => formated_dropdown($this->tags->all(array('id', 'tag as name')))
        );
        $this->load->view('admin/artigo/create', compact('dados'));
    }

    /**
     * Salva novo artigo
     *
     */
    public function store()
    {
        $dados = $this->input->post();

        $this->artigo->doInsert($dados);
    }

    /**
     * Exibe formulario de alteracao de um artigo
     *
     * @param $id
     */
    public function edit($id)
    {
        $dados = (object) array(
            'dados'=>  $this->artigo->getById($id),
            'autores'=>formated_dropdown($this->autor->all(array('id', 'autor as name'))),
            'all_tags'=>formated_dropdown($this->tags->all(array('id', 'tag as name'))),
            'tags_selected'=>formated_dropdown($this->tags->allTagsByArtigo($id, array('id')))
        );
        $this->load->view('admin/artigo/edit', compact('dados'));
    }

    /**
     * Retorna o numero de registros alterados
     *
     * @return mixed
     */
    public function update()
    {
        $dados = $this->input->post();
        $this->artigo->doUpdate($dados['id'], $dados);
    }

    /**
     * Confirmar a exclusao
     *
     */
    public function remove($id)
    {
        $dados = (object) array(
            'controller'=>'admin/artigo/',
            'id'=>$id
        );
        $this->load->view('admin/default/remove', compact('dados'));
    }

    /**
     * Finaliza a exclusao
     * Se falhar exibe o erro
     *
     */
    public function destroy($id)
    {
        $exclusao = $this->artigo->doDelete($id);
        if( $exclusao !== true ){
            $this->session->set_flashdata('erroaoexcluir', "Error(".$exclusao['code']."): ".$exclusao['message']);

            redirect('admin/artigo/remove/'.$id);
        }
        redirect('admin/artigo');
    }

}


text:
package com.twitter.diffy.workflow

import javax.inject.Inject

import com.twitter.diffy.analysis.{JoinedEndpoint, DifferencesFilterFactory, JoinedDifferences}
import com.twitter.diffy.proxy.Settings
import com.twitter.diffy.util.{SimpleMessage, EmailSender}
import com.twitter.finatra.http.internal.marshalling.mustache.MustacheService
import com.twitter.logging.Logger
import com.twitter.util.{Duration, Future}

case class Endpoint(endpointName: String, count: Long, fields: Iterable[Field])
case class Field(fieldName: String, relativeDifference: String, absoluteDifference: String)

case class ReportData(
    delay: Duration,
    rootUrl: String,
    serviceName: String,
    criticalDiffs: Int,
    criticalEndpoints: Seq[Endpoint],
    passingEndpoints: Seq[Endpoint])

object ReportGenerator {
  val NormalizedUrlRegex = "(http://)?([^/]*)(/?)".r
  def normalizeUrl(url: String): String = url match {
    case NormalizedUrlRegex(_, rawUrl, _) => s"http://$rawUrl/"
  }
}

class ReportGenerator @Inject()(
    joinedDifferences: JoinedDifferences,
    settings: Settings,
    mustacheService: MustacheService)
{
  import ReportGenerator._

  private[this] val log: Logger = Logger(classOf[ReportGenerator])
  private[this] val emailSender = new EmailSender(log)

  private[this] def sendReport(report: ReportData) =
    emailSender(buildMessage(report))

  def buildSubject(serviceName: String, criticalDiffs: Int) =
    if (criticalDiffs == 0) {
      s"[diffy] ${serviceName} - All endpoints passed"
    } else {
      s"[diffy] ${serviceName} ${criticalDiffs} critical"
    }

  def buildMessage(report: ReportData) : SimpleMessage = {
    SimpleMessage(
      from = "Diffy <diffy@twitter.com>",
      to = settings.teamEmail,
      bcc = "Diffy Team <diffy-team@twitter.com>",
      subject = buildSubject(report.serviceName, report.criticalDiffs),
      body = new String(mustacheService.createChannelBuffer("cron_report.mustache", report).toByteBuffer.array)
    )
  }

  private[this] val filter =
    DifferencesFilterFactory(
      settings.relativeThreshold,
      settings.absoluteThreshold
    )

  def extractReport(endpoints: Map[String, JoinedEndpoint]): ReportData = {
    val endpointGrouping =
      endpoints.map { case ((endpoint, joinedEndpoint)) =>
        Endpoint(
          endpoint,
          joinedEndpoint.total,
          joinedEndpoint.fields.collect {
            case ((path, field)) if filter(field) =>
              Field(path, "%1.2f".format(field.relativeDifference), "%1.2f".format(field.absoluteDifference))
          }
        )
      }.toSeq.groupBy(_.fields.size > 0)

    val criticalEndpoints = endpointGrouping.getOrElse(true, Seq.empty).sortBy(_.fields.size).reverse
    val passingEndpoints = endpointGrouping.getOrElse(false, Seq.empty).sortBy(_.endpointName)

    val fieldCount = criticalEndpoints.map(_.fields.size).sum

    ReportData(
      settings.emailDelay,
      normalizeUrl(settings.rootUrl),
      settings.serviceName,
      fieldCount,
      criticalEndpoints,
      passingEndpoints
    )
  }

  def conditionallySendReport(reportData: ReportData) =
    if (reportData.criticalDiffs == 0 && settings.skipEmailsWhenNoErrors) {
      Future.Unit
    } else {
      sendReport(reportData)
    }

  def sendEmail = {
    joinedDifferences.endpoints map { extractReport _ andThen conditionallySendReport }
  }

  def extractReportFromDifferences = {
    joinedDifferences.endpoints map extractReport
  }
}


text:
@class GHIssueComment;

@interface CommentCell : TextCell {
	GHIssueComment *comment;
	UIImageView *gravatarView;
	UILabel *userLabel;
	UILabel *dateLabel;
}

@property(nonatomic,retain)GHIssueComment *comment;
@property(nonatomic,retain)IBOutlet UIImageView *gravatarView;
@property(nonatomic,retain)IBOutlet UILabel *userLabel;
@property(nonatomic,retain)IBOutlet UILabel *dateLabel;

- (void)setComment:(GHIssueComment *)theComment;

@end


text:
<?php
namespace Auditing;

use InvalidArgumentException,
    Zend\Config\Config,
    Zend\Di\Locator,
    Zend\EventManager\Event,
    Zend\EventManager\EventCollection,
    Zend\EventManager\StaticEventCollection,
    Zend\EventManager\StaticEventManager,
    Zend\Module\Consumer\AutoloaderProvider,
    Zend\Module\Manager,
    Zend\Loader\StandardAutoloader as StandardAutoloader
    ;

use SimpleThings\EntityAudit\AuditConfiguration;
use SimpleThings\EntityAudit\AuditManager;

class Module implements AutoloaderProvider
{
    protected $appListeners    = array();
    protected $staticListeners = array();
    protected $viewListener;

    public function init(Manager $moduleManager) {
        $events = StaticEventManager::getInstance();
        $events->attach('bootstrap', 'bootstrap', array($this, 'initListeners'), 100);
    }

    protected function initAutoloader($env = null)
    {
//        require __DIR__ . '/autoload_register.php';
    }

    public static function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }

    /**
     * Return a configuration for an autoloader to cover the
     * classes used in this module
     */
    public function getAutoloaderConfig() {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    'SimpleThings\EntityAudit' => __DIR__ . '/vendor/EntityAudit',
                )
            ),
            'Zend\Loader\ClassMapAutoloader' => array(
                array(
                    'Stuki/Module' => __DIR__ . '/Module.php'
                )
            )
        );
    }

    /**
     * Configure EntityAudit
     */
    public function initListeners($e) {
        $locator = $e->getParam('application')->getLocator();

        $users = $locator->get('modelAuthentication');
        $em = $locator->get('doctrine_em');

        $auditconfig = new AuditConfiguration();
        $auditconfig->setAuditedEntityClasses(array(
            # Default Stuki entities
            'Entities\Attributes',
            'Entities\AttributeSets',
            'Entities\AttributeSetPlugins',
            'Entities\AttributeSetRelations',
            'Entities\Entities',
            'Entities\Plugins',
            'Entities\Renderers',
            'Entities\Themes',
            '\ZfcUserDoctrineORM\Entity\User',
            'Entities\ValuesArray',
            'Entities\ValuesDatetime',
            'Entities\ValuesDecimal',
            'Entities\ValuesInteger',
            'Entities\ValuesText',
            'Entities\ValuesVarchar',

            # Plugins
            'Entities\Attachments',
            'Entities\Favorites'
        ));

        // Set the current user
        $auditconfig->setCurrentUsername($users->getIdentity());

        $evm = $em->getEventManager();

        $auditManager = new AuditManager($auditconfig);
        $auditManager->registerEvents($evm);
    }

}


text:
<?php

namespace MVuoncino\tests;

class TestObjectChild extends TestObject
{
    private $privateVarChild;

    protected $protectedVarChild;

    public $publicVarChild;

    public function setPrivateVarChild($privateVarChild)
    {
        $this->privateVarChild = $privateVarChild;
    }

    public function setProtectedVarChild($protectedVarChild)
    {
        $this->protectedVarChild = $protectedVarChild;
    }
}


text:
package com.viro;

import java.io.IOException;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;

//import org.apache.commons.collections15.Transformer;
import org.xml.sax.SAXException;

import com.viro.graph.Graph;
import com.viro.repository.ItemDescriptor;
import com.viro.repository.RepositoryParser;

public class Initiator {
    public String nodeString;
    public String edgeString;

    public void createString() {
        Configuration configuration = new Configuration();
        RepositoryParser repositoryParser = new RepositoryParser(configuration);

        List<ItemDescriptor> repositoryItems = null;
        try {
            repositoryItems = repositoryParser.parseRepositoryXML("C:\\MyData\\ViRo\\ViRo_\\resources\\repo.xml");
        } catch (ParserConfigurationException e1) {
            e1.printStackTrace();
        } catch (SAXException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        Graph graph = Graph.createGraph(configuration, repositoryItems);

        nodeString = graph.nodesString();
        edgeString = graph.edgesString();
    }

}