text:
package net.bolbat.kit.vo;

/**
 * {@link EntityVO} constants.
 *
 * @author Alexandr Bolbat
 */
public final class EntityVOConstants {

	/**
	 * Persistence field name for creation timestamp.
	 */
	public static final String P_F_CREATED = "created";

	/**
	 * Persistence field name for update timestamp.
	 */
	public static final String P_F_UPDATED = "updated";

	/**
	 * Default constructor with preventing instantiations of this class.
	 */
	private EntityVOConstants() {
		throw new IllegalAccessError("Shouldn't be instantiated.");
	}

}

redpajama_set_name: RedPajamaGithub


text:
set -e -u

ROOT_PASSWORD=$1
DB_NAME=$2
DB_USER=$3
DB_PASSWORD=$4

# Install MySQL Server
echo "mysql-server-5.5 mysql-server/root_password password $ROOT_PASSWORD" | debconf-set-selections
echo "mysql-server-5.5 mysql-server/root_password_again password $ROOT_PASSWORD" | debconf-set-selections
apt-get -yqq install mysql-server mysql-client

# Enable remote access to MySQL
sed -i "s/bind-address.*/bind-address = 0.0.0.0/" /etc/mysql/mysql.conf.d/mysqld.cnf

# Set the general log file path
sed -i "s/^.*general_log_file.*$/general_log_file = \/var\/log\/mysql\/mysql.log/" /etc/mysql/mysql.conf.d/mysqld.cnf

/etc/init.d/mysql restart

echo "
-- Secure the MySQL installation
DROP DATABASE IF EXISTS test;
DELETE FROM mysql.user WHERE User='root' AND Host!='localhost';
DELETE FROM mysql.user WHERE User='';

-- Create the root account with a password
GRANT ALL ON *.* TO 'root'@'localhost' IDENTIFIED BY '$ROOT_PASSWORD' WITH GRANT OPTION;
GRANT ALL ON *.* TO 'root'@'%' IDENTIFIED BY '$ROOT_PASSWORD' WITH GRANT OPTION;
" | mysql -uroot -p$ROOT_PASSWORD

if [ ! -z $DB_NAME ]; then
    echo "
-- Create the research database
CREATE DATABASE IF NOT EXISTS $DB_NAME;

-- Create the user and grant them privileges
GRANT USAGE ON *.* TO '$DB_USER'@'%' IDENTIFIED BY '$DB_PASSWORD';  -- GRANT USAGE is used here to create the user if it doesn't exist.
GRANT USAGE ON *.* TO '$DB_USER'@'localhost' IDENTIFIED BY '$DB_PASSWORD';

GRANT ALTER, INDEX, SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, CREATE TEMPORARY TABLES ON $DB_NAME.* to '$DB_USER'@'%';
GRANT ALTER, INDEX, SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, CREATE TEMPORARY TABLES ON $DB_NAME.* to '$DB_USER'@'localhost';

-- Reload the privileges
FLUSH PRIVILEGES;
" | mysql -uroot -p$ROOT_PASSWORD
fi

tee -a /etc/bashrc << EOF

# Restart MySQL if not running
IS_MYSQL_RUNNING=\$( ps aux | grep mysqld | grep -v grep | wc -l )
if [ "\$PS1" ] && [ "\$IS_MYSQL_RUNNING" = "0" ]; then
    echo "Starting MySQL"
    sudo rm -f /var/run/mysqld/mysqld.sock
    sudo /etc/init.d/mysql restart
fi
EOF


text:
package org.elasticsearch.cluster.routing.allocation.decider;

import com.carrotsearch.hppc.cursors.ObjectCursor;
import org.elasticsearch.Version;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.ESAllocationTestCase;
import org.elasticsearch.cluster.RestoreInProgress;
import org.elasticsearch.cluster.metadata.IndexMetadata;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodeRole;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.IndexRoutingTable;
import org.elasticsearch.cluster.routing.IndexShardRoutingTable;
import org.elasticsearch.cluster.routing.RecoverySource;
import org.elasticsearch.cluster.routing.RoutingNode;
import org.elasticsearch.cluster.routing.RoutingTable;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.ShardRoutingState;
import org.elasticsearch.cluster.routing.UnassignedInfo;
import org.elasticsearch.cluster.routing.allocation.RoutingAllocation;
import org.elasticsearch.common.UUIDs;
import org.elasticsearch.common.collect.ImmutableOpenMap;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.repositories.IndexId;
import org.elasticsearch.snapshots.Snapshot;
import org.elasticsearch.snapshots.SnapshotId;

import java.io.IOException;
import java.util.Collections;

import static java.util.Collections.singletonList;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.startsWith;

/**
 * Test {@link RestoreInProgressAllocationDecider}
 */
public class RestoreInProgressAllocationDeciderTests extends ESAllocationTestCase {

    public void testCanAllocatePrimary() {
        ClusterState clusterState = createInitialClusterState();
        ShardRouting shard;
        if (randomBoolean()) {
            shard = clusterState.getRoutingTable().shardRoutingTable("test", 0).primaryShard();
            assertEquals(RecoverySource.Type.EMPTY_STORE, shard.recoverySource().getType());
        }  else {
            shard = clusterState.getRoutingTable().shardRoutingTable("test", 0).replicaShards().get(0);
            assertEquals(RecoverySource.Type.PEER, shard.recoverySource().getType());
        }

        final Decision decision = executeAllocation(clusterState, shard);
        assertEquals(Decision.Type.YES, decision.type());
        assertEquals("ignored as shard is not being recovered from a snapshot", decision.getExplanation());
    }

    public void testCannotAllocatePrimaryMissingInRestoreInProgress() {
        ClusterState clusterState = createInitialClusterState();
        RoutingTable routingTable = RoutingTable.builder(clusterState.getRoutingTable())
            .addAsRestore(clusterState.getMetadata().index("test"), createSnapshotRecoverySource("_missing"))
            .build();

        clusterState = ClusterState.builder(clusterState)
            .routingTable(routingTable)
            .build();

        ShardRouting primary = clusterState.getRoutingTable().shardRoutingTable("test", 0).primaryShard();
        assertEquals(ShardRoutingState.UNASSIGNED, primary.state());
        assertEquals(RecoverySource.Type.SNAPSHOT, primary.recoverySource().getType());

        final Decision decision = executeAllocation(clusterState, primary);
        assertEquals(Decision.Type.NO, decision.type());
        assertThat(decision.getExplanation(), equalTo("shard has failed to be restored from the snapshot " +
            "[_repository:_missing/_uuid] - manually close or delete the index [test] in order to retry to restore the snapshot again " +
            "or use the reroute API to force the allocation of an empty primary shard. Details: [restore_source[_repository/_missing]]"));
    }

    public void testCanAllocatePrimaryExistingInRestoreInProgress() {
        RecoverySource.SnapshotRecoverySource recoverySource = createSnapshotRecoverySource("_existing");

        ClusterState clusterState = createInitialClusterState();
        RoutingTable routingTable = RoutingTable.builder(clusterState.getRoutingTable())
            .addAsRestore(clusterState.getMetadata().index("test"), recoverySource)
            .build();

        clusterState = ClusterState.builder(clusterState)
            .routingTable(routingTable)
            .build();

        ShardRouting primary = clusterState.getRoutingTable().shardRoutingTable("test", 0).primaryShard();
        assertEquals(ShardRoutingState.UNASSIGNED, primary.state());
        assertEquals(RecoverySource.Type.SNAPSHOT, primary.recoverySource().getType());

        routingTable = clusterState.routingTable();

        final RestoreInProgress.State shardState;
        if (randomBoolean()) {
            shardState = randomFrom(RestoreInProgress.State.STARTED, RestoreInProgress.State.INIT);
        } else {
            shardState = RestoreInProgress.State.FAILURE;

            UnassignedInfo currentInfo = primary.unassignedInfo();
            UnassignedInfo newInfo = new UnassignedInfo(currentInfo.getReason(), currentInfo.getMessage(), new IOException("i/o failure"),
                currentInfo.getNumFailedAllocations(), currentInfo.getUnassignedTimeInNanos(), currentInfo.getUnassignedTimeInMillis(),
                currentInfo.isDelayed(), currentInfo.getLastAllocationStatus(), currentInfo.getFailedNodeIds());
            primary = primary.updateUnassigned(newInfo, primary.recoverySource());

            IndexRoutingTable indexRoutingTable = routingTable.index("test");
            IndexRoutingTable.Builder newIndexRoutingTable = IndexRoutingTable.builder(indexRoutingTable.getIndex());
            for (final ObjectCursor<IndexShardRoutingTable> shardEntry : indexRoutingTable.getShards().values()) {
                final IndexShardRoutingTable shardRoutingTable = shardEntry.value;
                for (ShardRouting shardRouting : shardRoutingTable.getShards()) {
                    if (shardRouting.primary()) {
                        newIndexRoutingTable.addShard(primary);
                    } else {
                        newIndexRoutingTable.addShard(shardRouting);
                    }
                }
            }
            routingTable = RoutingTable.builder(routingTable).add(newIndexRoutingTable).build();
        }

        ImmutableOpenMap.Builder<ShardId, RestoreInProgress.ShardRestoreStatus> shards = ImmutableOpenMap.builder();
        shards.put(primary.shardId(), new RestoreInProgress.ShardRestoreStatus(clusterState.getNodes().getLocalNodeId(), shardState));

        Snapshot snapshot = recoverySource.snapshot();
        RestoreInProgress.State restoreState = RestoreInProgress.State.STARTED;
        RestoreInProgress.Entry restore =
            new RestoreInProgress.Entry(recoverySource.restoreUUID(), snapshot, restoreState, singletonList("test"), shards.build());

        clusterState = ClusterState.builder(clusterState)
            .putCustom(RestoreInProgress.TYPE, new RestoreInProgress.Builder().add(restore).build())
            .routingTable(routingTable)
            .build();

        Decision decision = executeAllocation(clusterState, primary);
        if (shardState == RestoreInProgress.State.FAILURE) {
            assertEquals(Decision.Type.NO, decision.type());
            assertThat(decision.getExplanation(), startsWith("shard has failed to be restored from the snapshot " +
                "[_repository:_existing/_uuid] - manually close or delete the index " +
                "[test] in order to retry to restore the snapshot again or use the reroute API to force the allocation of " +
                "an empty primary shard. Details: [restore_source[_repository/_existing], failure java.io.IOException: i/o failure"));
        } else {
            assertEquals(Decision.Type.YES, decision.type());
            assertEquals("shard is currently being restored", decision.getExplanation());
        }
    }

    private ClusterState createInitialClusterState() {
        Metadata metadata = Metadata.builder()
            .put(IndexMetadata.builder("test").settings(settings(Version.CURRENT)).numberOfShards(1).numberOfReplicas(1))
            .build();

        RoutingTable routingTable = RoutingTable.builder()
            .addAsNew(metadata.index("test"))
            .build();

        DiscoveryNodes discoveryNodes = DiscoveryNodes.builder()
            .add(newNode("master", Collections.singleton(DiscoveryNodeRole.MASTER_ROLE)))
            .localNodeId("master")
            .masterNodeId("master")
            .build();

        ClusterState clusterState = ClusterState.builder(ClusterName.DEFAULT)
            .metadata(metadata)
            .routingTable(routingTable)
            .nodes(discoveryNodes)
            .build();

        assertEquals(2, clusterState.getRoutingTable().shardsWithState(ShardRoutingState.UNASSIGNED).size());
        return clusterState;
    }

    private Decision executeAllocation(final ClusterState clusterState, final ShardRouting shardRouting) {
        final AllocationDecider decider = new RestoreInProgressAllocationDecider();
        final RoutingAllocation allocation = new RoutingAllocation(new AllocationDeciders(Collections.singleton(decider)),
            clusterState.getRoutingNodes(), clusterState, null, 0L);
        allocation.debugDecision(true);

        final Decision decision;
        if (randomBoolean()) {
            decision = decider.canAllocate(shardRouting, allocation);
        } else {
            DiscoveryNode node = clusterState.getNodes().getMasterNode();
            decision = decider.canAllocate(shardRouting, new RoutingNode(node.getId(), node), allocation);
        }
        return decision;
    }

    private RecoverySource.SnapshotRecoverySource createSnapshotRecoverySource(final String snapshotName) {
        Snapshot snapshot = new Snapshot("_repository", new SnapshotId(snapshotName, "_uuid"));
        return new RecoverySource.SnapshotRecoverySource(UUIDs.randomBase64UUID(), snapshot, Version.CURRENT,
            new IndexId("test", UUIDs.randomBase64UUID(random())));
    }
}


text:
package Google::Ads::GoogleAds::V10::Resources::UseBroadMatchKeywordRecommendation;

use strict;
use warnings;
use base qw(Google::Ads::GoogleAds::BaseEntity);

use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;

sub new {
  my ($class, $args) = @_;
  my $self = {
    campaignKeywordsCount              => $args->{campaignKeywordsCount},
    campaignUsesSharedBudget           => $args->{campaignUsesSharedBudget},
    keyword                            => $args->{keyword},
    requiredCampaignBudgetAmountMicros =>
      $args->{requiredCampaignBudgetAmountMicros},
    suggestedKeywordsCount => $args->{suggestedKeywordsCount}};

  # Delete the unassigned fields in this object for a more concise JSON payload
  remove_unassigned_fields($self, $args);

  bless $self, $class;
  return $self;
}

1;


text:
from autokit import data_converter
from autokit import data_io
from autokit.data_io import vprint
import numpy as np
try:
    import pickle as pickle
except:
    import pickle
import os
import time

class DataManager:
    ''' This class aims at loading and saving data easily with a cache and at generating a dictionary (self.info) in which each key is a feature (e.g. : name, format, feat_num,...).
    Methods defined here are :
    __init__ (...)
        x.__init__([(feature, value)]) -> void
        Initialize the info dictionary with the tuples (feature, value) given as argument. It recognizes the type of value (int, string) and assign value to info[feature]. An unlimited number of tuple can be sent.

    getInfo (...)
        x.getInfo (filename) -> void
        Fill the dictionary with an info file. Each line of the info file must have this format 'feature' : value
        The information is obtained from the public.info file if it exists, or inferred from the data files

    getInfoFromFile (...)
        x.getInfoFromFile (filename) -> void
        Fill the dictionary with an info file. Each line of the info file must have this format 'feature' : value

    getFormatData (...)
        x.getFormatData (filename) -> str
        Get the format of the file ('dense', 'sparse' or 'sparse_binary') either using the 'is_sparse' feature if it exists (for example after a call of getInfoFromFile function) and then determing if it's binary or not, or determining it alone.

    getNbrFeatures (...)
        x.getNbrFeatures (*filenames) -> int
        Get the number of features, using the data files given. It first checks the format of the data. If it's a matrix, the number of features is trivial. If it's a sparse file, it gets the max feature index given in every files.

    getTypeProblem (...)
        x.getTypeProblem (filename) -> str
        Get the kind of problem ('binary.classification', 'multiclass.classification', 'multilabel.classification', 'regression'), using the solution file given.
    '''

    def __init__(self, basename, input_dir, verbose=False, replace_missing=True, filter_features=False):
        '''Constructor'''
        self.use_pickle = False # Turn this to true to save data as pickle (inefficient)
        self.basename = basename
        if basename in input_dir:
            self.input_dir = input_dir
        else:
            self.input_dir = input_dir + "/" + basename + "/"
        if self.use_pickle:
            if os.path.exists ("tmp"):
                self.tmp_dir = "tmp"
            elif os.path.exists ("../tmp"):
                self.tmp_dir = "../tmp"
            else:
                os.makedirs("tmp")
                self.tmp_dir = "tmp"
        info_file = os.path.join (self.input_dir, basename + '_public.info')
        self.info = {}
        self.getInfo (info_file)
        self.feat_type = self.loadType (os.path.join(self.input_dir, basename + '_feat.type'), verbose=verbose)
        self.data = {}
        Xtr = self.loadData (os.path.join(self.input_dir, basename + '_train.data'), verbose=verbose, replace_missing=replace_missing)
        Ytr = self.loadLabel (os.path.join(self.input_dir, basename + '_train.solution'), verbose=verbose)
        Xva = self.loadData (os.path.join(self.input_dir, basename + '_valid.data'), verbose=verbose, replace_missing=replace_missing)
        Xte = self.loadData (os.path.join(self.input_dir, basename + '_test.data'), verbose=verbose, replace_missing=replace_missing)
           # Normally, feature selection should be done as part of a pipeline.
           # However, here we do it as a preprocessing for efficiency reason
        idx=[]
        if filter_features: # add hoc feature selection, for the example...
            fn = min(Xtr.shape[1], 1000)
            idx = autokit.data_converter.tp_filter(Xtr, Ytr, feat_num=fn, verbose=verbose)
            Xtr = Xtr[:,idx]
            Xva = Xva[:,idx]
            Xte = Xte[:,idx]
        self.feat_idx = np.array(idx).ravel()
        self.data['X_train'] = Xtr
        self.data['Y_train'] = Ytr
        self.data['X_valid'] = Xva
        self.data['X_test'] = Xte

    def __repr__(self):
        return "DataManager : " + self.basename

    def __str__(self):
        val = "DataManager : " + self.basename + "\ninfo:\n"
        for item in self.info:
            val = val + "\t" + item + " = " + str(self.info[item]) + "\n"
        val = val + "data:\n"
        val = val + "\tX_train = array"  + str(self.data['X_train'].shape) + "\n"
        val = val + "\tY_train = array"  + str(self.data['Y_train'].shape) + "\n"
        val = val + "\tX_valid = array"  + str(self.data['X_valid'].shape) + "\n"
        val = val + "\tX_test = array"  + str(self.data['X_test'].shape) + "\n"
        val = val + "feat_type:\tarray" + str(self.feat_type.shape) + "\n"
        val = val + "feat_idx:\tarray" + str(self.feat_idx.shape) + "\n"
        return val

    def loadData (self, filename, verbose=True, replace_missing=True):
        ''' Get the data from a text file in one of 3 formats: matrix, sparse, binary_sparse'''
        if verbose:  print(("========= Reading " + filename))
        start = time.time()
        if self.use_pickle and os.path.exists (os.path.join (self.tmp_dir, os.path.basename(filename) + ".pickle")):
            with open (os.path.join (self.tmp_dir, os.path.basename(filename) + ".pickle"), "r") as pickle_file:
                vprint (verbose, "Loading pickle file : " + os.path.join(self.tmp_dir, os.path.basename(filename) + ".pickle"))
                return pickle.load(pickle_file)
        if 'format' not in list(self.info.keys()):
            self.getFormatData(filename)
        if 'feat_num' not in list(self.info.keys()):
            self.getNbrFeatures(filename)

        data_func = {'dense':autokit.data_io.data, 'sparse':autokit.data_io.data_sparse, 'sparse_binary':autokit.data_io.data_binary_sparse}

        data = data_func[self.info['format']](filename, self.info['feat_num'])

        # INPORTANT: when we replace missing values we double the number of variables

        if self.info['format']=='dense' and replace_missing and np.any(list(map(np.isnan,data))):
            vprint (verbose, "Replace missing values by 0 (slow, sorry)")
            data = autokit.data_converter.replace_missing(data)
        if self.use_pickle:
            with open (os.path.join (self.tmp_dir, os.path.basename(filename) + ".pickle"), "wb") as pickle_file:
                vprint (verbose, "Saving pickle file : " + os.path.join (self.tmp_dir, os.path.basename(filename) + ".pickle"))
                p = pickle.Pickler(pickle_file)
                p.fast = True
                p.dump(data)
        end = time.time()
        if verbose:  print(( "[+] Success in %5.2f sec" % (end - start)))
        return data

    def loadLabel (self, filename, verbose=True):
        ''' Get the solution/truth values'''
        if verbose:  print(("========= Reading " + filename))
        start = time.time()
        if self.use_pickle and os.path.exists (os.path.join (self.tmp_dir, os.path.basename(filename) + ".pickle")):
            with open (os.path.join (self.tmp_dir, os.path.basename(filename) + ".pickle"), "r") as pickle_file:
                vprint (verbose, "Loading pickle file : " + os.path.join (self.tmp_dir, os.path.basename(filename) + ".pickle"))
                return pickle.load(pickle_file)
        if 'task' not in list(self.info.keys()):
            self.getTypeProblem(filename)

           # IG: Here change to accommodate the new multiclass label format
        if self.info['task'] == 'multilabel.classification':
            label = autokit.data_io.data(filename)
        elif self.info['task'] == 'multiclass.classification':
            label = autokit.data_converter.convert_to_num(autokit.data_io.data(filename))
        else:
            label = np.ravel(autokit.data_io.data(filename)) # get a column vector
            #label = np.array([np.ravel(data_io.data(filename))]).transpose() # get a column vector

        if self.use_pickle:
            with open (os.path.join (self.tmp_dir, os.path.basename(filename) + ".pickle"), "wb") as pickle_file:
                vprint (verbose, "Saving pickle file : " + os.path.join (self.tmp_dir, os.path.basename(filename) + ".pickle"))
                p = pickle.Pickler(pickle_file)
                p.fast = True
                p.dump(label)
        end = time.time()
        if verbose:  print(( "[+] Success in %5.2f sec" % (end - start)))
        return label

    def loadType (self, filename, verbose=True):
        ''' Get the variable types'''
        if verbose:  print(("========= Reading " + filename))
        start = time.time()
        type_list = []
        if os.path.isfile(filename):
            type_list = autokit.data_converter.file_to_array (filename, verbose=False)
        else:
            n=self.info['feat_num']
            type_list = [self.info['feat_type']]*n
        type_list = np.array(type_list).ravel()
        end = time.time()
        if verbose:  print(( "[+] Success in %5.2f sec" % (end - start)))
        return type_list

    def getInfo (self, filename, verbose=True):
        ''' Get all information {attribute = value} pairs from the filename (public.info file),
              if it exists, otherwise, output default values'''
        if filename==None:
            basename = self.basename
            input_dir = self.input_dir
        else:
            basename = os.path.basename(filename).split('_')[0]
            input_dir = os.path.dirname(filename)
        if os.path.exists(filename):
            self.getInfoFromFile (filename)
            vprint (verbose, "Info file found : " + os.path.abspath(filename))
            # Finds the data format ('dense', 'sparse', or 'sparse_binary')
            self.getFormatData(os.path.join(input_dir, basename + '_train.data'))
        else:
            vprint (verbose, "Info file NOT found : " + os.path.abspath(filename))
            # Hopefully this never happens because this is done in a very inefficient way
            # reading the data multiple times...
            self.info['usage'] = 'No Info File'
            self.info['name'] = basename
            # Get the data format and sparsity
            self.getFormatData(os.path.join(input_dir, basename + '_train.data'))
            # Assume no categorical variable and no missing value (we'll deal with that later)
            self.info['has_categorical'] = 0
            self.info['has_missing'] = 0
            # Get the target number, label number, target type and task
            self.getTypeProblem(os.path.join(input_dir, basename + '_train.solution'))
            if self.info['task']=='regression':
                self.info['metric'] = 'r2_metric'
            else:
                self.info['metric'] = 'auc_metric'
            # Feature type: Numerical, Categorical, or Binary
            # Can also be determined from [filename].type
            self.info['feat_type'] = 'Mixed'
            # Get the number of features and patterns
            self.getNbrFeatures(os.path.join(input_dir, basename + '_train.data'), os.path.join(input_dir, basename + '_test.data'), os.path.join(input_dir, basename + '_valid.data'))
            self.getNbrPatterns(basename, input_dir, 'train')
            self.getNbrPatterns(basename, input_dir, 'valid')
            self.getNbrPatterns(basename, input_dir, 'test')
            # Set default time budget
            self.info['time_budget'] = 600
        return self.info

    def getInfoFromFile (self, filename):
        ''' Get all information {attribute = value} pairs from the public.info file'''
        with open (filename, "r") as info_file:
            lines = info_file.readlines()
            features_list = list([tuple(x.strip("\'").split(" = ")) for x in lines])

            for (key, value) in features_list:
                self.info[key] = value.rstrip().strip("'").strip(' ')
                if self.info[key].isdigit(): # if we have a number, we want it to be an integer
                    self.info[key] = int(self.info[key])
        return self.info

    def getFormatData(self,filename):
        ''' Get the data format directly from the data file (in case we do not have an info file)'''
        if 'format' in list(self.info.keys()):
            return self.info['format']
        if 'is_sparse' in list(self.info.keys()):
            if self.info['is_sparse'] == 0:
                self.info['format'] = 'dense'
            else:
                data = autokit.data_converter.read_first_line (filename)
                if ':' in data[0]:
                    self.info['format'] = 'sparse'
                else:
                    self.info['format'] = 'sparse_binary'
        else:
            data = autokit.data_converter.file_to_array (filename)
            if ':' in data[0][0]:
                self.info['is_sparse'] = 1
                self.info['format'] = 'sparse'
            else:
                nbr_columns = len(data[0])
                for row in range (len(data)):
                    if len(data[row]) != nbr_columns:
                        self.info['format'] = 'sparse_binary'
                if 'format' not in list(self.info.keys()):
                    self.info['format'] = 'dense'
                    self.info['is_sparse'] = 0
        return self.info['format']

    def getNbrFeatures (self, *filenames):
        ''' Get the number of features directly from the data file (in case we do not have an info file)'''
        if 'feat_num' not in list(self.info.keys()):
            self.getFormatData(filenames[0])
            if self.info['format'] == 'dense':
                data = autokit.data_converter.file_to_array(filenames[0])
                self.info['feat_num'] = len(data[0])
            elif self.info['format'] == 'sparse':
                self.info['feat_num'] = 0
                for filename in filenames:
                    sparse_list = autokit.data_converter.sparse_file_to_sparse_list (filename)
                    last_column = [sparse_list[i][-1] for i in range(len(sparse_list))]
                    last_column_feature = [a for (a,b) in last_column]
                    self.info['feat_num'] = max(self.info['feat_num'], max(last_column_feature))
            elif self.info['format'] == 'sparse_binary':
                self.info['feat_num'] = 0
                for filename in filenames:
                    data = autokit.data_converter.file_to_array (filename)
                    last_column = [int(data[i][-1]) for i in range(len(data))]
                    self.info['feat_num'] = max(self.info['feat_num'], max(last_column))
        return self.info['feat_num']

    def getNbrPatterns (self, basename, info_dir, datatype):
        ''' Get the number of patterns directly from the data file (in case we do not have an info file)'''
        line_num = autokit.data_converter.num_lines(os.path.join(info_dir, basename + '_' + datatype + '.data'))
        self.info[datatype+'_num'] =  line_num
        return line_num

    def getTypeProblem (self, solution_filename):
        ''' Get the type of problem directly from the solution file (in case we do not have an info file)'''
        if 'task' not in list(self.info.keys()):
            solution = np.array(autokit.data_converter.file_to_array(solution_filename))
            target_num = solution.shape[1]
            self.info['target_num']=target_num
            if target_num == 1: # if we have only one column
                solution = np.ravel(solution) # flatten
                nbr_unique_values = len(np.unique(solution))
                if nbr_unique_values < len(solution)/8:
                    # Classification
                    self.info['label_num'] = nbr_unique_values
                    if nbr_unique_values == 2:
                        self.info['task'] = 'binary.classification'
                        self.info['target_type'] = 'Binary'
                    else:
                        self.info['task'] = 'multiclass.classification'
                        self.info['target_type'] = 'Categorical'
                else:
                    # Regression
                    self.info['label_num'] = 0
                    self.info['task'] = 'regression'
                    self.info['target_type'] = 'Numerical'
            else:
                # Multilabel or multiclass
                self.info['label_num'] = target_num
                self.info['target_type'] = 'Binary'
                if any(item > 1 for item in map(np.sum,solution.astype(int))):
                    self.info['task'] = 'multilabel.classification'
                else:
                    self.info['task'] = 'multiclass.classification'
        return self.info['task']


text:
package fake

import (
	"context"

	v1beta1 "github.com/GoogleCloudPlatform/k8s-config-connector/pkg/clients/generated/apis/datafusion/v1beta1"
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	labels "k8s.io/apimachinery/pkg/labels"
	schema "k8s.io/apimachinery/pkg/runtime/schema"
	types "k8s.io/apimachinery/pkg/types"
	watch "k8s.io/apimachinery/pkg/watch"
	testing "k8s.io/client-go/testing"
)

// FakeDataFusionInstances implements DataFusionInstanceInterface
type FakeDataFusionInstances struct {
	Fake *FakeDatafusionV1beta1
	ns   string
}

var datafusioninstancesResource = schema.GroupVersionResource{Group: "datafusion.cnrm.cloud.google.com", Version: "v1beta1", Resource: "datafusioninstances"}

var datafusioninstancesKind = schema.GroupVersionKind{Group: "datafusion.cnrm.cloud.google.com", Version: "v1beta1", Kind: "DataFusionInstance"}

// Get takes name of the dataFusionInstance, and returns the corresponding dataFusionInstance object, and an error if there is any.
func (c *FakeDataFusionInstances) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.DataFusionInstance, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewGetAction(datafusioninstancesResource, c.ns, name), &v1beta1.DataFusionInstance{})

	if obj == nil {
		return nil, err
	}
	return obj.(*v1beta1.DataFusionInstance), err
}

// List takes label and field selectors, and returns the list of DataFusionInstances that match those selectors.
func (c *FakeDataFusionInstances) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.DataFusionInstanceList, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewListAction(datafusioninstancesResource, datafusioninstancesKind, c.ns, opts), &v1beta1.DataFusionInstanceList{})

	if obj == nil {
		return nil, err
	}

	label, _, _ := testing.ExtractFromListOptions(opts)
	if label == nil {
		label = labels.Everything()
	}
	list := &v1beta1.DataFusionInstanceList{ListMeta: obj.(*v1beta1.DataFusionInstanceList).ListMeta}
	for _, item := range obj.(*v1beta1.DataFusionInstanceList).Items {
		if label.Matches(labels.Set(item.Labels)) {
			list.Items = append(list.Items, item)
		}
	}
	return list, err
}

// Watch returns a watch.Interface that watches the requested dataFusionInstances.
func (c *FakeDataFusionInstances) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {
	return c.Fake.
		InvokesWatch(testing.NewWatchAction(datafusioninstancesResource, c.ns, opts))

}

// Create takes the representation of a dataFusionInstance and creates it.  Returns the server's representation of the dataFusionInstance, and an error, if there is any.
func (c *FakeDataFusionInstances) Create(ctx context.Context, dataFusionInstance *v1beta1.DataFusionInstance, opts v1.CreateOptions) (result *v1beta1.DataFusionInstance, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewCreateAction(datafusioninstancesResource, c.ns, dataFusionInstance), &v1beta1.DataFusionInstance{})

	if obj == nil {
		return nil, err
	}
	return obj.(*v1beta1.DataFusionInstance), err
}

// Update takes the representation of a dataFusionInstance and updates it. Returns the server's representation of the dataFusionInstance, and an error, if there is any.
func (c *FakeDataFusionInstances) Update(ctx context.Context, dataFusionInstance *v1beta1.DataFusionInstance, opts v1.UpdateOptions) (result *v1beta1.DataFusionInstance, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewUpdateAction(datafusioninstancesResource, c.ns, dataFusionInstance), &v1beta1.DataFusionInstance{})

	if obj == nil {
		return nil, err
	}
	return obj.(*v1beta1.DataFusionInstance), err
}

// UpdateStatus was generated because the type contains a Status member.
// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().
func (c *FakeDataFusionInstances) UpdateStatus(ctx context.Context, dataFusionInstance *v1beta1.DataFusionInstance, opts v1.UpdateOptions) (*v1beta1.DataFusionInstance, error) {
	obj, err := c.Fake.
		Invokes(testing.NewUpdateSubresourceAction(datafusioninstancesResource, "status", c.ns, dataFusionInstance), &v1beta1.DataFusionInstance{})

	if obj == nil {
		return nil, err
	}
	return obj.(*v1beta1.DataFusionInstance), err
}

// Delete takes name of the dataFusionInstance and deletes it. Returns an error if one occurs.
func (c *FakeDataFusionInstances) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {
	_, err := c.Fake.
		Invokes(testing.NewDeleteActionWithOptions(datafusioninstancesResource, c.ns, name, opts), &v1beta1.DataFusionInstance{})

	return err
}

// DeleteCollection deletes a collection of objects.
func (c *FakeDataFusionInstances) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {
	action := testing.NewDeleteCollectionAction(datafusioninstancesResource, c.ns, listOpts)

	_, err := c.Fake.Invokes(action, &v1beta1.DataFusionInstanceList{})
	return err
}

// Patch applies the patch and returns the patched dataFusionInstance.
func (c *FakeDataFusionInstances) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.DataFusionInstance, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewPatchSubresourceAction(datafusioninstancesResource, c.ns, name, pt, data, subresources...), &v1beta1.DataFusionInstance{})

	if obj == nil {
		return nil, err
	}
	return obj.(*v1beta1.DataFusionInstance), err
}


text:
/* Includes ------------------------------------------------------------------*/
#include "stm32w_systick.h"

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* ---------------------- SysTick registers bit mask -------------------- */
/* CTRL TICKINT Mask */
#define CTRL_TICKINT_Set      ((u32)0x00000002)
#define CTRL_TICKINT_Reset    ((u32)0xFFFFFFFD)

/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/

/*******************************************************************************
* Function Name  : SysTick_CLKSourceConfig
* Description    : Configures the SysTick clock source.
* Input          : - SysTick_CLKSource: specifies the SysTick clock source.
*                    This parameter can be one of the following values:
*                       - SysTick_CLKSource_HCLK_Div8: AHB clock divided by 8
*                         selected as SysTick clock source.
*                       - SysTick_CLKSource_HCLK: AHB clock selected as
*                         SysTick clock source.
* Output         : None
* Return         : None
*******************************************************************************/
void SysTick_CLKSourceConfig(u32 SysTick_CLKSource)
{
  /* Check the parameters */
  assert_param(IS_SYSTICK_CLK_SOURCE(SysTick_CLKSource));

  if (SysTick_CLKSource == SysTick_CLKSource_HCLK)
  {
    SysTick->CTRL |= SysTick_CLKSource_HCLK;
  }
  else
  {
    SysTick->CTRL &= SysTick_CLKSource_HCLK_Div8;
  }
}

/*******************************************************************************
* Function Name  : SysTick_SetReload
* Description    : Sets SysTick Reload value.
* Input          : - Reload: SysTick Reload new value.
*                    This parameter must be a number between 1 and 0xFFFFFF.
* Output         : None
* Return         : None
*******************************************************************************/
void SysTick_SetReload(u32 Reload)
{
  /* Check the parameters */
  assert_param(IS_SYSTICK_RELOAD(Reload));

  SysTick->LOAD = Reload;
}

/*******************************************************************************
* Function Name  : SysTick_CounterCmd
* Description    : Enables or disables the SysTick counter.
* Input          : - SysTick_Counter: new state of the SysTick counter.
*                    This parameter can be one of the following values:
*                       - SysTick_Counter_Disable: Disable counter
*                       - SysTick_Counter_Enable: Enable counter
*                       - SysTick_Counter_Clear: Clear counter value to 0
* Output         : None
* Return         : None
*******************************************************************************/
void SysTick_CounterCmd(u32 SysTick_Counter)
{
  /* Check the parameters */
  assert_param(IS_SYSTICK_COUNTER(SysTick_Counter));

  if (SysTick_Counter == SysTick_Counter_Enable)
  {
    SysTick->CTRL |= SysTick_Counter_Enable;
  }
  else if (SysTick_Counter == SysTick_Counter_Disable)
  {
    SysTick->CTRL &= SysTick_Counter_Disable;
  }
  else /* SysTick_Counter == SysTick_Counter_Clear */
  {
    SysTick->VAL = SysTick_Counter_Clear;
  }
}

/*******************************************************************************
* Function Name  : SysTick_ITConfig
* Description    : Enables or disables the SysTick Interrupt.
* Input          : - NewState: new state of the SysTick Interrupt.
*                    This parameter can be: ENABLE or DISABLE.
* Output         : None
* Return         : None
*******************************************************************************/
void SysTick_ITConfig(FunctionalState NewState)
{
  /* Check the parameters */
  assert_param(IS_FUNCTIONAL_STATE(NewState));

  if (NewState != DISABLE)
  {
    SysTick->CTRL |= CTRL_TICKINT_Set;
  }
  else
  {
    SysTick->CTRL &= CTRL_TICKINT_Reset;
  }
}

/*******************************************************************************
* Function Name  : SysTick_GetCounter
* Description    : Gets SysTick counter value.
* Input          : None
* Output         : None
* Return         : SysTick current value
*******************************************************************************/
u32 SysTick_GetCounter(void)
{
  return(SysTick->VAL);
}

/*******************************************************************************
* Function Name  : SysTick_GetFlagStatus
* Description    : Checks whether the specified SysTick flag is set or not.
* Input          : - SysTick_FLAG: specifies the flag to check.
*                    This parameter can be one of the following values:
*                       - SysTick_FLAG_COUNT
*                       - SysTick_FLAG_SKEW
*                       - SysTick_FLAG_NOREF
* Output         : None
* Return         : None
*******************************************************************************/
FlagStatus SysTick_GetFlagStatus(u8 SysTick_FLAG)
{
  u32 statusreg = 0, tmp = 0 ;
  FlagStatus bitstatus = RESET;

  /* Check the parameters */
  assert_param(IS_SYSTICK_FLAG(SysTick_FLAG));

  /* Get the SysTick register index */
  tmp = SysTick_FLAG >> 3;

  if (tmp == 2) /* The flag to check is in CTRL register */
  {
    statusreg = SysTick->CTRL;
  }
  else          /* The flag to check is in CALIB register */
  {
    statusreg = SysTick->CALIB;
  }

  if ((statusreg & ((u32)1 << SysTick_FLAG)) != (u32)RESET)
  {
    bitstatus = SET;
  }
  else
  {
    bitstatus = RESET;
  }
  return bitstatus;
}

/******************* (C) COPYRIGHT 2008 STMicroelectronics *****END OF FILE****/


text:
import TR from 'gui/GuiTR';

class GuiBackground {

  constructor(guiParent, ctrlGui) {
    this._main = ctrlGui._main; // main application
    this._menu = null; // ui menu
    this.init(guiParent);
  }

  init(guiParent) {
    // background fold
    var menu = this._menu = guiParent.addMenu(TR('backgroundTitle'));

    this._bg = this._main.getBackground();

    var types = ['Image', 'Environment', 'Ambient env'];
    menu.addCombobox('Type', this._bg._type, this.onBackgroundType.bind(this), types);
    this._ctrlBlur = menu.addSlider('Blur', this._bg._blur, this.onEnvBlur.bind(this), 0.0, 1.0, 0.01);
    this._ctrlBlur.setVisibility(this._bg._type === 1);

    menu.addTitle('Image');
    menu.addButton(TR('backgroundReset'), this, 'resetBackground');
    menu.addButton(TR('backgroundImport'), this, 'importBackground');
    menu.addCheckbox(TR('backgroundFill'), this._main.getBackground()._fill, this.updateFill.bind(this));
  }

  updateFill(val) {
    this._bg._fill = val;
    this._main.onCanvasResize();
  }

  resetBackground() {
    this._bg.deleteTexture();
    this._main.render();
  }

  onEnvBlur(val) {
    this._bg._blur = val;
    this._main.render();
  }

  onBackgroundType(val) {
    this._bg.setType(val);
    this._main.onCanvasResize();
    this._main.render();
    this._ctrlBlur.setVisibility(val === 1);
  }

  importBackground() {
    document.getElementById('backgroundopen').click();
  }
}

export default GuiBackground;


text:
require 'assay/assay'

class EqualityError < StandardError
  def self.assay(name, options={}, &block)
    Assay.new(name, self, options, &block)
  end
end

#def assay(name, error=StandardError, options={}, &block)
#  Assay.new(name, options, &block)
#end

#
TypeError.assay(:kind_of) do |target, criterion|
  target.kind_of?(criterion)
end

#
TypeError.assay(:instance_of)  do |target, criterion|
  target.instance_of?(criterion)
end

#
EqualityError.assay(:identical) do |target, criterion|
  criterion.object_id == target.object_id
end

#
#assay :equal, EqualityError do |target, criterion|
#  criterion.equal?(target)
#end

#
EqualityError.assay :eql  do |target, criterion|
  criterion.eql?(target)
end

#
EqualityError.assay :eq, :operator=>:== do |target, criterion|
  criterion == target
end

#
EqualityError.assay :like  do |target, criterion|
  criterion === target     ||
  criterion.equal?(target) ||
  criterion.eql?(target)   ||
  criterion.==(target)
end

#
StandardError.assay :empty do |target|
  target.empty?
end

#
StandardError.assay :include do |target, criterion|
  target.include?(criterion)
end

StandardError.assay :false  do |target|
  FalseClass = target  # target.false?
end

StandardError.assay :true  do |target|
  TrueClass = target   # target.true?
end

StandardError.assay :nil  do |target|
  NilClass = target    # target.nil?
end

NoMethodError.assay :respond_to |target, method|
  target.respond_to?(method)
end


text:
require 'optparse'

module Rcodetools
# Domain specific OptionParser extensions
module OptionHandler
  def set_banner
    self.banner = "Usage: #{$0} [options] [inputfile] [-- cmdline args]"
  end

  def handle_position(options)
    separator ""
    separator "Position options:"
    on("--line=LINE", "Current line number.") do |n|
      options[:lineno] = n.to_i
    end
    on("--column=COLUMN", "Current column number in BYTE.") do |n|
      options[:column] = n.to_i
    end
    on("-t TEST", "--test=TEST",
       "Execute test script. ",
       "TEST is TESTSCRIPT, TESTSCRIPT@TESTMETHOD, or TESTSCRIPT@LINENO.",
       "You must specify --filename option.") do |t|
      options[:test_script], options[:test_method] = t.split(/@/)
    end
    on("--filename=FILENAME", "Filename of standard input.") do |f|
      options[:filename] = f
    end
  end

  def handle_interpreter(options)
    separator ""
    separator "Interpreter options:"
    on("-S FILE", "--interpreter FILE", "Use interpreter FILE.") do |interpreter|
      options[:interpreter] = interpreter
    end
    on("-I PATH", "Add PATH to $LOAD_PATH") do |path|
      options[:include_paths] << path
    end
    on("--dev", "Add this project's bin/ and lib/ to $LOAD_PATH.",
       "A directory with a Rakefile is considered a project base directory.") do
      auto_include_paths(options[:include_paths], Dir.pwd)
    end
    on("-r LIB", "Require LIB before execution.") do |lib|
      options[:libs] << lib
    end
    on("-e EXPR", "--eval=EXPR", "--stub=EXPR", "Evaluate EXPR after execution.") do |expr|
      options[:evals] << expr
    end
    on("--fork", "Use rct-fork-client if rct-fork is running.") do
      options[:detect_rct_fork] = true
    end
    on("--rbtest", "Use rbtest.") do
      options[:use_rbtest] = true
    end
    on("--detect-rbtest", "Use rbtest if '=begin test_*' blocks exist.") do
      options[:detect_rbtest] = true
    end
  end

  def handle_misc(options)
    separator ""
    separator "Misc options:"
    on("--cd DIR", "Change working directory to DIR.") do |dir|
      options[:wd] = dir
    end
    on("--debug", "Write transformed source code to xmp-tmp.PID.rb.") do
      options[:dump] = "xmp-tmp.#{Process.pid}.rb"
    end
    on("--tmpfile", "--tempfile", "Use tmpfile instead of open3. (non-windows)") do
      options[:execute_ruby_tmpfile] = true
    end
    on("-w N", "--width N", Integer, "Set width of multi-line annotation. (xmpfilter only)") do |width|
      options[:width] = width
    end
    separator ""
    on("-h", "--help", "Show this message") do
      puts self
      exit
    end
    on("-v", "--version", "Show version information") do
      puts "#{File.basename($0)} #{XMPFilter::VERSION}"
      exit
    end
  end

  def auto_include_paths(include_paths, pwd)
    if pwd =~ %r!^(.+)/(lib|bin)!
      include_paths.unshift("#$1/lib").unshift("#$1/bin")
    elsif File.file? "#{pwd}/Rakefile" or File.file? "#{pwd}/rakefile"
      include_paths.unshift("#{pwd}/lib").unshift("#{pwd}/bin")
    end
  end
  module_function :auto_include_paths

end

def set_extra_opts(options)
  if idx = ARGV.index("--")
    options[:options] = ARGV[idx+1..-1]
    ARGV.replace ARGV[0...idx]
  else
    options[:options] = []
  end
end

def check_opts(options)
  if options[:test_script]
    unless options[:filename]
      $stderr.puts "You must specify --filename as well as -t(--test)."
      exit 1
    end
  end
end

DEFAULT_OPTIONS = {
  :interpreter       => "ruby",
  :options => ["hoge"],
  :min_codeline_size => 50,
  :width             => 79,
  :libs              => [],
  :evals             => [],
  :include_paths     => [],
  :dump              => nil,
  :wd                => nil,
  :warnings          => true,
  :use_parentheses   => true,
  :column            => nil,
  :output_stdout     => true,
  :test_script       => nil,
  :test_method       => nil,
  :detect_rct_fork   => false,
  :use_rbtest        => false,
  :detect_rbtest     => false,
  :execute_ruby_tmpfile => false,
  }
end                             # /Rcodetools


text:
public class Variable
{

	public Variable()
	{

	}

}


text:
import chai from 'chai';
import sinon from 'sinon';
import 'sinon-mongoose';
import 'sinon-as-promised';
import UrlSchema from '../../src/schemas/urlSchema';
import ShortUrlRepository from '../../src/url/shortUrlRepository';
import httpMocks from 'node-mocks-http';
import mongoose from 'mongoose';

const expect = chai.expect;

mongoose.Promise = global.Promise;

describe('Short URL Repository', () => {
  let Repository;

  before(() => {
    Repository = new ShortUrlRepository();
  });

  it('Should save a new Short URL', () => {
    let ShortUrl = new UrlSchema({
      url: 'https://medium.com',
      shortUrl: 'abc123'
    });

    sinon.stub(ShortUrl, 'save');

    Repository.persist(ShortUrl);

    sinon.assert.calledWith(ShortUrl.save);
  });

  it('Should findOneAndUpdate ShortUrl by ShortUrl id', (done) => {
    let ShortUrl = new UrlSchema({
      url: 'https://medium.com',
      shortUrl: 'abc123'
    });

    sinon.stub(UrlSchema, 'findOneAndUpdate').resolves(ShortUrl);

    const shortUrl = Repository.getShortUrlById('abc123', 'https://google.com');

    shortUrl.then((response) => {
      expect(response.url).to.equal('https://medium.com');
      expect(response.shortUrl).to.equal('abc123');
      expect(response).to.have.property('_id');
      done();
    })
  });
});


text:
package com.tlear.trise;

import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.math.Vector2;
import com.tlear.trise.environment.Environment;
import com.tlear.trise.graph.Edge;
import com.tlear.trise.graph.Node;
import com.tlear.trise.graph.TrackedGraph;
import com.tlear.trise.interactions.OmniscientSensor;
import com.tlear.trise.interactions.Sensor;
import com.tlear.trise.metrics.ImmutableMetrics;
import com.tlear.trise.objects.Agent;
import com.tlear.trise.objects.EnvObject;
import com.tlear.trise.objects.StaticGoal;
import com.tlear.trise.objects.StaticObstacle;
import com.tlear.trise.utils.Triple;

public class Simulation {

	private Environment env;

	private Map<Integer, Integer> timeMap;
	private Agent initAgent;
	private int prevKeyframe, nextKeyframe;
	private int time;
	private TrackedGraph<Vector2> g;

	private TRISE parent;

	private String infoText;

	public EnvObject selectedObject;

	public void reset() {
		timeMap = new LinkedHashMap<>();
		timeMap.put(0, 0);
		prevKeyframe = 0;
		nextKeyframe = 0;
		time = 0;
		env.agents = new LinkedList<>();
		env.agents.add(new Agent(initAgent));
		env.dirty();
		Triple<Integer, Integer, TrackedGraph<Vector2>> next = env
				.getNextKeyframe(timeMap);
		timeMap.put(next.fst, next.snd);
		g = next.thd;

		nextKeyframe++;
	}

	public Simulation(TRISE parent) {
		this.parent = parent;

		infoText = "";

		createSim();

		timeMap = new LinkedHashMap<>();
		timeMap.put(0, 0);

		prevKeyframe = 0;
		nextKeyframe = 0;

		time = 0;

		Triple<Integer, Integer, TrackedGraph<Vector2>> next = env
				.getNextKeyframe(timeMap);
		timeMap.put(next.fst, next.snd);
		g = next.thd;

		nextKeyframe++;

		selectedObject = null;
	}

	public void update() {
		// System.out.println("UPDATE SIMULATION");
		// System.out.println("PREV: " + prevKeyframe + ", NEXT: " +
		// nextKeyframe);
		// System.out.println("TIME MAP: " + timeMap.toString());

		// System.out.println(nextKeyframe);

		if (env.agents.isEmpty()) {
			System.out.println("NO AGENT");
			parent.modeSim = false;
		}
		if (env.goals.isEmpty()) {
			System.out.println("NO GOAL");
			parent.modeSim = false;
		}

		if (timeMap.get(nextKeyframe) == time) {
			prevKeyframe = nextKeyframe;

			Triple<Integer, Integer, TrackedGraph<Vector2>> next = env
					.getNextKeyframe(timeMap);
			timeMap.put(next.fst, next.snd);
			g = next.thd;

			nextKeyframe++;
		}

		// System.out.println(time);

		time++;
		env.update(timeMap, prevKeyframe, time, nextKeyframe);
	}

	public void draw(ShapeRenderer sr, SpriteBatch batch) {

		BitmapFont font = new BitmapFont();
		font.setColor(Color.WHITE);

		// Draw the graph
		if (parent.showGraph) {
			sr.begin(ShapeType.Line);
			sr.setColor(0, 0, 0, 1);
			for (Edge<Vector2> e : g.getEdges()) {
				sr.line(e.fst.getValue(), e.snd.getValue());
			}
			sr.end();
			sr.begin(ShapeType.Filled);
			sr.setColor(1, 1, 0, 1);
			for (Node<Vector2> n : g.getNodes()) {
				if (g.visited(n)) {
					sr.setColor(0, 0, 1, 1);
				} else {
					sr.setColor(1, 1, 0, 1);
				}
				Vector2 v = n.getValue();
				sr.circle(v.x, v.y, 2);
			}
			sr.end();
		}

		env.draw(sr, batch);

		// System.out.println(g.getExploredNodes().size() + " / " +
		// g.getNodes().size());

		batch.begin();
		// font.draw(batch, (float) (100 * g.getExploredNodes().size() /
		// g.getNodes().size()) + "%", 600, 50);
		font.draw(batch, parent.modeEdit ? "EDIT" : "",
				Gdx.graphics.getWidth() * 9 / 10, 100);
		font.draw(batch, parent.modeSim ? "SIMULATING" : "",
				Gdx.graphics.getWidth() * 9 / 10, 150);
		font.draw(batch, parent.modeNewObject ? "NEW OBJECT" : "",
				Gdx.graphics.getWidth() * 9 / 10, 200);
		int bottom = 250;
		int left = Gdx.graphics.getWidth() * 8 / 10;
		for (Agent agent : env.agents) {
			ImmutableMetrics metrics = agent.getMetrics();
			String text = "";
			text += metrics.isSet(metrics.getNodesExplored()) ? String.format(
					"Nodes explored: \n%d\n", metrics.getNodesExplored()) : "";
			text += metrics.isSet(metrics.getNodesInFrontier()) ? String
					.format("Nodes in frontier: \n%d\n",
							metrics.getNodesInFrontier()) : "";
			text += metrics.isSet(metrics.getTimeToSkeletonise()) ? String
					.format("Time to skeletonise: \n%dms\n",
							metrics.getTimeToSkeletonise()) : "";
			text += metrics.isSet(metrics.getTimeToSearch()) ? String.format(
					"Time to search: \n%dms\n", metrics.getTimeToSearch()) : "";
			text += metrics.isSet(metrics.getTimeToReachGoal()) ? String
					.format("Time to reach goal: \n%dms\n",
							metrics.getTimeToReachGoal()) : "";
			font.drawMultiLine(batch, text, left, bottom);
		}
		font.draw(batch, String.format("\n%s\n", infoText),
				Gdx.graphics.getHeight() * 9 / 10, 50);
		batch.end();
	}

	/**
	 * Returns which, if any, object contains this point
	 *
	 * @param pos
	 * @return
	 */
	public EnvObject getObjectContainingPoint(Vector2 pos) {
		for (Agent a : env.agents) {
			if (a.containsPoint(pos)) {
				return a;
			}
		}
		for (StaticObstacle o : env.obstacles) {
			if (o.containsPoint(pos)) {
				return o;
			}
		}
		for (StaticGoal g : env.goals) {
			if (g.containsPoint(pos)) {
				return g;
			}
		}
		return null;
	}

	public void selectEnvObject(EnvObject obj) {
		// Pre: obj != null
		if (obj == null) {
			throw new NullPointerException(
					"Object to be selected must not be null!!!");
		}
		if (!obj.selected) {
			obj.select();
			if (selectedObject != null) {
				selectedObject.deselect();
			}
			selectedObject = obj;
		} else {
			obj.deselect();
			selectedObject = null;
		}
	}

	public void dirtyEnvironment() {
		env.dirty();
	}

	public void cleanEnvironment() {
		env.clean();
	}

	private void createSim() {
		env = new Environment();

		StaticObstacle o = new StaticObstacle(100, 100, 100, 100);
		env.placeObstacle(o);
		o = new StaticObstacle(300, 300, 100, 100);
		env.placeObstacle(o);
		o = new StaticObstacle(100, 300, 100, 100);
		env.placeObstacle(o);
		o = new StaticObstacle(300, 100, 100, 100);
		env.placeObstacle(o);

		StaticGoal g = new StaticGoal(450, 450, 20, 20);
		env.placeGoal(g);

		HashSet<Sensor> sensors = new HashSet<>();
		sensors.add(new OmniscientSensor());
		// sensors.add(new ProximitySensor(0, 0, 0, 0));

		Agent a = new Agent(10, 10, 25, 25, env, sensors);
		initAgent = new Agent(a);
		env.placeAgent(a);

		// g = new StaticGoal(250, 250, 20, 20);
		// env.placeGoal(g);
		// g = new StaticGoal(450, 250, 20, 20);
		// env.placeGoal(g);
		// g = new StaticGoal(250, 450, 20, 20);
		// env.placeGoal(g);
		// g = new StaticGoal(250, 50, 20, 20);
		// env.placeGoal(g);
		// g = new StaticGoal(50, 250, 20, 20);
		// env.placeGoal(g);

		// System.out.println("Creating sim: " + env);
	}

	public void deleteObject(EnvObject obj) {
		if (obj instanceof Agent) {
			env.agents.remove(obj);
		} else if (obj instanceof StaticObstacle) {
			env.obstacles.remove(obj);
		} else if (obj instanceof StaticGoal) {
			env.goals.remove(obj);
		} else {
			throw new RuntimeException(
					"Could not delete object from simulation");
		}

	}

	public void addObject(boolean agent, boolean obstacle, boolean goal) {
		if (agent) {
			System.out.println("NOT YET IMPLEMENTED");

		} else if (obstacle) {
			StaticObstacle o = new StaticObstacle(Gdx.input.getX(),
					Gdx.graphics.getHeight() - Gdx.input.getY(), 50, 50);
			env.placeObstacle(o);
		} else if (goal) {
			Vector2 mousePos = new Vector2(Gdx.input.getX(),
					Gdx.graphics.getHeight() - Gdx.input.getY());
			for (StaticObstacle o : env.obstacles) {
				if (o.containsPoint(mousePos)) {
					System.out.println("COULD NOT PLACE GOAL IN OBSTACLE");
					return;
				}
			}
			StaticGoal g = new StaticGoal(Gdx.input.getX(),
					Gdx.graphics.getHeight() - Gdx.input.getY(), 20, 20);
			env.placeGoal(g);

		}

		dirtyEnvironment();
	}

	/**
	 * Set the info text to be displayed currently.
	 *
	 * @param text
	 */
	public void setInfoText(String text) {
		infoText = text;
	}
}


text:
import { text } from '@storybook/addon-knobs';
import { forModule } from 'storybook-addon-angularjs';

import Tooltip from '@ovh-ux/ui-kit.tooltip';

import { compileTemplate } from '../../../src/utils';

const moduleName = 'tooltip.stories';
angular.module(moduleName, [Tooltip]);

export default {
  title: 'Legacy/Directives/Tooltip',

  parameters: {
    options: {
      showPanel: true,
    },
  },
};

export const StaticTitleAttribute = forModule(moduleName).createElement(
  () => compileTemplate(
    `

      focus or hover me

      <button class="oui-button oui-button_primary" title="Lorem ipsum" oui-tooltip>focus or hover me</button>

      <input type="text" class="oui-input oui-input_inline" placeholder="focus or hover me" title="Lorem ipsum" oui-tooltip>

`,
  ),
);

StaticTitleAttribute.story = {
  name: 'Static (title attribute)',
};

export const DynamicOuiTooltipAttribute = forModule(moduleName).createElement(
  () => compileTemplate(
    `

      focus or hover me

      <button class="oui-button oui-button_primary" oui-tooltip="{{ $ctrl.text }}">focus or hover me</button>

      <input type="text" class="oui-input oui-input_inline" placeholder="focus or hover me" oui-tooltip="{{ $ctrl.text }}">

`,
    {
      $ctrl: {
        text: text('Text', 'Lorem ipsum'),
      },
    },
  ),
);

DynamicOuiTooltipAttribute.story = {
  name: 'Dynamic (oui-tooltip attribute)',
};

export const Directions = forModule(moduleName).createElement(
  () => compileTemplate(
    `

      <input type="text" class="oui-input oui-input_inline" placeholder="Top Left" oui-tooltip="Lorem ipsum" oui-tooltip-placement="top-start">

      <input type="text" class="oui-input oui-input_inline" placeholder="Top Center" oui-tooltip="Lorem ipsum" oui-tooltip-placement="top">

      <input type="text" class="oui-input oui-input_inline" placeholder="Top Right" oui-tooltip="Lorem ipsum" oui-tooltip-placement="top-end">

      <input type="text" class="oui-input oui-input_inline" placeholder="Bottom Left" oui-tooltip="Lorem ipsum" oui-tooltip-placement="bottom-start">

      <input type="text" class="oui-input oui-input_inline" placeholder="Bottom Center" oui-tooltip="Lorem ipsum" oui-tooltip-placement="bottom">

      <input type="text" class="oui-input oui-input_inline" placeholder="Bottom Right" oui-tooltip="Lorem ipsum" oui-tooltip-placement="bottom-end">

`,
  ),
);


text:
using Foundation;
using System;
using System.Collections.Generic;
using System.Text;

namespace DSoft.MessageBus
{
    public partial class ThreadControl
    {
        static bool PlatformIsMainThread => NSThread.Current.IsMainThread;

        static void PlatformBeginInvokeOnMainThread(Action action)
        {
            NSRunLoop.Main.BeginInvokeOnMainThread(action.Invoke);
        }

    }
}


text:
module Envault
  DEFAULT_SOURCE_FILE = ".env"
  DEFAULT_ENV_PREFIX = "ENVAULT_"
  DEFAULT_CIPHER = "aes-256-cbc"
  DEFAULT_DIGEST = "SHA256"
  SKIP_INITIALIZE_COMMANDS = ["reencrypt_file"]
end


text:
"""
Utlity functions.
"""

def check_insteon_id(identifier):
    """
    Makes sure an identifier is a reasonable one for INSTEON devices.

    :param identifier: ID to check.
    :type identifier: bytes
    """
    if type(identifier) != bytes:
        return False

    if len(identifier) != 3:
        return False

    return True


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Design for the Hopeless – Experiences with Front-End Development">
    <meta name="author" content="theJoeBlankenship">

    <title>theJoeBlankenship</title>

    <link rel="icon" type="image/ico" href="../../img/favicon.ico">

    <link href="../../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="../../css/clean-blog.min.css" rel="stylesheet">

    <link href="../../vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation
                    Menu
                </button>
                theJoeBlankenship

                        News

                        Research

                        About

Design for the Hopeless

Experiences with Front-End Development

                        Posted by Joe Blankenship on February 28, 2018

"What is the marker of good design? It moves... Design gains value as it moves from hand to hand; context to context; need to need." - Frank Chimero

Introduction

I will admit that I still do not consider myself a good front-end developer or designer despite my best efforts, but I think the challenge of trying to be creative in web design is what keeps me coming back to this challenging set
                        of concepts. Since my focus has been on data science and GIS, I often opted to find web page and dashboard templates that I could simply drop in, modify, and represent data to customers in an "efficient enough" manner. Due to the
                        work of many incredibly talented web developers and designers, I never really had to engage with all that goes into building good HTML and CSS nor did I have to engage with JavaScript (something I always hated manipulating and
                        programming in). However, I was long overdue for a change in my mindset towards all of the above.

I recently started taking a UX/UI course through the New Maps Plus Program at the University of Kentucky (a program that I can't recommend highly enough). This forced me to
                        really open my eyes in reconsideration of all the misconceptions I had about serious web development and front-end design. New Maps Plus not only addressed my long-standing neglect with these, but did so using cartography and interactive
                        data visualizations (two things I absolutely love in a great data journalism article or website). The following sections cover the biggest takeaways thus far from my adventures and struggles with front-end web development.

                    Household Composition in West Virginia

Forget What You Think You Know

I came into the UX/UI course with a chip on my shoulder: I did not like doing anything in JavaScript. If I could wrap anything I was doing with Python so that I didn't have to touch JavaScript, I did. However, this was due to my misunderstanding
                        of JavaScript and my laziness in not dedicating enough time to program in JavaScript and to understand all that could be done with it in web development and beyond.

Once I let go of my ignorance and stubbornness, I was able to understand and really enjoy developing in JavaScript. In many ways, I improved the data science work I was already doing with a number of new skill sets. I use to urge newcomers
                        to programming to start with something like Python. However, if you are new to programming and are looking to start with web development, I'm now more prone to point you at Bootstrap and Node than at Django and Flask. Understanding
                        the former will make the experience of the latter much more rewarding.

                    Rates of Unemployment in the US

Struggle Better

Much like learning any new skill, you have to make it matter to you. You should also try to make it as "fun" as possible: "gamify" projects and make them relevant to things that you have a passion for. I did not take a UX/UI course
                        because I wanted to advance a career in web development; I wanted to make my research and data service products more visually effective and pleasing to the viewers. I challenged myself using areas of interest I enjoyed (e.g., maps
                        and interactive data visualizations) and with materials that intrigued me (e.g., data sets I considered cool). This ultimately pushed me to obtain and adapt my knowledge in a way that positively reinforced the processes and experiences.

This is not to say that I don't struggle with new topics: we all do. But you have to make that struggle matter and at the end you have to say not only was it worth it, but I can now help myself and others using all of my hard-earned
                        experience.

                    Kenya: Education and Progress

You Have To Feel

One of the best part of the UX/UI course was the introduction of conceptual literature on design. From QT to Electron, I had used frameworks and build UIs, but never once had I been told why to build things in a certain way or why
                        to abandon all of those guidelines for something better. Frank Chimero's book, The Shape of Design, really opened my eyes to how a person or group should approach UI
                        development for another group of people. I realized how much I had neglected the UX aspect of any website or data visualization I had previously built.

This failure was not largely because the things I built were bad or didn't function, it was due to the fact that I had not considered how the user would feel about what I built or consider it worth their time. I never considered how
                        the colors and arrangement could be "beautiful" to a viewer or how narrative and flow "affect" the people my creation is meant to assist in understanding something. I started to understand that once my front-end was built, that
                        was only the beginning of my work; I had to then take that product and consider who would be using it and how I could make it better for them. This is probably the biggest takeaway for me thus far.

                    Submarine Cables

Keep Doing It

Any person that uses code in their work will tell you that programming is a perishable skill; if you don't use it, you lose it. The same thing goes for good design. Read up everyday on good design practices, not just in areas that
                        are relevant to you. A web developer can learn a lot about color theory from interior designers and a lot about arrangement from architects.

Find inspiration everywhere.

If you're able to find inspiration in the everyday, your work will reflect the techniques and sensitivities to the world that you built it for and the return to you as the developer and designer will be many times more than the simplified
                        approach of requirements-based development practices.

You want your work to do more than just work; you want your work to move others.

                        References

                        Eloquent JavaScript

                        The Shape of Design

                        Laws of UX

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Copyright © 2015-2022 Joe Blankenship


text:
import translations from '../data/translations'

export function _t(key) {
  return translations[key]
}


text:
package org.apache.causeway.viewer.wicket.viewer.registries.components;

import java.util.List;

import org.apache.wicket.model.IModel;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;

import static org.hamcrest.MatcherAssert.assertThat;

import org.apache.causeway.viewer.commons.model.components.UiComponentType;
import org.apache.causeway.viewer.wicket.ui.ComponentFactory;
import org.apache.causeway.viewer.wicket.ui.ComponentFactory.ApplicationAdvice;
import org.apache.causeway.viewer.wicket.ui.ComponentFactoryAbstract;
import org.apache.causeway.viewer.wicket.ui.components.collection.selector.CollectionPresentationSelectorHelper;
import org.apache.causeway.viewer.wicket.ui.components.collectioncontents.ajaxtable.CollectionContentsAsAjaxTablePanelFactory;

import lombok.val;

class ComponentFactoryRegistryDefaultTest {

    private ComponentFactory one;
    private ComponentFactory two;
    private ComponentFactory ajaxTableComponentFactory;

    @BeforeEach
    void setUp() throws Exception {

        ajaxTableComponentFactory = new CollectionContentsAsAjaxTablePanelFactory() {
            private static final long serialVersionUID = 1L;
            @Override public ApplicationAdvice appliesTo(final IModel<?> model) {
                return ApplicationAdvice.APPLIES;
            }
        };

        one = Mockito.mock(ComponentFactoryAbstract.class);
        Mockito.when(one.getComponentType()).thenReturn(UiComponentType.COLLECTION_CONTENTS);
        Mockito.when(one.appliesTo(UiComponentType.COLLECTION_CONTENTS, null)).thenReturn(ApplicationAdvice.APPLIES);

        two = Mockito.mock(ComponentFactoryAbstract.class);
        Mockito.when(two.getComponentType()).thenReturn(UiComponentType.COLLECTION_CONTENTS);
        Mockito.when(two.appliesTo(UiComponentType.COLLECTION_CONTENTS, null)).thenReturn(ApplicationAdvice.APPLIES);
    }

    @Test
    void testOrderAjaxTableToEnd() {

        val compRegistry = ComponentFactoryRegistryDefault.forTesting(List.of(
                one,
                ajaxTableComponentFactory,
                two));

        val orderAjaxTableToEnd = new CollectionPresentationSelectorHelper(null, compRegistry)
                .getComponentFactories();

        assertThat(orderAjaxTableToEnd, Matchers.contains(
                one,
                two,
                ajaxTableComponentFactory));

    }

}


text:
<?php

namespace Cake\Auth;

use Cake\Controller\ComponentRegistry;
use Cake\Core\InstanceConfigTrait;
use Cake\Network\Request;

/**
 * Abstract base authorization adapter for AuthComponent.
 *
 * @see \Cake\Controller\Component\AuthComponent::$authenticate
 */
abstract class BaseAuthorize
{

    use InstanceConfigTrait;

    /**
     * ComponentRegistry instance for getting more components.
     *
     * @var \Cake\Controller\ComponentRegistry
     */
    protected $_registry;

    /**
     * Default config for authorize objects.
     *
     * @var array
     */
    protected $_defaultConfig = [];

    /**
     * Constructor
     *
     * @param \Cake\Controller\ComponentRegistry $registry The controller for this request.
     * @param array $config An array of config. This class does not use any config.
     */
    public function __construct(ComponentRegistry $registry, array $config = [])
    {
        $this->_registry = $registry;
        $this->config($config);
    }

    /**
     * Checks user authorization.
     *
     * @param array|\ArrayAccess $user Active user data
     * @param \Cake\Network\Request $request Request instance.
     * @return bool
     */
    abstract public function authorize($user, Request $request);
}


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

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * Details of the Studio Lifecycle Configuration.
 *

 *
 * @see AWS API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class StudioLifecycleConfigDetails implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * The Amazon Resource Name (ARN) of the Lifecycle Configuration.
     *

     */
    private String studioLifecycleConfigArn;
    /**
     *

     * The name of the Studio Lifecycle Configuration.
     *

     */
    private String studioLifecycleConfigName;
    /**
     *

     * The creation time of the Studio Lifecycle Configuration.
     *

     */
    private java.util.Date creationTime;
    /**
     *

     * This value is equivalent to CreationTime because Studio Lifecycle Configurations are immutable.
     *

     */
    private java.util.Date lastModifiedTime;
    /**
     *

     * The App type to which the Lifecycle Configuration is attached.
     *

     */
    private String studioLifecycleConfigAppType;

    /**
     *

     * The Amazon Resource Name (ARN) of the Lifecycle Configuration.
     *

     *
     * @param studioLifecycleConfigArn
     *        The Amazon Resource Name (ARN) of the Lifecycle Configuration.
     */

    public void setStudioLifecycleConfigArn(String studioLifecycleConfigArn) {
        this.studioLifecycleConfigArn = studioLifecycleConfigArn;
    }

    /**
     *

     * The Amazon Resource Name (ARN) of the Lifecycle Configuration.
     *

     *
     * @return The Amazon Resource Name (ARN) of the Lifecycle Configuration.
     */

    public String getStudioLifecycleConfigArn() {
        return this.studioLifecycleConfigArn;
    }

    /**
     *

     * The Amazon Resource Name (ARN) of the Lifecycle Configuration.
     *

     *
     * @param studioLifecycleConfigArn
     *        The Amazon Resource Name (ARN) of the Lifecycle Configuration.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public StudioLifecycleConfigDetails withStudioLifecycleConfigArn(String studioLifecycleConfigArn) {
        setStudioLifecycleConfigArn(studioLifecycleConfigArn);
        return this;
    }

    /**
     *

     * The name of the Studio Lifecycle Configuration.
     *

     *
     * @param studioLifecycleConfigName
     *        The name of the Studio Lifecycle Configuration.
     */

    public void setStudioLifecycleConfigName(String studioLifecycleConfigName) {
        this.studioLifecycleConfigName = studioLifecycleConfigName;
    }

    /**
     *

     * The name of the Studio Lifecycle Configuration.
     *

     *
     * @return The name of the Studio Lifecycle Configuration.
     */

    public String getStudioLifecycleConfigName() {
        return this.studioLifecycleConfigName;
    }

    /**
     *

     * The name of the Studio Lifecycle Configuration.
     *

     *
     * @param studioLifecycleConfigName
     *        The name of the Studio Lifecycle Configuration.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public StudioLifecycleConfigDetails withStudioLifecycleConfigName(String studioLifecycleConfigName) {
        setStudioLifecycleConfigName(studioLifecycleConfigName);
        return this;
    }

    /**
     *

     * The creation time of the Studio Lifecycle Configuration.
     *

     *
     * @param creationTime
     *        The creation time of the Studio Lifecycle Configuration.
     */

    public void setCreationTime(java.util.Date creationTime) {
        this.creationTime = creationTime;
    }

    /**
     *

     * The creation time of the Studio Lifecycle Configuration.
     *

     *
     * @return The creation time of the Studio Lifecycle Configuration.
     */

    public java.util.Date getCreationTime() {
        return this.creationTime;
    }

    /**
     *

     * The creation time of the Studio Lifecycle Configuration.
     *

     *
     * @param creationTime
     *        The creation time of the Studio Lifecycle Configuration.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public StudioLifecycleConfigDetails withCreationTime(java.util.Date creationTime) {
        setCreationTime(creationTime);
        return this;
    }

    /**
     *

     * This value is equivalent to CreationTime because Studio Lifecycle Configurations are immutable.
     *

     *
     * @param lastModifiedTime
     *        This value is equivalent to CreationTime because Studio Lifecycle Configurations are immutable.
     */

    public void setLastModifiedTime(java.util.Date lastModifiedTime) {
        this.lastModifiedTime = lastModifiedTime;
    }

    /**
     *

     * This value is equivalent to CreationTime because Studio Lifecycle Configurations are immutable.
     *

     *
     * @return This value is equivalent to CreationTime because Studio Lifecycle Configurations are immutable.
     */

    public java.util.Date getLastModifiedTime() {
        return this.lastModifiedTime;
    }

    /**
     *

     * This value is equivalent to CreationTime because Studio Lifecycle Configurations are immutable.
     *

     *
     * @param lastModifiedTime
     *        This value is equivalent to CreationTime because Studio Lifecycle Configurations are immutable.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public StudioLifecycleConfigDetails withLastModifiedTime(java.util.Date lastModifiedTime) {
        setLastModifiedTime(lastModifiedTime);
        return this;
    }

    /**
     *

     * The App type to which the Lifecycle Configuration is attached.
     *

     *
     * @param studioLifecycleConfigAppType
     *        The App type to which the Lifecycle Configuration is attached.
     * @see StudioLifecycleConfigAppType
     */

    public void setStudioLifecycleConfigAppType(String studioLifecycleConfigAppType) {
        this.studioLifecycleConfigAppType = studioLifecycleConfigAppType;
    }

    /**
     *

     * The App type to which the Lifecycle Configuration is attached.
     *

     *
     * @return The App type to which the Lifecycle Configuration is attached.
     * @see StudioLifecycleConfigAppType
     */

    public String getStudioLifecycleConfigAppType() {
        return this.studioLifecycleConfigAppType;
    }

    /**
     *

     * The App type to which the Lifecycle Configuration is attached.
     *

     *
     * @param studioLifecycleConfigAppType
     *        The App type to which the Lifecycle Configuration is attached.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see StudioLifecycleConfigAppType
     */

    public StudioLifecycleConfigDetails withStudioLifecycleConfigAppType(String studioLifecycleConfigAppType) {
        setStudioLifecycleConfigAppType(studioLifecycleConfigAppType);
        return this;
    }

    /**
     *

     * The App type to which the Lifecycle Configuration is attached.
     *

     *
     * @param studioLifecycleConfigAppType
     *        The App type to which the Lifecycle Configuration is attached.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see StudioLifecycleConfigAppType
     */

    public StudioLifecycleConfigDetails withStudioLifecycleConfigAppType(StudioLifecycleConfigAppType studioLifecycleConfigAppType) {
        this.studioLifecycleConfigAppType = studioLifecycleConfigAppType.toString();
        return this;
    }

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

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

        if (obj instanceof StudioLifecycleConfigDetails == false)
            return false;
        StudioLifecycleConfigDetails other = (StudioLifecycleConfigDetails) obj;
        if (other.getStudioLifecycleConfigArn() == null ^ this.getStudioLifecycleConfigArn() == null)
            return false;
        if (other.getStudioLifecycleConfigArn() != null && other.getStudioLifecycleConfigArn().equals(this.getStudioLifecycleConfigArn()) == false)
            return false;
        if (other.getStudioLifecycleConfigName() == null ^ this.getStudioLifecycleConfigName() == null)
            return false;
        if (other.getStudioLifecycleConfigName() != null && other.getStudioLifecycleConfigName().equals(this.getStudioLifecycleConfigName()) == false)
            return false;
        if (other.getCreationTime() == null ^ this.getCreationTime() == null)
            return false;
        if (other.getCreationTime() != null && other.getCreationTime().equals(this.getCreationTime()) == false)
            return false;
        if (other.getLastModifiedTime() == null ^ this.getLastModifiedTime() == null)
            return false;
        if (other.getLastModifiedTime() != null && other.getLastModifiedTime().equals(this.getLastModifiedTime()) == false)
            return false;
        if (other.getStudioLifecycleConfigAppType() == null ^ this.getStudioLifecycleConfigAppType() == null)
            return false;
        if (other.getStudioLifecycleConfigAppType() != null && other.getStudioLifecycleConfigAppType().equals(this.getStudioLifecycleConfigAppType()) == false)
            return false;
        return true;
    }

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

        hashCode = prime * hashCode + ((getStudioLifecycleConfigArn() == null) ? 0 : getStudioLifecycleConfigArn().hashCode());
        hashCode = prime * hashCode + ((getStudioLifecycleConfigName() == null) ? 0 : getStudioLifecycleConfigName().hashCode());
        hashCode = prime * hashCode + ((getCreationTime() == null) ? 0 : getCreationTime().hashCode());
        hashCode = prime * hashCode + ((getLastModifiedTime() == null) ? 0 : getLastModifiedTime().hashCode());
        hashCode = prime * hashCode + ((getStudioLifecycleConfigAppType() == null) ? 0 : getStudioLifecycleConfigAppType().hashCode());
        return hashCode;
    }

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

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.sagemaker.model.transform.StudioLifecycleConfigDetailsMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
package com.alekseyzhelo.evilislands.mobplugin.script.psi.base;

import com.alekseyzhelo.evilislands.mobplugin.script.psi.EIExpression;
import com.alekseyzhelo.evilislands.mobplugin.script.util.EITypeToken;
import org.jetbrains.annotations.NotNull;

import java.util.List;

public interface EIForBlockBase extends EIScriptPsiElement {
    @NotNull
    List<EIExpression> getArguments();

    int indexOfArgument(@NotNull EIExpression expression);

    @NotNull
    EITypeToken[] getArgumentTypes();
}


text:
<?php

declare(strict_types=1);

/*
 * This file is part of SolidInvoice project.
 *
 * (c) Pierre du Plessis <open-source@solidworx.co>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace SolidInvoice\PaymentBundle\Form\Methods;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints\NotBlank;

class AuthorizeNetAim extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add(
            'login_id',
            TextType::class,
            [
                'constraints' => new NotBlank(),
            ]
        );

        $builder->add(
            'transaction_key',
            TextType::class,
            [
                'constraints' => new NotBlank(),
            ]
        );

        $builder->add(
            'sandbox',
            CheckboxType::class,
            [
                'required' => false,
            ]
        );
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'authorize_net_aim';
    }
}