text:
package handlers

import (
	"archive/tar"
	"bufio"
	"compress/gzip"
	b64 "encoding/base64"
	"fmt"
	log "github.com/Sirupsen/logrus"
	"github.com/rancherio/go-machine-service/events"
	"github.com/rancherio/go-rancher/client"
	"io"
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"reflect"
	"regexp"
	"strings"
	"time"
)

const (
	levelInfo            = "level=\"info\""
	levelError           = "level=\"error\""
	errorCreatingMachine = "Error creating machine: "
)

var regExDockerMsg = regexp.MustCompile("msg=.*")
var regExHyphen = regexp.MustCompile("([a-z])([A-Z])")

func CreateMachine(event *events.Event, apiClient *client.RancherClient) error {
	log.WithFields(log.Fields{
		"resourceId": event.ResourceId,
		"eventId":    event.Id,
	}).Info("Creating Machine")

	machine, err := getMachine(event.ResourceId, apiClient)
	if err != nil {
		return handleByIdError(err, event, apiClient)
	}

	// Idempotency. If the resource has the property, we're done.
	if _, ok := machine.Data[machineDirField]; ok {
		reply := newReply(event)
		return publishReply(reply, apiClient)
	}

	command, machineDir, err := buildCreateCommand(machine)
	if err != nil {
		return err
	}

	//Setup republishing timer
	publishChan := make(chan string, 10)
	go republishTransitioningReply(publishChan, event, apiClient)

	publishChan <- "Contacting " + machine.Driver
	alreadyClosed := false
	defer func() {
		if !alreadyClosed {
			close(publishChan)
		}
	}()

	readerStdout, readerStderr, err := startReturnOutput(command)
	if err != nil {
		return err
	}

	errChan := make(chan string, 1)
	go logProgress(readerStdout, readerStderr, publishChan, machine, event, errChan)

	err = command.Wait()

	if err != nil {
		select {
		case errString := <-errChan:
			if errString != "" {
				return fmt.Errorf(errString)
			}
		case <-time.After(10 * time.Second):
			log.Error("Waited 10 seconds to break after command.Wait().  Please review logProgress.")
		}
		return err
	}

	dataUpdates := map[string]interface{}{machineDirField: machineDir}
	eventDataWrapper := map[string]interface{}{"+data": dataUpdates}

	log.WithFields(log.Fields{
		"resourceId":        event.ResourceId,
		"machineExternalId": machine.ExternalId,
	}).Info("Machine Created")

	destFile, err := createExtractedConfig(event, machine)
	if err != nil {
		return err
	}

	if destFile != "" {
		publishChan <- "Saving Machine Config"
		extractedConf, err := getExtractedConfig(destFile, machine, apiClient)
		if err != nil {
			return err
		}
		dataUpdates["+fields"] = map[string]string{"extractedConfig": extractedConf}
	}

	reply := newReply(event)
	reply.Data = eventDataWrapper

	// Explicitly close publish channel so that it doesn't conflict with final reply
	close(publishChan)
	alreadyClosed = true
	return publishReply(reply, apiClient)
}

func logProgress(readerStdout io.Reader, readerStderr io.Reader, publishChan chan<- string, machine *client.Machine, event *events.Event, errChan chan<- string) {
	// We will just log stdout first, then stderr, ignoring all errors.
	defer close(errChan)
	scanner := bufio.NewScanner(readerStdout)
	for scanner.Scan() {
		msg := scanner.Text()
		log.WithFields(log.Fields{
			"resourceId: ": event.ResourceId,
		}).Infof("stdout: %s", msg)
		msg = filterDockerMessage(msg, machine, errChan)
		if msg != "" {
			publishChan <- msg
		}
	}
	scanner = bufio.NewScanner(readerStderr)
	for scanner.Scan() {
		log.WithFields(log.Fields{
			"resourceId": event.ResourceId,
		}).Infof("stderr: %s", scanner.Text())
	}
}

func filterDockerMessage(msg string, machine *client.Machine, errChan chan<- string) string {
	// Docker log messages come in the format: time=<t> level=<log-level> msg=<message>
	// The minimum string should be greater than 7 characters msg="."
	match := regExDockerMsg.FindString(msg)
	if len(match) < 7 || !strings.HasPrefix(match, "msg=\"") {
		return ""
	}

	match = (match[5 : len(strings.TrimSpace(match))-1])
	if strings.Contains(msg, levelInfo) {
		// We just want to return <message> to cattle and only messages that do not contain the machine uuid or namee
		if strings.Contains(msg, machine.ExternalId) || strings.Contains(msg, machine.Name) {
			return ""
		}
		return match
	} else if strings.Contains(msg, levelError) {
		errChan <- strings.Replace(match, errorCreatingMachine, "", 1)
		return ""
	}
	return ""
}

func startReturnOutput(command *exec.Cmd) (io.Reader, io.Reader, error) {
	readerStdout, err := command.StdoutPipe()
	if err != nil {
		return nil, nil, err
	}

	readerStderr, err := command.StderrPipe()
	if err != nil {
		return nil, nil, err
	}

	err = command.Start()
	if err != nil {

		defer readerStdout.Close()
		defer readerStderr.Close()
		return nil, nil, err
	}
	return readerStdout, readerStderr, nil
}

func buildCreateCommand(machine *client.Machine) (*exec.Cmd, string, error) {
	cmdArgs, err := buildMachineCreateCmd(machine)
	if err != nil {
		return nil, "", err
	}

	machineDir, err := buildBaseMachineDir(machine.ExternalId)
	if err != nil {
		return nil, "", err
	}

	command := buildCommand(machineDir, cmdArgs)
	return command, machineDir, nil
}

func buildBaseMachineDir(uuid string) (string, error) {
	machineDir, err := getBaseMachineDir(uuid)
	if err != nil {
		return "", err
	}

	err = os.MkdirAll(machineDir, 0740)
	if err != nil {
		return "", err
	}
	return machineDir, err
}

func getBaseMachineDir(uuid string) (string, error) {
	cattleHome := os.Getenv("CATTLE_HOME")
	if cattleHome == "" {
		return "", fmt.Errorf("CATTLE_HOME not set. Cant create machine. Uuid: [%v].", uuid)
	}
	machineDir := filepath.Join(cattleHome, "machine", uuid)
	return machineDir, nil
}

func buildMachineCreateCmd(machine *client.Machine) ([]string, error) {
	sDriver := strings.ToLower(machine.Driver)
	cmd := []string{"create", "-d", sDriver}

	valueOfMachine := reflect.ValueOf(machine).Elem()

	// Grab the reflected Value of XyzConfig (i.e. DigitaloceanConfig) based on the machine driver
	driverConfig := valueOfMachine.FieldByName(strings.ToUpper(sDriver[:1]) + sDriver[1:] + "Config").Elem()
	typeOfDriverConfig := driverConfig.Type()

	for i := 0; i < driverConfig.NumField(); i++ {
		// We are ignoring the Resource Field as we don't need it.
		nameConfigField := typeOfDriverConfig.Field(i).Name
		if nameConfigField == "Resource" {
			continue
		}

		f := driverConfig.Field(i)

		// This converts all field name of ParameterName to --<driver name>-parameter-name
		// i.e. AccessToken parameter for DigitalOcean driver becomes --digitalocean-access-token
		dmField := "--" + sDriver + "-" + strings.ToLower(regExHyphen.ReplaceAllString(nameConfigField, "${1}-${2}"))

		// For now, we only support bool and string.  Will add more as required.
		switch f.Interface().(type) {
		case bool:
			// dm only accepts field or field=true if value=true
			if f.Bool() {
				cmd = append(cmd, dmField)
			}
		case string:
			if f.String() != "" {
				cmd = append(cmd, dmField, f.String())
			}
		default:
			return nil, fmt.Errorf("Unsupported type: %v", f.Type())
		}

	}

	cmd = append(cmd, machine.Name)
	log.Infof("Cmd slice: %v", cmd)
	return cmd, nil
}

func createExtractedConfig(event *events.Event, machine *client.Machine) (string, error) {
	// We are going to ignore doing anything for VirtualBox given that there is no way you can
	// use Machine once it has been created.  Virtual is mainly a test-only use case
	if strings.ToLower(machine.Driver) == "virtualbox" {
		log.Debug("VirtualBox machine does not need config extracted")
		return "", nil
	}

	// We will now zip, base64 encode the machine directory created, and upload this to cattle server.  This can be used to either recover
	// the machine directory or used by Rancher users for their own local machine setup.
	log.WithFields(log.Fields{
		"resourceId": event.ResourceId,
	}).Info("Creating and uploading extracted machine config")

	// tar.gz the $CATTLE_HOME/machine/<machine-id>/machines/<machine-name> dir (v0.2.0)
	// Open the source directory and read all the files we want to tar.gz
	baseDir, err := getBaseMachineDir(machine.ExternalId)
	if err != nil {
		return "", err
	}

	machineDir := filepath.Join(baseDir, "machines", machine.Name)
	dir, err := os.Open(machineDir)
	if err != nil {
		return "", err
	}
	defer dir.Close()

	log.WithFields(log.Fields{
		"machineDir": machineDir,
	}).Debug("Preparing directory to be tar.gz")

	// Be able to read the files under this dir
	files, err := dir.Readdir(0)
	if err != nil {
		return "", err
	}

	// create the tar.gz file
	destFile := filepath.Join(baseDir, machine.Name+".tar.gz")
	tarfile, err := os.Create(destFile)
	if err != nil {
		return "", err
	}

	defer tarfile.Close()
	fileWriter := gzip.NewWriter(tarfile)
	defer fileWriter.Close()

	tarfileWriter := tar.NewWriter(fileWriter)
	defer tarfileWriter.Close()

	// Read and add files into <machine-name>.tar.gz
	for _, fileInfo := range files {

		// For now, we will skip directories.  If we need to zip directories, we need to revist this code
		if fileInfo.IsDir() {
			continue
		}

		file, err := os.Open(filepath.Join(machineDir, fileInfo.Name()))
		if err != nil {
			return "", err
		}

		defer file.Close()

		// prepare the tar header
		header := new(tar.Header)
		header.Name = filepath.Join(machine.Name, fileInfo.Name())
		header.Size = fileInfo.Size()
		header.Mode = int64(fileInfo.Mode())
		header.ModTime = fileInfo.ModTime()

		err = tarfileWriter.WriteHeader(header)
		if err != nil {
			return "", err
		}

		_, err = io.Copy(tarfileWriter, file)
		if err != nil {
			return "", err
		}
	}
	return destFile, nil
}

func getExtractedConfig(destFile string, machine *client.Machine, apiClient *client.RancherClient) (string, error) {
	extractedTarfile, err := ioutil.ReadFile(destFile)
	if err != nil {
		return "", err
	}

	extractedEncodedConfig := b64.StdEncoding.EncodeToString(extractedTarfile)
	if err != nil {
		return "", err
	}

	log.WithFields(log.Fields{
		"resourceId": machine.Id,
		"destFile":   destFile,
	}).Info("Machine config file created and encoded.")

	return extractedEncodedConfig, nil
}


text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"/>
  <title>DL Divine | Gallery</title>

  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link href="css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"/>
  <link href="css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>

Home

About us

Rooms

Gallery

Contact us

Loginarrow_drop_down

Login as Guest

Login as Admin

Home

About us

Rooms

Gallery

Contact us

Loginarrow_drop_down

Login as Guest

Login as Admin

      menu

Dl Divine

Family Room

Front View Room

Quad Room

Standard Room

        Made by Materialize

redpajama_set_name: RedPajamaGithub


text:
package org.apache.calcite.test.fuzzer;

import org.apache.calcite.adapter.java.JavaTypeFactory;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rex.RexBuilder;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.rex.RexProgramBuilderBase;
import org.apache.calcite.sql.SqlOperator;
import org.apache.calcite.sql.fun.SqlStdOperatorTable;
import org.apache.calcite.sql.type.SqlTypeName;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.function.Function;

/**
 * Generates random {@link RexNode} instances for tests.
 */
public class RexFuzzer extends RexProgramBuilderBase {
  private static final int MAX_VARS = 2;

  private static final SqlOperator[] BOOL_TO_BOOL = {
      SqlStdOperatorTable.NOT,
      SqlStdOperatorTable.IS_TRUE,
      SqlStdOperatorTable.IS_FALSE,
      SqlStdOperatorTable.IS_NOT_TRUE,
      SqlStdOperatorTable.IS_NOT_FALSE,
  };

  private static final SqlOperator[] ANY_TO_BOOL = {
      SqlStdOperatorTable.IS_NULL,
      SqlStdOperatorTable.IS_NOT_NULL,
      SqlStdOperatorTable.IS_UNKNOWN,
      SqlStdOperatorTable.IS_NOT_UNKNOWN,
  };

  private static final SqlOperator[] COMPARABLE_TO_BOOL = {
      SqlStdOperatorTable.EQUALS,
      SqlStdOperatorTable.NOT_EQUALS,
      SqlStdOperatorTable.GREATER_THAN,
      SqlStdOperatorTable.GREATER_THAN_OR_EQUAL,
      SqlStdOperatorTable.LESS_THAN,
      SqlStdOperatorTable.LESS_THAN_OR_EQUAL,
      SqlStdOperatorTable.IS_DISTINCT_FROM,
      SqlStdOperatorTable.IS_NOT_DISTINCT_FROM,
  };

  private static final SqlOperator[] BOOL_TO_BOOL_MULTI_ARG = {
      SqlStdOperatorTable.OR,
      SqlStdOperatorTable.AND,
      SqlStdOperatorTable.COALESCE,
  };

  private static final SqlOperator[] ANY_SAME_TYPE_MULTI_ARG = {
      SqlStdOperatorTable.COALESCE,
  };

  private static final SqlOperator[] NUMERIC_TO_NUMERIC = {
      SqlStdOperatorTable.PLUS,
      SqlStdOperatorTable.MINUS,
      SqlStdOperatorTable.MULTIPLY,
      // Divide by zero is not allowed, so we do not generate divide
//      SqlStdOperatorTable.DIVIDE,
//      SqlStdOperatorTable.DIVIDE_INTEGER,
  };

  private static final SqlOperator[] UNARY_NUMERIC = {
      SqlStdOperatorTable.UNARY_MINUS,
      SqlStdOperatorTable.UNARY_PLUS,
  };

  private static final int[] INT_VALUES = {-1, 0, 1, 100500};

  private final RelDataType intType;
  private final RelDataType nullableIntType;

  /**
   * Generates randomized {@link RexNode}.
   *
   * @param rexBuilder  builder to be used to create nodes
   * @param typeFactory type factory
   */
  public RexFuzzer(RexBuilder rexBuilder, JavaTypeFactory typeFactory) {
    setUp();
    this.rexBuilder = rexBuilder;
    this.typeFactory = typeFactory;

    intType = typeFactory.createSqlType(SqlTypeName.INTEGER);
    nullableIntType = typeFactory.createTypeWithNullability(intType, true);
  }

  public RexNode getExpression(Random r, int depth) {
    return getComparableExpression(r, depth);
  }

  private RexNode fuzzOperator(Random r, SqlOperator[] operators, RexNode... args) {
    return rexBuilder.makeCall(operators[r.nextInt(operators.length)], args);
  }

  private RexNode fuzzOperator(Random r, SqlOperator[] operators, int length,
      Function<Random, RexNode> factory) {
    List<RexNode> args = new ArrayList<>(length);
    for (int i = 0; i < length; i++) {
      args.add(factory.apply(r));
    }
    return rexBuilder.makeCall(operators[r.nextInt(operators.length)], args);
  }

  public RexNode getComparableExpression(Random r, int depth) {
    int v = r.nextInt(2);
    switch (v) {
    case 0:
      return getBoolExpression(r, depth);
    case 1:
      return getIntExpression(r, depth);
    }
    throw new AssertionError("should not reach here");
  }

  public RexNode getSimpleBool(Random r) {
    int v = r.nextInt(2);
    switch (v) {
    case 0:
      boolean nullable = r.nextBoolean();
      int field = r.nextInt(MAX_VARS);
      return nullable ? vBool(field) : vBoolNotNull(field);
    case 1:
      return r.nextBoolean() ? trueLiteral : falseLiteral;
    case 2:
      return nullBool;
    }
    throw new AssertionError("should not reach here");
  }

  public RexNode getBoolExpression(Random r, int depth) {
    int v = depth <= 0 ? 0 : r.nextInt(7);
    switch (v) {
    case 0:
      return getSimpleBool(r);
    case 1:
      return fuzzOperator(r, ANY_TO_BOOL, getExpression(r, depth - 1));
    case 2:
      return fuzzOperator(r, BOOL_TO_BOOL, getBoolExpression(r, depth - 1));
    case 3:
      return fuzzOperator(r, COMPARABLE_TO_BOOL, getBoolExpression(r, depth - 1),
          getBoolExpression(r, depth - 1));
    case 4:
      return fuzzOperator(r, COMPARABLE_TO_BOOL, getIntExpression(r, depth - 1),
          getIntExpression(r, depth - 1));
    case 5:
      return fuzzOperator(r, BOOL_TO_BOOL_MULTI_ARG, r.nextInt(3) + 2,
          x -> getBoolExpression(x, depth - 1));
    case 6:
      return fuzzCase(r, depth - 1,
          x -> getBoolExpression(x, depth - 1));
    }
    throw new AssertionError("should not reach here");
  }

  public RexNode getSimpleInt(Random r) {
    int v = r.nextInt(3);
    switch (v) {
    case 0:
      boolean nullable = r.nextBoolean();
      int field = r.nextInt(MAX_VARS);
      return nullable ? vInt(field) : vIntNotNull(field);
    case 1: {
      int i = r.nextInt(INT_VALUES.length + 1);
      int val = i < INT_VALUES.length ? INT_VALUES[i] : r.nextInt();
      return rexBuilder.makeLiteral(val, r.nextBoolean() ? intType : nullableIntType, false);
    }
    case 2:
      return nullInt;
    }
    throw new AssertionError("should not reach here");
  }

  public RexNode getIntExpression(Random r, int depth) {
    int v = depth <= 0 ? 0 : r.nextInt(5);
    switch (v) {
    case 0:
      return getSimpleInt(r);
    case 1:
      return fuzzOperator(r, UNARY_NUMERIC, getIntExpression(r, depth - 1));
    case 2:
      return fuzzOperator(r, NUMERIC_TO_NUMERIC, getIntExpression(r, depth - 1),
          getIntExpression(r, depth - 1));
    case 3:
      return fuzzOperator(r, ANY_SAME_TYPE_MULTI_ARG, r.nextInt(3) + 2,
          x -> getIntExpression(x, depth - 1));
    case 4:
      return fuzzCase(r, depth - 1,
          x -> getIntExpression(x, depth - 1));
    }
    throw new AssertionError("should not reach here");
  }

  public RexNode fuzzCase(Random r, int depth, Function<Random, RexNode> resultFactory) {
    boolean caseArgWhen = r.nextBoolean();
    int caseBranches = 1 + (depth <= 0 ? 0 : r.nextInt(3));
    List<RexNode> args = new ArrayList<>(caseBranches + 1);

    Function<Random, RexNode> exprFactory;
    if (!caseArgWhen) {
      exprFactory = x -> getBoolExpression(x, depth - 1);
    } else {
      int type = r.nextInt(2);
      RexNode arg;
      Function<Random, RexNode> baseExprFactory;
      switch (type) {
      case 0:
        baseExprFactory = x -> getBoolExpression(x, depth - 1);
        break;
      case 1:
        baseExprFactory = x -> getIntExpression(x, depth - 1);
        break;
      default:
        throw new AssertionError("should not reach here: " + type);
      }
      arg = baseExprFactory.apply(r);
      // emulate  case when arg=2 then .. when arg=4 then ...
      exprFactory = x -> eq(arg, baseExprFactory.apply(x));
    }

    for (int i = 0; i < caseBranches; i++) {
      args.add(exprFactory.apply(r)); // when
      args.add(resultFactory.apply(r)); // then
    }
    args.add(resultFactory.apply(r)); // else
    return case_(args);
  }

}


text:
package org.anderes.cookbook.domain;

import java.util.Collection;
import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface RecipeRepository extends JpaRepository<Recipe, String> {

    Collection<Recipe> findByTitleLike(String string);

    List<String> findAllTag();

}


text:
'use strict';

module.exports = [
  {
    type: 'customer',
    routePrefix: '/customers'
  }, {
    type: 'assignment',
    routePrefix: '/assignments',
    useDataStore: true
  }, {
    type: 'plan',
    routePrefix: '/plans',
    useDataStore: true
  }, {
    type: 'product',
    routePrefix: '/products',
    useDataStore: true
  }, {
    type: 'feature',
    routePrefix: '/features',
    useDataStore: true
  }, {
    type: 'transcoder_profile',
    routePrefix: '/transcoderprofiles',
    useDataStore: true
  }, {
    type: 'user',
    routePrefix: '/users',
    useDataStore: true
  }, {
    type: 'player_skin',
    routePrefix: '/player-skins',
    useDataStore: true
  }, {
    type: 'log',
    routePrefix: '/logs',
    useDataStore: true
  }
];


text:
from __future__ import unicode_literals

import copy

from django.forms import Select
from django.utils.safestring import mark_safe

from .base import WidgetTest

class SelectTest(WidgetTest):
    widget = Select
    nested_widget = Select(choices=(
        ('outer1', 'Outer 1'),
        ('Group "1"', (('inner1', 'Inner 1'), ('inner2', 'Inner 2'))),
    ))

    def test_render(self):
        self.check_html(self.widget(choices=self.beatles), 'beatle', 'J', html=(
            """<select name="beatle">
            <option value="J" selected="selected">John</option>
            <option value="P">Paul</option>
            <option value="G">George</option>
            <option value="R">Ringo</option>
            </select>"""
        ))

    def test_render_none(self):
        """
        If the value is None, none of the options are selected.
        """
        self.check_html(self.widget(choices=self.beatles), 'beatle', None, html=(
            """<select name="beatle">
            <option value="J">John</option>
            <option value="P">Paul</option>
            <option value="G">George</option>
            <option value="R">Ringo</option>
            </select>"""
        ))

    def test_render_label_value(self):
        """
        If the value corresponds to a label (but not to an option value), none
        of the options are selected.
        """
        self.check_html(self.widget(choices=self.beatles), 'beatle', 'John', html=(
            """<select name="beatle">
            <option value="J">John</option>
            <option value="P">Paul</option>
            <option value="G">George</option>
            <option value="R">Ringo</option>
            </select>"""
        ))

    def test_render_selected(self):
        """
        Only one option can be selected (#8103).
        """
        choices = [('0', '0'), ('1', '1'), ('2', '2'), ('3', '3'), ('0', 'extra')]

        self.check_html(self.widget(choices=choices), 'choices', '0', html=(
            """<select name="choices">
            <option value="0" selected="selected">0</option>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="0">extra</option>
            </select>"""
        ))

    def test_constructor_attrs(self):
        """
        Select options shouldn't inherit the parent widget attrs.
        """
        widget = Select(
            attrs={'class': 'super', 'id': 'super'},
            choices=[(1, 1), (2, 2), (3, 3)],
        )
        self.check_html(widget, 'num', 2, html=(
            """<select name="num" class="super" id="super">
              <option value="1">1</option>
              <option value="2" selected="selected">2</option>
              <option value="3">3</option>
            </select>"""
        ))

    def test_compare_to_str(self):
        """
        The value is compared to its str().
        """
        self.check_html(
            self.widget(choices=[('1', '1'), ('2', '2'), ('3', '3')]),
            'num', 2,
            html=(
                """<select name="num">
                <option value="1">1</option>
                <option value="2" selected="selected">2</option>
                <option value="3">3</option>
                </select>"""
            ),
        )
        self.check_html(
            self.widget(choices=[(1, 1), (2, 2), (3, 3)]),
            'num', '2',
            html=(
                """<select name="num">
                <option value="1">1</option>
                <option value="2" selected="selected">2</option>
                <option value="3">3</option>
                </select>"""
            ),
        )
        self.check_html(
            self.widget(choices=[(1, 1), (2, 2), (3, 3)]),
            'num', 2,
            html=(
                """<select name="num">
                <option value="1">1</option>
                <option value="2" selected="selected">2</option>
                <option value="3">3</option>
                </select>"""
            ),
        )

    def test_choices_constuctor(self):
        widget = Select(choices=[(1, 1), (2, 2), (3, 3)])
        self.check_html(widget, 'num', 2, html=(
            """<select name="num">
            <option value="1">1</option>
            <option value="2" selected="selected">2</option>
            <option value="3">3</option>
            </select>"""
        ))

    def test_choices_constructor_generator(self):
        """
        If choices is passed to the constructor and is a generator, it can be
        iterated over multiple times without getting consumed.
        """
        def get_choices():
            for i in range(5):
                yield (i, i)

        widget = Select(choices=get_choices())
        self.check_html(widget, 'num', 2, html=(
            """<select name="num">
            <option value="0">0</option>
            <option value="1">1</option>
            <option value="2" selected="selected">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            </select>"""
        ))
        self.check_html(widget, 'num', 3, html=(
            """<select name="num">
            <option value="0">0</option>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3" selected="selected">3</option>
            <option value="4">4</option>
            </select>"""
        ))

    def test_choices_escaping(self):
        choices = (('bad', 'you & me'), ('good', mark_safe('you > me')))
        self.check_html(self.widget(choices=choices), 'escape', None, html=(
            """<select name="escape">
            <option value="bad">you & me</option>
            <option value="good">you > me</option>
            </select>"""
        ))

    def test_choices_unicode(self):
        self.check_html(
            self.widget(choices=[('ŠĐĆŽćžšđ', 'ŠĐabcĆŽćžšđ'), ('ćžšđ', 'abcćžšđ')]),
            'email', 'ŠĐĆŽćžšđ',
            html=(
                """<select name="email">
                <option value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" selected="selected">
                    \u0160\u0110abc\u0106\u017d\u0107\u017e\u0161\u0111
                </option>
                <option value="\u0107\u017e\u0161\u0111">abc\u0107\u017e\u0161\u0111</option>
                </select>"""
            ),
        )

    def test_choices_optgroup(self):
        """
        Choices can be nested one level in order to create HTML optgroups.
        """
        self.check_html(self.nested_widget, 'nestchoice', None, html=(
            """<select name="nestchoice">
            <option value="outer1">Outer 1</option>
            <optgroup label="Group "1"">
            <option value="inner1">Inner 1</option>
            <option value="inner2">Inner 2</option>
            </optgroup>
            </select>"""
        ))

    def test_choices_select_outer(self):
        self.check_html(self.nested_widget, 'nestchoice', 'outer1', html=(
            """<select name="nestchoice">
            <option value="outer1" selected="selected">Outer 1</option>
            <optgroup label="Group "1"">
            <option value="inner1">Inner 1</option>
            <option value="inner2">Inner 2</option>
            </optgroup>
            </select>"""
        ))

    def test_choices_select_inner(self):
        self.check_html(self.nested_widget, 'nestchoice', 'inner1', html=(
            """<select name="nestchoice">
            <option value="outer1">Outer 1</option>
            <optgroup label="Group "1"">
            <option value="inner1" selected="selected">Inner 1</option>
            <option value="inner2">Inner 2</option>
            </optgroup>
            </select>"""
        ))

    def test_deepcopy(self):
        """
        __deepcopy__() should copy all attributes properly (#25085).
        """
        widget = Select()
        obj = copy.deepcopy(widget)
        self.assertIsNot(widget, obj)
        self.assertEqual(widget.choices, obj.choices)
        self.assertIsNot(widget.choices, obj.choices)
        self.assertEqual(widget.attrs, obj.attrs)
        self.assertIsNot(widget.attrs, obj.attrs)