text:
local cli, _

-- ------- --
-- Helpers --
-- ------- --

local split = function(str, pat)
  local t = {}
  local fpat = "(.-)" .. pat
  local last_end = 1
  local s, e, cap = str:find(fpat, 1)
  while s do
    if s ~= 1 or cap ~= "" then
      table.insert(t,cap)
    end
    last_end = e+1
    s, e, cap = str:find(fpat, last_end)
  end
  if last_end <= #str then
    cap = str:sub(last_end)
    table.insert(t, cap)
  end
  return t
end

local buildline = function(words, size, overflow)
  -- if overflow is set, a word longer than size, will overflow the size
  -- otherwise it will be chopped in line-length pieces
  local line = ""
  if string.len(words[1]) > size then
    -- word longer than line
    if overflow then
      line = words[1]
      table.remove(words, 1)
    else
      line = words[1]:sub(1, size)
      words[1] = words[1]:sub(size + 1, -1)
    end
  else
    while words[1] and (#line + string.len(words[1]) + 1 <= size) or (line == "" and #words[1] == size) do
      if line == "" then
        line = words[1]
      else
        line = line .. " " .. words[1]
      end
      table.remove(words, 1)
    end
  end
  return line, words
end

local wordwrap = function(str, size, pad, overflow)
  -- if overflow is set, then words longer than a line will overflow
  -- otherwise, they'll be chopped in pieces
  pad = pad or 0

  local line = ""
  local out = ""
  local padstr = string.rep(" ", pad)
  local words = split(str, ' ')

  while words[1] do
    line, words = buildline(words, size, overflow)
    if out == "" then
      out = padstr .. line
    else
        out = out .. "\n" .. padstr .. line
    end
  end

  return out
end

local function disect(key)
  -- characters allowed are a-z, A-Z, 0-9
  -- extended + values also allow; # @ _ + -
  local k, ek, v
  local dummy
  -- if there is no comma, between short and extended, add one
  _, _, dummy = key:find("^%-([%a%d]+)[%s]%-%-")
  if dummy then key = key:gsub("^%-[%a%d][%s]%-%-", "-"..dummy..", --", 1) end
  -- for a short key + value, replace space by "="
  _, _, dummy = key:find("^%-([%a%d]+)[%s]")
  if dummy then key = key:gsub("^%-([%a%d]+)[ ]", "-"..dummy.."=", 1) end
  -- if there is no "=", then append one
  if not key:find("=") then key = key .. "=" end
  -- get value
  _, _, v = key:find(".-%=(.+)")
  -- get key(s), remove spaces
  key = split(key, "=")[1]:gsub(" ", "")
  -- get short key & extended key
  _, _, k = key:find("^%-([^-][^%s,]*)")
  _, _, ek = key:find("%-%-(.+)$")
  if v == "" then v = nil end
  return k,ek,v
end

local function callable(fn)
  return type(fn) == "function" or (getmetatable(fn) or {}).__call
end

function cli_error(msg, noprint)
  local msg = cli.name .. ": error: " .. msg .. '; re-run with --help for usage.'
  if not noprint then print(msg) end
  return nil, msg
end

-- -------- --
-- CLI Main --
-- -------- --

cli = {
  name = "",
  required = {},
  optional = {},
  optargument = {maxcount = 0},
  colsz = { 0, 0 }, -- column width, help text. Set to 0 for auto detect
  maxlabel = 0,
}

--- Assigns the name of the program which will be used for logging.
function cli:set_name(name)
  self.name = name
end

-- Used internally to lookup an entry using either its short or expanded keys
function cli:__lookup(k, ek, t)
  t = t or self.optional
  local _
  for _,entry in ipairs(t) do
    if k  and entry.key == k then return entry end
    if ek and entry.expanded_key == ek then return entry end
    if entry.has_no_flag then
      if ek and ("no-"..entry.expanded_key) == ek then return entry end
    end
  end

  return nil
end

--- Defines a required argument.
--- Required arguments have no special notation and are order-sensitive.
--- *Note:* the value will be stored in `args[@key]`.
--- *Aliases: `add_argument`*
---
--- ### Parameters
--- 1. **key**: the argument's "name" that will be displayed to the user
--- 2. **desc**: a description of the argument
--- 3. **callback**: *optional*; specify a function to call when this argument is parsed (the default is nil)
---
--- ### Usage example
--- The following will parse the argument (if specified) and set its value in `args["root"]`:
--- `cli:add_arg("root", "path to where root scripts can be found")`
function cli:add_arg(key, desc, callback)
  assert(type(key) == "string" and type(desc) == "string", "Key and description are mandatory arguments (Strings)")
  assert(callable(callback) or callback == nil, "Callback argument: expected a function or nil")

  if self:__lookup(key, nil, self.required) then
    error("Duplicate argument: " .. key .. ", please rename one of them.")
  end

  table.insert(self.required, { key = key, desc = desc, value = nil, callback = callback })
  if #key > self.maxlabel then self.maxlabel = #key end
end

--- Defines an optional argument (or more than one).
--- There can be only 1 optional argument, and it has to be the last one on the argumentlist.
--- *Note:* the value will be stored in `args[@key]`. The value will be a 'string' if 'maxcount == 1',
--- or a table if 'maxcount > 1'
---
--- ### Parameters
--- 1. **key**: the argument's "name" that will be displayed to the user
--- 2. **desc**: a description of the argument
--- 3. **default**: *optional*; specify a default value (the default is nil)
--- 4. **maxcount**: *optional*; specify the maximum number of occurences allowed (default is 1)
--- 5. **callback**: *optional*; specify a function to call when this argument is parsed (the default is nil)
---
--- ### Usage example
--- The following will parse the argument (if specified) and set its value in `args["root"]`:
--- `cli:add_arg("root", "path to where root scripts can be found", "", 2)`
--- The value returned will be a table with at least 1 entry and a maximum of 2 entries
function cli:optarg(key, desc, default, maxcount, callback)
  assert(type(key) == "string" and type(desc) == "string", "Key and description are mandatory arguments (Strings)")
  assert(type(default) == "string" or default == nil, "Default value must either be omitted or be a string")
  maxcount = maxcount or 1
  maxcount = tonumber(maxcount)
  assert(maxcount and maxcount>0 and maxcount<1000,"Maxcount must be a number from 1 to 999")
  assert(callable(callback) or callback == nil, "Callback argument: expected a function or nil")

  self.optargument = { key = key, desc = desc, default = default, maxcount = maxcount, value = nil, callback = callback }
  if #key > self.maxlabel then self.maxlabel = #key end
end

-- Used internally to add an option
function cli:__add_opt(k, ek, v, label, desc, default, callback)
  local flag = (v == nil) -- no value, so it's a flag
  local has_no_flag = flag and (ek and ek:find('^%[no%-]') ~= nil)
  local ek = has_no_flag and ek:sub(6) or ek

  -- guard against duplicates
  if self:__lookup(k, ek) then
    error("Duplicate option: " .. (k or ek) .. ", please rename one of them.")
  end
  if has_no_flag and self:__lookup(nil, "no-"..ek) then
    error("Duplicate option: " .. ("no-"..ek) .. ", please rename one of them.")
  end

  -- below description of full entry record, nils included for reference
  local entry = {
    key = k,
    expanded_key = ek,
    desc = desc,
    default = default,
    label = label,
    flag = flag,
    has_no_flag = has_no_flag,
    value = default,
    callback = callback,
  }

  table.insert(self.optional, entry)
  if #label > self.maxlabel then self.maxlabel = #label end

end

--- Defines an option.
--- Optional arguments can use 3 different notations, and can accept a value.
--- *Aliases: `add_option`*
---
--- ### Parameters
--- 1. **key**: the argument identifier, can be either `-key`, or `-key, --expanded-key`:
--- if the first notation is used then a value can be defined after a space (`'-key VALUE'`),
--- if the 2nd notation is used then a value can be defined after an `=` (`'-key, --expanded-key=VALUE'`).
--- As a final option it is possible to only use the expanded key (eg. `'--expanded-key'`) both with and
--- without a value specified.
--- 2. **desc**: a description for the argument to be shown in --help
--- 3. **default**: *optional*; specify a default value (the default is nil)
--- 4. **callback**: *optional*; specify a function to call when this option is parsed (the default is nil)
---
--- ### Usage example
--- The following option will be stored in `args["i"]` and `args["input"]` with a default value of `my_file.txt`:
--- `cli:add_option("-i, --input=FILE", "path to the input file", "my_file.txt")`
function cli:add_opt(key, desc, default, callback)
  -- parameterize the key if needed, possible variations:
  -- 1. -key
  -- 2. -key VALUE
  -- 3. -key, --expanded
  -- 4. -key, --expanded=VALUE
  -- 5. -key --expanded
  -- 6. -key --expanded=VALUE
  -- 7. --expanded
  -- 8. --expanded=VALUE

  assert(type(key) == "string" and type(desc) == "string", "Key and description are mandatory arguments (Strings)")
  assert(callable(callback) or callback == nil, "Callback argument: expected a function or nil")
  assert(
    (
      type(default) == "string"
      or default == nil
      or type(default) == "boolean"
      or (type(default) == "table" and next(default) == nil)
    ),
    "Default argument: expected a string, nil, or {}"
  )

  local k, ek, v = disect(key)

  -- set defaults
  if v == nil and type(default) ~= "boolean" then default = nil end

  self:__add_opt(k, ek, v, key, desc, default, callback)
end

--- Define a flag argument (on/off). This is a convenience helper for cli.add_opt().
--- See cli.add_opt() for more information.
---
--- ### Parameters
-- 1. **key**: the argument's key
-- 2. **desc**: a description of the argument to be displayed in the help listing
-- 3. **default**: *optional*; specify a default value (the default is nil)
-- 4. **callback**: *optional*; specify a function to call when this flag is parsed (the default is nil)
function cli:add_flag(key, desc, default, callback)
  if type(default) == "function" then
    callback = default
    default = nil
  end
  assert(default == nil or type(default) == "boolean", "Default argument: expected a boolean, nil")

  local k, ek, v = disect(key)

  if v ~= nil then
    error("A flag type option cannot have a value set: " .. key)
  end

  self:__add_opt(k, ek, nil, key, desc, default, callback)
end

--- Parses the arguments found in #arg and returns a table with the populated values.
--- (NOTE: after succesful parsing, the module will delete itself to free resources)
--- *Aliases: `parse_args`*
---
--- ### Parameters
--- 1. **arguments**: set this to arg
--- 2. **noprint**: set this flag to prevent any information (error or help info) from being printed
--- 3. **dump**: set this flag to dump the parsed variables for debugging purposes, alternatively
--- set the first option to --__DUMP__ (option with 2 trailing and leading underscores) to dump at runtime.
---
--- ### Returns
--- 1. a table containing the keys specified when the arguments were defined along with the parsed values,
--- or nil + error message (--help option is considered an error and returns nil + help message)
function cli:parse(arguments, noprint, dump)
  if type(arguments) ~= "table" then
    -- optional 'arguments' was not provided, so shift remaining arguments
    noprint, dump, arguments = arguments, noprint, nil
  end
  local arguments = arguments or arg or {}
  local args = {}
  for k,v in pairs(arguments) do args[k] = v end  -- copy args local

  -- starts with --help? display the help listing and abort!
  if args[1] and (args[1] == "--help" or args[1] == "-h") then
    return nil, self:print_help(noprint)
  end

  -- starts with --__DUMP__; set dump to true to dump the parsed arguments
  if dump == nil then
    if args[1] and args[1] == "--__DUMP__" then
      dump = true
      table.remove(args, 1)  -- delete it to prevent further parsing
    end
  end

  while args[1] do
    local entry = nil
    local opt = args[1]
    local _, optpref, optkey, optkey2, optval
    _, _, optpref, optkey = opt:find("^(%-[%-]?)(.+)")   -- split PREFIX & NAME+VALUE
    if optkey then
      _, _, optkey2, optval = optkey:find("(.-)[=](.+)")       -- split value and key
      if optval then
        optkey = optkey2
      end
    end

    if not optpref then
      break   -- no optional prefix, so options are done
    end

    if opt == "--" then
      table.remove(args, 1)
      break   -- end of options
    end

    if optkey:sub(-1,-1) == "=" then  -- check on a blank value eg. --insert=
      optval = ""
      optkey = optkey:sub(1,-2)
    end

    if optkey then
      entry =
        self:__lookup(optpref == '-' and optkey or nil,
                      optpref == '--' and optkey or nil)
    end

    if not optkey or not entry then
      local option_type = optval and "option" or "flag"
      return cli_error("unknown/bad " .. option_type .. ": " .. opt, noprint)
    end

    table.remove(args,1)
    if optpref == "-" then
      if optval then
        return cli_error("short option does not allow value through '=': "..opt, noprint)
      end
      if entry.flag then
        optval = true
      else
        -- not a flag, value is in the next argument
        optval = args[1]
        table.remove(args, 1)
      end
    elseif optpref == "--" then
      -- using the expanded-key notation
      entry = self:__lookup(nil, optkey)
      if entry then
        if entry.flag then
          if optval then
            return cli_error("flag --" .. optkey .. " does not take a value", noprint)
          else
            optval = not entry.has_no_flag or (optkey:sub(1,3) ~= "no-")
          end
        else
          if not optval then
            -- value is in the next argument
            optval = args[1]
            table.remove(args, 1)
          end
        end
      else
        return cli_error("unknown/bad flag: " .. opt, noprint)
      end
    end

    if type(entry.value) == 'table' then
      table.insert(entry.value, optval)
    else
      entry.value = optval
    end

    -- invoke the option's parse-callback, if any
    if entry.callback then
      local altkey = entry.key

      if optkey == entry.key then
        altkey = entry.expanded_key
      else
        optkey = entry.expanded_key
      end

      local status, err = entry.callback(optkey, optval, altkey, opt)
      if status == nil and err then
        return cli_error(err, noprint)
      end
    end
  end

  -- missing any required arguments, or too many?
  if #args < #self.required or #args > #self.required + self.optargument.maxcount then
    if self.optargument.maxcount > 0 then
      return cli_error("bad number of arguments: " .. #self.required .."-" .. #self.required + self.optargument.maxcount .. " argument(s) must be specified, not " .. #args, noprint)
    else
      return cli_error("bad number of arguments: " .. #self.required .. " argument(s) must be specified, not " .. #args, noprint)
    end
  end

  -- deal with required args here
  for i, entry in ipairs(self.required) do
    entry.value = args[1]
    if entry.callback then
      local status, err = entry.callback(entry.key, entry.value)
      if status == nil and err then
        return cli_error(err, noprint)
      end
    end
    table.remove(args, 1)
  end
  -- deal with the last optional argument
  while args[1] do
    if self.optargument.maxcount > 1 then
      self.optargument.value = self.optargument.value or {}
      table.insert(self.optargument.value, args[1])
    else
      self.optargument.value = args[1]
    end
    if self.optargument.callback then
      local status, err = self.optargument.callback(self.optargument.key, args[1])
      if status == nil and err then
        return cli_error(err, noprint)
      end
    end
    table.remove(args,1)
  end
  -- if necessary set the defaults for the last optional argument here
  if self.optargument.maxcount > 0 and not self.optargument.value then
    if self.optargument.maxcount == 1 then
      self.optargument.value = self.optargument.default
    else
      self.optargument.value = { self.optargument.default }
    end
  end

  -- populate the results table
  local results = {}
  if self.optargument.maxcount > 0 then
    results[self.optargument.key] = self.optargument.value
  end
  for _, entry in pairs(self.required) do
    results[entry.key] = entry.value
  end
  for _, entry in pairs(self.optional) do
    if entry.key then results[entry.key] = entry.value end
    if entry.expanded_key then results[entry.expanded_key] = entry.value end
  end

  if dump then
    print("\n======= Provided command line =============")
    print("\nNumber of arguments: ", #arg)
    for i,v in ipairs(arg) do -- use gloabl 'arg' not the modified local 'args'
      print(string.format("%3i = '%s'", i, v))
    end

    print("\n======= Parsed command line ===============")
    if #self.required > 0 then print("\nArguments:") end
    for i,v in ipairs(self.required) do
      print("  " .. v.key .. string.rep(" ", self.maxlabel + 2 - #v.key) .. " => '" .. v.value .. "'")
    end

    if self.optargument.maxcount > 0 then
      print("\nOptional arguments:")
      print("  " .. self.optargument.key .. "; allowed are " .. tostring(self.optargument.maxcount) .. " arguments")
      if self.optargument.maxcount == 1 then
          print("  " .. self.optargument.key .. string.rep(" ", self.maxlabel + 2 - #self.optargument.key) .. " => '" .. self.optargument.key .. "'")
      else
        for i = 1, self.optargument.maxcount do
          if self.optargument.value[i] then
            print("  " .. tostring(i) .. string.rep(" ", self.maxlabel + 2 - #tostring(i)) .. " => '" .. tostring(self.optargument.value[i]) .. "'")
          end
        end
      end
    end

    if #self.optional > 0 then print("\nOptional parameters:") end
    local doubles = {}
    for _, v in pairs(self.optional) do
      if not doubles[v] then
        local m = v.value
        if type(m) == "string" then
          m = "'"..m.."'"
        else
          m = tostring(m) .." (" .. type(m) .. ")"
        end
        print("  " .. v.label .. string.rep(" ", self.maxlabel + 2 - #v.label) .. " => " .. m)
        doubles[v] = v
      end
    end
    print("\n===========================================\n\n")
    return cli_error("commandline dump created as requested per '--__DUMP__' option", noprint)
  end

  if not _TEST then
    -- cleanup entire module, as it's single use
    -- remove from package.loaded table to enable the module to
    -- garbage collected.
    for k, v in pairs(package.loaded) do
      if v == cli then
        package.loaded[k] = nil
        break
      end
    end
    -- clear table in case user holds on to module table
    for k, _ in pairs(cli) do
      cli[k] = nil
    end
  end

  return results
end

--- Prints the USAGE heading.
---
--- ### Parameters
 ---1. **noprint**: set this flag to prevent the line from being printed
---
--- ### Returns
--- 1. a string with the USAGE message.
function cli:print_usage(noprint)
  -- print the USAGE heading
  local msg = "Usage: " .. tostring(self.name)
  if #self.optional > 0 then
    msg = msg .. " [OPTIONS]"
  end
  if #self.required > 0 or self.optargument.maxcount > 0 then
    msg = msg .. " [--]"
  end
  if #self.required > 0 then
    for _,entry in ipairs(self.required) do
      msg = msg .. " " .. entry.key
    end
  end
  if self.optargument.maxcount == 1 then
    msg = msg .. " [" .. self.optargument.key .. "]"
  elseif self.optargument.maxcount == 2 then
    msg = msg .. " [" .. self.optargument.key .. "-1 [" .. self.optargument.key .. "-2]]"
  elseif self.optargument.maxcount > 2 then
    msg = msg .. " [" .. self.optargument.key .. "-1 [" .. self.optargument.key .. "-2 [...]]]"
  end

  if not noprint then print(msg) end
  return msg
end

--- Prints the HELP information.
---
--- ### Parameters
--- 1. **noprint**: set this flag to prevent the information from being printed
---
--- ### Returns
--- 1. a string with the HELP message.
function cli:print_help(noprint)
  local msg = self:print_usage(true) .. "\n"
  local col1 = self.colsz[1]
  local col2 = self.colsz[2]
  if col1 == 0 then col1 = cli.maxlabel end
  col1 = col1 + 3     --add margins
  if col2 == 0 then col2 = 72 - col1 end
  if col2 <10 then col2 = 10 end

  local append = function(label, desc)
      label = "  " .. label .. string.rep(" ", col1 - (#label + 2))
      desc = wordwrap(desc, col2)   -- word-wrap
      desc = desc:gsub("\n", "\n" .. string.rep(" ", col1)) -- add padding

      msg = msg .. label .. desc .. "\n"
  end

  if self.required[1] then
    msg = msg .. "\nARGUMENTS: \n"
    for _,entry in ipairs(self.required) do
      append(entry.key, entry.desc .. " (required)")
    end
  end

  if self.optargument.maxcount > 0 then
    append(self.optargument.key, self.optargument.desc .. " (optional, default: " .. self.optargument.default .. ")")
  end

  if #self.optional > 0 then
    msg = msg .. "\nOPTIONS: \n"

    for _,entry in ipairs(self.optional) do
      local desc = entry.desc
      if not entry.flag and entry.default and #tostring(entry.default) > 0 then
        local readable_default = type(entry.default) == "table" and "[]" or tostring(entry.default)
        desc = desc .. " (default: " .. readable_default .. ")"
      elseif entry.flag and entry.has_no_flag then
        local readable_default = entry.default and 'on' or 'off'
        desc = desc .. " (default: " .. readable_default .. ")"
      end
      append(entry.label, desc)
    end
  end

  if not noprint then print(msg) end
  return msg
end

--- Sets the amount of space allocated to the argument keys and descriptions in the help listing.
--- The sizes are used for wrapping long argument keys and descriptions.
--- ### Parameters
--- 1. **key_cols**: the number of columns assigned to the argument keys, set to 0 to auto detect (default: 0)
--- 1. **desc_cols**: the number of columns assigned to the argument descriptions, set to 0 to auto set the total width to 72 (default: 0)
function cli:set_colsz(key_cols, desc_cols)
  self.colsz = { key_cols or self.colsz[1], desc_cols or self.colsz[2] }
end

-- finalize setup
cli._COPYRIGHT   = "Copyright (C) 2011-2014 Ahmad Amireh"
cli._LICENSE     = "The code is released under the MIT terms. Feel free to use it in both open and closed software as you please."
cli._DESCRIPTION = "Commandline argument parser for Lua"
cli._VERSION     = "cliargs 2.5-1"

-- aliases
cli.add_argument = cli.add_arg
cli.add_option = cli.add_opt
cli.parse_args = cli.parse    -- backward compatibility

-- test aliases for local functions
if _TEST then
  cli.split = split
  cli.wordwrap = wordwrap
end

return cli


text:
package org.springframework.boot.context.properties.source;

import java.util.function.Function;

import org.springframework.core.env.PropertySource;

/**
 * Details a mapping between a {@link PropertySource} item and a
 * {@link ConfigurationPropertySource} item.
 *
 * @author Phillip Webb
 * @author Madhura Bhave
 * @see SpringConfigurationPropertySource
 */
class PropertyMapping {

	private final String propertySourceName;

	private final ConfigurationPropertyName configurationPropertyName;

	private final Function<Object, Object> valueExtractor;

	/**
	 * Create a new {@link PropertyMapper} instance.
	 * @param propertySourceName the {@link PropertySource} name
	 * @param configurationPropertyName the {@link ConfigurationPropertySource}
	 * {@link ConfigurationPropertyName}
	 */
	PropertyMapping(String propertySourceName,
			ConfigurationPropertyName configurationPropertyName) {
		this(propertySourceName, configurationPropertyName, Function.identity());
	}

	/**
	 * Create a new {@link PropertyMapper} instance.
	 * @param propertySourceName the {@link PropertySource} name
	 * @param configurationPropertyName the {@link ConfigurationPropertySource}
	 * {@link ConfigurationPropertyName}
	 * @param valueExtractor the extractor used to obtain the value
	 */
	PropertyMapping(String propertySourceName,
			ConfigurationPropertyName configurationPropertyName,
			Function<Object, Object> valueExtractor) {
		this.propertySourceName = propertySourceName;
		this.configurationPropertyName = configurationPropertyName;
		this.valueExtractor = valueExtractor;
	}

	/**
	 * Return the mapped {@link PropertySource} name.
	 * @return the property source name (never {@code null})
	 */
	public String getPropertySourceName() {
		return this.propertySourceName;

	}

	/**
	 * Return the mapped {@link ConfigurationPropertySource}
	 * {@link ConfigurationPropertyName}.
	 * @return the configuration property source name (never {@code null})
	 */
	public ConfigurationPropertyName getConfigurationPropertyName() {
		return this.configurationPropertyName;

	}

	/**
	 * Return a function that can be used to extract the {@link PropertySource} value.
	 * @return the value extractor (never {@code null})
	 */
	public Function<Object, Object> getValueExtractor() {
		return this.valueExtractor;
	}

	/**
	 * Return if this mapping is applicable for the given
	 * {@link ConfigurationPropertyName}.
	 * @param name the name to check
	 * @return if the mapping is applicable
	 */
	public boolean isApplicable(ConfigurationPropertyName name) {
		return this.configurationPropertyName.equals(name);
	}

}

redpajama_set_name: RedPajamaGithub


text:
package ch.fhnw.ima.bimgur.activiti;

import ch.fhnw.ima.bimgur.activiti.service.*;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import javaslang.Lazy;
import javaslang.jackson.datatype.JavaslangModule;
import okhttp3.Credentials;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;

@SuppressWarnings("WeakerAccess")
public final class ActivitiRestClient {

    private static final Logger LOG = LoggerFactory.getLogger(ActivitiRestClient.class);

    private final Lazy<IdentityService> identityService;
    private final Lazy<RepositoryService> repositoryServices;
    private final Lazy<RuntimeService> runtimeServices;
    private final Lazy<TaskService> taskService;
    private final Lazy<FormDataService> formDataService;

    private ActivitiRestClient(Retrofit retrofit) {
        this.identityService = Lazy.of(() -> retrofit.create(IdentityService.class));
        this.repositoryServices = Lazy.of(() -> retrofit.create(RepositoryService.class));
        this.runtimeServices = Lazy.of(() -> retrofit.create(RuntimeService.class));
        this.taskService = Lazy.of(() -> retrofit.create(TaskService.class));
        this.formDataService = Lazy.of(() -> retrofit.create(FormDataService.class));

    }

    public static ActivitiRestClient connect(String baseUrl, String username, String password) {
        JacksonConverterFactory jacksonConverterFactory = createJacksonConverterFactory();
        OkHttpClient httpClient = createOkHttpClient(username, password);
        Retrofit retrofit = createRetrofit(baseUrl, jacksonConverterFactory, httpClient);
        return new ActivitiRestClient(retrofit);
    }

    public IdentityService getIdentityService() {
        return identityService.get();
    }

    private static JacksonConverterFactory createJacksonConverterFactory() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JavaslangModule());
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return JacksonConverterFactory.create(mapper);
    }

    private static OkHttpClient createOkHttpClient(String username, String password) {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(LOG::debug);
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
        return new OkHttpClient.Builder()
                .authenticator((route, response) -> {
                    String credential = Credentials.basic(username, password);

                    // If we already failed with these credentials, don't retry
                    // https://github.com/square/retrofit/issues/1561
                    if (credential.equals(response.request().header("Authorization"))) {
                        return null;
                    }

                    return response.request().newBuilder()
                            .header("Authorization", credential)
                            .build();
                })
                .addInterceptor(loggingInterceptor)
                .build();
    }

    private static Retrofit createRetrofit(String baseUrl, JacksonConverterFactory jacksonConverterFactory, OkHttpClient httpClient) {
        return new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(jacksonConverterFactory)
                .client(httpClient)
                .build();
    }

    public RepositoryService getRepositoryService() {
        return repositoryServices.get();
    }

    public RuntimeService getRuntimeService() {
        return this.runtimeServices.get();
    }

    public TaskService getTaskService() {
        return this.taskService.get();
    }

    public FormDataService getFormDataService() {
        return formDataService.get();
    }
}


text:
/**
 * Displays a list of runtime messages.
 *
 * Messages can be added with runtimeMessages.add and removed with runtimeMessages.remove.
 *
 * Messages are backbone models with the following attributes:
 *     code: the code to be used to look up the string for the message
 *     info: an object with any contextual params that the message needs
 *
 * Updating a message's attributes, runtimeMessages.add, and runtimeMessages.remove
 * will automatically trigger the UI to update with the latest state.
 */

var $ = require('jquery');
var _ = require('underscore');
var Backbone = require('backbone');
var messageStrings = require('../strings/runtime-message-strings');
var StringBundle  = require('../strings/string-bundle');
var escapeHtml = require('escape-html');

var stringBundle = new StringBundle(messageStrings);

function htmlEscapeObjectFields(obj) {
    return _.mapObject(obj, function(val) {
        return escapeHtml(val);
    });
}

var RuntimeMessages = function() {
    var el = this.el = document.createElement('div');
    var messageContentsEl = document.createElement('span');
    messageContentsEl.classList.add('message-contents');

    el.classList.add('juttle-view-runtime-messages');
    el.setAttribute('style', 'display: none');
    el.appendChild(messageContentsEl);

    this._messages = new Backbone.Collection();

    this._messages.on('add', this._render, this);
    this._messages.on('remove', this._render, this);
    this._messages.on('change', this._render, this);
};

RuntimeMessages.prototype.add = function(message) {
    this._messages.add(message);
};

RuntimeMessages.prototype.remove = function(message) {
    this._messages.remove(message);
};

RuntimeMessages.prototype.getMessages = function() {
    return this._messages;
};

RuntimeMessages.prototype._render = function() {
    var $el = $(this.el);

    if (this._messages.length === 0) {
        $el.stop(true).slideUp(function() {
            // a bit hacky but basically we need to clear any
            // other attributes jquery might have added.
            var $thisEl = $(this);
            $thisEl.attr('style', 'display: none;');
            $thisEl.find('.message-contents').html('');
            $el.find('.loader').remove();
        });
    }
    else {
        //loop over messages, if any are the waiting for data, then show it's special display
        var messages = [];

        $el.find('.loader').remove();
        $el.find('.message-icon').remove();

        _.each(this._messages.models, function(msg) {
            if (msg.get('code') === 'WAITING_FOR_DATA') {
                $el.append('
<svg class="circular"><circle class="path" cx="50" cy="50" r="20" fill="none" stroke-width="4" stroke-miterlimit="10"/></svg>
');
                setTimeout(function() {
                    var loader = $el.find('.loader');

                    if (loader.length > 0) {
                        loader.html('
' + stringBundle.getStringForCode('WAITING_FOR_DATA') + '
');
                    }
                }, 5000);
            } else {
                var escapedMsgInfo = htmlEscapeObjectFields(msg.get('info'));
                messages.push(stringBundle.getStringForCode(msg.get('code'),escapedMsgInfo));
            }
        });

        if (messages.length > 0) {
            // show the other messages as usual
            var messageIcon = $(' ')[0];
            $el[0].insertBefore(messageIcon, $el[0].firstChild);
            $el.find('.message-contents').html(messages.join(' '));
        }

        $el.stop(true).slideDown(function() {
            // a bit hacky but basically we need to clear any
            // other attributes jquery might have added.
            $(this).removeAttr('style');
        });
    }
};

RuntimeMessages.prototype.destroy = function() {
    this.el = null;
    this._messages.off();
    this._messages = null;
};

module.exports = RuntimeMessages;


text:
#include "fw_dunit.hpp"
#include "ThinClientHelper.hpp"

/* This is to test
1) Client can have diffrent Redundancy levels across Pools.
2) Diffrent Pools can connect to diff server groups,
3) Server Groups may have overlapping servers.
*/

#define CLIENT1 s1p1
#define CLIENT2 s1p2
#define LOCATOR s2p1
#define SERVERS s2p2

bool isLocalServer = false;
bool isLocator = false;
const char* endPoints1 = CacheHelper::getTcrEndpoints(isLocalServer, 1);
const char* endPoints2 = CacheHelper::getTcrEndpoints(isLocalServer, 2);
const char* endPoints3 = CacheHelper::getTcrEndpoints(isLocalServer, 3);
const char* locHostPort =
    CacheHelper::getLocatorHostPort(isLocator, isLocalServer, 1);
const char* poolRegNames[] = {"PoolRegion1", "PoolRegion2", "PoolRegion3"};
const char* poolNames[] = {"Pool1", "Pool2", "Pool3"};
const char* sGNames[] = {"ServerGroup1", "ServerGroup2", "ServerGroup3"};

void feedEntries(int keyIndex, bool newValue = false, bool update = false) {
  if (!update) {
    createEntry(poolRegNames[0], keys[keyIndex],
                newValue ? nvals[keyIndex] : vals[keyIndex]);
    createEntry(poolRegNames[1], keys[keyIndex],
                newValue ? nvals[keyIndex] : vals[keyIndex]);
    createEntry(poolRegNames[2], keys[keyIndex],
                newValue ? nvals[keyIndex] : vals[keyIndex]);
  } else {
    updateEntry(poolRegNames[0], keys[keyIndex],
                newValue ? nvals[keyIndex] : vals[keyIndex]);
    updateEntry(poolRegNames[1], keys[keyIndex],
                newValue ? nvals[keyIndex] : vals[keyIndex]);
    updateEntry(poolRegNames[2], keys[keyIndex],
                newValue ? nvals[keyIndex] : vals[keyIndex]);
  }
}

void verifyEntries(int keyIndex, bool netSearch = false,
                   bool newValue = false) {
  if (!netSearch) {
    verifyEntry(poolRegNames[0], keys[keyIndex],
                newValue ? nvals[keyIndex] : vals[keyIndex]);
    verifyEntry(poolRegNames[1], keys[keyIndex],
                newValue ? nvals[keyIndex] : vals[keyIndex]);
    verifyEntry(poolRegNames[2], keys[keyIndex],
                newValue ? nvals[keyIndex] : vals[keyIndex]);
  } else {
    doNetsearch(poolRegNames[0], keys[keyIndex],
                newValue ? nvals[keyIndex] : vals[keyIndex]);
    doNetsearch(poolRegNames[1], keys[keyIndex],
                newValue ? nvals[keyIndex] : vals[keyIndex]);
    doNetsearch(poolRegNames[2], keys[keyIndex],
                newValue ? nvals[keyIndex] : vals[keyIndex]);
  }
}

DUNIT_TASK_DEFINITION(LOCATOR, StartLocator)
  {
    // starting locator
    if (isLocator) CacheHelper::initLocator(1);
    LOG("Locator1 started");
  }
END_TASK_DEFINITION

DUNIT_TASK_DEFINITION(SERVERS, StartServers)
  {
    if (isLocalServer) {
      CacheHelper::initServer(1, "CacheServPoolRedun1.xml", locHostPort);
      LOG("SERVER1 started");
      CacheHelper::initServer(2, "CacheServPoolRedun2.xml", locHostPort);
      LOG("SERVER2 started");
      CacheHelper::initServer(3, "CacheServPoolRedun3.xml", locHostPort);
      LOG("SERVER3 started");
    }
  }
END_TASK_DEFINITION

DUNIT_TASK_DEFINITION(CLIENT1, CreateClient1_1)
  {
    initClient(true);

    // create three regions with three pools ( each having diff redun )
    createPool(poolNames[0], locHostPort, sGNames[0], 2, true);
    createRegionAndAttachPool(poolRegNames[0], USE_ACK, poolNames[0], true);

    createPool(poolNames[1], locHostPort, sGNames[0], 1, true);
    createRegionAndAttachPool(poolRegNames[1], USE_ACK, poolNames[1], true);

    createPool(poolNames[2], locHostPort, sGNames[0], 0, true);
    createRegionAndAttachPool(poolRegNames[2], USE_ACK, poolNames[2], true);

    feedEntries(0);

    auto regPtr0 = getHelper()->getRegion(poolRegNames[0]);
    auto regPtr1 = getHelper()->getRegion(poolRegNames[1]);
    auto regPtr2 = getHelper()->getRegion(poolRegNames[2]);

    regPtr0->registerAllKeys(false, true);
    regPtr1->registerAllKeys(false, true);
    regPtr2->registerAllKeys(false, true);

    LOG("CreateClient1 complete.");
  }
END_TASK_DEFINITION

DUNIT_TASK_DEFINITION(CLIENT2, CreateClient2_1)
  {
    initClient(true);

    // create three regions with three pools ( each having diff redun )
    createPool(poolNames[0], locHostPort, nullptr, 2, true);
    createRegionAndAttachPool(poolRegNames[0], USE_ACK, poolNames[0], true);

    createPool(poolNames[1], locHostPort, nullptr, 1, true);
    createRegionAndAttachPool(poolRegNames[1], USE_ACK, poolNames[1], true);

    createPool(poolNames[2], locHostPort, nullptr, 0, true);
    createRegionAndAttachPool(poolRegNames[2], USE_ACK, poolNames[2], true);

    feedEntries(1);

    auto regPtr0 = getHelper()->getRegion(poolRegNames[0]);
    auto regPtr1 = getHelper()->getRegion(poolRegNames[1]);
    auto regPtr2 = getHelper()->getRegion(poolRegNames[2]);

    regPtr0->registerAllKeys(false, true);
    regPtr1->registerAllKeys(false, true);
    regPtr2->registerAllKeys(false, true);

    LOG("CreateClient2 verify starts.");
    verifyEntries(0);

    LOG("CreateClient2 complete.");
  }
END_TASK_DEFINITION

DUNIT_TASK_DEFINITION(CLIENT1, CreateClient1_2)
  {
    initClient(true);

    // create three regions with three pools ( each having diff redun )
    createPool(poolNames[0], locHostPort, sGNames[0], 2, true);
    createRegionAndAttachPool(poolRegNames[0], USE_ACK, poolNames[0], true);

    createPool(poolNames[1], locHostPort, sGNames[1], 1, true);
    createRegionAndAttachPool(poolRegNames[1], USE_ACK, poolNames[1], true);

    createPool(poolNames[2], locHostPort, sGNames[2], 0, true);
    createRegionAndAttachPool(poolRegNames[2], USE_ACK, poolNames[2], true);

    feedEntries(0);

    auto regPtr0 = getHelper()->getRegion(poolRegNames[0]);
    auto regPtr1 = getHelper()->getRegion(poolRegNames[1]);
    auto regPtr2 = getHelper()->getRegion(poolRegNames[2]);

    regPtr0->registerAllKeys(false, true);
    regPtr1->registerAllKeys(false, true);
    regPtr2->registerAllKeys(false, true);

    LOG("CreateClient1 complete.");
  }
END_TASK_DEFINITION

DUNIT_TASK_DEFINITION(CLIENT2, CreateClient2_2)
  {
    initClient(true);

    // create three regions with three pools ( each having diff redun )
    createPool(poolNames[0], locHostPort, nullptr, 2, true);
    createRegionAndAttachPool(poolRegNames[0], USE_ACK, poolNames[0], true);

    createPool(poolNames[1], locHostPort, nullptr, 1, true);
    createRegionAndAttachPool(poolRegNames[1], USE_ACK, poolNames[1], true);

    createPool(poolNames[2], locHostPort, nullptr, 0, true);
    createRegionAndAttachPool(poolRegNames[2], USE_ACK, poolNames[2], true);

    feedEntries(1);

    auto regPtr0 = getHelper()->getRegion(poolRegNames[0]);
    auto regPtr1 = getHelper()->getRegion(poolRegNames[1]);
    auto regPtr2 = getHelper()->getRegion(poolRegNames[2]);

    regPtr0->registerAllKeys(false, true);
    regPtr1->registerAllKeys(false, true);
    regPtr2->registerAllKeys(false, true);

    verifyEntries(0);

    LOG("CreateClient2 complete.");
  }
END_TASK_DEFINITION

DUNIT_TASK_DEFINITION(CLIENT1, VerifyK1C1)
  {
    verifyEntries(1);
    LOG("Verify1Client1 complete.");
  }
END_TASK_DEFINITION

DUNIT_TASK_DEFINITION(CLIENT1, CloseServer1)
  {
    CacheHelper::closeServer(1);
    LOG("SERVER1 stopped");
  }
END_TASK_DEFINITION

DUNIT_TASK_DEFINITION(CLIENT1, CloseServer2)
  {
    CacheHelper::closeServer(2);
    LOG("SERVER2 stopped");
  }
END_TASK_DEFINITION

DUNIT_TASK_DEFINITION(CLIENT1, FeedC1)
  {
    feedEntries(0, true, true);
    SLEEP(1000);
    LOG("FeedC1 complete.");
  }
END_TASK_DEFINITION

DUNIT_TASK_DEFINITION(CLIENT2, VerifyK0C2New)
  {
    verifyEntries(0, false, true);
    LOG("StepFive complete.");
  }
END_TASK_DEFINITION

DUNIT_TASK_DEFINITION(CLIENT2, FeedC2)
  {
    LOG("wait after step seven");
    SLEEP(10000);
    LOG("StepSeven complete.");
    feedEntries(1, true, true);
  }
END_TASK_DEFINITION

DUNIT_TASK_DEFINITION(CLIENT1, VerifyK1C1New)
  {
    verifyEntries(1, false, true);
    LOG("Verify1Client1 complete.");
  }
END_TASK_DEFINITION

DUNIT_TASK_DEFINITION(CLIENT1, VerifyK1C1New2)
  {
    auto regPtr = getHelper()->getRegion(poolRegNames[2]);

    auto keyPtr = createKey(keys[1]);

    auto checkPtr =
        std::dynamic_pointer_cast<CacheableString>(regPtr->get(keyPtr));

    ASSERT(checkPtr != nullptr, "Value Ptr should not be null.");

    char buf[1024];
    sprintf(buf, "get returned %s for key %s", checkPtr->asChar(), keys[1]);
    LOG(buf);

    if (strcmp(checkPtr->asChar(), nvals[1]) != 0) {
      LOG("ServerGroup2 is not available. So poolRegion2 returned old value..");
      return;
    }

    LOG("Verify1Client1 complete.");

    ASSERT(false, "Something is wrong with ServerGroup2");
  }
END_TASK_DEFINITION

DUNIT_TASK_DEFINITION(CLIENT1, CloseCache1)
  { cleanProc(); }
END_TASK_DEFINITION

DUNIT_TASK_DEFINITION(CLIENT2, CloseCache2)
  { cleanProc(); }
END_TASK_DEFINITION

DUNIT_TASK_DEFINITION(SERVERS, CloseServers)
  {
    if (isLocalServer) {
      CacheHelper::closeServer(1);
      LOG("SERVER2 stopped");
      CacheHelper::closeServer(2);
      LOG("SERVER3 stopped");
      CacheHelper::closeServer(3);
      LOG("SERVER4 stopped");
    }
  }
END_TASK_DEFINITION

DUNIT_TASK_DEFINITION(LOCATOR, CloseLocator)
  {
    // stop locator
    if (isLocator) {
      CacheHelper::closeLocator(1);
      LOG("Locator1 stopped");
    }
  }
END_TASK_DEFINITION

DUNIT_MAIN
  {
    for (int runIndex = 0; runIndex < 2; ++runIndex) {
      CALL_TASK(StartLocator)
      CALL_TASK(StartServers)
      if (runIndex == 0) {
        CALL_TASK(CreateClient1_1)
        CALL_TASK(CreateClient2_1)
      } else {
        CALL_TASK(CreateClient1_2)
        CALL_TASK(CreateClient2_2)
      }
      CALL_TASK(VerifyK1C1)

      // Failover

      if (runIndex == 0) {
        CALL_TASK(CloseServer1)
        CALL_TASK(CloseServer2)
      }

      CALL_TASK(FeedC1)
      CALL_TASK(VerifyK0C2New)
      if (runIndex == 1) {
        CALL_TASK(CloseServer1)
      }
      CALL_TASK(FeedC2)

      if (runIndex == 0) {
        CALL_TASK(VerifyK1C1New)
      } else {
        CALL_TASK(VerifyK1C1New2)
      }
      CALL_TASK(CloseCache1)
      CALL_TASK(CloseCache2)
      CALL_TASK(CloseServers)
      CALL_TASK(CloseLocator)
    }
  }
END_MAIN


text:
package com.xplus.commons.thread.senior.concurrent.util.lock;

import java.util.Random;

public class ReadWithSynchronizedTest {

  // 输出结果会是,直到thread1执行完读操作之后,才会打印thread2执行读操作的信息。
  public static void main(String[] args) {
    final ReadWithSynchronizedTest test = new ReadWithSynchronizedTest();
    for(int i = 0; i < 5; i++) {
      new Thread() {
        public void run() {
          test.get(Thread.currentThread());
        };
      }.start();
    }
  }

  public synchronized void get(Thread thread) {
    System.out.println(thread.getName() + "正在进行读操作");
    try {
      Thread.sleep(new Random().nextInt(1000));
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println(thread.getName() + "读操作完毕");
  }
}


text:
from flask_wtf import validators, Form
from wtforms import StringField, PasswordField, validators, BooleanField

class LoginForm(Form):
    username = StringField('username', [validators.DataRequired()])
    password = PasswordField('password', [validators.DataRequired()])

class AddUser(Form):
    username = StringField('Username', [validators.DataRequired()])
    email = StringField('Email', [validators.DataRequired(), validators.Email()])
    password = PasswordField('New Password', [
        validators.DataRequired(),
        validators.EqualTo('confirm', message='Passwords must match')
    ])
    confirm = PasswordField('Repeat Password')
    adminuser = BooleanField('Admin?')

class EditUser(Form):
    username = StringField('Username')
    email = StringField('Email', [validators.Email()])
    oldpassword = PasswordField('Old Password')
    password = PasswordField('New Password', [
        validators.DataRequired(),
        validators.EqualTo('confirm', message='Passwords must match')])
    confirm = PasswordField('Repeat Password')


text:
import { LetterAa20 } from "../../";

export = LetterAa20;


text: INSERT INTO t1 VALUES(314159, 'sqlite')


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Minimal</string>

    <string name="action_settings">设置</string>
    <string name="no_to_dos">任务都完成啦~</string>
    <string name="title">标题</string>
    <string name="remind_me">提醒我</string>
    <string name="choose_date">日期</string>
    <string name="choose_time">时间</string>
    <string name="remind_date_and_time">设置提醒时间为 %1$s, %2$s %3$s</string>
    <string name="about">关于</string>
    <string name="app_version">版本号: %1$s</string>
    <string name="contact_me">联系作者</string>
    <string name="made_by">由Avjinder开发</string>
    <string name="done_label">完成</string>
    <string name="date_reminder_default">今天</string>
    <string name="date_error_check_again">该提醒时间已设置</string>
    <string name="night_mode">夜间模式</string>
    <string name="night_mode_on_summary">夜间模式已开启</string>
    <string name="night_mode_off_summary">夜间模式已关闭</string>

    <string-array name="snooze_options">
        <item>10 分钟</item>
        <item>30 分钟</item>
        <item>1 小时</item>
    </string-array>

    <string name="snooze">小睡</string>
    <string name="remove">移除</string>
</resources>


text:
FactoryGirl.define do
  factory :school_class do
    sequence(:name) { |n| "school-class-#{n}" }
    teacher
  end
end


text:
#include "xmlsecrb.h"

/* not actually called anywhere right now, but here for posterity */
void Shutdown_xmlsecrb() {
  xmlSecCryptoShutdown();
  xmlSecCryptoAppShutdown();
  xmlSecShutdown();
  xsltCleanupGlobals();
  #ifndef XMLSEC_NO_XSLT
    xsltCleanupGlobals();
  #endif /* XMLSEC_NO_XSLT */
}


text:
<?php

namespace HtSession\Options;

interface SessionOptionsInterface
{
    public function setEnableSessionSetSaveHandler($enableSessionSetSaveHandler);

    public function getEnableSessionSetSaveHandler();

    public function setConfigClass($configClass);

    public function getConfigClass();

    public function setConfigOptions($configOptions) ;

    public function setStorage($storage);

    public function getStorage();

    public function setValidators(array $validators);

    public function getValidators();

    public function addValidator($validator);

}


text:
package main

import (
	"github.com/hyperledger/fabric/common/localmsp"
	"github.com/hyperledger/fabric/common/tools/configtxgen/encoder"
	genesisconfig "github.com/hyperledger/fabric/common/tools/configtxgen/localconfig"
	cb "github.com/hyperledger/fabric/protos/common"
)

func newChainRequest(consensusType, creationPolicy, newChannelID string) *cb.Envelope {
	env, err := encoder.MakeChannelCreationTransaction(newChannelID, localmsp.NewSigner(), genesisconfig.Load(genesisconfig.SampleSingleMSPChannelProfile))
	if err != nil {
		panic(err)
	}
	return env
}


text:
require 'faraday'
require 'hashie'
require 'multi_json'

require 'shirtsio/version'
require 'shirtsio/error'
require 'shirtsio/utils'

require 'shirtsio/configuration'
require 'shirtsio/connection'
require 'shirtsio/request'
require 'shirtsio/api'
require 'shirtsio/dsl'
require 'shirtsio/endpoint'

require 'shirtsio/product'
require 'shirtsio/quote'
require 'shirtsio/order'
require 'shirtsio/status'

module Shirtsio
  extend Configuration

  def self.api(options = {})
    Shirtsio::API.new(options)
  end

  def self.method_missing(method, *args, &block)
    return super unless api.respond_to?(method)
    api.send(method, *args, &block)
  end

  def self.respond_to?(method)
    api.respond_to?(method) || super
  end
end


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE23_Relative_Path_Traversal__wchar_t_environment_ifstream_43.cpp
Label Definition File: CWE23_Relative_Path_Traversal.label.xml
Template File: sources-sink-43.tmpl.cpp
*/
/*
 * @description
 * CWE: 23 Relative Path Traversal
 * BadSource: environment Read input from an environment variable
 * GoodSource: Use a fixed file name
 * Sinks: ifstream
 *    BadSink : Open the file named in data using ifstream::open()
 * Flow Variant: 43 Data flow: data flows using a C++ reference from one function to another in the same source file
 *
 * */

#include "std_testcase.h"

#ifdef _WIN32
#define BASEPATH L"c:\\temp\\"
#else
#include <wchar.h>
#define BASEPATH L"/tmp/"
#endif

#define ENV_VARIABLE L"ADD"

#ifdef _WIN32
#define GETENV _wgetenv
#else
#define GETENV getenv
#endif

#include <fstream>
using namespace std;

namespace CWE23_Relative_Path_Traversal__wchar_t_environment_ifstream_43
{

#ifndef OMITBAD

void badSource(wchar_t * &data)
{
    {
        /* Append input from an environment variable to data */
        size_t dataLen = wcslen(data);
        wchar_t * environment = GETENV(ENV_VARIABLE);
        /* If there is data in the environment variable */
        if (environment != NULL)
        {
            /* POTENTIAL FLAW: Read data from an environment variable */
            wcsncat(data+dataLen, environment, FILENAME_MAX-dataLen-1);
        }
    }
}

void bad()
{
    wchar_t * data;
    wchar_t dataBuffer[FILENAME_MAX] = BASEPATH;
    data = dataBuffer;
    badSource(data);
    {
        ifstream inputFile;
        /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
        inputFile.open((char *)data);
        inputFile.close();
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2BSource(wchar_t * &data)
{
    /* FIX: Use a fixed file name */
    wcscat(data, L"file.txt");
}

static void goodG2B()
{
    wchar_t * data;
    wchar_t dataBuffer[FILENAME_MAX] = BASEPATH;
    data = dataBuffer;
    goodG2BSource(data);
    {
        ifstream inputFile;
        /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
        inputFile.open((char *)data);
        inputFile.close();
    }
}

void good()
{
    goodG2B();
}

#endif /* OMITGOOD */

} /* close namespace */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

using namespace CWE23_Relative_Path_Traversal__wchar_t_environment_ifstream_43; /* so that we can use good and bad easily */

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
// © 2012 - 2019 Soverance Studios
// https://soverance.com

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

// http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#pragma once

#include "GameFramework/Actor.h"
#include "CombatEffectStruct.h"
#include "VisualEffect.generated.h"

UCLASS()
class ENDLESSREACHHD_API AVisualEffect : public AActor
{
	GENERATED_BODY()

public:

	// Sets default values for this actor's properties
	AVisualEffect(const FObjectInitializer& ObjectInitializer);

	// Called when the game starts or when spawned
	virtual void BeginPlay() override;

	// Called every frame
	virtual void Tick( float DeltaSeconds ) override;

	/** The root scene component for all Visual Effect actors. */
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Bindings)
	USceneComponent* Root;

	// Status FX.
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Effects)
	UParticleSystemComponent* StatusFX;
	UParticleSystem* P_StatusFX;

	// Status FX.
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Effects)
	FCombatEffectStruct CombatEffect;

	/** Casts this spell. */
	UFUNCTION(BlueprintCallable, Category = Controls)
	void StartFX(FCombatEffectStruct Effect);
};


text:
        This test is to see if a remote file can include a local page via a filesystem: URI in an iFrame.

        Test not run correctly.


text:
from gnr.core.gnrbag import Bag
from gnr.core.gnrdecorator import public_method

from settings import BOARD_METHODS

class GnrCustomWebPage(object):

    css_requires = 'css/base'
    js_requires = 'js/team,js/board,js/list,js/card'

    auth_main = 'admin,user'

    def main(self, root, **kwargs):
        frame = root.framePane()
        sc = frame.center.stackContainer(selected='^page_selected')

        self.team_page(sc.contentPane(title='!!Teams', datapath='teams'))
        self.board_page(sc.contentPane(datapath='board'))

        top = frame.top.slotToolbar('8,home,*,logout', _class='page-slotbar')
        top.home.i(
            _class='fa fa-home home-icon',
            connect_onclick="this.setRelativeData('page_selected', 0);"
        )
        top.logout.div(
        connect_onclick="genro.mainGenroWindow.genro.logout()",
        _class='iconbox icnBaseUserLogout',
        tip='!!Logout'
        )
        sc.data('^page_selected', 0)
        sc.data('new_board.methods', BOARD_METHODS)

    def team_page(self, pane):
        pane.attributes.update({'background_color': 'white',
                                'nodeId': 'team_page',
                                'id': 'team_page'})

        qs =  self.get_teams_boards()
        pane.data('^teams', qs)

        for r in qs:
            team_id = r.getLabel()
            values = r.getValue()

            team_div = pane.div(_class='team-div')
            team_div.div(
                '^.{0}?team_name'.format(team_id),
                _class='team-title'
            )

            board_div = team_div.div(_class='team-boards-div'
            ).div(_class='board-list', nodeId=team_id, id=team_id)

            if values:
                for v in values:
                    board_id = v.getValue().getItem('pkey')
                    # Set the board_id as attribute so i can use to his list etc..
                    board_div.div(
                        board_id=board_id ,
                        board_name=v.getValue().getItem('name'),
                        _class='board-list-item',
                        connect_onclick="""
                        // call a function to generate the board page
                        generate_board_page(this);
                        """,
                    ).div(
                        '^.{0}.{1}.name'.format(team_id, board_id),
                        _class='board-tile'
                    )

            # Button to create a new board
            board_div.div(
                id='create_new_board_' + team_id,
                team_id=team_id,
                _class='board-list-item',
                connect_onclick="create_new_board(this);"
            ).div(
                '!!+ Create new board...',
                _class='board-tile create-new-board'
            )

        pane.div(_class='team-div').div(
            id='create_new_team', _class='add-new-team-btn',
            connect_onclick="create_new_team(this);"
        ).div('!!Add new team')

    def board_page(self, pane):
        # Entry point of the board page.
        pane.attributes.update({'background_color': 'rgb(0, 121, 191)'})

        pane.div(
            id='board_header', nodeId='board_header',
            _class='board-header'
        )

        pane.div(
            id='board_page', nodeId='board_page',
            _class='board-page'
        )

        pane.dataRpc(
            'rels_saved', self.save_cards_rel,
            board='=board', board_id='=board_id',
            is_changed='=board_is_changed',
            page_selected='^page_selected'
        )

    @public_method
    def get_teams_boards(self):
        """Gets a bag with team and boards"""

        user_id = self.dbCurrentEnv()['user_id']

        tbl = self.db.table('base.team')
        teams_qs = tbl.query(
            where='$owner_user_id=:user_id',
            user_id=user_id,
            order_by='$__ins_ts'
        ).fetch()

        tbl = self.db.table('base.board')
        boards_qs = tbl.query(
            '$name,$team_id',
            where='$owner_user_id=:user_id',
            user_id=user_id,
            order_by='$position'
        ).fetch()

        result = Bag()
        for t in teams_qs:
            result.setAttr(t['id'], team_name=t['name'])

        for b in boards_qs:
            result.setItem('{0}.{1}'.format(b['team_id'], b['pkey']), Bag(b))

        return result

    @public_method
    def get_lists_cards(self, board_id):
        """Gets a bag with lists and cards"""

        tbl = self.db.table('base.list')
        lists_qs = tbl.query(
            where='$board_id=:board_id',
            board_id=board_id,
            order_by='$position'
        ).fetch()

        tbl = self.db.table('base.card')
        cards_qs = tbl.query(
            '$name,$description,$position,$list_name,$list_id',
            where='$list_board_id=:board_id',
            board_id=board_id,
            order_by='$position'
        ).fetch()

        result = Bag()
        for lst in lists_qs:
            result.setItem(lst['id'], Bag(), list_name=lst['name'])

        for crd in cards_qs:
            result.setItem('{0}.{1}'.format(crd['list_id'], crd['pkey']), Bag(crd))

        return result

    @public_method
    def get_card_comments(self, card_id):
        tbl = self.db.table('base.comment')
        comments_qs = tbl.query(
            '$comment,$__ins_ts,$__mod_ts,$username',
            where='card_id=:card_id',
            card_id=card_id,
            order_by='$__ins_ts DESC'
        ).fetch()
        result = Bag()
        for cm in comments_qs:
            result.setItem(cm['pkey'], Bag(cm))

        return result

    @public_method
    def save_cards_rel(self, board, board_id, is_changed, page_selected):
        """Save the chaange of relationship list-card """

        if not is_changed:
            return

        tbl = self.db.table('base.card')
        for _list in board[board_id]:
            for card in _list.getValue():
                tbl.update({
                    'id': card.getLabel(),
                    'list_id': _list.getLabel()
                })
                tbl.db.commit()

    @public_method
    def save_card(self, list_id, card_name):
        """Save the card """

        tbl = self.db.table('base.card')
        card = {
            'name': card_name,
            'list_id': list_id
        }
        tbl.insert(card)
        tbl.db.commit()
        return Bag(card)

    @public_method
    def save_comment(self, card_id, value):
        user_id = self.dbCurrentEnv()['user_id']
        username = self.dbCurrentEnv()['user']

        tbl = self.db.table('base.comment')
        comment = {
            'comment': value,
            'card_id': card_id,
            'owner_user_id': user_id
        }
        try:
            tbl.insert(comment)
            tbl.db.commit()
            comment['username'] = username
            return Bag(comment)
        except Exception as e:
            raise e

    @public_method
    def update_card_description(self, card_id, description):
        """Add/Update the description of a card"""

        tbl = self.db.table('base.card')
        tbl.update({
            'id': card_id,
            'description': description
        })
        tbl.db.commit()
        return True

    @public_method
    def edit_list_name(self, list_id, board_id, value):
        """Save name of a list after the field has been edited"""

        value = value.strip()
        if not value:
            return False

        tbl = self.db.table('base.list')
        tbl.update({'id': list_id, 'name': value,
                    'board_id': board_id})
        tbl.db.commit()
        return True

    @public_method
    def delete_list(self, list_id):
        """Delete list"""

        tbl = self.db.table('base.list')
        try:
            tbl.delete({'id': list_id})
            tbl.db.commit()
            return True
        except Exception as e:
            print e
            return False

    @public_method
    def add_new_list(self, board_id, value):
        """Add new list"""

        value = value.strip()
        if not value:
            return False

        tbl = self.db.table('base.list')
        new_list = {'name': value,
                    'board_id': board_id}
        tbl.insert(new_list)
        tbl.db.commit()
        return Bag(new_list)

    @public_method
    def add_board(self, name, description, b_method, position, team_id):
        """Add a new board"""

        values = {
            'name': name,
            'description': description,
            'method': b_method,
            'position': position,
            'team_id': team_id,
            'owner_user_id': self.dbCurrentEnv()['user_id']
        }
        tbl = self.db.table('base.board')
        tbl.insert(values)
        tbl.db.commit()

        return Bag(values)

    @public_method
    def add_team(self, name, description):
        values = {
            'name': name,
            'description': description,
            'owner_user_id': self.dbCurrentEnv()['user_id']
        }
        tbl = self.db.table('base.team')
        tbl.insert(values)
        tbl.db.commit()

        return Bag(values)


text:
class CPDF_Dictionary;
class CPDF_Document;
class CPDF_Font;
class CPDF_FontEncoding;
class CPDF_IccProfile;
class CPDF_Image;
class CPDF_Object;
class CPDF_Stream;
class CPDF_StreamAcc;

class CPDF_DocPageData {
 public:
  explicit CPDF_DocPageData(CPDF_Document* pPDFDoc);
  ~CPDF_DocPageData();

  void Clear(bool bRelease = false);
  CPDF_Font* GetFont(CPDF_Dictionary* pFontDict);
  CPDF_Font* GetStandardFont(const CFX_ByteString& fontName,
                             CPDF_FontEncoding* pEncoding);
  void ReleaseFont(const CPDF_Dictionary* pFontDict);
  CPDF_ColorSpace* GetColorSpace(CPDF_Object* pCSObj,
                                 const CPDF_Dictionary* pResources);
  CPDF_ColorSpace* GetCopiedColorSpace(CPDF_Object* pCSObj);
  void ReleaseColorSpace(const CPDF_Object* pColorSpace);
  CPDF_Pattern* GetPattern(CPDF_Object* pPatternObj,
                           bool bShading,
                           const CFX_Matrix& matrix);
  void ReleasePattern(const CPDF_Object* pPatternObj);
  CPDF_Image* GetImage(uint32_t dwStreamObjNum);
  void ReleaseImage(uint32_t dwStreamObjNum);
  CPDF_IccProfile* GetIccProfile(CPDF_Stream* pIccProfileStream);
  void ReleaseIccProfile(const CPDF_IccProfile* pIccProfile);
  CPDF_StreamAcc* GetFontFileStreamAcc(CPDF_Stream* pFontStream);
  void ReleaseFontFileStreamAcc(const CPDF_Stream* pFontStream);
  bool IsForceClear() const { return m_bForceClear; }
  CPDF_CountedColorSpace* FindColorSpacePtr(CPDF_Object* pCSObj) const;
  CPDF_CountedPattern* FindPatternPtr(CPDF_Object* pPatternObj) const;

 private:
  using CPDF_CountedFont = CPDF_CountedObject<CPDF_Font>;
  using CPDF_CountedIccProfile = CPDF_CountedObject<CPDF_IccProfile>;
  using CPDF_CountedImage = CPDF_CountedObject<CPDF_Image>;
  using CPDF_CountedStreamAcc = CPDF_CountedObject<CPDF_StreamAcc>;

  using CPDF_ColorSpaceMap =
      std::map<const CPDF_Object*, CPDF_CountedColorSpace*>;
  using CPDF_FontFileMap = std::map<const CPDF_Stream*, CPDF_CountedStreamAcc*>;
  using CPDF_FontMap = std::map<const CPDF_Dictionary*, CPDF_CountedFont*>;
  using CPDF_IccProfileMap =
      std::map<const CPDF_Stream*, CPDF_CountedIccProfile*>;
  using CPDF_ImageMap = std::map<uint32_t, CPDF_CountedImage*>;
  using CPDF_PatternMap = std::map<const CPDF_Object*, CPDF_CountedPattern*>;

  CPDF_ColorSpace* GetColorSpaceImpl(CPDF_Object* pCSObj,
                                     const CPDF_Dictionary* pResources,
                                     std::set<CPDF_Object*>* pVisited);

  CPDF_Document* const m_pPDFDoc;
  bool m_bForceClear;
  std::map<CFX_ByteString, CPDF_Stream*> m_HashProfileMap;
  CPDF_ColorSpaceMap m_ColorSpaceMap;
  CPDF_FontFileMap m_FontFileMap;
  CPDF_FontMap m_FontMap;
  CPDF_IccProfileMap m_IccProfileMap;
  CPDF_ImageMap m_ImageMap;
  CPDF_PatternMap m_PatternMap;
};

#endif  // CORE_FPDFAPI_PAGE_CPDF_DOCPAGEDATA_H_


text:
<component name="libraryTable">
  <library name="Maven: javax.security.auth.message:javax.security.auth.message-api:1.1">
    <CLASSES>
      <root url="jar://$MAVEN_REPOSITORY$/javax/security/auth/message/javax.security.auth.message-api/1.1/javax.security.auth.message-api-1.1.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://$MAVEN_REPOSITORY$/javax/security/auth/message/javax.security.auth.message-api/1.1/javax.security.auth.message-api-1.1-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://$MAVEN_REPOSITORY$/javax/security/auth/message/javax.security.auth.message-api/1.1/javax.security.auth.message-api-1.1-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
package miyagi389.android.apps.tr.presentation.ui;

import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentManager;

import miyagi389.android.apps.tr.presentation.R;
import miyagi389.android.apps.tr.presentation.databinding.EventsEditActivityBinding;

public class EventsEditActivity extends BaseActivity implements EventsEditFragment.Listener {

    public static final String EXTRA_ID = "EXTRA_ID";

    public static final int RESULT_SAVED = RESULT_FIRST_USER + 1;

    private final EventsEditActivity self = this;

    private EventsEditActivityBinding binding;

    private EventsEditFragment eventsEditFragment;

    @NonNull
    public static Intent newIntent(
        @NonNull final Context context,
        final long id
    ) {
        final Intent intent = new Intent(context, EventsEditActivity.class);
        intent.putExtra(EXTRA_ID, id);
        return intent;
    }

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bindingContentView();
        initializeActivity();
    }

    private void bindingContentView() {
        self.binding = DataBindingUtil.setContentView(self, R.layout.events_edit_activity);

        setSupportActionBar(self.binding.toolbar);
    }

    private void initializeActivity() {
        final FragmentManager fm = getSupportFragmentManager();
        self.eventsEditFragment = (EventsEditFragment) fm.findFragmentById(R.id.content_wrapper);
        if (self.eventsEditFragment == null) {
            final long id = getIntentId();
            if (id > 0) {
                self.eventsEditFragment = EventsEditFragment.newInstance(getIntentId());
                replaceFragment(R.id.content_wrapper, self.eventsEditFragment);
            }
        }
    }

    private long getIntentId() {
        final Intent intent = getIntent();
        return intent == null ? 0L : intent.getLongExtra(EXTRA_ID, 0L);
    }

    /**
     * {@link EventsEditFragment.Listener#onSaved(EventsEditFragment)}
     */
    @Override
    public void onSaved(@NonNull final EventsEditFragment fragment) {
        setResult(RESULT_SAVED);
        finish();
    }
}


text:
<?php

namespace Orchestra\Control\Contracts\Command;

interface Synchronizer
{
    /**
     * Re-sync administrator access control.
     *
     * @return void
     */
    public function handle();
}


text:
ARG ARCH
FROM $ARCH/busybox
ARG TEST
ADD ${TEST} ${TEST}


text:
namespace std _GLIBCXX_VISIBILITY(default)
{
_GLIBCXX_BEGIN_NAMESPACE_VERSION

  // These are basically extensions to char_traits, and perhaps should
  // be put there instead of here.
  template<>
    int
    collate<char>::_M_compare(const char* __one,
			      const char* __two) const throw()
    {
      int __cmp = strcoll(__one, __two);
      return (__cmp >> (8 * sizeof (int) - 2)) | (__cmp != 0);
    }

  template<>
    size_t
    collate<char>::_M_transform(char* __to, const char* __from,
				size_t __n) const throw()
    { return strxfrm(__to, __from, __n); }

#ifdef _GLIBCXX_USE_WCHAR_T
  template<>
    int
    collate<wchar_t>::_M_compare(const wchar_t* __one,
				 const wchar_t* __two) const throw()
    {
      int __cmp = wcscoll(__one, __two);
      return (__cmp >> (8 * sizeof (int) - 2)) | (__cmp != 0);
    }

  template<>
    size_t
    collate<wchar_t>::_M_transform(wchar_t* __to, const wchar_t* __from,
				   size_t __n) const throw()
    { return wcsxfrm(__to, __from, __n); }
#endif

_GLIBCXX_END_NAMESPACE_VERSION
} // namespace


text:
package org.virtue.game.world.region.movement.routefinder;

import org.virtue.game.world.region.Tile;
import org.virtue.game.world.region.movement.path.Path;

/**
 * @author Im Frizzy <skype:kfriz1998>
 * @author Frosty Teh Snowman <skype:travis.mccorkle>
 * @author Arthur <skype:arthur.behesnilian>
 * @author Kayla <skype:ashbysmith1996>
 * @author Sundays211
 * @since 15/01/2015
 */
public class SimplePathFinder extends AbstractPathFinder {

	/**
	 * @param map
	 */
	public SimplePathFinder(TraversalMap map) {
		super(map);
	}

	/* (non-Javadoc)
	 * @see org.virtue.game.entity.region.movement.routefinder.PathFinder#find(org.virtue.game.entity.region.Tile, int, int, int, int, int, int, int, int)
	 */
	@Override
	public Path find(Tile tile, int radius, int srcX, int srcY, int destX,
			int destY, int objWidth, int objHeight, int size) {
		int deltaX = srcX - destX;
		//int deltaY = srcY - destY;
		if (deltaX > 0) {

		} else if (deltaX < 0) {

		}
		return null;
	}

	/* (non-Javadoc)
	 * @see org.virtue.game.entity.region.movement.path.Pathfinder#find(org.virtue.game.entity.region.Tile, int, org.virtue.game.entity.region.Tile, int, int, int, int, int, boolean)
	 */
	@Override
	public Path find(Tile startCoords, int size, Tile end, int sizeX,
			int sizeY, int rotation, int type, int walkingFlag, boolean near) {
		// TODO Auto-generated method stub
		return null;
	}

}


text:
layout: event
categories: eventolocale
title: "A Christmas Curl"
CL: Bologna
locandina: https://www.ai-sf.it/dbaisf/docs/eventilocaliLC/BO38/A_Christmas_Curl_2017.jpg
gallery:
articolo: "-"
report:
facebook:
link:
---


text:
egg-frenzy
==========

Base on Angularjs and jQuery,design for web app.


text:
#region License

// Distributed under the MIT License
// ============================================================
// Copyright (c) 2019 Hotcakes Commerce, LLC
// Copyright (c) 2020 Upendo Ventures, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute,
// sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using Hotcakes.Commerce.Data;
using Hotcakes.Commerce.Data.EF;
using Hotcakes.Web.Data;

namespace Hotcakes.Commerce.Orders
{
    public class OrderNoteRepository : HccSimpleRepoBase<hcc_OrderNote, OrderNote>
    {
        public OrderNoteRepository(HccRequestContext c)
            : base(c)
        {
        }

        protected override Func<hcc_OrderNote, bool> MatchItems(OrderNote item)
        {
            return on => on.Id == item.Id;
        }

        protected override Func<hcc_OrderNote, bool> NotMatchItems(List<OrderNote> items)
        {
            var itemIds = items.Select(i => i.Id).ToList();
            return on => !itemIds.Contains(on.Id);
        }

        protected override void CopyModelToData(hcc_OrderNote data, OrderNote model)
        {
            data.AuditDate = model.AuditDate;
            data.Id = model.Id;
            data.IsPublic = model.IsPublic;
            data.LastUpdatedUtc = model.LastUpdatedUtc;
            data.Note = model.Note;
            data.OrderId = DataTypeHelper.BvinToGuid(model.OrderID);
            data.StoreId = model.StoreId;
        }

        protected override void CopyDataToModel(hcc_OrderNote data, OrderNote model)
        {
            model.AuditDate = data.AuditDate;
            model.Id = data.Id;
            model.IsPublic = data.IsPublic;
            model.LastUpdatedUtc = data.LastUpdatedUtc;
            model.Note = data.Note;
            model.OrderID = DataTypeHelper.GuidToBvin(data.OrderId);
            model.StoreId = data.StoreId;
        }

        public bool Update(OrderNote item)
        {
            item.LastUpdatedUtc = DateTime.UtcNow;
            return base.Update(item, y => y.Id == item.Id);
        }

        public bool Delete(long id)
        {
            return Delete(y => y.Id == id);
        }

        public List<OrderNote> FindForOrders(List<string> orderBvins)
        {
            var orderGuids = orderBvins.Select(bvin => DataTypeHelper.BvinToGuid(bvin)).ToList();
            return FindListPoco(q =>
            {
                return q.Where(y => orderGuids.Contains(y.OrderId))
                    .OrderBy(y => y.OrderId)
                    .ThenBy(y => y.Id);
            });
        }

        public List<OrderNote> FindForOrder(string orderBvin)
        {
            var guid = DataTypeHelper.BvinToGuid(orderBvin);
            return FindListPoco(q =>
            {
                return q.Where(y => y.OrderId == guid)
                    .OrderBy(y => y.Id);
            });
        }

        public void DeleteForOrder(string orderBvin)
        {
            var orderGuid = DataTypeHelper.BvinToGuid(orderBvin);
            Delete(on => on.OrderId == orderGuid);
        }

        public void MergeList(string orderBvin, long storeId, List<OrderNote> subitems)
        {
            // Set Base Key Field
            foreach (var item in subitems)
            {
                item.OrderID = orderBvin;
                item.StoreId = storeId;
                item.LastUpdatedUtc = DateTime.UtcNow;
            }

            var orderGuid = DataTypeHelper.BvinToGuid(orderBvin);
            MergeList(subitems, on => on.OrderId == orderGuid && on.StoreId == storeId);
        }
    }
}


text:
package actions;

import play.libs.F;
import play.mvc.Action;
import play.mvc.Http;
import play.mvc.Result;

/**
 * @author Steve Chaloner (steve@objectify.be)
 */
public class UpdateContextAction extends Action<UpdateContext>
{
    @Override
    public F.Promise<Result> call(Http.Context context) throws Throwable
    {
        context.args.put("UpdateContext",
                         configuration.value());
        return delegate.call(context);
    }
}


text:
package org.jabref.logic.layout.format;

import org.jabref.logic.layout.LayoutFormatter;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class RemoveTildeTest {
    private LayoutFormatter formatter;

    @Before
    public void setUp() {
        formatter = new RemoveTilde();
    }

    @Test
    public void testFormatString() {
        Assert.assertEquals("", formatter.format(""));
        Assert.assertEquals("simple", formatter.format("simple"));
        Assert.assertEquals(" ", formatter.format("~"));
        Assert.assertEquals("   ", formatter.format("~~~"));
        Assert.assertEquals(" \\~ ", formatter.format("~\\~~"));
        Assert.assertEquals("\\\\ ", formatter.format("\\\\~"));
        Assert.assertEquals("Doe Joe and Jane, M. and Kamp, J. A.", formatter.format("Doe Joe and Jane, M. and Kamp, J.~A."));
        Assert.assertEquals("T\\~olkien, J. R. R.", formatter.format("T\\~olkien, J.~R.~R."));
    }
}


text:
import { NgModule } from '@angular/core';
import { LySkeleton } from './skeleton';

@NgModule({
  declarations: [LySkeleton],
  exports: [LySkeleton]
})
export class LySkeletonModule { }


text:
namespace reporting {
namespace test {

// An |EncryptionModuleInterface| that does no encryption.
class TestEncryptionModuleStrict : public EncryptionModuleInterface {
 public:
  TestEncryptionModuleStrict();

  MOCK_METHOD(void,
              EncryptRecordImpl,
              (base::StringPiece record,
               base::OnceCallback<void(StatusOr<EncryptedRecord>)> cb),
              (const override));

  void UpdateAsymmetricKeyImpl(
      base::StringPiece new_public_key,
      PublicKeyId new_public_key_id,
      base::OnceCallback<void(Status)> response_cb) override;

 protected:
  ~TestEncryptionModuleStrict() override;
};

// Most of the time no need to log uninterested calls to |EncryptRecord|.
typedef ::testing::NiceMock<TestEncryptionModuleStrict> TestEncryptionModule;

}  // namespace test
}  // namespace reporting

#endif  // COMPONENTS_REPORTING_ENCRYPTION_TEST_ENCRYPTION_MODULE_H_


text:
package name.monkey.slackjavaclient.model;

import com.google.api.client.util.Key;

/**
 * Created by tina on 10/30/15.
 */
public class UsersInfoResponse {
  @Key
  public boolean ok;

  @Key
  public SlackUser user;
}


text:
    <dfn>
      WWW
    </dfn>

The World-Wide Web (WWW) is a system of interlinked hypertext documents accessed on the Internet.


text:
print_usage()
{
	#local script_name

	# Get the script name
	#script_name=${0##*/}

	# Echo usage info
	echo " "
	echo " "$script_name
	echo " "
	echo " Field G. Van Zee"
	echo " "
	echo " Automatically generates makefile fragments for a specified directory"
	echo " tree. "
	echo " "
	echo " Usage:"
	echo "   ${script_name} [options] root_dir templ.mk suff_list ign_list spec_list"
	echo " "
	echo " Arguments (mandatory):"
	echo " "
	echo "   root_dir    The root directory in which makefile fragments will be"
	echo "               generated."
	echo " "
	echo "   templ.mk    The template makefile fragment used to generate the actual"
	echo "               fragments."
	echo " "
	echo "   suff_list   File containing a newline-separated list of file suffixes"
	echo "               of source files to that the top-level makefile expects to"
	echo "               access."
	echo " "
	echo "   ign_list    File containing a newline-separated list of directory names"
	echo "               to ignore when descending recursively into "
	echo " "
	echo "   spec_list   File containing a newline-separated list of directories"
	echo "               considered to be special in some way; source files found"
	echo "               in these directories will be accumulated into a different"
	echo "               makefile sub-variables based on the name of the special"
	echo "               directory names."
	echo " "
	echo " The following options are accepted:"
	echo " "
	echo "   -d          dry-run"
	echo "                 Go through all the motions, but don't actually generate any"
	echo "                 makefile fragments."
	echo "   -r          recursive"
	echo "                 Also generate makefile fragments for subdirectories of"
	echo "                 root_dir."
	echo "   -h          hide"
	echo "                 Hide the makefile fragments by prepending filenames with '.'."
	echo "   -p PREFIX   prefix name"
	echo "                 Use PREFIX instead of uppercased root_dir in the makefile"
	echo "                 variable name. If the root_dir were 'stuff' and -p was not"
	echo "                 used, then source would be accumulated into a makefile"
	echo "                 variable named 'MK_STUFF', but if -p JUNK were given, then"
	echo "                 the variable name would instead be MK_JUNK."
	echo "   -o SCRIPT   output script name"
	echo "                 Use SCRIPT when outputting messages instead of the script's"
	echo "                 actual name."
	echo "   -v [0|1|2]  verboseness level"
	echo "                 level 0: silent  (no output)"
	echo "                 level 1: default (one line per directory)"
	echo "                 level 2: verbose (several lines per directory)."
	echo " "

	# Exit with non-zero exit status
	exit 1
}

#
# gen_mkfile()
#
# Creates a single makefile fragment in a user-specified directory and adds
# any local source files found to a top-level Makefile variable.
#
gen_mkfile()
{
	# Local variable declarations
	local mkfile_frag_var_name
	local this_dir
	local mkfile_frag_tmpl_name
	local mkfile_name
	local mkfile_frag_path
	local cur_frag_dir
	local cur_frag_path
	local local_src_files
	local sub_items
	local item_path
	local item_suffix
	local cur_frag_sub_dirs

	# Extract our arguments to local variables
	mkfile_frag_var_name=$1
	this_dir=$2

	# Strip the leading path from the template makefile path to get its
	# simple filename. Hide the output makefile fragment filename, if
	# requested.
	mkfile_frag_tmpl_name=${mkfile_frag_tmpl_path##*/}
	if [ -n "$hide_flag" ]; then
		mkfile_frag_path=$this_dir/.$mkfile_frag_tmpl_name
	else
		mkfile_frag_path=$this_dir/$mkfile_frag_tmpl_name
	fi

	# Determine the directory in which the fragment will reside.
	cur_frag_path=$this_dir
	cur_frag_dir=${this_dir##*/}

	# Initialize the local source list to empty
	local_src_files=""

	# Get a listing of the items in $this_dir
	sub_items=$(ls $this_dir)

	# Generate a list of the source files we've chosen
	for item in $sub_items; do

		# Prepend the directory to the item to get a relative path
		item_path=$this_dir/$item

		# Acquire the item's suffix, if it has one
		item_suffix=${item_path##*.}

		# If the suffix matches, then add it to our list
		if is_in_list $item_suffix "$src_file_suffixes"
		then
			local_src_files="$local_src_files $item"
		fi
	done

	# Delete the leading " " space character in the local source files list.
	local_src_files=${local_src_files##" "}

	# Initialize the fragment subdirectory list to empty
	cur_frag_sub_dirs=""

	# Capture the relative path listing of items in $this_dir.
	sub_items=$(ls $this_dir)

	# Determine the fragment's subdirectory names, if any exist
	for item in $sub_items; do

		# Prepend the directory to the item to get a relative path
		item_path=$this_dir/$item

		# If item is a directory, and it's not in the ignore list, descend into it.
		#if [ -d $item_path ] && ! should_ignore $item; then
		if [ -d $item_path ] && ! is_in_list $item "$ignore_dirs" ; then
			cur_frag_sub_dirs=$cur_frag_sub_dirs" "$item
		fi
	done

	# Delete the leading " " space character in fragment's subdirectory list.
	cur_frag_sub_dirs=${cur_frag_sub_dirs##" "}

	# Be verbose, if level 2 was requested.
	if [ "$verbose_flag" = "2" ]; then
		echo "mkf frag tmpl path: $mkfile_frag_tmpl_path"
		echo "mkf frag path:      $mkfile_frag_path"
		echo "cur frag path:      $cur_frag_path"
		echo "cur frag dir:       $cur_frag_dir"
		echo "cur frag sub dirs:  $cur_frag_sub_dirs"
		echo "local src files:    $local_src_files"
		echo "src file suffixes:  $src_file_suffixes"
		echo "mkf frag var name:  $mkfile_frag_var_name"
		echo "--------------------------------------------------"
	fi

	# Copy the template makefile to the directory given, using the new
	# makefile name we just created above.
	if [ -z "$dry_run_flag" ]; then
		cat $mkfile_frag_tmpl_path | sed -e s/"$mkfile_fragment_cur_dir_name_anchor"/"$cur_frag_dir"/g \
		                           | sed -e s/"$mkfile_fragment_sub_dir_names_anchor"/"$cur_frag_sub_dirs"/g \
		                           | sed -e s/"$mkfile_fragment_local_src_files_anchor"/"$local_src_files"/g \
		                           | sed -e s/"$mkfile_fragment_src_var_name_anchor"/"$mkfile_frag_var_name"/g \
		                           > $mkfile_frag_path
	fi

	# Return peacefully.
	return 0
}

#
# gen_mkfiles
#
# Recursively generates makefile fragments for a directory and all
# subdirectories. All of the actual work happens in gen_mkfile().
#
gen_mkfiles()
{
	# Local variable declarations
	local item sub_items cur_dir this_dir

	# Extract our argument
	cur_dir=$1

	# Append a relevant suffix to the makefile variable name, if necesary
	all_add_src_var_name "$cur_dir"

	# Be verbose if level 2 was requested
	if   [ "$verbose_flag" = "2" ]; then
		echo ">>>" $script_name ${src_var_name}_$SRC $cur_dir
	elif [ "$verbose_flag" = "1" ]; then
		echo "$script_name: creating makefile fragment in $cur_dir"
	fi

	# Call our function to generate a makefile in the directory given.
	gen_mkfile "${src_var_name}_$SRC" $cur_dir

	# Get a listing of the directories in $directory
	sub_items=$(ls $cur_dir)

	# Descend into the contents of root_dir to generate the subdirectories'
	# makefile fragments.
	for item in $sub_items; do

		# If item is a directory, and it's not in the ignore list, descend into it.
		#if [ -d "$cur_dir/$item" ] && ! should_ignore $item; then
		if [ -d "$cur_dir/$item" ] && ! is_in_list $item "$ignore_dirs" ; then
			this_dir=$cur_dir/$item
			gen_mkfiles $this_dir
		fi
	done

	# Remove a relevant suffix from the makefile variable name, if necesary
	all_del_src_var_name "$cur_dir"

	# Return peacefully
	return 0
}

update_src_var_name_special()
{
	local dir act i name var_suffix

	# Extract arguments.
	act="$1"
	dir="$2"

	# Strip / from end of directory path, if there is one, and then strip
	# path from directory name.
	dir=${dir%/}
	dir=${dir##*/}

	# Run through our list.
	for specdir in "${special_dirs}"; do

		# If the current item matches sdir, then we'll have
		# to make a modification of some form.
		if [ "$dir" = "$specdir" ]; then

			# Convert the directory name to uppercase.
			var_suffix=$(echo "$dir" | tr '[:lower:]' '[:upper:]')

			# Either add or remove the suffix, and also update the
			# source file suffix variable.
			if [ "$act" == "+" ]; then
				src_var_name=${src_var_name}_$var_suffix
			else
				src_var_name=${src_var_name%_$var_suffix}
			fi

			# No need to continue iterating.
			break;
		fi
	done
}

#init_src_var_name()
#{
#	local dir="$1"
#
#	# Strip off the leading / if there is one
#	dir=${dir%%/}
#
#	# Convert the / directory separators into spaces to make a list of
#	# directories.
#	list=${dir//\// }
#
#	# Inspect each item in $list
#	for item in $list; do
#
#		# Try to initialize the source variable name
#		all_add_src_var_name $item
#	done
#}

all_add_src_var_name()
{
	local dir="$1"

	update_src_var_name_special "+" "$dir"

}

all_del_src_var_name()
{
	local dir="$1"

	update_src_var_name_special "-" "$dir"
}

read_mkfile_config()
{
	local index lname
	declare -i count

	# Read the file describing file suffixes.
	src_file_suffixes=$(cat "${suffix_file}")

	# Read the file listing the directories to ignore.
	ignore_dirs=$(cat "${ignore_file}")

	# Read the file listing the special directories.
	special_dirs=$(cat "${special_file}")

	# Change newlines into spaces. This is optional, but helps when
	# printing these values out (so they appear on one line).
	src_file_suffixes=$(echo ${src_file_suffixes} | sed "s/\n/ /g")
	ignore_dirs=$(echo ${ignore_dirs} | sed "s/\n/ /g")
	special_dirs=$(echo ${special_dirs} | sed "s/\n/ /g")

}

main()
{
	# -- BEGIN GLOBAL VARIABLE DECLARATIONS --

	# Define these makefile template "anchors" used in gen_mkfile().
	mkfile_fragment_cur_dir_name_anchor="_mkfile_fragment_cur_dir_name_"
	mkfile_fragment_sub_dir_names_anchor="_mkfile_fragment_sub_dir_names_"
	mkfile_fragment_local_src_files_anchor="_mkfile_fragment_local_src_files_"
	mkfile_fragment_src_var_name_anchor="_mkfile_fragment_src_var_name_"

	# The name of the script, stripped of any preceeding path.
	script_name=${0##*/}

	# The prefix for all makefile variables.
	src_var_name_prefix='MK'

	# The variable that always holds the string that will be passed to
	# gen_mkfile() as the source variable to insert into the fragment.mk.
	src_var_name=''

	# The suffix appended to all makefile fragment source variables.
	SRC='SRC'

	# The list of source file suffixes to add to the makefile variables.
	src_file_suffixes=''

	# The lists of directories to ignore and that are special.
	ignore_dirs=''
	special_dirs=''

	# The arguments to this function. They'll get assigned meaningful
	# values after getopts.
	mkfile_frag_tmpl_path=""
	root_dir=""
	suffix_file=""
	ignore_file=""
	special_file=""

	# Flags set by getopts.
	dry_run_flag=""
	hide_flag=""
	recursive_flag=""
	output_name=""
	prefix_flag=""
	verbose_flag=""

	# -- END GLOBAL VARIABLE DECLARATIONS --

	# Local variable declarations.
	local item sub_items this_dir

	# Process our command line options.
	while getopts ":dho:p:rv:" opt; do
		case $opt in
			d  ) dry_run_flag="1" ;;
			h  ) hide_flag="1" ;;
			r  ) recursive_flag="1" ;;
			o  ) output_name=$OPTARG ;;
			p  ) prefix_flag=$OPTARG ;;
			v  ) verbose_flag=$OPTARG ;;
			\? ) print_usage
		esac
	done
	shift $(($OPTIND - 1))

	# Make sure that verboseness level is valid.
	if [ "$verbose_flag" != "0" ] &&
	   [ "$verbose_flag" != "1" ] &&
	   [ "$verbose_flag" != "2" ]; then
		verbose_flag="1"
	fi

	# Check the number of arguments after command line option processing.
	if [ $# != "5" ]; then
		print_usage
	fi

	# If an output script name was given, overwrite script_name with it.
	if [ -n "${output_name}" ]; then
		script_name="${output_name}"
	fi

	# Extract our arguments.
	root_dir=$1
	mkfile_frag_tmpl_path=$2
	suffix_file=$3
	ignore_file=$4
	special_file=$5

	# Read the makefile config files to be used in the makefile fragment
	# generation.
	read_mkfile_config

	# Strip / from end of directory path, if there is one.
	root_dir=${root_dir%/}

	# Initialize the name of the makefile source variable.
	if [ -n "$prefix_flag" ]; then

		# If prefix_flag is not null, then we construct src_var_name using
		# it instead of root_dir. So if the prefix is 'junk', we will get
		# makefile variables that begin with 'MK_JUNK'.
		root_dir_upper=$(echo "$prefix_flag" | tr '[:lower:]' '[:upper:]')
		src_var_name="${src_var_name_prefix}_${root_dir_upper}"

	else

		# Otherwise, we use root_dir. If the root directory is 'foo' then
		# makefile variables will begin with 'MK_FOO'.
		# We are also careful to convert forward slashes into underscore so
		# root directories such as foo/bar result in makefile variables
		# that begin with 'MK_FOO_BAR'.
		root_dir_upper=$(echo "$root_dir" | tr '[:lower:]' '[:upper:]')
		root_dir_upper=$(echo "$root_dir_upper" | tr '/' '_')
		src_var_name="${src_var_name_prefix}_${root_dir_upper}"
	fi

	# Be verbose if level 2 was requested.
	if   [ "$verbose_flag" = "2" ]; then
		echo ">>>" $script_name ${src_var_name}_$SRC $root_dir
	elif [ "$verbose_flag" = "1" ]; then
		echo "$script_name: creating makefile fragment in $root_dir"
	fi

	# Call our function to generate a makefile in the root directory given.
	gen_mkfile "${src_var_name}_$SRC" $root_dir

	# If we were asked to act recursively, then continue processing
	# root_dir's contents.
	if [ -n "$recursive_flag" ]; then

		# Get a listing of the directories in $directory.
		sub_items=$(ls $root_dir)

		# Descend into the contents of root_dir to generate the makefile
		# fragments.
		for item in $sub_items; do

			# If item is a directory, and it's not in the ignore list, descend into it.
			#if [ -d "$root_dir/$item" ] && ! should_ignore $item ; then
			if [ -d "$root_dir/$item" ] && ! is_in_list $item "$ignore_dirs" ; then

				this_dir=$root_dir/$item
				gen_mkfiles $this_dir
			fi
		done
	fi

	# Exit peacefully.
	return 0
}

is_in_list()
{
	local cur_item the_item item_list

	# Extract argument.
	the_item="$1"
	item_list="$2"

	# Check each item in the list against the item of interest.
	for cur_item in ${item_list}; do

		# If the current item in the list matches the one of interest.
		if [ "${cur_item}" = "${the_item}" ]; then

			# Return success (ie: item was found).
			return 0
		fi
	done

	# If we made it this far, return failure (ie: item not found).
	return 1
}

# The script's main entry point, passing all parameters given.
main "$@"


text:
select distinct pid, cmd || ' ' || argv
from process
where cmd like :name
order by pss desc;


text:
var React = require('react');
var Input = require('./base_text_input');
var ErrorList = require('./base_error_list');

module.exports = React.createClass({
    render: function () {
        return (

                {this.props.field.label}
                <Input type="date" field={this.props.field} />

{this.props.field.help_text}

                <ErrorList errors={this.props.errors} />

        )
    }
});


text:
package internal

import (
	"fmt"
	"reflect"

	"github.com/BurntSushi/toml"
	"github.com/onsi/gomega/types"
)

func MatchTOML(expected interface{}) types.GomegaMatcher {
	return &matchTOML{
		expected: expected,
	}
}

type matchTOML struct {
	expected interface{}
}

func (matcher *matchTOML) Match(actual interface{}) (success bool, err error) {
	var e, a string

	switch eType := matcher.expected.(type) {
	case string:
		e = eType
	case []byte:
		e = string(eType)
	default:
		return false, fmt.Errorf("expected value must be []byte or string, received %T", matcher.expected)
	}

	switch aType := actual.(type) {
	case string:
		a = aType
	case []byte:
		a = string(aType)
	default:
		return false, fmt.Errorf("actual value must be []byte or string, received %T", matcher.expected)
	}

	var eValue map[string]interface{}
	_, err = toml.Decode(e, &eValue)
	if err != nil {
		return false, err
	}

	var aValue map[string]interface{}
	_, err = toml.Decode(a, &aValue)
	if err != nil {
		return false, err
	}

	return reflect.DeepEqual(eValue, aValue), nil
}

func (matcher *matchTOML) FailureMessage(actual interface{}) (message string) {
	return fmt.Sprintf("Expected\n%s\nto match the TOML representation of\n%s", actual, matcher.expected)
}

func (matcher *matchTOML) NegatedFailureMessage(actual interface{}) (message string) {
	return fmt.Sprintf("Expected\n%s\nnot to match the TOML representation of\n%s", actual, matcher.expected)
}


text:
using StankinsInterfaces;
using System;
using System.Text;
using System.Threading.Tasks;

namespace SenderAction
{
    public class SenderStringBuilder : SenderActionGenericRow
    {
        public StringBuilder StringWithData;
        public SenderStringBuilder() : base()
        {
            StringWithData = new StringBuilder();
            writeAfter = (rowNumber, s) =>
            {
                if (rowNumber < valuesToBeSent.Length - 1)
                    StringWithData.AppendLine();
            };
            writeValues = (rowNumber,s) => StringWithData.Append(s);

        }
    }
    public class SenderActionConsole : SenderActionGenericRow
    {
        public SenderActionConsole() : base()
        {
            writeAfter = (rowNumber, t) =>
            {
                if (rowNumber < valuesToBeSent.Length - 1)
                    Console.WriteLine("");
            };
            writeValues = (rowNumber,s) => Console.Write(s);
        }
    }
    public abstract class SenderActionGenericRow : SenderActionOrdered
    {

        public SenderActionGenericRow() : base()
        {

        }
        protected Action<int,string> writeValues;
        protected Action<int,IRow> writeBefore;
        protected Action<int, IRow> writeAfter;
        public void Generate()
        {
            ActionToRow = (rowNumber,r) =>
            {
                writeBefore?.Invoke(rowNumber, r);
                foreach (var item in r.Values)
                {
                    writeValues?.Invoke(rowNumber, $"{item.Key} =>{item.Value}");
                }
                writeAfter?.Invoke(rowNumber,r);

            };
        }
        public override Task Send()
        {
            if(ActionToRow== null)
                Generate();

            return base.Send();
        }

    }

}


text:
	<title>It's a goat!</title>

		<input type="checkbox" id="spin" checked>Spin
		<input type="checkbox" id="text" value="true">Show text
		— Make sure to press F11 to go full screen!

It's a goat!


text:
The OrechidIgnem package is used for adding or removing generated ores to/from the Botania Orechid Ignem Flowers.

## 导入包

You can call the OrechidIgnem package using `mods.botania.OrechidIgnem`

## 添加配方

You can either add recipes using the returned [IOreDictEntry](/Vanilla/OreDict/IOreDictEntry/) as output parameter, or the name of said oreDictEntry as string. Note, than having two recipes with same weight will crash the game.

```zenscript
//mods.botania.OrechidIgnem.addOre(IOreDictEntry oreDict, int weight);
mods.botania.OrechidIgnem.addOre(<ore:logWood>, 500);

//mods.botania.OrechidIgnem.addOre(String oreDict, int weight);
mods.botania.OrechidIgnem.addOre("logWood", 500);
```

## 删除配方

You can either remove recipes using the returned [IOreDictEntry](/Vanilla/OreDict/IOreDictEntry/) as output parameter, or the name of said oreDictEntry as string.

```zenscript
//mods.botania.OrechidIgnem.removeOre(IOreDictEntry oreDict);
mods.botania.OrechidIgnem.removeOre(<ore:oreGold>);

//mods.botania.OrechidIgnem.removeOre(String oreDict);
mods.botania.OrechidIgnem.removeOre("oreGold");
```