text:
package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"path"
	"strings"
	"text/template"
	"unicode"

	"github.com/mijia/modelq/drivers"
)

type CodeResult struct {
	name string
	err  error
}

type CodeConfig struct {
	packageName    string
	touchTimestamp bool
	template       string
}

func (cc CodeConfig) MustCompileTemplate() *template.Template {
	if cc.template == "" {
		return nil
	}
	funcMap := template.FuncMap{
		"ToUpper": strings.ToUpper,
		"ToLower": strings.ToLower,
		"FirstLower": func(s string) string {
			b := []rune(s)
			b[0] = unicode.ToLower(b[0])
			return string(b)
		},
		"First": func(s string) string {
			if "" == s {
				return ""
			}
			return s[:1]
		},
		"SubStr": func(from int, to int, s string) string {
			l := len(s)
			if from > l {
				return ""
			}
			if to > l {
				return s[from:]
			}
			if 0 == to {
				return s[from:]
			}
			return s[from:to]
		},
	}
	tmpl := template.New("tmp").Funcs(funcMap)

	tmpl, err := tmpl.ParseFiles(cc.template)
	return template.Must(tmpl, err)
}

func generateModels(dbName string, dbSchema drivers.DbSchema, config CodeConfig) {
	customTmpl := config.MustCompileTemplate()

	if fs, err := os.Stat(config.packageName); err != nil || !fs.IsDir() {
		os.Mkdir(config.packageName, os.ModeDir|os.ModePerm)
	}

	jobs := make(chan CodeResult)
	for tbl, cols := range dbSchema {
		go func(tableName string, schema drivers.TableSchema) {
			err := generateModel(dbName, tableName, schema, config, customTmpl)
			jobs <- CodeResult{tableName, err}
		}(tbl, cols)
	}

	for i := 0; i < len(dbSchema); i++ {
		result := <-jobs
		if result.err != nil {
			log.Printf("Error when generating code for %s, %s", result.name, result.err)
		} else {
			log.Printf("Code generated for table %s, into package %s/%s.go", result.name, config.packageName, result.name)
		}
	}
	close(jobs)
}

func generateModel(dbName, tName string, schema drivers.TableSchema, config CodeConfig, tmpl *template.Template) error {
	file, err := os.Create(path.Join(config.packageName, tName+".go"))
	if err != nil {
		return err
	}
	w := bufio.NewWriter(file)

	defer func() {
		w.Flush()
		file.Close()
	}()

	model := ModelMeta{
		Name:      toCapitalCase(tName),
		DbName:    dbName,
		TableName: tName,
		Fields:    make([]ModelField, len(schema)),
		Uniques:   make([]ModelField, 0, len(schema)),
		Indexed:   make([]ModelField, 0, len(schema)),
		config:    config,
	}
	needTime := false
	for i, col := range schema {
		field := ModelField{
			Name:            toCapitalCase(col.ColumnName),
			ColumnName:      col.ColumnName,
			Type:            col.DataType,
			IsNullable:      strings.ToUpper(col.IsNullable) == "YES",
			JsonMeta:        fmt.Sprintf("`json:\"%s\"`", col.ColumnName),
			IsPrimaryKey:    strings.ToUpper(col.ColumnKey) == "PRI",
			IsUniqueKey:     strings.ToUpper(col.ColumnKey) == "UNI",
			IsIndexed:       strings.ToUpper(col.ColumnKey) == "MUL",
			IsAutoIncrement: strings.ToUpper(col.Extra) == "AUTO_INCREMENT",
			DefaultValue:    col.DefaultValue,
			Extra:           col.Extra,
			Comment:         col.Comment,
		}
		if field.Type == "time.Time" {
			needTime = true
		}
		if field.IsPrimaryKey {
			model.PrimaryFields = append(model.PrimaryFields, &field)
		}

		if field.IsUniqueKey {
			model.Uniques = append(model.Uniques, field)
		}

		if field.IsIndexed {
			model.Indexed = append(model.Indexed, field)
		}

		model.Fields[i] = field
	}

	if err := model.GenHeader(w, tmpl, needTime); err != nil {
		return fmt.Errorf("[%s] Fail to gen model header, %s", tName, err)
	}
	if err := model.GenStruct(w, tmpl); err != nil {
		return fmt.Errorf("[%s] Fail to gen model struct, %s", tName, err)
	}
	if err := model.GenObjectApi(w, tmpl); err != nil {
		return fmt.Errorf("[%s] Fail to gen model object api, %s", tName, err)
	}
	if err := model.GenQueryApi(w, tmpl); err != nil {
		return fmt.Errorf("[%s] Fail to gen model query api, %s", tName, err)
	}
	if err := model.GenManagedObjApi(w, tmpl); err != nil {
		return fmt.Errorf("[%s] Fail to gen model managed objects api, %s", tName, err)
	}

	return nil
}

type ModelField struct {
	Name            string
	ColumnName      string
	Type            string
	JsonMeta        string
	IsNullable      bool
	IsPrimaryKey    bool
	IsUniqueKey     bool
	IsIndexed       bool
	IsAutoIncrement bool
	DefaultValue    string
	Extra           string
	Comment         string
}

func (f ModelField) ConverterFuncName() string {
	convertors := map[string]string{
		"int64":     "AsInt64",
		"int":       "AsInt",
		"string":    "AsString",
		"time.Time": "AsTime",
		"float64":   "AsFloat64",
		"bool":      "AsBool",
	}
	if c, ok := convertors[f.Type]; ok {
		return c
	}
	return "AsString"
}

type PrimaryFields []*ModelField

func (pf PrimaryFields) FormatObject() func(string) string {
	return func(name string) string {
		// "<Article ArticleId=%v UserId=%v>", obj.ArticleId, obj.UserId
		formats := make([]string, len(pf))
		for i, field := range pf {
			formats[i] = fmt.Sprintf("%s=%%v", field.Name)
		}
		outputs := make([]string, 1+len(pf))
		outputs[0] = fmt.Sprintf("\"<%s %s>\"", name, strings.Join(formats, " "))
		for i, field := range pf {
			outputs[i+1] = fmt.Sprintf("obj.%s", field.Name)
		}
		return strings.Join(outputs, ", ")
	}
}

func (pf PrimaryFields) FormatIncrementId() func() string {
	// obj.Id = {{if eq .PrimaryField.Type "int64"}}id{{else}}{{.PrimaryField.Type}}(id){{end}}
	return func() string {
		for _, field := range pf {
			if field.IsAutoIncrement {
				if field.Type == "int64" {
					return fmt.Sprintf("obj.%s = id", field.Name)
				} else {
					return fmt.Sprintf("obj.%s = %s(id)", field.Name, field.Type)
				}
			}
		}
		return ""
	}
}

func (pf PrimaryFields) FormatFilters() func(string) string {
	// filter := {{.Name}}Objs.Filter{{.PrimaryField.Name}}("=", obj.{{.PrimaryField.Name}})
	return func(name string) string {
		filters := make([]string, len(pf))
		for i, field := range pf {
			if i == 0 {
				filters[i] = fmt.Sprintf("filter := %sObjs.Filter%s(\"=\", obj.%s)", name, field.Name, field.Name)
			} else {
				filters[i] = fmt.Sprintf("filter = filter.And(%sObjs.Filter%s(\"=\", obj.%s))", name, field.Name, field.Name)
			}
		}
		return strings.Join(filters, "\n")
	}
}

type ModelMeta struct {
	Name          string
	DbName        string
	TableName     string
	PrimaryFields PrimaryFields
	Fields        []ModelField
	Uniques       []ModelField
	Indexed       []ModelField
	config        CodeConfig
}

func (m ModelMeta) HasAutoIncrementPrimaryKey() bool {
	for _, pField := range m.PrimaryFields {
		if pField.IsAutoIncrement {
			return true
		}
	}
	return false
}

func (m ModelMeta) AllFields() string {
	fields := make([]string, len(m.Fields))
	for i, f := range m.Fields {
		fields[i] = fmt.Sprintf("\"%s\"", f.Name)
	}
	return strings.Join(fields, ", ")
}

func (m ModelMeta) InsertableFields() string {
	fields := make([]string, 0, len(m.Fields))
	for _, f := range m.Fields {
		if f.IsPrimaryKey && f.IsAutoIncrement {
			continue
		}
		autoTimestamp := strings.ToUpper(f.DefaultValue) == "CURRENT_TIMESTAMP" ||
			strings.ToUpper(f.DefaultValue) == "NOW()"
		if f.Type == "time.Time" && autoTimestamp && !m.config.touchTimestamp {
			continue
		}
		fields = append(fields, fmt.Sprintf("\"%s\"", f.Name))
	}
	return strings.Join(fields, ", ")
}

func (m ModelMeta) GetInsertableFields() []ModelField {
	fields := make([]ModelField, 0, len(m.Fields))
	for _, f := range m.Fields {
		if f.IsPrimaryKey && f.IsAutoIncrement {
			continue
		}
		autoTimestamp := strings.ToUpper(f.DefaultValue) == "CURRENT_TIMESTAMP" ||
			strings.ToUpper(f.DefaultValue) == "NOW()"
		if f.Type == "time.Time" && autoTimestamp && !m.config.touchTimestamp {
			continue
		}
		fields = append(fields, f)
	}
	return fields
}

func (m ModelMeta) UpdatableFields() string {
	fields := make([]string, 0, len(m.Fields))
	for _, f := range m.Fields {
		if f.IsPrimaryKey {
			continue
		}
		autoUpdateTime := strings.ToUpper(f.Extra) == "ON UPDATE CURRENT_TIMESTAMP"
		if autoUpdateTime && !m.config.touchTimestamp {
			continue
		}
		fields = append(fields, fmt.Sprintf("\"%s\"", f.Name))
	}
	return strings.Join(fields, ", ")
}

func (m ModelMeta) GetUpdatableFields() []ModelField {
	fields := make([]ModelField, 0, len(m.Fields))
	for _, f := range m.Fields {
		if f.IsPrimaryKey {
			continue
		}
		autoUpdateTime := strings.ToUpper(f.Extra) == "ON UPDATE CURRENT_TIMESTAMP"
		if autoUpdateTime && !m.config.touchTimestamp {
			continue
		}
		fields = append(fields, f)
	}
	return fields
}

func (m ModelMeta) getTemplate(tmpl *template.Template, name string, defaultTmpl *template.Template) *template.Template {
	if tmpl != nil {
		if definedTmpl := tmpl.Lookup(name); definedTmpl != nil {
			return definedTmpl
		}
	}
	return defaultTmpl
}

func (m ModelMeta) GenHeader(w *bufio.Writer, tmpl *template.Template, importTime bool) error {
	return m.getTemplate(tmpl, "header", tmHeader).Execute(w, map[string]interface{}{
		"DbName":     m.DbName,
		"TableName":  m.TableName,
		"PkgName":    m.config.packageName,
		"ImportTime": importTime,
	})
}

func (m ModelMeta) GenStruct(w *bufio.Writer, tmpl *template.Template) error {
	return m.getTemplate(tmpl, "struct", tmStruct).Execute(w, m)
}

func (m ModelMeta) GenObjectApi(w *bufio.Writer, tmpl *template.Template) error {
	return m.getTemplate(tmpl, "obj_api", tmObjApi).Execute(w, m)
}

func (m ModelMeta) GenQueryApi(w *bufio.Writer, tmpl *template.Template) error {
	return m.getTemplate(tmpl, "query_api", tmQueryApi).Execute(w, m)
}

func (m ModelMeta) GenManagedObjApi(w *bufio.Writer, tmpl *template.Template) error {
	return m.getTemplate(tmpl, "managed_api", tmManagedObjApi).Execute(w, m)
}

func toCapitalCase(name string) string {
	// cp___hello_12jiu -> CpHello12Jiu
	data := []byte(name)
	segStart := true
	endPos := 0
	for i := 0; i < len(data); i++ {
		ch := data[i]
		if (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') {
			if segStart {
				if ch >= 'a' && ch <= 'z' {
					ch = ch - 'a' + 'A'
				}
				segStart = false
			} else {
				if ch >= 'A' && ch <= 'Z' {
					ch = ch - 'A' + 'a'
				}
			}
			data[endPos] = ch
			endPos++
		} else if ch >= '0' && ch <= '9' {
			data[endPos] = ch
			endPos++
			segStart = true
		} else {
			segStart = true
		}
	}
	return string(data[:endPos])
}


text:
<?php use_stylesheets_for_form($form) ?>
<?php use_javascripts_for_form($form) ?>

<form id="commentform" class="form-stacked" action="<?php echo url_for('comment_create', $post) ?>" method="post" <?php $form->isMultipart() and print 'enctype="multipart/form-data" ' ?>>

    <fieldset>

    <legend><?php echo __('Write a comment'); ?></legend>

    <?php echo $form->renderHiddenFields(false); ?>

    <?php echo $form->renderGlobalErrors() ?>

    <?php echo $form['author']->renderLabel() ?>
    <?php echo $form['author']->renderError() ?>

        <?php echo $form['author']->render(array('class' => 'span6', 'placeholder' => __('Anonymous'))); ?>

    <?php echo $form['content']->renderLabel() ?>
    <?php echo $form['content']->renderError() ?>

<?php echo $form['content']->render(array('class' => 'span6')); ?>

        <input type="submit" class="btn btn-primary" value="<?php echo __('Post Comment'); ?>" />
        <input type="reset" class="btn" value="<?php echo __('Cancel'); ?>" />

</fieldset>
</form>

redpajama_set_name: RedPajamaGithub


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

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

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CreateStreamProcessorResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {

    /**
     *

     * Amazon Resource Number for the newly created stream processor.
     *

     */
    private String streamProcessorArn;

    /**
     *

     * Amazon Resource Number for the newly created stream processor.
     *

     *
     * @param streamProcessorArn
     *        Amazon Resource Number for the newly created stream processor.
     */

    public void setStreamProcessorArn(String streamProcessorArn) {
        this.streamProcessorArn = streamProcessorArn;
    }

    /**
     *

     * Amazon Resource Number for the newly created stream processor.
     *

     *
     * @return Amazon Resource Number for the newly created stream processor.
     */

    public String getStreamProcessorArn() {
        return this.streamProcessorArn;
    }

    /**
     *

     * Amazon Resource Number for the newly created stream processor.
     *

     *
     * @param streamProcessorArn
     *        Amazon Resource Number for the newly created stream processor.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CreateStreamProcessorResult withStreamProcessorArn(String streamProcessorArn) {
        setStreamProcessorArn(streamProcessorArn);
        return this;
    }

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

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

        if (obj instanceof CreateStreamProcessorResult == false)
            return false;
        CreateStreamProcessorResult other = (CreateStreamProcessorResult) obj;
        if (other.getStreamProcessorArn() == null ^ this.getStreamProcessorArn() == null)
            return false;
        if (other.getStreamProcessorArn() != null && other.getStreamProcessorArn().equals(this.getStreamProcessorArn()) == false)
            return false;
        return true;
    }

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

        hashCode = prime * hashCode + ((getStreamProcessorArn() == null) ? 0 : getStreamProcessorArn().hashCode());
        return hashCode;
    }

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

}


text:
(function() {
  var FSMask, FSTrivialMask, FSWildcardMask, RegExp_escape,
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  RegExp_escape = require('./util').RegExp_escape;

  FSMask = (function() {

    function FSMask() {}

    return FSMask;

  })();

  FSTrivialMask = (function(_super) {

    __extends(FSTrivialMask, _super);

    function FSTrivialMask(name) {
      this.name = name;
    }

    FSTrivialMask.prototype.matches = function(candidate) {
      return candidate === this.name;
    };

    FSTrivialMask.prototype.toString = function() {
      return this.name;
    };

    return FSTrivialMask;

  })(FSMask);

  FSWildcardMask = (function(_super) {

    __extends(FSWildcardMask, _super);

    function FSWildcardMask(wildcard) {
      var p, parts;
      if (typeof wildcard === 'string') {
        this.wildcard = wildcard;
        parts = wildcard.split('*');
      } else {
        parts = wildcard;
        this.wildcard = parts.join('*');
      }
      this.len = ((function() {
        var _i, _len, _results;
        _results = [];
        for (_i = 0, _len = parts.length; _i < _len; _i++) {
          p = parts[_i];
          _results.push(p.length);
        }
        return _results;
      })()).reduce(function(a, b) {
        return a + b;
      });
      this.regexp = new RegExp('^' + ((function() {
        var _i, _len, _results;
        _results = [];
        for (_i = 0, _len = parts.length; _i < _len; _i++) {
          p = parts[_i];
          _results.push(RegExp_escape(p));
        }
        return _results;
      })()).join('.*?') + '$');
    }

    FSWildcardMask.prototype.matches = function(candidate) {
      return candidate.length >= this.len && this.regexp.test(candidate);
    };

    FSWildcardMask.prototype.toString = function() {
      return this.wildcard;
    };

    return FSWildcardMask;

  })(FSMask);

  FSMask.parse = function(wildcard) {
    if (wildcard.indexOf('*') >= 0) {
      return new FSWildcardMask(wildcard);
    } else {
      return new FSTrivialMask(wildcard);
    }
  };

  module.exports = FSMask;

}).call(this);


text:
* Fix bindung of this. ([13a4bfa](https://github.com/patternslib/pat-resourcepolling/commit/13a4bfa3616d2a85e2b82dbf206984036f23bde2))

### Maintenance

* Add demo page. ([3912e68](https://github.com/patternslib/pat-resourcepolling/commit/3912e685fee7694ac5c9a10dda501e90a68c9612))
* Add missing bundle config. ([5c82f84](https://github.com/patternslib/pat-resourcepolling/commit/5c82f8421b9ba69b9312ff40b0fee9c99da94608))

## 1.0.0 (2021-04-20)

### Maintenance

* Add basic (dummy) test. ([e21394f](https://github.com/patternslib/pat-resourcepolling/commit/e21394f50bfde6ef238c17d3b8684af1f4cbbbd5))
* Prepare release, move repo to github/patternslib ([56c08ac](https://github.com/patternslib/pat-resourcepolling/commit/56c08ac31e7833ccba530e40e2f18aecb89730ae))
* Upgrade to Patternslib v4 final - resourcepolling customizations. ([739153f](https://github.com/patternslib/pat-resourcepolling/commit/739153f788c87113d16afda03c2cb13b2d11c755))
* Upgrade to Patternslib v4 final. ([7e28c83](https://github.com/patternslib/pat-resourcepolling/commit/7e28c8377ac269bec1eebf01c6270e150de45d2d))


text:
import methods
import os

# To match other platforms
STACK_SIZE = 8388608

def is_active():
    return True

def get_name():
    return "Windows"

def can_build():
    if os.name == "nt":
        # Building natively on Windows
        # If VCINSTALLDIR is set in the OS environ, use traditional Godot logic to set up MSVC
        if os.getenv("VCINSTALLDIR"):  # MSVC, manual setup
            return True

        # Otherwise, let SCons find MSVC if installed, or else Mingw.
        # Since we're just returning True here, if there's no compiler
        # installed, we'll get errors when it tries to build with the
        # null compiler.
        return True

    if os.name == "posix":
        # Cross-compiling with MinGW-w64 (old MinGW32 is not supported)
        mingw32 = "i686-w64-mingw32-"
        mingw64 = "x86_64-w64-mingw32-"

        if os.getenv("MINGW32_PREFIX"):
            mingw32 = os.getenv("MINGW32_PREFIX")
        if os.getenv("MINGW64_PREFIX"):
            mingw64 = os.getenv("MINGW64_PREFIX")

        test = "gcc --version > /dev/null 2>&1"
        if os.system(mingw64 + test) == 0 or os.system(mingw32 + test) == 0:
            return True

    return False

def get_opts():
    from SCons.Variables import BoolVariable, EnumVariable

    mingw32 = ""
    mingw64 = ""
    if os.name == "posix":
        mingw32 = "i686-w64-mingw32-"
        mingw64 = "x86_64-w64-mingw32-"

    if os.getenv("MINGW32_PREFIX"):
        mingw32 = os.getenv("MINGW32_PREFIX")
    if os.getenv("MINGW64_PREFIX"):
        mingw64 = os.getenv("MINGW64_PREFIX")

    return [
        ("mingw_prefix_32", "MinGW prefix (Win32)", mingw32),
        ("mingw_prefix_64", "MinGW prefix (Win64)", mingw64),
        # Targeted Windows version: 7 (and later), minimum supported version
        # XP support dropped after EOL due to missing API for IPv6 and other issues
        # Vista support dropped after EOL due to GH-10243
        ("target_win_version", "Targeted Windows version, >= 0x0601 (Windows 7)", "0x0601"),
        BoolVariable("debug_symbols", "Add debugging symbols to release/release_debug builds", True),
        EnumVariable("windows_subsystem", "Windows subsystem", "gui", ("gui", "console")),
        BoolVariable("separate_debug_symbols", "Create a separate file containing debugging symbols", False),
        ("msvc_version", "MSVC version to use. Ignored if VCINSTALLDIR is set in shell env.", None),
        BoolVariable("use_mingw", "Use the Mingw compiler, even if MSVC is installed.", False),
        BoolVariable("use_llvm", "Use the LLVM compiler", False),
        BoolVariable("use_thinlto", "Use ThinLTO", False),
        BoolVariable("use_static_cpp", "Link MinGW/MSVC C++ runtime libraries statically", True),
        BoolVariable("use_asan", "Use address sanitizer (ASAN)", False),
    ]

def get_flags():
    return []

def build_res_file(target, source, env):
    if env["bits"] == "32":
        cmdbase = env["mingw_prefix_32"]
    else:
        cmdbase = env["mingw_prefix_64"]
    cmdbase = cmdbase + "windres --include-dir . "
    import subprocess

    for x in range(len(source)):
        cmd = cmdbase + "-i " + str(source[x]) + " -o " + str(target[x])
        try:
            out = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE).communicate()
            if len(out[1]):
                return 1
        except Exception:
            return 1
    return 0

def setup_msvc_manual(env):
    """Set up env to use MSVC manually, using VCINSTALLDIR"""
    if env["bits"] != "default":
        print(
            """
            Bits argument is not supported for MSVC compilation. Architecture depends on the Native/Cross Compile Tools Prompt/Developer Console
            (or Visual Studio settings) that is being used to run SCons. As a consequence, bits argument is disabled. Run scons again without bits
            argument (example: scons p=windows) and SCons will attempt to detect what MSVC compiler will be executed and inform you.
            """
        )
        raise SCons.Errors.UserError("Bits argument should not be used when using VCINSTALLDIR")

    # Force bits arg
    # (Actually msys2 mingw can support 64-bit, we could detect that)
    env["bits"] = "32"
    env["x86_libtheora_opt_vc"] = True

    # find compiler manually
    compiler_version_str = methods.detect_visual_c_compiler_version(env["ENV"])
    print("Found MSVC compiler: " + compiler_version_str)

    # If building for 64bit architecture, disable assembly optimisations for 32 bit builds (theora as of writing)... vc compiler for 64bit can not compile _asm
    if compiler_version_str == "amd64" or compiler_version_str == "x86_amd64":
        env["bits"] = "64"
        env["x86_libtheora_opt_vc"] = False
        print("Compiled program architecture will be a 64 bit executable (forcing bits=64).")
    elif compiler_version_str == "x86" or compiler_version_str == "amd64_x86":
        print("Compiled program architecture will be a 32 bit executable. (forcing bits=32).")
    else:
        print(
            "Failed to manually detect MSVC compiler architecture version... Defaulting to 32bit executable settings"
            " (forcing bits=32). Compilation attempt will continue, but SCons can not detect for what architecture this"
            " build is compiled for. You should check your settings/compilation setup, or avoid setting VCINSTALLDIR."
        )

def setup_msvc_auto(env):
    """Set up MSVC using SCons's auto-detection logic"""

    # If MSVC_VERSION is set by SCons, we know MSVC is installed.
    # But we may want a different version or target arch.

    # The env may have already been set up with default MSVC tools, so
    # reset a few things so we can set it up with the tools we want.
    # (Ideally we'd decide on the tool config before configuring any
    # environment, and just set the env up once, but this function runs
    # on an existing env so this is the simplest way.)
    env["MSVC_SETUP_RUN"] = False  # Need to set this to re-run the tool
    env["MSVS_VERSION"] = None
    env["MSVC_VERSION"] = None
    env["TARGET_ARCH"] = None
    if env["bits"] != "default":
        env["TARGET_ARCH"] = {"32": "x86", "64": "x86_64"}[env["bits"]]
    if "msvc_version" in env:
        env["MSVC_VERSION"] = env["msvc_version"]
    env.Tool("msvc")
    env.Tool("mssdk")  # we want the MS SDK
    # Note: actual compiler version can be found in env['MSVC_VERSION'], e.g. "14.1" for VS2015
    # Get actual target arch into bits (it may be "default" at this point):
    if env["TARGET_ARCH"] in ("amd64", "x86_64"):
        env["bits"] = "64"
    else:
        env["bits"] = "32"
    print("Found MSVC version %s, arch %s, bits=%s" % (env["MSVC_VERSION"], env["TARGET_ARCH"], env["bits"]))
    if env["TARGET_ARCH"] in ("amd64", "x86_64"):
        env["x86_libtheora_opt_vc"] = False

def setup_mingw(env):
    """Set up env for use with mingw"""
    # Nothing to do here
    print("Using MinGW")

def configure_msvc(env, manual_msvc_config):
    """Configure env to work with MSVC"""

    # Build type

    if env["target"] == "release":
        if env["optimize"] == "speed":  # optimize for speed (default)
            env.Append(CCFLAGS=["/O2"])
            env.Append(LINKFLAGS=["/OPT:REF"])
        elif env["optimize"] == "size":  # optimize for size
            env.Append(CCFLAGS=["/O1"])
            env.Append(LINKFLAGS=["/OPT:REF"])
        env.Append(LINKFLAGS=["/ENTRY:mainCRTStartup"])

    elif env["target"] == "release_debug":
        if env["optimize"] == "speed":  # optimize for speed (default)
            env.Append(CCFLAGS=["/O2"])
            env.Append(LINKFLAGS=["/OPT:REF"])
        elif env["optimize"] == "size":  # optimize for size
            env.Append(CCFLAGS=["/O1"])
            env.Append(LINKFLAGS=["/OPT:REF"])

    elif env["target"] == "debug":
        env.AppendUnique(CCFLAGS=["/Zi", "/FS", "/Od", "/EHsc"])
        # Allow big objects. Only needed for debug, see MinGW branch for rationale.
        env.AppendUnique(CCFLAGS=["/bigobj"])
        env.Append(LINKFLAGS=["/DEBUG"])

    if env["debug_symbols"]:
        env.AppendUnique(CCFLAGS=["/Zi", "/FS"])
        env.AppendUnique(LINKFLAGS=["/DEBUG"])

    if env["windows_subsystem"] == "gui":
        env.Append(LINKFLAGS=["/SUBSYSTEM:WINDOWS"])
    else:
        env.Append(LINKFLAGS=["/SUBSYSTEM:CONSOLE"])
        env.AppendUnique(CPPDEFINES=["WINDOWS_SUBSYSTEM_CONSOLE"])

    ## Compile/link flags

    if env["use_static_cpp"]:
        env.AppendUnique(CCFLAGS=["/MT"])
    else:
        env.AppendUnique(CCFLAGS=["/MD"])

    env.AppendUnique(CCFLAGS=["/Gd", "/GR", "/nologo"])
    env.AppendUnique(CCFLAGS=["/utf-8"])  # Force to use Unicode encoding.
    env.AppendUnique(CXXFLAGS=["/TP"])  # assume all sources are C++

    if manual_msvc_config:  # should be automatic if SCons found it
        if os.getenv("WindowsSdkDir") is not None:
            env.Prepend(CPPPATH=[os.getenv("WindowsSdkDir") + "/Include"])
        else:
            print("Missing environment variable: WindowsSdkDir")

    env.AppendUnique(
        CPPDEFINES=[
            "WINDOWS_ENABLED",
            "WASAPI_ENABLED",
            "WINMIDI_ENABLED",
            "TYPED_METHOD_BIND",
            "WIN32",
            "MSVC",
            "WINVER=%s" % env["target_win_version"],
            "_WIN32_WINNT=%s" % env["target_win_version"],
        ]
    )
    env.AppendUnique(CPPDEFINES=["NOMINMAX"])  # disable bogus min/max WinDef.h macros
    if env["bits"] == "64":
        env.AppendUnique(CPPDEFINES=["_WIN64"])

    ## Libs

    LIBS = [
        "winmm",
        "dsound",
        "kernel32",
        "ole32",
        "oleaut32",
        "user32",
        "gdi32",
        "IPHLPAPI",
        "Shlwapi",
        "wsock32",
        "Ws2_32",
        "shell32",
        "advapi32",
        "dinput8",
        "dxguid",
        "imm32",
        "bcrypt",
        "Avrt",
        "dwmapi",
    ]

    env.AppendUnique(CPPDEFINES=["VULKAN_ENABLED"])
    if not env["use_volk"]:
        LIBS += ["vulkan"]

    env.AppendUnique(CPPDEFINES=["GLES3_ENABLED"])
    LIBS += ["opengl32"]

    env.Append(LINKFLAGS=[p + env["LIBSUFFIX"] for p in LIBS])

    if manual_msvc_config:
        if os.getenv("WindowsSdkDir") is not None:
            env.Append(LIBPATH=[os.getenv("WindowsSdkDir") + "/Lib"])
        else:
            print("Missing environment variable: WindowsSdkDir")

    ## LTO

    if env["use_lto"]:
        env.AppendUnique(CCFLAGS=["/GL"])
        env.AppendUnique(ARFLAGS=["/LTCG"])
        if env["progress"]:
            env.AppendUnique(LINKFLAGS=["/LTCG:STATUS"])
        else:
            env.AppendUnique(LINKFLAGS=["/LTCG"])

    if manual_msvc_config:
        env.Prepend(CPPPATH=[p for p in os.getenv("INCLUDE").split(";")])
        env.Append(LIBPATH=[p for p in os.getenv("LIB").split(";")])

    # Sanitizers
    if env["use_asan"]:
        env.extra_suffix += ".san"
        env.Append(LINKFLAGS=["/INFERASANLIBS"])
        env.Append(CCFLAGS=["/fsanitize=address"])

    # Incremental linking fix
    env["BUILDERS"]["ProgramOriginal"] = env["BUILDERS"]["Program"]
    env["BUILDERS"]["Program"] = methods.precious_program

    env.AppendUnique(LINKFLAGS=["/STACK:" + str(STACK_SIZE)])

def configure_mingw(env):
    # Workaround for MinGW. See:
    # https://www.scons.org/wiki/LongCmdLinesOnWin32
    env.use_windows_spawn_fix()

    ## Build type

    if env["target"] == "release":
        env.Append(CCFLAGS=["-msse2"])

        if env["optimize"] == "speed":  # optimize for speed (default)
            if env["bits"] == "64":
                env.Append(CCFLAGS=["-O3"])
            else:
                env.Append(CCFLAGS=["-O2"])
        else:  # optimize for size
            env.Prepend(CCFLAGS=["-Os"])

        if env["debug_symbols"]:
            env.Prepend(CCFLAGS=["-g2"])

    elif env["target"] == "release_debug":
        env.Append(CCFLAGS=["-O2"])
        if env["debug_symbols"]:
            env.Prepend(CCFLAGS=["-g2"])
        if env["optimize"] == "speed":  # optimize for speed (default)
            env.Append(CCFLAGS=["-O2"])
        else:  # optimize for size
            env.Prepend(CCFLAGS=["-Os"])

    elif env["target"] == "debug":
        env.Append(CCFLAGS=["-g3"])
        # Allow big objects. It's supposed not to have drawbacks but seems to break
        # GCC LTO, so enabling for debug builds only (which are not built with LTO
        # and are the only ones with too big objects).
        env.Append(CCFLAGS=["-Wa,-mbig-obj"])

    if env["windows_subsystem"] == "gui":
        env.Append(LINKFLAGS=["-Wl,--subsystem,windows"])
    else:
        env.Append(LINKFLAGS=["-Wl,--subsystem,console"])
        env.AppendUnique(CPPDEFINES=["WINDOWS_SUBSYSTEM_CONSOLE"])

    ## Compiler configuration

    if os.name != "nt":
        env["PROGSUFFIX"] = env["PROGSUFFIX"] + ".exe"  # for linux cross-compilation

    if env["bits"] == "default":
        if os.name == "nt":
            env["bits"] = "64" if "PROGRAMFILES(X86)" in os.environ else "32"
        else:  # default to 64-bit on Linux
            env["bits"] = "64"

    mingw_prefix = ""

    if env["bits"] == "32":
        if env["use_static_cpp"]:
            env.Append(LINKFLAGS=["-static"])
            env.Append(LINKFLAGS=["-static-libgcc"])
            env.Append(LINKFLAGS=["-static-libstdc++"])
        mingw_prefix = env["mingw_prefix_32"]
    else:
        if env["use_static_cpp"]:
            env.Append(LINKFLAGS=["-static"])
        mingw_prefix = env["mingw_prefix_64"]

    if env["use_llvm"]:
        env["CC"] = mingw_prefix + "clang"
        env["CXX"] = mingw_prefix + "clang++"
        env["AS"] = mingw_prefix + "as"
        env["AR"] = mingw_prefix + "ar"
        env["RANLIB"] = mingw_prefix + "ranlib"
    else:
        env["CC"] = mingw_prefix + "gcc"
        env["CXX"] = mingw_prefix + "g++"
        env["AS"] = mingw_prefix + "as"
        env["AR"] = mingw_prefix + "gcc-ar"
        env["RANLIB"] = mingw_prefix + "gcc-ranlib"

    env["x86_libtheora_opt_gcc"] = True

    if env["use_lto"]:
        if not env["use_llvm"] and env.GetOption("num_jobs") > 1:
            env.Append(CCFLAGS=["-flto"])
            env.Append(LINKFLAGS=["-flto=" + str(env.GetOption("num_jobs"))])
        else:
            if env["use_thinlto"]:
                env.Append(CCFLAGS=["-flto=thin"])
                env.Append(LINKFLAGS=["-flto=thin"])
            else:
                env.Append(CCFLAGS=["-flto"])
                env.Append(LINKFLAGS=["-flto"])

    env.Append(LINKFLAGS=["-Wl,--stack," + str(STACK_SIZE)])

    ## Compile flags

    env.Append(CCFLAGS=["-mwindows"])

    env.Append(CPPDEFINES=["WINDOWS_ENABLED", "WASAPI_ENABLED", "WINMIDI_ENABLED"])
    env.Append(CPPDEFINES=[("WINVER", env["target_win_version"]), ("_WIN32_WINNT", env["target_win_version"])])
    env.Append(
        LIBS=[
            "mingw32",
            "dsound",
            "ole32",
            "d3d9",
            "winmm",
            "gdi32",
            "iphlpapi",
            "shlwapi",
            "wsock32",
            "ws2_32",
            "kernel32",
            "oleaut32",
            "dinput8",
            "dxguid",
            "ksuser",
            "imm32",
            "bcrypt",
            "avrt",
            "uuid",
            "dwmapi",
        ]
    )

    env.Append(CPPDEFINES=["VULKAN_ENABLED"])
    if not env["use_volk"]:
        env.Append(LIBS=["vulkan"])

    env.Append(CPPDEFINES=["GLES3_ENABLED"])
    env.Append(LIBS=["opengl32"])

    env.Append(CPPDEFINES=["MINGW_ENABLED", ("MINGW_HAS_SECURE_API", 1)])

    # resrc
    env.Append(BUILDERS={"RES": env.Builder(action=build_res_file, suffix=".o", src_suffix=".rc")})

def configure(env):
    # At this point the env has been set up with basic tools/compilers.
    env.Prepend(CPPPATH=["#platform/windows"])

    print("Configuring for Windows: target=%s, bits=%s" % (env["target"], env["bits"]))

    if os.name == "nt":
        env["ENV"] = os.environ  # this makes build less repeatable, but simplifies some things
        env["ENV"]["TMP"] = os.environ["TMP"]

    # First figure out which compiler, version, and target arch we're using
    if os.getenv("VCINSTALLDIR") and not env["use_mingw"]:
        # Manual setup of MSVC
        setup_msvc_manual(env)
        env.msvc = True
        manual_msvc_config = True
    elif env.get("MSVC_VERSION", "") and not env["use_mingw"]:
        setup_msvc_auto(env)
        env.msvc = True
        manual_msvc_config = False
    else:
        setup_mingw(env)
        env.msvc = False

    # Now set compiler/linker flags
    if env.msvc:
        configure_msvc(env, manual_msvc_config)

    else:  # MinGW
        configure_mingw(env)


text:
#pragma once
#include <aws/cognito-idp/CognitoIdentityProvider_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace CognitoIdentityProvider
{
namespace Model
{

  /**
   *
The configuration for a custom domain that hosts the sign-up and sign-in
   * webpages for your application.

See Also:
   AWS
   * API Reference

   */
  class AWS_COGNITOIDENTITYPROVIDER_API CustomDomainConfigType
  {
  public:
    CustomDomainConfigType();
    CustomDomainConfigType(Aws::Utils::Json::JsonView jsonValue);
    CustomDomainConfigType& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The Amazon Resource Name (ARN) of an Certificate Manager SSL certificate. You
     * use this certificate for the subdomain of your custom domain.

     */
    inline const Aws::String& GetCertificateArn() const{ return m_certificateArn; }

    /**
     *
The Amazon Resource Name (ARN) of an Certificate Manager SSL certificate. You
     * use this certificate for the subdomain of your custom domain.

     */
    inline bool CertificateArnHasBeenSet() const { return m_certificateArnHasBeenSet; }

    /**
     *
The Amazon Resource Name (ARN) of an Certificate Manager SSL certificate. You
     * use this certificate for the subdomain of your custom domain.

     */
    inline void SetCertificateArn(const Aws::String& value) { m_certificateArnHasBeenSet = true; m_certificateArn = value; }

    /**
     *
The Amazon Resource Name (ARN) of an Certificate Manager SSL certificate. You
     * use this certificate for the subdomain of your custom domain.

     */
    inline void SetCertificateArn(Aws::String&& value) { m_certificateArnHasBeenSet = true; m_certificateArn = std::move(value); }

    /**
     *
The Amazon Resource Name (ARN) of an Certificate Manager SSL certificate. You
     * use this certificate for the subdomain of your custom domain.

     */
    inline void SetCertificateArn(const char* value) { m_certificateArnHasBeenSet = true; m_certificateArn.assign(value); }

    /**
     *
The Amazon Resource Name (ARN) of an Certificate Manager SSL certificate. You
     * use this certificate for the subdomain of your custom domain.

     */
    inline CustomDomainConfigType& WithCertificateArn(const Aws::String& value) { SetCertificateArn(value); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of an Certificate Manager SSL certificate. You
     * use this certificate for the subdomain of your custom domain.

     */
    inline CustomDomainConfigType& WithCertificateArn(Aws::String&& value) { SetCertificateArn(std::move(value)); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of an Certificate Manager SSL certificate. You
     * use this certificate for the subdomain of your custom domain.

     */
    inline CustomDomainConfigType& WithCertificateArn(const char* value) { SetCertificateArn(value); return *this;}

  private:

    Aws::String m_certificateArn;
    bool m_certificateArnHasBeenSet = false;
  };

} // namespace Model
} // namespace CognitoIdentityProvider
} // namespace Aws


text:
package com.google.gerrit.client.diff;

import com.google.gerrit.client.Gerrit;
import com.google.gerrit.client.patches.PatchUtil;
import com.google.gerrit.common.PageLinks;
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwtexpui.globalkey.client.KeyCommand;

class UpToChangeCommand extends KeyCommand {
  private final PatchSet.Id revision;

  UpToChangeCommand(PatchSet.Id revision, int mask, int key) {
    super(mask, key, PatchUtil.C.upToChange());
    this.revision = revision;
  }

  @Override
  public void onKeyPress(final KeyPressEvent event) {
    Gerrit.display(PageLinks.toChange(
        revision.getParentKey(),
        revision.getId()));
  }
}


text:
package org.apache.shardingsphere.infra.hint;

import org.apache.shardingsphere.infra.properties.TypedProperties;

import java.util.Properties;

/**
 * SQL Hint properties.
 */
public final class SQLHintProperties extends TypedProperties<SQLHintPropertiesKey> {

    public SQLHintProperties(final Properties props) {
        super(SQLHintPropertiesKey.class, props);
    }
}


text:
package provision.util;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;

public class DateTimeUtil{

	public static Date getDateXDaysFromNow(int daysFromStartDate){
		return getDateXDaysFromY(System.currentTimeMillis(), daysFromStartDate);
	}

	public static Timestamp getTimestampXDaysFromNow(int daysFromStartDate){
		return getTimestampXDaysFromY(System.currentTimeMillis(), daysFromStartDate);
	}

	public static Date getDateXDaysFromY(long startTimeInMillis, int daysFromStartDate){
		Calendar cal = getCalendarXDaysFromY(startTimeInMillis, daysFromStartDate);
		return new Date(cal.getTimeInMillis());
	}

	public static Timestamp getTimestampXDaysFromY(long startTimeInMillis, int daysFromStartDate){
	    Calendar cal = getCalendarXDaysFromY(startTimeInMillis, daysFromStartDate);
		return new Timestamp(cal.getTimeInMillis());
	}

	private static Calendar getCalendarXDaysFromY(long startTimeInMillis, int daysFromStartDate){
		Calendar cal = Calendar.getInstance();
		cal.setTimeInMillis(startTimeInMillis);
		cal.add(Calendar.DAY_OF_YEAR, daysFromStartDate);

		return cal;
	}

}


text:
package com.google.ads.googleads.v11.enums;

public final class AccessReasonProto {
  private AccessReasonProto() {}
  public static void registerAllExtensions(
      com.google.protobuf.ExtensionRegistryLite registry) {
  }

  public static void registerAllExtensions(
      com.google.protobuf.ExtensionRegistry registry) {
    registerAllExtensions(
        (com.google.protobuf.ExtensionRegistryLite) registry);
  }
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_google_ads_googleads_v11_enums_AccessReasonEnum_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_ads_googleads_v11_enums_AccessReasonEnum_fieldAccessorTable;

  public static com.google.protobuf.Descriptors.FileDescriptor
      getDescriptor() {
    return descriptor;
  }
  private static  com.google.protobuf.Descriptors.FileDescriptor
      descriptor;
  static {
    java.lang.String[] descriptorData = {
      "\n2google/ads/googleads/v11/enums/access_" +
      "reason.proto\022\036google.ads.googleads.v11.e" +
      "nums\"\205\001\n\020AccessReasonEnum\"q\n\014AccessReaso" +
      "n\022\017\n\013UNSPECIFIED\020\000\022\013\n\007UNKNOWN\020\001\022\t\n\005OWNED" +
      "\020\002\022\n\n\006SHARED\020\003\022\014\n\010LICENSED\020\004\022\016\n\nSUBSCRIB" +
      "ED\020\005\022\016\n\nAFFILIATED\020\006B\353\001\n\"com.google.ads." +
      "googleads.v11.enumsB\021AccessReasonProtoP\001" +
      "ZCgoogle.golang.org/genproto/googleapis/" +
      "ads/googleads/v11/enums;enums\242\002\003GAA\252\002\036Go" +
      "ogle.Ads.GoogleAds.V11.Enums\312\002\036Google\\Ad" +
      "s\\GoogleAds\\V11\\Enums\352\002\"Google::Ads::Goo" +
      "gleAds::V11::Enumsb\006proto3"
    };
    descriptor = com.google.protobuf.Descriptors.FileDescriptor
      .internalBuildGeneratedFileFrom(descriptorData,
        new com.google.protobuf.Descriptors.FileDescriptor[] {
        });
    internal_static_google_ads_googleads_v11_enums_AccessReasonEnum_descriptor =
      getDescriptor().getMessageTypes().get(0);
    internal_static_google_ads_googleads_v11_enums_AccessReasonEnum_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_google_ads_googleads_v11_enums_AccessReasonEnum_descriptor,
        new java.lang.String[] { });
  }

  // @@protoc_insertion_point(outer_class_scope)
}


text:
declare interface ISpFxWebCamWebPartStrings {
  PropertyPaneDescription: string;
  BasicGroupName: string;
  DescriptionFieldLabel: string;
}

declare module 'SpFxWebCamWebPartStrings' {
  const strings: ISpFxWebCamWebPartStrings;
  export = strings;
}


text:
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { isUnsafe } from './unsafe';

export default class Td extends PureComponent {
  static defaultProps = {
    children: null,
  };
  static propTypes = {
    children: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.instanceOf(Object),
    ]),
  };
  render() {
    if (isUnsafe(this.props.children)) {
      const options = {};
      if (this.props.children) {
        options.dangerouslySetInnerHTML = { __html: this.props.children.toString() };
      }
      return (
        <td
          {...options}
        />
      );
    }
    return <td>{this.props.children}</td>;
  }
}


text:
require "dry/web/roda/generators/abstract_generator"

module Dry
  module Web
    module Roda
      module Generators
        class SubApp < AbstractGenerator
          def populate_templates
            add_lib
            add_system
            add_web
          end

          private

          def destination
            options.fetch(:to) { File.join("apps", target_dir) }
          end

          def umbrella_name
            options.fetch(:umbrella)
          end

          def underscored_umbrella_name
            Inflections.underscored_name(umbrella_name)
          end

          def lib_path
            "lib/#{underscored_umbrella_name}/#{underscored_project_name}"
          end

          def system_lib_path
            "system/#{underscored_umbrella_name}/#{underscored_project_name}"
          end

          def add_lib
            add_template('subapp/view_context.rb.tt', "#{lib_path}/view_context.rb")
            add_template('subapp/view.rb.tt', "#{lib_path}/view.rb")
            add_template('subapp/welcome.rb.tt', "#{lib_path}/views/welcome.rb")
          end

          def add_system
            add_template('subapp/web.rb.tt', "#{system_lib_path}/web.rb")
            add_template('subapp/container.rb.tt', "#{system_lib_path}/container.rb")
            add_template('subapp/import.rb.tt', "#{system_lib_path}/import.rb")
            add_template('subapp/boot.rb.tt', 'system/boot.rb')
          end

          def add_web
            add_template('subapp/example_routes.rb.tt', 'web/routes/example.rb')
            add_template('application.html.slim', 'web/templates/layouts/application.html.slim')
            add_template('welcome.html.slim', 'web/templates/welcome.html.slim')
          end

          def template_scope
            {
              underscored_project_name: underscored_project_name,
              camel_cased_app_name: Inflections.camel_cased_name(target_dir),
              underscored_umbrella_name: underscored_umbrella_name,
              camel_cased_umbrella_name: Inflections.camel_cased_name(umbrella_name),
            }
          end
        end
      end
    end
  end
end


text:
module.exports.run = function() {
  var utils = require('../../utils');
  var config = require('../../config');
  var paths = config.paths;
  var path = require('path');
  var webpackDevConfig = path.join(paths.forklift, 'webpack.config.dev.js');

  if (!utils.fileExists(webpackDevConfig)) {
    return utils.fileNotFound(webpackDevConfig);
  }

  require('./cleanDist').run();

  var args = [
    '--config', webpackDevConfig
  ];
  utils.execModule('webpack', args.join(' '));
};


text:
#include "config.h"
#include "CookieStorage.h"

#include "NotImplemented.h"

namespace WebCore {

void setCookieStoragePrivateBrowsingEnabled(bool)
{
    notImplemented();
}

} // namespace WebCore


text:
const fs = require('fs')

const Action = require('./action')
const capture = require('./capture')

class Group {
  constructor(parent) {
    this.depth = parent ? parent.depth + 1 : 0
    this.children = []
    this.parent = parent
    this.actions = []
    this.docs = {
      title: '',
      descriptions: [],
      schemes: [],
      host: '',
      basePath: '',
      version: '',
    }
  }

  title(title) {
    this.docs.title = title
    return this
  }

  desc(...descriptions) {
    this.docs.descriptions = descriptions
    return this
  }

  scheme(...schemes) {
    this.docs.schemes = schemes
    return this
  }

  host(host) {
    this.docs.host = host
    return this
  }

  version(version) {
    this.docs.version = version
    return this
  }

  basePath(basePath, parameters) {
    // eslint-disable-next-line no-param-reassign
    if (basePath.startsWith('/')) basePath = basePath.substr(1)
    if (basePath.endsWith('/'))
      // eslint-disable-next-line no-param-reassign
      basePath = basePath.substr(0, basePath.length - 1)
    this.docs.basePath = basePath
    if (parameters) {
      this.params(parameters)
    }
    return this
  }

  // eslint-disable-next-line class-methods-use-this
  val(value, ...descriptions) {
    return capture(value).desc(...descriptions)
  }

  params(parameters) {
    this.parameters = capture(parameters)
    return this
  }

  query(queries) {
    this.queries = capture(queries)
    return this
  }

  reqHeaders(headers) {
    this.requestHeaders = capture(headers)
    return this
  }

  group(title) {
    const groupIndex = this.children.findIndex((g) => g.docs.title === title)
    if (groupIndex >= 0) return this.children[groupIndex]
    const group = new Group(this).title(title)
    this.children.push(group)
    return group
  }

  action(title) {
    const actionIndex = this.actions.findIndex((a) => a.docs.title === title)
    if (actionIndex >= 0) {
      this.actions[actionIndex].anotherExample()
      return this.actions[actionIndex]
    }
    const action = new Action(this).title(title)
    this.actions.push(action)
    return action
  }

  is(collectFn) {
    const collect = collectFn(this)
    return collect instanceof Promise ? collect.then(() => this) : this
  }

  // eslint-disable-next-line class-methods-use-this
  uncapture(object, shouldSliceArray = false) {
    return capture.undo(object, shouldSliceArray)
  }

  // eslint-disable-next-line consistent-return
  emit(file, generator = 'apib', options = {}) {
    /* eslint-disable import/no-dynamic-require,global-require */
    const generateFn =
      typeof generator === 'string'
        ? require(`./${generator}-generator`).generate
        : generator
    /* eslint-enable import/no-dynamic-require,global-require */
    const documentText = generateFn(this, options)
    if (!file) return documentText
    fs.writeFileSync(file, documentText)
  }
}

module.exports = Group


text:
package com.atlassian.plugins.codegen.modules.common;

/**
 * @since 3.6
 */
public class Tooltip extends Label
{

    public Tooltip(String key, String value)
    {
        super(key, value);
    }
}


text:
<?php
if(!defined('IN_INDEX') || empty($_SESSION[$settings['session_prefix'].'user_id'])) exit;

if(isset($_SESSION[$settings['session_prefix'].'user_type']) && $_SESSION[$settings['session_prefix'].'user_type']==1)
 {
  if(isset($_POST['settings_submitted']))
   {
    if(empty($_POST['caching'])) $_POST['caching'] = 0;
    if(empty($_POST['wysiwyg_editor'])) $_POST['wysiwyg_editor'] = 0;
    Database::$content->beginTransaction();
    $dbr = Database::$content->prepare("UPDATE ".Database::$db_settings['settings_table']." SET value=:value WHERE name=:name");
    $dbr->bindParam(':value', $val, PDO::PARAM_STR);
    $dbr->bindParam(':name', $key, PDO::PARAM_STR);
    // while(list($key, $val) = each($_POST)) # each() is deprecated in php7.2 and
    // removed in php8.0
    foreach ($_POST as $key => $val) {
      if($key!='settings_submitted' && $key!='clear_cache')
       {
        $dbr->execute();
       }
     }
    Database::$content->commit();
    if(isset($cache) && ($cache->autoClear || isset($_POST['clear_cache'])))
     {
      $cache->clear();
      header('Location: '.BASE_URL.ADMIN_DIR.'index.php?mode=settings&saved=true&cache_cleared=true');
     }
    else
     {
      header('Location: '.BASE_URL.ADMIN_DIR.'index.php?mode=settings&saved=true');
     }
    #header('Location: '.BASE_URL.ADMIN_DIR.'index.php?msg=settings_saved');
    exit;
   }

  if(isset($_GET['delete']))
   {
    $dbr = Database::$content->prepare("DELETE FROM ".Database::$db_settings['settings_table']." WHERE name=:name");
    $dbr->bindParam(':name', $_GET['delete'], PDO::PARAM_STR);
    $dbr->execute();
    if(isset($cache) && $cache->autoClear) $cache->clear();
    header('Location: '.BASE_URL.ADMIN_DIR.'index.php?mode=settings&action=advanced_settings');
    exit;
   }

  if(isset($_POST['new_var_submitted']))
   {
    if(!preg_match('/^[a-zA-Z0-9_\-]+$/', $_POST['name']))
     {
      $errors[] = 'error_settings_spec_chars';
      $action = 'advanced_settings';
     }
    if(empty($errors))
     {
      $dbr = Database::$content->prepare("INSERT INTO ".Database::$db_settings['settings_table']." (name,value) VALUES (:name, :value)");
      $dbr->bindParam(':name', $_POST['name'], PDO::PARAM_STR);
      $dbr->bindParam(':value', $_POST['value'], PDO::PARAM_STR);
      $dbr->execute();
      if(isset($cache) && $cache->autoClear) $cache->clear();
      header('Location: '.BASE_URL.ADMIN_DIR.'index.php?mode=settings&action=advanced_settings');
      exit;
     }
    else
     {
      $template->assign('errors', $errors);
     }
   }

  if(isset($_GET['action'])) $action = $_GET['action'];
  if(empty($action)) $action = 'main_settings';

  if(isset($_GET['saved'])) $template->assign('saved', true);
  if(isset($_GET['cache_cleared'])) $template->assign('cache_cleared', true);

  switch($action)
   {
    case 'main_settings':
     // get available pages:
     $dbr = Database::$content->query("SELECT id, page FROM ".Database::$db_settings['pages_table']." ORDER BY page ASC");
     $i=0;
     while($pages_data = $dbr->fetch())
      {
       $pages[$i]['id'] = $pages_data['id'];
       $pages[$i]['page'] = $pages_data['page'];
       ++$i;
      }
     if(isset($pages))
      {
       $template->assign('pages',$pages);
      }

     $template->assign('page_languages', get_languages());
     $template->assign('admin_languages', get_languages(true));

     $template->assign('subtitle', Localization::$lang['settings']);
     $template->assign('subtemplate', 'settings.inc.tpl');

     // WYSIWYG editor available?
     #if(file_exists(BASE_PATH.WYSIWYG_EDITOR))
     # {
     #  $template->assign('wysiwyg_editor_available', true);
     # }

    break;
    case 'advanced_settings';
     $settings_sorted = array_map('htmlspecialchars', $settings);
     ksort($settings_sorted);
     $template->assign('settings_sorted', $settings_sorted);
     $template->assign('subtitle', Localization::$lang['advanced_settings']);
     $template->assign('subtemplate', 'settings_advanced.inc.tpl');
    break;
   }
 }
?>


text:
require 'spec_helper'

include TwitterCldr::Tokenizers

describe CompositeToken do
  describe "#initialize" do
    it "should set an array of tokens" do
  		token_0 = Token.new(type: "my_type_0", value: "my_value_0")
  		token_1 = Token.new(type: "my_type_1", value: "my_value_1")

  		composite_token = CompositeToken.new([token_0, token_1])
  		expect(composite_token.tokens.map { |t| t.type }).to eq(["my_type_0", "my_type_1"])
  		expect(composite_token.tokens.map { |t| t.value }).to eq(["my_value_0", "my_value_1"])
  	end

    it "should return content" do
  		token_0 = Token.new(type: "my_type_0", value: "my_value_0")
  		token_1 = Token.new(type: "my_type_1", value: "my_value_1")

  		composite_token = CompositeToken.new([token_0, token_1])
  		expect(composite_token.to_s).to eq("my_value_0my_value_1")
  	end
  end
end


text:
<?php
declare(strict_types = 1);

namespace App\Repository\Distribution;

use App\Entity\Distribution;
use App\Entity\Server;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use LaravelDoctrine\ORM\Pagination\PaginatesFromParams;

class DoctrineDistributionRepository implements DistributionRepository
{
    use PaginatesFromParams;

    /**
     * @var EntityManagerInterface
     */
    private $em;

    /**
     * @var EntityRepository
     */
    private $er;

    public function __construct(EntityManagerInterface $em, EntityRepository $er)
    {
        $this->em = $em;
        $this->er = $er;
    }

    public function create(Distribution $distribution): void
    {
        $this->em->persist($distribution);
        $this->em->flush();
    }

    public function update(Distribution $distribution): void
    {
        $this->em->merge($distribution);
        $this->em->flush();
    }

    public function remove(Distribution $distribution): void
    {
        $this->em->remove($distribution);
        $this->em->flush();
    }

    public function find(int $id): ?Distribution
    {
        /** @noinspection PhpIncompatibleReturnTypeInspection */
        return $this->er->find($id);
    }

    public function findByUserPaginated(User $user, int $page, int $perPage): LengthAwarePaginator
    {
        return $this->paginate(
            $this->createQueryBuilder('distribution')
                ->join('distribution.purchaseItem', 'purchaseItem')
                ->join('purchaseItem.purchase', 'purchase')
                ->where('purchase.user = :user')
                ->setParameter('user', $user)
                ->getQuery(),
            $perPage,
            $page
        );
    }

    public function findByUserPaginatedWithOrder(User $user, int $page, string $orderBy, bool $descending, int $perPage): LengthAwarePaginator
    {
        return $this->paginate(
            $this->createQueryBuilder('distribution')
                ->join('distribution.purchaseItem', 'purchaseItem')
                ->join('purchaseItem.purchase', 'purchase')
                ->join('purchaseItem.product', 'product')
                ->join('product.item', 'item')
                ->join('product.category', 'category')
                ->join('category.server', 'server')
                ->where('purchase.user = :user')
                ->orderBy($orderBy, $descending ? 'DESC' : 'ASC')
                ->setParameter('user', $user)
                ->getQuery(),
            $perPage,
            $page,
            false
        );
    }

    public function findByUserAndServerPaginated(User $user, Server $server, int $page, int $perPage): LengthAwarePaginator
    {
        return $this->paginate(
            $this->createQueryBuilder('distribution')
                ->join('distribution.purchaseItem', 'purchaseItem')
                ->join('purchaseItem.purchase', 'purchase')
                ->join('purchaseItem.product', 'product')
                ->join('product.category', 'category')
                ->join('category.server', 'server')
                ->where('purchase.user = :user')
                ->andWhere('category.server = :server')
                ->setParameter('user', $user)
                ->setParameter('server', $server)
                ->getQuery(),
            $perPage,
            $page,
            false
        );
    }

    public function findByUserAndServerPaginatedWithOrder(User $user, Server $server, int $page, string $orderBy, bool $descending, int $perPage): LengthAwarePaginator
    {
        return $this->paginate(
            $this->createQueryBuilder('distribution')
                ->join('distribution.purchaseItem', 'purchaseItem')
                ->join('purchaseItem.purchase', 'purchase')
                ->join('purchaseItem.product', 'product')
                ->join('product.item', 'item')
                ->join('product.category', 'category')
                ->join('category.server', 'server')
                ->where('purchase.user = :user')
                ->andWhere('category.server = :server')
                ->orderBy($orderBy, $descending ? 'DESC' : 'ASC')
                ->setParameter('user', $user)
                ->setParameter('server', $server)
                ->getQuery(),
            $perPage,
            $page,
            false
        );
    }

    public function deleteAll(): bool
    {
        return (bool)$this->er->createQueryBuilder('d')
            ->delete()
            ->getQuery()
            ->getResult();
    }

    /**
     * @inheritDoc
     */
    public function createQueryBuilder($alias, $indexBy = null)
    {
        return $this->er->createQueryBuilder($alias, $indexBy);
    }
}


text:
package org.corpus_tools.annis.gui.admin.reflinks;

import au.com.bytecode.opencsv.CSVReader;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.vaadin.ui.Button;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.Notification;
import com.vaadin.ui.Panel;
import com.vaadin.ui.PasswordField;
import com.vaadin.ui.ProgressBar;
import com.vaadin.ui.TextArea;
import com.vaadin.ui.TextField;
import com.vaadin.ui.Upload;
import com.vaadin.ui.Upload.FailedEvent;
import com.vaadin.ui.Upload.FinishedEvent;
import com.vaadin.ui.VerticalLayout;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Stream;
import okhttp3.Credentials;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.corpus_tools.annis.ApiClient;
import org.corpus_tools.annis.ApiException;
import org.corpus_tools.annis.api.CorporaApi;
import org.corpus_tools.annis.api.SearchApi;
import org.corpus_tools.annis.gui.AnnisUI;
import org.corpus_tools.annis.gui.Background;
import org.corpus_tools.annis.gui.Helper;
import org.corpus_tools.annis.gui.components.ExceptionDialog;
import org.corpus_tools.annis.gui.query_references.UrlShortener;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.web.util.UriComponentsBuilder;

public class MigrationPanel extends Panel
    implements Upload.Receiver, Upload.FinishedListener, Upload.FailedListener {

  private static final int TEXTFIELD_WIDTH = 30;

  static final String QUERY_PREFIX = "Query:";
  static final String UUID_PREFIX = "UUID: \"";
  static final String CORPUS_PREFIX = "Corpus: \"";

  private static final long serialVersionUID = -6893786947746535332L;

  private final TextArea txtMessages = new TextArea();
  private final Upload exportedFileUpload = new Upload();
  final ProgressBar progress = new ProgressBar();
  final TextField emailText = new TextField();
  final Button migrateButton = new Button("Start migration");

  private File urlShortenerFile;
  AnnisUI ui;

  private FormLayout formLayout;

  public MigrationPanel() {
    TextField serviceUrl = new TextField("Legacy ANNIS service URL");
    serviceUrl.setWidth(TEXTFIELD_WIDTH, Unit.EM);
    serviceUrl.setPlaceholder("https://example.com/annis3-service");
    TextField serviceUsername = new TextField("Username for legacy ANNIS service");
    serviceUsername.setWidth(TEXTFIELD_WIDTH, Unit.EM);
    PasswordField servicePassword = new PasswordField("Password for legacy ANNIS service");
    servicePassword.setWidth(30, Unit.EM);
    CheckBox skipExisting = new CheckBox("Skip existing UUIDs");

    migrateButton.addClickListener(event -> {
      txtMessages.setValue("");
      progress.setValue(0.0f);
      progress.setCaption("");
      Multimap<QueryStatus, URLShortenerDefinition> failedQueries = HashMultimap.create();
      String url = serviceUrl.getValue();
      String username = serviceUsername.getValue();
      String password = servicePassword.getValue();
      boolean skip = skipExisting.getValue();
      Background.runWithCallback(() -> {
        try {
          return migrateUrlShortener(url, username, password, skip, failedQueries);
        } catch (ApiException | IOException ex) {
          ExceptionDialog.show(ex, "Migrating URL shortener table failed", ui);
          return 0;
        }
      }, new MigrationCallback(this, failedQueries));

    });

    emailText.setCaption("E-Mail for status reports (optional)");
    emailText.setPlaceholder("you@example.com");
    emailText.setWidth(TEXTFIELD_WIDTH, Unit.EM);

    formLayout = new FormLayout(exportedFileUpload, serviceUrl, serviceUsername,
        servicePassword, skipExisting);
  }

  @Override
  public void attach() {
    super.attach();

    this.ui = (AnnisUI) getUI();
    setSizeFull();

    VerticalLayout layout = new VerticalLayout(formLayout, migrateButton, progress, txtMessages);
    layout.setSizeFull();
    layout.setMargin(true);
    layout.setExpandRatio(txtMessages, 1.0f);

    if (ui.getConfig().getMailHost() != null) {
      formLayout.addComponent(emailText);
    }

    exportedFileUpload.setCaption("Exported URL shortener entries as CSV file");
    exportedFileUpload.setReceiver(this);
    exportedFileUpload.addFinishedListener(this);
    exportedFileUpload.addFailedListener(this);

    progress.setValue(0.0f);
    progress.setCaption("");
    progress.setWidthFull();

    txtMessages.setSizeFull();
    txtMessages.setValue("");
    txtMessages.setReadOnly(true);
    txtMessages.addStyleName("message-output");

    migrateButton.setEnabled(false);
    migrateButton.setDisableOnClick(true);

    Optional<OAuth2User> user = Helper.getUser(getUI());
    if (user.isPresent()) {
      Set<String> roles = Helper.getUserRoles(user.get());
      if (roles.contains("admin")) {
        setContent(layout);
      }
    }
  }

  void setMessageAndScrollToEnd(String message) {
    txtMessages.setValue(message);
    txtMessages.setCursorPosition(txtMessages.getValue().length() - 1);
  }

  private boolean checkSingleQuery(URLShortenerDefinition q, SearchApi searchApi,
      UrlShortener urlShortener, OkHttpClient client, HttpUrl searchServiceBaseUrl,
      Multimap<QueryStatus, URLShortenerDefinition> failedQueries) {
    // check the query
    try {
      ui.access(() -> progress.setCaption(String.format("testing query %s on corpus %s (UUID %s)",
          q.getQuery().getQuery().trim(), q.getQuery().getCorpora(), q.getUuid())));

      QueryStatus status = q.test(searchApi, client, searchServiceBaseUrl);

      // insert URLs into new database
      URI temporary = null;

      if (status != QueryStatus.OK) {
        failedQueries.put(status, q);
        // Link the UUID to an error page temporarily, until the issue is fixed.
        // Remember the original URL, so the temporary URL can just be set
        // to null to resolve to the original URL when the issue is fixed in ANNIS.
        temporary = UriComponentsBuilder.newInstance().pathSegment("unsupported-query")
            .queryParam("url", q.getUri().toASCIIString()).build().toUri();
      }
      urlShortener.migrate(q.getUri(), temporary, "anonymous", q.getUuid(),
          q.getCreationTime() == null ? new Date() : q.getCreationTime().toDate());

      if (status == QueryStatus.OK) {
        return true;
      }

    } catch (RuntimeException ex) {
      q.setErrorMsg(getErrorMessage(ex));
      failedQueries.put(QueryStatus.FAILED, q);
    }

    return false;
  }

  private String getErrorMessage(Exception ex) {
    if (ex == null) {
      return "";
    } else if (ex.getMessage() == null) {
      return ex.getClass().toString();
    } else {
      return ex.getMessage();
    }
  }

  private boolean readUrlShortenerLine(String[] line, boolean skipExisting,
      Set<String> knownCorpora, SearchApi searchApi, OkHttpClient client,
      HttpUrl searchServiceBaseUrl, Multimap<QueryStatus, URLShortenerDefinition> failedQueries) {

    if (line.length != 4) {
      return false;
    }

    // parse URL
    try {
      URLShortenerDefinition q = URLShortenerDefinition.parse(line[3], line[0], line[2]);
      if (q != null) {
        // check if all corpora exist in the new instance
        List<String> corpusNames =
            q.getQuery() == null || q.getQuery().getCorpora() == null ? new LinkedList<>()
                : new LinkedList<>(q.getQuery().getCorpora());
        corpusNames.stream().filter(c -> !knownCorpora.contains(c)).forEach(q::addUnknownCorpus);

        if (!q.getUnknownCorpora().isEmpty()) {
          failedQueries.put(QueryStatus.UNKNOWN_CORPUS, q);
        } else if (corpusNames.isEmpty()) {
          q.setErrorMsg("Corpus name is empty");
          failedQueries.put(QueryStatus.FAILED, q);
        } else if (ui.getUrlShortener().unshorten(q.getUuid()).isPresent()) {
          if (skipExisting) {
            return false;
          } else {
            failedQueries.put(QueryStatus.UUID_EXISTS, q);
          }
        } else {
          return checkSingleQuery(q, searchApi, ui.getUrlShortener(), client, searchServiceBaseUrl,
              failedQueries);
        }
      }
    } catch (RuntimeException | URISyntaxException ex) {
      URLShortenerDefinition q =
          new URLShortenerDefinition(null, URLShortenerDefinition.parseUUID(line[0]), null);
      q.setErrorMsg(getErrorMessage(ex));
      failedQueries.put(QueryStatus.FAILED, q);
    }

    return false;
  }

  private Optional<OkHttpClient> createClient(String serviceURL, String username, String password) {
    OkHttpClient.Builder client = new OkHttpClient.Builder();

    HttpUrl parsedServiceUrl = HttpUrl.parse(serviceURL);
    if (username != null && password != null) {
      // Preemptivly add the authorization header to all requests
      client.addInterceptor(new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
          String credential = Credentials.basic(username, password);
          Request.Builder requestBuilder =
              chain.request().newBuilder().header("Authorization", credential);
          return chain.proceed(requestBuilder.build());
        }
      });

      // test authentication and fail early
      HttpUrl testUrl = parsedServiceUrl.newBuilder().addPathSegment("annis")
          .addPathSegment("admin").addPathSegment("is-authenticated").build();
      Request testRequest =
          new Request.Builder().url(testUrl).build();
      try {
        String result =
            client.build().newCall(testRequest).execute().body().string();
        if (!"true".equalsIgnoreCase(result)) {
          ui.access(() -> Notification
              .show("Authentication failed, please check the provided user name and password",
                  Notification.Type.ERROR_MESSAGE));
          return Optional.empty();
        }
      } catch (IOException ex) {
        ui.access(() -> ExceptionDialog.show(ex, "Could not connect to legacy service", ui));
        return Optional.empty();
      }
    }
    return Optional.of(client.build());
  }

  private int migrateUrlShortener(String serviceURL, String username, String password,
      boolean skipExisting, Multimap<QueryStatus, URLShortenerDefinition> failedQueries)
      throws ApiException, IOException {

    int successfulQueries = 0;

    HttpUrl parsedServiceUrl = HttpUrl.parse(serviceURL);
    HttpUrl searchServiceBaseUrl = parsedServiceUrl.newBuilder().addPathSegment("annis")
        .addPathSegment("query").addPathSegment("search").build();

    ApiClient apiClient = Helper.getClient(ui);
    CorporaApi corporaApi = new CorporaApi(apiClient);
    SearchApi searchApi = new SearchApi(apiClient);
    Set<String> knownCorpora = new HashSet<>(corporaApi.listCorpora());

    Optional<OkHttpClient> client = createClient(serviceURL, username, password);

    if (client.isPresent() && urlShortenerFile != null && urlShortenerFile.isFile()) {
      // Count all lines first so we can calculate the progress
      long numberOfQueries = 0;
      try (Stream<String> stream = Files.lines(urlShortenerFile.toPath(), StandardCharsets.UTF_8)) {
        numberOfQueries = stream.count();
      }
      long processedQueries = 0;
      try (CSVReader csvReader = new CSVReader(new FileReader(urlShortenerFile), '\t')) {
        String[] line;
        while ((line = csvReader.readNext()) != null) {
          if (readUrlShortenerLine(line, skipExisting, knownCorpora,
              searchApi, client.get(), searchServiceBaseUrl, failedQueries)) {
            successfulQueries++;
          }
          processedQueries++;
          float progressValue = numberOfQueries > 0 && processedQueries < numberOfQueries
              ? ((float) processedQueries / (float) numberOfQueries)
              : 1.0f;
          ui.access(() -> progress.setValue(progressValue));
        }
      }
    }

    return successfulQueries;
  }

  @Override
  public OutputStream receiveUpload(String filename, String mimeType) { // NO_UCD (test only)
    try {
      urlShortenerFile = File.createTempFile(filename, "");
      urlShortenerFile.deleteOnExit();
      exportedFileUpload.setButtonCaption(filename + " (Click to change)");
      return new FileOutputStream(urlShortenerFile);
    } catch (IOException ex) {
      ExceptionDialog.show(ex, getUI());
    }
    return null;
  }

  @Override
  public void uploadFinished(FinishedEvent event) { // NO_UCD (test only)
    migrateButton.setEnabled(true);
  }

  @Override
  public void uploadFailed(FailedEvent event) {
    setMessageAndScrollToEnd("Could not upload file: " + event.toString());
  }

  public String getMessages() {
    return txtMessages.getValue();
  }

  @Override
  public int hashCode() {
    return super.hashCode();
  }

  @Override
  public boolean equals(Object obj) {
    return super.equals(obj);
  }

}


text:
package org.jenkins.plugins.lockableresources;

import hudson.init.InitMilestone;
import hudson.init.Initializer;

import java.util.ArrayList;
import java.util.List;

import org.jenkinsci.plugins.workflow.steps.StepContext;
import org.jenkins.plugins.lockableresources.queue.LockableResourcesStruct;
import org.jenkins.plugins.lockableresources.queue.QueuedContextStruct;
import org.jenkins.plugins.lockableresources.LockableResource;
import org.jenkins.plugins.lockableresources.LockableResourcesManager;

import java.util.logging.Level;
import java.util.logging.Logger;

public final class BackwardCompatibility {
	private static final Logger LOG = Logger.getLogger(BackwardCompatibility.class.getName());

	@Initializer(after = InitMilestone.JOB_LOADED)
	public static void compatibilityMigration() {
		LOG.log(Level.FINE, "lockable-resource-plugin compatibility migration task run");
		List<LockableResource> resources = LockableResourcesManager.get().getResources();
		for (LockableResource resource : resources) {
			List<StepContext> queuedContexts = resource.getQueuedContexts();
			if (queuedContexts.size() > 0) {
				for (StepContext queuedContext : queuedContexts) {
					List<String> resourcesNames = new ArrayList<String>();
					resourcesNames.add(resource.getName());
					LockableResourcesStruct resourceHolder = new LockableResourcesStruct(resourcesNames, "", 0);
					LockableResourcesManager.get().queueContext(queuedContext, resourceHolder, resource.getName());
				}
				queuedContexts.clear();
			}
		}
	}
}


text:
package nagini.client.command;

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

import joptsimple.OptionParser;
import joptsimple.OptionSet;
import nagini.client.NaginiClient;

/**
 * Implements all stop commands.
 */
public class NaginiCommandStop extends AbstractCommand {

    /**
     * Parses command-line and directs to sub-commands.
     *
     * @param args Command-line input
     * @throws Exception
     */
    public static void executeCommand(String[] args) throws Exception {
        String subCmd = (args.length > 0) ? args[0] : "";
        args = CommandUtils.copyArrayCutFirst(args);
        if(subCmd.equals("app")) {
            SubCommandStopApp.executeCommand(args);
        } else {
            printHelp(System.out);
        }
    }

    /**
     * Prints command-line help menu.
     * */
    public static void printHelp(PrintStream stream) {
        stream.println();
        stream.println("Nagini Stop Commands");
        stream.println("--------------------");
        stream.println("app         Stop all application nodes on remote hosts.");
        stream.println();
        stream.println("To get more information on each command,");
        stream.println("please try \'help stop <command-name>\'.");
        stream.println();
    }

    /**
     * Parses command-line input and prints help menu.
     *
     * @throws Exception
     */
    public static void executeHelp(String[] args, PrintStream stream) throws Exception {
        String subCmd = (args.length > 0) ? args[0] : "";
        if(subCmd.equals("app")) {
            SubCommandStopApp.printHelp(stream);
        } else {
            printHelp(stream);
        }
    }

    /**
     * stop application command
     */
    public static class SubCommandStopApp extends AbstractCommand {

        /**
         * Initializes parser
         *
         * @return OptionParser object with all available options
         */
        protected static OptionParser getParser() {
            OptionParser parser = new OptionParser();
            // help options
            ParserUtils.acceptsHelp(parser);
            // required options
            ParserUtils.acceptsConfig(parser);
            // optional options
            ParserUtils.acceptsAllNodes(parser);
            ParserUtils.acceptsNodeMultiple(parser);
            return parser;
        }

        /**
         * Prints help menu for command.
         *
         * @param stream PrintStream object for output
         * @throws IOException
         */
        public static void printHelp(PrintStream stream) throws IOException {
            stream.println();
            stream.println("NAME");
            stream.println("  stop app - Stop all application nodes on remote hosts");
            stream.println();
            stream.println("SYNOPSIS");
            stream.println("  stop app --config <config-path> [-n <node-id-list> | --all-nodes]");
            stream.println();
            getParser().printHelpOn(stream);
            stream.println();
        }

        /**
         * Parses command-line and executes command.
         *
         * @param args Command-line input
         * @param printHelp Tells whether to print help only or execute command
         *        actually
         * @throws IOException
         *
         */
        @SuppressWarnings("unchecked")
        public static void executeCommand(String[] args) throws IOException {

            OptionParser parser = getParser();

            // declare parameters
            String configPath = null;
            Boolean allNodes = true;
            List<Integer> nodeIds = null;

            // parse command-line input
            OptionSet options = parser.parse(args);
            if(options.has(ParserUtils.OPT_HELP)) {
                printHelp(System.out);
                return;
            }

            // check required options and/or conflicting options
            ParserUtils.checkRequired(options, ParserUtils.OPT_CONFIG);
            ParserUtils.checkOptional(options, ParserUtils.OPT_NODE, ParserUtils.OPT_ALL_NODES);

            // load parameters
            configPath = (String) options.valueOf(ParserUtils.OPT_CONFIG);
            if(options.has(ParserUtils.OPT_NODE)) {
                nodeIds = (List<Integer>) options.valuesOf(ParserUtils.OPT_NODE);
                allNodes = false;
            }

            // execute command
            NaginiClient naginiClient = new NaginiClient(configPath);
            if(allNodes) {
                naginiClient.serviceOps.stopApplicationAllNodes();
            } else {
                for(Integer nodeId: nodeIds) {
                    naginiClient.serviceOps.stopApplicationOneNode(nodeId);
                }
            }
        }
    }
}