text:
package name.guke.commons.excel;

import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.ComparatorUtils;
import org.apache.commons.collections.comparators.ComparableComparator;
import org.apache.commons.collections.comparators.ComparatorChain;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.text.MessageFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Guke on 2016/11/3.
 */
public class ExcelUtil {

    private static Logger LG = LoggerFactory.getLogger(ExcelUtil.class);

    /**
     * 用来验证excel与Vo中的类型是否一致

     * Map<栏位类型,只能是哪些Cell类型>
     */
    private static Map<Class<?>, Integer[]> validateMap = new HashMap<Class<?>, Integer[]>();

    static {
        validateMap.put(String[].class, new Integer[]{Cell.CELL_TYPE_STRING});
        validateMap.put(Double[].class, new Integer[]{Cell.CELL_TYPE_NUMERIC});
        validateMap.put(String.class, new Integer[]{Cell.CELL_TYPE_STRING});
        validateMap.put(Double.class, new Integer[]{Cell.CELL_TYPE_NUMERIC});
        validateMap.put(Date.class, new Integer[]{Cell.CELL_TYPE_NUMERIC, Cell.CELL_TYPE_STRING});
        validateMap.put(Integer.class, new Integer[]{Cell.CELL_TYPE_NUMERIC});
        validateMap.put(Float.class, new Integer[]{Cell.CELL_TYPE_NUMERIC});
        validateMap.put(Long.class, new Integer[]{Cell.CELL_TYPE_NUMERIC});
        validateMap.put(Boolean.class, new Integer[]{Cell.CELL_TYPE_BOOLEAN});
    }

    /**
     * 获取cell类型的文字描述
     *
     * @param cellType

     *                 Cell.CELL_TYPE_BLANK
     *                 Cell.CELL_TYPE_BOOLEAN
     *                 Cell.CELL_TYPE_ERROR
     *                 Cell.CELL_TYPE_FORMULA
     *                 Cell.CELL_TYPE_NUMERIC
     *                 Cell.CELL_TYPE_STRING
     *

     * @return
     */
    private static String getCellTypeByInt(int cellType) {
        switch (cellType) {
            case Cell.CELL_TYPE_BLANK:
                return "Null type";
            case Cell.CELL_TYPE_BOOLEAN:
                return "Boolean type";
            case Cell.CELL_TYPE_ERROR:
                return "Error type";
            case Cell.CELL_TYPE_FORMULA:
                return "Formula type";
            case Cell.CELL_TYPE_NUMERIC:
                return "Numeric type";
            case Cell.CELL_TYPE_STRING:
                return "String type";
            default:
                return "Unknown type";
        }
    }

    /**
     * 获取单元格值
     *
     * @param cell
     * @return
     */
    private static Object getCellValue(Cell cell) {
        if (cell == null
                || (cell.getCellType() == Cell.CELL_TYPE_STRING && StringUtils.isBlank(cell
                .getStringCellValue()))) {
            return null;
        }
        int cellType = cell.getCellType();
        switch (cellType) {
            case Cell.CELL_TYPE_BLANK:
                return null;
            case Cell.CELL_TYPE_BOOLEAN:
                return cell.getBooleanCellValue();
            case Cell.CELL_TYPE_ERROR:
                return cell.getErrorCellValue();
            case Cell.CELL_TYPE_FORMULA:
                return cell.getNumericCellValue();
            case Cell.CELL_TYPE_NUMERIC:
                return cell.getNumericCellValue();
            case Cell.CELL_TYPE_STRING:
                return cell.getStringCellValue();
            default:
                return null;
        }
    }

    /**
     * 利用JAVA的反射机制,将放置在JAVA集合中并且符号一定条件的数据以EXCEL 的形式输出到指定IO设备上

     * 用于单个sheet
     *
     * @param <T>
     * @param headers 表格属性列名数组
     * @param dataset 需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。此方法支持的
     *                javabean属性的数据类型有基本数据类型及String,Date,String[],Double[]
     * @param out     与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
     */
    public static <T> void exportExcel(String[] headers, Collection<T> dataset, OutputStream out) {
        exportExcel(headers, dataset, out, null);
    }

    /**
     * 利用JAVA的反射机制,将放置在JAVA集合中并且符号一定条件的数据以EXCEL 的形式输出到指定IO设备上

     * 用于单个sheet
     *
     * @param <T>
     * @param headers 表格属性列名数组
     * @param dataset 需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。此方法支持的
     *                javabean属性的数据类型有基本数据类型及String,Date,String[],Double[]
     * @param out     与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
     * @param pattern 如果有时间数据,设定输出格式。默认为"yyy-MM-dd"
     */
    public static <T> void exportExcel(String[] headers, Collection<T> dataset, OutputStream out,
                                       String pattern) {
        // 声明一个工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet();

        write2Sheet(sheet, headers, dataset, pattern);
        try {
            workbook.write(out);
        } catch (IOException e) {
            LG.error(e.toString(), e);
        }
    }

    public static void exportExcel(String[][] datalist, OutputStream out) {
        try {
            // 声明一个工作薄
            HSSFWorkbook workbook = new HSSFWorkbook();
            // 生成一个表格
            HSSFSheet sheet = workbook.createSheet();

            for (int i = 0; i < datalist.length; i++) {
                String[] r = datalist[i];
                HSSFRow row = sheet.createRow(i);
                for (int j = 0; j < r.length; j++) {
                    HSSFCell cell = row.createCell(j);
                    //cell max length 32767
                    if (r[j].length() > 32767) {
                        r[j] = "--此字段过长(超过32767),已被截断--" + r[j];
                        r[j] = r[j].substring(0, 32766);
                    }
                    cell.setCellValue(r[j]);
                }
            }
            //自动列宽
            if (datalist.length > 0) {
                int colcount = datalist[0].length;
                for (int i = 0; i < colcount; i++) {
                    sheet.autoSizeColumn(i);
                }
            }
            workbook.write(out);
        } catch (IOException e) {
            LG.error(e.toString(), e);
        }
    }

    /**
     * 利用JAVA的反射机制,将放置在JAVA集合中并且符号一定条件的数据以EXCEL 的形式输出到指定IO设备上

     * 用于多个sheet
     *
     * @param <T>
     * @param sheets {@link ExcelSheet}的集合
     * @param out    与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
     */
    public static <T> void exportExcel(List<ExcelSheet<T>> sheets, OutputStream out) {
        exportExcel(sheets, out, null);
    }

    /**
     * 利用JAVA的反射机制,将放置在JAVA集合中并且符号一定条件的数据以EXCEL 的形式输出到指定IO设备上

     * 用于多个sheet
     *
     * @param <T>
     * @param sheets  {@link ExcelSheet}的集合
     * @param out     与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
     * @param pattern 如果有时间数据,设定输出格式。默认为"yyy-MM-dd"
     */
    public static <T> void exportExcel(List<ExcelSheet<T>> sheets, OutputStream out, String pattern) {
        if (CollectionUtils.isEmpty(sheets)) {
            return;
        }
        // 声明一个工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        for (ExcelSheet<T> sheet : sheets) {
            // 生成一个表格
            HSSFSheet hssfSheet = workbook.createSheet(sheet.getSheetName());
            write2Sheet(hssfSheet, sheet.getHeaders(), sheet.getDataset(), pattern);
        }
        try {
            workbook.write(out);
        } catch (IOException e) {
            LG.error(e.toString(), e);
        }
    }

    /**
     * 每个sheet的写入
     *
     * @param sheet   页签
     * @param headers 表头
     * @param dataset 数据集合
     * @param pattern 日期格式
     */
    private static <T> void write2Sheet(HSSFSheet sheet, String[] headers, Collection<T> dataset,
                                        String pattern) {
        // 产生表格标题行
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        // 遍历集合数据,产生数据行
        Iterator<T> it = dataset.iterator();
        int index = 0;
        while (it.hasNext()) {
            index++;
            row = sheet.createRow(index);
            T t = (T) it.next();
            try {
                if (t instanceof Map) {
                    @SuppressWarnings("unchecked")
                    Map<String, Object> map = (Map<String, Object>) t;
                    int cellNum = 0;
                    for (String k : headers) {
                        if (map.containsKey(k) == false) {
                            LG.error("Map 中 不存在 key [" + k + "]");
                            continue;
                        }
                        Object value = map.get(k);
                        HSSFCell cell = row.createCell(cellNum);
                        cell.setCellValue(String.valueOf(value));
                        cellNum++;
                    }
                } else {
                    List<FieldForSortting> fields = sortFieldByAnno(t.getClass());
                    int cellNum = 0;
                    for (int i = 0; i < fields.size(); i++) {
                        HSSFCell cell = row.createCell(cellNum);
                        Field field = fields.get(i).getField();
                        field.setAccessible(true);
                        Object value = field.get(t);
                        String textValue = null;
                        if (value instanceof Integer) {
                            int intValue = (Integer) value;
                            cell.setCellValue(intValue);
                        } else if (value instanceof Float) {
                            float fValue = (Float) value;
                            cell.setCellValue(fValue);
                        } else if (value instanceof Double) {
                            double dValue = (Double) value;
                            cell.setCellValue(dValue);
                        } else if (value instanceof Long) {
                            long longValue = (Long) value;
                            cell.setCellValue(longValue);
                        } else if (value instanceof Boolean) {
                            boolean bValue = (Boolean) value;
                            cell.setCellValue(bValue);
                        } else if (value instanceof Date) {
                            Date date = (Date) value;
                            if (date != null) {
                                SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                                textValue = sdf.format(date);
                            }
                        } else if (value instanceof String[]) {
                            String[] strArr = (String[]) value;
                            for (int j = 0; j < strArr.length; j++) {
                                String str = strArr[j];
                                cell.setCellValue(str);
                                if (j != strArr.length - 1) {
                                    cellNum++;
                                    cell = row.createCell(cellNum);
                                }
                            }
                        } else if (value instanceof Double[]) {
                            Double[] douArr = (Double[]) value;
                            for (int j = 0; j < douArr.length; j++) {
                                Double val = douArr[j];
                                // 资料不为空则set Value
                                if (val != null) {
                                    cell.setCellValue(val);
                                }

                                if (j != douArr.length - 1) {
                                    cellNum++;
                                    cell = row.createCell(cellNum);
                                }
                            }
                        } else {
                            // 其它数据类型都当作字符串简单处理
                            String empty = StringUtils.EMPTY;
                            ExcelCell anno = field.getAnnotation(ExcelCell.class);
                            if (anno != null) {
                                empty = anno.defaultValue();
                            }
                            textValue = value == null ? empty : value.toString();
                        }
                        if (textValue != null) {
                            HSSFRichTextString richString = new HSSFRichTextString(textValue);
                            cell.setCellValue(richString);
                        }

                        cellNum++;
                    }
                }
            } catch (Exception e) {
                LG.error(e.toString(), e);
            }
        }
        // 设定自动宽度
        for (int i = 0; i < headers.length; i++) {
            sheet.autoSizeColumn(i);
        }

    }

    /**
     * 把Excel的数据封装成voList
     *
     * @param clazz       vo的Class
     * @param inputStream excel输入流
     * @param pattern     如果有时间数据,设定输入格式。默认为"yyy-MM-dd"
     * @param logs        错误log集合
     * @param arrayCount  如果vo中有数组类型,那就按照index顺序,把数组应该有几个值写上.
     * @return voList
     * @throws RuntimeException
     */
    @SuppressWarnings("unchecked")
    public static <T> Collection<T> importExcel(Class<T> clazz, InputStream inputStream,
                                                String pattern, ExcelLogs logs, Integer... arrayCount) {
        HSSFWorkbook workBook = null;
        try {
            workBook = new HSSFWorkbook(inputStream);
        } catch (IOException e) {
            LG.error(e.toString(), e);
        }
        List<T> list = new ArrayList<T>();
        HSSFSheet sheet = workBook.getSheetAt(0);
        Iterator<Row> rowIterator = sheet.rowIterator();
        try {
            List<ExcelLog> logList = new ArrayList<ExcelLog>();
            // Map<title,index>
            Map<String, Integer> titleMap = new HashMap<String, Integer>();

            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                if (row.getRowNum() == 0) {
                    if (clazz == Map.class) {
                        // 解析map用的key,就是excel标题行
                        Iterator<Cell> cellIterator = row.cellIterator();
                        Integer index = 0;
                        while (cellIterator.hasNext()) {
                            String value = cellIterator.next().getStringCellValue();
                            titleMap.put(value, index);
                            index++;
                        }
                    }
                    continue;
                }
                // 整行都空,就跳过
                boolean allRowIsNull = true;
                Iterator<Cell> cellIterator = row.cellIterator();
                while (cellIterator.hasNext()) {
                    Object cellValue = getCellValue(cellIterator.next());
                    if (cellValue != null) {
                        allRowIsNull = false;
                        break;
                    }
                }
                if (allRowIsNull) {
                    LG.warn("Excel row " + row.getRowNum() + " all row value is null!");
                    continue;
                }
                T t = null;
                StringBuilder log = new StringBuilder();
                if (clazz == Map.class) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    for (String k : titleMap.keySet()) {
                        Integer index = titleMap.get(k);
                        String value = row.getCell(index).getStringCellValue();
                        map.put(k, value);
                    }
                    list.add((T) map);

                } else {
                    t = clazz.newInstance();
                    int arrayIndex = 0;// 标识当前第几个数组了
                    int cellIndex = 0;// 标识当前读到这一行的第几个cell了
                    List<FieldForSortting> fields = sortFieldByAnno(clazz);
                    for (FieldForSortting ffs : fields) {
                        Field field = ffs.getField();
                        field.setAccessible(true);
                        if (field.getType().isArray()) {
                            Integer count = arrayCount[arrayIndex];
                            Object[] value = null;
                            if (field.getType().equals(String[].class)) {
                                value = new String[count];
                            } else {
                                // 目前只支持String[]和Double[]
                                value = new Double[count];
                            }
                            for (int i = 0; i < count; i++) {
                                Cell cell = row.getCell(cellIndex);
                                String errMsg = validateCell(cell, field, cellIndex);
                                if (StringUtils.isBlank(errMsg)) {
                                    value[i] = getCellValue(cell);
                                } else {
                                    log.append(errMsg);
                                    log.append(";");
                                    logs.setHasError(true);
                                }
                                cellIndex++;
                            }
                            field.set(t, value);
                            arrayIndex++;
                        } else {
                            Cell cell = row.getCell(cellIndex);
                            String errMsg = validateCell(cell, field, cellIndex);
                            if (StringUtils.isBlank(errMsg)) {
                                Object value = null;
                                // 处理特殊情况,Excel中的String,转换成Bean的Date
                                if (field.getType().equals(Date.class)
                                        && cell.getCellType() == Cell.CELL_TYPE_STRING) {
                                    Object strDate = getCellValue(cell);
                                    try {
                                        value = new SimpleDateFormat(pattern).parse(strDate.toString());
                                    } catch (ParseException e) {

                                        errMsg =
                                                MessageFormat.format("the cell [{0}] can not be converted to a date ",
                                                        CellReference.convertNumToColString(cell.getColumnIndex()));
                                    }
                                } else {
                                    value = getCellValue(cell);
                                    // 处理特殊情况,excel的value为String,且bean中为其他,且defaultValue不为空,那就=defaultValue
                                    ExcelCell annoCell = field.getAnnotation(ExcelCell.class);
                                    if (value instanceof String && !field.getType().equals(String.class)
                                            && StringUtils.isNotBlank(annoCell.defaultValue())) {
                                        value = annoCell.defaultValue();
                                    }
                                }
                                field.set(t, value);
                            }
                            if (StringUtils.isNotBlank(errMsg)) {
                                log.append(errMsg);
                                log.append(";");
                                logs.setHasError(true);
                            }
                            cellIndex++;
                        }
                    }
                    list.add(t);
                    logList.add(new ExcelLog(t, log.toString(), row.getRowNum() + 1));
                }
            }
            logs.setLogList(logList);
        } catch (InstantiationException e) {
            throw new RuntimeException(MessageFormat.format("can not instance class:{0}",
                    clazz.getSimpleName()), e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(MessageFormat.format("can not instance class:{0}",
                    clazz.getSimpleName()), e);
        }
        return list;
    }

    /**
     * 驗證Cell類型是否正確
     *
     * @param cell    cell單元格
     * @param field   欄位
     * @param cellNum 第幾個欄位,用於errMsg
     * @return
     */
    private static String validateCell(Cell cell, Field field, int cellNum) {
        String columnName = CellReference.convertNumToColString(cellNum);
        String result = null;
        Integer[] integers = validateMap.get(field.getType());
        if (integers == null) {
            result = MessageFormat.format("Unsupported type [{0}]", field.getType().getSimpleName());
            return result;
        }
        ExcelCell annoCell = field.getAnnotation(ExcelCell.class);
        if (cell == null
                || (cell.getCellType() == Cell.CELL_TYPE_STRING && StringUtils.isBlank(cell
                .getStringCellValue()))) {
            if (annoCell != null && annoCell.valid().allowNull() == false) {
                result = MessageFormat.format("the cell [{0}] can not null", columnName);
            }
            ;
        } else if (cell.getCellType() == Cell.CELL_TYPE_BLANK && annoCell.valid().allowNull()) {
            return result;
        } else {
            List<Integer> cellTypes = Arrays.asList(integers);

            // 如果類型不在指定範圍內,並且沒有默認值
            if (!(cellTypes.contains(cell.getCellType()))
                    || StringUtils.isNotBlank(annoCell.defaultValue())
                    && cell.getCellType() == Cell.CELL_TYPE_STRING) {
                StringBuilder strType = new StringBuilder();
                for (int i = 0; i < cellTypes.size(); i++) {
                    Integer intType = cellTypes.get(i);
                    strType.append(getCellTypeByInt(intType));
                    if (i != cellTypes.size() - 1) {
                        strType.append(",");
                    }
                }
                result =
                        MessageFormat.format("the cell [{0}] type must [{1}]", columnName, strType.toString());
            } else {
                // 类型符合验证,但值不在要求范围内的
                // String in
                if (annoCell.valid().in().length != 0 && cell.getCellType() == Cell.CELL_TYPE_STRING) {
                    String[] in = annoCell.valid().in();
                    String cellValue = cell.getStringCellValue();
                    boolean isIn = false;
                    for (String str : in) {
                        if (str.equals(cellValue)) {
                            isIn = true;
                        }
                    }
                    if (!isIn) {
                        result = MessageFormat.format("the cell [{0}] value must in {1}", columnName, in);
                    }
                }
                // 数字型
                if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
                    double cellValue = cell.getNumericCellValue();
                    // 小于
                    if (!Double.isNaN(annoCell.valid().lt())) {
                        if (!(cellValue < annoCell.valid().lt())) {
                            result =
                                    MessageFormat.format("the cell [{0}] value must less than [{1}]", columnName,
                                            annoCell.valid().lt());
                        }
                    }
                    // 大于
                    if (!Double.isNaN(annoCell.valid().gt())) {
                        if (!(cellValue > annoCell.valid().gt())) {
                            result =
                                    MessageFormat.format("the cell [{0}] value must greater than [{1}]", columnName,
                                            annoCell.valid().gt());
                        }
                    }
                    // 小于等于
                    if (!Double.isNaN(annoCell.valid().le())) {
                        if (!(cellValue <= annoCell.valid().le())) {
                            result =
                                    MessageFormat.format("the cell [{0}] value must less than or equal [{1}]",
                                            columnName, annoCell.valid().le());
                        }
                    }
                    // 大于等于
                    if (!Double.isNaN(annoCell.valid().ge())) {
                        if (!(cellValue >= annoCell.valid().ge())) {
                            result =
                                    MessageFormat.format("the cell [{0}] value must greater than or equal [{1}]",
                                            columnName, annoCell.valid().ge());
                        }
                    }
                }
            }
        }
        return result;
    }

    /**
     * 根据annotation的seq排序后的栏位
     *
     * @param clazz
     * @return
     */
    private static List<FieldForSortting> sortFieldByAnno(Class<?> clazz) {
        Field[] fieldsArr = clazz.getDeclaredFields();
        List<FieldForSortting> fields = new ArrayList<FieldForSortting>();
        List<FieldForSortting> annoNullFields = new ArrayList<FieldForSortting>();
        for (Field field : fieldsArr) {
            ExcelCell ec = field.getAnnotation(ExcelCell.class);
            if (ec == null) {
                // 没有ExcelCell Annotation 视为不汇入
                continue;
            }
            int id = ec.index();
            fields.add(new FieldForSortting(field, id));
        }
        fields.addAll(annoNullFields);
        sortByProperties(fields, true, false, "index");
        return fields;
    }

    @SuppressWarnings("unchecked")
    private static void sortByProperties(List<? extends Object> list, boolean isNullHigh,
                                         boolean isReversed, String... props) {
        if (CollectionUtils.isNotEmpty(list)) {
            Comparator<?> typeComp = ComparableComparator.getInstance();
            if (isNullHigh == true) {
                typeComp = ComparatorUtils.nullHighComparator(typeComp);
            } else {
                typeComp = ComparatorUtils.nullLowComparator(typeComp);
            }
            if (isReversed) {
                typeComp = ComparatorUtils.reversedComparator(typeComp);
            }

            List<Object> sortCols = new ArrayList<Object>();

            if (props != null) {
                for (String prop : props) {
                    sortCols.add(new BeanComparator(prop, typeComp));
                }
            }
            if (sortCols.size() > 0) {
                Comparator<Object> sortChain = new ComparatorChain(sortCols);
                Collections.sort(list, sortChain);
            }
        }
    }

}


text:
require File.dirname(__FILE__) + '/../spec_helper'

describe Address do

  before(:each) do
    @address = Address.new
  end

  it "should be valid" do
    address = new_address
    address.should be_valid
  end

  it "should be valid with the minimal parameters" do
    @address.street1 = "Soda Hall"
    @address.city = "Berkeley"
    @address.country = "United States"
    @address.zip = 94720
    @address.should be_valid
  end

  it "should have a street address" do
    @address.should have(1).errors_on(:street1)
  end

  it "should have a city" do
    @address.should have(1).errors_on(:city)
  end

  it "should have a zip code" do
    @address.should have(1).errors_on(:zip)
  end

  it "should have a country" do
    @address.should have(1).errors_on(:country)
  end

  it "should allow duplicate addresses" do
    address = new_address
    @address.street1 = address.street1
    @address.city = address.city
    @address.country = address.country
    @address.zip = address.zip
    address.should be_valid
    @address.should be_valid
  end

end

redpajama_set_name: RedPajamaGithub


text:
This repository demonstrates the usage of [Admin Interface](https://github.com/admin-interface/admin-interface).

## Starting App
```bash
npm install # install dependencies
npm run fixtures # load fixtures
npm start
```

This will start the application and create an sqlite database in your app dir.
Just open [http://localhost:3000/admin](http://localhost:3000/admin).


text: kngsnh.github.io


text:
<!DOCTYPE html>

	<meta charset="UTF-8" />

	<title>Mobile Password Manager</title>
	<link rel="icon" type="image/png" href="chrome://mobile_password_manager/content/assets/hdpi.png" />
	<link rel="stylesheet" type="text/css" href="chrome://mobile_password_manager/content/viewer.css" />
	<link rel="prefetch" href="chrome://mobile_password_manager/content/editor.html" />

	<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />

					<input placeholder="Filter" id="filter" size="11">
					<select id="filterwhich">
					 <option value="1">All</option>
					 <option value="2">Site</option>
					 <option value="3">Username</option>
					</select>

		<form id="editor_form">

					<select id="login_type" onchange="updateForm()">
						<option id="web_form_option" value="web_form"></option>
						<option id="http_auth_option" value="http_auth"></option>
					</select>

					<input id="in_hostname" type="text" maxlength="900" />

					<input id="in_form_submit_url" type="text" maxlength="900" />

					<input id="in_realm" type="text" disabled="disabled" maxlength="100" />

					<input id="in_username" type="text" maxlength="100" />

						<input id="mobile_password_manager_cant_touch_this" type="password" maxlength="100" />

					<input id="in_username_field" type="text" maxlength="100" />

					<input id="in_password_field" type="text" maxlength="100" />

		</form>


text:
<?xml version="1.0" encoding="UTF-8"?>
<folder exportedWithPermissions="true">
    <parent>/organizations/organization_1/organizations/org_template</parent>
    <name>adhoc</name>
    <label>Ad Hoc Components</label>
    <description>Ad Hoc Components</description>
    <creationDate>2015-05-27T15:05:14.510-07:00</creationDate>
    <updateDate>2015-05-27T15:05:11.808-07:00</updateDate>
    <folder>topics</folder>
</folder>


text:
import { Component, OnInit } from '@angular/core';
import { AuthService, IUser } from '../../auth.service';
import { PortalUser, SexType } from '../../Models/User';
import { localeConfig } from '../../calendar-app-config.service'
@Component({
    moduleId: module.id,
    selector: 'userdetails',
    templateUrl: 'userdetails-g.component.html'
})
export class UserDetailsComponent implements OnInit {
    submitted: boolean;
    modelUser: PortalUser;
    sexList: boolean[];
    locale: any;

    // datepickerOption: DatePickerOptions;
    // datepickerModel: DateModel;

    courseListConfig = { columns: ['Name', 'Lecturer'] };

    constructor(public _authService: AuthService) {
        this.modelUser = {
            id: -1,
            FirstName: _authService.getUserName().given_name,
            LastName: _authService.getUserName().family_name
        };
        this.submitted = true;
        this.sexList = [false, false];
        this.locale = localeConfig;
        // this.datepickerOption = { locale: 'ru', firstWeekdaySunday: false, style: 'bold' };
    }

    ngOnInit() { }

    onSubmit() {
        this.submitted = true;
        console.log('form after submit: ', this.modelUser);
    }

    formReset() {
        this.submitted = false;
    }

    sexListToggle(index: number) {
        if (this.submitted) {
            return;
        }
        this.sexList[index] = true;
        this.sexList[1 - index] = false;
        this.modelUser.Sex = SexType[SexType[1 - index]];
    }
}


text:
using System.IO;
using Machine.Specifications;

namespace Sourcery.Tests.FileSource
{
    [Subject(typeof (Sources.FileSource), "GetAsText")]
    public class When_I_get_a_file_as_text_twice
    {
        private static string _testFile;
        private static ISource _sut;
        private static string _text1;
        private static string _testContent;
        private static string _text2;

        private Establish context = () =>
        {
            _testFile = Path.GetTempFileName();
            _testContent = "This is some example content";

            File.WriteAllText(_testFile, _testContent);

            _sut = Source.FromFile(_testFile);
        };

        private Because of = () =>
        {
            _text1 = _sut.GetAsText();
            _text2 = _sut.GetAsText();
        };

        private It should_return_all_lines_the_first_time = () => _text1.ShouldEqual(_testContent);

        private It should_return_all_lines_the_second_time = () => _text2.ShouldEqual(_testContent);

        private Cleanup stuff = () => File.Delete(_testFile);
    }
}


text:
import { UNDEFINED } from "../types/primitive-type";

export default function MetaProperty (node, context) {
  if (node.meta.name === "new" && node.property.name === "target") {
    return context.result(context.env.current.getMeta("newTarget") || UNDEFINED);
  }

  throw SyntaxError(`Unknown MetaProperty: ${node.meta.name}.${node.property.name}`);
}


text:
<input type="text" value="" id="archivo">

<input type="button" value="Abrir archivo de Excel" onclick="openB()">

<script language="javascript">
function runApp()
{
var excApp = new ActiveXObject("Excel.Application");
excApp.visible = false;
var excBook = excApp.Workbooks.open("d:\\prueba.xlsx");
alert(excBook);

alert(excBook.close);
excBook.close();

}

function openB() {
var archivo = document.getElementById("archivo").value;

var excel=new ActiveXObject("Excel.Application");
var book=excel.Workbooks.Open(archivo);
var sheet=book.Sheets.Item(1);
var value=sheet.Range("A1");
alert(value);
}

</script>


text:
package org.jbehave.core.annotations;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.jbehave.core.embedder.Embedder;

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE })
@Inherited
@Documented
public @interface UsingEmbedder {

    Class<?> embedder() default Embedder.class;
    boolean batch()  default false;
	boolean skip()  default false;
	boolean generateViewAfterStories()  default true;
	boolean ignoreFailureInStories()  default false;
	boolean ignoreFailureInView()  default false;
	boolean verboseFailures() default false;
    boolean verboseFiltering() default false;
    String storyTimeouts() default "";
    /** @deprecated Use storyTimeouts() */
    @Deprecated long storyTimeoutInSecs() default 300;
    /** @deprecated Use storyTimeouts() */
    @Deprecated String storyTimeoutInSecsByPath() default "";
    boolean failOnStoryTimeout() default false;
	int threads() default 1;
	boolean stepsFactory() default true;
    String[] metaFilters() default {};
    String systemProperties() default "";

}


text:
.. _resource:

Resource
--------
.. automodule:: rdflib.resource
.. :noindex:


text:
<?php

namespace Zend\Http\Header;

use Zend\Uri\UriFactory;

/**
 * @throws Exception\InvalidArgumentException
 * @see http://tools.ietf.org/id/draft-abarth-origin-03.html#rfc.section.2
 */
class Origin implements HeaderInterface
{
    /**
     * @var string
     */
    protected $value = '';

    public static function fromString($headerLine)
    {
        list($name, $value) = explode(': ', $headerLine, 2);

        // check to ensure proper header type for this factory
        if (strtolower($name) !== 'origin') {
            throw new Exception\InvalidArgumentException('Invalid header line for Origin string: "' . $name . '"');
        }

        $uri = UriFactory::factory($value);
        if (! $uri->isValid()) {
            throw new Exception\InvalidArgumentException('Invalid header value for Origin key: "' . $name . '"');
        }

        return new static($value);
    }

    /**
     * @param string|null $value
     */
    public function __construct($value = null)
    {
        if ($value !== null) {
            HeaderValue::assertValid($value);
            $this->value = $value;
        }
    }

    public function getFieldName()
    {
        return 'Origin';
    }

    public function getFieldValue()
    {
        return (string) $this->value;
    }

    public function toString()
    {
        return 'Origin: ' . $this->getFieldValue();
    }
}


text:
#include "logging.hpp"

#include "PE/json_internal.hpp"
#include "LIEF/PE.hpp"

#include "Object.tcc"

namespace LIEF {
namespace PE {

std::string to_hex(const char c) {
  std::stringstream ss;
  ss << std::setfill('0') << std::setw(2) << std::hex << (0xff & (unsigned int)c);
  return std::string("\\x") + ss.str();
}

std::string escape_non_ascii(const std::string& s) {
  std::string result;
  const auto len = s.size();
  for (auto i = 0u; i < len; i++) {
    const auto c = s[i];
    if (c < 32 || c >= 127) {
      result += to_hex(c);
    } else {
      result.push_back(c);
    }
  }
  return result;
}

void JsonVisitor::visit(const Binary& binary) {
  node_["name"]         = binary.name();
  node_["entrypoint"]   = binary.entrypoint();
  node_["virtual_size"] = binary.virtual_size();

  // DOS Header
  JsonVisitor dos_header_visitor;
  dos_header_visitor(binary.dos_header());

  // Rich Header
  if (binary.has_rich_header()) {
    JsonVisitor visitor;
    visitor(binary.rich_header());
    node_["rich_header"] = visitor.get();
  }

  // PE header
  JsonVisitor header_visitor;
  header_visitor(binary.header());

  // PE Optional Header
  JsonVisitor optional_header_visitor;
  optional_header_visitor(binary.optional_header());

  node_["dos_header"]      = dos_header_visitor.get();
  node_["header"]          = header_visitor.get();
  node_["optional_header"] = optional_header_visitor.get();

  // Data directories
  std::vector<json> data_directories;
  for (const DataDirectory& data_directory : binary.data_directories()) {
    JsonVisitor visitor;
    visitor(data_directory);
    data_directories.emplace_back(visitor.get());
  }
  node_["data_directories"] = data_directories;

  // Section
  std::vector<json> sections;
  for (const Section& section : binary.sections()) {
    JsonVisitor visitor;
    visitor(section);
    sections.emplace_back(visitor.get());
  }
  node_["sections"] = sections;

  // Relocations
  if (binary.has_relocations()) {
    std::vector<json> relocations;
    for (const Relocation& relocation : binary.relocations()) {
      JsonVisitor visitor;
      visitor(relocation);
      relocations.emplace_back(visitor.get());
    }
    node_["relocations"] = relocations;
  }

  // TLS
  if (binary.has_tls()) {
    JsonVisitor visitor;
    visitor(binary.tls());
    node_["tls"] = visitor.get();
  }

  // Exports
  if (binary.has_exports()) {
    JsonVisitor visitor;
    visitor(binary.get_export());
    node_["export"] = visitor.get();
  }

  // Debug
  if (binary.has_debug()) {
    std::vector<json> debug_entries;
    for (const Debug& debug : binary.debug()) {
      JsonVisitor visitor;
      visitor(debug);
      debug_entries.emplace_back(visitor.get());
    }
    node_["debug"] = debug_entries;
  }

  // Imports
  if (binary.has_imports()) {
    std::vector<json> imports;
    for (const Import& import : binary.imports()) {
      JsonVisitor visitor;
      visitor(import);
      imports.emplace_back(visitor.get());
    }
    node_["imports"] = imports;
  }

  // Delay Imports
  if (binary.has_delay_imports()) {
    std::vector<json> imports;
    for (const DelayImport& import : binary.delay_imports()) {
      JsonVisitor visitor;
      visitor(import);
      imports.emplace_back(visitor.get());
    }
    node_["delay_imports"] = imports;
  }

  // Resources
  if (binary.has_resources()) {
    JsonVisitor visitor;
    binary.resources()->accept(visitor);

    JsonVisitor manager_visitor;

    if (auto manager = binary.resources_manager()) {
      manager->accept(manager_visitor);
    }

    node_["resources_tree"]    = visitor.get();
    node_["resources_manager"] = manager_visitor.get();
  }

  // Signatures
  std::vector<json> sigs;
  if (binary.has_signatures()) {
    for (const Signature& sig : binary.signatures()) {
      JsonVisitor visitor;
      visitor(sig);
      sigs.push_back(visitor.get());
    }
    node_["signatures"] = sigs;
  }

  std::vector<json> symbols;
  for (const Symbol& symbol : binary.symbols()) {
    JsonVisitor visitor;
    visitor(symbol);
    symbols.emplace_back(visitor.get());
  }
  if (!symbols.empty()) {
    node_["symbols"] = symbols;
  }

  // Load Configuration
  if (binary.has_configuration()) {
    JsonVisitor visitor;
    const LoadConfiguration* config = binary.load_configuration();
    config->accept(visitor);
    node_["load_configuration"] = visitor.get();
  }

}

void JsonVisitor::visit(const DosHeader& dos_header) {
  node_["magic"]                       = dos_header.magic();
  node_["used_bytes_in_the_last_page"] = dos_header.used_bytes_in_the_last_page();
  node_["file_size_in_pages"]          = dos_header.file_size_in_pages();
  node_["numberof_relocation"]         = dos_header.numberof_relocation();
  node_["header_size_in_paragraphs"]   = dos_header.header_size_in_paragraphs();
  node_["minimum_extra_paragraphs"]    = dos_header.minimum_extra_paragraphs();
  node_["maximum_extra_paragraphs"]    = dos_header.maximum_extra_paragraphs();
  node_["initial_relative_ss"]         = dos_header.initial_relative_ss();
  node_["initial_sp"]                  = dos_header.initial_sp();
  node_["checksum"]                    = dos_header.checksum();
  node_["initial_ip"]                  = dos_header.initial_ip();
  node_["initial_relative_cs"]         = dos_header.initial_relative_cs();
  node_["addressof_relocation_table"]  = dos_header.addressof_relocation_table();
  node_["overlay_number"]              = dos_header.overlay_number();
  node_["reserved"]                    = dos_header.reserved();
  node_["oem_id"]                      = dos_header.oem_id();
  node_["oem_info"]                    = dos_header.oem_info();
  node_["reserved2"]                   = dos_header.reserved2();
  node_["addressof_new_exeheader"]     = dos_header.addressof_new_exeheader();
}

void JsonVisitor::visit(const RichHeader& rich_header) {
  std::vector<json> entries;
  for (const RichEntry& entry : rich_header.entries()) {
    JsonVisitor visitor;
    visitor(entry);
    entries.emplace_back(visitor.get());
  }

  node_["key"]     = rich_header.key();
  node_["entries"] = entries;
}

void JsonVisitor::visit(const RichEntry& rich_entry) {

  node_["id"]       = rich_entry.id();
  node_["build_id"] = rich_entry.build_id();
  node_["count"]    = rich_entry.count();
}

void JsonVisitor::visit(const Header& header) {

  node_["signature"]              = header.signature();
  node_["machine"]                = to_string(header.machine());
  node_["numberof_sections"]      = header.numberof_sections();
  node_["time_date_stamp"]        = header.time_date_stamp();
  node_["pointerto_symbol_table"] = header.pointerto_symbol_table();
  node_["numberof_symbols"]       = header.numberof_symbols();
  node_["sizeof_optional_header"] = header.sizeof_optional_header();
  node_["characteristics"]        = static_cast<size_t>(header.characteristics());
}

void JsonVisitor::visit(const OptionalHeader& optional_header) {

  node_["magic"]                          = to_string(optional_header.magic());
  node_["major_linker_version"]           = optional_header.major_linker_version();
  node_["minor_linker_version"]           = optional_header.minor_linker_version();
  node_["sizeof_code"]                    = optional_header.sizeof_code();
  node_["sizeof_initialized_data"]        = optional_header.sizeof_initialized_data();
  node_["sizeof_uninitialized_data"]      = optional_header.sizeof_uninitialized_data();
  node_["addressof_entrypoint"]           = optional_header.addressof_entrypoint();
  node_["baseof_code"]                    = optional_header.baseof_code();
  if (optional_header.magic() == PE_TYPE::PE32) {
    node_["baseof_data"]     = optional_header.baseof_data();
  }
  node_["imagebase"]                      = optional_header.imagebase();
  node_["section_alignment"]              = optional_header.section_alignment();
  node_["file_alignment"]                 = optional_header.file_alignment();
  node_["major_operating_system_version"] = optional_header.major_operating_system_version();
  node_["minor_operating_system_version"] = optional_header.minor_operating_system_version();
  node_["major_image_version"]            = optional_header.major_image_version();
  node_["minor_image_version"]            = optional_header.minor_image_version();
  node_["major_subsystem_version"]        = optional_header.major_subsystem_version();
  node_["minor_subsystem_version"]        = optional_header.minor_subsystem_version();
  node_["win32_version_value"]            = optional_header.win32_version_value();
  node_["sizeof_image"]                   = optional_header.sizeof_image();
  node_["sizeof_headers"]                 = optional_header.sizeof_headers();
  node_["checksum"]                       = optional_header.checksum();
  node_["subsystem"]                      = to_string(optional_header.subsystem());
  node_["dll_characteristics"]            = optional_header.dll_characteristics();
  node_["sizeof_stack_reserve"]           = optional_header.sizeof_stack_reserve();
  node_["sizeof_stack_commit"]            = optional_header.sizeof_stack_commit();
  node_["sizeof_heap_reserve"]            = optional_header.sizeof_heap_reserve();
  node_["sizeof_heap_commit"]             = optional_header.sizeof_heap_commit();
  node_["loader_flags"]                   = optional_header.loader_flags();
  node_["numberof_rva_and_size"]          = optional_header.numberof_rva_and_size();
}

void JsonVisitor::visit(const DataDirectory& data_directory) {

  node_["RVA"]  = data_directory.RVA();
  node_["size"] = data_directory.size();
  node_["type"] = to_string(data_directory.type());
  if (data_directory.has_section()) {
    node_["section"] = escape_non_ascii(data_directory.section()->name());
  }
}

void JsonVisitor::visit(const Section& section) {

  std::vector<json> characteristics;
  for (SECTION_CHARACTERISTICS c : section.characteristics_list()) {
    characteristics.emplace_back(to_string(c));
  }

  std::vector<json> types;
  for (PE_SECTION_TYPES t : section.types()) {
    types.emplace_back(to_string(t));
  }

  node_["name"]                   = escape_non_ascii(section.name());
  node_["pointerto_relocation"]   = section.pointerto_relocation();
  node_["pointerto_line_numbers"] = section.pointerto_line_numbers();
  node_["numberof_relocations"]   = section.numberof_relocations();
  node_["numberof_line_numbers"]  = section.numberof_line_numbers();
  node_["entropy"]                = section.entropy();
  node_["characteristics"]        = characteristics;
  node_["types"]                  = types;
}

void JsonVisitor::visit(const Relocation& relocation) {

  std::vector<json> entries;
  for (const RelocationEntry& entry : relocation.entries()) {
    JsonVisitor visitor;
    visitor(entry);
    entries.emplace_back(visitor.get());
  }

  node_["virtual_address"] = relocation.virtual_address();
  node_["block_size"]      = relocation.block_size();
  node_["entries"]         = entries;
}

void JsonVisitor::visit(const RelocationEntry& relocation_entry) {

  node_["data"]     = relocation_entry.data();
  node_["position"] = relocation_entry.position();
  node_["type"]     = to_string(relocation_entry.type());
}

void JsonVisitor::visit(const Export& export_) {

  std::vector<json> entries;
  for (const ExportEntry& entry : export_.entries()) {
    JsonVisitor visitor;
    visitor(entry);
    entries.emplace_back(visitor.get());
  }
  node_["export_flags"]  = export_.export_flags();
  node_["timestamp"]     = export_.timestamp();
  node_["major_version"] = export_.major_version();
  node_["minor_version"] = export_.minor_version();
  node_["ordinal_base"]  = export_.ordinal_base();
  node_["name"]          = escape_non_ascii(export_.name());
  node_["entries"]       = entries;
}

void JsonVisitor::visit(const ExportEntry& export_entry) {

  node_["name"]      = escape_non_ascii(export_entry.name());
  node_["ordinal"]   = export_entry.ordinal();
  node_["address"]   = export_entry.address();
  node_["is_extern"] = export_entry.is_extern();

  if (export_entry.is_forwarded()) {
    const ExportEntry::forward_information_t& fwd_info = export_entry.forward_information();
    node_["forward_information"] = {
      {"library",  fwd_info.library},
      {"function", fwd_info.function},
    };
  }
}

void JsonVisitor::visit(const TLS& tls) {

  node_["callbacks"]           = tls.callbacks();
  node_["addressof_raw_data"]  = std::vector<uint64_t>{tls.addressof_raw_data().first, tls.addressof_raw_data().second};
  node_["addressof_index"]     = tls.addressof_index();
  node_["addressof_callbacks"] = tls.addressof_callbacks();
  node_["sizeof_zero_fill"]    = tls.sizeof_zero_fill();
  node_["characteristics"]     = tls.characteristics();

  if (tls.has_data_directory()) {
    node_["data_directory"] = to_string(tls.directory()->type());
  }

  if (tls.has_section()) {
    node_["section"] = escape_non_ascii(tls.section()->name());
  }
}

void JsonVisitor::visit(const Symbol& symbol) {

  node_["value"]                = symbol.value();
  node_["size"]                 = symbol.size();
  node_["name"]                 = escape_non_ascii(symbol.name());

  node_["section_number"]       = symbol.section_number();
  node_["type"]                 = symbol.type();
  node_["base_type"]            = to_string(symbol.base_type());
  node_["complex_type"]         = to_string(symbol.complex_type());
  node_["storage_class"]        = to_string(symbol.storage_class());
  node_["numberof_aux_symbols"] = symbol.numberof_aux_symbols();

  if (symbol.has_section()) {
    node_["section"] = symbol.section()->name();
  }
}

void JsonVisitor::visit(const Debug& debug) {

  node_["characteristics"]   = debug.characteristics();
  node_["timestamp"]         = debug.timestamp();
  node_["major_version"]     = debug.major_version();
  node_["minor_version"]     = debug.minor_version();
  node_["type"]              = to_string(debug.type());
  node_["sizeof_data"]       = debug.sizeof_data();
  node_["addressof_rawdata"] = debug.addressof_rawdata();
  node_["pointerto_rawdata"] = debug.pointerto_rawdata();

  if (debug.has_code_view()) {
    JsonVisitor codeview_visitor;
    const CodeView* codeview = debug.code_view();
    codeview->accept(codeview_visitor);
    node_["code_view"] = codeview_visitor.get();
  }

  if (debug.has_pogo()) {
    JsonVisitor pogo_visitor;
    const Pogo* pogo = debug.pogo();
    pogo->accept(pogo_visitor);
    node_["pogo"] = pogo_visitor.get();
  }
}

void JsonVisitor::visit(const CodeView& cv) {

  node_["cv_signature"] = to_string(cv.cv_signature());
}

void JsonVisitor::visit(const CodeViewPDB& cvpdb) {

  visit(static_cast<const CodeView&>(cvpdb));
  node_["signature"] = cvpdb.signature();
  node_["age"]       = cvpdb.age();
  node_["filename"]  = escape_non_ascii(cvpdb.filename());
}

void JsonVisitor::visit(const DelayImport& import) {

  std::vector<json> entries;
  for (const DelayImportEntry& entry : import.entries()) {
    JsonVisitor visitor;
    visitor(entry);
    entries.emplace_back(visitor.get());
  }
  node_["attribute"]   = import.attribute();
  node_["name"]        = import.name();
  node_["handle"]      = import.handle();
  node_["iat"]         = import.iat();
  node_["names_table"] = import.names_table();
  node_["biat"]        = import.biat();
  node_["uiat"]        = import.uiat();
  node_["timestamp"]   = import.timestamp();
  node_["entries"]     = entries;
}

void JsonVisitor::visit(const DelayImportEntry& import_entry) {
  if (import_entry.is_ordinal()) {
    node_["ordinal"] = import_entry.ordinal();
  } else {
    node_["name"] = import_entry.name();
  }

  node_["value"]       = import_entry.value();
  node_["iat_address"] = import_entry.iat_value();
  node_["data"]        = import_entry.data();
  node_["hint"]        = import_entry.hint();
}

void JsonVisitor::visit(const Import& import) {

  std::vector<json> entries;
  for (const ImportEntry& entry : import.entries()) {
    JsonVisitor visitor;
    visitor(entry);
    entries.emplace_back(visitor.get());
  }

  node_["forwarder_chain"]          = import.forwarder_chain();
  node_["timedatestamp"]            = import.timedatestamp();
  node_["import_address_table_rva"] = import.import_address_table_rva();
  node_["import_lookup_table_rva"]  = import.import_lookup_table_rva();
  node_["name"]                     = import.name();
  node_["entries"]                  = entries;

}

void JsonVisitor::visit(const ImportEntry& import_entry) {

  if (import_entry.is_ordinal()) {
    node_["ordinal"] = import_entry.ordinal();
  } else {
    node_["name"] = import_entry.name();
  }

  node_["iat_address"] = import_entry.iat_address();
  node_["data"]        = import_entry.data();
  node_["hint"]        = import_entry.hint();
}

void JsonVisitor::visit(const ResourceData& resource_data) {

  node_["code_page"] = resource_data.code_page();
  node_["reserved"]  = resource_data.reserved();
  node_["offset"]    = resource_data.offset();
  node_["hash"]      = Hash::hash(resource_data.content());

}

void JsonVisitor::visit(const ResourceNode& resource_node) {

  node_["id"] = resource_node.id();

  if (resource_node.has_name()) {
    node_["name"] = u16tou8(resource_node.name());
  }

  if (resource_node.childs().size() > 0) {
    std::vector<json> childs;
    for (const ResourceNode& rsrc : resource_node.childs()) {
      JsonVisitor visitor;
      rsrc.accept(visitor);
      childs.emplace_back(visitor.get());
    }

    node_["childs"] = childs;
  }

}

void JsonVisitor::visit(const ResourceDirectory& resource_directory) {

  node_["id"] = resource_directory.id();

  if (resource_directory.has_name()) {
    node_["name"] = u16tou8(resource_directory.name());
  }

  node_["characteristics"]       = resource_directory.characteristics();
  node_["time_date_stamp"]       = resource_directory.time_date_stamp();
  node_["major_version"]         = resource_directory.major_version();
  node_["minor_version"]         = resource_directory.minor_version();
  node_["numberof_name_entries"] = resource_directory.numberof_name_entries();
  node_["numberof_id_entries"]   = resource_directory.numberof_id_entries();

  if (resource_directory.childs().size() > 0) {
    std::vector<json> childs;
    for (const ResourceNode& rsrc : resource_directory.childs()) {
      JsonVisitor visitor;
      rsrc.accept(visitor);
      childs.emplace_back(visitor.get());
    }

    node_["childs"] = childs;
  }
}

void JsonVisitor::visit(const ResourcesManager& resources_manager) {

  if (resources_manager.has_manifest()) {
    node_["manifest"] = escape_non_ascii(resources_manager.manifest()) ;
  }

  if (resources_manager.has_html()) {
    std::vector<std::string> escaped_strs;
    for (const std::string& elem : resources_manager.html()) {
      escaped_strs.emplace_back(escape_non_ascii(elem));
    }
    node_["html"] = escaped_strs;
  }

  if (resources_manager.has_version()) {
    JsonVisitor version_visitor;
    if (auto version = resources_manager.version()) {
      version_visitor(*version);
    }
    node_["version"] = version_visitor.get();
  }

  if (resources_manager.has_icons()) {
    std::vector<json> icons;
    for (const ResourceIcon& icon : resources_manager.icons()) {
      JsonVisitor icon_visitor;
      icon_visitor(icon);
      icons.emplace_back(icon_visitor.get());
    }
    node_["icons"] = icons;
  }

  if (resources_manager.has_dialogs()) {
    std::vector<json> dialogs;
    for (const ResourceDialog& dialog : resources_manager.dialogs()) {
      JsonVisitor dialog_visitor;
      dialog_visitor(dialog);
      dialogs.emplace_back(dialog_visitor.get());
    }
    node_["dialogs"] = dialogs;
  }

  if (resources_manager.has_string_table()) {
    std::vector<json> string_table_json;
    for (const ResourceStringTable& string_table : resources_manager.string_table()) {
      JsonVisitor string_table_visitor;
      string_table_visitor(string_table);
      string_table_json.emplace_back(string_table_visitor.get());
    }
    node_["string_table"] = string_table_json;
  }

  if (resources_manager.has_accelerator()) {
    std::vector<json> accelerator_json;
    for (const ResourceAccelerator& acc : resources_manager.accelerator()) {
      JsonVisitor accelerator_visitor;
      accelerator_visitor(acc);
      accelerator_json.emplace_back(accelerator_visitor.get());
    }
    node_["accelerator"] = accelerator_json;
  }
}

void JsonVisitor::visit(const ResourceStringFileInfo& resource_sfi) {

  std::vector<json> langcode_items;
  for (const LangCodeItem& item : resource_sfi.langcode_items()) {
    JsonVisitor langcode_visitor;
    langcode_visitor(item);
    langcode_items.emplace_back(langcode_visitor.get());
  }

  node_["type"]  = resource_sfi.type();
  node_["key"]   = u16tou8(resource_sfi.key());
  node_["langcode_items"] = langcode_items;
}

void JsonVisitor::visit(const ResourceFixedFileInfo& resource_ffi) {

  node_["signature"]          = resource_ffi.signature();
  node_["struct_version"]     = resource_ffi.struct_version();
  node_["file_version_MS"]    = resource_ffi.file_version_MS();
  node_["file_version_LS"]    = resource_ffi.file_version_LS();
  node_["product_version_MS"] = resource_ffi.product_version_MS();
  node_["product_version_LS"] = resource_ffi.product_version_LS();
  node_["file_flags_mask"]    = resource_ffi.file_flags_mask();
  node_["file_flags"]         = resource_ffi.file_flags();
  node_["file_os"]            = to_string(resource_ffi.file_os());
  node_["file_type"]          = to_string(resource_ffi.file_type());
  node_["file_subtype"]       = to_string(resource_ffi.file_subtype());
  node_["file_date_MS"]       = resource_ffi.file_date_MS();
  node_["file_date_LS"]       = resource_ffi.file_date_LS();
}

void JsonVisitor::visit(const ResourceVarFileInfo& resource_vfi) {

  node_["type"]         = resource_vfi.type();
  node_["key"]          = u16tou8(resource_vfi.key());
  node_["translations"] = resource_vfi.translations();
}

void JsonVisitor::visit(const LangCodeItem& resource_lci) {

  std::map<std::string, std::string> items;
  std::transform(
      std::begin(resource_lci.items()), std::end(resource_lci.items()),
      std::insert_iterator<decltype(items)>(items, std::end(items)),
      [] (const std::pair<std::u16string, std::u16string>& p) {
        return std::pair<std::string, std::string>{u16tou8(p.first), u16tou8(p.second)};
      });

  node_["type"]  = resource_lci.type();
  node_["key"]   = u16tou8(resource_lci.key());
  node_["items"] = items;

}

void JsonVisitor::visit(const ResourceVersion& resource_version) {

  node_["type"] = resource_version.type();
  node_["key"]  = u16tou8(resource_version.key());

  if (resource_version.has_fixed_file_info()) {
    JsonVisitor visitor;
    visitor(*resource_version.fixed_file_info());
    node_["fixed_file_info"] = visitor.get();
  }

  if (resource_version.has_string_file_info()) {
    JsonVisitor visitor;
    visitor(*resource_version.string_file_info());
    node_["string_file_info"] = visitor.get();
  }

  if (resource_version.has_var_file_info()) {
    JsonVisitor visitor;
    visitor(*resource_version.var_file_info());
    node_["var_file_info"] = visitor.get();
  }
}

void JsonVisitor::visit(const ResourceIcon& resource_icon) {

  node_["id"]          = resource_icon.id();
  node_["lang"]        = to_string(resource_icon.lang());
  node_["sublang"]     = to_string(resource_icon.sublang());
  node_["width"]       = resource_icon.width();
  node_["height"]      = resource_icon.height();
  node_["color_count"] = resource_icon.color_count();
  node_["reserved"]    = resource_icon.reserved();
  node_["planes"]      = resource_icon.planes();
  node_["bit_count"]   = resource_icon.bit_count();
  node_["pixels"]      = Hash::hash(resource_icon.pixels());
}

void JsonVisitor::visit(const ResourceDialog& dialog) {

  node_["x"]              = dialog.x();
  node_["y"]              = dialog.y();
  node_["cx"]             = dialog.cx();
  node_["cy"]             = dialog.cy();
  node_["style"]          = dialog.style();
  node_["extended_style"] = dialog.extended_style();

  std::vector<json> dialog_items;
  for (const ResourceDialogItem& item : dialog.items()) {
    JsonVisitor dialogitem_visitor;
    dialogitem_visitor(item);
    dialog_items.emplace_back(dialogitem_visitor.get());
  }

  node_["items"] = dialog_items;

  if (dialog.is_extended()) {
    node_["version"]    = dialog.version();
    node_["signature"]  = dialog.signature();
    node_["help_id"]    = dialog.help_id();
    node_["weight"]     = dialog.weight();
    node_["point_size"] = dialog.point_size();
    node_["is_italic"]  = dialog.is_italic();
    node_["charset"]    = dialog.charset();
    node_["title"]      = u16tou8(dialog.title());
    node_["typeface"]   = u16tou8(dialog.typeface());
  }
}

void JsonVisitor::visit(const ResourceDialogItem& dialog_item) {

  node_["id"]             = dialog_item.id();
  node_["x"]              = dialog_item.x();
  node_["y"]              = dialog_item.y();
  node_["cx"]             = dialog_item.cx();
  node_["cy"]             = dialog_item.cy();
  node_["style"]          = dialog_item.style();
  node_["extended_style"] = dialog_item.extended_style();

  if (dialog_item.is_extended()) {
    node_["title"]   = u16tou8(dialog_item.title());
    node_["help_id"] = dialog_item.help_id();
  }

}

void JsonVisitor::visit(const ResourceStringTable& string_table) {

  node_["length"] = string_table.length();
  node_["name"] = u16tou8(string_table.name());
}

void JsonVisitor::visit(const ResourceAccelerator& acc) {

  std::vector<json> flags;
  for (const ACCELERATOR_FLAGS c : acc.flags_list()) {
    flags.emplace_back(to_string(c));
  }
  node_["flags"]   = flags;
  node_["ansi"]    = acc.ansi_str();
  node_["id"]      = acc.id();
  node_["padding"] = acc.padding();
}

void JsonVisitor::visit(const Signature& signature) {

  JsonVisitor content_info_visitor;
  content_info_visitor(signature.content_info());

  std::vector<json> jsigners;
  for (const SignerInfo& signer : signature.signers()) {
    JsonVisitor visitor;
    visitor(signer);
    jsigners.emplace_back(visitor.get());
  }

  std::vector<json> crts;
  for (const x509& crt : signature.certificates()) {
    JsonVisitor crt_visitor;
    crt_visitor(crt);
    crts.emplace_back(crt_visitor.get());
  }

  node_["digest_algorithm"] = to_string(signature.digest_algorithm());
  node_["version"]          = signature.version();
  node_["content_info"]     = content_info_visitor.get();
  node_["signer_info"]      = jsigners;
  node_["certificates"]     = crts;
}

void JsonVisitor::visit(const x509& x509) {

  node_["serial_number"]       = x509.serial_number();
  node_["version"]             = x509.version();
  node_["issuer"]              = x509.issuer();
  node_["subject"]             = x509.subject();
  node_["signature_algorithm"] = x509.signature_algorithm();
  node_["valid_from"]          = x509.valid_from();
  node_["valid_to"]            = x509.valid_to();
}

void JsonVisitor::visit(const SignerInfo& signerinfo) {

  std::vector<json> auth_attrs;
  for (const Attribute& attr : signerinfo.authenticated_attributes()) {
    JsonVisitor visitor;
    visitor(attr);
    auth_attrs.emplace_back(visitor.get());
  }

  std::vector<json> unauth_attrs;
  for (const Attribute& attr : signerinfo.unauthenticated_attributes()) {
    JsonVisitor visitor;
    visitor(attr);
    auth_attrs.emplace_back(visitor.get());
  }

  node_["version"]                    = signerinfo.version();
  node_["digest_algorithm"]           = to_string(signerinfo.digest_algorithm());
  node_["encryption_algorithm"]       = to_string(signerinfo.encryption_algorithm());
  node_["encrypted_digest"]           = signerinfo.encrypted_digest();
  node_["issuer"]                     = signerinfo.issuer();
  node_["serial_number"]              = signerinfo.serial_number();
  node_["authenticated_attributes"]   = auth_attrs;
  node_["unauthenticated_attributes"] = unauth_attrs;
}

void JsonVisitor::visit(const ContentInfo& contentinfo) {

  node_["content_type"]     = contentinfo.content_type();
  node_["digest_algorithm"] = to_string(contentinfo.digest_algorithm());
  node_["digest"]           = contentinfo.digest();
  node_["file"]             = contentinfo.file();
}

void JsonVisitor::visit(const Attribute& auth) {

  node_["type"] = to_string(auth.type());
}

void JsonVisitor::visit(const ContentType& attr) {

  visit(*attr.as<Attribute>());
  node_["oid"] = attr.oid();
}

void JsonVisitor::visit(const GenericType& attr) {

  visit(*attr.as<Attribute>());
  node_["oid"] = attr.oid();
}

void JsonVisitor::visit(const MsSpcNestedSignature& attr) {

  visit(*attr.as<Attribute>());
  JsonVisitor visitor;
  visitor(attr.sig());
  node_["signature"] = visitor.get();
}

void JsonVisitor::visit(const MsSpcStatementType& attr) {

  visit(*attr.as<Attribute>());
  node_["oid"] = attr.oid();
}

void JsonVisitor::visit(const PKCS9AtSequenceNumber& attr) {

  visit(*attr.as<Attribute>());
  node_["number"] = attr.number();
}
void JsonVisitor::visit(const PKCS9CounterSignature& attr) {

  visit(*attr.as<Attribute>());

  JsonVisitor visitor;
  visitor(attr.signer());
  node_["signer"] = visitor.get();
}

void JsonVisitor::visit(const PKCS9MessageDigest& attr) {

  visit(*attr.as<Attribute>());
  node_["digest"] = attr.digest();
}

void JsonVisitor::visit(const PKCS9SigningTime& attr) {

  visit(*attr.as<Attribute>());
  node_["time"] = attr.time();
}

void JsonVisitor::visit(const SpcSpOpusInfo& attr) {

  visit(*attr.as<Attribute>());
  node_["more_info"]    = attr.more_info();
  node_["program_name"] = attr.program_name();
}

void JsonVisitor::visit(const CodeIntegrity& code_integrity) {

  node_["flags"]          = code_integrity.flags();
  node_["catalog"]        = code_integrity.catalog();
  node_["catalog_offset"] = code_integrity.catalog_offset();
  node_["reserved"]       = code_integrity.reserved();
}

void JsonVisitor::visit(const LoadConfiguration& config) {

  node_["version"]                          = to_string(config.version());
  node_["characteristics"]                  = config.characteristics();
  node_["timedatestamp"]                    = config.timedatestamp();
  node_["major_version"]                    = config.major_version();
  node_["minor_version"]                    = config.minor_version();
  node_["global_flags_clear"]               = config.global_flags_clear();
  node_["global_flags_set"]                 = config.global_flags_set();
  node_["critical_section_default_timeout"] = config.critical_section_default_timeout();
  node_["decommit_free_block_threshold"]    = config.decommit_free_block_threshold();
  node_["decommit_total_free_threshold"]    = config.decommit_total_free_threshold();
  node_["lock_prefix_table"]                = config.lock_prefix_table();
  node_["maximum_allocation_size"]          = config.maximum_allocation_size();
  node_["virtual_memory_threshold"]         = config.virtual_memory_threshold();
  node_["process_affinity_mask"]            = config.process_affinity_mask();
  node_["process_heap_flags"]               = config.process_heap_flags();
  node_["csd_version"]                      = config.csd_version();
  node_["reserved1"]                        = config.reserved1();
  node_["editlist"]                         = config.editlist();
  node_["security_cookie"]                  = config.security_cookie();

}

void JsonVisitor::visit(const LoadConfigurationV0& config) {

  node_["se_handler_table"] = config.se_handler_table();
  node_["se_handler_count"] = config.se_handler_count();
  visit(static_cast<const LoadConfiguration&>(config));
}

void JsonVisitor::visit(const LoadConfigurationV1& config) {

  node_["guard_cf_check_function_pointer"]    = config.guard_cf_check_function_pointer();
  node_["guard_cf_dispatch_function_pointer"] = config.guard_cf_dispatch_function_pointer();
  node_["guard_cf_function_table"]            = config.guard_cf_function_table();
  node_["guard_cf_function_count"]            = config.guard_cf_function_count();
  node_["guard_flags"]                        = static_cast<size_t>(config.guard_flags());
  visit(static_cast<const LoadConfigurationV0&>(config));
}

void JsonVisitor::visit(const LoadConfigurationV2& config) {

  JsonVisitor code_integrity_visitor;
  code_integrity_visitor(config.code_integrity());

  node_["code_integrity"] = code_integrity_visitor.get();
  visit(static_cast<const LoadConfigurationV1&>(config));
}

void JsonVisitor::visit(const LoadConfigurationV3& config) {

  node_["guard_address_taken_iat_entry_table"] = config.guard_address_taken_iat_entry_table();
  node_["guard_address_taken_iat_entry_count"] = config.guard_address_taken_iat_entry_count();
  node_["guard_long_jump_target_table"]        = config.guard_long_jump_target_table();
  node_["guard_long_jump_target_count"]        = config.guard_long_jump_target_count();
  visit(static_cast<const LoadConfigurationV2&>(config));
}

void JsonVisitor::visit(const LoadConfigurationV4& config) {

  node_["dynamic_value_reloc_table"] = config.dynamic_value_reloc_table();
  node_["hybrid_metadata_pointer"]   = config.hybrid_metadata_pointer();
  visit(static_cast<const LoadConfigurationV3&>(config));
}

void JsonVisitor::visit(const LoadConfigurationV5& config) {

  node_["guard_rf_failure_routine"]                   = config.guard_rf_failure_routine();
  node_["guard_rf_failure_routine_function_pointer"]  = config.guard_rf_failure_routine_function_pointer();
  node_["dynamic_value_reloctable_offset"]            = config.dynamic_value_reloctable_offset();
  node_["dynamic_value_reloctable_section"]           = config.dynamic_value_reloctable_section();
  node_["reserved2"]                                  = config.guard_rf_failure_routine();
  visit(static_cast<const LoadConfigurationV4&>(config));
}

void JsonVisitor::visit(const LoadConfigurationV6& config) {

  node_["guard_rf_verify_stackpointer_function_pointer"]  = config.guard_rf_verify_stackpointer_function_pointer();
  node_["hotpatch_table_offset"]                          = config.hotpatch_table_offset();
  visit(static_cast<const LoadConfigurationV5&>(config));
}

void JsonVisitor::visit(const LoadConfigurationV7& config) {

  node_["reserved3"]                = config.reserved3();
  node_["addressof_unicode_string"] = config.addressof_unicode_string();
  visit(static_cast<const LoadConfigurationV6&>(config));
}

void JsonVisitor::visit(const Pogo& pogo) {

  node_["signature"] = to_string(pogo.signature());

  std::vector<json> entries;
  for (const PogoEntry& entry : pogo.entries()) {
    JsonVisitor v;
    v(entry);
    entries.emplace_back(v.get());
  }
  node_["entries"] = entries;
}

void JsonVisitor::visit(const PogoEntry& entry) {

  node_["name"]      = entry.name();
  node_["start_rva"] = entry.start_rva();
  node_["size"]      = entry.size();
}

// LIEF Abstract
void JsonVisitor::visit(const LIEF::Binary& binary) {
  visit(reinterpret_cast<const LIEF::PE::Binary&>(binary));
}

void JsonVisitor::visit(const LIEF::Symbol& symbol) {
  visit(reinterpret_cast<const LIEF::PE::Symbol&>(symbol));
}

void JsonVisitor::visit(const LIEF::Section& section) {
  visit(reinterpret_cast<const LIEF::PE::Section&>(section));
}

} // namespace PE
} // namespace LIEF


text:
import vstruct
from vstruct.primitives import *


text:
package org.gluu.oxauth.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.gluu.oxauth.model.common.ResponseMode;
import org.gluu.oxauth.model.common.ResponseType;
import org.gluu.oxauth.model.util.Util;

/**
 * @author Javier Rojas Blum
 * @version October 7, 2019
 */
public class RedirectUri {

    private String baseRedirectUri;
    private List<ResponseType> responseTypes;
    private ResponseMode responseMode;
    private Map<String, String> responseParameters;

    public RedirectUri(String baseRedirectUri) {
        this.baseRedirectUri = baseRedirectUri;
        this.responseMode = ResponseMode.QUERY;

        responseParameters = new HashMap<String, String>();
    }

    public RedirectUri(String baseRedirectUri, List<ResponseType> responseTypes, ResponseMode responseMode) {
        this(baseRedirectUri);
        this.responseTypes = responseTypes;
        this.responseMode = responseMode;
    }

    public String getBaseRedirectUri() {
        return baseRedirectUri;
    }

    public void setBaseRedirectUri(String baseRedirectUri) {
        this.baseRedirectUri = baseRedirectUri;
    }

    public ResponseMode getResponseMode() {
        return responseMode;
    }

    public void setResponseMode(ResponseMode responseMode) {
        this.responseMode = responseMode;
    }

    public void addResponseParameter(String key, String value) {
        if (StringUtils.isNotBlank(key)) {
            responseParameters.put(key, value);
        }
    }

    public void parseQueryString(String queryString) {
        if (queryString != null) {
            StringTokenizer st = new StringTokenizer(queryString, "&", false);
            while (st.hasMoreElements()) {
                String nameValueToken = st.nextElement().toString();

                StringTokenizer stParamValue = new StringTokenizer(nameValueToken, "=", false);

                if (stParamValue.countTokens() == 1) {
                    String paramName = stParamValue.nextElement().toString();
                    responseParameters.put(paramName, null);
                } else if (stParamValue.countTokens() == 2) {
                    try {
                        String paramName = stParamValue.nextElement().toString();
                        String paramValue = URLDecoder.decode(stParamValue.nextElement().toString(), Util.UTF8_STRING_ENCODING);
                        responseParameters.put(paramName, paramValue);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public String getQueryString() {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : responseParameters.entrySet()) {
            try {
                if (StringUtils.isNotBlank(entry.getKey()) && StringUtils.isNotBlank(entry.getValue())) {
                    if (sb.length() > 0) {
                        sb.append('&');
                    }
                    sb.append(URLEncoder.encode(entry.getKey(), Util.UTF8_STRING_ENCODING));
                    sb.append('=').append(URLEncoder.encode(entry.getValue(), Util.UTF8_STRING_ENCODING));
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }

    private void appendQuerySymbol(StringBuilder sb) {
        if (!sb.toString().contains("?")) {
            sb.append("?");
        } else {
            sb.append("&");
        }
    }

    private void appendFragmentSymbol(StringBuilder sb) {
        if (!sb.toString().contains("#")) {
            sb.append("#");
        } else {
            sb.append("&");
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder(baseRedirectUri);

        if (responseParameters.size() > 0) {
            if (responseMode != ResponseMode.FORM_POST) {
                if (responseMode != null) {
                    if (responseMode == ResponseMode.QUERY) {
                        appendQuerySymbol(sb);
                    } else if (responseMode == ResponseMode.FRAGMENT) {
                        appendFragmentSymbol(sb);
                    }
                } else if (responseTypes != null && (responseTypes.contains(ResponseType.TOKEN) || responseTypes.contains(ResponseType.ID_TOKEN))) {
                    appendFragmentSymbol(sb);
                } else {
                    appendQuerySymbol(sb);
                }
                sb.append(getQueryString());
            }

            if (responseMode == ResponseMode.FORM_POST) {
                sb = new StringBuilder();
                sb.append("");
                sb.append("<title>oxAuth - Submit This Form</title>");
                sb.append("");
                //sb.append("");
                sb.append("<form method=\"post\" action=\"").append(baseRedirectUri).append("\">");
                for (Map.Entry<String, String> entry : responseParameters.entrySet()) {
                    String entryValue = StringEscapeUtils.escapeHtml(entry.getValue());
                    sb.append("<input type=\"hidden\" name=\"").append(entry.getKey()).append("\" value=\"").append(entryValue).append("\"/>");
                }
                sb.append("</form>");
                sb.append("");
                sb.append("");
            }
        }
        return sb.toString();
    }
}


text:
TEST(canvas_test, can_perform_loops_over_a_canvas)
{
    terminalpp::canvas canvas({5, 5});
    auto size = canvas.size();

    ASSERT_EQ(terminalpp::extent(5, 5), size);

    for (auto &&elem : canvas)
    {
        elem = {'x'};
    }

    for (terminalpp::coordinate_type row = 0; row < size.height_; ++row)
    {
        for (terminalpp::coordinate_type column = 0; column < size.width_; column++)
        {
            auto expected = terminalpp::element('x');
            auto result   = terminalpp::element(canvas[column][row]);
            ASSERT_EQ(expected, result);
        }
    }
}

TEST(canvas_test, can_perform_loops_over_a_const_canvas)
{
    terminalpp::canvas canvas({5, 5});
    auto size = canvas.size();

    ASSERT_EQ(terminalpp::extent(5, 5), size);

    for (auto &&elem : canvas)
    {
        elem = {'x'};
    }

    terminalpp::canvas const &ccanvas = canvas;

    for (terminalpp::coordinate_type row = 0; row < size.height_; ++row)
    {
        for (terminalpp::coordinate_type column = 0; column < size.width_; column++)
        {
            auto expected = terminalpp::element('x');
            auto result   = terminalpp::element(ccanvas[column][row]);
            ASSERT_EQ(expected, result);
        }
    }
}

TEST(canvas_test, can_assign_from_canvas_to_canvas)
{
    terminalpp::canvas canvas_source({1, 1});
    terminalpp::canvas canvas_dest({1, 1});

    canvas_dest[0][0] = canvas_source[0][0];
}

TEST(canvas_test, resizing_canvas_larger_keeps_content)
{
    auto small_size = terminalpp::extent{5, 6};
    auto large_size = terminalpp::extent{10, 9};

    terminalpp::canvas canvas(small_size);

    for (auto &&elem : canvas)
    {
        elem = {'x'};
    }

    canvas.resize(large_size);
    ASSERT_EQ(large_size, canvas.size());

    for (terminalpp::coordinate_type row = 0; row < large_size.height_; ++row)
    {
        for (terminalpp::coordinate_type column = 0; column < large_size.width_; ++column)
        {
            auto expected =
                row < small_size.height_ && column < small_size.width_
              ? terminalpp::element{'x'}
              : terminalpp::element{' '};

            auto result   = terminalpp::element(canvas[column][row]);
            ASSERT_EQ(expected, result);
        }
    }
}

TEST(canvas_test, resizing_canvas_smaller_truncates_content)
{
    auto small_size = terminalpp::extent{5, 6};
    auto large_size = terminalpp::extent{10, 9};

    terminalpp::canvas canvas(large_size);

    for (terminalpp::coordinate_type row = 0; row < large_size.height_; ++row)
    {
        for (terminalpp::coordinate_type column = 0; column < large_size.width_; ++column)
        {
            canvas[column][row] = {terminalpp::byte(column * row)};
        }
    }

    canvas.resize(small_size);

    for (terminalpp::coordinate_type row = 0; row < small_size.height_; ++row)
    {
        for (terminalpp::coordinate_type column = 0; column < small_size.width_; ++column)
        {
            auto expected = terminalpp::element(terminalpp::byte(column * row));
            auto result   = terminalpp::element(canvas[column][row]);

            ASSERT_EQ(expected, result);
        }
    }
}


text:
/* Filter button styling */
.header button.dropdown {
    display: inline-block;
    padding: 15px;
    color: #FFFFFF;
    text-align: left;
    font-size: 13px;
    font-weight: bold;
    line-height: 13px;
    min-width: 140px;
    border: none;
    outline: none;
    background-color: transparent;
    transition: background-color 0.075s ease 0.075s;
}
.header button.dropdown.active {
    background-color: #462D73;
    transition: background-color 0.075s ease;
}

.header button.dropdown i {
    display: inline-block;
    margin-right: 5px;
    font-size: 11.5px;
    line-height: 13px;
    color: #FFFFFF;
    cursor: pointer;
}

/* Dropdown styling */
.dropdown-container {
    position: absolute;
    top: -1000px;
    left: 0px;
    color: #FFFFFF;
    background-color: #6441A5;
    opacity: 0;
    z-index: 200;
    transition: opacity 0.075s ease 0.075s;
}
.dropdown-container.active {
    opacity: 1;
    transition: opacity 0.075s ease;
}

.dropdown-container .option {
    padding: 8px 15px;
    font-size: 13px;
    cursor: pointer;
}
.dropdown-container .option.active,
.dropdown-container .option:hover {
    background-color: #462D73;
}


text:
copy(){
	local src=$1
	local dest=$2

	if [ -f $dest ];
	then
		echo "- Aborted. File $dest exists."
	else
		cp -r $src $dest
		echo "* Copied. File $src to $dest"
	fi
}

# Copy .bashrc file
copy "linux/_bashrc" "${HOME}/.bashrc"

# Copy .gitconfig file
copy "git/_gitconfig" "${HOME}/.gitconfig"


text:
package api.web.gw2.mapping.v2.skills;

import api.web.gw2.mapping.core.ImplementationSpecific;
import api.web.gw2.mapping.v2.APIv2;

/**
 * Defines all combo field types.
 * @author Fabrice Bouyé
 */
@APIv2(endpoint = "v2/skills")
public enum SkillComboFieldType {

    /**
     * Defines the air combo field type.
     */
    AIR("Air"), // NOI18N.
    /**
     * Defines the dark combo field type.
     */
    DARK("Dark"), // NOI18N.
    /**
     * Defines the ethereal combo field type.
     */
    ETHEREAL("Ethereal"), // NOI18N.
    /**
     * Defines the fire combo field type.
     */
    FIRE("Fire"), // NOI18N.
    /**
     * Defines the ice combo field type.
     */
    ICE("Ice"), // NOI18N.
    /**
     * Defines the light combo field type.
     */
    LIGHT("Light"), // NOI18N.
    /**
     * Defines the lightning combo field type.
     */
    LIGHTNING("Lightning"), // NOI18N.
    /**
     * Defines the poison combo field type.
     */
    POISON("Poison"), // NOI18N.
    /**
     * Defines the smoke combo field type.
     */
    SMOKE("Smoke"), // NOI18N.
    /**
     * Defines the water combo field type.
     */
    WATER("Water"), // NOI18N.
    /**
     * Fail safe value.
     */
    @ImplementationSpecific
    UNKNOWN(null);

    final String value;

    private SkillComboFieldType(String value) {
        this.value = value;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="abc_action_bar_home_description">Перейти на головний</string>
    <string name="abc_action_bar_home_description_format">%1$s, %2$s</string>
    <string name="abc_action_bar_home_subtitle_description_format">%1$s, %2$s, %3$s</string>
    <string name="abc_action_bar_up_description">Перейти вгору</string>
    <string name="abc_action_menu_overflow_description">Інші опції</string>
    <string name="abc_action_mode_done">Готово</string>
    <string name="abc_activity_chooser_view_see_all">Переглянути всі</string>
    <string name="abc_activitychooserview_choose_application">Вибрати програму</string>
    <string name="abc_capital_off">ВИМК.</string>
    <string name="abc_capital_on">УВІМК.</string>
    <string name="abc_search_hint">Пошук…</string>
    <string name="abc_searchview_description_clear">Очистити запит</string>
    <string name="abc_searchview_description_query">Пошуковий запит</string>
    <string name="abc_searchview_description_search">Пошук</string>
    <string name="abc_searchview_description_submit">Надіслати запит</string>
    <string name="abc_searchview_description_voice">Голосовий пошук</string>
    <string name="abc_shareactionprovider_share_with">Надіслати через</string>
    <string name="abc_shareactionprovider_share_with_application">Надіслати через %s</string>
    <string name="abc_toolbar_collapse_description">Згорнути</string>
    <string name="common_android_wear_notification_needs_update_text">Для роботи додатка %1$s потрібно оновити Android Wear.</string>
    <string name="common_android_wear_update_text">Додаток %1$s не працюватиме, якщо не оновити Android Wear.</string>
    <string name="common_android_wear_update_title">Оновити Android Wear</string>
    <string name="common_google_play_services_api_unavailable_text">Для роботи додатка %1$s потрібні один або декілька сервісів Google Play, які зараз недоступні. Зверніться по допомогу до розробника.</string>
    <string name="common_google_play_services_enable_button">Увімкнути сервіси Google Play</string>
    <string name="common_google_play_services_enable_text">Додаток %1$s не працюватиме, якщо не ввімкнути сервіси Google Play.</string>
    <string name="common_google_play_services_enable_title">Увімкніть сервіси Google Play</string>
    <string name="common_google_play_services_error_notification_requested_by_msg">Запит від додатка %1$s</string>
    <string name="common_google_play_services_install_button">Установити сервіси Google Play</string>
    <string name="common_google_play_services_install_text_phone">Додаток %1$s не працюватиме без сервісів Google Play, яких немає на вашому телефоні.</string>
    <string name="common_google_play_services_install_text_tablet">Додаток %1$s не працюватиме без сервісів Google Play, яких немає на вашому планшеті.</string>
    <string name="common_google_play_services_install_title">Установіть сервіси Google Play</string>
    <string name="common_google_play_services_invalid_account_text">Указаний обліковий запис не існує на цьому пристрої. Виберіть інший обліковий запис.</string>
    <string name="common_google_play_services_invalid_account_title">Недійсний обліковий запис</string>
    <string name="common_google_play_services_needs_enabling_title">Щоб додаток працював, потрібно ввімкнути сервіси Google Play.</string>
    <string name="common_google_play_services_network_error_text">Для під'єднання до сервісів Google Play потрібне з'єднання з мережею.</string>
    <string name="common_google_play_services_network_error_title">Помилка мережі</string>
    <string name="common_google_play_services_notification_needs_update_title">Щоб додаток працював, потрібно оновити сервіси Google Play.</string>
    <string name="common_google_play_services_notification_ticker">Помилка сервісів Google Play</string>
    <string name="common_google_play_services_sign_in_failed_text">Не вдалося ввійти в указаний обліковий запис. Виберіть інший.</string>
    <string name="common_google_play_services_sign_in_failed_title">Помилка під час входу</string>
    <string name="common_google_play_services_unknown_issue">Невідома проблема із сервісами Google Play.</string>
    <string name="common_google_play_services_unsupported_text">Додаток %1$s працює завдяки сервісам Google Play, які не підтримуються на вашому пристрої. Зверніться по допомогу до виробника.</string>
    <string name="common_google_play_services_unsupported_title">Сервіси Google Play</string>
    <string name="common_google_play_services_update_button">Оновити</string>
    <string name="common_google_play_services_update_text">Додаток %1$s не працюватиме, якщо не оновити сервіси Google Play.</string>
    <string name="common_google_play_services_update_title">Оновіть сервіси Google Play</string>
    <string name="common_google_play_services_updating_text">Додаток %1$s не працюватиме без сервісів Google Play, які зараз оновлюються.</string>
    <string name="common_google_play_services_updating_title">Сервіси Google Play оновлюються</string>
    <string name="common_open_on_phone">Відкрити на телефоні</string>
    <string name="common_signin_button_text">Увійти</string>
    <string name="common_signin_button_text_long">Увійти в облік. запис Google</string>
    <string name="mr_media_route_button_content_description">Вивід медіа-даних</string>
    <string name="mr_media_route_chooser_searching">Пошук пристроїв…</string>
    <string name="mr_media_route_chooser_title">Під'єднатися до пристрою</string>
    <string name="mr_media_route_controller_disconnect">Від'єднатися</string>
    <string name="mr_system_route_name">Система</string>
    <string name="mr_user_route_category_name">Пристрої</string>
    <string name="status_bar_notification_info_overflow">999+</string>
    <string name="wallet_buy_button_place_holder">Купити за допомогою Google</string>
    <string name="tw__allow_btn_txt">Дозволити</string>
    <string name="tw__cta_text">Відкрити у Vine</string>
    <string name="tw__like_tweet">Вподобати твіт</string>
    <string name="tw__liked_tweet">Скасувати вподобання</string>
    <string name="tw__loading_tweet">Завантаження твіта</string>
    <string name="tw__login_btn_txt">Увійти за допомогою профілю Твіттера</string>
    <string name="tw__not_now_btn_txt">Не зараз</string>
    <string name="tw__pause">призупинити</string>
    <string name="tw__play">відтворити</string>
    <string name="tw__replay">повторити</string>
    <string name="tw__retweeted_by_format">Ретвітнуто користувачем(кою) %1$s</string>
    <string name="tw__share_content_format">Перегляньте твіт користувача(ки) @%1$s: https://twitter.com/%1$s/status/%2$s</string>
    <string name="tw__share_email_desc">Відкрийте %1$s доступ до адреси електронної пошти, пов'язаної з вашим профілем у Твіттері @%2$s, щоб %1$s користувався(лась) нею згідно з політикою конфіденційності. Наприклад, %1$s може надсилати вам оновлення та іншу інформацію на цю адресу.</string>
    <string name="tw__share_email_title">Поділіться своєю адресою електронної пошти</string>
    <string name="tw__share_subject_format">Твіт від користувача(ки) %1$s (@%2$s)</string>
    <string name="tw__share_tweet">Поділитися твітом</string>
    <string name="tw__tweet_content_description">%1$s. %2$s. %3$s.</string>
    <string name="tw__tweet_media">Медіафайли твітів</string>
</resources>