text:
console.time("server-start");

const PORT = 3000;

var express = require("express");
var bodyParser = require('body-parser');
var multipartFormMiddleware = require('multer')();
var fs = require("fs");

var app = express();

app.get('/', function(req, res){
    var html = fs.readFileSync('post-from-js.html');
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(html);
});

app.post('/', multipartFormMiddleware.array(), function(req, res){
    console.log(req.body);
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('Thanks for the submission, ' + req.body.name);
});

app.listen(PORT);

console.log('Listening at http://localhost:' + PORT);
console.timeEnd("server-start");


text:
//Copyright © 2014 Sony Computer Entertainment America LLC. See License.txt.

using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;

namespace Sce.Atf.Applications.NetworkTargetServices
{
    ///
    /// Class to describe TCP/IP target information
    [GroupAttribute("TcpIpTargetInfo", Header = @"TCP/IP Targets", ReadOnlyProperties = "Protocol")]//localized below
    public class TcpIpTargetInfo : TargetInfo, IPropertyValueValidator
    {
        ///
        /// Constructor
        public TcpIpTargetInfo()
        {
            Name = "LocalHost".Localize("The English version should have had a space between the words, but it's too late to change");
            Platform = "<undefined>".Localize("The '<' and '>' indicate that this is not a real name.");
            Endpoint = "127.0.0.1:12345"; // local host
            Protocol = ProtocolName;
            Scope = TargetScope.PerApp;

            // Make the GroupAttribute strings localizable, by making sure that the LocalizableStringExtractor can find them.
            //@"TCP/IP Targets".Localize();
            "Protocol".Localize();
        }

        ///
        /// Gets or sets the fixed port value for the  TCP/IP target
        /// <remarks>If this value is set to a positive integer, then IPEndPoint will be constructed
        /// using the IPAddress from  endpoint value(in string format) , combined with this fixed port number.
        /// The port number in the endpoint string value will be ignored even it includes one.</remarks>
        public int FixedPort { get; set; }

        ///
        /// Protocol name for TCP
        public const string ProtocolName = @"Tcp";

        ///
        /// Gets or sets the endpoint
        public IPEndPoint IPEndPoint
        {
            // Gets the endpoint as an IPEndPoint object, return null for invalid address
            get
            {
                if (FixedPort > 0)
                    return TryParseEndPointUsingPort(Endpoint, FixedPort);
                return TryParseIPEndPoint(Endpoint);
            }
            set
            {
                // Sets the endpoint from an IPEndPoint object
                if (value == null) return;
                if (FixedPort > 0 && FixedPort != value.Port)
                    throw new InvalidDataException("The port number does not match expected fixed value " + FixedPort);

                Endpoint = value.Address.ToString() + ":"+ value.Port;
            }
        }

        ///
        /// Convenience method to parse a string as a network endpoint; try to handle IPv4, IPv6, and host name notation
        /// <param name="endPoint">The string to parse</param>
        /// <returns>End point or null for invalid address</returns>
        /// <example>Example:
        ///  IPEndPoint ipv4Addr = TcpIpTargetInfo.TryParseIPEndPoint(@"192.168.0.1:12345");
        ///  IPEndPoint ipv6Addr = TcpIpTargetInfo.TryParseIPEndPoint(@"2001:740:8deb:0::1:12345");
        /// </example>
        public static IPEndPoint TryParseIPEndPoint(string endPoint)
        {
            string[] ep = endPoint.Split(':');

            int port;
            if (!int.TryParse(ep[ep.Length - 1], out port))
                return null;

            if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
                return null;

            IPAddress ip = TryParseIPAddress(endPoint);
            if (ip != null)
                return new IPEndPoint(ip, port);
            return null;
        }

        ///
        /// Convenience method to parse a string as a network endpoint; try to handle IPv4, IPv6, and host name notation
        /// <param name="endPoint">The string to parse, accept either a fully-qualified endpoint (IP address + port #) or just an IP address.</param>
        /// <param name="port">The port to combine with the IPAddress, ignore the port number in the endpoint even it includes one</param>
        /// <returns>End point or null for invalid address</returns>
        public static IPEndPoint TryParseEndPointUsingPort(string endPoint, int port)
        {
            if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
                return null;

            IPAddress ip = TryParseIPAddress(endPoint);
            if (ip!= null)
                return new IPEndPoint(ip, port);
            return null;
        }

        private static  IPAddress TryParseIPAddress(string ipAddress)
        {
            IPAddress ip;
            string[] ep = ipAddress.Split(':');
            if (ep.Length > 2) // must be an IPv6 address
            {
                if (!IPAddress.TryParse(string.Join(":", ep, 0, ep.Length - 1), out ip))
                {
                    return null;
                }
            }
            else
            {
                if (!IPAddress.TryParse(ep[0], out ip))
                {
                    // try as host name
                    try
                    {
                        ip = Dns.GetHostEntry(ep[0])
                            .AddressList
                            .FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork || x.AddressFamily == AddressFamily.InterNetworkV6);
                        if (ip == null)
                            return null;
                    }
                    catch (Exception)
                    {
                        return null;
                    }

                }
            }
            return ip;
        }

        #region IPropertyValueValidator Members

        ///
        /// Validates target property
        /// <param name="propertyName">Property name</param>
        /// <param name="formattedValue">Property value</param>
        /// <param name="errorMessage">Error message</param>
        /// <returns>True iff target property is valid</returns>
        public virtual bool Validate(string propertyName, object formattedValue, out string errorMessage)
        {
            bool result;
            errorMessage = string.Empty;

            if (propertyName.Equals("Endpoint"))
            {
                if (FixedPort > 0)
                    result = TryParseEndPointUsingPort(formattedValue.ToString(), FixedPort) != null;
                else
                    result = TryParseIPEndPoint(formattedValue.ToString()) != null;
                if (!result)
                    errorMessage = "The IP address format should be like \"192.168.0.1:12345\" or \"2001:740:8deb:0::1:12345\"".Localize();
                return result;
            }

            if (propertyName.Equals("Scope"))
            {
                result = Enum.IsDefined(typeof(TargetScope), formattedValue.ToString());
                if (!result)
                    errorMessage = "The scope type is unknown".Localize();
            }
            else if (propertyName.Equals("Name"))
            {
                result = !StringUtil.IsNullOrEmptyOrWhitespace(formattedValue.ToString());
                if (!result)
                    errorMessage = "The name must not be empty or all whitespace".Localize();
            }
            else
            {
                result = false;
                errorMessage = "The property name is unknown: ".Localize() + propertyName;
            }

            return result;
        }

        #endregion

    }

    ///
    /// Class to describe X86 target information
    [GroupAttribute("X86TargetInfo", Header = @"TCP/IP Targets", ReadOnlyProperties = "Protocol")]
    public class X86TargetInfo : TcpIpTargetInfo, IPropertyValueValidator
    {
        ///
        /// Platform name for X86
        public const string PlatformName = @"x86";

        ///
        /// Constructor
        public X86TargetInfo()
            : base()
        {
            Name = "localhost";
            Platform = PlatformName;
            Endpoint = "127.0.0.1:1338";
        }
    }

    ///
    /// Class to describe PS3 target information
    [GroupAttribute("Ps3TargetInfo", Header = @"TCP/IP Targets", ReadOnlyProperties = "Protocol")]
    public class Ps3TargetInfo : TcpIpTargetInfo, IPropertyValueValidator
    {
        ///
        /// PS3 platform name
        public const string PlatformName = @"Ps3";

        ///
        /// Constructor
        public Ps3TargetInfo()
            : base()
        {
            Name = "Ps3Host";
            Platform = PlatformName;
            Endpoint = "10.89.0.0:1338";
        }
    }

    ///
    /// Class to describe PS4 target information
    [GroupAttribute("Ps4TargetInfo", Header = @"TCP/IP Targets", ReadOnlyProperties = "Protocol")]
    public class Ps4TargetInfo : TcpIpTargetInfo, IPropertyValueValidator
    {
        ///
        /// PS4 platform name
        public const string PlatformName = @"Ps4";

        ///
        /// Constructor
        public Ps4TargetInfo()
            : base()
        {
            Name = "Ps4Host";
            Platform = PlatformName;
            Endpoint = "10.89.0.0:1338";
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
{-# LANGUAGE DeriveGeneric              #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TemplateHaskell            #-}

module Kubernetes.Model.V1.NodeSystemInfo
    ( NodeSystemInfo (..)
    , machineID
    , systemUUID
    , bootID
    , kernelVersion
    , osImage
    , containerRuntimeVersion
    , kubeletVersion
    , kubeProxyVersion
    , mkNodeSystemInfo
    ) where

import           Control.Lens.TH           (makeLenses)
import           Data.Aeson.TH             (defaultOptions, deriveJSON,
                                            fieldLabelModifier)
import           Data.Text                 (Text)
import           GHC.Generics              (Generic)
import           Prelude                   hiding (drop, error, max, min)
import qualified Prelude                   as P
import           Test.QuickCheck           (Arbitrary, arbitrary)
import           Test.QuickCheck.Instances ()

-- | NodeSystemInfo is a set of ids/uuids to uniquely identify the node.
data NodeSystemInfo = NodeSystemInfo
    { _machineID               :: !(Text)
    , _systemUUID              :: !(Text)
    , _bootID                  :: !(Text)
    , _kernelVersion           :: !(Text)
    , _osImage                 :: !(Text)
    , _containerRuntimeVersion :: !(Text)
    , _kubeletVersion          :: !(Text)
    , _kubeProxyVersion        :: !(Text)
    } deriving (Show, Eq, Generic)

makeLenses ''NodeSystemInfo

$(deriveJSON defaultOptions{fieldLabelModifier = (\n -> if n == "_type_" then "type" else P.drop 1 n)} ''NodeSystemInfo)

instance Arbitrary NodeSystemInfo where
    arbitrary = NodeSystemInfo <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary

-- | Use this method to build a NodeSystemInfo
mkNodeSystemInfo :: Text -> Text -> Text -> Text -> Text -> Text -> Text -> Text -> NodeSystemInfo
mkNodeSystemInfo xmachineIDx xsystemUUIDx xbootIDx xkernelVersionx xosImagex xcontainerRuntimeVersionx xkubeletVersionx xkubeProxyVersionx = NodeSystemInfo xmachineIDx xsystemUUIDx xbootIDx xkernelVersionx xosImagex xcontainerRuntimeVersionx xkubeletVersionx xkubeProxyVersionx


text:
import { Strategy } from 'passport-local';

const User = require('mongoose').model('User');

import passport from 'passport';
import { Strategy as FacebookStrategy } from 'passport-facebook';
// import { User, UserLogin, UserClaim, UserProfile } from '../data/models'; <= this one needs to be mongoose
import { auth as config } from '../config';

/**
 * Sign in with Facebook.
 */
passport.use(new FacebookStrategy({
  clientID: config.facebook.id,
  clientSecret: config.facebook.secret,
  callbackURL: '/login/facebook/return',
  profileFields: ['name', 'email', 'link', 'locale', 'timezone'],
  passReqToCallback: true,
}, (req, accessToken, refreshToken, profile, done) => {
  /* eslint-disable no-underscore-dangle */
  const loginName = 'facebook';
  const claimType = 'urn:facebook:access_token';
  const fooBar = async () => {
    if (req.user) {
      const userLogin = await UserLogin.findOne({
        attributes: ['name', 'key'],
        where: { name: loginName, key: profile.id },
      });
      if (userLogin) {
        // There is already a Facebook account that belongs to you.
        // Sign in with that account or delete it, then link it with your current account.
        done();
      } else {
        const user = await User.create({
          id: req.user.id,
          email: profile._json.email,
          logins: [
            { name: loginName, key: profile.id },
          ],
          claims: [
            { type: claimType, value: profile.id },
          ],
          profile: {
            displayName: profile.displayName,
            gender: profile._json.gender,
            picture: `https://graph.facebook.com/${profile.id}/picture?type=large`,
          },
        }, {
          include: [
            { model: UserLogin, as: 'logins' },
            { model: UserClaim, as: 'claims' },
            { model: UserProfile, as: 'profile' },
          ],
        });
        done(null, {
          id: user.id,
          email: user.email,
        });
      }
    } else {
      const users = await User.findAll({
        attributes: ['id', 'email'],
        where: { '$logins.name$': loginName, '$logins.key$': profile.id },
        include: [
          {
            attributes: ['name', 'key'],
            model: UserLogin,
            as: 'logins',
            required: true,
          },
        ],
      });
      if (users.length) {
        done(null, users[0]);
      } else {
        let user = await User.findOne({ where: { email: profile._json.email } });
        if (user) {
          // There is already an account using this email address. Sign in to
          // that account and link it with Facebook manually from Account Settings.
          done(null);
        } else {
          user = await User.create({
            email: profile._json.email,
            emailConfirmed: true,
            logins: [
              { name: loginName, key: profile.id },
            ],
            claims: [
              { type: claimType, value: accessToken },
            ],
            profile: {
              displayName: profile.displayName,
              gender: profile._json.gender,
              picture: `https://graph.facebook.com/${profile.id}/picture?type=large`,
            },
          }, {
            include: [
              { model: UserLogin, as: 'logins' },
              { model: UserClaim, as: 'claims' },
              { model: UserProfile, as: 'profile' },
            ],
          });
          done(null, {
            id: user.id,
            email: user.email,
          });
        }
      }
    }
  };

  fooBar().catch(done);
}));

export default passport;

/**
 * Return the Passport Local Strategy object.
 */
module.exports = new Strategy({
  usernameField: 'email',
  passwordField: 'password',
  session: false,
  passReqToCallback: true
}, (req, email, password, done) => {
  const userData = {
    email: email.trim(),
    password: password.trim(),
    name: req.body.name.trim()
  };

  const newUser = new User(userData);
  newUser.save((err) => {
    if (err) { return done(err); }

    return done(null);
  });
});


text:
package net.darold.ora2pg.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Ora2Pg command line options
 *
 * @author yang.dongdong
 *
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Ora2PgOption {
	/** short representation of the option */
	public String opt() default "";

	/** the long name of the Option */
	public String longOpt();

	/** specifies whether the Option takes an argument or not */
	public boolean hasArg();

	/** Sets whether the Option can have an optional argument. */
	public boolean optionalArg() default false;

	/** the display name for the argument value */
	public String argName() default "";

	/** the description of the option */
	public String desc() default "";

	/** the type of the Option */
	public Class<?> type() default Object.class;

	/** the default value */
	public String defaultValue() default "";
}


text:
package org.apache.maven.plugins.dependency.utils;

/**
 *
 */

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import org.apache.maven.artifact.Artifact;

/**
 * @author Brian Fox
 * @version $Id$
 */
public class DependencyStatusSets
{

    Set<Artifact> resolvedDependencies = null;

    Set<Artifact> unResolvedDependencies = null;

    Set<Artifact> skippedDependencies = null;

    public DependencyStatusSets()
    {

    }

    public DependencyStatusSets( Set<Artifact> resolved, Set<Artifact> unResolved, Set<Artifact> skipped )
    {
        if ( resolved != null )
        {
            this.resolvedDependencies = new LinkedHashSet<Artifact>( resolved );
        }
        if ( unResolved != null )
        {
            this.unResolvedDependencies = new LinkedHashSet<Artifact>( unResolved );
        }
        if ( skipped != null )
        {
            this.skippedDependencies = new LinkedHashSet<Artifact>( skipped );
        }
    }

    /**
     * @return Returns the resolvedDependencies.
     */
    public Set<Artifact> getResolvedDependencies()
    {
        return this.resolvedDependencies;
    }

    /**
     * @param resolvedDependencies
     *            The resolvedDependencies to set.
     */
    public void setResolvedDependencies( Set<Artifact> resolvedDependencies )
    {
        if ( resolvedDependencies != null )
        {
            this.resolvedDependencies = new LinkedHashSet<Artifact>( resolvedDependencies );
        }
        else
        {
            this.resolvedDependencies = null;
        }
    }

    /**
     * @return Returns the skippedDependencies.
     */
    public Set<Artifact> getSkippedDependencies()
    {
        return this.skippedDependencies;
    }

    /**
     * @param skippedDependencies
     *            The skippedDependencies to set.
     */
    public void setSkippedDependencies( Set<Artifact> skippedDependencies )
    {
        if ( skippedDependencies != null )
        {
            this.skippedDependencies = new LinkedHashSet<Artifact>( skippedDependencies );
        }
        else
        {
            this.skippedDependencies = null;
        }
    }

    /**
     * @return Returns the unResolvedDependencies.
     */
    public Set<Artifact> getUnResolvedDependencies()
    {
        return this.unResolvedDependencies;
    }

    /**
     * @param unResolvedDependencies
     *            The unResolvedDependencies to set.
     */
    public void setUnResolvedDependencies( Set<Artifact> unResolvedDependencies )
    {
        if ( unResolvedDependencies != null )
        {
            this.unResolvedDependencies = new LinkedHashSet<Artifact>( unResolvedDependencies );
        }
        else
        {
            this.unResolvedDependencies = null;
        }
    }

    public String getOutput( boolean outputAbsoluteArtifactFilename )
    {
        return getOutput( outputAbsoluteArtifactFilename, true );
    }

    public String getOutput( boolean outputAbsoluteArtifactFilename, boolean outputScope )
    {
        return getOutput( outputAbsoluteArtifactFilename, outputScope, false );
    }

    public String getOutput( boolean outputAbsoluteArtifactFilename, boolean outputScope, boolean sort )
    {
        StringBuilder sb = new StringBuilder();
        sb.append( "\n" );
        sb.append( "The following files have been resolved:\n" );
        if ( this.resolvedDependencies == null || this.resolvedDependencies.isEmpty() )
        {
            sb.append( "   none\n" );
        }
        else
        {
            sb.append( buildArtifactListOutput( resolvedDependencies, outputAbsoluteArtifactFilename,
                                                outputScope, sort ) );
        }

        if ( this.skippedDependencies != null && !this.skippedDependencies.isEmpty() )
        {
            sb.append( "\n" );
            sb.append( "The following files were skipped:\n" );
            Set<Artifact> skippedDependencies = new LinkedHashSet<Artifact>();
            skippedDependencies.addAll( this.skippedDependencies );
            sb.append( buildArtifactListOutput( skippedDependencies, outputAbsoluteArtifactFilename,
                                                outputScope, sort ) );
        }

        if ( this.unResolvedDependencies != null && !this.unResolvedDependencies.isEmpty() )
        {
            sb.append( "\n" );
            sb.append( "The following files have NOT been resolved:\n" );
            Set<Artifact> unResolvedDependencies = new LinkedHashSet<Artifact>();
            unResolvedDependencies.addAll( this.unResolvedDependencies );
            sb.append( buildArtifactListOutput( unResolvedDependencies, outputAbsoluteArtifactFilename,
                                                outputScope, sort ) );
        }
        sb.append( "\n" );

        return sb.toString();
    }

    private StringBuilder buildArtifactListOutput( Set<Artifact> artifacts, boolean outputAbsoluteArtifactFilename,
                                                   boolean outputScope, boolean sort )
    {
        StringBuilder sb = new StringBuilder();
        List<String> artifactStringList = new ArrayList<String>();
        for ( Artifact artifact : artifacts )
        {
            String artifactFilename = null;
            if ( outputAbsoluteArtifactFilename )
            {
                try
                {
                    // we want to print the absolute file name here
                    artifactFilename = artifact.getFile().getAbsoluteFile().getPath();
                }
                catch ( NullPointerException e )
                {
                    // ignore the null pointer, we'll output a null string
                    artifactFilename = null;
                }
            }

            String id = outputScope ? artifact.toString() : artifact.getId();

            artifactStringList.add( "   " + id + ( outputAbsoluteArtifactFilename ? ":" + artifactFilename : "" )
                + "\n" );
        }
        if ( sort )
        {
            Collections.sort( artifactStringList );
        }
        for ( String artifactString : artifactStringList )
        {
            sb.append( artifactString );
        }
        return sb;
    }
}


text:
<?php

namespace Bureaupieper\StoreeClient\Client;

use Bureaupieper\StoreeClient\Client;
use Bureaupieper\StoreeClient\BaseTest;

/**
 * Class InstantiationTest
 * @package Bureaupieper\StoreeClient\Client
 * @covers Bureaupieper\StoreeClient\Client::__construct
 */
class InstantiationTest extends BaseTest
{
    const FQCLIENT = '\Bureaupieper\StoreeClient\Client';

    function validConfig() {
        return [
            'version' => 1,
            'platform' => 'sugarbombs.com',
            'apikey' => 'apikey'
        ];
    }

    function validConfigInstance() {
        return new Client\Config($this->validConfig());
    }

    function testValidInstance() {
        $this->assertInstanceOf(self::FQCLIENT, new Client($this->validConfigInstance()));
    }

    /**
     * @expectedException PHPUnit_Framework_Error
     * @expectedExceptionMessageRegExp /must be an instance of Bureaupieper\\StoreeClient\\Client\\Config/
     */
    function testInvalidConf() {
        new Client;
    }

    /**
     * @expectedException PHPUnit_Framework_Error
     * @expectedExceptionMessageRegExp /must be an instance of GuzzleHttp\\Client/
     */
    function testInvalidGuzzle() {
        new Client($this->validConfigInstance(), new \stdClass());
    }

    /**
     * @expectedException PHPUnit_Framework_Error
     * @expectedExceptionMessageRegExp /must be an instance of Stash\\Driver\\AbstractDriver/
     */
    function testInvalidCacheDriver() {
        new Client($this->validConfigInstance(), null, new \stdClass());
    }

    /**
     * @expectedException PHPUnit_Framework_Error
     * @expectedExceptionMessageRegExp /must implement interface Psr\\Log\\LoggerInterface/
     */
    function testInvalidLogger() {
        new Client($this->validConfigInstance(), null, null, new \stdClass());
    }

    function testCacheEnabledWithDefaultDriver() {
        $conf = $this->validConfig();
        $conf['cache'] = true;
        $this->assertInstanceOf(self::FQCLIENT, new Client(new Client\Config($conf)));
    }

    /**
     * @expectedException     \Bureaupieper\StoreeClient\Client\ClientException
     * @expectedExceptionCode 1
     */
    function testNoCacheDriver() {
        $conf = $this->validConfig();
        $conf['cache'] = [
            'default_driver' => false
        ];
        new Client(new Client\Config($conf));
    }

    /**
     * @expectedException     \Bureaupieper\StoreeClient\Client\ClientException
     * @expectedExceptionCode 16
     */
    function testPathForDefaultCacheNotWritable() {
        $conf = $this->validConfig();
        $conf['cache'] = [
            'default_driver' => [
                'path' => '/some_strange_path_that_shouldnt_exist',
            ]
        ];
        new Client(new Client\Config($conf));
    }

    /**
     * @expectedException     \Bureaupieper\StoreeClient\Client\ClientException
     * @expectedExceptionCode 2
     */
    function testNoLoggingDriver() {
        $conf = $this->validConfig();
        $conf['logs'] = [
            'default_driver' => false
        ];
        new Client(new Client\Config($conf));
    }

    /**
     * @expectedException     \Bureaupieper\StoreeClient\Client\ClientException
     * @expectedExceptionCode 8
     */
    function testPathForDefaultLoggerNotWritable() {
        $conf = $this->validConfig();
        $conf['logs'] = [
            'default_driver' => [
                'path' => '/some_strange_path_that_shouldnt_exist',
            ]
        ];
        new Client(new Client\Config($conf));
    }
}


text:
#define CAMERA_PARAMETERS_EXTRA_C \
const char CameraParameters::AUDIO_ZOOM_OFF[] = "audio-zoom"; \
const char CameraParameters::AUDIO_ZOOM_ON[] = "audio-zoom"; \
const char CameraParameters::BEAUTY_SHOT_OFF[] = "beauty-shot"; \
const char CameraParameters::BEAUTY_SHOT_ON[] = "beauty-shot"; \
const char CameraParameters::BURST_SHOT_OFF[] = "burst-shot"; \
const char CameraParameters::BURST_SHOT_ON[] = "burst-shot"; \
const char CameraParameters::KEY_AUDIO_ZOOM[] = "audio-zoom"; \
const char CameraParameters::KEY_AUDIO_ZOOM_SUPPORTED[] = "audio-zoom-supported"; \
const char CameraParameters::KEY_BEAUTY_SHOT[] = "beauty-shot"; \
const char CameraParameters::KEY_BEAUTY_SHOT_SUPPORTED[] = "beauty-shot-supported"; \
const char CameraParameters::KEY_BURST_SHOT[] = "burst-shot"; \
const char CameraParameters::KEY_BURST_SHOT_SUPPORTED[] = "burst-shot-supported"; \
const char CameraParameters::KEY_FOCUS_MODE_OBJECT_TRACKING[] = "object-tracking"; \
const char CameraParameters::KEY_FOCUS_MODE_OBJECT_TRACKING_SUPPORTED[] = "object-tracking-supported"; \
const char CameraParameters::KEY_VIDEO_WDR[] = "video-wdr"; \
const char CameraParameters::KEY_VIDEO_WDR_SUPPORTED[] = "video-wdr-supported"; \
const char CameraParameters::VIDEO_WDR_OFF[] = "video-wdr"; \
const char CameraParameters::VIDEO_WDR_ON[] = "video-wdr"; \
const char CameraParameters::OBJECT_TRACKING_ON[] = "object-tracking"; \
const char CameraParameters::OBJECT_TRACKING_OFF[] = "object-tracking";

#define CAMERA_PARAMETERS_EXTRA_H \
    static const char AUDIO_ZOOM_OFF[]; \
    static const char AUDIO_ZOOM_ON[]; \
    static const char BEAUTY_SHOT_OFF[]; \
    static const char BEAUTY_SHOT_ON[]; \
    static const char BURST_SHOT_OFF[]; \
    static const char BURST_SHOT_ON[]; \
    static const char KEY_AUDIO_ZOOM[]; \
    static const char KEY_AUDIO_ZOOM_SUPPORTED[]; \
    static const char KEY_BEAUTY_SHOT[]; \
    static const char KEY_BEAUTY_SHOT_SUPPORTED[]; \
    static const char KEY_BURST_SHOT[]; \
    static const char KEY_BURST_SHOT_SUPPORTED[]; \
    static const char KEY_FOCUS_MODE_OBJECT_TRACKING[]; \
    static const char KEY_FOCUS_MODE_OBJECT_TRACKING_SUPPORTED[]; \
    static const char KEY_VIDEO_WDR[]; \
    static const char KEY_VIDEO_WDR_SUPPORTED[]; \
    static const char VIDEO_WDR_OFF[]; \
    static const char VIDEO_WDR_ON[]; \
    static const char OBJECT_TRACKING_ON[]; \
    static const char OBJECT_TRACKING_OFF[];


text:
package com.swfarm.biz.aliexpress.dao;

import com.swfarm.biz.aliexpress.bo.AliExpressShippingService;
import com.swfarm.pub.framework.dao.GenericDao;

public interface AliExpressShippingServiceDao extends
		GenericDao<AliExpressShippingService, Long> {

}


text:
param(
	[parameter(Mandatory=$true)]
	[string]$ApiKey,
    [parameter(Mandatory=$true)]
    [string]$csprojLocation
)

# removes existing '*.nupkg' packages in the current folder
Get-ChildItem . | Where-Object { $_.Name -imatch ".nupkg$" } | ForEach-Object { Remove-Item $_.FullName }

# creates nuget package
..\NuGet.exe pack $csprojLocation -Prop Configuration=Release

# publish package
$packageName = Get-ChildItem . | Where-Object { $_.Name -imatch ".nupkg$" }

Write-Output "`r`nAbout to publish '$packageName'."
$userConfirm = Read-Host 'Do you want to proceed? [Y]es/[N]o'

if($userConfirm -match 'Y')
{
	Write-Output "`r`nPublishing package..."
	..\NuGet.exe push $packageName -ApiKey $ApiKey
}
else
{
	Write-Output "`r`nPublish operation skipped by the user."
}


text:
using OKHOSTING.Data.Validation;

namespace OKHOSTING.ORM.Filters
{
	/// <summary>
	/// Use this to validate using a filter
	/// </summary>
	/// <example>
	/// If you want Customer.MainAddress to be only selectable from Addreses where Address.Customer.Id == Customer.Id
	/// </example>
	public class FilterValidator : ValidatorBase
	{
		public Filter Filter { get; set; }

		public override ValidationError Validate(object obj)
		{
			if (!Filter.Match(obj))
			{
				return new ValidationError(this, "Object does not match with the filter");
			}
			else
			{
				return null;
			}
		}
	}
}


text:
def register_api_url_stubs
  unless(TEST_LIVE_API)

    File.open(File.join(File.dirname(__FILE__), "..", "fixtures", "movie_search.txt")) do |file|
      stub_request(:get, Regexp.new(Tmdb.base_api_url + "Movie.search/" + ".*")).to_return(file)
    end

    File.open(File.join(File.dirname(__FILE__), "..", "fixtures", "movie_get_info.txt")) do |file|
      stub_request(:get, Regexp.new(Tmdb.base_api_url + "Movie.getInfo/" + ".*")).to_return(file)
    end

    File.open(File.join(File.dirname(__FILE__), "..", "fixtures", "movie_imdb_lookup.txt")) do |file|
      stub_request(:get, Regexp.new(Tmdb.base_api_url + "Movie.imdbLookup/" + ".*")).to_return(file)
    end

    File.open(File.join(File.dirname(__FILE__), "..", "fixtures", "movie_browse.txt")) do |file|
      stub_request(:get, Regexp.new(Tmdb.base_api_url + "Movie.browse/" + ".*")).to_return(file)
    end

    File.open(File.join(File.dirname(__FILE__), "..", "fixtures", "person_get_info.txt")) do |file|
      stub_request(:get, Regexp.new(Tmdb.base_api_url + "Person.getInfo/" + ".*")).to_return(file)
    end

    File.open(File.join(File.dirname(__FILE__), "..", "fixtures", "person_search.txt")) do |file|
      stub_request(:get, Regexp.new(Tmdb.base_api_url + "Person.search/" + ".*")).to_return(file)
    end

    File.open(File.join(File.dirname(__FILE__), "..", "fixtures", "incorrect_api_url.txt")) do |file|
      stub_request(:get, Regexp.new(Tmdb.base_api_url + "Movie.blarg/" + ".*")).to_return(file)
    end

    File.open(File.join(File.dirname(__FILE__), "..", "fixtures", "blank_result.txt")) do |file|
      stub_request(:get, Regexp.new(Tmdb.base_api_url + "Search.empty/" + ".*")).to_return(file)
    end

    File.open(File.join(File.dirname(__FILE__), "..", "fixtures", "example_com.txt")) do |file|
      stub_request(:get, Regexp.new("http://example.com.*")).to_return(file)
    end

    File.open(File.join(File.dirname(__FILE__), "..", "fixtures", "image.jpg")) do |file|
      stub_request(:get, Regexp.new('http://i[0-9].themoviedb.org/[backdrops|posters|profiles].*')).to_return(file)
    end

    File.open(File.join(File.dirname(__FILE__), "..", "fixtures", "image.jpg")) do |file|
      stub_request(:get, Regexp.new('http://hwcdn.themoviedb.org/[backdrops|posters|profiles].*')).to_return(file)
    end

    File.open(File.join(File.dirname(__FILE__), "..", "fixtures", "blank_result.txt")) do |file|
      stub_request(:get, Regexp.new("item_not_found$")).to_return(file)
    end

    stub_request(:get, 'http://thisisaurlthatdoesntexist.co.nz').to_return(:body => "", :status => 404, :headers => {'content-length' => 0})
  end
end


text:
package celv3

import (
	"bytes"
	"errors"
	"fmt"
	"net"
	"net/mail"
	"net/url"
	"regexp"
	"sort"
	"strings"
	"time"
	"unicode/utf8"

	"google.golang.org/protobuf/types/known/anypb"
)

// ensure the imports are used
var (
	_ = bytes.MinRead
	_ = errors.New("")
	_ = fmt.Print
	_ = utf8.UTFMax
	_ = (*regexp.Regexp)(nil)
	_ = (*strings.Reader)(nil)
	_ = net.IPv4len
	_ = time.Duration(0)
	_ = (*url.URL)(nil)
	_ = (*mail.Address)(nil)
	_ = anypb.Any{}
	_ = sort.Sort
)

// Validate checks the field values on ExpressionFilter with the rules defined
// in the proto definition for this message. If any rules are violated, the
// first error encountered is returned, or nil if there are no violations.
func (m *ExpressionFilter) Validate() error {
	return m.validate(false)
}

// ValidateAll checks the field values on ExpressionFilter with the rules
// defined in the proto definition for this message. If any rules are
// violated, the result is a list of violation errors wrapped in
// ExpressionFilterMultiError, or nil if none found.
func (m *ExpressionFilter) ValidateAll() error {
	return m.validate(true)
}

func (m *ExpressionFilter) validate(all bool) error {
	if m == nil {
		return nil
	}

	var errors []error

	// no validation rules for Expression

	if len(errors) > 0 {
		return ExpressionFilterMultiError(errors)
	}

	return nil
}

// ExpressionFilterMultiError is an error wrapping multiple validation errors
// returned by ExpressionFilter.ValidateAll() if the designated constraints
// aren't met.
type ExpressionFilterMultiError []error

// Error returns a concatenation of all the error messages it wraps.
func (m ExpressionFilterMultiError) Error() string {
	var msgs []string
	for _, err := range m {
		msgs = append(msgs, err.Error())
	}
	return strings.Join(msgs, "; ")
}

// AllErrors returns a list of validation violation errors.
func (m ExpressionFilterMultiError) AllErrors() []error { return m }

// ExpressionFilterValidationError is the validation error returned by
// ExpressionFilter.Validate if the designated constraints aren't met.
type ExpressionFilterValidationError struct {
	field  string
	reason string
	cause  error
	key    bool
}

// Field function returns field value.
func (e ExpressionFilterValidationError) Field() string { return e.field }

// Reason function returns reason value.
func (e ExpressionFilterValidationError) Reason() string { return e.reason }

// Cause function returns cause value.
func (e ExpressionFilterValidationError) Cause() error { return e.cause }

// Key function returns key value.
func (e ExpressionFilterValidationError) Key() bool { return e.key }

// ErrorName returns error name.
func (e ExpressionFilterValidationError) ErrorName() string { return "ExpressionFilterValidationError" }

// Error satisfies the builtin error interface
func (e ExpressionFilterValidationError) Error() string {
	cause := ""
	if e.cause != nil {
		cause = fmt.Sprintf(" | caused by: %v", e.cause)
	}

	key := ""
	if e.key {
		key = "key for "
	}

	return fmt.Sprintf(
		"invalid %sExpressionFilter.%s: %s%s",
		key,
		e.field,
		e.reason,
		cause)
}

var _ error = ExpressionFilterValidationError{}

var _ interface {
	Field() string
	Reason() string
	Key() bool
	Cause() error
	ErrorName() string
} = ExpressionFilterValidationError{}


text:
using System;
using System.Collections.Generic;
using System.Reflection;
using Autofac.Builder;
using Microsoft.Framework.DependencyInjection;

namespace Autofac.Dnx
{
    public static class AutofacRegistration
    {
        public static void Populate(
                this ContainerBuilder builder,
                IEnumerable<ServiceDescriptor> descriptors)
        {
            builder.RegisterType<AutofacServiceProvider>().As<IServiceProvider>();
            builder.RegisterType<AutofacServiceScopeFactory>().As<IServiceScopeFactory>();

            Register(builder, descriptors);
        }

        private static void Register(
                ContainerBuilder builder,
                IEnumerable<ServiceDescriptor> descriptors)
        {
            foreach (var descriptor in descriptors)
            {
                if (descriptor.ImplementationType != null)
                {
                    // Test if the an open generic type is being registered
                    var serviceTypeInfo = descriptor.ServiceType.GetTypeInfo();
                    if (serviceTypeInfo.IsGenericTypeDefinition)
                    {
                        builder
                            .RegisterGeneric(descriptor.ImplementationType)
                            .As(descriptor.ServiceType)
                            .ConfigureLifecycle(descriptor.Lifetime);
                    }
                    else
                    {
                        builder
                            .RegisterType(descriptor.ImplementationType)
                            .As(descriptor.ServiceType)
                            .ConfigureLifecycle(descriptor.Lifetime);
                    }
                }
                else if (descriptor.ImplementationFactory != null)
                {
                    var registration = RegistrationBuilder.ForDelegate(descriptor.ServiceType, (context, parameters) =>
                    {
                        var serviceProvider = context.Resolve<IServiceProvider>();
                        return descriptor.ImplementationFactory(serviceProvider);
                    })
                    .ConfigureLifecycle(descriptor.Lifetime)
                    .CreateRegistration();

                    builder.RegisterComponent(registration);
                }
                else
                {
                    builder
                        .RegisterInstance(descriptor.ImplementationInstance)
                        .As(descriptor.ServiceType)
                        .ConfigureLifecycle(descriptor.Lifetime);
                }
            }
        }

        private static IRegistrationBuilder<object, T, U> ConfigureLifecycle<T, U>(
                this IRegistrationBuilder<object, T, U> registrationBuilder,
                ServiceLifetime lifecycleKind)
        {
            switch (lifecycleKind)
            {
                case ServiceLifetime.Singleton:
                    registrationBuilder.SingleInstance();
                    break;
                case ServiceLifetime.Scoped:
                    registrationBuilder.InstancePerLifetimeScope();
                    break;
                case ServiceLifetime.Transient:
                    registrationBuilder.InstancePerDependency();
                    break;
            }

            return registrationBuilder;
        }
    }
}


text:
require 'gosu'
require 'gosu_texture_packer'
require 'perlin_noise'

root_dir = File.dirname(__FILE__)
require_pattern = File.join(root_dir, '**/*.rb')
@failed = []

# Dynamically require everything
Dir.glob(require_pattern).each do |f|
  next if f.end_with?('/main.rb')
  begin
    require_relative f.gsub("#{root_dir}/", '')
  rescue
    # May fail if parent class not required yet
    @failed << f
  end
end

# Retry unresolved requires
@failed.each do |f|
  require_relative f.gsub("#{root_dir}/", '')
end

$debug = false
$window = GameWindow.new
GameState.switch(MenuState.instance)
$window.show


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.content.model;

/**
 * Model definition for HolidaysHoliday.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Content API for Shopping. For a detailed explanation
 * see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class HolidaysHoliday extends com.google.api.client.json.GenericJson {

  /**
   * The CLDR territory code of the country in which the holiday is available. E.g. "US", "DE",
   * "GB". A holiday cutoff can only be configured in a shipping settings service with matching
   * delivery country. Always present.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String countryCode;

  /**
   * Date of the holiday, in ISO 8601 format. E.g. "2016-12-25" for Christmas 2016. Always present.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String date;

  /**
   * Date on which the order has to arrive at the customer's, in ISO 8601 format. E.g. "2016-12-24"
   * for 24th December 2016. Always present.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String deliveryGuaranteeDate;

  /**
   * Hour of the day in the delivery location's timezone on the guaranteed delivery date by which
   * the order has to arrive at the customer's. Possible values are: 0 (midnight), 1, ..., 12
   * (noon), 13, ..., 23. Always present.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key @com.google.api.client.json.JsonString
  private java.math.BigInteger deliveryGuaranteeHour;

  /**
   * Unique identifier for the holiday to be used when configuring holiday cutoffs. Always present.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String id;

  /**
   * The holiday type. Always present. Acceptable values are: - "`Christmas`" - "`Easter`" -
   * "`Father's Day`" - "`Halloween`" - "`Independence Day (USA)`" - "`Mother's Day`" -
   * "`Thanksgiving`" - "`Valentine's Day`"
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String type;

  /**
   * The CLDR territory code of the country in which the holiday is available. E.g. "US", "DE",
   * "GB". A holiday cutoff can only be configured in a shipping settings service with matching
   * delivery country. Always present.
   * @return value or {@code null} for none
   */
  public java.lang.String getCountryCode() {
    return countryCode;
  }

  /**
   * The CLDR territory code of the country in which the holiday is available. E.g. "US", "DE",
   * "GB". A holiday cutoff can only be configured in a shipping settings service with matching
   * delivery country. Always present.
   * @param countryCode countryCode or {@code null} for none
   */
  public HolidaysHoliday setCountryCode(java.lang.String countryCode) {
    this.countryCode = countryCode;
    return this;
  }

  /**
   * Date of the holiday, in ISO 8601 format. E.g. "2016-12-25" for Christmas 2016. Always present.
   * @return value or {@code null} for none
   */
  public java.lang.String getDate() {
    return date;
  }

  /**
   * Date of the holiday, in ISO 8601 format. E.g. "2016-12-25" for Christmas 2016. Always present.
   * @param date date or {@code null} for none
   */
  public HolidaysHoliday setDate(java.lang.String date) {
    this.date = date;
    return this;
  }

  /**
   * Date on which the order has to arrive at the customer's, in ISO 8601 format. E.g. "2016-12-24"
   * for 24th December 2016. Always present.
   * @return value or {@code null} for none
   */
  public java.lang.String getDeliveryGuaranteeDate() {
    return deliveryGuaranteeDate;
  }

  /**
   * Date on which the order has to arrive at the customer's, in ISO 8601 format. E.g. "2016-12-24"
   * for 24th December 2016. Always present.
   * @param deliveryGuaranteeDate deliveryGuaranteeDate or {@code null} for none
   */
  public HolidaysHoliday setDeliveryGuaranteeDate(java.lang.String deliveryGuaranteeDate) {
    this.deliveryGuaranteeDate = deliveryGuaranteeDate;
    return this;
  }

  /**
   * Hour of the day in the delivery location's timezone on the guaranteed delivery date by which
   * the order has to arrive at the customer's. Possible values are: 0 (midnight), 1, ..., 12
   * (noon), 13, ..., 23. Always present.
   * @return value or {@code null} for none
   */
  public java.math.BigInteger getDeliveryGuaranteeHour() {
    return deliveryGuaranteeHour;
  }

  /**
   * Hour of the day in the delivery location's timezone on the guaranteed delivery date by which
   * the order has to arrive at the customer's. Possible values are: 0 (midnight), 1, ..., 12
   * (noon), 13, ..., 23. Always present.
   * @param deliveryGuaranteeHour deliveryGuaranteeHour or {@code null} for none
   */
  public HolidaysHoliday setDeliveryGuaranteeHour(java.math.BigInteger deliveryGuaranteeHour) {
    this.deliveryGuaranteeHour = deliveryGuaranteeHour;
    return this;
  }

  /**
   * Unique identifier for the holiday to be used when configuring holiday cutoffs. Always present.
   * @return value or {@code null} for none
   */
  public java.lang.String getId() {
    return id;
  }

  /**
   * Unique identifier for the holiday to be used when configuring holiday cutoffs. Always present.
   * @param id id or {@code null} for none
   */
  public HolidaysHoliday setId(java.lang.String id) {
    this.id = id;
    return this;
  }

  /**
   * The holiday type. Always present. Acceptable values are: - "`Christmas`" - "`Easter`" -
   * "`Father's Day`" - "`Halloween`" - "`Independence Day (USA)`" - "`Mother's Day`" -
   * "`Thanksgiving`" - "`Valentine's Day`"
   * @return value or {@code null} for none
   */
  public java.lang.String getType() {
    return type;
  }

  /**
   * The holiday type. Always present. Acceptable values are: - "`Christmas`" - "`Easter`" -
   * "`Father's Day`" - "`Halloween`" - "`Independence Day (USA)`" - "`Mother's Day`" -
   * "`Thanksgiving`" - "`Valentine's Day`"
   * @param type type or {@code null} for none
   */
  public HolidaysHoliday setType(java.lang.String type) {
    this.type = type;
    return this;
  }

  @Override
  public HolidaysHoliday set(String fieldName, Object value) {
    return (HolidaysHoliday) super.set(fieldName, value);
  }

  @Override
  public HolidaysHoliday clone() {
    return (HolidaysHoliday) super.clone();
  }

}


text:
function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.");
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}

function getPlayerMove(move) {
    return move || getInput();
}

function getComputerMove(move) {
    return move || randomPlay();
}

function getWinner(playerMove,computerMove) {
    var winner;

    if (playerMove === "rock" && computerMove === "paper") {
         winner = "computer";
    }
    else if (playerMove === "paper" && computerMove === "paper") {
         winner = "tie";
    }
    else if (playerMove === "scissors" && computerMove === "paper") {
         winner = "player";
    }
    else if (playerMove === "rock" && computerMove === "rock") {
         winner = "tie";
    }
    else if (playerMove === "rock" && computerMove === "scissors") {
         winner = "player";
    }
    else if (playerMove === "scissors" && computerMove === "rock") {
         winner = "computer";
    }
    else if (playerMove === "scissors" && computerMove === "scissors") {
         winner = "tie";
    }
    else if (playerMove === "paper" && computerMove === "scissors") {
         winner = "computer";
    }
    else if (playerMove === "paper" && computerMove === "rock") {
         winner = "player";
    }
    else {
        winner = "invalid";
    }
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    var playerMove1;
    var computerMove1;
    var winner;

    while (playerWins < 5 && computerWins < 5) {
        playerMove1 = getPlayerMove();
        console.log("Player moved!");
        computerMove1 = getComputerMove();
        console.log("Computer moved!");
        console.log('Player chose ' + playerMove1 + ' while Computer chose ' + computerMove1);
        winner = getWinner(playerMove1, computerMove1);
        if (winner === "player") {
            playerWins = playerWins + 1;
            console.log("Player wins!");
        }
        else if (winner === "computer") {
            computerWins = computerWins + 1;
            console.log("Computer wins!");
        }
        else {
            console.log("It's a draw.");
        }
        console.log('The score is currently ' + playerWins + ' to ' + computerWins + '\n');
    }

    return [playerWins, computerWins];
}
playToFive();


text:
package org.sleuthkit.autopsy.modules.fileextmismatch;

import java.awt.Color;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.logging.Level;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
import org.sleuthkit.autopsy.ingest.IngestModuleGlobalSettingsPanel;
import org.openide.util.NbBundle;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.corecomponents.OptionsPanel;
import org.sleuthkit.autopsy.modules.filetypeid.FileTypeDetector;

/**
 * Container panel for File Extension Mismatch Ingest Module advanced
 * configuration options
 */
final class FileExtMismatchSettingsPanel extends IngestModuleGlobalSettingsPanel implements OptionsPanel {

    private static final Logger logger = Logger.getLogger(FileExtMismatchSettingsPanel.class.getName());
    private HashMap<String, String[]> editableMap = new HashMap<>();
    private ArrayList<String> mimeList = null;
    private ArrayList<String> currentExtensions = null;
    private MimeTableModel mimeTableModel;
    private ExtTableModel extTableModel;
    private final String EXT_HEADER_LABEL = NbBundle.getMessage(FileExtMismatchSettingsPanel.class,
            "AddFileExtensionAction.extHeaderLbl.text");
    private String selectedMime = "";
    private String selectedExt = "";
    ListSelectionModel lsm = null;
    private FileTypeDetector fileTypeDetector;

    public FileExtMismatchSettingsPanel() {
        mimeTableModel = new MimeTableModel();
        extTableModel = new ExtTableModel();

        try {
            fileTypeDetector = new FileTypeDetector();
        } catch (FileTypeDetector.FileTypeDetectorInitException ex) {
            logger.log(Level.SEVERE, "Failed to create file type detector", ex); //NON-NLS
            fileTypeDetector = null;
        }

        initComponents();
        customizeComponents();
    }

    private void customizeComponents() {
        setName(NbBundle.getMessage(this.getClass(), "FileExtMismatchConfigPanel.name.text"));

        // Handle selections on the left table
        lsm = mimeTable.getSelectionModel();
        lsm.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                ListSelectionModel listSelectionModel = (ListSelectionModel) e.getSource();
                if (!listSelectionModel.isSelectionEmpty()) {
                    int index = listSelectionModel.getMinSelectionIndex();
                    listSelectionModel.setSelectionInterval(index, index);

                    selectedMime = mimeList.get(index);
                    String labelStr = EXT_HEADER_LABEL + selectedMime + ":";
                    if (labelStr.length() > 80) {
                        labelStr = labelStr.substring(0, 80);
                    }
                    extHeaderLabel.setText(labelStr);
                    updateExtList();

                    extTableModel.resync();
                    //initButtons();
                } else {
                    selectedMime = "";
                    currentExtensions = null;
                    extTableModel.resync();
                }

                clearErrLabels();
            }
        });

        // Handle selections on the right table
        ListSelectionModel extLsm = extTable.getSelectionModel();
        extLsm.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                ListSelectionModel listSelectionModel = (ListSelectionModel) e.getSource();
                if (!listSelectionModel.isSelectionEmpty()) {
                    int index = listSelectionModel.getMinSelectionIndex();
                    listSelectionModel.setSelectionInterval(index, index);

                    selectedExt = currentExtensions.get(index);
                } else {
                    selectedExt = "";
                }

                extRemoveErrLabel.setText(" ");

            }
        });

    }

    private void clearErrLabels() {
        mimeErrLabel.setText(" ");
        mimeRemoveErrLabel.setText(" ");
        extRemoveErrLabel.setText(" ");
        extErrorLabel.setText(" ");
        saveMsgLabel.setText(" ");
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jPanel1 = new javax.swing.JPanel();
        saveButton = new javax.swing.JButton();
        jSplitPane1 = new javax.swing.JSplitPane();
        mimePanel = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        mimeTable = new javax.swing.JTable();
        userTypeTextField = new javax.swing.JTextField();
        addTypeButton = new javax.swing.JButton();
        removeTypeButton = new javax.swing.JButton();
        mimeErrLabel = new javax.swing.JLabel();
        mimeRemoveErrLabel = new javax.swing.JLabel();
        extensionPanel = new javax.swing.JPanel();
        userExtTextField = new javax.swing.JTextField();
        addExtButton = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        extTable = new javax.swing.JTable();
        removeExtButton = new javax.swing.JButton();
        extHeaderLabel = new javax.swing.JLabel();
        extErrorLabel = new javax.swing.JLabel();
        extRemoveErrLabel = new javax.swing.JLabel();
        saveMsgLabel = new javax.swing.JLabel();

        jPanel1.setPreferredSize(new java.awt.Dimension(687, 450));

        saveButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/modules/fileextmismatch/save16.png"))); // NOI18N
        saveButton.setText(org.openide.util.NbBundle.getMessage(FileExtMismatchSettingsPanel.class, "FileExtMismatchSettingsPanel.saveButton.text")); // NOI18N
        saveButton.setEnabled(false);
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        jSplitPane1.setDividerLocation(430);

        jLabel1.setText(org.openide.util.NbBundle.getMessage(FileExtMismatchSettingsPanel.class, "FileExtMismatchSettingsPanel.jLabel1.text")); // NOI18N

        mimeTable.setModel(mimeTableModel);
        jScrollPane2.setViewportView(mimeTable);

        userTypeTextField.setText(org.openide.util.NbBundle.getMessage(FileExtMismatchSettingsPanel.class, "FileExtMismatchSettingsPanel.userTypeTextField.text")); // NOI18N
        userTypeTextField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                userTypeTextFieldFocusGained(evt);
            }
        });

        addTypeButton.setText(org.openide.util.NbBundle.getMessage(FileExtMismatchSettingsPanel.class, "FileExtMismatchSettingsPanel.addTypeButton.text")); // NOI18N
        addTypeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addTypeButtonActionPerformed(evt);
            }
        });

        removeTypeButton.setText(org.openide.util.NbBundle.getMessage(FileExtMismatchSettingsPanel.class, "FileExtMismatchSettingsPanel.removeTypeButton.text")); // NOI18N
        removeTypeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeTypeButtonActionPerformed(evt);
            }
        });

        mimeErrLabel.setForeground(new java.awt.Color(255, 0, 0));
        mimeErrLabel.setText(org.openide.util.NbBundle.getMessage(FileExtMismatchSettingsPanel.class, "FileExtMismatchSettingsPanel.mimeErrLabel.text")); // NOI18N

        mimeRemoveErrLabel.setText(org.openide.util.NbBundle.getMessage(FileExtMismatchSettingsPanel.class, "FileExtMismatchSettingsPanel.mimeRemoveErrLabel.text")); // NOI18N

        javax.swing.GroupLayout mimePanelLayout = new javax.swing.GroupLayout(mimePanel);
        mimePanel.setLayout(mimePanelLayout);
        mimePanelLayout.setHorizontalGroup(
            mimePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mimePanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mimePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addGroup(mimePanelLayout.createSequentialGroup()
                        .addGroup(mimePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addGroup(mimePanelLayout.createSequentialGroup()
                                .addComponent(userTypeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(addTypeButton))
                            .addComponent(removeTypeButton))
                        .addGap(0, 196, Short.MAX_VALUE))
                    .addComponent(mimeErrLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(mimeRemoveErrLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        mimePanelLayout.setVerticalGroup(
            mimePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mimePanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(mimePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(userTypeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(addTypeButton))
                .addGap(3, 3, 3)
                .addComponent(mimeErrLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(removeTypeButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(mimeRemoveErrLabel)
                .addContainerGap(47, Short.MAX_VALUE))
        );

        jSplitPane1.setLeftComponent(mimePanel);

        userExtTextField.setText(org.openide.util.NbBundle.getMessage(FileExtMismatchSettingsPanel.class, "FileExtMismatchSettingsPanel.userExtTextField.text")); // NOI18N
        userExtTextField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                userExtTextFieldFocusGained(evt);
            }
        });

        addExtButton.setText(org.openide.util.NbBundle.getMessage(FileExtMismatchSettingsPanel.class, "FileExtMismatchSettingsPanel.addExtButton.text")); // NOI18N
        addExtButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addExtButtonActionPerformed(evt);
            }
        });

        extTable.setModel(extTableModel);
        jScrollPane3.setViewportView(extTable);

        removeExtButton.setText(org.openide.util.NbBundle.getMessage(FileExtMismatchSettingsPanel.class, "FileExtMismatchSettingsPanel.removeExtButton.text")); // NOI18N
        removeExtButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeExtButtonActionPerformed(evt);
            }
        });

        extHeaderLabel.setText(org.openide.util.NbBundle.getMessage(FileExtMismatchSettingsPanel.class, "FileExtMismatchSettingsPanel.extHeaderLabel.text")); // NOI18N

        extErrorLabel.setForeground(new java.awt.Color(255, 0, 0));
        extErrorLabel.setText(org.openide.util.NbBundle.getMessage(FileExtMismatchSettingsPanel.class, "FileExtMismatchSettingsPanel.extErrorLabel.text")); // NOI18N

        extRemoveErrLabel.setText(org.openide.util.NbBundle.getMessage(FileExtMismatchSettingsPanel.class, "FileExtMismatchSettingsPanel.extRemoveErrLabel.text")); // NOI18N

        javax.swing.GroupLayout extensionPanelLayout = new javax.swing.GroupLayout(extensionPanel);
        extensionPanel.setLayout(extensionPanelLayout);
        extensionPanelLayout.setHorizontalGroup(
            extensionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(extensionPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(extensionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addComponent(extHeaderLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(extensionPanelLayout.createSequentialGroup()
                        .addGroup(extensionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(removeExtButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(extensionPanelLayout.createSequentialGroup()
                                .addComponent(userExtTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(addExtButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                        .addGap(0, 46, Short.MAX_VALUE))
                    .addComponent(extErrorLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(extRemoveErrLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        extensionPanelLayout.setVerticalGroup(
            extensionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, extensionPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(extHeaderLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 285, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(extensionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(userExtTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(addExtButton))
                .addGap(2, 2, 2)
                .addComponent(extErrorLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(removeExtButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(extRemoveErrLabel)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jSplitPane1.setRightComponent(extensionPanel);

        saveMsgLabel.setForeground(new java.awt.Color(0, 0, 255));
        saveMsgLabel.setText(org.openide.util.NbBundle.getMessage(FileExtMismatchSettingsPanel.class, "FileExtMismatchSettingsPanel.saveMsgLabel.text")); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 667, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(saveButton, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(saveMsgLabel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jSplitPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(saveButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(saveMsgLabel)
                .addContainerGap())
        );

        jScrollPane1.setViewportView(jPanel1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 482, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 8, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    // Add a user-provided filename extension string to the selecte mimetype
    private void addExtButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addExtButtonActionPerformed
        String newExt = userExtTextField.getText();
        if (newExt.isEmpty()) {
            extErrorLabel.setForeground(Color.red);
            extErrorLabel.setText(
                    NbBundle.getMessage(this.getClass(), "FileExtMismatchConfigPanel.addExtButton.errLabel.empty"));
            return;
        }

        if (selectedMime.isEmpty()) {
            extErrorLabel.setForeground(Color.red);
            extErrorLabel.setText(
                    NbBundle.getMessage(this.getClass(), "FileExtMismatchConfigPanel.addExtButton.errLabel.noMimeType"));
            return;
        }

        if (currentExtensions.contains(newExt)) {
            extErrorLabel.setForeground(Color.red);
            extErrorLabel.setText(
                    NbBundle.getMessage(this.getClass(), "FileExtMismatchConfigPanel.addExtButton.errLabel.extExists"));
            return;
        }

        ArrayList<String> editedExtensions = new ArrayList<>(Arrays.asList(editableMap.get(selectedMime)));
        editedExtensions.add(newExt);

        // Old array will be replaced by new array for this key
        editableMap.put(selectedMime, editedExtensions.toArray(new String[0]));

        // Refresh table
        updateExtList();
        extTableModel.resync();

        // user feedback for successful add
        extErrorLabel.setForeground(Color.blue);
        extErrorLabel.setText(
                NbBundle.getMessage(this.getClass(), "FileExtMismatchConfigPanel.addExtButton.errLabel.extAdded",
                        newExt));
        extRemoveErrLabel.setText(" ");
        userExtTextField.setText("");
        setIsModified();
    }//GEN-LAST:event_addExtButtonActionPerformed

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        store();
    }//GEN-LAST:event_saveButtonActionPerformed

    private void addTypeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addTypeButtonActionPerformed
        String newMime = userTypeTextField.getText();
        if (newMime.isEmpty()) {
            mimeErrLabel.setForeground(Color.red);
            mimeErrLabel.setText(NbBundle.getMessage(this.getClass(), "FileExtMismatchConfigPanel.addTypeButton.empty"));
            return;
        }
        if (newMime.equals("application/octet-stream")) { //NON-NLS
            mimeErrLabel.setForeground(Color.red);
            mimeErrLabel.setText(NbBundle.getMessage(this.getClass(),
                    "FileExtMismatchConfigPanel.addTypeButton.mimeTypeNotSupported"));
            return;
        }
        if (mimeList.contains(newMime)) {
            mimeErrLabel.setForeground(Color.red);
            mimeErrLabel.setText(
                    NbBundle.getMessage(this.getClass(), "FileExtMismatchConfigPanel.addTypeButton.mimeTypeExists"));
            return;
        }

        boolean mimeTypeDetectable = (null != fileTypeDetector) ? fileTypeDetector.isDetectable(newMime) : false;
        if (!mimeTypeDetectable) {
            mimeErrLabel.setForeground(Color.red);
            mimeErrLabel.setText(NbBundle.getMessage(this.getClass(),
                    "FileExtMismatchConfigPanel.addTypeButton.mimeTypeNotDetectable"));
            return;
        }

        editableMap.put(newMime, new String[0]);

        // Refresh table
        updateMimeList();
        mimeTableModel.resync();

        // user feedback for successful add
        //selectByMimeString(newMime);
        mimeErrLabel.setForeground(Color.blue);
        mimeErrLabel.setText(
                NbBundle.getMessage(this.getClass(), "FileExtMismatchConfigPanel.addTypeButton.mimeTypeAdded", newMime));
        mimeRemoveErrLabel.setText(" ");
        userTypeTextField.setText("");
        setIsModified();
    }//GEN-LAST:event_addTypeButtonActionPerformed

    private void userExtTextFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_userExtTextFieldFocusGained
        extErrorLabel.setText(" "); //space so Swing doesn't mess up vertical spacing
    }//GEN-LAST:event_userExtTextFieldFocusGained

    private void userTypeTextFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_userTypeTextFieldFocusGained
        mimeErrLabel.setText(" "); //space so Swing doesn't mess up vertical spacing
    }//GEN-LAST:event_userTypeTextFieldFocusGained

    private void removeTypeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeTypeButtonActionPerformed
        if (selectedMime.isEmpty()) {
            mimeRemoveErrLabel.setForeground(Color.red);
            mimeRemoveErrLabel.setText(
                    NbBundle.getMessage(this.getClass(), "FileExtMismatchConfigPanel.removeTypeButton.noneSelected"));
            return;
        }

        editableMap.remove(selectedMime);
        String deadMime = selectedMime;

        // Refresh table
        updateMimeList();
        mimeTableModel.resync();

        // user feedback for successful add
        mimeRemoveErrLabel.setForeground(Color.blue);
        mimeRemoveErrLabel.setText(
                NbBundle.getMessage(this.getClass(), "FileExtMismatchConfigPanel.remoteTypeButton.deleted", deadMime));
        setIsModified();
    }//GEN-LAST:event_removeTypeButtonActionPerformed

    private void removeExtButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeExtButtonActionPerformed
        if (selectedExt.isEmpty()) {
            extRemoveErrLabel.setForeground(Color.red);
            extRemoveErrLabel.setText(
                    NbBundle.getMessage(this.getClass(), "FileExtMismatchConfigPanel.removeExtButton.noneSelected"));
            return;
        }

        if (selectedMime.isEmpty()) {
            extErrorLabel.setForeground(Color.red);
            extErrorLabel.setText(NbBundle.getMessage(this.getClass(),
                    "FileExtMismatchConfigPanel.removeExtButton.noMimeTypeSelected"));
            return;
        }

        ArrayList<String> editedExtensions = new ArrayList<>(Arrays.asList(editableMap.get(selectedMime)));
        editedExtensions.remove(selectedExt);
        String deadExt = selectedExt;

        // Old array will be replaced by new array for this key
        editableMap.put(selectedMime, editedExtensions.toArray(new String[0]));

        // Refresh tables
        updateExtList();
        extTableModel.resync();

        // user feedback for successful add
        extRemoveErrLabel.setForeground(Color.blue);
        extRemoveErrLabel.setText(
                NbBundle.getMessage(this.getClass(), "FileExtMismatchConfigPanel.removeExtButton.deleted", deadExt));
        setIsModified();
    }//GEN-LAST:event_removeExtButtonActionPerformed

    private void updateMimeList() {
        mimeList = new ArrayList<>(editableMap.keySet());
        if (mimeList.size() > 0) {
            Collections.sort(mimeList);
        }
    }

    private void updateExtList() {
        String[] temp = editableMap.get(selectedMime);
        if (temp != null) {
            currentExtensions = new ArrayList<>(Arrays.asList(temp));
            if (temp.length > 0) {
                Collections.sort(currentExtensions);
            }
        } else {
            currentExtensions = null;
        }
    }

    @Override
    public void saveSettings() {
        if (FileExtMismatchXML.getDefault().save(editableMap)) {
            mimeErrLabel.setText(" ");
            mimeRemoveErrLabel.setText(" ");
            extRemoveErrLabel.setText(" ");
            extErrorLabel.setText(" ");

            saveMsgLabel.setText(NbBundle.getMessage(this.getClass(), "FileExtMismatchConfigPanel.store.msg"));
            saveButton.setEnabled(false);
        } else {
            //error
            JOptionPane.showMessageDialog(this,
                    NbBundle.getMessage(this.getClass(),
                            "FileExtMismatchConfigPanel.store.msgDlg.msg"),
                    NbBundle.getMessage(this.getClass(),
                            "FileExtMismatchConfigPanel.save.msgDlg.title"),
                    JOptionPane.ERROR_MESSAGE);
        }
    }

    @Override
    public void load() {
        // Load the XML into a buffer that the user can modify. They can choose
        // to save it back to the file after making changes.
        editableMap = FileExtMismatchXML.getDefault().load();
        updateMimeList();
        updateExtList();
    }

    @Override
    public void store() {
        saveSettings();
    }

    private void setIsModified() {
        saveButton.setEnabled(true);
        saveMsgLabel.setText(" ");
    }

    public void cancel() {
        clearErrLabels();
        load(); // The next time this panel is opened, we want it to be fresh
    }

    public void ok() {
        // if data is unsaved
        if (saveButton.isEnabled()) {
            int choice = JOptionPane.showConfirmDialog(this,
                    NbBundle.getMessage(this.getClass(),
                            "FileExtMismatchConfigPanel.ok.confDlg.msg"),
                    NbBundle.getMessage(this.getClass(),
                            "FileExtMismatchConfigPanel.confDlg.title"),
                    JOptionPane.YES_NO_OPTION);
            if (choice == JOptionPane.YES_OPTION) {
                store();
            }
        }
        clearErrLabels();
        load(); // The next time this panel is opened, we want it to be fresh
    }

    boolean valid() {
        return true;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addExtButton;
    private javax.swing.JButton addTypeButton;
    private javax.swing.JLabel extErrorLabel;
    private javax.swing.JLabel extHeaderLabel;
    private javax.swing.JLabel extRemoveErrLabel;
    private javax.swing.JTable extTable;
    private javax.swing.JPanel extensionPanel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JLabel mimeErrLabel;
    private javax.swing.JPanel mimePanel;
    private javax.swing.JLabel mimeRemoveErrLabel;
    private javax.swing.JTable mimeTable;
    private javax.swing.JButton removeExtButton;
    private javax.swing.JButton removeTypeButton;
    private javax.swing.JButton saveButton;
    private javax.swing.JLabel saveMsgLabel;
    private javax.swing.JTextField userExtTextField;
    private javax.swing.JTextField userTypeTextField;
    // End of variables declaration//GEN-END:variables

    private class MimeTableModel extends AbstractTableModel {

        @Override
        public int getColumnCount() {
            return 1;
        }

        @Override
        public int getRowCount() {
            return editableMap == null ? 0 : editableMap.size();
        }

        @Override
        public String getColumnName(int column) {
            String colName = null;

            switch (column) {
                case 0:
                    colName = NbBundle.getMessage(this.getClass(), "FileExtMismatchConfigPanel.mimeTableModel.colName");
                    break;
                default:
                    ;

            }
            return colName;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            Object ret = null;
            if ((mimeList == null) || (rowIndex > mimeList.size())) {
                return "";
            }
            String word = mimeList.get(rowIndex);
            switch (columnIndex) {
                case 0:
                    ret = (Object) word;
                    break;
                default:
                    logger.log(Level.SEVERE, "Invalid table column index: {0}", columnIndex); //NON-NLS
                    break;
            }
            return ret;
        }

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return false;
        }

        @Override
        public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
        }

        @Override
        public Class<?> getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }

        void resync() {
            fireTableDataChanged();
        }
    }

    private class ExtTableModel extends AbstractTableModel {

        @Override
        public int getColumnCount() {
            return 1;
        }

        @Override
        public int getRowCount() {
            return currentExtensions == null ? 0 : currentExtensions.size();
        }

        @Override
        public String getColumnName(int column) {
            String colName = null;

            switch (column) {
                case 0:
                    colName = NbBundle.getMessage(this.getClass(), "FileExtMismatchConfigPanel.extTableModel.colName");
                    break;
                default:
                    ;

            }
            return colName;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            Object ret = null;

            if ((currentExtensions == null) || (currentExtensions.isEmpty()) || (rowIndex > currentExtensions.size())) {
                return "";
            }
            String word = currentExtensions.get(rowIndex);
            switch (columnIndex) {
                case 0:
                    ret = (Object) word;
                    break;
                default:
                    logger.log(Level.SEVERE, "Invalid table column index: {0}", columnIndex); //NON-NLS
                    break;
            }
            return ret;
        }

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return false;
        }

        @Override
        public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
        }

        @Override
        public Class<?> getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }

        void resync() {
            fireTableDataChanged();
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <corners android:radius="15dp"/>
    <solid android:color="#ffffff"/>
    <stroke android:width="1dp" android:color="#ffffff"/>

</shape>


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/launchAppItem"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/selectableItemBackgroundBorderless"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:padding="8dp">

    <androidx.appcompat.widget.AppCompatImageView
        android:id="@+id/appIcon"
        android:layout_width="64dp"
        android:layout_height="64dp"
        android:layout_gravity="center_horizontal"
        android:src="@android:drawable/sym_def_app_icon" />

    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/appName"
        style="@style/SingleLineText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginTop="8dp"
        android:gravity="center_horizontal"
        android:text="@string/app_name"
        android:textAppearance="@style/TextAppearance.HEBF.Body2"
        android:textColor="?attr/colorOnSurface" />

</LinearLayout>


text:
package io.part12.xfiles;

import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;

/**
 * Created by chenyang on 2016/10/25.
 */
public class ThawAlien {
    public static void main(String[] args) throws Exception{
        ObjectInputStream in=new ObjectInputStream(
                new FileInputStream(new File("./src/main/java/io/part12/X.file")));
        Object mystery=in.readObject();
        System.out.println(mystery.getClass());

    }
}


text:
package org.jetbrains.plugins.scala.lang.typeConformance
package generated

class TypeConformanceExistentialTest extends TypeConformanceTestBase {
  //This class was generated by build script, please don't change this
  override def folderPath: String = super.folderPath + "existential/"

  //todo:
  /*def testBadLowerBound() {doTest()}*/

  //todo:
  /*def testBadLowerBound2() {doTest()}*/

  //todo:
  /*def testBadLowerBoundPrimitive() {doTest()}*/

  def testBadLowerUpper() {doTest()}

  def testBadToExistential() {doTest()}

  def testInnerPlaceHolder() {doTest()}

  def testInnerPlaceholderBack() {doTest()}

  def testLowerBound() {doTest()}

  def testLowerBound2() {doTest()}

  def testLowerBoundAbstract() {doTest()}

  //todo:
  /*def testLowerBoundAbstract2() {doTest()}*/

  def testLowerBoundPrimitive() {doTest()}

  def testLowerBoundsPrimitiveCovariant() {doTest()}

  def testLowerUpperBouns() {doTest()}

  def testSCL2977() {doTest()}

  def testSCL2977B() {doTest()}

  def testToExistential() {doTest()}

  def testToExistentialSimple() {doTest()}

  //SCL-10295
  def testExistentialWithAliasedDesignator() {doTest()}

  def testSCL12127ConformanceFreeze(): Unit = {
    doTest(
      """
        |abstract class Quantity[A <: Quantity[A]] extends Serializable with Ordered[A] {
        |  self: A ⇒
        |}
        |
        |trait Dimension[A <: Quantity[A]]
        |
        |type RQuantity = T forSome {type T <: Quantity[T]}
        |type RDimension = Dimension[_ <: RQuantity]
        |
        |val rq: RQuantity = ???
        |val x: Function[_, _] = rq
        |//false
        |""".stripMargin
    )
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

  <fragment android:name="com.appboy.ui.AppboyFeedbackFragment"
      android:id="@+id/com_appboy_feedback"
      android:layout_width="match_parent"
      android:layout_height="match_parent"/>
</LinearLayout>