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 local.Inventario;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import local.DAO.Repuestos_DAO;
import local.DAO.Roles_DAO;
import local.Empleados.Empleados;
import local.PrincipalFrame.Principal_Frame;

/**
 *
 * @author Leonel
 */
public class Repuesto_Add extends javax.swing.JInternalFrame {

    DefaultTableModel modeloRepuesto;
    Repuestos_DAO resDao = new Repuestos_DAO();
    FileInputStream file = null;
    InputStream fotoFile = null;
    int idRepuesto;
    int bite;
    boolean isPhotoChange;

    public Repuesto_Add() {
        //Cargando los datos de la tabla
        modeloRepuesto = new DefaultTableModel(null, getColums());
        getRows();

        //Iniciando los componentes del formulario
        initComponents();
        setVisible(true);

        //Acciones por rol
        accionRol();

        //Ocultar columnas
        jtblRepuestos.getColumnModel().getColumn(0).setMaxWidth(0);
        jtblRepuestos.getColumnModel().getColumn(0).setMinWidth(0);
        jtblRepuestos.getColumnModel().getColumn(0).setPreferredWidth(0);
        jtblRepuestos.getColumnModel().getColumn(4).setMaxWidth(0);
        jtblRepuestos.getColumnModel().getColumn(4).setMinWidth(0);
        jtblRepuestos.getColumnModel().getColumn(4).setPreferredWidth(0);

        //Centrando el formulario
        int wdith = Principal_Frame.jdpContenedor.getWidth() - this.getWidth();
        int hght = Principal_Frame.jdpContenedor.getHeight() - this.getHeight();
        this.setLocation(wdith / 2, hght / 2);

        this.jlblFoto.setHorizontalAlignment(JLabel.CENTER);
    }

    private String[] getColums(){
        String[] columnas = new String[]{"Id","Repuesto", "Estado", "Descripcion", "Foto", "Usuario"};
        return columnas;
    }

    private void getRows(){
        ResultSet rs = resDao.getListRepuestos();

        try{
            Object datos[] = new Object[6];

            while(rs.next()){
                for (int i = 0; i < datos.length; i++) {
                    datos[i] = rs.getObject(i+1);
                    if(i == 2){
                        if(rs.getInt(i+1) == 1)
                            datos[i] = "Activo";
                        else
                            datos[i] = "Inactivo";
                    }
                }
                modeloRepuesto.addRow(datos);
            }

            rs.close();
        }
        catch(SQLException ex){
            JOptionPane.showMessageDialog(null, "Error al cargar datos.");
            Logger.getLogger(Repuesto_Add.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void loadImage() throws IOException {
        ResultSet rs = resDao.loadImage(idRepuesto);
        InputStream is;
        ImageIcon foto;

        try {
            if (rs.next()) {
                is = rs.getBinaryStream(1);

                if (is != null)
                {
                    BufferedImage bf = ImageIO.read(is);
                    foto = new ImageIcon(bf);

                    Image img = foto.getImage();
                    Image newImg = img.getScaledInstance(jlblFoto.getHeight(), jlblFoto.getHeight(), Image.SCALE_DEFAULT);

                    ImageIcon newIcon = new ImageIcon(newImg);

                    jlblFoto.setIcon(newIcon);
                }
            }

            rs.close();

        } catch (SQLException ex) {
            Logger.getLogger(Empleados.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void limpiar() {
        jtfDescripcion.setText("");
        jtfRepuesto.setText("");
        jlblFoto.setIcon(null);
        jbtgEstado.clearSelection();
    }

    private void limpieza() {
        limpiar();
        for (int i = 0; i < jtblRepuestos.getRowCount(); i++) {
            modeloRepuesto.removeRow(i);
            i -= 1;
        }
    }

    //metodo para verificar los permisos para el formulario cargos
    private void accionRol(){
        Roles_DAO rolDao = new Roles_DAO();
        ResultSet rs = rolDao.listaTareas();
        int acciones;

        try {
            while(rs.next()){
                acciones = rs.getInt(1);
                switch(acciones){
                    case 16:
                        jrbtnAdd.setEnabled(true);
                        break;

                    case 17:
                        jrbtnUpdate.setEnabled(true);
                        break;

                    case 18:
                        jrbtnDelete.setEnabled(true);
                        break;
                }
            }
        } catch (SQLException ex) {
            Logger.getLogger(Repuesto_Add.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    /**
     * 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() {

        jbtgAcciones = new javax.swing.ButtonGroup();
        jbtgEstado = new javax.swing.ButtonGroup();
        jPanelAcciones = new javax.swing.JPanel();
        jrbtnAdd = new javax.swing.JRadioButton();
        jrbtnUpdate = new javax.swing.JRadioButton();
        jrbtnDelete = new javax.swing.JRadioButton();
        jLabel2 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtblRepuestos = new javax.swing.JTable();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jtfRepuesto = new javax.swing.JTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtfDescripcion = new javax.swing.JTextArea();
        jrbtActivo = new javax.swing.JRadioButton();
        jrbtInactivo = new javax.swing.JRadioButton();
        jLabel6 = new javax.swing.JLabel();
        jlblFoto = new javax.swing.JLabel();
        jbtnFoto = new javax.swing.JButton();
        jbtnAceptar = new javax.swing.JButton();

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle("Repuestos");
        setMinimumSize(new java.awt.Dimension(500, 600));
        setPreferredSize(new java.awt.Dimension(600, 800));

        jPanelAcciones.setBackground(new java.awt.Color(80, 81, 79));

        jrbtnAdd.setBackground(new java.awt.Color(80, 81, 79));
        jbtgAcciones.add(jrbtnAdd);
        jrbtnAdd.setFont(new java.awt.Font("Calibri", 0, 16)); // NOI18N
        jrbtnAdd.setForeground(new java.awt.Color(242, 95, 92));
        jrbtnAdd.setText("Agregar");
        jrbtnAdd.setEnabled(false);
        jrbtnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jrbtnAddActionPerformed(evt);
            }
        });

        jrbtnUpdate.setBackground(new java.awt.Color(80, 81, 79));
        jbtgAcciones.add(jrbtnUpdate);
        jrbtnUpdate.setFont(new java.awt.Font("Calibri", 0, 16)); // NOI18N
        jrbtnUpdate.setForeground(new java.awt.Color(242, 95, 92));
        jrbtnUpdate.setText("Editar");
        jrbtnUpdate.setEnabled(false);

        jrbtnDelete.setBackground(new java.awt.Color(80, 81, 79));
        jbtgAcciones.add(jrbtnDelete);
        jrbtnDelete.setFont(new java.awt.Font("Calibri", 0, 16)); // NOI18N
        jrbtnDelete.setForeground(new java.awt.Color(242, 95, 92));
        jrbtnDelete.setText("Eliminar");
        jrbtnDelete.setEnabled(false);

        javax.swing.GroupLayout jPanelAccionesLayout = new javax.swing.GroupLayout(jPanelAcciones);
        jPanelAcciones.setLayout(jPanelAccionesLayout);
        jPanelAccionesLayout.setHorizontalGroup(
            jPanelAccionesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelAccionesLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jrbtnAdd)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jrbtnUpdate)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jrbtnDelete)
                .addContainerGap())
        );
        jPanelAccionesLayout.setVerticalGroup(
            jPanelAccionesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelAccionesLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanelAccionesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jrbtnAdd)
                    .addComponent(jrbtnDelete)
                    .addComponent(jrbtnUpdate))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jLabel2.setFont(new java.awt.Font("Calibri", 0, 14)); // NOI18N
        jLabel2.setText("Buscar:");

        jTextField1.setFont(new java.awt.Font("Calibri", 0, 14)); // NOI18N

        jtblRepuestos.setModel(modeloRepuesto);
        jtblRepuestos.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jtblRepuestosMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jtblRepuestos);

        jLabel3.setFont(new java.awt.Font("Calibri", 0, 14)); // NOI18N
        jLabel3.setText("Repuesto:");

        jLabel4.setFont(new java.awt.Font("Calibri", 0, 14)); // NOI18N
        jLabel4.setText("Descripcion:");

        jLabel5.setFont(new java.awt.Font("Calibri", 0, 14)); // NOI18N
        jLabel5.setText("Estado:");

        jtfRepuesto.setFont(new java.awt.Font("Calibri", 0, 14)); // NOI18N

        jtfDescripcion.setColumns(20);
        jtfDescripcion.setFont(new java.awt.Font("Calibri", 0, 14)); // NOI18N
        jtfDescripcion.setRows(3);
        jScrollPane2.setViewportView(jtfDescripcion);

        jbtgEstado.add(jrbtActivo);
        jrbtActivo.setFont(new java.awt.Font("Calibri", 0, 14)); // NOI18N
        jrbtActivo.setText("Activo");

        jbtgEstado.add(jrbtInactivo);
        jrbtInactivo.setFont(new java.awt.Font("Calibri", 0, 14)); // NOI18N
        jrbtInactivo.setText("Inactivo");

        jLabel6.setFont(new java.awt.Font("Calibri", 0, 14)); // NOI18N
        jLabel6.setText("Foto:");

        jlblFoto.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        jbtnFoto.setFont(new java.awt.Font("Calibri", 0, 14)); // NOI18N
        jbtnFoto.setText("Foto");
        jbtnFoto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnFotoActionPerformed(evt);
            }
        });

        jbtnAceptar.setFont(new java.awt.Font("Calibri", 0, 14)); // NOI18N
        jbtnAceptar.setText("Aceptar");
        jbtnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnAceptarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanelAcciones, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(18, 18, 18)
                        .addComponent(jTextField1)
                        .addGap(10, 10, 10))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 464, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel4)
                                    .addComponent(jLabel6)
                                    .addComponent(jLabel5))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jrbtActivo)
                                        .addGap(18, 18, 18)
                                        .addComponent(jrbtInactivo)
                                        .addGap(0, 0, Short.MAX_VALUE))
                                    .addComponent(jlblFoto, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jbtnFoto, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jScrollPane2)
                                    .addComponent(jtfRepuesto))))
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jbtnAceptar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanelAcciones, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 82, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jtfRepuesto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtnFoto)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jlblFoto, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jrbtActivo)
                    .addComponent(jrbtInactivo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtnAceptar)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jbtnFotoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnFotoActionPerformed
        jlblFoto.setIcon(null);
        JFileChooser j = new JFileChooser();
        j.setFileSelectionMode(JFileChooser.FILES_ONLY);
        int estado = j.showOpenDialog(null);

        if (estado == JFileChooser.APPROVE_OPTION) {
            try {
                file = new FileInputStream(j.getSelectedFile());
                bite = (int) j.getSelectedFile().length();

                try {
                    Image icono = ImageIO.read(j.getSelectedFile()).getScaledInstance(jlblFoto.getHeight(), jlblFoto.getHeight(), Image.SCALE_DEFAULT);
                    jlblFoto.setIcon(new ImageIcon(icono));
                    jlblFoto.updateUI();
                    if (jrbtnUpdate.isSelected()) {
                        isPhotoChange = true;
                    }
                } catch (IOException ex) {
                    Logger.getLogger(Empleados.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch (FileNotFoundException ex) {
                Logger.getLogger(Empleados.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_jbtnFotoActionPerformed

    private void jbtnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnAceptarActionPerformed
        if(!jtfRepuesto.getText().isEmpty() && !jtfDescripcion.getText().isEmpty()){
            if(jrbtActivo.isSelected() || jrbtInactivo.isSelected()){
                if(jrbtnAdd.isSelected() && bite > 0){
                    int i, estado;

                    //Verificando si el estado es activo o inactivo
                    if(jrbtActivo.isSelected())
                        estado = 1;
                    else
                        estado = 0;

                    i = resDao.addRepuestos(jtfRepuesto.getText(), estado, jtfDescripcion.getText(), file, bite);

                    if(i > 0){
                        limpieza();
                        getRows();
                    } else
                        JOptionPane.showMessageDialog(null, "No se puedo agregar el repuesto");
                } else if(jrbtnUpdate.isSelected()){
                    int i, estado;

                    //Verificando si el estado es activo o inactivo
                    if(jrbtActivo.isSelected())
                        estado = 1;
                    else
                        estado = 0;

                    //verificamos si se ha cambiado la foto del repuesto
                    if(isPhotoChange)
                        i = resDao.updateRepuestosPhoto(jtfRepuesto.getText(), estado, jtfDescripcion.getText(), file, bite, idRepuesto);
                    else
                        i = resDao.updateRepuestos(jtfRepuesto.getText(), estado, jtfDescripcion.getText(), idRepuesto);

                    if(i > 0){
                        limpieza();
                        getRows();
                    } else
                        JOptionPane.showMessageDialog(null, "No se puede actualizar el repuesto");

                } else if(jrbtnDelete.isSelected()){
                    int i;

                    i = resDao.deleteRepuestos(idRepuesto);

                    if(i > 0){
                        limpieza();
                        getRows();
                    } else
                        JOptionPane.showMessageDialog(null, "No se puede eliminar el repuesto");
                }

                isPhotoChange = false;
                bite = 0;
            } else //fin de verificacion del estado
                JOptionPane.showMessageDialog(null, "Selecciona si el estado es activo o inactivo");
        } else //fin de validacion de campos
            JOptionPane.showMessageDialog(null, "No dejes campos vacios");
    }//GEN-LAST:event_jbtnAceptarActionPerformed

    private void jtblRepuestosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtblRepuestosMouseClicked
        if(jrbtnDelete.isSelected() || jrbtnUpdate.isSelected()){
            idRepuesto = (int) modeloRepuesto.getValueAt(jtblRepuestos.getSelectedRow(), 0);
            jtfRepuesto.setText((String) modeloRepuesto.getValueAt(jtblRepuestos.getSelectedRow(), 1));
            String es = (String) modeloRepuesto.getValueAt(jtblRepuestos.getSelectedRow(), 2);
            jtfDescripcion.setText((String) modeloRepuesto.getValueAt(jtblRepuestos.getSelectedRow(), 3));
            try {
                loadImage();
            } catch (IOException ex) {
                Logger.getLogger(Repuesto_Add.class.getName()).log(Level.SEVERE, null, ex);
            }

            if(es.equals("Activo"))
                jrbtActivo.setSelected(true);
            else
                jrbtInactivo.setSelected(true);
        }
    }//GEN-LAST:event_jtblRepuestosMouseClicked

    private void jrbtnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jrbtnAddActionPerformed
        // TODO add your handling code here:
        limpiar();
    }//GEN-LAST:event_jrbtnAddActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanelAcciones;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.ButtonGroup jbtgAcciones;
    private javax.swing.ButtonGroup jbtgEstado;
    private javax.swing.JButton jbtnAceptar;
    private javax.swing.JButton jbtnFoto;
    private javax.swing.JLabel jlblFoto;
    private javax.swing.JRadioButton jrbtActivo;
    private javax.swing.JRadioButton jrbtInactivo;
    private javax.swing.JRadioButton jrbtnAdd;
    private javax.swing.JRadioButton jrbtnDelete;
    private javax.swing.JRadioButton jrbtnUpdate;
    private javax.swing.JTable jtblRepuestos;
    private javax.swing.JTextArea jtfDescripcion;
    private javax.swing.JTextField jtfRepuesto;
    // End of variables declaration//GEN-END:variables
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EasyNotifyFramework
{
	class ProxyViewModelBase<ViewModel, Model> : ViewModelBase<ViewModel> where Model : INotifyPropertyChanged
	{
		#region Protected fields

		protected static Dictionary<string, List<IProperty<ViewModel>>> _dependencies = new Dictionary<string, List<IProperty<ViewModel>>>();
		protected Model _model;

		#endregion

		#region ProxyPropertyNotifier implementation
		protected class ProxyPropertyNotifier : PropertyNotifier
		{

			public ProxyPropertyNotifier AlsoRaises(params PropertyNotifier[] properties);
			public ProxyPropertyNotifier DependsOn(params Expression<Func<Model, object>>[] modelProperties);
			public ProxyPropertyNotifier DependsOn<PropertyType>(Expression<Func<Model, PropertyType>> modelProperty);

		}
		#endregion

		#region Ctor
		public ProxyViewModelBase(Model model)
		{

			_model = model;
			Register();
		}
		#endregion
		private static void SetDependency(string name, IProperty<ViewModel> property)
		{

		}

		private void model_PropertyChanged(object sender, PropertyChangedEventArgs e)
		{

			List<IProperty<ViewModel>> dependentProperties = null;
			if (!_dependencies.TryGetValue(e.PropertyName, out dependentProperties))
			{
				return;
			}

			foreach (var prop in dependentProperties)
			{

				RaisePropertyChange(prop);
			}
		}

		protected void Unregister()
		{
			_model.PropertyChanged -= model_PropertyChanged;
		}

		protected void Register()
		{
			_model.PropertyChanged += model_PropertyChanged;
		}

	}
}

redpajama_set_name: RedPajamaGithub


text:
package ldap

import (
	"crypto/x509"
	"fmt"
	"io/ioutil"
	"os"
	"strings"
	"unicode"
	"unicode/utf8"

	"github.com/openshift/library-go/pkg/certs"

	"gopkg.in/ldap.v2"

	"k8s.io/apimachinery/pkg/util/validation/field"

	legacyconfigv1 "github.com/openshift/api/legacyconfig/v1"
	"github.com/openshift/library-go/pkg/config/validation"
	"github.com/openshift/library-go/pkg/security/ldaputil"
)

func GetStringSourceFileReferences(s *legacyconfigv1.StringSource) []*string {
	if s == nil {
		return nil
	}
	return []*string{
		&s.File,
		&s.KeyFile,
	}
}

func ResolveStringValue(s legacyconfigv1.StringSource) (string, error) {
	var value string
	switch {
	case len(s.Value) > 0:
		value = s.Value
	case len(s.Env) > 0:
		value = os.Getenv(s.Env)
	case len(s.File) > 0:
		data, err := ioutil.ReadFile(s.File)
		if err != nil {
			return "", err
		}
		value = string(data)
	default:
		value = ""
	}

	if len(s.KeyFile) == 0 {
		// value is cleartext, return
		return value, nil
	}

	keyData, err := ioutil.ReadFile(s.KeyFile)
	if err != nil {
		return "", err
	}

	secretBlock, ok := certs.BlockFromBytes([]byte(value), certs.StringSourceEncryptedBlockType)
	if !ok {
		return "", fmt.Errorf("no valid PEM block of type %q found in data", certs.StringSourceEncryptedBlockType)
	}

	keyBlock, ok := certs.BlockFromBytes(keyData, certs.StringSourceKeyBlockType)
	if !ok {
		return "", fmt.Errorf("no valid PEM block of type %q found in key", certs.StringSourceKeyBlockType)
	}

	data, err := x509.DecryptPEMBlock(secretBlock, keyBlock.Bytes)
	return string(data), err
}

func ValidateLDAPSyncConfig(config *legacyconfigv1.LDAPSyncConfig) validation.ValidationResults {
	validationResults := validation.ValidationResults{}

	validationResults.Append(ValidateStringSource(config.BindPassword, field.NewPath("bindPassword")))
	bindPassword, _ := ResolveStringValue(config.BindPassword)
	validationResults.Append(ValidateLDAPClientConfig(config.URL, config.BindDN, bindPassword, config.CA, config.Insecure, nil))

	for ldapGroupUID, openShiftGroupName := range config.LDAPGroupUIDToOpenShiftGroupNameMapping {
		if len(ldapGroupUID) == 0 || len(openShiftGroupName) == 0 {
			validationResults.AddErrors(field.Invalid(field.NewPath("groupUIDNameMapping").Key(ldapGroupUID), openShiftGroupName, "has empty key or value"))
		}
	}

	schemaConfigsFound := []string{}

	if config.RFC2307Config != nil {
		configResults := ValidateRFC2307Config(config.RFC2307Config)
		validationResults.AddErrors(configResults.Errors...)
		validationResults.AddWarnings(configResults.Warnings...)
		schemaConfigsFound = append(schemaConfigsFound, "rfc2307")
	}
	if config.ActiveDirectoryConfig != nil {
		configResults := ValidateActiveDirectoryConfig(config.ActiveDirectoryConfig)
		validationResults.AddErrors(configResults.Errors...)
		validationResults.AddWarnings(configResults.Warnings...)
		schemaConfigsFound = append(schemaConfigsFound, "activeDirectory")
	}
	if config.AugmentedActiveDirectoryConfig != nil {
		configResults := ValidateAugmentedActiveDirectoryConfig(config.AugmentedActiveDirectoryConfig)
		validationResults.AddErrors(configResults.Errors...)
		validationResults.AddWarnings(configResults.Warnings...)
		schemaConfigsFound = append(schemaConfigsFound, "augmentedActiveDirectory")
	}

	if len(schemaConfigsFound) > 1 {
		validationResults.AddErrors(field.Invalid(field.NewPath("schema"), config, fmt.Sprintf("only one schema-specific config is allowed; found %v", schemaConfigsFound)))
	}
	if len(schemaConfigsFound) == 0 {
		validationResults.AddErrors(field.Required(field.NewPath("schema"), fmt.Sprintf("exactly one schema-specific config is required;  one of %v", []string{"rfc2307", "activeDirectory", "augmentedActiveDirectory"})))
	}

	return validationResults
}

func ValidateLDAPClientConfig(url, bindDN, bindPassword, CA string, insecure bool, fldPath *field.Path) validation.ValidationResults {
	validationResults := validation.ValidationResults{}

	if len(url) == 0 {
		validationResults.AddErrors(field.Required(fldPath.Child("url"), ""))
		return validationResults
	}

	u, err := ldaputil.ParseURL(url)
	if err != nil {
		validationResults.AddErrors(field.Invalid(fldPath.Child("url"), url, err.Error()))
		return validationResults
	}

	// Make sure bindDN and bindPassword are both set, or both unset
	// Both unset means an anonymous bind is used for search (https://tools.ietf.org/html/rfc4513#section-5.1.1)
	// Both set means the name/password simple bind is used for search (https://tools.ietf.org/html/rfc4513#section-5.1.3)
	if (len(bindDN) == 0) != (len(bindPassword) == 0) {
		validationResults.AddErrors(field.Invalid(fldPath.Child("bindDN"), bindDN,
			"bindDN and bindPassword must both be specified, or both be empty"))
		validationResults.AddErrors(field.Invalid(fldPath.Child("bindPassword"), "(masked)",
			"bindDN and bindPassword must both be specified, or both be empty"))
	}

	if insecure {
		if u.Scheme == ldaputil.SchemeLDAPS {
			validationResults.AddErrors(field.Invalid(fldPath.Child("url"), url,
				fmt.Sprintf("Cannot use %s scheme with insecure=true", u.Scheme)))
		}
		if len(CA) > 0 {
			validationResults.AddErrors(field.Invalid(fldPath.Child("ca"), CA,
				"Cannot specify a ca with insecure=true"))
		}
	} else {
		if len(CA) > 0 {
			validationResults.AddErrors(validation.ValidateFile(CA, fldPath.Child("ca"))...)
		}
	}

	// Warn if insecure
	if insecure {
		validationResults.AddWarnings(field.Invalid(fldPath.Child("insecure"), insecure,
			"validating passwords over an insecure connection could allow them to be intercepted"))
	}

	return validationResults
}

func ValidateRFC2307Config(config *legacyconfigv1.RFC2307Config) validation.ValidationResults {
	validationResults := validation.ValidationResults{}

	validationResults.Append(ValidateLDAPQuery(config.AllGroupsQuery, field.NewPath("groupsQuery")))
	if len(config.GroupUIDAttribute) == 0 {
		validationResults.AddErrors(field.Required(field.NewPath("groupUIDAttribute"), ""))
	}
	if len(config.GroupNameAttributes) == 0 {
		validationResults.AddErrors(field.Required(field.NewPath("groupNameAttributes"), ""))
	}
	if len(config.GroupMembershipAttributes) == 0 {
		validationResults.AddErrors(field.Required(field.NewPath("groupMembershipAttributes"), ""))
	}

	isUserDNQuery := strings.TrimSpace(strings.ToLower(config.UserUIDAttribute)) == "dn"
	validationResults.Append(validateLDAPQuery(config.AllUsersQuery, field.NewPath("usersQuery"), isUserDNQuery))
	if len(config.UserUIDAttribute) == 0 {
		validationResults.AddErrors(field.Required(field.NewPath("userUIDAttribute"), ""))
	}
	if len(config.UserNameAttributes) == 0 {
		validationResults.AddErrors(field.Required(field.NewPath("userNameAttributes"), ""))
	}

	return validationResults
}

func ValidateActiveDirectoryConfig(config *legacyconfigv1.ActiveDirectoryConfig) validation.ValidationResults {
	validationResults := validation.ValidationResults{}

	validationResults.Append(ValidateLDAPQuery(config.AllUsersQuery, field.NewPath("usersQuery")))
	if len(config.UserNameAttributes) == 0 {
		validationResults.AddErrors(field.Required(field.NewPath("userNameAttributes"), ""))
	}
	if len(config.GroupMembershipAttributes) == 0 {
		validationResults.AddErrors(field.Required(field.NewPath("groupMembershipAttributes"), ""))
	}

	return validationResults
}

func ValidateAugmentedActiveDirectoryConfig(config *legacyconfigv1.AugmentedActiveDirectoryConfig) validation.ValidationResults {
	validationResults := validation.ValidationResults{}

	validationResults.Append(ValidateLDAPQuery(config.AllUsersQuery, field.NewPath("usersQuery")))
	if len(config.UserNameAttributes) == 0 {
		validationResults.AddErrors(field.Required(field.NewPath("userNameAttributes"), ""))
	}
	if len(config.GroupMembershipAttributes) == 0 {
		validationResults.AddErrors(field.Required(field.NewPath("groupMembershipAttributes"), ""))
	}

	isGroupDNQuery := strings.TrimSpace(strings.ToLower(config.GroupUIDAttribute)) == "dn"
	validationResults.Append(validateLDAPQuery(config.AllGroupsQuery, field.NewPath("groupsQuery"), isGroupDNQuery))
	if len(config.GroupUIDAttribute) == 0 {
		validationResults.AddErrors(field.Required(field.NewPath("groupUIDAttribute"), ""))
	}
	if len(config.GroupNameAttributes) == 0 {
		validationResults.AddErrors(field.Required(field.NewPath("groupNameAttributes"), ""))
	}

	return validationResults
}

func ValidateLDAPQuery(query legacyconfigv1.LDAPQuery, fldPath *field.Path) validation.ValidationResults {
	return validateLDAPQuery(query, fldPath, false)
}
func validateLDAPQuery(query legacyconfigv1.LDAPQuery, fldPath *field.Path, isDNOnly bool) validation.ValidationResults {
	validationResults := validation.ValidationResults{}

	if _, err := ldap.ParseDN(query.BaseDN); err != nil {
		validationResults.AddErrors(field.Invalid(fldPath.Child("baseDN"), query.BaseDN,
			fmt.Sprintf("invalid base DN for search: %v", err)))
	}

	if len(query.Scope) > 0 {
		if _, err := ldaputil.DetermineLDAPScope(query.Scope); err != nil {
			validationResults.AddErrors(field.Invalid(fldPath.Child("scope"), query.Scope,
				"invalid LDAP search scope"))
		}
	}

	if len(query.DerefAliases) > 0 {
		if _, err := ldaputil.DetermineDerefAliasesBehavior(query.DerefAliases); err != nil {
			validationResults.AddErrors(field.Invalid(fldPath.Child("derefAliases"),
				query.DerefAliases, "LDAP alias dereferencing instruction invalid"))
		}
	}

	if query.TimeLimit < 0 {
		validationResults.AddErrors(field.Invalid(fldPath.Child("timeout"), query.TimeLimit,
			"timeout must be equal to or greater than zero"))
	}

	if isDNOnly {
		if len(query.Filter) != 0 {
			validationResults.AddErrors(field.Invalid(fldPath.Child("filter"), query.Filter, `cannot specify a filter when using "dn" as the UID attribute`))
		}
		return validationResults
	}

	if _, err := ldap.CompileFilter(query.Filter); err != nil {
		validationResults.AddErrors(field.Invalid(fldPath.Child("filter"), query.Filter,
			fmt.Sprintf("invalid query filter: %v", err)))
	}

	return validationResults
}

func ValidateStringSource(s legacyconfigv1.StringSource, fieldPath *field.Path) validation.ValidationResults {
	validationResults := validation.ValidationResults{}
	methods := 0
	if len(s.Value) > 0 {
		methods++
	}
	if len(s.File) > 0 {
		methods++
		fileErrors := validation.ValidateFile(s.File, fieldPath.Child("file"))
		validationResults.AddErrors(fileErrors...)

		// If the file was otherwise ok, and its value will be used verbatim, warn about trailing whitespace
		if len(fileErrors) == 0 && len(s.KeyFile) == 0 {
			if data, err := ioutil.ReadFile(s.File); err != nil {
				validationResults.AddErrors(field.Invalid(fieldPath.Child("file"), s.File, fmt.Sprintf("could not read file: %v", err)))
			} else if len(data) > 0 {
				r, _ := utf8.DecodeLastRune(data)
				if unicode.IsSpace(r) {
					validationResults.AddWarnings(field.Invalid(fieldPath.Child("file"), s.File, "contains trailing whitespace which will be included in the value"))
				}
			}
		}
	}
	if len(s.Env) > 0 {
		methods++
	}
	if methods > 1 {
		validationResults.AddErrors(field.Invalid(fieldPath, "", "only one of value, file, and env can be specified"))
	}

	if len(s.KeyFile) > 0 {
		validationResults.AddErrors(validation.ValidateFile(s.KeyFile, fieldPath.Child("keyFile"))...)
	}

	return validationResults
}


text:
<component name="ProjectRunConfigurationManager">
  <configuration default="false" name="RKCalendarLink" type="AppleRunConfiguration" factoryName="Application" WORKING_DIR="" PASS_PARENT_ENVS="FALSE" PROJECT_NAME="RKCalendarLink" TARGET_NAME="RKCalendarLink" CONFIG_NAME="Debug" SCHEME_NAME="RKCalendarLink" RUN_TARGET_PROJECT_NAME="RKCalendarLink" RUN_TARGET_NAME="RKCalendarLink" MAKE_ACTIVE="TRUE" WAIT_FOR="FALSE">
    <envs />
    <RunnerSettings RunnerId="AppRunner" />
    <ConfigurationWrapper RunnerId="AppRunner" />
    <method />
  </configuration>
</component>


text:
require "spec_helper"
require "chef/version_constraint"

describe Chef::VersionConstraint do
  describe "validation" do
    bad_version = [">= 1.2.z", "> 1.2.3 < 5.0", "> 1.2.3, < 5.0"]
    bad_op = ["> >", ">$ 1.2.3", "! 3.4"]
    o_error = Chef::Exceptions::InvalidVersionConstraint
    v_error = Chef::Exceptions::InvalidCookbookVersion
    bad_version.each do |s|
      it "should raise #{v_error} when given #{s}" do
        expect { Chef::VersionConstraint.new s }.to raise_error(v_error)
      end
    end
    bad_op.each do |s|
      it "should raise #{o_error} when given #{s}" do
        expect { Chef::VersionConstraint.new s }.to raise_error(o_error)
      end
    end

    it "should interpret a lone version number as implicit = OP" do
      vc = Chef::VersionConstraint.new("1.2.3")
      expect(vc.to_s).to eq("= 1.2.3")
    end

    it "should allow initialization with [] for back compatibility" do
      Chef::VersionConstraint.new([]) == Chef::VersionConstraint.new
    end

    it "should allow initialization with ['1.2.3'] for back compatibility" do
      Chef::VersionConstraint.new(["1.2"]) == Chef::VersionConstraint.new("1.2")
    end

  end

  it "should default to >= 0.0.0" do
    vc = Chef::VersionConstraint.new
    expect(vc.to_s).to eq(">= 0.0.0")
  end

  it "should default to >= 0.0.0 when initialized with nil" do
    expect(Chef::VersionConstraint.new(nil).to_s).to eq(">= 0.0.0")
  end

  it "should work with Chef::Version classes" do
    vc = Chef::VersionConstraint.new("1.0")
    expect(vc.version).to be_an_instance_of(Chef::Version)
  end

  it "should allow ops without space separator" do
    expect(Chef::VersionConstraint.new("=1.2.3")).to eql(Chef::VersionConstraint.new("= 1.2.3"))
    expect(Chef::VersionConstraint.new(">1.2.3")).to eql(Chef::VersionConstraint.new("> 1.2.3"))
    expect(Chef::VersionConstraint.new("<1.2.3")).to eql(Chef::VersionConstraint.new("< 1.2.3"))
    expect(Chef::VersionConstraint.new(">=1.2.3")).to eql(Chef::VersionConstraint.new(">= 1.2.3"))
    expect(Chef::VersionConstraint.new("<=1.2.3")).to eql(Chef::VersionConstraint.new("<= 1.2.3"))
  end

  it "should allow ops with multiple spaces" do
    expect(Chef::VersionConstraint.new("=  1.2.3")).to eql(Chef::VersionConstraint.new("= 1.2.3"))
  end

  describe "include?" do
    describe "handles various input data types" do
      before do
        @vc = Chef::VersionConstraint.new "> 1.2.3"
      end
      it "String" do
        expect(@vc).to include "1.4"
      end
      it "Chef::Version" do
        expect(@vc).to include Chef::Version.new("1.4")
      end
      it "Chef::CookbookVersion" do
        cv = Chef::CookbookVersion.new("alice", "/tmp/blah.txt")
        cv.version = "1.4"
        expect(@vc).to include cv
      end
    end

    it "strictly less than" do
      vc = Chef::VersionConstraint.new "< 1.2.3"
      expect(vc).not_to include "1.3.0"
      expect(vc).not_to include "1.2.3"
      expect(vc).to include "1.2.2"
    end

    it "strictly greater than" do
      vc = Chef::VersionConstraint.new "> 1.2.3"
      expect(vc).to include "1.3.0"
      expect(vc).not_to include "1.2.3"
      expect(vc).not_to include "1.2.2"
    end

    it "less than or equal to" do
      vc = Chef::VersionConstraint.new "<= 1.2.3"
      expect(vc).not_to include "1.3.0"
      expect(vc).to include "1.2.3"
      expect(vc).to include "1.2.2"
    end

    it "greater than or equal to" do
      vc = Chef::VersionConstraint.new ">= 1.2.3"
      expect(vc).to include "1.3.0"
      expect(vc).to include "1.2.3"
      expect(vc).not_to include "1.2.2"
    end

    it "equal to" do
      vc = Chef::VersionConstraint.new "= 1.2.3"
      expect(vc).not_to include "1.3.0"
      expect(vc).to include "1.2.3"
      expect(vc).not_to include "0.3.0"
    end

    it "pessimistic ~> x.y.z" do
      vc = Chef::VersionConstraint.new "~> 1.2.3"
      expect(vc).to include "1.2.3"
      expect(vc).to include "1.2.4"

      expect(vc).not_to include "1.2.2"
      expect(vc).not_to include "1.3.0"
      expect(vc).not_to include "2.0.0"
    end

    it "pessimistic ~> x.y" do
      vc = Chef::VersionConstraint.new "~> 1.2"
      expect(vc).to include "1.3.3"
      expect(vc).to include "1.4"

      expect(vc).not_to include "2.2"
      expect(vc).not_to include "0.3.0"
    end
  end

  describe "to_s" do
    it "shows a patch-level if one is given" do
      vc = Chef::VersionConstraint.new "~> 1.2.0"

      expect(vc.to_s).to eq("~> 1.2.0")
    end

    it "shows no patch-level if one is not given" do
      vc = Chef::VersionConstraint.new "~> 1.2"

      expect(vc.to_s).to eq("~> 1.2")
    end
  end

  describe "inspect" do
    it "shows a patch-level if one is given" do
      vc = Chef::VersionConstraint.new "~> 1.2.0"

      expect(vc.inspect).to eq("(~> 1.2.0)")
    end

    it "shows no patch-level if one is not given" do
      vc = Chef::VersionConstraint.new "~> 1.2"

      expect(vc.inspect).to eq("(~> 1.2)")
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
    <?xml-stylesheet type="text/xsl" href="./testcase.xsl"?>
<test_definition>
  <suite name="tct-mediacapture-w3c-tests" category="W3C/HTML5 APIs">
    <set name="MediaCapture" type="js">
      <testcase component="WebAPI/Media/HTML Media Capture" execution_type="auto" id="HTMLInputElement_exist" purpose="Check if the interface HTMLInputElement exists">
        <description>
          <test_script_entry>/opt/tct-mediacapture-w3c-tests/mediacapture/HTMLInputElement_attribute.html?total_num=4&amp;locator_key=id&amp;value=1</test_script_entry>
        </description>
        </testcase>
      <testcase component="WebAPI/Media/HTML Media Capture" execution_type="auto" id="HTMLInputElement_type" purpose="Check if the type of HTMLInputElement is object">
        <description>
          <test_script_entry>/opt/tct-mediacapture-w3c-tests/mediacapture/HTMLInputElement_attribute.html?total_num=4&amp;locator_key=id&amp;value=2</test_script_entry>
        </description>
        </testcase>
      <testcase component="WebAPI/Media/HTML Media Capture" execution_type="auto" id="HTMLInputElement_capture_exist" purpose="Check if the attribute capture exists">
        <description>
          <test_script_entry>/opt/tct-mediacapture-w3c-tests/mediacapture/HTMLInputElement_attribute.html?total_num=4&amp;locator_key=id&amp;value=3</test_script_entry>
        </description>
        </testcase>
      <testcase component="WebAPI/Media/HTML Media Capture" execution_type="auto" id="HTMLInputElement_capture_type" purpose="Check if the type of HTMLInputElement.capture is boolean">
        <description>
          <test_script_entry>/opt/tct-mediacapture-w3c-tests/mediacapture/HTMLInputElement_attribute.html?total_num=4&amp;locator_key=id&amp;value=4</test_script_entry>
        </description>
        </testcase>
      <testcase component="WebAPI/Media/HTML Media Capture" execution_type="manual" id="capture_video" purpose="Check if the input will accept an video when capture set to acmcorder">
        <description>
          <steps>
            <pre_condition/>
            <step order="1">
              <step_desc>Click the button, allow microphone and camera access, and start to capture a video</step_desc>
              <expected>There appears a video capture screen, there is a way to disable the audio record, and there is a way to stop the video capture.</expected>
            </step>
          </steps>
          <test_script_entry>/opt/tct-mediacapture-w3c-tests/mediacapture/capture_video-manual.html</test_script_entry>
        </description>
        </testcase>
    </set>
  </suite>
</test_definition>


text:
@interface HYHeadImageCell()<UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong) UICollectionView *myCollectionView;
@property (strong, nonatomic) UIImageView *iconUserView;
@property (strong, nonatomic) UIButton *bigBtn;
@property (strong, nonatomic) UILabel *titleLabel;
@property (strong, nonatomic) UIButton *smallBtn;

@end

static NSString *HYHeadImageCollectionCellID = @"HYHeadImageCollectionCellID";

@implementation HYHeadImageCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self setupUI];
    }
    return self;
}

-(void)setupUI{
    if (nil == _myCollectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
        flowLayout.minimumLineSpacing = 0;
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.itemSize = CGSizeMake(KScreen_Width, HYHeadImageCellHeight);
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;

        _myCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, KScreen_Width, HYHeadImageCellHeight) collectionViewLayout:flowLayout];
        _myCollectionView.delegate = self;
        _myCollectionView.dataSource = self;
        _myCollectionView.backgroundColor = [UIColor whiteColor];
        _myCollectionView.pagingEnabled = YES;
        _myCollectionView.bounces = NO;
        [_myCollectionView registerClass: [HYHeadImageCollectionCell class] forCellWithReuseIdentifier:HYHeadImageCollectionCellID];
        [self.contentView addSubview:_myCollectionView];
    }
    if (nil == _iconUserView) {
        _iconUserView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, KScreen_Width, HYHeadImageCellHeight)];
        _iconUserView.image = [UIImage imageNamed:@"imagepub_back"];
        [self.contentView addSubview:_iconUserView];
    }
    if (nil == _bigBtn) {
        _bigBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 80, 80)];
        _bigBtn.center = _iconUserView.center;
        _bigBtn.centerY = _iconUserView.centerY - 20;
        [_bigBtn setBackgroundImage:[UIImage imageNamed:@"imagepub_add_big"] forState:UIControlStateNormal];
        [_bigBtn addTarget:self action:@selector(clickButton) forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:_bigBtn];
    }
    if (nil == _titleLabel) {
        _titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, _bigBtn.bottom, KScreen_Width - 20, 30)];
        _titleLabel.text = @"拍个照呗";
        _titleLabel.textColor = [UIColor whiteColor];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        [self.contentView addSubview:_titleLabel];
    }
    if (nil == _smallBtn) {
        _smallBtn = [[UIButton alloc]initWithFrame:CGRectMake(KScreen_Width - 44, HYHeadImageCellHeight - 44, 44, 44)];
        [_smallBtn setBackgroundImage:[UIImage imageNamed:@"imagepub_add_small"] forState:UIControlStateNormal];
        [_smallBtn addTarget:self action:@selector(clickButton) forControlEvents:UIControlEventTouchUpInside];
        _smallBtn.hidden = YES;
        [self.contentView addSubview:_smallBtn];
    }
}
-(void)clickButton{
    if (self.myBlock) {
        self.myBlock();
    }

}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.photoArr.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    HYHeadImageCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:HYHeadImageCollectionCellID forIndexPath:indexPath];

    cell.iconImageView.image = self.photoArr[indexPath.item];
    cell.iconImageView.contentMode = UIViewContentModeScaleAspectFill;

    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    HYHeadImageCollectionCell *cell = (HYHeadImageCollectionCell *)[collectionView cellForItemAtIndexPath:indexPath];
    [ZLShowBigImage showBigImage:cell.iconImageView];
}

-(void)setPhotoArr:(NSArray *)photoArr{
    _photoArr = photoArr;
    if (photoArr.count > 0) {
        self.iconUserView.hidden = YES;
        self.titleLabel.hidden = YES;
        self.bigBtn.hidden = YES;
        self.smallBtn.hidden = NO;
    }
    [self.myCollectionView reloadData];
}

@end

@implementation HYHeadImageCollectionCell

-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        if (nil == _iconImageView) {
            _iconImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, KScreen_Width, HYHeadImageCellHeight)];
            [self.contentView addSubview:_iconImageView];
        }
    }
    return self;
}

@end


text:
<!-- ChromeFrame Support -->
<meta http-equiv="X-UA-Compatible" content="IE=9;chrome=1">
<!doctype html>

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
   <head>
      <title>Tutorial Fourteen</title>

      <!-- Load the main engine script -->
      <script type="text/javascript" src="../../engine/runtime/engine.js"></script>
      <style type="text/css">
         .ui.buttoncontrol {
            font-weight: bold;
         }

         .ui.buttoncontrol.mouseover {
            background-color: navy;
            color: white;
         }
      </style>
   </head>
   <body>
      <script type="text/javascript">
         // Load the game script
         R.Engine.loadGame('game.js','Tutorial14', 'Tutorial 14: Data Storage');
      </script>
   </body>
</html>


text:
'''
Copyright (c) 2016, Battelle Memorial Institute
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
'''

'''
This material was prepared as an account of work sponsored by an
agency of the United States Government.  Neither the United States
Government nor the United States Department of Energy, nor Battelle,
nor any of their employees, nor any jurisdiction or organization
that has cooperated in the development of these materials, makes
any warranty, express or implied, or assumes any legal liability
or responsibility for the accuracy, completeness, or usefulness or
any information, apparatus, product, software, or process disclosed,
or represents that its use would not infringe privately owned rights.

Reference herein to any specific commercial product, process, or
service by trade name, trademark, manufacturer, or otherwise does
not necessarily constitute or imply its endorsement, recommendation,
r favoring by the United States Government or any agency thereof,
or Battelle Memorial Institute. The views and opinions of authors
expressed herein do not necessarily state or reflect those of the
United States Government or any agency thereof.

PACIFIC NORTHWEST NATIONAL LABORATORY
operated by BATTELLE for the UNITED STATES DEPARTMENT OF ENERGY
under Contract DE-AC05-76RL01830
'''

__docformat__ = 'reStructuredText'

"""The cdriver is an example implementation of an interface that
allows the master driver to transparently call C code.
This file is an `interface` and will only be usable in the
master_driver/interfaces directory. The shared object will
need to be somewhere it can be found by this file.
"""

from StringIO import StringIO
from csv import DictReader

from master_driver.interfaces import BasicRevert, BaseInterface, BaseRegister

from ctypes import *

def so_lookup_function(shared_object, function_name):
    """Attempt to find a symbol in the loaded shared object
    or raise an IOerror.

    :param shared_object:
    :type shared_object: shared object
    :param function_name:
    :type function_name: string
    :returns: function or raises an exception
    """
    try:
        function = getattr(shared_object, function_name)
    except AttributeError:
        raise IOError("No such function in shared object: {}".format(function_name))

    return function

class CRegister(BaseRegister):
    def __init__(self,read_only, pointName, units, description = ''):
        super(CRegister, self).__init__("byte", read_only, pointName, units, description = '')

class Interface(BasicRevert, BaseInterface):
    """Simple interface that calls c code.
    Function names are constructed based on register
    point names for brevity. Few if any APIs will
    support this.
    """
    def __init__(self, **kwargs):
        super(Interface, self).__init__(**kwargs)

    def configure(self, config_dict, registry_config_str):
        so_filename = config_dict['shared_object']
        cdll.LoadLibrary(so_filename)
        self.shared_object = CDLL(so_filename)
        self.parse_config(registry_config_str)

    def get_point(self, point_name):
        register = self.get_register_by_name(point_name)
        so_get_point = so_lookup_function(self.shared_object,
                                          "get_" + register.point_name)
        return so_get_point()

    def _set_point(self, point_name, value):
        register = self.get_register_by_name(point_name)
        if register.read_only:
            raise  IOError("Trying to write to a point configured read only: "+point_name)

        so_set_point = so_lookup_function(self.shared_object,
                                          "set_" + register.point_name)
        so_set_point(value)

    def _scrape_all(self):
        result = {}
        read_registers = self.get_registers_by_type("byte", True)
        write_registers = self.get_registers_by_type("byte", False)
        for register in read_registers + write_registers:
            result[register.point_name] = self.get_point(register.point_name)

        return result

    def parse_config(self, configDict):
        if configDict is None:
            return

        for regDef in configDict:
            #Skip lines that have no address yet.
            if not regDef['Point Name']:
                continue

            read_only = regDef['Writable'].lower() != 'true'
            point_name = regDef['Volttron Point Name']
            description = regDef['Notes']
            units = regDef['Units']
            register = CRegister(read_only, point_name, units, description=description)

            self.insert_register(register)


text:
var qunit = require('node-qunit-phantomjs');

qunit('./test/qunit.html', { 'verbose': true });


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>SingleColumnRestriction.Contains (apache-cassandra API)</title>
<meta name="date" content="2014-11-05">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.cassandra.cql3.statements

Class SingleColumnRestriction.Contains

java.lang.Object

org.apache.cassandra.cql3.statements.SingleColumnRestriction

org.apache.cassandra.cql3.statements.SingleColumnRestriction.Contains

All Implemented Interfaces:

Restriction

Enclosing class:

SingleColumnRestriction

public static class SingleColumnRestriction.Contains
extends SingleColumnRestriction

Nested Class Summary

Nested classes/interfaces inherited from class org.apache.cassandra.cql3.statements.SingleColumnRestriction

SingleColumnRestriction.Contains, SingleColumnRestriction.EQ, SingleColumnRestriction.InWithMarker, SingleColumnRestriction.InWithValues, SingleColumnRestriction.Slice

Nested classes/interfaces inherited from interface org.apache.cassandra.cql3.statements.Restriction

Restriction.IN

Constructor Summary

Constructors

Constructor and Description

SingleColumnRestriction.Contains()

Method Summary

Methods

Modifier and Type
Method and Description

void
add(Term t,
   boolean isKey)

void
addKey(Term t)

void
addValue(Term t)

boolean
hasContains()

boolean
hasContainsKey()

boolean
isContains()

boolean
isEQ()

boolean
isIN()

boolean
isOnToken()

boolean
isSlice()

java.util.List<java.nio.ByteBuffer>
keys(QueryOptions options)

int
numberOfKeys()

int
numberOfValues()

java.lang.String
toString()

java.util.List<java.nio.ByteBuffer>
values(QueryOptions options)

Methods inherited from class org.apache.cassandra.cql3.statements.SingleColumnRestriction

isMultiColumn

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

SingleColumnRestriction.Contains

public SingleColumnRestriction.Contains()

Method Detail

hasContains

public boolean hasContains()

hasContainsKey

public boolean hasContainsKey()

numberOfValues

public int numberOfValues()

numberOfKeys

public int numberOfKeys()

add

public void add(Term t,
       boolean isKey)

addValue

public void addValue(Term t)

addKey

public void addKey(Term t)

values

public java.util.List<java.nio.ByteBuffer> values(QueryOptions options)
                                           throws InvalidRequestException

Throws:

InvalidRequestException

keys

public java.util.List<java.nio.ByteBuffer> keys(QueryOptions options)
                                         throws InvalidRequestException

Throws:

InvalidRequestException

isSlice

public boolean isSlice()

isEQ

public boolean isEQ()

isIN

public boolean isIN()

isContains

public boolean isContains()

isOnToken

public boolean isOnToken()

toString

public java.lang.String toString()

Overrides:

toString in class java.lang.Object

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2014 The Apache Software Foundation


text:
package com.saicmotor.property.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.saicmotor.framework.conf.GlobalConfig;
import com.saicmotor.framework.persistence.Page;
import com.saicmotor.framework.web.BaseController;
import com.saicmotor.framework.utils.DateUtils;
import com.saicmotor.framework.utils.StringUtils;
import com.saicmotor.property.entity.TmPropertyDelete;
import com.saicmotor.property.entity.TmPropertyInfo;
import com.saicmotor.property.entity.TmPropertyQuery;
import com.saicmotor.property.service.TmPropertyDeleteService;
import com.saicmotor.property.service.TmPropertyInfoService;
import com.saicmotor.property.service.TmPropertyQueryService;
import com.saicmotor.sales.entity.TmSalesInfo;
import com.saicmotor.sys.excel.ExportExcelSales;
import com.saicmotor.sys.service.AreaService;

/**
 * 综合查询Controller
 * @author zcj
 * @version 2016-05-26
 */
@Controller
@RequestMapping(value = "${adminPath}/property/tmPropertyQuery")
public class TmPropertyQueryController extends BaseController {

	@Autowired
	private TmPropertyQueryService tmPropertyQueryService;

	@ModelAttribute
	public TmPropertyQuery get(@RequestParam(required=false) String id) {
		TmPropertyQuery entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = tmPropertyQueryService.get(id);
		}
		if (entity == null){
			entity = new TmPropertyQuery();
		}
		return entity;
	}

	@RequiresPermissions("property:tmPropertyQuery:view")
	@RequestMapping(value = {"list", ""})
	public String list(TmPropertyQuery tmPropertyQuery, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<TmPropertyQuery> page = tmPropertyQueryService.findPage(new Page<TmPropertyQuery>(request, response), tmPropertyQuery);
		model.addAttribute("page", page);

		return "modules/property/tmPropertyInfoQuery";
	}

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="API documentation for the Rust `texture` mod in crate `glium`.">
    <meta name="keywords" content="rust, rustlang, rust-lang, texture">

    <title>glium::texture - Rust</title>

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

glium

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options..."
                       type="search">

        </form>

Module glium::<wbr>texture

                [−]

        [src]

A texture is an image loaded in video memory, which can be sampled in your shaders.

Textures come in ten different dimensions:

Textures with one dimension.

Textures with two dimensions.

Textures with two dimensions and multisampling enabled.

Textures with three dimensions.

Cube textures, which are arrays of six two-dimensional textures
corresponding to the six faces of a cube.

Arrays of one-dimensional textures.

Arrays of two-dimensional textures.

Arrays of two-dimensional textures with multisampling enabled.

Arrays of cube textures.

Buffer textures, which are one-dimensional textures that are mapped to a buffer.

In addition to this, there are six kinds of texture formats:

The texture contains floating-point data,
with either the Compressed prefix or no prefix at all.

The texture contains signed integers, with the Integral prefix.

The texture contains unsigned integers, with the Unsigned prefix.

The texture contains depth information, with the Depth prefix.

The texture contains stencil information, with the Stencil prefix.

The texture contains depth and stencil information, with the DepthStencil prefix.

Each combination of dimensions and format corresponds to a sampler type in GLSL. For example,
an IntegralTexture3d can only be bound to an isampler3D uniform in GLSL. Some combinations
don't exist, like DepthBufferTexture.

The difference between compressed textures and uncompressed textures is that you can't do
render-to-texture on the former.

The most common types of textures are CompressedTexture2d and Texture2d (the two dimensions
being the width and height). These are what you will use most of the time.

Structs

                        CompressedSrgbTexture1d

A one-dimensional texture  containing sRGB floating-point data.

                        CompressedSrgbTexture1dArray

An array of one-dimensional textures  containing sRGB floating-point data.

                        CompressedSrgbTexture1dArrayLayer

Represents a single layer of a CompressedSrgbTexture1dArray.

                        CompressedSrgbTexture1dArrayMipmap

Represents a single mipmap level of a CompressedSrgbTexture1dArray.

                        CompressedSrgbTexture1dMipmap

Represents a single mipmap level of a CompressedSrgbTexture1d.

                        CompressedSrgbTexture2d

A two-dimensional texture  containing sRGB floating-point data.

                        CompressedSrgbTexture2dArray

An array of two-dimensional textures  containing sRGB floating-point data.

                        CompressedSrgbTexture2dArrayLayer

Represents a single layer of a CompressedSrgbTexture2dArray.

                        CompressedSrgbTexture2dArrayMipmap

Represents a single mipmap level of a CompressedSrgbTexture2dArray.

                        CompressedSrgbTexture2dMipmap

Represents a single mipmap level of a CompressedSrgbTexture2d.

                        CompressedSrgbTexture3d

A three-dimensional texture  containing sRGB floating-point data.

                        CompressedSrgbTexture3dMipmap

Represents a single mipmap level of a CompressedSrgbTexture3d.

                        CompressedTexture1d

A compressed one-dimensional texture  containing floating-point data.

                        CompressedTexture1dArray

An array of compressed one-dimensional textures  containing floating-point data.

                        CompressedTexture1dArrayLayer

Represents a single layer of a CompressedTexture1dArray.

                        CompressedTexture1dArrayMipmap

Represents a single mipmap level of a CompressedTexture1dArray.

                        CompressedTexture1dMipmap

Represents a single mipmap level of a CompressedTexture1d.

                        CompressedTexture2d

A compressed two-dimensional texture  containing floating-point data.

                        CompressedTexture2dArray

An array of compressed two-dimensional textures  containing floating-point data.

                        CompressedTexture2dArrayLayer

Represents a single layer of a CompressedTexture2dArray.

                        CompressedTexture2dArrayMipmap

Represents a single mipmap level of a CompressedTexture2dArray.

                        CompressedTexture2dMipmap

Represents a single mipmap level of a CompressedTexture2d.

                        CompressedTexture3d

A compressed three-dimensional texture  containing floating-point data.

                        CompressedTexture3dMipmap

Represents a single mipmap level of a CompressedTexture3d.

                        DepthStencilTexture1d

A one-dimensional texture  containing both depth and stencil data.

                        DepthStencilTexture1dArray

An array of one-dimensional textures  containing both depth and stencil data.

                        DepthStencilTexture1dArrayLayer

Represents a single layer of a DepthStencilTexture1dArray.

                        DepthStencilTexture1dArrayMipmap

Represents a single mipmap level of a DepthStencilTexture1dArray.

                        DepthStencilTexture1dMipmap

Represents a single mipmap level of a DepthStencilTexture1d.

                        DepthStencilTexture2d

A two-dimensional texture  containing both depth and stencil data.

                        DepthStencilTexture2dArray

An array of two-dimensional textures  containing both depth and stencil data.

                        DepthStencilTexture2dArrayLayer

Represents a single layer of a DepthStencilTexture2dArray.

                        DepthStencilTexture2dArrayMipmap

Represents a single mipmap level of a DepthStencilTexture2dArray.

                        DepthStencilTexture2dMipmap

Represents a single mipmap level of a DepthStencilTexture2d.

                        DepthStencilTexture2dMultisample

A two-dimensional texture  containing both depth and stencil data.

                        DepthStencilTexture2dMultisampleArray

An array of two-dimensional textures  containing both depth and stencil data.

                        DepthStencilTexture2dMultisampleArrayMipmap

Represents a single mipmap level of a DepthStencilTexture2dMultisampleArray.

                        DepthStencilTexture2dMultisampleMipmap

Represents a single mipmap level of a DepthStencilTexture2dMultisample.

                        DepthStencilTexture3d

A three-dimensional texture  containing both depth and stencil data.

                        DepthStencilTexture3dMipmap

Represents a single mipmap level of a DepthStencilTexture3d.

                        DepthTexture1d

A one-dimensional texture  containing depth data.

                        DepthTexture1dArray

An array of one-dimensional textures  containing depth data.

                        DepthTexture1dArrayLayer

Represents a single layer of a DepthTexture1dArray.

                        DepthTexture1dArrayMipmap

Represents a single mipmap level of a DepthTexture1dArray.

                        DepthTexture1dMipmap

Represents a single mipmap level of a DepthTexture1d.

                        DepthTexture2d

A two-dimensional texture  containing depth data.

                        DepthTexture2dArray

An array of two-dimensional textures  containing depth data.

                        DepthTexture2dArrayLayer

Represents a single layer of a DepthTexture2dArray.

                        DepthTexture2dArrayMipmap

Represents a single mipmap level of a DepthTexture2dArray.

                        DepthTexture2dMipmap

Represents a single mipmap level of a DepthTexture2d.

                        DepthTexture2dMultisample

A two-dimensional texture  containing depth data.

                        DepthTexture2dMultisampleArray

An array of two-dimensional textures  containing depth data.

                        DepthTexture2dMultisampleArrayMipmap

Represents a single mipmap level of a DepthTexture2dMultisampleArray.

                        DepthTexture2dMultisampleMipmap

Represents a single mipmap level of a DepthTexture2dMultisample.

                        DepthTexture3d

A three-dimensional texture  containing depth data.

                        DepthTexture3dMipmap

Represents a single mipmap level of a DepthTexture3d.

                        IntegralTexture1d

A one-dimensional texture  containing signed integral data.

                        IntegralTexture1dArray

An array of one-dimensional textures  containing signed integral data.

                        IntegralTexture1dArrayLayer

Represents a single layer of a IntegralTexture1dArray.

                        IntegralTexture1dArrayMipmap

Represents a single mipmap level of a IntegralTexture1dArray.

                        IntegralTexture1dMipmap

Represents a single mipmap level of a IntegralTexture1d.

                        IntegralTexture2d

A two-dimensional texture  containing signed integral data.

                        IntegralTexture2dArray

An array of two-dimensional textures  containing signed integral data.

                        IntegralTexture2dArrayLayer

Represents a single layer of a IntegralTexture2dArray.

                        IntegralTexture2dArrayMipmap

Represents a single mipmap level of a IntegralTexture2dArray.

                        IntegralTexture2dMipmap

Represents a single mipmap level of a IntegralTexture2d.

                        IntegralTexture2dMultisample

A two-dimensional texture  containing signed integral data.

                        IntegralTexture2dMultisampleArray

An array of two-dimensional textures  containing signed integral data.

                        IntegralTexture2dMultisampleArrayMipmap

Represents a single mipmap level of a IntegralTexture2dMultisampleArray.

                        IntegralTexture2dMultisampleMipmap

Represents a single mipmap level of a IntegralTexture2dMultisample.

                        IntegralTexture3d

A three-dimensional texture  containing signed integral data.

                        IntegralTexture3dMipmap

Represents a single mipmap level of a IntegralTexture3d.

                        RawImage1d

Represents raw data for a two-dimensional image.

                        RawImage2d

Represents raw data for a two-dimensional image.

                        RawImage3d

Represents raw data for a two-dimensional image.

                        SrgbTexture1d

A one-dimensional texture  containing sRGB floating-point data.

                        SrgbTexture1dArray

An array of one-dimensional textures  containing sRGB floating-point data.

                        SrgbTexture1dArrayLayer

Represents a single layer of a SrgbTexture1dArray.

                        SrgbTexture1dArrayMipmap

Represents a single mipmap level of a SrgbTexture1dArray.

                        SrgbTexture1dMipmap

Represents a single mipmap level of a SrgbTexture1d.

                        SrgbTexture2d

A two-dimensional texture  containing sRGB floating-point data.

                        SrgbTexture2dArray

An array of two-dimensional textures  containing sRGB floating-point data.

                        SrgbTexture2dArrayLayer

Represents a single layer of a SrgbTexture2dArray.

                        SrgbTexture2dArrayMipmap

Represents a single mipmap level of a SrgbTexture2dArray.

                        SrgbTexture2dMipmap

Represents a single mipmap level of a SrgbTexture2d.

                        SrgbTexture2dMultisample

A two-dimensional texture  containing sRGB floating-point data.

                        SrgbTexture2dMultisampleArray

An array of two-dimensional textures  containing sRGB floating-point data.

                        SrgbTexture2dMultisampleArrayMipmap

Represents a single mipmap level of a SrgbTexture2dMultisampleArray.

                        SrgbTexture2dMultisampleMipmap

Represents a single mipmap level of a SrgbTexture2dMultisample.

                        SrgbTexture3d

A three-dimensional texture  containing sRGB floating-point data.

                        SrgbTexture3dMipmap

Represents a single mipmap level of a SrgbTexture3d.

                        StencilTexture1d

A one-dimensional texture  containing stencil data.

                        StencilTexture1dArray

An array of one-dimensional textures  containing stencil data.

                        StencilTexture1dArrayLayer

Represents a single layer of a StencilTexture1dArray.

                        StencilTexture1dArrayMipmap

Represents a single mipmap level of a StencilTexture1dArray.

                        StencilTexture1dMipmap

Represents a single mipmap level of a StencilTexture1d.

                        StencilTexture2d

A two-dimensional texture  containing stencil data.

                        StencilTexture2dArray

An array of two-dimensional textures  containing stencil data.

                        StencilTexture2dArrayLayer

Represents a single layer of a StencilTexture2dArray.

                        StencilTexture2dArrayMipmap

Represents a single mipmap level of a StencilTexture2dArray.

                        StencilTexture2dMipmap

Represents a single mipmap level of a StencilTexture2d.

                        StencilTexture2dMultisample

A two-dimensional texture  containing stencil data.

                        StencilTexture2dMultisampleArray

An array of two-dimensional textures  containing stencil data.

                        StencilTexture2dMultisampleArrayMipmap

Represents a single mipmap level of a StencilTexture2dMultisampleArray.

                        StencilTexture2dMultisampleMipmap

Represents a single mipmap level of a StencilTexture2dMultisample.

                        StencilTexture3d

A three-dimensional texture  containing stencil data.

                        StencilTexture3dMipmap

Represents a single mipmap level of a StencilTexture3d.

                        Texture1d

A one-dimensional texture  containing floating-point data.

                        Texture1dArray

An array of one-dimensional textures  containing floating-point data.

                        Texture1dArrayLayer

Represents a single layer of a Texture1dArray.

                        Texture1dArrayMipmap

Represents a single mipmap level of a Texture1dArray.

                        Texture1dMipmap

Represents a single mipmap level of a Texture1d.

                        Texture2d

A two-dimensional texture  containing floating-point data.

                        Texture2dArray

An array of two-dimensional textures  containing floating-point data.

                        Texture2dArrayLayer

Represents a single layer of a Texture2dArray.

                        Texture2dArrayMipmap

Represents a single mipmap level of a Texture2dArray.

                        Texture2dMipmap

Represents a single mipmap level of a Texture2d.

                        Texture2dMultisample

A two-dimensional texture  containing floating-point data.

                        Texture2dMultisampleArray

An array of two-dimensional textures  containing floating-point data.

                        Texture2dMultisampleArrayMipmap

Represents a single mipmap level of a Texture2dMultisampleArray.

                        Texture2dMultisampleMipmap

Represents a single mipmap level of a Texture2dMultisample.

                        Texture3d

A three-dimensional texture  containing floating-point data.

                        Texture3dMipmap

Represents a single mipmap level of a Texture3d.

                        TextureSurface

Struct that allows you to draw on a texture.

                        UnsignedTexture1d

A one-dimensional texture  containing unsigned integral data.

                        UnsignedTexture1dArray

An array of one-dimensional textures  containing unsigned integral data.

                        UnsignedTexture1dArrayLayer

Represents a single layer of a UnsignedTexture1dArray.

                        UnsignedTexture1dArrayMipmap

Represents a single mipmap level of a UnsignedTexture1dArray.

                        UnsignedTexture1dMipmap

Represents a single mipmap level of a UnsignedTexture1d.

                        UnsignedTexture2d

A two-dimensional texture  containing unsigned integral data.

                        UnsignedTexture2dArray

An array of two-dimensional textures  containing unsigned integral data.

                        UnsignedTexture2dArrayLayer

Represents a single layer of a UnsignedTexture2dArray.

                        UnsignedTexture2dArrayMipmap

Represents a single mipmap level of a UnsignedTexture2dArray.

                        UnsignedTexture2dMipmap

Represents a single mipmap level of a UnsignedTexture2d.

                        UnsignedTexture2dMultisample

A two-dimensional texture  containing unsigned integral data.

                        UnsignedTexture2dMultisampleArray

An array of two-dimensional textures  containing unsigned integral data.

                        UnsignedTexture2dMultisampleArrayMipmap

Represents a single mipmap level of a UnsignedTexture2dMultisampleArray.

                        UnsignedTexture2dMultisampleMipmap

Represents a single mipmap level of a UnsignedTexture2dMultisample.

                        UnsignedTexture3d

A three-dimensional texture  containing unsigned integral data.

                        UnsignedTexture3dMipmap

Represents a single mipmap level of a UnsignedTexture3d.

Enums

                        ClientFormat

List of client-side pixel formats.

                        CompressedFormat

List of compressed texture formats.

                        CompressedSrgbFormat

List of compressed pixel formats in the sRGB color space.

                        DepthFormat

List of formats available for depth textures.

                        DepthStencilFormat

List of formats available for depth-stencil textures.

                        SrgbFormat

List of uncompressed pixel formats that contain floating-point data in the sRGB color space.

                        StencilFormat

List of formats available for stencil textures.

                        TextureCreationError

Error that can happen when creating a texture.

                        TextureFormat

Format of the internal representation of a texture.

                        TextureMaybeSupportedCreationError

Error that can happen when creating a texture which we don't know whether it is supported.

                        UncompressedFloatFormat

List of uncompressed pixel formats that contain floating-point-like data.

                        UncompressedIntFormat

List of uncompressed pixel formats that contain signed integral data.

                        UncompressedUintFormat

List of uncompressed pixel formats that contain unsigned integral data.

Traits

                        PixelValue

A trait that must be implemented for any type that can represent the value of a pixel.

                        Texture

Trait that describes a texture.

                        Texture1dDataSink

Trait that describes data for a one-dimensional texture.

                        Texture1dDataSource

Trait that describes data for a one-dimensional texture.

                        Texture2dDataSink

Trait that describes data for a two-dimensional texture.

                        Texture2dDataSource

Trait that describes data for a two-dimensional texture.

                        Texture3dDataSink

Trait that describes data for a two-dimensional texture.

                        Texture3dDataSource

Trait that describes data for a two-dimensional texture.

Keyboard shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

Search tricks

                Prefix searches with a type followed by a colon (e.g.
                fn:) to restrict the search to a given type.

                Accepted types are: fn, mod,
                struct, enum,
                trait, typedef (or
                tdef).

                Search functions by type signature (e.g.
                vec -> usize)


text:
//
// Licensed under the terms in License.txt
//
// Copyright 2010 Allen Ding. All rights reserved.
//

#import "KWSpec.h"
#import <objc/runtime.h>
#import "KWExample.h"
#import "KWExampleGroupBuilder.h"
#import "KWIntercept.h"
#import "KWObjCUtilities.h"
#import "KWStringUtilities.h"
#import "NSMethodSignature+KiwiAdditions.h"
#import "KWFailure.h"
#import "KWExampleSuite.h"

@interface KWSpec()

#pragma mark - Properties

@property (nonatomic, retain) KWExample *example;

@end

@implementation KWSpec

@synthesize example;

- (void)dealloc
{
    [example release];
    [super dealloc];
}

/* Methods are only implemented by sub-classes */

+ (NSString *)file { return nil; }

+ (void)buildExampleGroups {}

/* Reported by XCode SenTestingKit Runner before and after invocation of the test
   Use camel case to make method friendly names from example description
 */

- (NSString *)description
{
    KWExample *currentExample = self.example ? self.example : [[self invocation] kw_example];
    NSString *name = [currentExample descriptionWithContext];

    // CamelCase the string
    NSArray *words = [name componentsSeparatedByString:@" "];
    name = @"";
    for (NSString *word in words) {
        if ([word length] < 1)
        {
            continue;
        }
        name = [name stringByAppendingString:[[word substringToIndex:1] uppercaseString]];
        name = [name stringByAppendingString:[word substringFromIndex:1]];
    }

    // Replace the commas with underscores to separate the levels of context
    name = [name stringByReplacingOccurrencesOfString:@"," withString:@"_"];

    // Strip out characters not legal in function names
    NSError *error = nil;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[^a-zA-Z0-9_]*" options:0 error:&error];
    name = [regex stringByReplacingMatchesInString:name options:0 range:NSMakeRange(0, name.length) withTemplate:@""];

    return [NSString stringWithFormat:@"-[%@ %@]", NSStringFromClass([self class]), name];
}

#pragma mark - Getting Invocations

/* Called by the SenTestingKit test suite to get an array of invocations that
   should be run on instances of test cases. */

+ (NSArray *)testInvocations
{
    SEL selector = @selector(buildExampleGroups);

    // Only return invocation if the receiver is a concrete spec that has overridden -buildExampleGroups.
    if ([self methodForSelector:selector] == [KWSpec methodForSelector:selector])
        return nil;

    KWExampleSuite *exampleSuite = [[KWExampleGroupBuilder sharedExampleGroupBuilder] buildExampleGroups:^{
        [self buildExampleGroups];
    }];

    return [exampleSuite invocationsForTestCase];
}

#pragma mark - Running Specs

- (void)invokeTest
{
    self.example = [[self invocation] kw_example];

    NSAutoreleasePool *subPool = [[NSAutoreleasePool alloc] init];

    @try {
        [self.example runWithDelegate:self];
    } @catch (NSException *exception) {
        [self failWithException:exception];
    }

    [[self invocation] kw_setExample:nil];

    [subPool release];
}

#pragma mark - KWExampleGroupDelegate methods

- (void)example:(KWExample *)example didFailWithFailure:(KWFailure *)failure
{
    [self failWithException:[failure exceptionValue]];
}

#pragma mark - Verification proxies

+ (id)addVerifier:(id<KWVerifying>)aVerifier
{
  return [[[KWExampleGroupBuilder sharedExampleGroupBuilder] currentExample] addVerifier:aVerifier];
}

+ (id)addExistVerifierWithExpectationType:(KWExpectationType)anExpectationType callSite:(KWCallSite *)aCallSite
{
  return [[[KWExampleGroupBuilder sharedExampleGroupBuilder] currentExample] addExistVerifierWithExpectationType:anExpectationType callSite:aCallSite];
}

+ (id)addMatchVerifierWithExpectationType:(KWExpectationType)anExpectationType callSite:(KWCallSite *)aCallSite
{
  return [[[KWExampleGroupBuilder sharedExampleGroupBuilder] currentExample] addMatchVerifierWithExpectationType:anExpectationType callSite:aCallSite];
}

+ (id)addAsyncVerifierWithExpectationType:(KWExpectationType)anExpectationType callSite:(KWCallSite *)aCallSite timeout:(NSInteger)timeout shouldWait:(BOOL)shouldWait
{
  return [[[KWExampleGroupBuilder sharedExampleGroupBuilder] currentExample] addAsyncVerifierWithExpectationType:anExpectationType callSite:aCallSite timeout:timeout shouldWait: shouldWait];
}

@end