text:
VARERR="NO"

iam_config_rsp=${DEPLOYER}/user-config/iam/provisioning.rsp
lcm_config_rsp=${DEPLOYER}/user-config/lcm/lcm_install.rsp

getvar() {
  #eval $(grep ${1} ${iam_config_rsp}) 2>/dev/null || true
  if ! eval $(grep ${1} ${iam_config_rsp}) 2>/dev/null ; then
    echo "WARNING: could not read variable  ${1}  from provisioning.rsp"
  fi
}

. ${DEPLOYER}/user-config/iam.config

#  there are three categories of config values
#
#  1) config already in the two response files
#      lcm/lcm_install.rsp
#      iam/provisioning.rsp
#  2) default values if no config available
#      to override put config in iam.config
#  3) passwords
#      pwd are encrypted in response files and
#      need to be specified twice
#

getvar DT_SINGLEHOST
getvar IDMPROV_ACCESS_DOMAIN
getvar IDMPROV_PRODUCT_IDENTITY_DOMAIN
getvar IDMPROV_LBR_OIMADMIN_HOST
getvar IDMPROV_LBR_IDMADMIN_HOST

# TODO some var changed from PS2 to PS3
# PS2
getvar IDMPROV_LBR_OIMINTERNAL_HOST
getvar IDMPROV_LBR_SSO_HOST
# PS3
getvar IDMPROV_LBR_IDGINTERNAL_HOST
getvar IDMPROV_LBR_IAGINTERNAL_HOST
getvar IDMPROV_LBR_SSO_ACCESS_HOST
getvar IDMPROV_LBR_SSO_IDENTITY_HOST

getvar IDMPROV_IDMDOMAIN_ADMINSERVER_HOST
getvar IDMPROV_IDMDOMAIN_ADMINSERVER_PORT
getvar IDMPROV_OIMDOMAIN_ADMINSERVER_HOST
getvar IDMPROV_OIMDOMAIN_ADMINSERVER_PORT
getvar IDMPROV_OAM_HOST
getvar IDMPROV_OAM_PORT
getvar IDMPROV_OIM_HOST
getvar IDMPROV_OIM_PORT
getvar IDMPROV_SOA_HOST
getvar IDMPROV_SOA_PORT
getvar IDMPROV_OHS_HOST
getvar IDMPROV_OHS_PORT
getvar IDMPROV_OID_HOST
getvar DIR_PORT
getvar DIR_SSL_PORT
getvar IDMPROV_SECOND_OAM_HOST
getvar IDMPROV_SECOND_OAM_PORT
getvar IDMPROV_SECOND_OIM_HOST
getvar IDMPROV_SECOND_OIM_PORT
getvar IDMPROV_SECOND_SOA_HOST
getvar IDMPROV_SECOND_SOA_PORT
getvar IDMPROV_SECOND_OHS_HOST
getvar IDMPROV_SECOND_OHS_PORT
getvar IDMPROV_SECOND_OID_PORT
getvar IL_APP_BASE
getvar IL_APP_CONFIG
getvar IL_INSTALLERDIR_LOCATION
getvar INSTALL_LCMHOME_DIR
getvar INSTALL_LOCALCONFIG_DIR
getvar NODEMANAGER_NAME
getvar OHS_INSTANCENAME
getvar OIMADMIN_NAME
getvar OIM_DB_SCHEMAPREFIX
getvar OIM_DB_SERVICENAME
getvar OIM_SINGLE_DB_HOST
getvar OIM_SINGLE_DB_PORT
getvar OIM_RAC_SCAN_ADDRESS
getvar OIM_RAC_SCAN_PORT
getvar WLSADMIN_NAME

getvar DIR_REALM_DN
getvar SYSTEM_IDS_CONTAINER
getvar IDMPROV_OID_HOST
getvar DIR_PORT
getvar DIR_ADMIN_NAME
getvar DIR_SSL_PORT

:          ${iam_user_umask:="0007"}
:          ${iam_orainv_grp:="oinstall"}

:                 ${iam_pwd:="Montag11"}
:     ${iam_oim_schema_pass:=${iam_pwd}}
:     ${iam_oam_schema_pass:=${iam_pwd}}
:     ${iam_bip_schema_pass:=${iam_pwd}}
:     ${iam_oia_schema_pass:=${iam_pwd}}
:            ${iam_dba_pass:=${iam_pwd}}
:                   ${nmPwd:=${iam_pwd}}
:                 ${domaPwd:=${iam_pwd}}
:                 ${domiPwd:=${iam_pwd}}
:                  ${oudPwd:=${iam_pwd}}
:               ${oiaWlUser:="Weblogic"}
:                ${oiaWlPwd:=${iam_pwd}}
:         ${domiAdminServer:="AdminServer"}
:         ${domaAdminServer:="AdminServer"}
:         ${domlAdminServer:="AdminServer"}
:        ${IDMPROV_OIA_HOST:=${IDMPROV_OIM_HOST}}
: ${IDMPROV_SECOND_OIA_HOST:=${IDMPROV_SECOND_OIM_HOST}}
:        ${IDMPROV_OIA_PORT:="7310"}
: ${IDMPROV_SECOND_OIA_PORT:="7310"}
# shipped_jdk: ps2=jdk6, ps3=jdk
:         ${shipped_jdk_dir:="jdk"}
# iam_jdk: ps2=jdk6/current, ps3=jdk
:                 ${iam_jdk:="jdk"}
#

# --------- user must not set this
            iam_top=${IL_APP_BASE}
        iam_lcmhome=${INSTALL_LCMHOME_DIR}
       iam_services=${INSTALL_LOCALCONFIG_DIR}
        iam_hostenv=${HOME}

             nmUser=${NODEMANAGER_NAME}
           domaUser=${WLSADMIN_NAME}
           domiUser=${WLSADMIN_NAME}

: ${iam_orainv_ptr:=${iam_top}/lcm/oraInst.loc}
:     ${iam_orainv:=${iam_top}/lcm/oraInventory}

             s_base=${IL_INSTALLERDIR_LOCATION}
              s_lcm=${s_base}/installers/idmlcm
:    ${s_rcu_home:="${s_base}/installers/fmw_rcu/linux/rcuHome"}
:         ${s_wls:="${s_base}/installers/weblogic/wls_generic.jar"}
:      ${s_runjdk:="${s_base}/installers/jdk/jdk6"}
:      ${s_runjre:="${s_runjdk}/jre"}
:     ${s_patches:?"Set variable s_patches in iam.config (PS3 LCM patches)"}

:      ${dbs_dbhost:=${OIM_SINGLE_DB_HOST:-${OIM_RAC_SCAN_ADDRESS}}}
:        ${dbs_port:=${OIM_SINGLE_DB_PORT:-${OIM_RAC_SCAN_PORT}}}
: ${iam_servicename:=${OIM_DB_SERVICENAME}}
:  ${iam_oim_prefix:=${OIM_DB_SCHEMAPREFIX}}
:  ${iam_oam_prefix:=${OAM_DB_SCHEMAPREFIX}}

     iam_domain_oim=${IDMPROV_PRODUCT_IDENTITY_DOMAIN}
     iam_domain_acc=${IDMPROV_ACCESS_DOMAIN}
   iam_instance_ohs=${OHS_INSTANCENAME}

   # get oud instance name dynamically, always local dirctory
for d in ${iam_services}/instances/* ; do
  [[ "${d}" =~ "ohs" ]] && continue
  iam_instance_oud=${d}
  break
done

iam_lcm=$(grep "ORACLE_HOME=" ${lcm_config_rsp} | cut -d= -f2)

# hostname shortnames, used in workflow file
# IDMPROV variables are set at the end of provisioning.rsp
#
oim1=${IDMPROV_OIM_HOST}
oim2=${IDMPROV_SECOND_OIM_HOST}
oam1=${IDMPROV_OAM_HOST}
oam2=${IDMPROV_SECOND_OAM_HOST}
oud1=${IDMPROV_OVD_HOST}
oud2=${IDMPROV_SECOND_OVD_HOST}
web1=${IDMPROV_OHS_HOST}
web2=${IDMPROV_SECOND_OHS_HOST}
oia1=${IDMPROV_OIA_HOST}
oia2=${IDMPROV_SECOND_OIA_HOST}


text:
using Elastic.Clients.Elasticsearch.Fluent;
using Elastic.Clients.Elasticsearch.Serialization;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text.Json;
using System.Text.Json.Serialization;

#nullable restore
namespace Elastic.Clients.Elasticsearch.Analysis;
public sealed partial class NoriTokenizer : ITokenizerDefinition
{
	[JsonInclude]
	[JsonPropertyName("decompound_mode")]
	public Elastic.Clients.Elasticsearch.Analysis.NoriDecompoundMode? DecompoundMode { get; set; }

	[JsonInclude]
	[JsonPropertyName("discard_punctuation")]
	public bool? DiscardPunctuation { get; set; }

	[JsonInclude]
	[JsonPropertyName("type")]
	public string Type => "nori_tokenizer";
	[JsonInclude]
	[JsonPropertyName("user_dictionary")]
	public string? UserDictionary { get; set; }

	[JsonInclude]
	[JsonPropertyName("user_dictionary_rules")]
	public ICollection<string>? UserDictionaryRules { get; set; }

	[JsonInclude]
	[JsonPropertyName("version")]
	public string? Version { get; set; }
}

public sealed partial class NoriTokenizerDescriptor : SerializableDescriptor<NoriTokenizerDescriptor>, IBuildableDescriptor<NoriTokenizer>
{
	internal NoriTokenizerDescriptor(Action<NoriTokenizerDescriptor> configure) => configure.Invoke(this);
	public NoriTokenizerDescriptor() : base()
	{
	}

	private Elastic.Clients.Elasticsearch.Analysis.NoriDecompoundMode? DecompoundModeValue { get; set; }

	private bool? DiscardPunctuationValue { get; set; }

	private string? UserDictionaryValue { get; set; }

	private ICollection<string>? UserDictionaryRulesValue { get; set; }

	private string? VersionValue { get; set; }

	public NoriTokenizerDescriptor DecompoundMode(Elastic.Clients.Elasticsearch.Analysis.NoriDecompoundMode? decompoundMode)
	{
		DecompoundModeValue = decompoundMode;
		return Self;
	}

	public NoriTokenizerDescriptor DiscardPunctuation(bool? discardPunctuation = true)
	{
		DiscardPunctuationValue = discardPunctuation;
		return Self;
	}

	public NoriTokenizerDescriptor UserDictionary(string? userDictionary)
	{
		UserDictionaryValue = userDictionary;
		return Self;
	}

	public NoriTokenizerDescriptor UserDictionaryRules(ICollection<string>? userDictionaryRules)
	{
		UserDictionaryRulesValue = userDictionaryRules;
		return Self;
	}

	public NoriTokenizerDescriptor Version(string? version)
	{
		VersionValue = version;
		return Self;
	}

	protected override void Serialize(Utf8JsonWriter writer, JsonSerializerOptions options, IElasticsearchClientSettings settings)
	{
		writer.WriteStartObject();
		if (DecompoundModeValue is not null)
		{
			writer.WritePropertyName("decompound_mode");
			JsonSerializer.Serialize(writer, DecompoundModeValue, options);
		}

		if (DiscardPunctuationValue.HasValue)
		{
			writer.WritePropertyName("discard_punctuation");
			writer.WriteBooleanValue(DiscardPunctuationValue.Value);
		}

		writer.WritePropertyName("type");
		writer.WriteStringValue("nori_tokenizer");
		if (!string.IsNullOrEmpty(UserDictionaryValue))
		{
			writer.WritePropertyName("user_dictionary");
			writer.WriteStringValue(UserDictionaryValue);
		}

		if (UserDictionaryRulesValue is not null)
		{
			writer.WritePropertyName("user_dictionary_rules");
			JsonSerializer.Serialize(writer, UserDictionaryRulesValue, options);
		}

		if (VersionValue is not null)
		{
			writer.WritePropertyName("version");
			JsonSerializer.Serialize(writer, VersionValue, options);
		}

		writer.WriteEndObject();
	}

	NoriTokenizer IBuildableDescriptor<NoriTokenizer>.Build() => new()
	{ DecompoundMode = DecompoundModeValue, DiscardPunctuation = DiscardPunctuationValue, UserDictionary = UserDictionaryValue, UserDictionaryRules = UserDictionaryRulesValue, Version = VersionValue };
}

redpajama_set_name: RedPajamaGithub


text:
using System.Diagnostics.CodeAnalysis;

namespace Pook.SlackAPI
{
	[SuppressMessage("ReSharper", "InconsistentNaming")]
	public class IncomingWebHookMessage
	{
		public string channel { get; set; }
		public string icon_emoji { get; set; }
		public string icon_url { get; set; }
		public string text { get; set; }
		public bool unfurl_links { get; set; }
		public string username { get; set; }
	}
}


text:
<link rel="import" href="../../../bower_components/polymer/polymer.html">
<link rel="import" href="../../../bower_components/i18n-msg/i18n-msg-behavior.html">

<dom-module id="cic-header">
    <link rel="import" type="css" href="style.css">
    <template>

            @kashesandr
            [[i18n.github]]

    </template>
</dom-module>


text:
'''
Example uncore frequency sweep experiment using geopmbench.
'''

from experiment.uncore_frequency_sweep import uncore_frequency_sweep
from apps.geopmbench import geopmbench

if __name__ == '__main__':

    app_conf = geopmbench.TinyAppConf()
    uncore_frequency_sweep.main(app_conf, cool_off_time=0)


text:
import Vue from 'vue';
import { createStore } from '~/monitoring/stores/embed_group/';

// TODO: Handle copy-pasting - https://gitlab.com/gitlab-org/gitlab-foss/issues/64369.
export default function renderMetrics(elements) {
  if (!elements.length) {
    return Promise.resolve();
  }

  const wrapperList = [];

  elements.forEach(element => {
    let wrapper;
    const { previousElementSibling } = element;
    const isFirstElementInGroup = !previousElementSibling?.urls;

    if (isFirstElementInGroup) {
      wrapper = document.createElement('div');
      wrapper.urls = [element.dataset.dashboardUrl];
      element.parentNode.insertBefore(wrapper, element);
      wrapperList.push(wrapper);
    } else {
      wrapper = previousElementSibling;
      wrapper.urls.push(element.dataset.dashboardUrl);
    }

    // Clean up processed element
    element.parentNode.removeChild(element);
  });

  return import(
    /* webpackChunkName: 'gfm_metrics' */ '~/monitoring/components/embeds/embed_group.vue'
  ).then(({ default: EmbedGroup }) => {
    const EmbedGroupComponent = Vue.extend(EmbedGroup);

    wrapperList.forEach(wrapper => {
      // eslint-disable-next-line no-new
      new EmbedGroupComponent({
        el: wrapper,
        store: createStore(),
        propsData: {
          urls: wrapper.urls,
        },
      });
    });
  });
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Boletus bresadolianus J. Blum

### Remarks
null


text:
using CharacterGen.Characters;
using CharacterGen.Domain.Generators.Characters;
using CharacterGen.Randomizers.Abilities;
using CharacterGen.Randomizers.Alignments;
using CharacterGen.Randomizers.CharacterClasses;
using CharacterGen.Randomizers.Races;
using EventGen;
using Moq;
using NUnit.Framework;
using System;

namespace CharacterGen.Tests.Unit.Generators.Characters
{
    [TestFixture]
    public class CharacterGeneratorEventGenDecoratorTests
    {
        private ICharacterGenerator decorator;
        private Mock<ICharacterGenerator> mockInnerGenerator;
        private Mock<GenEventQueue> mockEventQueue;
        private Mock<IAlignmentRandomizer> mockAlignmentRandomizer;
        private Mock<IClassNameRandomizer> mockClassNameRandomizer;
        private Mock<ILevelRandomizer> mockLevelRandomizer;
        private Mock<RaceRandomizer> mockBaseRaceRandomizer;
        private Mock<RaceRandomizer> mockMetaraceRandomizer;
        private Mock<IAbilitiesRandomizer> mockAbilitiesRandomizer;

        [SetUp]
        public void Setup()
        {
            mockInnerGenerator = new Mock<ICharacterGenerator>();
            mockEventQueue = new Mock<GenEventQueue>();
            decorator = new CharacterGeneratorEventGenDecorator(mockInnerGenerator.Object, mockEventQueue.Object);

            mockAlignmentRandomizer = new Mock<IAlignmentRandomizer>();
            mockClassNameRandomizer = new Mock<IClassNameRandomizer>();
            mockLevelRandomizer = new Mock<ILevelRandomizer>();
            mockAbilitiesRandomizer = new Mock<IAbilitiesRandomizer>();
            mockBaseRaceRandomizer = new Mock<RaceRandomizer>();
            mockMetaraceRandomizer = new Mock<RaceRandomizer>();
        }

        [Test]
        public void ReturnInnerCharacter()
        {
            var character = new Character();
            mockInnerGenerator.Setup(g => g.GenerateWith(mockAlignmentRandomizer.Object, mockClassNameRandomizer.Object, mockLevelRandomizer.Object, mockBaseRaceRandomizer.Object, mockMetaraceRandomizer.Object, mockAbilitiesRandomizer.Object))
                .Returns(character);

            var generatedCharacter = decorator.GenerateWith(mockAlignmentRandomizer.Object, mockClassNameRandomizer.Object, mockLevelRandomizer.Object, mockBaseRaceRandomizer.Object, mockMetaraceRandomizer.Object, mockAbilitiesRandomizer.Object);
            Assert.That(generatedCharacter, Is.EqualTo(character));
        }

        [Test]
        public void LogEventsForCharacterGeneration()
        {
            var character = new Character();
            character.Alignment.Goodness = Guid.NewGuid().ToString();
            character.Alignment.Lawfulness = Guid.NewGuid().ToString();
            character.Class.Name = Guid.NewGuid().ToString();
            character.Class.Level = 9266;
            character.Race.BaseRace = Guid.NewGuid().ToString();
            character.Race.Metarace = Guid.NewGuid().ToString();

            mockInnerGenerator.Setup(g => g.GenerateWith(mockAlignmentRandomizer.Object, mockClassNameRandomizer.Object, mockLevelRandomizer.Object, mockBaseRaceRandomizer.Object, mockMetaraceRandomizer.Object, mockAbilitiesRandomizer.Object))
                .Returns(character);

            var generatedCharacter = decorator.GenerateWith(mockAlignmentRandomizer.Object, mockClassNameRandomizer.Object, mockLevelRandomizer.Object, mockBaseRaceRandomizer.Object, mockMetaraceRandomizer.Object, mockAbilitiesRandomizer.Object);
            Assert.That(generatedCharacter, Is.EqualTo(character));
            mockEventQueue.Verify(q => q.Enqueue(It.IsAny<string>(), It.IsAny<string>()), Times.Exactly(2));
            mockEventQueue.Verify(q => q.Enqueue("CharacterGen", "Generating character"), Times.Once);
            mockEventQueue.Verify(q => q.Enqueue("CharacterGen", $"Generated {character.Summary}"), Times.Once);
        }
    }
}


text:
/* simpleJsCopy.js v0.2.0 by @ryanpcmcquen */

// Ryan P.C. McQuen | Everett, WA | ryan.q@linux.com
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version, with the following exception:
// the text of the GPL license may be omitted.
//
// This program is distributed in the hope that it will be useful, but
// without any warranty; without even the implied warranty of
// merchantability or fitness for a particular purpose. Compiling,
// interpreting, executing or merely reading the text of the program
// may result in lapses of consciousness and/or very being, up to and
// including the end of all existence and the Universe as we know it.
// See the GNU General Public License for more details.
//
// You may have received a copy of the GNU General Public License along
// with this program (most likely, a file named COPYING).  If not, see
// <https://www.gnu.org/licenses/>.

/*global window*/
/*jslint browser:true, white:true*/

(function() {
  'use strict';
  // a stupidly simple copy button
  // - copies on awesome browsers/devices
  // - selects text on underwhelming mobile devices
  // - the button instructs the user if necessary
  window.addEventListener('load', function() {
    var copyBtn = document.querySelector('.js-copy-btn');
    var iPhoneORiPod = false,
      iPad = false,
      safari = false;
    if (navigator.userAgent.match(/iPhone|iPod/i)) {
      iPhoneORiPod = true;
    } else if (navigator.userAgent.match(/iPad/i)) {
      iPad = true;
    } else if (/^((?!chrome).)*safari/i.test(navigator.userAgent)) {
      safari = true;
    }
    if (iPhoneORiPod || iPad || safari) {
      copyBtn.textContent = "Select text";
    }
    copyBtn.addEventListener('click', function() {
      // select the text
      var copyItem = document.querySelector('.text-to-copy');
      copyItem.select();
      try {
        // now that we've selected the text, execute the copy command
        document.execCommand('copy');
        if (iPhoneORiPod) {
          copyBtn.textContent = "Now tap 'Copy'";
        } else if (iPad) {
          // the iPad doesn't have the 'Copy' box pop up,
          // you have to tap the text first
          copyBtn.textContent = "Now tap the text, then 'Copy'";
        } else if (safari) {
          // fancy safari detection thanks to: http://stackoverflow.com/a/23522755
          copyBtn.textContent = "Press Command + C to copy";
        } else {
          copyBtn.textContent = "Copied!";
        }
      } catch (ignore) {
        copyBtn.textContent = "Please copy manually";
      }
      // this is what selects it on iOS
      copyItem.focus();
      if (iPhoneORiPod || iPad) {
        copyItem.selectionStart = 0;
        copyItem.selectionEnd = copyItem.textContent.length;
      } else {
        copyItem.select();
      }

      // disable the button because clicking it again could cause madness
      copyBtn.disabled = true;
    });
  });
}());


text:
from cloudify import ctx

from cloudify_agent.installer import exceptions

def raise_missing_attribute(attribute_name):
    raise exceptions.AgentInstallerConfigurationError(
        '{0} must be set in one of the following:\n{1}'
        .format(attribute_name, _create_configuration_options())
    )

def raise_missing_attributes(*attributes):
    raise exceptions.AgentInstallerConfigurationError(
        '{0} must be set in one of the following:\n{1}'
        .format(' or '.join(attributes), _create_configuration_options())
    )

def _create_configuration_options():
    inputs_path = '{0}.interfaces.[{1}].inputs.' \
                  'agent_config' \
        .format(ctx.node.name, ctx.task_name)
    properties_path = '{0}.properties.agent_config'.format(
        ctx.node.name
    )
    runtime_properties_path = \
        '{0}.runtime_properties.cloudify_agent' \
        .format(ctx.instance.id)
    context_path = 'bootstrap_context.cloudify_agent'
    return '1. {0} \n' \
           '2. {1} \n' \
           '3. {2} \n' \
           '4. {3}'.format(inputs_path, runtime_properties_path,
                           properties_path, context_path)


text:
require 'scrivener'

module Mlk

  class Model
    include Scrivener::Validations
    extend SingleForwardable

    def_delegators :all, :[], :first, :find, :find_match

    class << self
      attr_accessor :storage_engine
    end

    def self.defined_models
      @all_models ||= [ ]
    end

    def self.inherited(subclass)
      defined_models << subclass
    end

    def self.all
      results = storage.all.map do |path, raw_document|
        document = Document.new(raw_document)
        self.new(document, { :path => path })
      end

      ResultSet.new(results)
    end

    def self.add_attribute(attr)
      @attrs ||= [ ]

      @attrs << attr
    end

    # Manage relations between models

    def self.attribute(name, block = -> {})
      define_method(name) do
        data.fetch(name.to_s) do
          block.arity == 1 ? block.call(self) : block.call
        end
      end

      add_attribute(name)
    end

    def self.attributes
      if superclass.respond_to?(:attributes)
        superclass.attributes + @attrs
      else
        @attrs
      end
    end

    def self.has_attribute?(attribute)
      attributes.include?(attribute)
    end

    def self.belongs_to(model, name)
      define_method(name) do
        name = name.to_s
        model_class = Utils.class_lookup(self.class, model)
        model_class.first(:name => self.data[name])
      end
    end

    def self.has_many(model, name, reference = to_reference)
      define_method(name) do
        model_class = Utils.class_lookup(self.class, model)
        if reference.to_s.end_with?("s")
          model_class.find_match(:"#{ reference }" => self.name)
        else
          model_class.find(:"#{ reference }" => self.name)
        end
      end
    end

    def self.storage
      ref = Utils.pluralize(to_reference)
      Model.storage_engine.new(ref)
    end

    def self.to_reference
      self.name.downcase
    end

    attr_reader :document

    attribute :name

    def initialize(document, options = { })
      @path = options[:path]
      @document = document
    end

    def content
      document.content
    end

    def data
      document.data
    end

    def attributes
      self.class.attributes
    end

    def validate
      assert_present(:name)
    end

    def template
      data.fetch('template') { default_template }.to_sym
    end

    def default_template
      self.class.name.split('::').last.
        gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
        gsub(/([a-z\d])([A-Z])/,'\1_\2').
        tr("-", "_").downcase
    end

    def ==(other_model)
      self.document == other_model.document
    end

    def save
      self.class.storage.save(self.name, @document.serialize)
    end
  end

end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.berico</groupId>
  <artifactId>tweet-exp</artifactId>
  <name>tweet-exp</name>
  <version>0.1.0-RELEASE</version>
  <url>http://maven.apache.org</url>
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-shade-plugin</artifactId>
        <version>2.1</version>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
            <configuration>
              <transformers>
                <transformer>
                  <Main-Class>com.berico.tweet.App</Main-Class>
                </transformer>
              </transformers>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
  <repositories>
    <repository>
      <releases />
      <snapshots />
      <id>nexus.bericotechnologies.com</id>
      <name>Berico Technologies Nexus</name>
      <url>http://nexus.bericotechnologies.com/content/groups/public</url>
    </repository>
    <repository>
      <releases />
      <snapshots />
      <id>opennlp</id>
      <name>OpenNLP</name>
      <url>http://opennlp.sourceforge.net/maven2/</url>
    </repository>
  </repositories>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
</project>


text:
<?php

namespace Amadeus\Client\Struct\Fop;

/**
 * Routing
 *
 * @package Amadeus\Client\Struct\Fop
 * @author Dieter Devlieghere <dermikagh@gmail.com>
 */
class Routing
{
    /**
     * @var RoutingDetails
     */
    public $routingDetails;

    /**
     * Routing constructor.
     *
     * @param string $otherStation
     */
    public function __construct($otherStation)
    {
        $this->routingDetails = new RoutingDetails($otherStation);
    }
}


text:
#include <stdio.h>
#include <malloc.h>
#include <winpr/crt.h>
#include <winpr/windows.h>
#include <winpr/interlocked.h>

typedef struct _PROGRAM_ITEM
{
	SLIST_ENTRY ItemEntry;
	ULONG Signature;
} PROGRAM_ITEM, *PPROGRAM_ITEM;

int TestInterlockedSList(int argc, char* argv[])
{
	ULONG Count;
	PSLIST_ENTRY pFirstEntry;
	PSLIST_ENTRY pListEntry;
	PSLIST_HEADER pListHead;
	PPROGRAM_ITEM pProgramItem;

	/* Initialize the list header to a MEMORY_ALLOCATION_ALIGNMENT boundary. */
	pListHead = (PSLIST_HEADER) _aligned_malloc(sizeof(SLIST_HEADER), MEMORY_ALLOCATION_ALIGNMENT);

	if (!pListHead)
	{
		printf("Memory allocation failed.\n");
		return -1;
	}

	InitializeSListHead(pListHead);

	/* Insert 10 items into the list. */
	for (Count = 1; Count <= 10; Count += 1)
	{
		pProgramItem = (PPROGRAM_ITEM) _aligned_malloc(sizeof(PROGRAM_ITEM), MEMORY_ALLOCATION_ALIGNMENT);

		if (!pProgramItem)
		{
			printf("Memory allocation failed.\n");
			return -1;
		}

		pProgramItem->Signature = Count;
		pFirstEntry = InterlockedPushEntrySList(pListHead, &(pProgramItem->ItemEntry));
	}

	/* Remove 10 items from the list and display the signature. */
	for (Count = 10; Count >= 1; Count -= 1)
	{
		pListEntry = InterlockedPopEntrySList(pListHead);

		if (!pListEntry)
		{
			printf("List is empty.\n");
			return -1;
		}

		pProgramItem = (PPROGRAM_ITEM) pListEntry;
		printf("Signature is %d\n", (int) pProgramItem->Signature);

		/*
		 * This example assumes that the SLIST_ENTRY structure is the
		 * first member of the structure. If your structure does not
		 * follow this convention, you must compute the starting address
		 * of the structure before calling the free function.
		 */

		_aligned_free(pListEntry);
	}

	/* Flush the list and verify that the items are gone. */
	pListEntry = InterlockedFlushSList(pListHead);
	pFirstEntry = InterlockedPopEntrySList(pListHead);

	if (pFirstEntry)
	{
		printf("Error: List is not empty.\n");
		return -1;
	}

	_aligned_free(pListHead);

	return 0;
}


text:
echo "Running Couchbase docker image..."
docker run -d --name couchbase -p 8091-8094:8091-8094 -p 11210:11210 couchbase/server:5.1.3

docker ps | grep "couchbase"
retVal=$?
if [ $retVal == 0 ]; then
    echo "Couchbase docker image is running."
else
    echo "Couchbase docker image failed to start."
    exit $retVal
fi

echo "Waiting for Couchbase server to come online..."
sleep 10
until $(curl --output /dev/null --silent --head --fail http://localhost:8091); do
    printf '.'
    sleep 1
done

echo -e "\n*************************************************************"
echo -e "Setting default memory quota for the pool"
echo -e "*************************************************************"
curl http://localhost:8091/pools/default -d memoryQuota=512

echo -e "\n*************************************************************"
echo -e "Initialize node..."
echo -e "*************************************************************"
curl http://localhost:8091/nodes/self/controller/settings -d path=/opt/couchbase/var/lib/couchbase/data -d \
index_path=/opt/couchbase/var/lib/couchbase/data

echo -e "*************************************************************"
echo -e "Rename node..."
echo -e "*************************************************************"
curl  http://localhost:8091/node/controller/rename -d hostname=127.0.0.1

echo -e "\n*************************************************************"
echo -e "Setting cluster services..."
echo -e "*************************************************************"
curl http://localhost:8091/node/controller/setupServices -d 'services=kv%2Cn1ql%2Cindex'

echo -e "\n*************************************************************"
echo -e "Setup Administrator username and password..."
echo -e "*************************************************************"
curl http://localhost:8091/settings/web -d password=password -d username=admin -d port=8091

echo -e "\n*************************************************************"
echo -e "Creating Couchbase buckets..."
echo -e "*************************************************************"

curl -u 'admin:password'  -d 'name=testbucket' -d 'bucketType=couchbase' -d 'ramQuotaMB=120' -d 'authType=sasl' -d \
'saslPassword=password' -d 'proxyPort=11216' http://localhost:8091/pools/default/buckets

curl -u 'admin:password' -X PUT --data "roles=bucket_admin[testbucket]&password=password" \
             -H "Content-Type: application/x-www-form-urlencoded" \
             http://localhost:8091/settings/rbac/users/local/testbucket

curl -u 'admin:password' -d name=casbucket -d bucketType=couchbase -d 'ramQuotaMB=120' -d authType='none' -d \
'proxyPort=11217' http://localhost:8091/pools/default/buckets

echo -e "\n*************************************************************"
echo -e "Loading Couchbase buckets..."
echo -e "*************************************************************"
curl -u 'admin:password' http://localhost:8091/pools/default/buckets

echo -e "\n*************************************************************"
echo -e "Creating index settings..."
echo -e "*************************************************************"
curl  -u 'admin:password' 'http://localhost:8091/settings/indexes' -d 'indexerThreads=0' -d 'logLevel=info' -d \
'maxRollbackPoints=5' -d 'memorySnapshotInterval=200' -d 'stableSnapshotInterval=5000' -d 'storageMode=memory_optimized'
sleep 1
echo -e "\n*************************************************************"
echo -e "Creating index..."
echo -e "*************************************************************"
curl -u 'admin:password'  http://localhost:8093/query/service -d 'statement=CREATE INDEX accounts_idx ON testbucket(username)' \
-d 'namespace=default'
sleep 1
echo -e "\n*************************************************************"
echo -e "Creating primary index..."
echo -e "*************************************************************"
curl -u 'admin:password'  http://localhost:8093/query/service -d \
'statement=CREATE PRIMARY INDEX `primary-idx` ON `testbucket` USING GSI;' \
-d 'namespace=default'
sleep 1

echo -e "\n*************************************************************"
echo -e "Creating document/accounts..."
echo -e "*************************************************************"
curl -u 'admin:password'  http://localhost:8093/query/service \
-d 'statement=INSERT INTO `testbucket` (KEY,VALUE) VALUES("accounts", {"username": "casuser", "psw": "Mellon", "firstname": "CAS", "lastname":"User"})'


text:
package com.example.pocketknife;

public class GrandchildActivity extends ChildActivity {
}


text:
@implementation ScanVC

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.automaticallyAdjustsScrollViewInsets = NO;

    // Navigation Bar
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0 green:0.48f blue:1 alpha:1];
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName : [UIColor whiteColor], NSFontAttributeName : [UIFont fontWithName:@"Helvetica-Bold" size:20]};

    UIBarButtonItem *filterButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"filter.png"] style:UIBarButtonItemStylePlain target:self action:@selector(filterBeacons)];
    filterButton.tintColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = filterButton;

    UIBarButtonItem *settingsButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"settings.png"] style:UIBarButtonItemStylePlain target:self action:@selector(openSettings)];
    [settingsButton setTitleTextAttributes:@{NSFontAttributeName : [UIFont fontWithName:@"Helvetica" size: 18]} forState:UIControlStateNormal];
    settingsButton.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = settingsButton;

    // FilterVC
    _filter = [[FilterVC alloc]init];
    [_filter setFilterDelegate:self];
    _filter.modalTransitionStyle = UIModalTransitionStyleCoverVertical;

    // Detect view
    _detectedView = [[DetectedFlyers alloc] initWithFrame:CGRectMake(0, 65, self.view.frame.size.width, self.view.frame.size.height-114)];
    [_detectedView setDetectedDelegate:self];
    [self.view addSubview:_detectedView];

    _pageControl = [[FXPageControl alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 20)];
    _pageControl.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height-57);
    _pageControl.defersCurrentPageDisplay = YES;
    _pageControl.selectedDotColor = [UIColor colorWithRed:0 green:0.48f blue:1 alpha:1];
    _pageControl.selectedDotShape = FXPageControlDotShapeCircle;
    _pageControl.selectedDotSize = 9.0f;
    _pageControl.dotColor = [UIColor lightGrayColor];
    _pageControl.dotSpacing = 8.0f;
    [self.view addSubview:_pageControl];

    // Searching loader

}

// Ranging actions
- (void) viewWillAppear:(BOOL)animated
{
    [_detectedView reloadFavButtons];
    [_detectedView startRanging];
}

- (void) viewDidDisappear:(BOOL)animated
{
    [_detectedView stopRanging];
}

// Open filter list
- (void) filterBeacons;
{
    [self presentViewController:_filter animated:YES completion:nil];
}

- (void) filterDidDismissWithArray:(NSArray *)array
{
    _detectedView.filterCategories = array;
    [_detectedView rearrangeFlyers];
}

// Open settings view
- (void) openSettings
{
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:[SettingVC sharedView]];
    [self presentViewController:navigationController animated:YES completion:nil];

}

// Adjust view when flyer expanded
- (void) scrollHadBeaconExpanded:(BOOL)fullscreen
{
    if (fullscreen)
    {
        // Make scrollview bigger to show fullscreen content
        [self.navigationController setNavigationBarHidden:YES animated:NO];
        _detectedView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-50);

        // Hide status bar
        [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];

        // Hide page controll
        _pageControl.hidden = YES;

        // Stop ranging beacons
        [_detectedView stopRanging];
    }
    else
    {
        // Turn to normal size
        [self.navigationController setNavigationBarHidden:NO animated:NO];
        _detectedView.frame = CGRectMake(0, 65, self.view.frame.size.width, self.view.frame.size.height-114);

        // Show status bar
        [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];

        // Hide page controll
        _pageControl.hidden = NO;

        // Start ranging beacons
        [_detectedView startRanging];
    }
}

// Page controll delegate
- (void) modifyPageControllNumber: (NSInteger) pages
{
    _pageControl.numberOfPages = pages;
}
- (void) selectedPage: (NSInteger) index
{
    _pageControl.currentPage = index;
}

- (BOOL)shouldAutorotate
{
    return NO;
}

- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateQuestionsTable extends Migration
{
    /**
     * Run the Create Questions Table migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('questions', function (Blueprint $table)
	{
		$table->increments('id');//Create a primary, auto-incrementing 'id' column.
		$table->timestamps();//Create standard Laravel 'created_at' and 'updated_at' columns.
		$table->string('text');//Text of the question to be shown to the user.
	});
    }

    /**
     * Reverse the Create Questions Table migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('questions');
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>com.github.kucera-jan-cz.esBench</groupId>
		<artifactId>esBench-pom</artifactId>
		<version>0.0.4-SNAPSHOT</version>
	</parent>
	<artifactId>elastic-module</artifactId>
	<description>ElasticSearch tool for generating JSON documents and collecting workload</description>
	<dependencies>
		<dependency>
			<groupId>com.github.kucera-jan-cz.esBench</groupId>
			<artifactId>core</artifactId>
			<version>${project.version}</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
		</dependency>
		<dependency>
			<groupId>org.elasticsearch</groupId>
			<artifactId>elasticsearch</artifactId>
		</dependency>

		<dependency>
			<groupId>io.dropwizard.metrics</groupId>
			<artifactId>metrics-core</artifactId>
		</dependency>

		<dependency>
			<groupId>com.hazelcast</groupId>
			<artifactId>hazelcast-client</artifactId>
		</dependency>

		<!-- Hazelcast internally uses Log4j -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>log4j-over-slf4j</artifactId>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jul-to-slf4j</artifactId>
		</dependency>

		<!-- TESTING -->
		<dependency>
			<groupId>org.testng</groupId>
			<artifactId>testng</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.unitils</groupId>
			<artifactId>unitils-core</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.mockito</groupId>
			<artifactId>mockito-core</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>net.java.dev.jna</groupId>
			<artifactId>jna</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>net.javacrumbs.json-unit</groupId>
			<artifactId>json-unit</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>com.github.kucera-jan-cz.esBench</groupId>
			<artifactId>core-test</artifactId>
			<version>${project.version}</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
</project>


text:
package org.mbari.vars.ui.commands;

import org.mbari.vars.core.EventBus;
import org.mbari.vars.core.util.Preconditions;
import org.mbari.vars.ui.UIToolBox;
import org.mbari.vars.ui.messages.ShowFatalErrorAlert;
import org.mbari.vars.ui.messages.ShowNonfatalErrorAlert;
import org.mbari.vars.services.model.Annotation;
import org.mbari.vars.services.model.Image;
import org.mbari.vars.services.model.ImageReference;
import org.mbari.vars.services.AnnotationService;
import org.mbari.vars.ui.javafx.AnnotationServiceDecorator;
import org.mbari.vars.core.util.AsyncUtils;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author Brian Schlining
 * @since 2018-08-10T10:38:00
 */
public class DetachFramegrabCmd implements Command {

    private final Collection<Annotation> originalAnnotations;
    private Collection<Image> originalImages = new CopyOnWriteArrayList<>();

    public DetachFramegrabCmd(Collection<Annotation> originalAnnotations) {
        Preconditions.checkNotNull(originalAnnotations,
                "Can not execute command on empty collection");
        this.originalAnnotations = Collections.unmodifiableCollection(originalAnnotations);
    }

    /**
     * Looks up all the images that need to be deleted from the annotations.
     * The results are cached so that we don't need to look them up again through
     * subseguent apply/unapply cycles.
     * @param toolBox
     * @return The images to delete
     */
    private CompletableFuture<Collection<Image>> findImagesToDelete(UIToolBox toolBox) {

        AnnotationService annotationService = toolBox.getServices().getAnnotationService();

        // Can't delete until we cache the images we're deleting. Store them in this future
        CompletableFuture<Collection<Image>> f = new CompletableFuture<>();

        if (!originalAnnotations.isEmpty() && originalImages.isEmpty()) {

            // Extract all distinct image_reference_uuid from annotations
            List<UUID> imageReferenceUuids = originalAnnotations.stream()
                    .flatMap(anno -> anno.getImages().stream())
                    .map(ImageReference::getUuid)
                    .distinct()
                    .collect(Collectors.toList());

            // Get the original images from the database. We'll need them for undo
            CompletableFuture<Collection<Image>> findImagesFuture =
                    AsyncUtils.collectAll(imageReferenceUuids, annotationService::findImageByUuid);
            findImagesFuture.whenComplete((images, exception) -> {
                if (exception == null) {
                    originalImages.addAll(images);
                    f.complete(originalImages);  // COMPLETED FUTURE!
                }
                else {
                    showAlert(exception, toolBox);
                }
            });

        }
        else {
            f.complete(originalImages);         // COMPLETED FUTURE!
        }
        return f;
    }

    private void showAlert(Throwable t, UIToolBox toolBox) {
        EventBus eventBus = toolBox.getEventBus();
        ResourceBundle i18n = toolBox.getI18nBundle();
        String title = i18n.getString("commands.detachimage.title");
        String header = i18n.getString("commands.detachimage.header");
        if (t instanceof Exception) {
            String content = i18n.getString("commands.detachimage.exception.content");
            eventBus.send(new ShowNonfatalErrorAlert(title, header, content, (Exception) t));
        }
        else {
            String content = i18n.getString("commands.detachimage.error.content");
            eventBus.send(new ShowFatalErrorAlert(title, header, content, new RuntimeException(t)));
        }
    }

    @Override
    public void apply(UIToolBox toolBox) {
        AnnotationService annotationService = toolBox.getServices().getAnnotationService();
        AnnotationServiceDecorator decorator = new AnnotationServiceDecorator(toolBox);

        Function<Image, CompletableFuture> deleteImageFn = image ->
                annotationService.deleteImage(image.getImageReferenceUuid());

        findImagesToDelete(toolBox)
                .thenCompose(images -> decorator.findAnnotationsForImages(images)
                        .thenCompose(annotations -> AsyncUtils.completeAll(images, deleteImageFn).thenApply(v -> annotations))
                        .thenAccept(annotations -> {
                            Set<UUID> observationUuids = annotations.stream()
                                    .map(Annotation::getObservationUuid)
                                    .collect(Collectors.toSet());
                            decorator.refreshAnnotationsView(observationUuids);
                        })
                );

    }

    @Override
    public void unapply(UIToolBox toolBox) {
        AnnotationService annotationService = toolBox.getServices().getAnnotationService();
        AnnotationServiceDecorator decorator = new AnnotationServiceDecorator(toolBox);

        // Create an iamge and
        Function<Image, CompletableFuture<List<Annotation>>> createImageAndFindAnnotationFn =
                image -> annotationService.createImage(image)
                        .thenCompose(image1 -> annotationService.findByImageReference(image1.getImageReferenceUuid()));

        AsyncUtils.collectAll(originalImages, createImageAndFindAnnotationFn)
                .whenComplete((annotationLists, exception) -> {
                    List<Annotation> annotations = annotationLists.stream()
                            .flatMap(List::stream)
                            .collect(Collectors.toList());
                    if (exception == null) {
                        Set<UUID> observationUuids = annotations.stream()
                                .map(Annotation::getObservationUuid)
                                .collect(Collectors.toSet());
                        decorator.refreshAnnotationsView(observationUuids);
                    }
                    else {
                        showAlert(exception, toolBox);
                    }
                });
    }

    @Override
    public String getDescription() {
        int size = originalAnnotations == null ? 0 : originalAnnotations.size();
        return "Detach images from " + size + " annotations";
    }
}


text:
@interface ImageCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UIImageView *previewImage;

@end


text:
package ai.agnos.sparql.api

import akka.http.scaladsl.model.{HttpMethod, HttpMethods}
import org.eclipse.rdf4j.model.{BNode, IRI, Literal, Value}

object SparqlConstruct extends SparqlConstructFactory {

  def apply(resourceIRIs: Seq[IRI] = Nil,
            propertyIRIs: Seq[IRI] = Nil,
            valueIRIs: Seq[IRI] = Nil,
            graphIRIs: Seq[IRI] = Nil,
            reasoningEnabled: Boolean = false)(
           // JC why make _paging implicit?
    implicit _paging: PagingParams = NoPaging
  ): SparqlConstruct = {

    new SparqlConstruct()(PrefixMapping.standard) {

      private val whereClause = {
        s"""
           |WHERE {
           |  ${values("graphIri", graphIRIs)}
           |  GRAPH ?graphIri {
           |    ${values("resourceIri", resourceIRIs)}
           |    ${values("propertyIri", propertyIRIs)}
           |    ${values("value", valueIRIs)}
           |    ?resourceIri ?propertyIri ?value .
           |  }
           |}
         """.stripMargin
      }

//      private val graphConstruct = {
//        s"""
//           |CONSTRUCT {
//           |  GRAPH ?graphIri {
//           |    ?resourceIri ?propertyIri ?value .
//           |  }
//           |}
//           |$whereClause
//           |${pagingParams(_paging)}
//        """.stripMargin.trim
//      }

      // this won't work when n-quads or n-triples are required to be returned via HTTP from the triple store.
//      private val graphConstructViaSelect = {
//        s"""
//           |SELECT ?resourceIri ?propertyIri ?value ?graphIri
//           |$whereClause
//           |${pagingParams(_paging)}
//        """.stripMargin.trim
//
//      }

      override val statement: String = build(graphConstructReified(whereClause, _paging))

      override val reasoning: Boolean = reasoningEnabled
    }
  }

}

trait SparqlConstructFactory {

  def unapply(construct: SparqlConstruct): Option[(HttpMethod, String, Boolean)] = {
    Some((construct.httpMethod, construct.statement, construct.reasoning))
  }
}

abstract class SparqlConstruct()(
  implicit pm: PrefixMapping) extends SparqlStatement()(pm) {

  override val httpMethod = HttpMethods.POST

  def reasoning = false

  protected def graphConstructReified (
                                        whereClause: String,
                                        _paging: PagingParams
                                      ): String = {

    val pagingParams: String = {
      s"""
         |${_paging.offset.map(o => s"OFFSET $o").getOrElse("")}
         |${_paging.limit.map(o => s"LIMIT $o").getOrElse("")}
         """.stripMargin
    }

    s"""
       |CONSTRUCT {
       |  _:g rdf:subject ?resourceIri ;
       |      rdf:predicate ?propertyIri ;
       |      rdf:object ?value ;
       |      rdf:graph ?graphIri .
       |}
       |$whereClause
       |$pagingParams
        """.stripMargin.trim
  }

  protected def values(binding: String, iris: Seq[IRI])(implicit pm: PrefixMapping): String = {
    def mkIRIs(iris: Seq[IRI]): String = {
      iris.map(iri => strInSparql(iri)).mkString(" ")
    }
    iris match {
      case Nil => ""
      case _ => s"VALUES ?$binding { ${mkIRIs(iris)} }"
    }
  }

  protected def strInSparql(value: Value)(implicit pm: PrefixMapping): String = {
    value match {
      case _: IRI =>
        val s = value.stringValue()
        if (pm.isPrefixed(s)) s else s"<$s>"
      case literal: Literal =>
        val tpe = literal.getDatatype
        s"'${literal.stringValue()}'^^${pm.getNsURIPrefix(tpe.getNamespace)}:${tpe.getLocalName}"
      case bn: BNode => throw new IllegalArgumentException("Should not use Blank Node as query parameter")
    }
  }
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Sample extends Base_Controller {

    function __construct(){
        parent::__construct(array(
            'table'=>'samples',
            'view_dir'=>'sample'
        ));
    }
    function get($id)
    {
        $data['sample'] = $this->{$this->model}->_get($id);
    }
    function gets()
    {
        // $data['samples'] = $this->{$this->model}->_gets_with_pgi(null,'style_1');
        $data['samples'] = $this->{$this->model}->_gets();
        $this->_template("gets",$data);
    }

    function add()
    {
        $this->_set_rules();
        if($this->fv->run() === false)
        {
            $data['sample']  = (object)array();
            $data['mode'] = "add";
            $this->_template("admin_addUpdate",$data);
            return;
        }
        else
        {
            parent::_dbSet_addUpdate();
            // $this->_dbSet_addUpdate();
            $insert_id =$this->{$this->model}->_add();
            my_redirect(sample_uri."/update/$insert_id");
            // my_redirect($_SERVER['HTTP_REFERER']);
            return;
        }
    }

    function update($id)
    {
        parent::_set_rules();
        // $this->_set_rules();
        if($this->fv->run() === false)
        {
            $data['panel']  = $this->{$this->model}->_get($id);
            $data['mode'] = "update/$id";
            $this->_template("admin_addUpdate",$data);
            return;
        }
        else
        {
            parent::_dbSet_addUpdate();
            // $this->_dbSet_addUpdate();
            $this->{$this->model}->_update($id);
            // my_redirect(sample_uri."/update/$insert_id");
            my_redirect(sample_uri."/get/$id");
            // my_redirect($_SERVER['HTTP_REFERER']);
            return;
        }
    }
    function delete($id)
    {
        $this->{$this->model}->_delete($id);
        my_redirect(sample_uri."/gets");
        // my_redirect($_SERVER['HTTP_REFERER']);
    }
    function ajax_add(){
        header("Content-Type:application/json");

        parent::_set_rules();
         // $this->_set_rules();
        if($this->fv->run() === false)
        {
            $data['alert'] =  validation_errors(false,false);

        }
        else
        {
            parent::_dbSet_addUpdate();
            // $this->_dbSet_addUpdate();
            $insert_id =$this->{$this->model}->_add();
            $data['alert'] ="완료";
            $data['reload'] =true;
        }
        echo json_encode($data);
        return;
    }

    public function ajax_delete($id)
    {
        header("content-type:application/json");
        $this->{$this->model}->_delete($id);

        $data = array("reload"=>true);
        echo json_encode($data);
        return;
    }
    function _set_rules()
    {
        $this->fv->set_rules("name","이름","required");
    }

    function _dbSet_addUpdate()
    {
        $this->db->set("name",$this->input->post("name"));
    }
}


text:
package upgrade

import (
	"crypto/sha256"
	"fmt"
	"io/ioutil"
	"math/big"
	"os"
	"path/filepath"
	"strings"
	"testing"
	"time"

	"github.com/coreos/etcd/clientv3"
	"github.com/coreos/etcd/pkg/transport"
	"github.com/pkg/errors"

	kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
	"k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/validation"
	"k8s.io/kubernetes/cmd/kubeadm/app/constants"
	certsphase "k8s.io/kubernetes/cmd/kubeadm/app/phases/certs"
	controlplanephase "k8s.io/kubernetes/cmd/kubeadm/app/phases/controlplane"
	etcdphase "k8s.io/kubernetes/cmd/kubeadm/app/phases/etcd"
	"k8s.io/kubernetes/cmd/kubeadm/app/util/apiclient"
	certstestutil "k8s.io/kubernetes/cmd/kubeadm/app/util/certs"
	configutil "k8s.io/kubernetes/cmd/kubeadm/app/util/config"
	etcdutil "k8s.io/kubernetes/cmd/kubeadm/app/util/etcd"
	"k8s.io/kubernetes/cmd/kubeadm/app/util/pkiutil"
	testutil "k8s.io/kubernetes/cmd/kubeadm/test"
)

const (
	waitForHashes        = "wait-for-hashes"
	waitForHashChange    = "wait-for-hash-change"
	waitForPodsWithLabel = "wait-for-pods-with-label"

	testConfiguration = `
apiVersion: kubeadm.k8s.io/v1beta1
kind: InitConfiguration
nodeRegistration:
  name: foo
  criSocket: ""
localAPIEndpoint:
  advertiseAddress: 192.168.2.2
  bindPort: 6443
bootstrapTokens:
- token: ce3aa5.5ec8455bb76b379f
  ttl: 24h
---
apiVersion: kubeadm.k8s.io/v1beta1
kind: ClusterConfiguration

apiServer:
  certSANs: null
  extraArgs: null
certificatesDir: %s
etcd:
  local:
    dataDir: %s
    image: ""
imageRepository: k8s.gcr.io
kubernetesVersion: %s
networking:
  dnsDomain: cluster.local
  podSubnet: ""
  serviceSubnet: 10.96.0.0/12
useHyperKubeImage: false
`
)

// fakeWaiter is a fake apiclient.Waiter that returns errors it was initialized with
type fakeWaiter struct {
	errsToReturn map[string]error
}

func NewFakeStaticPodWaiter(errsToReturn map[string]error) apiclient.Waiter {
	return &fakeWaiter{
		errsToReturn: errsToReturn,
	}
}

// WaitForAPI just returns a dummy nil, to indicate that the program should just proceed
func (w *fakeWaiter) WaitForAPI() error {
	return nil
}

// WaitForPodsWithLabel just returns an error if set from errsToReturn
func (w *fakeWaiter) WaitForPodsWithLabel(kvLabel string) error {
	return w.errsToReturn[waitForPodsWithLabel]
}

// WaitForPodToDisappear just returns a dummy nil, to indicate that the program should just proceed
func (w *fakeWaiter) WaitForPodToDisappear(podName string) error {
	return nil
}

// SetTimeout is a no-op; we don't use it in this implementation
func (w *fakeWaiter) SetTimeout(_ time.Duration) {}

// WaitForStaticPodControlPlaneHashes returns an error if set from errsToReturn
func (w *fakeWaiter) WaitForStaticPodControlPlaneHashes(_ string) (map[string]string, error) {
	return map[string]string{}, w.errsToReturn[waitForHashes]
}

// WaitForStaticPodSingleHash returns an error if set from errsToReturn
func (w *fakeWaiter) WaitForStaticPodSingleHash(_ string, _ string) (string, error) {
	return "", w.errsToReturn[waitForHashes]
}

// WaitForStaticPodHashChange returns an error if set from errsToReturn
func (w *fakeWaiter) WaitForStaticPodHashChange(_, _, _ string) error {
	return w.errsToReturn[waitForHashChange]
}

// WaitForHealthyKubelet returns a dummy nil just to implement the interface
func (w *fakeWaiter) WaitForHealthyKubelet(_ time.Duration, _ string) error {
	return nil
}

// WaitForKubeletAndFunc is a wrapper for WaitForHealthyKubelet that also blocks for a function
func (w *fakeWaiter) WaitForKubeletAndFunc(f func() error) error {
	return nil
}

type fakeStaticPodPathManager struct {
	kubernetesDir     string
	realManifestDir   string
	tempManifestDir   string
	backupManifestDir string
	backupEtcdDir     string
	MoveFileFunc      func(string, string) error
}

func NewFakeStaticPodPathManager(moveFileFunc func(string, string) error) (StaticPodPathManager, error) {
	kubernetesDir, err := ioutil.TempDir("", "kubeadm-pathmanager-")
	if err != nil {
		return nil, errors.Wrapf(err, "couldn't create a temporary directory for the upgrade")
	}

	realManifestDir := filepath.Join(kubernetesDir, constants.ManifestsSubDirName)
	if err := os.Mkdir(realManifestDir, 0700); err != nil {
		return nil, errors.Wrapf(err, "couldn't create a realManifestDir for the upgrade")
	}

	upgradedManifestDir := filepath.Join(kubernetesDir, "upgraded-manifests")
	if err := os.Mkdir(upgradedManifestDir, 0700); err != nil {
		return nil, errors.Wrapf(err, "couldn't create a upgradedManifestDir for the upgrade")
	}

	backupManifestDir := filepath.Join(kubernetesDir, "backup-manifests")
	if err := os.Mkdir(backupManifestDir, 0700); err != nil {
		return nil, errors.Wrap(err, "couldn't create a backupManifestDir for the upgrade")
	}

	backupEtcdDir := filepath.Join(kubernetesDir, "kubeadm-backup-etcd")
	if err := os.Mkdir(backupEtcdDir, 0700); err != nil {
		return nil, err
	}

	return &fakeStaticPodPathManager{
		kubernetesDir:     kubernetesDir,
		realManifestDir:   realManifestDir,
		tempManifestDir:   upgradedManifestDir,
		backupManifestDir: backupManifestDir,
		backupEtcdDir:     backupEtcdDir,
		MoveFileFunc:      moveFileFunc,
	}, nil
}

func (spm *fakeStaticPodPathManager) MoveFile(oldPath, newPath string) error {
	return spm.MoveFileFunc(oldPath, newPath)
}

func (spm *fakeStaticPodPathManager) KubernetesDir() string {
	return spm.kubernetesDir
}

func (spm *fakeStaticPodPathManager) RealManifestPath(component string) string {
	return constants.GetStaticPodFilepath(component, spm.realManifestDir)
}
func (spm *fakeStaticPodPathManager) RealManifestDir() string {
	return spm.realManifestDir
}

func (spm *fakeStaticPodPathManager) TempManifestPath(component string) string {
	return constants.GetStaticPodFilepath(component, spm.tempManifestDir)
}
func (spm *fakeStaticPodPathManager) TempManifestDir() string {
	return spm.tempManifestDir
}

func (spm *fakeStaticPodPathManager) BackupManifestPath(component string) string {
	return constants.GetStaticPodFilepath(component, spm.backupManifestDir)
}
func (spm *fakeStaticPodPathManager) BackupManifestDir() string {
	return spm.backupManifestDir
}

func (spm *fakeStaticPodPathManager) BackupEtcdDir() string {
	return spm.backupEtcdDir
}

func (spm *fakeStaticPodPathManager) CleanupDirs() error {
	if err := os.RemoveAll(spm.TempManifestDir()); err != nil {
		return err
	}
	if err := os.RemoveAll(spm.BackupManifestDir()); err != nil {
		return err
	}
	return os.RemoveAll(spm.BackupEtcdDir())
}

type fakeTLSEtcdClient struct{ TLS bool }

func (c fakeTLSEtcdClient) ClusterAvailable() (bool, error) { return true, nil }

func (c fakeTLSEtcdClient) WaitForClusterAvailable(retries int, retryInterval time.Duration) (bool, error) {
	return true, nil
}

func (c fakeTLSEtcdClient) GetClusterStatus() (map[string]*clientv3.StatusResponse, error) {
	return map[string]*clientv3.StatusResponse{
		"https://1.2.3.4:2379": {
			Version: "3.1.12",
		}}, nil
}

func (c fakeTLSEtcdClient) GetClusterVersions() (map[string]string, error) {
	return map[string]string{
		"https://1.2.3.4:2379": "3.1.12",
	}, nil
}

func (c fakeTLSEtcdClient) GetVersion() (string, error) {
	return "3.1.12", nil
}

func (c fakeTLSEtcdClient) Sync() error { return nil }

func (c fakeTLSEtcdClient) AddMember(name string, peerAddrs string) ([]etcdutil.Member, error) {
	return []etcdutil.Member{}, nil
}

type fakePodManifestEtcdClient struct{ ManifestDir, CertificatesDir string }

func (c fakePodManifestEtcdClient) ClusterAvailable() (bool, error) { return true, nil }

func (c fakePodManifestEtcdClient) WaitForClusterAvailable(retries int, retryInterval time.Duration) (bool, error) {
	return true, nil
}

func (c fakePodManifestEtcdClient) GetClusterStatus() (map[string]*clientv3.StatusResponse, error) {
	// Make sure the certificates generated from the upgrade are readable from disk
	tlsInfo := transport.TLSInfo{
		CertFile:      filepath.Join(c.CertificatesDir, constants.EtcdCACertName),
		KeyFile:       filepath.Join(c.CertificatesDir, constants.EtcdHealthcheckClientCertName),
		TrustedCAFile: filepath.Join(c.CertificatesDir, constants.EtcdHealthcheckClientKeyName),
	}
	_, err := tlsInfo.ClientConfig()
	if err != nil {
		return nil, err
	}

	return map[string]*clientv3.StatusResponse{
		"https://1.2.3.4:2379": {Version: "3.1.12"},
	}, nil
}

func (c fakePodManifestEtcdClient) GetClusterVersions() (map[string]string, error) {
	return map[string]string{
		"https://1.2.3.4:2379": "3.1.12",
	}, nil
}

func (c fakePodManifestEtcdClient) GetVersion() (string, error) {
	return "3.1.12", nil
}

func (c fakePodManifestEtcdClient) Sync() error { return nil }

func (c fakePodManifestEtcdClient) AddMember(name string, peerAddrs string) ([]etcdutil.Member, error) {
	return []etcdutil.Member{}, nil
}

func TestStaticPodControlPlane(t *testing.T) {
	tests := []struct {
		description          string
		waitErrsToReturn     map[string]error
		moveFileFunc         func(string, string) error
		expectedErr          bool
		manifestShouldChange bool
	}{
		{
			description: "error-free case should succeed",
			waitErrsToReturn: map[string]error{
				waitForHashes:        nil,
				waitForHashChange:    nil,
				waitForPodsWithLabel: nil,
			},
			moveFileFunc: func(oldPath, newPath string) error {
				return os.Rename(oldPath, newPath)
			},
			expectedErr:          false,
			manifestShouldChange: true,
		},
		{
			description: "any wait error should result in a rollback and an abort",
			waitErrsToReturn: map[string]error{
				waitForHashes:        errors.New("boo! failed"),
				waitForHashChange:    nil,
				waitForPodsWithLabel: nil,
			},
			moveFileFunc: func(oldPath, newPath string) error {
				return os.Rename(oldPath, newPath)
			},
			expectedErr:          true,
			manifestShouldChange: false,
		},
		{
			description: "any wait error should result in a rollback and an abort",
			waitErrsToReturn: map[string]error{
				waitForHashes:        nil,
				waitForHashChange:    errors.New("boo! failed"),
				waitForPodsWithLabel: nil,
			},
			moveFileFunc: func(oldPath, newPath string) error {
				return os.Rename(oldPath, newPath)
			},
			expectedErr:          true,
			manifestShouldChange: false,
		},
		{
			description: "any wait error should result in a rollback and an abort",
			waitErrsToReturn: map[string]error{
				waitForHashes:        nil,
				waitForHashChange:    nil,
				waitForPodsWithLabel: errors.New("boo! failed"),
			},
			moveFileFunc: func(oldPath, newPath string) error {
				return os.Rename(oldPath, newPath)
			},
			expectedErr:          true,
			manifestShouldChange: false,
		},
		{
			description: "any path-moving error should result in a rollback and an abort",
			waitErrsToReturn: map[string]error{
				waitForHashes:        nil,
				waitForHashChange:    nil,
				waitForPodsWithLabel: nil,
			},
			moveFileFunc: func(oldPath, newPath string) error {
				// fail for kube-apiserver move
				if strings.Contains(newPath, "kube-apiserver") {
					return errors.New("moving the kube-apiserver file failed")
				}
				return os.Rename(oldPath, newPath)
			},
			expectedErr:          true,
			manifestShouldChange: false,
		},
		{
			description: "any path-moving error should result in a rollback and an abort",
			waitErrsToReturn: map[string]error{
				waitForHashes:        nil,
				waitForHashChange:    nil,
				waitForPodsWithLabel: nil,
			},
			moveFileFunc: func(oldPath, newPath string) error {
				// fail for kube-controller-manager move
				if strings.Contains(newPath, "kube-controller-manager") {
					return errors.New("moving the kube-apiserver file failed")
				}
				return os.Rename(oldPath, newPath)
			},
			expectedErr:          true,
			manifestShouldChange: false,
		},
		{
			description: "any path-moving error should result in a rollback and an abort; even though this is the last component (kube-apiserver and kube-controller-manager healthy)",
			waitErrsToReturn: map[string]error{
				waitForHashes:        nil,
				waitForHashChange:    nil,
				waitForPodsWithLabel: nil,
			},
			moveFileFunc: func(oldPath, newPath string) error {
				// fail for kube-scheduler move
				if strings.Contains(newPath, "kube-scheduler") {
					return errors.New("moving the kube-apiserver file failed")
				}
				return os.Rename(oldPath, newPath)
			},
			expectedErr:          true,
			manifestShouldChange: false,
		},
	}

	for _, rt := range tests {
		t.Run(rt.description, func(t *testing.T) {
			waiter := NewFakeStaticPodWaiter(rt.waitErrsToReturn)
			pathMgr, err := NewFakeStaticPodPathManager(rt.moveFileFunc)
			if err != nil {
				t.Fatalf("couldn't run NewFakeStaticPodPathManager: %v", err)
			}
			defer os.RemoveAll(pathMgr.(*fakeStaticPodPathManager).KubernetesDir())
			constants.KubernetesDir = pathMgr.(*fakeStaticPodPathManager).KubernetesDir()

			tempCertsDir, err := ioutil.TempDir("", "kubeadm-certs")
			if err != nil {
				t.Fatalf("couldn't create temporary certificates directory: %v", err)
			}
			defer os.RemoveAll(tempCertsDir)
			tmpEtcdDataDir, err := ioutil.TempDir("", "kubeadm-etcd-data")
			if err != nil {
				t.Fatalf("couldn't create temporary etcd data directory: %v", err)
			}
			defer os.RemoveAll(tmpEtcdDataDir)

			oldcfg, err := getConfig(constants.MinimumControlPlaneVersion.String(), tempCertsDir, tmpEtcdDataDir)
			if err != nil {
				t.Fatalf("couldn't create config: %v", err)
			}

			tree, err := certsphase.GetCertsWithoutEtcd().AsMap().CertTree()
			if err != nil {
				t.Fatalf("couldn't get cert tree: %v", err)
			}

			if err := tree.CreateTree(oldcfg); err != nil {
				t.Fatalf("couldn't get create cert tree: %v", err)
			}

			t.Logf("Wrote certs to %s\n", oldcfg.CertificatesDir)

			// Initialize the directory with v1.7 manifests; should then be upgraded to v1.8 using the method
			err = controlplanephase.CreateInitStaticPodManifestFiles(pathMgr.RealManifestDir(), oldcfg)
			if err != nil {
				t.Fatalf("couldn't run CreateInitStaticPodManifestFiles: %v", err)
			}
			err = etcdphase.CreateLocalEtcdStaticPodManifestFile(pathMgr.RealManifestDir(), oldcfg)
			if err != nil {
				t.Fatalf("couldn't run CreateLocalEtcdStaticPodManifestFile: %v", err)
			}
			// Get a hash of the v1.7 API server manifest to compare later (was the file re-written)
			oldHash, err := getAPIServerHash(pathMgr.RealManifestDir())
			if err != nil {
				t.Fatalf("couldn't read temp file: %v", err)
			}

			newcfg, err := getConfig(constants.CurrentKubernetesVersion.String(), tempCertsDir, tmpEtcdDataDir)
			if err != nil {
				t.Fatalf("couldn't create config: %v", err)
			}

			// create the kubeadm etcd certs
			caCert, caKey, err := certsphase.KubeadmCertEtcdCA.CreateAsCA(newcfg)
			if err != nil {
				t.Fatalf("couldn't create new CA certificate: %v", err)
			}
			for _, cert := range []*certsphase.KubeadmCert{
				&certsphase.KubeadmCertEtcdServer,
				&certsphase.KubeadmCertEtcdPeer,
				&certsphase.KubeadmCertEtcdHealthcheck,
				&certsphase.KubeadmCertEtcdAPIClient,
			} {
				if err := cert.CreateFromCA(newcfg, caCert, caKey); err != nil {
					t.Fatalf("couldn't create certificate %s: %v", cert.Name, err)
				}
			}

			actualErr := StaticPodControlPlane(
				nil,
				waiter,
				pathMgr,
				newcfg,
				true,
				fakeTLSEtcdClient{
					TLS: false,
				},
				fakePodManifestEtcdClient{
					ManifestDir:     pathMgr.RealManifestDir(),
					CertificatesDir: newcfg.CertificatesDir,
				},
			)
			if (actualErr != nil) != rt.expectedErr {
				t.Errorf(
					"failed UpgradeStaticPodControlPlane\n%s\n\texpected error: %t\n\tgot: %t\n\tactual error: %v",
					rt.description,
					rt.expectedErr,
					(actualErr != nil),
					actualErr,
				)
			}

			newHash, err := getAPIServerHash(pathMgr.RealManifestDir())
			if err != nil {
				t.Fatalf("couldn't read temp file: %v", err)
			}

			if (oldHash != newHash) != rt.manifestShouldChange {
				t.Errorf(
					"failed StaticPodControlPlane\n%s\n\texpected manifest change: %t\n\tgot: %t\n\tnewHash: %v",
					rt.description,
					rt.manifestShouldChange,
					(oldHash != newHash),
					newHash,
				)
			}
		})
	}
}

func getAPIServerHash(dir string) (string, error) {
	manifestPath := constants.GetStaticPodFilepath(constants.KubeAPIServer, dir)

	fileBytes, err := ioutil.ReadFile(manifestPath)
	if err != nil {
		return "", err
	}

	return fmt.Sprintf("%x", sha256.Sum256(fileBytes)), nil
}

func getConfig(version, certsDir, etcdDataDir string) (*kubeadmapi.InitConfiguration, error) {
	configBytes := []byte(fmt.Sprintf(testConfiguration, certsDir, etcdDataDir, version))

	// Unmarshal the config
	cfg, err := configutil.BytesToInternalConfig(configBytes)
	if err != nil {
		return nil, err
	}

	// Applies dynamic defaults to settings not provided with flags
	if err = configutil.SetInitDynamicDefaults(cfg); err != nil {
		return nil, err
	}

	// Validates cfg (flags/configs + defaults + dynamic defaults)
	if err = validation.ValidateInitConfiguration(cfg).ToAggregate(); err != nil {
		return nil, err
	}

	return cfg, nil
}

func getTempDir(t *testing.T, name string) (string, func()) {
	dir, err := ioutil.TempDir(os.TempDir(), name)
	if err != nil {
		t.Fatalf("couldn't make temporary directory: %v", err)
	}

	return dir, func() {
		os.RemoveAll(dir)
	}
}

func TestCleanupDirs(t *testing.T) {
	tests := []struct {
		name                   string
		keepManifest, keepEtcd bool
	}{
		{
			name:         "save manifest backup",
			keepManifest: true,
		},
		{
			name:         "save both etcd and manifest",
			keepManifest: true,
			keepEtcd:     true,
		},
		{
			name: "save nothing",
		},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			realManifestDir, cleanup := getTempDir(t, "realManifestDir")
			defer cleanup()

			tempManifestDir, cleanup := getTempDir(t, "tempManifestDir")
			defer cleanup()

			backupManifestDir, cleanup := getTempDir(t, "backupManifestDir")
			defer cleanup()

			backupEtcdDir, cleanup := getTempDir(t, "backupEtcdDir")
			defer cleanup()

			mgr := NewKubeStaticPodPathManager(realManifestDir, tempManifestDir, backupManifestDir, backupEtcdDir, test.keepManifest, test.keepEtcd)
			err := mgr.CleanupDirs()
			if err != nil {
				t.Errorf("unexpected error cleaning up: %v", err)
			}

			if _, err := os.Stat(tempManifestDir); !os.IsNotExist(err) {
				t.Errorf("%q should not have existed", tempManifestDir)
			}
			_, err = os.Stat(backupManifestDir)
			if test.keepManifest {
				if err != nil {
					t.Errorf("unexpected error getting backup manifest dir")
				}
			} else {
				if !os.IsNotExist(err) {
					t.Error("expected backup manifest to not exist")
				}
			}

			_, err = os.Stat(backupEtcdDir)
			if test.keepEtcd {
				if err != nil {
					t.Errorf("unexpected error getting backup etcd dir")
				}
			} else {
				if !os.IsNotExist(err) {
					t.Error("expected backup etcd dir to not exist")
				}
			}
		})
	}
}

func TestRenewCerts(t *testing.T) {
	caCert, caKey := certstestutil.SetupCertificateAuthorithy(t)
	t.Run("all certs exist, should be rotated", func(t *testing.T) {
	})
	tests := []struct {
		name               string
		component          string
		skipCreateCA       bool
		shouldErrorOnRenew bool
		certsShouldExist   []*certsphase.KubeadmCert
	}{
		{
			name:      "all certs exist, should be rotated",
			component: constants.Etcd,
			certsShouldExist: []*certsphase.KubeadmCert{
				&certsphase.KubeadmCertEtcdServer,
				&certsphase.KubeadmCertEtcdPeer,
				&certsphase.KubeadmCertEtcdHealthcheck,
			},
		},
		{
			name:      "just renew API cert",
			component: constants.KubeAPIServer,
			certsShouldExist: []*certsphase.KubeadmCert{
				&certsphase.KubeadmCertEtcdAPIClient,
			},
		},
		{
			name:         "ignores other compnonents",
			skipCreateCA: true,
			component:    constants.KubeScheduler,
		},
		{
			name:               "missing a cert to renew",
			component:          constants.Etcd,
			shouldErrorOnRenew: true,
			certsShouldExist: []*certsphase.KubeadmCert{
				&certsphase.KubeadmCertEtcdServer,
				&certsphase.KubeadmCertEtcdPeer,
			},
		},
		{
			name:               "no CA, cannot continue",
			component:          constants.Etcd,
			skipCreateCA:       true,
			shouldErrorOnRenew: true,
		},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			// Setup up basic requities
			tmpDir := testutil.SetupTempDir(t)
			defer os.RemoveAll(tmpDir)

			cfg := testutil.GetDefaultInternalConfig(t)
			cfg.CertificatesDir = tmpDir

			if !test.skipCreateCA {
				if err := pkiutil.WriteCertAndKey(tmpDir, constants.EtcdCACertAndKeyBaseName, caCert, caKey); err != nil {
					t.Fatalf("couldn't write out CA: %v", err)
				}
			}

			// Create expected certs
			for _, kubeCert := range test.certsShouldExist {
				if err := kubeCert.CreateFromCA(cfg, caCert, caKey); err != nil {
					t.Fatalf("couldn't renew certificate %q: %v", kubeCert.Name, err)
				}
			}

			// Load expected certs to check if serial numbers changes
			certMaps := make(map[*certsphase.KubeadmCert]big.Int)
			for _, kubeCert := range test.certsShouldExist {
				cert, err := pkiutil.TryLoadCertFromDisk(tmpDir, kubeCert.BaseName)
				if err != nil {
					t.Fatalf("couldn't load certificate %q: %v", kubeCert.Name, err)
				}
				certMaps[kubeCert] = *cert.SerialNumber
			}

			// Renew everything
			err := renewCerts(cfg, test.component)
			if test.shouldErrorOnRenew {
				if err == nil {
					t.Fatal("expected renewal error, got nothing")
				}
				// expected error, got error
				return
			}
			if err != nil {
				t.Fatalf("couldn't renew certificates: %v", err)
			}

			// See if the certificate serial numbers change
			for kubeCert, cert := range certMaps {
				newCert, err := pkiutil.TryLoadCertFromDisk(tmpDir, kubeCert.BaseName)
				if err != nil {
					t.Errorf("couldn't load new certificate %q: %v", kubeCert.Name, err)
					continue
				}
				if cert.Cmp(newCert.SerialNumber) == 0 {
					t.Errorf("certifitate %v was not reissued", kubeCert.Name)
				}
			}
		})

	}
}


text:
import { run } from '@ember/runloop';
import $ from 'jquery';

var timeSlotHeight = function() {
  return $('.as-calendar-timetable-content')
    .find('.as-calendar-timetable__slot-item:first')
    .height();
};

var dayWidth = function() {
  var $content = $('.as-calendar-timetable-content');
  return $content.width() / $content.find('.as-calendar-timetable__day').length;
};

var pointForTime = function(options) {
  var $target = $('.as-calendar-timetable-content');
  var offsetX = options.day * dayWidth();
  var offsetY = options.timeSlot * timeSlotHeight();
  var pageX = $target.offset().left + offsetX;
  var pageY = $target.offset().top + offsetY;

  return {
    pageX: pageX,
    pageY: pageY,
    clientX: pageX - $(document).scrollLeft(),
    clientY: pageY - $(document).scrollTop()
  };
};

var selectTime = function(options) {
  run(() => {
    var $target = $('.as-calendar-timetable-content');
    var point = pointForTime(options);
    var event = $.Event('click');

    event.pageX = point.pageX;
    event.pageY = point.pageY;

    $target.trigger(event);
  });
};

// var resizeOccurrence = function(occurrence, options) {
//   Ember.run(() => {
//     occurrence.find('.as-calendar-occurrence__resize-handle').simulate('drag', {
//       dx: 0,
//       dy: options.timeSlots * timeSlotHeight() + occurrence.height()
//     });
//   });
// };

// var dragOccurrence = function(occurrence, options) {
//   Ember.run(() => {
//     occurrence.simulate('drag', {
//       dx: options.days * dayWidth(),
//       dy: options.timeSlots * timeSlotHeight() + occurrence.height()
//     });
//   });
// };

var selectNextWeek = function() {
  run(() => {
    $('button.as-calendar-header__nav-group-action').last().click();
  });
};

var selectPreviousWeek = function() {
  run(() => {
    $('button.as-calendar-header__nav-group-action').first().click();
  });
};

export {
  timeSlotHeight,
  dayWidth,
  selectTime,
  selectNextWeek,
  selectPreviousWeek
};


text:
from celery import shared_task
from django.contrib.auth.models import User

from kitsune.customercare.zendesk import ZendeskClient

@shared_task
def update_zendesk_user(user_id: int) -> None:
    user = User.objects.get(pk=user_id)
    if user.profile.zendesk_id:
        zendesk = ZendeskClient()
        zendesk.update_user(user)

@shared_task
def update_zendesk_identity(user_id: int, email: str) -> None:
    user = User.objects.get(pk=user_id)
    zendesk_user_id = user.profile.zendesk_id

    # fetch identity id
    if zendesk_user_id:
        zendesk = ZendeskClient()
        zendesk.update_primary_email(zendesk_user_id, email)


text:
<component name="libraryTable">
  <library name="BaseRecyclerViewAdapterHelper-2.9.16">
    <ANNOTATIONS>
      <root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.github.CymChad/BaseRecyclerViewAdapterHelper/2.9.16/annotations.zip!/" />
    </ANNOTATIONS>
    <CLASSES>
      <root url="file://$USER_HOME$/.android/build-cache/d0d1330efdce130da0f382205d8657504bd4f671/output/res" />
      <root url="jar://$USER_HOME$/.android/build-cache/d0d1330efdce130da0f382205d8657504bd4f671/output/jars/classes.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES>
      <root url="jar://$USER_HOME$/.gradle/caches/modules-2/files-2.1/com.github.CymChad/BaseRecyclerViewAdapterHelper/2.9.16/139a03d944b9ddf935a448768d7ca209f9ef985e/BaseRecyclerViewAdapterHelper-2.9.16-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
package azkaban.execapp.event;

import static org.mockito.Mockito.mock;

import azkaban.execapp.EventCollectorListener;
import azkaban.execapp.EventReporterUtil;
import azkaban.execapp.FlowRunner;
import azkaban.execapp.FlowRunnerTestUtil;
import azkaban.execapp.jmx.JmxJobMBeanManager;
import azkaban.executor.ExecutableFlow;
import azkaban.executor.ExecutableFlowBase;
import azkaban.executor.ExecutableNode;
import azkaban.executor.ExecutionOptions;
import azkaban.executor.ExecutorLoader;
import azkaban.executor.InteractiveTestJob;
import azkaban.executor.MockExecutorLoader;
import azkaban.executor.Status;
import azkaban.jobtype.JobTypeManager;
import azkaban.project.ProjectLoader;
import azkaban.spi.AzkabanEventReporter;
import azkaban.test.Utils;
import azkaban.test.executions.ExecutionsTestUtil;
import azkaban.utils.Props;
import java.io.File;
import java.io.IOException;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

public class RemoteFlowWatcherTest {

  private final AzkabanEventReporter azkabanEventReporter =
      EventReporterUtil.getTestAzkabanEventReporter();
  @Rule
  public TemporaryFolder temporaryFolder = new TemporaryFolder();
  private JobTypeManager jobtypeManager;

  @Before
  public void setUp() throws Exception {
    this.jobtypeManager =
        new JobTypeManager(null, null, this.getClass().getClassLoader());
    this.jobtypeManager.getJobTypePluginSet().addPluginClass("test", InteractiveTestJob.class);
    Utils.initServiceProvider();
    JmxJobMBeanManager.getInstance().initialize(new Props());
    InteractiveTestJob.setQuickSuccess(true);
  }

  @After
  public void tearDown() throws IOException {
    InteractiveTestJob.resetQuickSuccess();
  }

  @Test
  public void testBasicRemoteFlowWatcher() throws Exception {
    final MockExecutorLoader loader = new MockExecutorLoader();

    final EventCollectorListener eventCollector = new EventCollectorListener();

    final File workingDir1 = this.temporaryFolder.newFolder();
    final FlowRunner runner1 =
        createFlowRunner(workingDir1, loader, eventCollector, "exec1", 1, null,
            null);
    final Thread runner1Thread = new Thread(runner1);

    final File workingDir2 = this.temporaryFolder.newFolder();
    final RemoteFlowWatcher watcher = new RemoteFlowWatcher(1, loader, 100);
    final FlowRunner runner2 =
        createFlowRunner(workingDir2, loader, eventCollector, "exec1", 2,
            watcher, 2);
    final Thread runner2Thread = new Thread(runner2);

    printCurrentState("runner1 ", runner1.getExecutableFlow());
    runner1Thread.start();
    runner2Thread.start();

    runner2Thread.join();

    assertPipelineLevel2(runner1.getExecutableFlow(), runner2.getExecutableFlow());
  }

  @Test
  public void testLevel1RemoteFlowWatcher() throws Exception {
    final MockExecutorLoader loader = new MockExecutorLoader();

    final EventCollectorListener eventCollector = new EventCollectorListener();

    final File workingDir1 = this.temporaryFolder.newFolder();
    final FlowRunner runner1 =
        createFlowRunner(workingDir1, loader, eventCollector, "exec1", 1, null,
            null);
    final Thread runner1Thread = new Thread(runner1);

    final File workingDir2 = this.temporaryFolder.newFolder();
    final RemoteFlowWatcher watcher = new RemoteFlowWatcher(1, loader, 100);
    final FlowRunner runner2 =
        createFlowRunner(workingDir2, loader, eventCollector, "exec1", 2,
            watcher, 1);
    final Thread runner2Thread = new Thread(runner2);

    runner1Thread.start();
    runner2Thread.start();
    runner2Thread.join();

    testPipelineLevel1(runner1.getExecutableFlow(), runner2.getExecutableFlow());
  }

  @Test
  public void testLevel2DiffRemoteFlowWatcher() throws Exception {
    final MockExecutorLoader loader = new MockExecutorLoader();

    final EventCollectorListener eventCollector = new EventCollectorListener();

    final File workingDir1 = this.temporaryFolder.newFolder();
    final FlowRunner runner1 =
        createFlowRunner(workingDir1, loader, eventCollector, "exec1", 1, null,
            null);
    final Thread runner1Thread = new Thread(runner1);

    final File workingDir2 = this.temporaryFolder.newFolder();

    final RemoteFlowWatcher watcher = new RemoteFlowWatcher(1, loader, 100);
    final FlowRunner runner2 =
        createFlowRunner(workingDir2, loader, eventCollector, "exec1-mod", 2,
            watcher, 1);
    final Thread runner2Thread = new Thread(runner2);

    runner1Thread.start();
    runner2Thread.start();
    runner2Thread.join();

    testPipelineLevel1(runner1.getExecutableFlow(), runner2.getExecutableFlow());
  }

  private void testPipelineLevel1(final ExecutableFlow first, final ExecutableFlow second) {
    for (final ExecutableNode node : second.getExecutableNodes()) {
      Assert.assertEquals(Status.SUCCEEDED, node.getStatus());

      // check it's start time is after the first's children.
      final ExecutableNode watchedNode = first.getExecutableNode(node.getId());
      if (watchedNode == null) {
        continue;
      }
      Assert.assertEquals(Status.SUCCEEDED, watchedNode.getStatus());

      System.out.println("Node " + node.getId() + " start: "
          + node.getStartTime() + " dependent on " + watchedNode.getId() + " "
          + watchedNode.getEndTime() + " diff: "
          + (node.getStartTime() - watchedNode.getEndTime()));

      Assert.assertTrue(node.getStartTime() >= watchedNode.getEndTime());

      long minParentDiff = 0;
      if (node.getInNodes().size() > 0) {
        minParentDiff = Long.MAX_VALUE;
        for (final String dependency : node.getInNodes()) {
          final ExecutableNode parent = second.getExecutableNode(dependency);
          final long diff = node.getStartTime() - parent.getEndTime();
          minParentDiff = Math.min(minParentDiff, diff);
        }
      }
      final long diff = node.getStartTime() - watchedNode.getEndTime();
      Assert.assertTrue(minParentDiff < 500 || diff < 500);
    }
  }

  private void assertPipelineLevel2(final ExecutableFlow first, final ExecutableFlow second) {
    for (final ExecutableNode node : second.getExecutableNodes()) {
      Assert.assertEquals(Status.SUCCEEDED, node.getStatus());

      // check it's start time is after the first's children.
      final ExecutableNode watchedNode = first.getExecutableNode(node.getId());
      if (watchedNode == null) {
        continue;
      }
      Assert.assertEquals(Status.SUCCEEDED, watchedNode.getStatus());

      long minDiff = Long.MAX_VALUE;
      for (final String watchedChild : watchedNode.getOutNodes()) {
        final ExecutableNode child = first.getExecutableNode(watchedChild);
        if (child == null) {
          continue;
        }
        Assert.assertEquals(Status.SUCCEEDED, child.getStatus());
        final long diff = node.getStartTime() - child.getEndTime();
        minDiff = Math.min(minDiff, diff);
        Assert.assertTrue(
            "Node " + node.getId() + " start: " + node.getStartTime() + " dependent on "
                + watchedChild + " " + child.getEndTime() + " diff: " + diff,
            node.getStartTime() >= child.getEndTime());
      }

      long minParentDiff = Long.MAX_VALUE;
      for (final String dependency : node.getInNodes()) {
        final ExecutableNode parent = second.getExecutableNode(dependency);
        final long diff = node.getStartTime() - parent.getEndTime();
        minParentDiff = Math.min(minParentDiff, diff);
      }
      Assert.assertTrue("minPipelineTimeDiff:" + minDiff
              + " minDependencyTimeDiff:" + minParentDiff,
          minParentDiff < 5000 || minDiff < 5000);
    }
  }

  private FlowRunner createFlowRunner(final File workingDir, final ExecutorLoader loader,
      final EventCollectorListener eventCollector, final String flowName, final int execId,
      final FlowWatcher watcher, final Integer pipeline) throws Exception {
    return createFlowRunner(workingDir, loader, eventCollector, flowName, execId, watcher, pipeline,
        new Props());
  }

  private FlowRunner createFlowRunner(final File workingDir, final ExecutorLoader loader,
      final EventCollectorListener eventCollector, final String flowName, final int execId,
      final FlowWatcher watcher, final Integer pipeline, final Props azkabanProps)
      throws Exception {
    final File testDir = ExecutionsTestUtil.getFlowDir("exectest1");
    final ExecutableFlow exFlow =
        FlowRunnerTestUtil.prepareExecDir(workingDir, testDir, flowName, execId);
    final ExecutionOptions options = exFlow.getExecutionOptions();
    if (watcher != null) {
      options.setPipelineLevel(pipeline);
      options.setPipelineExecutionId(watcher.getExecId());
    }

    loader.uploadExecutableFlow(exFlow);
    final FlowRunner runner = new FlowRunner(exFlow, loader, mock(ProjectLoader.class),
        this.jobtypeManager, azkabanProps, this.azkabanEventReporter);
    runner.setFlowWatcher(watcher);
    runner.addListener(eventCollector);

    return runner;
  }

  private void printCurrentState(final String prefix, final ExecutableFlowBase flow) {
    for (final ExecutableNode node : flow.getExecutableNodes()) {

      System.err.println(prefix + node.getNestedId() + "->"
          + node.getStatus().name());
      if (node instanceof ExecutableFlowBase) {
        printCurrentState(prefix, (ExecutableFlowBase) node);
      }
    }
  }

}


text:
<?php

namespace Magento\Catalog\Model\Plugin;

class QuoteItemProductOption
{
    /**
     * @param \Magento\Quote\Model\Quote\Item\ToOrderItem $subject
     * @param callable $proceed
     * @param \Magento\Quote\Model\Quote\Item\AbstractItem $item
     * @param array $additional
     * @return \Magento\Sales\Model\Order\Item
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function aroundConvert(
        \Magento\Quote\Model\Quote\Item\ToOrderItem $subject,
        \Closure $proceed,
        \Magento\Quote\Model\Quote\Item\AbstractItem $item,
        $additional = []
    ) {
        /** @var $orderItem \Magento\Sales\Model\Order\Item */
        $orderItem = $proceed($item, $additional);

        if (is_array($item->getOptions())) {
            foreach ($item->getOptions() as $itemOption) {
                $code = explode('_', $itemOption->getCode());
                if (isset($code[1]) && is_numeric($code[1])) {
                    $option = $item->getProduct()->getOptionById($code[1]);
                    if ($option && $option->getType() == \Magento\Catalog\Model\Product\Option::OPTION_TYPE_FILE) {
                        try {
                            $option->groupFactory(
                                $option->getType()
                            )->setQuoteItemOption(
                                $itemOption
                            )->copyQuoteToOrder();
                        } catch (\Exception $e) {
                            continue;
                        }
                    }
                }
            }
        }
        return $orderItem;
    }
}


text:
[@cspell/cspell-types](../README.md) / [Exports](../modules.md) / CSpellReporter

# Interface: CSpellReporter

## Table of contents

### Properties

- [debug](CSpellReporter.md#debug)
- [error](CSpellReporter.md#error)
- [info](CSpellReporter.md#info)
- [issue](CSpellReporter.md#issue)
- [progress](CSpellReporter.md#progress)
- [result](CSpellReporter.md#result)

## Properties

### debug

• **debug**: [`DebugEmitter`](../modules.md#debugemitter)

#### Defined in

[CSpellReporter.ts:63](https://github.com/streetsidesoftware/cspell/blob/34586d56/packages/cspell-types/src/CSpellReporter.ts#L63)

___

### error

• **error**: [`ErrorEmitter`](../modules.md#erroremitter)

#### Defined in

[CSpellReporter.ts:64](https://github.com/streetsidesoftware/cspell/blob/34586d56/packages/cspell-types/src/CSpellReporter.ts#L64)

___

### info

• **info**: [`MessageEmitter`](../modules.md#messageemitter)

#### Defined in

[CSpellReporter.ts:62](https://github.com/streetsidesoftware/cspell/blob/34586d56/packages/cspell-types/src/CSpellReporter.ts#L62)

___

### issue

• **issue**: [`SpellingErrorEmitter`](../modules.md#spellingerroremitter)

#### Defined in

[CSpellReporter.ts:61](https://github.com/streetsidesoftware/cspell/blob/34586d56/packages/cspell-types/src/CSpellReporter.ts#L61)

___

### progress

• **progress**: [`ProgressEmitter`](../modules.md#progressemitter)

#### Defined in

[CSpellReporter.ts:65](https://github.com/streetsidesoftware/cspell/blob/34586d56/packages/cspell-types/src/CSpellReporter.ts#L65)

___

### result

• **result**: [`ResultEmitter`](../modules.md#resultemitter)

#### Defined in

[CSpellReporter.ts:66](https://github.com/streetsidesoftware/cspell/blob/34586d56/packages/cspell-types/src/CSpellReporter.ts#L66)


text:
from . import utils
from . import inference
from . import nodes
from . import plot

from ._meta import __author__, __copyright__, __contact__, __license__

from ._version import get_versions
__version__ = get_versions()['version']
del get_versions