text:
from hat_trie import Trie
from collections import Counter
from gevent import Greenlet
from hashlib import sha224
from hashring import HashRing
from json import dumps, loads
from monoids import dictm
from random import random, sample
from service import UnitOfWork
from string import ascii_lowercase
from util import instantiate_class, post_distrib_rest
import logging
import sys

######################################################################
## class definitions

class Population (UnitOfWork):
    def __init__ (self, uow_name, prefix, indiv_instance):
        super(Population, self).__init__(uow_name, prefix)

        logging.debug("INIT POPULATION")

        self.indiv_class = indiv_instance.__class__
        self.total_indiv = 0
        self.current_gen = 0

        self._shard = {}
        self._trie = Trie(ascii_lowercase)

    def perform_task (self, payload):
        """perform a task consumed from the Worker.task_queue"""
        key = payload["key"]
        gen = payload["gen"]
        feature_set = payload["feature_set"]
        self.receive_reify(key, gen, feature_set)

    def orchestrate (self, framework):
        """
        initialize a Population of unique Individuals at generation 0,
        then iterate N times or until a "good enough" solution is found
        """
        framework.send_ring_rest("pop/init", {})
        framework.send_ring_rest("pop/gen", {})

        while True:
            framework.phase_barrier()

            if self.current_gen == self.uow_factory.n_gen:
                break

            # determine the fitness cutoff threshold
            self.total_indiv = 0
            hist = {}

            for shard_msg in framework.send_ring_rest("pop/hist", {}):
                logging.debug(shard_msg)
                payload = loads(shard_msg)
                self.total_indiv += payload["total_indiv"]
                hist = dictm.fold([hist, payload["hist"]])

            # test for the terminating condition
            hist_items = map(lambda x: (float(x[0]), x[1],), sorted(hist.items(), reverse=True))

            if self.test_termination(self.current_gen, hist_items):
                break

            ## NB: TODO save Framework state to Zookeeper

            # apply the fitness cutoff and breed "children" for the
            # next generation
            fitness_cutoff = self.get_fitness_cutoff(hist_items)
            framework.send_ring_rest("pop/next", { "current_gen": self.current_gen, "fitness_cutoff": fitness_cutoff })
            self.current_gen += 1

        # report the best Individuals in the final result
        results = []

        for l in framework.send_ring_rest("pop/enum", { "fitness_cutoff": fitness_cutoff }):
            results.extend(loads(l))

        results.sort(reverse=True)

        for x in results:
            # print results to stdout
            print "\t".join(x)

    def handle_endpoints (self, worker, uri_path, env, start_response, body):
        """UnitOfWork REST endpoints, delegated from the Worker"""
        if uri_path == '/pop/init':
            # initialize the Population subset on this shard
            Greenlet(self.pop_init, worker, env, start_response, body).start()
            return True
        elif uri_path == '/pop/gen':
            # create generation 0 in this shard
            Greenlet(self.pop_gen, worker, env, start_response, body).start()
            return True
        elif uri_path == '/pop/hist':
            # calculate a partial histogram for the fitness distribution
            Greenlet(self.pop_hist, worker, env, start_response, body).start()
            return True
        elif uri_path == '/pop/next':
            # attempt to run another generation
            Greenlet(self.pop_next, worker, env, start_response, body).start()
            return True
        elif uri_path == '/pop/enum':
            # enumerate the Individuals in this shard of the Population
            Greenlet(self.pop_enum, worker, env, start_response, body).start()
            return True
        elif uri_path == '/pop/reify':
            # test/add a new Individual into the Population (birth)
            Greenlet(self.pop_reify, worker, env, start_response, body).start()
            return True
        else:
            return False

    ######################################################################
    ## GA-specific REST endpoints implemented as gevent coroutines

    def pop_init (self, *args, **kwargs):
        """initialize a Population of unique Individuals on this shard"""
        worker = args[0]
        payload, start_response, body = worker.get_response_context(args[1:])

        if worker.auth_request(payload, start_response, body):
            self.set_ring(worker.shard_id, worker.ring)
            worker.prep_task_queue()

            start_response('200 OK', [('Content-Type', 'text/plain')])
            body.put("Bokay\r\n")
            body.put(StopIteration)

    def pop_gen (self, *args, **kwargs):
        """create generation 0 of Individuals in this shard of the Population"""
        worker = args[0]
        payload, start_response, body = worker.get_response_context(args[1:])

        if worker.auth_request(payload, start_response, body):
            with worker.wrap_task_event():
                # HTTP response first, then initiate long-running task
                start_response('200 OK', [('Content-Type', 'text/plain')])
                body.put("Bokay\r\n")
                body.put(StopIteration)

                self.populate(0)

    def pop_hist (self, *args, **kwargs):
        """calculate a partial histogram for the fitness distribution"""
        worker = args[0]
        payload, start_response, body = worker.get_response_context(args[1:])

        if worker.auth_request(payload, start_response, body):
            start_response('200 OK', [('Content-Type', 'application/json')])
            body.put(dumps({ "total_indiv": self.total_indiv, "hist": self.get_part_hist() }))
            body.put("\r\n")
            body.put(StopIteration)

    def pop_next (self, *args, **kwargs):
        """iterate N times or until a 'good enough' solution is found"""
        worker = args[0]
        payload, start_response, body = worker.get_response_context(args[1:])

        if worker.auth_request(payload, start_response, body):
            with worker.wrap_task_event():
                # HTTP response first, then initiate long-running task
                start_response('200 OK', [('Content-Type', 'text/plain')])
                body.put("Bokay\r\n")
                body.put(StopIteration)

                current_gen = payload["current_gen"]
                fitness_cutoff = payload["fitness_cutoff"]
                self.next_generation(current_gen, fitness_cutoff)

    def pop_enum (self, *args, **kwargs):
        """enumerate the Individuals in this shard of the Population"""
        worker = args[0]
        payload, start_response, body = worker.get_response_context(args[1:])

        if worker.auth_request(payload, start_response, body):
            fitness_cutoff = payload["fitness_cutoff"]

            start_response('200 OK', [('Content-Type', 'application/json')])
            body.put(dumps(self.enum(fitness_cutoff)))
            body.put("\r\n")
            body.put(StopIteration)

    def pop_reify (self, *args, **kwargs):
        """test/add a newly generated Individual into the Population (birth)"""
        worker = args[0]
        payload, start_response, body = worker.get_response_context(args[1:])

        if worker.auth_request(payload, start_response, body):
            worker.put_task_queue(payload)

            start_response('200 OK', [('Content-Type', 'text/plain')])
            body.put("Bokay\r\n")
            body.put(StopIteration)

    ######################################################################
    ## Individual lifecycle within the local subset of the Population

    def populate (self, current_gen):
        """initialize the population"""
        for _ in xrange(self.uow_factory.n_pop):
            # constructor pattern
            indiv = self.indiv_class()
            indiv.populate(current_gen, self.uow_factory.generate_features())

            # add the generated Individual to the Population
            # failure semantics: must filter nulls from initial population
            self.reify(indiv)

    def reify (self, indiv):
        """test/add a newly generated Individual into the Population (birth)"""
        neighbor_shard_id = None
        shard_uri = None

        if self._hash_ring:
            neighbor_shard_id = self._hash_ring.get_node(indiv.key)

            if neighbor_shard_id != self._shard_id:
                shard_uri = self._shard_dict[neighbor_shard_id]

        # distribute the tasks in this phase throughout the HashRing,
        # using a remote task_queue with synchronization based on a
        # barrier pattern

        if shard_uri:
            msg = { "key": indiv.key, "gen": indiv.gen, "feature_set": loads(indiv.get_json_feature_set()) }
            lines = post_distrib_rest(self.prefix, neighbor_shard_id, shard_uri, "pop/reify", msg)
            return False
        else:
            return self._reify_locally(indiv)

    def receive_reify (self, key, gen, feature_set):
        """test/add a received reify request """
        indiv = self.indiv_class()
        indiv.populate(gen, feature_set)
        self._reify_locally(indiv)

    def _reify_locally (self, indiv):
        """test/add a newly generated Individual into the Population locally (birth)"""
        if not (indiv.key in self._trie):
            self._trie[indiv.key] = 1
            self.total_indiv += 1

            # potentially an expensive operation, deferred until remote reification
            indiv.get_fitness(self.uow_factory, force=True)
            self._shard[indiv.key] = indiv

            return True
        else:
            return False

    def evict (self, indiv):
        """remove an Individual from the Population (death)"""
        if indiv.key in self._shard:
            # Individual only needs to be removed locally
            del self._shard[indiv.key]

            # NB: serialize to disk (write behinds)
            url = self._get_storage_path(indiv)

    def get_part_hist (self):
        """tally counts for the partial histogram of the fitness distribution"""
        l = [ round(indiv.get_fitness(self.uow_factory, force=False), self.uow_factory.hist_granularity) for indiv in self._shard.values() ]
        return dict(Counter(l))

    def get_fitness_cutoff (self, hist_items):
        """determine fitness cutoff (bin lower bounds) for the parent selection filter"""
        logging.debug("fit: %s", hist_items)

        n_indiv = sum([ count for bin, count in hist_items ])
        part_sum = 0
        break_next = False

        for bin, count in hist_items:
            if break_next:
                break

            part_sum += count
            percentile = part_sum / float(n_indiv)
            break_next = percentile >= self.uow_factory.selection_rate

        logging.debug("fit: percentile %f part_sum %d n_indiv %d bin %f", percentile, part_sum, n_indiv, bin)
        return bin

    def _get_storage_path (self, indiv):
        """create a path for durable storage of an Individual"""
        return self.prefix + "/" + indiv.key

    def _boost_diversity (self, current_gen, indiv):
        """randomly select other individuals and mutate them, to promote genetic diversity"""
        if self.uow_factory.mutation_rate > random():
            indiv.mutate(self, current_gen, self.uow_factory)
        elif len(self._shard.values()) >= 3:
            # NB: ensure that at least three parents remain in each
            # shard per generation
            self.evict(indiv)

    def _select_parents (self, current_gen, fitness_cutoff):
        """select the parents for the next generation"""
        partition = map(lambda x: (round(x.get_fitness(), self.uow_factory.hist_granularity) > fitness_cutoff, x), self._shard.values())
        good_fit = map(lambda x: x[1], filter(lambda x: x[0], partition))
        poor_fit = map(lambda x: x[1], filter(lambda x: not x[0], partition))

        # randomly select other individuals to promote genetic
        # diversity, while removing the remnant
        for indiv in poor_fit:
            self._boost_diversity(current_gen, indiv)

        return self._shard.values()

    def next_generation (self, current_gen, fitness_cutoff):
        """select/mutate/crossover parents to produce a new generation"""
        parents = self._select_parents(current_gen, fitness_cutoff)

        for _ in xrange(self.uow_factory.n_pop - len(parents)):
            f, m = sample(parents, 2)
            success = f.breed(self, current_gen, m, self.uow_factory)

        # backfill to replenish / avoid the dreaded Population collapse
        new_count = 0

        for _ in xrange(self.uow_factory.n_pop - len(self._shard.values())):
            # constructor pattern
            indiv = self.indiv_class()
            indiv.populate(current_gen, self.uow_factory.generate_features())
            self.reify(indiv)

        logging.info("gen\t%d\tshard\t%s\tsize\t%d\ttotal\t%d", current_gen, self._shard_id, len(self._shard.values()), self.total_indiv)

    def test_termination (self, current_gen, hist):
        """evaluate the terminating condition for this generation and report progress"""
        return self.uow_factory.test_termination(current_gen, hist, self.total_indiv)

    def enum (self, fitness_cutoff):
        """enum all Individuals that exceed the given fitness cutoff"""
        return [[ "indiv", "%0.4f" % indiv.get_fitness(), str(indiv.gen), indiv.get_json_feature_set() ]
                for indiv in filter(lambda x: x.get_fitness() >= fitness_cutoff, self._shard.values()) ]

class Individual (object):
    def __init__ (self):
        """create an Individual member of the Population"""
        self.gen = None
        self.key = None
        self._feature_set = None
        self._fitness = None

    def get_fitness (self, uow_factory=None, force=False):
        """determine the fitness ranging [0.0, 1.0]; higher is better"""
        if uow_factory and uow_factory.use_force(force):
            # potentially the most expensive operation, deferred with careful consideration
            self._fitness = uow_factory.get_fitness(self._feature_set)

        return self._fitness

    def get_json_feature_set (self):
        """dump the feature set as a JSON string"""
        return dumps(tuple(self._feature_set))

    def populate (self, gen, feature_set):
        """populate the instance variables"""
        self.gen = gen
        self._feature_set = feature_set

        # create a unique key using a SHA-3 digest of the JSON representing this feature set
        m = sha224()
        m.update(self.get_json_feature_set())
        self.key = unicode(m.hexdigest())

    def mutate (self, pop, gen, uow_factory):
        """attempt to mutate the feature set"""
        # constructor pattern
        mutant = self.__class__()
        mutant.populate(gen, uow_factory.mutate_features(self._feature_set))

        # add the mutant Individual to the Population, but remove its prior self
        # failure semantics: ignore, mutation rate is approx upper bounds
        if pop.reify(mutant):
            pop.evict(self)
            return True
        else:
            return False

    def breed (self, pop, gen, mate, uow_factory):
        """breed with a mate to produce a child"""
        # constructor pattern
        child = self.__class__()
        child.populate(gen, uow_factory.breed_features(self._feature_set, mate._feature_set))

        # add the child Individual to the Population
        # failure semantics: ignore, the count will rebalance over the hash ring
        return pop.reify(child)

if __name__=='__main__':
    ## test GA in standalone-mode, without distributed services

    # parse command line options
    if len(sys.argv) < 2:
        uow_name = "uow.UnitOfWorkFactory"
    else:
        uow_name = sys.argv[1]

    uow_factory = instantiate_class(uow_name)

    # initialize a Population of unique Individuals at generation 0
    uow = uow_factory.instantiate_uow(uow_name, "/tmp/exelixi")
    uow.populate(uow.current_gen)
    fitness_cutoff = 0

    # iterate N times or until a "good enough" solution is found
    while uow.current_gen < uow_factory.n_gen:
        hist = uow.get_part_hist()
        hist_items = map(lambda x: (float(x[0]), x[1],), sorted(hist.items(), reverse=True))

        if uow.test_termination(uow.current_gen, hist_items):
            break

        fitness_cutoff = uow.get_fitness_cutoff(hist_items)
        uow.next_generation(uow.current_gen, fitness_cutoff)

        uow.current_gen += 1

    # report summary
    for x in sorted(uow.enum(fitness_cutoff), reverse=True):
        print "\t".join(x)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cbn.Lib.Authentication;
using Cbn.Lib.Configure;

namespace Cbn.Sample.Core
{
    public class CbnConfig : IConfig, IAuthenticationConfig
    {
        public string ClientId { get; set; }
        public string RedirectUri { get; set; }
        public string ClientSecret { get; set; }
        public string TokenUrl { get; set; }
        public string TokenInfoUrl { get; set; }
        public string AuthUrl { get; set; }
        public string Scope { get; set; }
        public bool CanRegisterNewUser { get; set; }
        public string BatchExecutePath { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
@implementation FeedListModulePresenter

#pragma mark - Методы FeedListModuleModuleInput

- (void)configureModule
{
    // Стартовая конфигурация модуля, не привязанная к состоянию view
}

#pragma mark - Методы FeedListModuleViewOutput

- (void)didTriggerViewReadyEvent
{
    [self.view setupInitialState];
}

#pragma mark - Методы FeedListModuleInteractorOutput

@end


text:
package org.cloudfoundry.receptor.actions;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * @author Mark Fisher
 */
public class UploadAction implements Action {

	private String artifact;

	private String to;

	private String from;

	private String user = "vcap";

	@JsonProperty("log_source")
	private String logSource;

	public String getArtifact() {
		return artifact;
	}

	public void setArtifact(String artifact) {
		this.artifact = artifact;
	}

	public String getTo() {
		return to;
	}

	public void setTo(String to) {
		this.to = to;
	}

	public String getFrom() {
		return from;
	}

	public void setFrom(String from) {
		this.from = from;
	}

	public String getUser() {
		return user;
	}

	public void setUser(String user) {
		this.user = user;
	}

	public String getLogSource() {
		return logSource;
	}

	public void setLogSource(String logSource) {
		this.logSource = logSource;
	}

	@Override
	public String toString() {
		return "UploadAction [artifact=" + artifact + ", to=" + to + ", from="
				+ from + ", user=" + user + ", logSource=" + logSource + "]";
	}
}


text:
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you 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.

"""

import os
import tarfile

from resource_management.libraries.script.script import Script
from resource_management.libraries.functions import conf_select, tar_archive
from resource_management.libraries.functions import hdp_select
from resource_management.libraries.functions.check_process_status import check_process_status
from resource_management.libraries.functions import format
from resource_management.libraries.functions.version import compare_versions, format_hdp_stack_version
from resource_management.libraries.functions import conf_select
from resource_management.libraries.functions import hdp_select
from resource_management.libraries.functions import Direction
from resource_management.libraries.functions.security_commons import build_expectations, \
  cached_kinit_executor, validate_security_config_properties, get_params_from_filesystem, \
  FILE_TYPE_XML
from resource_management.core.resources.system import File, Execute, Directory, Link
from resource_management.core.resources.service import Service
from resource_management.core.logger import Logger

from ambari_commons import OSConst, OSCheck
from ambari_commons.os_family_impl import OsFamilyFuncImpl, OsFamilyImpl

if OSCheck.is_windows_family():
  from resource_management.libraries.functions.windows_service_utils import check_windows_service_status

import upgrade
from knox import knox
from knox_ldap import ldap
from setup_ranger_knox import setup_ranger_knox

class KnoxGateway(Script):
  def install(self, env):
    import params
    env.set_params(params)
    self.install_packages(env)

    File(os.path.join(params.knox_conf_dir, 'topologies', 'sandbox.xml'),
         action = "delete",
    )

  def configure(self, env):
    import params
    env.set_params(params)
    knox()
    ldap()

  def configureldap(self, env):
    import params
    env.set_params(params)
    ldap()

@OsFamilyImpl(os_family=OSConst.WINSRV_FAMILY)
class KnoxGatewayWindows(KnoxGateway):
  def start(self, env):
    import params
    env.set_params(params)
    self.configure(env)
    # setup_ranger_knox(env)
    Service(params.knox_gateway_win_service_name, action="start")

  def stop(self, env):
    import params
    env.set_params(params)
    Service(params.knox_gateway_win_service_name, action="stop")

  def status(self, env):
    import status_params
    env.set_params(status_params)
    check_windows_service_status(status_params.knox_gateway_win_service_name)

  def startdemoldap(self, env):
    import params
    env.set_params(params)
    self.configureldap(env)
    Service(params.knox_ldap_win_service_name, action="start")

  def stopdemoldap(self, env):
    import params
    env.set_params(params)
    Service(params.knox_ldap_win_service_name, action="stop")

@OsFamilyImpl(os_family=OsFamilyImpl.DEFAULT)
class KnoxGatewayDefault(KnoxGateway):
  def get_stack_to_component(self):
    return {"HDP": "knox-server"}

  def pre_rolling_restart(self, env):
    import params
    env.set_params(params)
    if params.version and compare_versions(format_hdp_stack_version(params.version), '2.2.0.0') >= 0:

      absolute_backup_dir = None
      if params.upgrade_direction and params.upgrade_direction == Direction.UPGRADE:
        Logger.info("Backing up directories. Initial conf folder: %s" % os.path.realpath(params.knox_conf_dir))

        # This will backup the contents of the conf directory into /tmp/knox-upgrade-backup/knox-conf-backup.tar
        absolute_backup_dir = upgrade.backup_data()

      # conf-select will change the symlink to the conf folder.
      conf_select.select(params.stack_name, "knox", params.version)
      hdp_select.select("knox-server", params.version)

      # Extract the tar of the old conf folder into the new conf directory
      if absolute_backup_dir is not None and params.upgrade_direction and params.upgrade_direction == Direction.UPGRADE:
        conf_tar_source_path = os.path.join(absolute_backup_dir, upgrade.BACKUP_CONF_ARCHIVE)
        if os.path.exists(conf_tar_source_path):
          extract_dir = os.path.realpath(params.knox_conf_dir)
          conf_tar_dest_path = os.path.join(extract_dir, upgrade.BACKUP_CONF_ARCHIVE)
          Logger.info("Copying %s into %s file." % (upgrade.BACKUP_CONF_ARCHIVE, conf_tar_dest_path))
          Execute(('cp', conf_tar_source_path, conf_tar_dest_path),
                  sudo = True,
          )

          tar_archive.untar_archive(conf_tar_source_path, extract_dir)

          File(conf_tar_dest_path,
               action = "delete",
          )

  def start(self, env, rolling_restart=False):
    import params
    env.set_params(params)
    self.configure(env)
    daemon_cmd = format('{knox_bin} start')
    no_op_test = format('ls {knox_pid_file} >/dev/null 2>&1 && ps -p `cat {knox_pid_file}` >/dev/null 2>&1')
    setup_ranger_knox(rolling_upgrade=rolling_restart)
    # Used to setup symlink, needed to update the knox managed symlink, in case of custom locations
    if os.path.islink(params.knox_managed_pid_symlink):
      Link(params.knox_managed_pid_symlink,
           to = params.knox_pid_dir,
      )

    Execute(daemon_cmd,
            user=params.knox_user,
            environment={'JAVA_HOME': params.java_home},
            not_if=no_op_test
    )

  def stop(self, env, rolling_restart=False):
    import params
    env.set_params(params)
    daemon_cmd = format('{knox_bin} stop')
    Execute(daemon_cmd,
            environment={'JAVA_HOME': params.java_home},
            user=params.knox_user,
    )
    File(params.knox_pid_file,
         action="delete",
    )

  def status(self, env):
    import status_params
    env.set_params(status_params)
    check_process_status(status_params.knox_pid_file)

  def startdemoldap(self, env):
    import params
    env.set_params(params)
    self.configureldap(env)
    daemon_cmd = format('{ldap_bin} start')
    no_op_test = format('ls {ldap_pid_file} >/dev/null 2>&1 && ps -p `cat {ldap_pid_file}` >/dev/null 2>&1')
    Execute(daemon_cmd,
            user=params.knox_user,
            environment={'JAVA_HOME': params.java_home},
            not_if=no_op_test
    )

  def stopdemoldap(self, env):
    import params
    env.set_params(params)
    self.configureldap(env)
    daemon_cmd = format('{ldap_bin} stop')
    Execute(daemon_cmd,
            environment={'JAVA_HOME': params.java_home},
            user=params.knox_user,
            )
    File(params.ldap_pid_file,
      action = "delete"
    )

  def security_status(self, env):
    import status_params
    env.set_params(status_params)

    if status_params.security_enabled:
      expectations = {}
      expectations.update(build_expectations(
        'krb5JAASLogin',
        None,
        ['keytab', 'principal'],
        None
      ))
      expectations.update(build_expectations(
        'gateway-site',
        {
          "gateway.hadoop.kerberos.secured" : "true"
        },
        None,
        None
      ))

      security_params = {
        "krb5JAASLogin":
          {
            'keytab': status_params.knox_keytab_path,
            'principal': status_params.knox_principal_name
          }
      }
      security_params.update(get_params_from_filesystem(status_params.knox_conf_dir,
        {"gateway-site.xml" : FILE_TYPE_XML}))

      result_issues = validate_security_config_properties(security_params, expectations)
      if not result_issues:  # If all validations passed successfully
        try:
          # Double check the dict before calling execute
          if ( 'krb5JAASLogin' not in security_params
               or 'keytab' not in security_params['krb5JAASLogin']
               or 'principal' not in security_params['krb5JAASLogin']):
            self.put_structured_out({"securityState": "UNSECURED"})
            self.put_structured_out({"securityIssuesFound": "Keytab file and principal are not set."})
            return

          cached_kinit_executor(status_params.kinit_path_local,
                                status_params.knox_user,
                                security_params['krb5JAASLogin']['keytab'],
                                security_params['krb5JAASLogin']['principal'],
                                status_params.hostname,
                                status_params.temp_dir)
          self.put_structured_out({"securityState": "SECURED_KERBEROS"})
        except Exception as e:
          self.put_structured_out({"securityState": "ERROR"})
          self.put_structured_out({"securityStateErrorInfo": str(e)})
      else:
        issues = []
        for cf in result_issues:
          issues.append("Configuration file %s did not pass the validation. Reason: %s" % (cf, result_issues[cf]))
        self.put_structured_out({"securityIssuesFound": ". ".join(issues)})
        self.put_structured_out({"securityState": "UNSECURED"})
    else:
      self.put_structured_out({"securityState": "UNSECURED"})

if __name__ == "__main__":
  KnoxGateway().execute()


text:
package com.example.excadmin.tvcleanarchitecture.presentation.ui.viewpresenter;

import android.content.res.Resources;
import android.graphics.Color;
import android.support.v17.leanback.widget.Presenter;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.excadmin.tvcleanarchitecture.R;
import com.example.excadmin.tvcleanarchitecture.presentation.ui.fragment.MainFragment;

public class GridItemPresenter extends Presenter {
    private final MainFragment mainFragment;

    public GridItemPresenter(MainFragment mainFragment) {
        this.mainFragment = mainFragment;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent) {
        TextView view = new TextView(parent.getContext());

        Resources res = parent.getResources();
        int width = res.getDimensionPixelSize(R.dimen.grid_item_width);
        int height = res.getDimensionPixelSize(R.dimen.grid_item_height);

        view.setLayoutParams(new ViewGroup.LayoutParams(width, height));
        view.setFocusable(true);
        view.setFocusableInTouchMode(true);
        view.setBackgroundColor(ContextCompat.getColor(parent.getContext(),
                R.color.default_background));
        view.setTextColor(Color.WHITE);
        view.setGravity(Gravity.CENTER);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder viewHolder, Object item) {
        ((TextView) viewHolder.view).setText((String) item);
    }

    @Override
    public void onUnbindViewHolder(ViewHolder viewHolder) {
    }
}


text:
package com.bt.pi.core.scribe;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.argThat;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatcher;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.context.ApplicationContext;

import rice.environment.Environment;
import rice.p2p.commonapi.Application;
import rice.p2p.commonapi.Endpoint;
import rice.p2p.commonapi.Id;
import rice.p2p.commonapi.Message;
import rice.p2p.commonapi.NodeHandle;
import rice.p2p.commonapi.rawserialization.InputBuffer;
import rice.p2p.commonapi.rawserialization.MessageDeserializer;
import rice.p2p.commonapi.rawserialization.RawMessage;
import rice.p2p.scribe.ScribeContent;
import rice.p2p.scribe.ScribeMultiClient;
import rice.p2p.scribe.Topic;
import rice.p2p.scribe.messaging.AnycastMessage;
import rice.p2p.scribe.messaging.DropMessage;
import rice.p2p.scribe.messaging.SubscribeAckMessage;
import rice.p2p.scribe.messaging.SubscribeFailedMessage;
import rice.p2p.scribe.messaging.SubscribeMessage;
import rice.p2p.scribe.messaging.UnsubscribeMessage;
import rice.pastry.PastryNode;
import rice.pastry.PastryNodeFactory;
import rice.pastry.direct.DirectNodeHandle;
import rice.pastry.direct.DirectPastryNodeFactory;
import rice.pastry.direct.EuclideanNetwork;
import rice.pastry.direct.NetworkSimulator;
import rice.pastry.standard.RandomNodeIdFactory;

import com.bt.pi.core.entity.EntityMethod;
import com.bt.pi.core.id.KoalaIdFactory;
import com.bt.pi.core.id.PId;
import com.bt.pi.core.scope.NodeScope;
import com.bt.pi.core.scribe.content.KoalaScribeContent;
import com.bt.pi.core.scribe.content.WrappedScribeContentMessage;
import com.bt.pi.core.scribe.content.WrappedScribeContentMessageType;

@RunWith(PowerMockRunner.class)
@PrepareForTest(WrappedScribeContentMessage.class)
@PowerMockIgnore( { "org.apache.commons.logging.*", "org.apache.log4j.*" })
public class KoalaScribeImplTest {
    private static final String DUMMY_NETWORK = "dummyNetwork";
    private static final String TOPIC_ID = "topicId";

    @Rule
    public TestName testName = new TestName();

    private KoalaScribeImpl scribe;
    private ScribeMultiClient scribeClient;
    private KoalaIdFactory koalaIdFactory;
    private Topic topic;
    private KoalaScribeContent scribeContent;
    private Id id;
    private Id topicId;
    private Endpoint endpoint;
    private WrappedScribeContentMessage wrappedScribeContentMessage;
    private NodeHandle nodeHandle;
    private InputBuffer inputBuffer;
    private MessageDeserializer messageDeserializer;
    private ApplicationContext applicationContext;

    @Before
    public void before() throws Exception {
        scribeClient = mock(ScribeMultiClient.class);
        topic = mock(Topic.class);
        id = mock(Id.class);
        topicId = mock(Id.class);
        endpoint = mock(Endpoint.class);
        scribeContent = mock(KoalaScribeContent.class);
        applicationContext = mock(ApplicationContext.class);
        wrappedScribeContentMessage = new WrappedScribeContentMessage(mock(NodeHandle.class), topic, WrappedScribeContentMessageType.ANYCAST, EntityMethod.UPDATE, "json", "transaction-id");

        koalaIdFactory = mock(KoalaIdFactory.class);
        when(koalaIdFactory.buildIdFromToString(TOPIC_ID)).thenReturn(topicId);

        scribe = spy(new KoalaScribeImpl(setupPastryNode(), applicationContext));
        scribe.setKoalaIdFactory(koalaIdFactory);

        messageDeserializer = scribe.getEndpoint().getDeserializer();
    }

    private PastryNode setupPastryNode() throws Exception {
        Environment environment = new Environment();
        NetworkSimulator<DirectNodeHandle, RawMessage> simulator = new EuclideanNetwork<DirectNodeHandle, RawMessage>(environment);
        PastryNodeFactory factory = new DirectPastryNodeFactory(new RandomNodeIdFactory(environment), simulator, environment);
        PastryNode pastryNode = spy(factory.newNode());

        if (testName.getMethodName().equals("testSendScribeMessageFromRandomOrigin"))
            doReturn(endpoint).when(pastryNode).buildEndpoint(isA(Application.class), isA(String.class));

        return pastryNode;
    }

    @Before
    public void setupForMessageDeserializerTests() throws Exception {
        nodeHandle = mock(NodeHandle.class);
        inputBuffer = mock(InputBuffer.class);
        when(inputBuffer.readByte()).thenReturn((byte) 1);
        when(inputBuffer.readShort()).thenReturn((short) 1);
        when(inputBuffer.readUTF()).thenReturn(WrappedScribeContentMessageType.ANYCAST.toString());
    }

    @Test
    public void testSubscribeToTopic() {
        // setup
        doReturn(topic).when(scribe).createTopic(DUMMY_NETWORK);
        doNothing().when(scribe).subscribe(topic, scribeClient);

        // act
        Topic result = scribe.subscribeToTopic(DUMMY_NETWORK, scribeClient);

        // assert
        assertThat(result, equalTo(topic));
        verify(scribe).subscribe(topic, scribeClient);
    }

    @Test
    public void testPublishContent() {
        // setup
        doNothing().when(scribe).publish(topic, scribeContent);

        // act
        scribe.publishContent(topic, scribeContent);

        // assert
        verify(scribe).publish(topic, scribeContent);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testPublishContentNullTopic() {
        // act
        scribe.publishContent(null, scribeContent);
    }

    @Test
    public void testSendAnycast() {
        // setup
        doNothing().when(scribe).anycast(topic, scribeContent);

        // act
        scribe.sendAnycast(topic, scribeContent);

        // assert
        verify(scribe).anycast(topic, scribeContent);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testSendAnycastNullTopic() {
        // act
        scribe.sendAnycast(null, scribeContent);
    }

    @Test
    public void testCreateTopic() {
        // setup
        PId topicPId = mock(PId.class);
        when(topicPId.forLocalScope(eq(NodeScope.REGION))).thenReturn(topicPId);
        when(koalaIdFactory.buildPId(DUMMY_NETWORK)).thenReturn(topicPId);
        when(koalaIdFactory.buildId(topicPId)).thenReturn(id);

        // act
        Topic result = scribe.createTopic(DUMMY_NETWORK);

        // assert
        assertThat(result.getId(), equalTo(id));
    }

    @Test
    public void testSendScribeMessageFromRandomOrigin() throws Exception {
        // setup
        PId topicPId = mock(PId.class);
        when(topicPId.forLocalScope(eq(NodeScope.REGION))).thenReturn(topicPId);
        when(koalaIdFactory.buildId(topicPId)).thenReturn(id);

        // act
        scribe.sendScribeMessageFromRandomOrigin(topicPId, wrappedScribeContentMessage);

        // assert
        verify(endpoint).route(id, wrappedScribeContentMessage, null);
    }

    @Test
    public void testDeliver() throws Exception {
        // setup
        doNothing().when(scribe).anycast(eq(topic), isA(ScribeContent.class));

        // act
        scribe.deliver(id, wrappedScribeContentMessage);

        // assert
        verify(scribe).anycast(eq(topic), argThat(new ArgumentMatcher<KoalaScribeContent>() {
            @Override
            public boolean matches(Object argument) {
                return ((KoalaScribeContent) argument).getJsonData().equals("json");
            }
        }));
    }

    @Test
    public void testMessageDeserializerWrappedMessage() throws Exception {// setup
        PowerMockito.mockStatic(WrappedScribeContentMessage.class);
        when(WrappedScribeContentMessage.build(isA(InputBuffer.class), isA(Endpoint.class))).thenReturn(wrappedScribeContentMessage);

        // act
        Message message = messageDeserializer.deserialize(inputBuffer, wrappedScribeContentMessage.getType(), 0, nodeHandle);

        // assert
        assertThat(message instanceof WrappedScribeContentMessage, is(true));
    }

    @Test
    public void testMessageDeserializerAnycastMessage() throws Exception {
        // act
        Message message = messageDeserializer.deserialize(inputBuffer, AnycastMessage.TYPE, 0, nodeHandle);

        // assert
        assertThat(message instanceof AnycastMessage, is(true));
    }

    @Test
    public void testMessageDeserializerSubscribeMessage() throws Exception {
        // act
        Message message = messageDeserializer.deserialize(inputBuffer, SubscribeMessage.TYPE, 0, nodeHandle);

        // assert
        assertThat(message instanceof SubscribeMessage, is(true));
    }

    @Test
    public void testMessageDeserializerSubscribeAckMessage() throws Exception {
        // act
        Message message = messageDeserializer.deserialize(inputBuffer, SubscribeAckMessage.TYPE, 0, nodeHandle);

        // assert
        assertThat(message instanceof SubscribeAckMessage, is(true));
    }

    @Test
    public void testMessageDeserializerSubscribeFailedMessage() throws Exception {
        // act
        Message message = messageDeserializer.deserialize(inputBuffer, SubscribeFailedMessage.TYPE, 0, nodeHandle);

        // assert
        assertThat(message instanceof SubscribeFailedMessage, is(true));
    }

    @Test
    public void testMessageDeserializerDropMessage() throws Exception {
        // setup
        when(inputBuffer.readByte()).thenReturn((byte) 0);

        // act
        Message message = messageDeserializer.deserialize(inputBuffer, DropMessage.TYPE, 0, nodeHandle);

        // assert
        assertThat(message instanceof DropMessage, is(true));
    }

    @Test
    public void testMessageDeserializerUnsubscribeMessage() throws Exception {
        // act
        Message message = messageDeserializer.deserialize(inputBuffer, UnsubscribeMessage.TYPE, 0, nodeHandle);

        // assert
        assertThat(message instanceof UnsubscribeMessage, is(true));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testMessageDeserializerUnknownType() throws Exception {
        // act
        messageDeserializer.deserialize(inputBuffer, (short) 55, 0, nodeHandle);
    }

    @Test
    public void testThatAnycastFailureFiresOffAnApplicationEvent() throws Exception {
        // setup
        rice.pastry.NodeHandle source = mock(rice.pastry.NodeHandle.class);
        when(topic.getId()).thenReturn(topicId);
        Message message = new AnycastMessage(source, topic, scribeContent);

        // act
        scribe.deliver(topicId, message);

        // assert
        verify(applicationContext).publishEvent(argThat(new ArgumentMatcher<AnycastFailureEvent>() {
            @Override
            public boolean matches(Object argument) {
                AnycastFailureEvent anycastFailureEvent = (AnycastFailureEvent) argument;
                assertThat(anycastFailureEvent.getTopicId(), equalTo(topicId));
                assertThat(anycastFailureEvent.getKoalaScribeContent(), equalTo(scribeContent));
                return true;
            }
        }));
    }
}


text:
using System.Collections.Generic;
using System.Text;
using FlatRedBall.Glue.CodeGeneration.CodeBuilder;
using FlatRedBall.Glue.SaveClasses;
using FlatRedBall.Glue.Parsing;
using FlatRedBall.IO;
using FlatRedBall.Content.Instructions;
using FlatRedBall.Glue.Controls;
using FlatRedBall.Instructions;
using FlatRedBall.Glue.SaveClasses.Helpers;
using System;
using System.Linq;
using FlatRedBall.Glue.Elements;
using FlatRedBall.Glue.TypeConversions;
using Microsoft.Xna.Framework.Graphics;

namespace FlatRedBall.Glue.CodeGeneration
{
    public partial class StateCodeGenerator : ElementComponentCodeGenerator
    {

        #region Create Inner Class

        private static ICodeBlock CreateClassForStateCategory(ICodeBlock currentBlock, List<StateSave> statesForThisCategory, StateSaveCategory category, GlueElement element)
        {
            string categoryClassName = category?.Name ?? "VariableState";

            // Update August 18, 2021
            // We want to generate the
            // class even if it doesn't
            // have any states. This allows
            // GView to inject states dynamically.
            //if (statesForThisCategory.Count != 0)
            string prefix = "public";

            string postfix = null;
            if (IsStateDefinedInBase(element, categoryClassName))
            {
                postfix = $" : {element.BaseElement.Replace("\\", ".")}.{categoryClassName}";
            }

            currentBlock = currentBlock.Class(prefix, categoryClassName, postfix);

            currentBlock.Line($"public string Name;");

            var includedVariables = element.CustomVariables.Where(item =>
            {
                return ShouldIncludeVariable(category, element, item);
            })
                .ToArray();

            foreach (var variable in includedVariables)
            {
                string type = variable.Type;

                if (variable.GetIsFile())
                {
                    type = "string";
                }
                else if (!string.IsNullOrEmpty(variable.OverridingPropertyType))
                {
                    type = variable.OverridingPropertyType;
                }
                else
                {
                    type = CustomVariableCodeGenerator.GetMemberTypeFor(variable, element);
                }
                currentBlock.Line($"public {type} {variable.Name};");
            }

            CreatePredefinedStateInstances(currentBlock, statesForThisCategory, element, categoryClassName, includedVariables);

            currentBlock.Line($"public static Dictionary<string, {categoryClassName}> AllStates = new Dictionary<string, {categoryClassName}>");
            var dictionaryBlock = currentBlock.Block();
            dictionaryBlock.PostCodeLines.Add(new CodeLine(";"));

            for (int i = 0; i < statesForThisCategory.Count; i++)
            {
                var state = statesForThisCategory[i];
                dictionaryBlock.Line("{\"" + state.Name + "\", " + state.Name + "},");
            }

            currentBlock = currentBlock.End();

            return currentBlock;
        }

        private static bool ShouldIncludeVariable(StateSaveCategory category, GlueElement element, CustomVariable item)
        {
            if (category == null)
            {
                var isState = item.GetIsVariableState(element);

                // states setting other states causes lots of problems. Since uncategorized states can't exclude variables in the StateData world, we just won't
                // set other states
                return !isState;
            }
            else
            {
                return category?.ExcludedVariables.Contains(item.Name) == false;
            }
        }

        private static void CreatePredefinedStateInstances(ICodeBlock currentBlock, List<StateSave> statesForThisCategory, GlueElement element, string categoryClassName, CustomVariable[] includedVariables)
        {
            for (int i = 0; i < statesForThisCategory.Count; i++)
            {
                var state = statesForThisCategory[i];
                currentBlock.Line($"public static {categoryClassName} {state.Name} = new {categoryClassName}()");

                var variableBlock = currentBlock.Block();

                variableBlock.Line($"Name = \"{state.Name}\",");

                foreach (var variable in includedVariables)
                {
                    var instruction = state.InstructionSaves.FirstOrDefault(item => item.Member == variable.Name);

                    var instructionValue = instruction?.Value;

                    var valueToSet = instructionValue ?? variable.DefaultValue;

                    var shouldAssign = valueToSet != null;

                    if(shouldAssign && valueToSet is string && ((string)valueToSet) == string.Empty)
                    {
                        if(variable.Type == "bool" ||
                            variable.Type == "int" ||
                            variable.Type == "float" ||
                            variable.Type == "long" ||
                            variable.Type == "byte" ||
                            variable.Type == "double" ||
                            variable.Type == "decimal"
                            )
                        {
                            shouldAssign = false;
                        }
                    }

                    if(shouldAssign && instructionValue is string asString && variable.GetIsVariableState(element) == true && string.IsNullOrEmpty(asString))
                    {
                        shouldAssign = false;
                    }

                    if (shouldAssign)
                    {
                        var rightSide = GetRightSideAssignmentValueAsString(element, variable.Name, valueToSet);
                        var matchingVariable = element.GetCustomVariableRecursively(variable.Name);
                        if (matchingVariable?.GetIsFile() == true)
                        {
                            // If it's a file we are only going to reference the file name here as to not preload the file
                            rightSide = $"\"{rightSide}\"";
                        }

                        variableBlock.Line($"{variable.Name} = {rightSide},");
                    }
                }
                variableBlock.End().Line(";");
            }
        }

        #endregion

        #region Generating Fields / Properties

        // Generates the fields AND PROPERTIES even though it's only called GenerateFields
        public override ICodeBlock GenerateFields(ICodeBlock codeBlock, SaveClasses.IElement element)
        {

            var currentBlock = codeBlock;

            if (element.HasStates || element.StateCategoryList.Count > 0)
            {
                List<StateSave> statesForThisCategory = GetSharedVariableStates(element);

                currentBlock = CreateClassForStateCategory(currentBlock, statesForThisCategory, null, element as GlueElement);
                GenerateCurrentStateProperty(element as GlueElement, codeBlock, null, statesForThisCategory);

                //Build State Categories
                var stateCategories = GetAllStateCategoryNames(element, false);

                foreach (var kvp in stateCategories)
                {
                    var states = GetAllStatesForCategory(element, kvp.Key);

                    var category = kvp.Value;
                    CreateClassForStateCategory(currentBlock, states, category, element as GlueElement);
                    GenerateCurrentStateProperty(element as GlueElement, codeBlock, category, states);
                }
            }

            return codeBlock;
        }

        private static ICodeBlock GenerateCurrentStateProperty(GlueElement element, ICodeBlock codeBlock, StateSaveCategory category, List<StateSave> states)
        {
            string enumType = category?.Name ?? "VariableState";
            // early out
            // Update August 20, 2021
            // Don't early out anymore,
            // even though there are no states
            // now, they could be added dynamically
            // by the user or by GView
            //if (states.Count == 0)
            //{
            //    return codeBlock;
            //}

            string variableNameModifier = enumType;
            if (enumType == "VariableState")
            {
                variableNameModifier = "";
            }

            string qualifiedEnumType = element.Name.Replace("\\", ".").Replace("/", ".") + "." + enumType;

            string variableToLookFor = "Current" + variableNameModifier + "State";
            CustomVariable customVariable = element.GetCustomVariable(variableToLookFor);
            bool hasEvent = customVariable != null && customVariable.CreatesEvent;

            #region Header and Getter stuff - simple stuff with no logic

            codeBlock
                .Line($"private {enumType} mCurrent{variableNameModifier}State = null;");

            string publicWithOptionalNew = "public";
            if (IsStateDefinedInBase(element, enumType))
            {
                publicWithOptionalNew += " new";
            }

            // This is inclusive (-1), but includes 0 and 1 values (+2), which means the net is +1
            int maxIntValueInclusive = states.Count + 1;

            var setBlock = codeBlock
                .Property(publicWithOptionalNew + " " + qualifiedEnumType, "Current" + variableNameModifier + "State")
                    .Get()
                        .Line(string.Format("return mCurrent{1}State;", enumType, variableNameModifier))
                    .End()
                    .Set();

            #endregion

            #region Set the state value and call an event if necessary

            bool stillNeedsToAssignValue = true;

            if (hasEvent)
            {
                EventCodeGenerator.GenerateEventRaisingCode(setBlock, BeforeOrAfter.Before, variableToLookFor, element);
            }

            if (stillNeedsToAssignValue)
            {
                setBlock.Line("mCurrent" + variableNameModifier + "State = value;");
            }

            #endregion

            // August 9, 2021
            // Before StateData,
            // states were enums which
            // resulted in variables assigned
            // in code generation. After StateData,
            // states became an object which held their
            // own values. This means that users can now
            // define their own states dynamically and change
            // a state at runtime (not sure why, but it's possible).
            // Since states now store their own values, we no longer need
            // codegen to explicitly assign variables. Sure, assigning hard
            // values is faster, but having conditionals is slower so...does
            // it really save us that much? Also, it's extra gencode bloat that
            // we could get rid of and replace with a single assignment block. That
            // else statement was added today in GenerateVariableAssignmentForDynamicState
            // which means we could probably get rid of the GenerateVariableAssignmentForState
            // calls. But I don't know if the two are 100% equivalent so I'll leave the codegen
            // in for now. However, eventually this can go away completely with some testing...perhaps
            // once the automated test project is revived.
            // Update August 9, 2021 - Well that didn't take long. If we leave the hardcoded generation in
            // then if the user changes a compiled-in state, the hardcoded value will get assigned even if the
            // user changes it. I guess we're going to have to convert over right now...
            //bool isElse = false;
            //foreach (StateSave stateSave in states)
            //{
            //    GenerateVariableAssignmentForState(element, setBlock, stateSave, category, isElse);
            //    isElse = true;
            //}

            GenerateVariableAssignmentForDynamicState(element, setBlock, category);

            if ((enumType == "VariableState" && DoesBaseHaveUncategorizedStates(element)) ||
                (!string.IsNullOrEmpty(element.BaseElement) && GetAllStateCategoryNames(ObjectFinder.Self.GetElement(element.BaseElement), true).Any(category => category.Key == enumType)))
            {
                // October 29, 2021
                // I dont' think we need
                // an else anymore, we can
                // just call into the base:
                //setBlock.Else()
                setBlock
                    .Line("base.Current" + variableNameModifier + "State = base.Current" + variableNameModifier + "State;");
            }

            if (hasEvent)
            {
                EventCodeGenerator.GenerateEventRaisingCode(setBlock, BeforeOrAfter.After, variableToLookFor, element);
            }

            return codeBlock;
        }

        private static void GenerateVariableAssignmentForDynamicState(GlueElement element, ICodeBlock setBlock, StateSaveCategory category)
        {
            setBlock = setBlock.If("value != null");
            foreach (var variable in element.CustomVariables)
            {
                var shouldInclude = false;
                if (category != null)
                {
                    if (category.ExcludedVariables.Contains(variable.Name))
                    {
                        shouldInclude = false;
                    }
                    // If we don't do this, the variable will recursively get set.
                    // I can't think of a case where a user would want this since it
                    // will inevitably turn into a StackOverflowException.
                    else if (variable.Type == category.Name)
                    {
                        shouldInclude = false;
                    }
                    else
                    {
                        shouldInclude = true;
                    }
                }
                else
                {
                    // I guess if its the default state, we assign always?
                    shouldInclude = true;
                }

                if(shouldInclude)
                {
                    shouldInclude = ShouldIncludeVariable(category, element, variable);
                }

                if (shouldInclude)
                {

                    string member = variable.Name;

                    // Get the valueAsString, which is the right-side of the equals sign
                    string rightSideOfEquals = $"value.{variable.Name}";

                    CustomVariable customVariable = element.GetCustomVariableRecursively(member);
                    var isFile = customVariable.GetIsFile();
                    var assignOnlyIfNonNull = false;
                    if(isFile)
                    {
                        var type = customVariable.Type;
                        if(type == "AnimationChainList")
                        {
                            type = typeof(Graphics.Animation.AnimationChainList).FullName;
                            assignOnlyIfNonNull = true;
                        }
                        else if(type == nameof(Texture2D))
                        {
                            type = typeof(Texture2D).FullName;
                        }
                        rightSideOfEquals = $"GetFile(value.{variable.Name}) as {type}";
                    }
                    //else if(!string.IsNullOrWhiteSpace(customVariable.OverridingPropertyType))
                    //{
                    //    var value = TypeConverterHelper.Convert(customVariable, GetterOrSetter.Getter, "value." + variable.Name);
                    //    rightSideOfEquals = value;
                    //}

                    NamedObjectSave referencedNos = element.GetNamedObjectRecursively(customVariable.SourceObject);
                    if (referencedNos != null)
                    {
                        NamedObjectSaveCodeGenerator.AddIfConditionalSymbolIfNecesssary(setBlock, referencedNos);
                    }

                    string leftSideOfEquals = GetLeftSideOfEquals(element, customVariable, member, false);
                    string leftSideOfEqualsWithRelative = GetLeftSideOfEquals(element, customVariable, member, true);

                    if (leftSideOfEquals != leftSideOfEqualsWithRelative)
                    {
                        string objectWithParent = null;

                        if (string.IsNullOrEmpty(customVariable.SourceObject))
                        {
                            objectWithParent = "this";
                        }
                        else
                        {
                            objectWithParent = customVariable.SourceObject;
                        }

                        setBlock
                            .If(objectWithParent + ".Parent == null")
                                .Line(leftSideOfEquals + " = " + rightSideOfEquals + ";")
                            .End()

                            .Else()
                                .Line(leftSideOfEqualsWithRelative + " = " + rightSideOfEquals + ";");
                    }
                    else
                    {
                        var effectiveBlock = setBlock;
                        if(assignOnlyIfNonNull)
                        {
                            effectiveBlock = setBlock.If($"({rightSideOfEquals}) != null");
                        }
                        effectiveBlock.Line(leftSideOfEquals + " = " + rightSideOfEquals + ";");
                    }

                    if (referencedNos != null)
                    {
                        NamedObjectSaveCodeGenerator.AddEndIfIfNecessary(setBlock, referencedNos);
                    }

                }
            }
        }

        public static List<StateSave> GetAllStatesForCategory(IElement element, string stateCategory)
        {
            var states = new List<StateSave>();

            if (!string.IsNullOrEmpty(element.BaseElement))
            {
                IElement baseElement = ObjectFinder.Self.GetElement(element.BaseElement);

                if (baseElement != null)
                {
                    states.AddRange(GetAllStatesForCategory(baseElement, stateCategory));
                }
            }

            var category =
                element.StateCategoryList.Find(
                    cat => cat.Name == stateCategory);

            if(category != null)
                states.AddRange(category.States);

            return states;
        }

        private static Dictionary<string, StateSaveCategory> GetAllStateCategoryNames(IElement element, bool includeInheritance)
        {
            var names = new Dictionary<string, StateSaveCategory>();
            if (element != null)
            {
                if (!string.IsNullOrEmpty(element.BaseElement) && includeInheritance)
                {
                    var uncontained = GetAllStateCategoryNames(ObjectFinder.Self.GetElement(element.BaseElement), includeInheritance).Where(name => !names.ContainsKey(name.Key));

                    foreach (var kvp in uncontained)
                    {
                        names.Add(kvp.Key, kvp.Value);
                    }
                }

                foreach (var category in element.StateCategoryList.Where(category => !names.ContainsKey(category.Name)))
                {
                    names.Add(category.Name, category);
                }
            }
            return names;
        }

        private static bool IsStateDefinedInBase(IElement element, string enumName)
        {
            bool toReturn = false;
            if (string.IsNullOrEmpty(element.BaseElement))
            {
                toReturn = false;
            }
            else
            {
                IElement baseElement = ObjectFinder.Self.GetElement(element.BaseElement);

                if (baseElement != null)
                {
                    toReturn = baseElement.DefinesCategoryEnumRecursive(enumName);
                }
            }
            return toReturn;
        }

        private static ICodeBlock GenerateVariableAssignmentForState(GlueElement element, ICodeBlock codeBlock, StateSave stateSave, StateSaveCategory category, bool isElse)
        {
            string enumType = category?.Name ?? "VariableState";

            string variableNameModifier = enumType;
            if (enumType == "VariableState")
            {
                variableNameModifier = "";
            }

            ICodeBlock curBlock;

            if(isElse)
            {
                curBlock = codeBlock.ElseIf($"Current{variableNameModifier}State == {enumType}.{stateSave.Name}");
            }
            else
            {
                curBlock = codeBlock.If($"Current{variableNameModifier}State == {enumType}.{stateSave.Name}");

            }

            foreach(var variable in element.CustomVariables)
            {
                var shouldInclude = false;
                if(category != null)
                {
                    if(category.ExcludedVariables.Contains(variable.Name))
                    {
                        shouldInclude = false;
                    }
                    // If we don't do this, the variable will recursively get set.
                    // I can't think of a case where a user would want this since it
                    // will inevitably turn into a StackOverflowException.
                    else if(variable.Type == category.Name)
                    {
                        shouldInclude = false;
                    }
                    else
                    {
                        shouldInclude = true;
                    }
                }
                else if(category == null)
                {
                    shouldInclude = stateSave.InstructionSaves.Any(item => item.Member == variable.Name);
                }

                if(shouldInclude)
                {

                    string member = variable.Name;
                    var value = stateSave.InstructionSaves.FirstOrDefault(item => item.Member == variable.Name)?.Value ?? variable.DefaultValue;

                    if (value != null)
                    {
                        // Get the valueAsString, which is the right-side of the equals sign
                        string rightSideOfEquals = GetRightSideAssignmentValueAsString(element, member, value);

                        if (!string.IsNullOrEmpty(rightSideOfEquals))
                        {
                            CustomVariable customVariable = element.GetCustomVariableRecursively(member);
                            NamedObjectSave referencedNos = element.GetNamedObjectRecursively(customVariable.SourceObject);

                            if (referencedNos != null)
                            {
                                NamedObjectSaveCodeGenerator.AddIfConditionalSymbolIfNecesssary(curBlock, referencedNos);
                            }

                            string leftSideOfEquals = GetLeftSideOfEquals(element, customVariable, member, false);
                            string leftSideOfEqualsWithRelative = GetLeftSideOfEquals(element, customVariable, member, true);

                            if (leftSideOfEquals != leftSideOfEqualsWithRelative)
                            {
                                string objectWithParent = null;

                                if (string.IsNullOrEmpty(customVariable.SourceObject))
                                {
                                    objectWithParent = "this";
                                }
                                else
                                {
                                    objectWithParent = customVariable.SourceObject;
                                }

                                curBlock
                                    .If(objectWithParent + ".Parent == null")
                                        .Line(leftSideOfEquals + " = " + rightSideOfEquals + ";")
                                    .End()

                                    .Else()
                                        .Line(leftSideOfEqualsWithRelative + " = " + rightSideOfEquals + ";");
                            }
                            else
                            {
                                curBlock.Line(leftSideOfEquals + " = " + rightSideOfEquals + ";");
                            }

                            if (referencedNos != null)
                            {
                                NamedObjectSaveCodeGenerator.AddEndIfIfNecessary(curBlock, referencedNos);
                            }

                        }
                    }
                }
            }

            return codeBlock;
        }

        #endregion

        public static List<StateSave> GetSharedVariableStates(SaveClasses.IElement element)
        {
            if (element == null)
            {
                throw new ArgumentNullException("element argument cannot be null");
            }

            var statesForThisCategory = new List<StateSave>();

            var currentElement = element;

            //Get states for parent entities
            if (!string.IsNullOrEmpty(currentElement.BaseElement))
            {
                IElement baseElement = ObjectFinder.Self.GetElement(currentElement.BaseElement);
                if (baseElement != null)
                {
                    statesForThisCategory.AddRange(GetSharedVariableStates(baseElement));
                }
            }

            for (int i = 0; i < element.States.Count; i++)
            {
                statesForThisCategory.Add(element.States[i]);
            }

            return statesForThisCategory;
        }

        public override ICodeBlock GenerateAdditionalMethods(ICodeBlock codeBlock, SaveClasses.IElement element)
        {
            if (element.HasStates)
            {

                List<StateSave> sharedVariableStates = GetSharedVariableStates(element);

                if (sharedVariableStates.Count != 0)
                {
                    #region Create the static state that should be set prior to loading

                    string propertyPrefix = "public static ";

                    if (!string.IsNullOrEmpty(element.BaseElement))
                    {
                        IElement baseElement = ObjectFinder.Self.GetElement(element.BaseElement);
                        if (baseElement != null && baseElement.DefinesCategoryEnumRecursive("VariableState"))
                        {
                            propertyPrefix += "new ";
                        }
                    }

                    codeBlock
                        .Line("static VariableState mLoadingState = null;")
                        .Property(propertyPrefix + "VariableState", "LoadingState")
                            .Get()
                                .Line("return mLoadingState;")
                            .End()
                            .Set()
                                .Line("mLoadingState = value;")
                            .End()
                        .End();

                    #endregion
                }

                GenerateInterpolationAdditionalMethods(codeBlock, element as GlueElement, sharedVariableStates);

                GeneratePreloadStateContent(codeBlock, element, sharedVariableStates);
            }

            return codeBlock;
        }

        private void GeneratePreloadStateContent(ICodeBlock codeBlock, IElement element, List<StateSave> sharedVariableStates)
        {
            // For now we'll only support Entities because they have a ContentManagerName variable.  Screen content can't be shared
            // between Screens because of the hard-coded content manager name.  We'll have to revisit that if we need to share content
            // between screens programatically.
            if (element is EntitySave)
            {
                // This method is used to preload content for certain states.  States may use content that is
                // LoadedOnlyWhenReferenced.  If so, that means that the content will be loaded on first access
                // post-initialize.  This method will allow users to load this content on the async thread prior
                // to Initialize finishing without having to worry about which content belongs in which state.

                List<StateSave> list = sharedVariableStates;

                codeBlock = GeneratePreloadStateContentForStateType(codeBlock, element, list, "VariableState");

                foreach (StateSaveCategory category in element.StateCategoryList)
                {
                    codeBlock = GeneratePreloadStateContentForStateType(codeBlock, element, category.States, category.Name);
                }
            }
        }

        private static ICodeBlock GeneratePreloadStateContentForStateType(ICodeBlock codeBlock, IElement element, List<StateSave> list, string variableType)
        {
            if (list.Count != 0)
            {

                codeBlock = codeBlock.Function("public static void", "PreloadStateContent", variableType + " state, string contentManagerName");
                codeBlock.Line("ContentManagerName = contentManagerName;");

                //codeBlock = codeBlock.Switch("state");
                bool isElse = false;
                // Loop through states here and access properties that need the values
                foreach (StateSave state in list)
                {
                    if(isElse)
                    {
                        codeBlock = codeBlock.ElseIf($"state == {variableType}.{state.Name}");

                    }
                    else
                    {
                        codeBlock = codeBlock.If($"state == {variableType}.{state.Name}");

                    }

                    isElse = true;
                    foreach (InstructionSave instruction in state.InstructionSaves)
                    {
                        if (instruction.Value != null && instruction.Value is string)
                        {
                            // We insert a block so that object throwaway is not redefined in the switch scope.
                            // We do this instead of making an object throwaway above the switch so that we don't
                            // get warnings if is nothing to load
                            codeBlock.Block().Line("object throwaway = " + GetRightSideAssignmentValueAsString(element, instruction) + ";");
                        }
                    }
                    codeBlock = codeBlock.End();

                }

                codeBlock = codeBlock.End();
            }
            return codeBlock;
        }

        public override ICodeBlock GenerateLoadStaticContent(ICodeBlock codeBlock, IElement element)
        {
            return codeBlock;
        }

        private static bool DoesBaseHaveUncategorizedStates(IElement element)
        {
            if (string.IsNullOrEmpty(element.BaseElement) || element.InheritsFromFrbType())
            {
                return false;
            }
            else
            {
                IElement baseElement = ObjectFinder.Self.GetElement(element.BaseElement);

                if (baseElement != null)
                {

                    if (baseElement.States.Count != 0)
                    {
                        return true;
                    }

                }
                return false;

            }

        }

        private static string GetLeftSideOfEquals(GlueElement element, CustomVariable customVariable, string member, bool switchToRelative)
        {
            string leftSideOfEquals = member;

            if (switchToRelative && customVariable != null)
            {
                string possibleLeftSide = RelativeValueForInstruction(member, customVariable, element);
                if (!string.IsNullOrEmpty(possibleLeftSide))
                {

                    leftSideOfEquals = possibleLeftSide;
                    if (!string.IsNullOrEmpty(customVariable.SourceObject))
                    {
                        leftSideOfEquals = customVariable.SourceObject + "." + leftSideOfEquals;
                    }
                }
            }

            return leftSideOfEquals;
        }

        private static bool GetDoesStateAssignAbsoluteValues(StateSave stateSave, GlueElement element)
        {
            bool returnValue = false;
            foreach (InstructionSave instruction in stateSave.InstructionSaves)
            {
                CustomVariable customVariable = element.GetCustomVariableRecursively(instruction.Member);

                if (customVariable != null)
                {
                    returnValue |= !string.IsNullOrEmpty(RelativeValueForInstruction(instruction.Member, customVariable, element));
                }
            }

            return returnValue;
        }

        private static string RelativeValueForInstruction(string memberName, CustomVariable customVariable, GlueElement element)
        {
            var rootCustomVariable = ObjectFinder.Self.GetBaseCustomVariable(customVariable);

            if (!string.IsNullOrEmpty(rootCustomVariable.SourceObject))
            {
                var namedObject = element.GetNamedObjectRecursively(rootCustomVariable.SourceObject);

                var isGum = namedObject?.SourceType == SourceType.Gum;

                string relativeMember = null;

                if (!isGum)
                {
                    relativeMember = InstructionManager.GetRelativeForAbsolute(customVariable.SourceObjectProperty);
                }

                return relativeMember;
            }
            else
            {

                string relativeMember = null;

                if (element is EntitySave)
                {
                    relativeMember = InstructionManager.GetRelativeForAbsolute(memberName);
                }
                return relativeMember;
            }

        }

        public static string GetRightSideAssignmentValueAsString(IElement element, InstructionSave instruction)
        {
            var value = instruction.Value;
            var memberName = instruction.Member;
            return GetRightSideAssignmentValueAsString(element, memberName, value);
        }

        // Note - this code is very similar to CustomVariableCodeGenerator's AppendAssignmentForCustomVariableInElement
        // Unify?
        private static string GetRightSideAssignmentValueAsString(IElement element, string memberName, object value)
        {
            CustomVariable customVariable = element.GetCustomVariableRecursively(memberName);
            customVariable = ObjectFinder.Self.GetBaseCustomVariable(customVariable);

            IElement referencedElement = null;

            #region Determine if the assignment is a file

            bool isFile = false;

            if (customVariable != null)
            {
                referencedElement =
                    CustomVariableCodeGenerator.GetElementIfCustomVariableIsVariableState(customVariable, element);

                isFile = customVariable.GetIsFile();

            }

            #endregion

            string valueAsString = "";

            if (referencedElement == null)
            {

                valueAsString = CodeParser.ConvertValueToCodeString(value);

                if (isFile)
                {
                    valueAsString = valueAsString.Replace("\"", "");

                    if (valueAsString == "<NONE>")
                    {
                        valueAsString = "null";
                    }
                }
                else if (CustomVariableCodeGenerator.ShouldAssignToCsv(customVariable, valueAsString))
                {
                    valueAsString = CustomVariableCodeGenerator.GetAssignmentToCsvItem(customVariable, element, valueAsString);
                }
                else if (customVariable != null && customVariable.Type == "Color")
                {
                    valueAsString = "Color." + valueAsString.Replace("\"", "");
                }
                if (customVariable != null && !string.IsNullOrEmpty(customVariable.SourceObject) && !isFile)
                {
                    NamedObjectSave namedObject = element.GetNamedObjectRecursively(customVariable.SourceObject);

                    bool isVariableState = customVariable.GetIsVariableState();

                    IElement objectElement = null;

                    if (namedObject != null)
                    {
                        objectElement = ObjectFinder.Self.GetElement(namedObject.SourceClassType);
                    }

                    if (objectElement != null)
                    {
                        if (isVariableState)
                        {
                            string typeName = "VariableState";

                            StateSaveCategory category = objectElement.GetStateCategoryRecursively(customVariable.Type);

                            if(category != null)
                            {
                                typeName = category.Name;

                                valueAsString = objectElement.Name.Replace("/", ".").Replace("\\", ".") + "." + typeName + "." + valueAsString.Replace("\"", "");
                            }
                        }
                    }

                    valueAsString = CodeWriter.MakeLocalizedIfNecessary(
                        namedObject,
                        memberName,
                        value,
                        valueAsString,
                        customVariable);

                    if(namedObject?.SourceType == SourceType.Gum && customVariable.Type?.Contains(".") == true && customVariable.Type.EndsWith("?"))
                    {
                        // this is a state type, so remove the "?" and prefix it:
                        valueAsString = customVariable.Type.Substring(0, customVariable.Type.Length - 1) + "." + value;
                    }

                    // Conversion happens in the variable assignment on the instance, not in the state
                    //if(!string.IsNullOrEmpty(customVariable.OverridingPropertyType))
                    //{
                    //    valueAsString = TypeConverterHelper.Convert(customVariable, GetterOrSetter.Setter, valueAsString);
                    //}
                }
            }
            else
            {
                string enumValue = (string)value;

                if (!string.IsNullOrEmpty(enumValue) && enumValue != "<NONE>")
                {
                    string variableType = "VariableState";

                    if (customVariable != null && customVariable.Type.ToLower() != "string")
                    {
                        variableType = customVariable.Type;
                    }
                    valueAsString = FullyQualifyStateValue(referencedElement, enumValue, variableType);
                }

            }
            return valueAsString;
        }

        public static string FullyQualifyStateValue(IElement referencedElement, string enumValue, string variableType)
        {
            var isAlreadyQualifed = variableType.Contains('.');
            if(isAlreadyQualifed)
            {
                return $"{variableType}.{enumValue}";
            }
            else
            {
                string valueAsString =
                    ProjectManager.ProjectNamespace + "." + referencedElement.Name.Replace("\\", ".") + "." + variableType + "." + enumValue;
                return valueAsString;
            }
        }

        public static string FullyQualifiedDefaultStateValue(IElement referencedElement, string variableType)
        {
            string stateName = null;
            if (variableType == "VariableState")
            {
                if (referencedElement.States.Count != 0)
                {
                    stateName = referencedElement.States[0].Name;
                }
            }
            else
            {
                StateSaveCategory category = referencedElement.GetStateCategoryRecursively(variableType);
                if (category != null && category.States.Count != 0)
                {
                    stateName = category.States[0].Name;
                }
            }

            if (stateName != null)
            {
                return ProjectManager.ProjectNamespace + "." + referencedElement.Name.Replace("\\", ".") + "." + variableType + "." + stateName;
            }
            else
            {
                return null;
            }
        }

        public static void WriteSetStateOnNamedObject(NamedObjectSave namedObject, ICodeBlock codeBlock)
        {
            if (!string.IsNullOrEmpty(namedObject.CurrentState))
            {
                IElement referencedElement = namedObject.GetReferencedElement();
                if (referencedElement != null && referencedElement.GetUncategorizedStatesRecursively().Count != 0)
                {
                    string qualifiedName = NamedObjectSaveCodeGenerator.GetQualifiedTypeName(namedObject);

                    string lineToAdd = namedObject.FieldName + ".CurrentState = " + qualifiedName + ".VariableState." + namedObject.CurrentState + ";";
                    codeBlock.Line(lineToAdd);
                }

            }

        }
    }
}


text:
Edit Types

    {{ key.text }}

      <input type="text" class="form-control" name="type" ng-model="key.type">