text:
/*
 * Do not modify this file. This file is generated from the sts-2011-06-15.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;

using Amazon.Runtime;
using Amazon.Runtime.Internal;

namespace Amazon.SecurityToken.Model
{
    ///
    /// Container for the parameters to the GetFederationToken operation.
    /// Returns a set of temporary security credentials (consisting of an access key ID, a
    /// secret access key, and a security token) for a federated user. A typical use is in
    /// a proxy application that gets temporary security credentials on behalf of distributed
    /// applications inside a corporate network. Because you must call the GetFederationToken
    /// action using the long-term security credentials of an IAM user, this call is appropriate
    /// in contexts where those credentials can be safely stored, usually in a server-based
    /// application.
    ///
    ///  <note>
    /// <para>
    ///  If you are creating a mobile-based or browser-based app that can authenticate users
    /// using a web identity provider like Login with Amazon, Facebook, Google, or an OpenID
    /// Connect-compatible identity provider, we recommend that you use Amazon
    /// Cognito or AssumeRoleWithWebIdentity. For more information, see Federation
    /// Through a Web-based Identity Provider.
    /// </para>
    ///  </note>
    /// <para>
    /// The GetFederationToken action must be called by using the long-term AWS
    /// security credentials of an IAM user. You can also call GetFederationToken
    /// using the security credentials of an AWS account (root), but this is not recommended.
    /// Instead, we recommend that you create an IAM user for the purpose of the proxy application
    /// and then attach a policy to the IAM user that limits federated users to only the actions
    /// and resources they need access to. For more information, see IAM
    /// Best Practices in the Using IAM.
    /// </para>
    ///
    /// <para>
    /// The temporary security credentials that are obtained by using the long-term credentials
    /// of an IAM user are valid for the specified duration, between 900 seconds (15 minutes)
    /// and 129600 seconds (36 hours). Temporary credentials that are obtained by using AWS
    /// account (root) credentials have a maximum duration of 3600 seconds (1 hour)
    /// </para>
    ///
    /// <para>
    ///  Permissions
    /// </para>
    ///
    /// <para>
    /// The permissions for the temporary security credentials returned by GetFederationToken
    /// are determined by a combination of the following:
    /// </para>
    ///

The policy or policies that are attached to the IAM user whose credentials
    /// are used to call GetFederationToken.

The policy that is passed
    /// as a parameter in the call.

    /// <para>
    /// The passed policy is attached to the temporary security credentials that result from
    /// the GetFederationToken API call--that is, to the federated user.
    /// When the federated user makes an AWS request, AWS evaluates the policy attached to
    /// the federated user in combination with the policy or policies attached to the IAM
    /// user whose credentials were used to call GetFederationToken. AWS allows
    /// the federated user's request only when both the federated user and the
    /// IAM user are explicitly allowed to perform the requested action. The passed policy
    /// cannot grant more permissions than those that are defined in the IAM user policy.
    /// </para>
    ///
    /// <para>
    /// A typical use case is that the permissions of the IAM user whose credentials are used
    /// to call GetFederationToken are designed to allow access to all the actions
    /// and resources that any federated user will need. Then, for individual users, you pass
    /// a policy to the operation that scopes down the permissions to a level that's appropriate
    /// to that individual user, using a policy that allows only a subset of permissions that
    /// are granted to the IAM user.
    /// </para>
    ///
    /// <para>
    /// If you do not pass a policy, the resulting temporary security credentials have no
    /// effective permissions. The only exception is when the temporary security credentials
    /// are used to access a resource that has a resource-based policy that specifically allows
    /// the federated user to access the resource.
    /// </para>
    ///
    /// <para>
    /// For more information about how permissions work, see Permissions
    /// for GetFederationToken. For information about using GetFederationToken
    /// to create temporary security credentials, see GetFederationToken—Federation
    /// Through a Custom Identity Broker.
    /// </para>
    ///
    public partial class GetFederationTokenRequest : AmazonSecurityTokenServiceRequest
    {
        private int? _durationSeconds;
        private string _name;
        private string _policy;

        ///
        /// Empty constructor used to set  properties independently even when a simple constructor is available
        ///
        public GetFederationTokenRequest() { }

        ///
        /// Instantiates GetFederationTokenRequest with the parameterized properties
        ///
        /// <param name="name">The name of the federated user. The name is used as an identifier for the temporary security credentials (such as Bob). For example, you can reference the federated user name in a resource-based policy, such as in an Amazon S3 bucket policy. </param>
        public GetFederationTokenRequest(string name)
        {
            _name = name;
        }

        ///
        /// Gets and sets the property DurationSeconds.
        /// <para>
        /// The duration, in seconds, that the session should last. Acceptable durations for federation
        /// sessions range from 900 seconds (15 minutes) to 129600 seconds (36 hours), with 43200
        /// seconds (12 hours) as the default. Sessions obtained using AWS account (root) credentials
        /// are restricted to a maximum of 3600 seconds (one hour). If the specified duration
        /// is longer than one hour, the session obtained by using AWS account (root) credentials
        /// defaults to one hour.
        /// </para>
        ///
        public int DurationSeconds
        {
            get { return this._durationSeconds.GetValueOrDefault(); }
            set { this._durationSeconds = value; }
        }

        // Check to see if DurationSeconds property is set
        internal bool IsSetDurationSeconds()
        {
            return this._durationSeconds.HasValue;
        }

        ///
        /// Gets and sets the property Name.
        /// <para>
        /// The name of the federated user. The name is used as an identifier for the temporary
        /// security credentials (such as Bob). For example, you can reference the
        /// federated user name in a resource-based policy, such as in an Amazon S3 bucket policy.
        ///
        /// </para>
        ///
        public string Name
        {
            get { return this._name; }
            set { this._name = value; }
        }

        // Check to see if Name property is set
        internal bool IsSetName()
        {
            return this._name != null;
        }

        ///
        /// Gets and sets the property Policy.
        /// <para>
        /// An IAM policy in JSON format that is passed with the GetFederationToken
        /// call and evaluated along with the policy or policies that are attached to the IAM
        /// user whose credentials are used to call GetFederationToken. The passed
        /// policy is used to scope down the permissions that are available to the IAM user, by
        /// allowing only a subset of the permissions that are granted to the IAM user. The passed
        /// policy cannot grant more permissions than those granted to the IAM user. The final
        /// permissions for the federated user are the most restrictive set based on the intersection
        /// of the passed policy and the IAM user policy.
        /// </para>
        ///
        /// <para>
        /// If you do not pass a policy, the resulting temporary security credentials have no
        /// effective permissions. The only exception is when the temporary security credentials
        /// are used to access a resource that has a resource-based policy that specifically allows
        /// the federated user to access the resource.
        /// </para>
        ///  <note>The policy plain text must be 2048 bytes or shorter. However, an internal conversion
        /// compresses it into a packed binary format with a separate limit. The PackedPolicySize
        /// response element indicates by percentage how close to the upper size limit the policy
        /// is, with 100% equaling the maximum allowed size. </note>
        /// <para>
        /// For more information about how permissions work, see Permissions
        /// for GetFederationToken.
        /// </para>
        ///
        public string Policy
        {
            get { return this._policy; }
            set { this._policy = value; }
        }

        // Check to see if Policy property is set
        internal bool IsSetPolicy()
        {
            return this._policy != null;
        }

    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Malfunction</title>
<meta name="date" content="2017-02-21">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.mygdx.game

Class Malfunction

java.lang.Object

com.mygdx.game.RandomEvent

com.mygdx.game.Malfunction

public class Malfunction
extends RandomEvent

Field Summary

Fields inherited from class com.mygdx.game.RandomEvent

duration

Constructor Summary

Constructors

Constructor and Description

Malfunction(GameEngine gameEngine,
           GameScreen gameScreen,
           int playerToAffect)

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

void
eventEffect(boolean doOrUndo)

Overridden eventEffect() method initially found in the RandomEvent class.

java.lang.String
eventMessage(boolean doOrUndo)

Overridden eventMessage() method initially found in the RandomEvent class.

Roboticon
getRoboticonToMalfunction()

Gets the roboticon which will malfunction.

int[]
getStartingRoboticonLevels()

Gets the roboticon production levels before the malfunction occurs.

java.lang.String
toString()

Returns a string representation of a Malfunction random event.

Methods inherited from class com.mygdx.game.RandomEvent

decDuration, eventHappen, getDuration, getEventCooldown

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

Malfunction

public Malfunction(GameEngine gameEngine,
                   GameScreen gameScreen,
                   int playerToAffect)

Method Detail

getStartingRoboticonLevels

public int[] getStartingRoboticonLevels()

Gets the roboticon production levels before the malfunction occurs.

getRoboticonToMalfunction

public Roboticon getRoboticonToMalfunction()

Gets the roboticon which will malfunction.

eventEffect

public void eventEffect(boolean doOrUndo)

Overridden eventEffect() method initially found in the RandomEvent class.

Specified by:

eventEffect in class RandomEvent

Parameters:

doOrUndo: - boolean determining whether to cause the event effect, or
                reverse it. True -> Cause, False -> Reverse.

eventMessage

public java.lang.String eventMessage(boolean doOrUndo)

Overridden eventMessage() method initially found in the RandomEvent class.

Specified by:

eventMessage in class RandomEvent

Parameters:

doOrUndo: - boolean determining whether to cause the event effect, or
                reverse it. True -> Cause, False -> Reverse.

toString

public java.lang.String toString()

Returns a string representation of a Malfunction random event.

Overrides:

toString in class java.lang.Object

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

redpajama_set_name: RedPajamaGithub


text:
cp ../../Bin/silver.png $1.app/Contents/Resources
cp ../../Bin/background1.jpg $1.app/Contents/Resources


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
 Licensed to the Apache Software Foundation (ASF) under one
 or more contributor license agreements.  See the NOTICE file
 distributed with this work for additional information
 regarding copyright ownership.  The ASF licenses this file
 to you under the Apache License, Version 2.0 (the
 "License"); you may not use this file except in compliance
 with the License.  You may obtain a copy of the License at

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

 Unless required by applicable law or agreed to in writing,
 software distributed under the License is distributed on an
 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 KIND, either express or implied.  See the License for the
 specific language governing permissions and limitations
 under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.apache.aries.blueprint</groupId>
        <artifactId>blueprint-parent</artifactId>
        <version>1.0.0</version>
        <relativePath>../../blueprint-parent/pom.xml</relativePath>
    </parent>

    <groupId>org.apache.aries.blueprint</groupId>
    <artifactId>org.apache.aries.blueprint.sample-fragment</artifactId>
    <name>Apache Aries Blueprint Sample Fragment for Testing Annotation</name>
    <version>1.0.1-SNAPSHOT</version>
    <packaging>bundle</packaging>
    <description>
        Example blueprint fragment, mostly used for annotation tests.
    </description>

    <scm>
        <connection>scm:git:https://gitbox.apache.org/repos/asf/aries.git</connection>
        <developerConnection>scm:git:https://gitbox.apache.org/repos/asf/aries.git</developerConnection>
        <url>https://gitbox.apache.org/repos/asf?p=aries.git;a=summary</url>
    </scm>

    <properties>
        <aries.osgi.export>
            org.apache.aries.blueprint.fragment;-noimport:=true
        </aries.osgi.export>
        <aries.osgi.import>
            org.apache.aries.blueprint.annotation;provide:=true,
            *
        </aries.osgi.import>
        <aries.osgi.private.pkg />

        <blueprint.api.version>1.0.1</blueprint.api.version>
    </properties>

    <profiles>
        <profile>
            <id>dev</id>
            <properties>
                <blueprint.api.version>${blueprint.api.dev.version}</blueprint.api.version>
            </properties>
        </profile>
    </profiles>

    <dependencies>
        <dependency>
            <groupId>org.eclipse</groupId>
            <artifactId>osgi</artifactId>
            <version>3.5.0.v20090520</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.aries.blueprint</groupId>
            <artifactId>org.apache.aries.blueprint.api</artifactId>
            <version>${blueprint.api.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.aries.blueprint</groupId>
            <artifactId>org.apache.aries.blueprint.annotation.api</artifactId>
            <version>1.0.0</version>
        </dependency>
    </dependencies>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.felix</groupId>
                    <artifactId>maven-bundle-plugin</artifactId>
                    <extensions>true</extensions>
                    <inherited>true</inherited>
                    <configuration>
                        <excludeDependencies>${aries.osgi.exclude.dependencies}</excludeDependencies>
                        <instructions>
                            <Fragment-Host>org.apache.aries.blueprint.sample-annotation</Fragment-Host>
                        </instructions>
                    </configuration>
                </plugin>

            </plugins>
        </pluginManagement>
    </build>

</project>


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace mReporterLib
{

    public class FreeText : ReportItem
    {
        string _text;

        public FreeText(string text) : base(ReportItemType.UserDefined)
        {
            _text = text;
        }

        public override void Render(RenderContext context)
        {
            context.AddToOutput(this, new FreeTextElement(context, _text));
        }
    }

    class FreeTextElement : OutputElement
    {
        RenderContext _context;
        string _text;

        public FreeTextElement(RenderContext context, string text)
        {
            _context = context;
            _text = text;
        }

        public override void WriteTo(Stream stream, Encoding textEncoding)
        {
            List<_Tag> tags = new List<_Tag>();

            ParserState state = ParserState.Text;
            string tag = "";
            char[] buffer = new char[_text.Length];
            int bufferPos = 0;

            for (int i = 0; i < _text.Length; i++) {
                char c = _text[i];

                switch (state) {
                    case ParserState.Text:
                        if (c == TAG_START) {
                            state = ParserState.StartTag;

                            /*
                            tags.Add(new _Tag {
                                SimpleText = new string(buffer, 0, bufferPos - 1)
                            });
                            */

                            bufferPos = 0;

                        }
                        else {
                            Write(c);

                            //buffer[bufferPos++] = c;

                        }

                        break;

                    case ParserState.StartTag:

                        if (c == TAG_END_START) {
                            state = ParserState.EndTag;

                            bufferPos = 0;
                        }
                        else if (c == TAG_PARAMETER_DELIMITER) {

                            tag = new string(buffer, 0, bufferPos - 1);

                            state = ParserState.Parameter;
                            bufferPos = 0;
                        }
                        else if (c == TAG_END) {

                            state = ParserState.Text;

                        }
                        else {
                            buffer[bufferPos++] = c;
                        }

                        break;

                    case ParserState.EndTag:

                        if (c == TAG_END) {

                        }

                        _Tag t = new _Tag { Name = tag };

                        tags.Add(t);

                        buffer[bufferPos++] = c;

                        state = ParserState.Text;
                        bufferPos = 0;

                        break;

                    case ParserState.Parameter:

                        buffer[bufferPos++] = c;

                        break;
                    default:
                        break;
                }

            }

            void Write(char c)
            {
                var b = textEncoding.GetBytes(new char[] { c });
                stream.Write(b, 0, b.Length);
            }

        }

        class _Tag
        {
            public string Name { get; set; }
            public ReportItem Item { get; set; }
            public string SimpleText { get; set; }
        }

        enum ParserState { Text, StartTag, EndTag, Parameter }
        const char TAG_START = '<';
        const char TAG_END = '>';
        const char TAG_END_START = '/';
        const char PARAMETER_DELIMITER = ',';
        const char TAG_PARAMETER_DELIMITER = ':';
    }

}


text:
(function(factory) {
  if (typeof define === 'function' && define.amd) {
    define(['knockout'], factory)
  } else if (typeof exports === 'object' && typeof module === 'object') {
    /*global module*/
    module.exports = factory(require('knockout'))
  } else {
    /*global ko*/
    factory(ko)
  }
})(function(ko) {

  var deepObservifyArray = function(arr, merge, options) {
    for (var i = 0, len = merge.length; i < len; i++) {
      // TODO circular reference protection
      if (merge[i] != null && typeof merge[i] === 'object' &&
          arr[i] != null && typeof arr[i] === 'object') {
        if (options.deep !== false && Array.isArray(arr[i])) {
          deepObservifyArray(arr[i], merge[i], options)
        } else {
          ko.observe(arr[i], merge[i], options)
        }
      } else if (arr[i] !== merge[i]) {
        arr[i] = ko.observableObject(merge[i])
      }
    }
  },
  defineProperty = function(type, obj, prop, def /* definition or default */, options) {
    if (obj == null || typeof obj !== 'object' || typeof prop !== 'string') {
      throw new Error('invalid arguments passed')
    }

    if (Object.prototype.toString.call(def) === '[object Array]' && type === 'observable') {
      type = 'observableArray'
    }

    var descriptor = Object.getOwnPropertyDescriptor(obj, prop), observable
    if (!descriptor || (!descriptor.get && !descriptor.set)) {
      if (descriptor) delete obj[prop]

      observable = ko.isObservable(def) ? def : ko[type](def)
      Object.defineProperty(obj, prop, {
        set: ko.isWritableObservable(observable) ? observable : undefined,
        get: observable,
        enumerable: true,
        configurable: true
      })

      Object.defineProperty(obj, '_' + prop, {
        get: function() { return observable },
        enumerable: false
      })

      if (type === 'observableArray') {
        var update = function(arr) {
          if (Array.isArray(arr) && !Object.getOwnPropertyDescriptor(arr, 'push')) {
            ['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'].forEach(function(f) {
              // sadly we can't just use ko.observableArray.fn's functions, as it doesn't call
              // Array.prototype[f].apply but on the object, resulting in infinite recursion.
              Object.defineProperty(arr, f, {
                value: function() {
                  observable.valueWillMutate()
                  var result = Array.prototype[f].apply(observable.peek(), arguments)
                  observable.valueHasMutated()
                  return result
                }
              })
            });
            ['remove', 'replace', 'removeAll'].forEach(function(f) {
              Object.defineProperty(arr, f, { value: ko.observableArray.fn[f].bind(observable) })
            })
            Object.defineProperty(arr, 'toggle', {
              value: function(item) {
                var idx = observable().indexOf(item), contained = idx !== -1
                contained ? observable.splice(idx, 1) : observable.push(item)
                return !contained
              }
            })
          }
        }
        observable.subscribe(update)
        update(def)
      }
    }

    var current = obj[prop]
    if ((!options || options.deep !== false) && (current != null && typeof current === 'object')) {
      ko.observe(current, def, options, prop)
      // if the current propery is an observable array property, notify it's subscribers that it changed
      if (Array.isArray(current) && current !== def && obj['_' + prop]) {
        obj['_' + prop].notifySubscribers()
      }
    } else if (current !== def && !observable) {
      obj[prop] = def
    }
  }

  ko.defineObservableProperty = defineProperty.bind(null, 'observable')
  ko.defineComputedProperty = function(obj, prop, definition) {
    if (typeof definition === 'function') {
      definition = definition.bind(obj)
    }
    return defineProperty('computed', obj, prop, definition)
  }

  ko.observe = function(model, defaults, options, /* private */ parentProp) {
    var def, prop
    options = options || {}

    if (arguments.length < 2) {
      defaults = model
    }
    if (defaults == null || typeof defaults !== 'object') {
      return defaults
    }

    if (Array.isArray(model)) {
      // specially handle merging arrays if a mapping exists at all, a map exists for
      // this particular array, and if both sides are an array
      if (options.arrayMapping && parentProp && typeof options.arrayMapping === 'object' &&
          options.arrayMapping[parentProp] && Array.isArray(defaults)) {
        var itemProp = options.arrayMapping[parentProp],
            len = defaults.length,
            mappedDefaults = []

        model.forEach(function(modelItem) {
          var defaultsItem, def, idx
          if (modelItem != null && typeof modelItem === 'object') {
            var modelItemProp = modelItem[itemProp]
            for (idx = 0; idx < len; idx++) {
              def = defaults[idx]
              if (def && (def[itemProp] === modelItemProp)) {
                defaultsItem = def
                break
              }
            }
          }

          if (defaultsItem != null) {
            mappedDefaults.push(defaultsItem)
            delete defaults[idx]
          } else {
            mappedDefaults.push(modelItem)
          }
        })
        // filter (x) -> true makes an array not sparse
        defaults = mappedDefaults.concat(defaults.filter(function(x) { return true }))
      }

      deepObservifyArray(model, defaults, options)
    } else {
      for (prop in defaults) {
        if (defaults.hasOwnProperty(prop)) {
          ko.defineObservableProperty(model, prop, defaults[prop], options)
        }
      }
    }

    return model
  }

  ko.observableObject = function(defaults, options) {
    return ko.observe({}, defaults, options)
  }

  ko.track = function(obj, props) {
    (props || Object.keys(obj)).forEach(function(prop) {
      ko.defineObservableProperty(obj, prop, obj[prop], { deep: false })
    })
    return obj
  }

  return ko
})


text:
@interface XKPictureViewController : XKTopicViewController

@end


text:
<?php

$path = __FILE__;
$pathwp = explode( 'wp-content', $path );
$wp_url = $pathwp[0];
require_once( $wp_url.'/wp-load.php' );

?>

 Select Default Post Layout

<input type="hidden" name="<?php echo SN;?>_post_layout" id="<?php echo SN;?>_post_layout" value="<?php echo get_option(SN."_post_layout"); ?>" />

 Select Default Page Layout

<input type="hidden" name="<?php echo SN;?>_page_layout" id="<?php echo SN;?>_page_layout" value="<?php echo get_option(SN."_page_layout"); ?>" />


text:
<?php

/**
 * @namespace
 */
namespace PopTest\Pdf;

use Pop\Loader\Autoloader;
use Pop\Pdf\Object\Root;

// Require the library's autoloader.
require_once __DIR__ . '/../../../src/Pop/Loader/Autoloader.php';

// Call the autoloader's bootstrap function.
Autoloader::factory()->splAutoloadRegister();

class RootTest extends \PHPUnit_Framework_TestCase
{

    public function testConstructor()
    {
        $this->assertInstanceOf('Pop\Pdf\Object\Root', new Root());
    }

    public function testToString()
    {
        $r = new Root("<<1 0 obj\n<</Pages 2 0 R/Type/Catalog>>\nendobj\n>>");
        $this->assertContains('%PDF-1.7', (string)$r);
    }

}


text:
module MLIR.AST.Dialect.Linalg
  ( module MLIR.AST.Dialect.Generated.Linalg
  , module MLIR.AST.Dialect.Generated.LinalgStructured
  ) where

import MLIR.AST.Dialect.Generated.Linalg
import MLIR.AST.Dialect.Generated.LinalgStructured


text:
package jade.data.config;

import jade.content.onto.BasicOntology;
import jade.content.onto.BeanOntology;
import jade.content.onto.Ontology;
import jade.content.onto.OntologyException;
import jade.content.schema.ConceptSchema;
import jade.content.schema.ObjectSchema;

public class ConfigOntology extends BeanOntology {
	public static final String ONTOLOGY_NAME = "Config-Ontology";

	private static final ConfigOntology instance = new ConfigOntology();

	public static String CONFIG_PARAM = "ConfigParam";
	public static String CONFIG_PARAM_KEY = "key";
	public static String CONFIG_PARAM_VALUE = "value";

	public static ConfigOntology getInstance() {
		return instance;
	}

	private ConfigOntology() {
		super(ONTOLOGY_NAME);

		try {
			add("jade.data.config");
		} catch(OntologyException ex) {
			ex.printStackTrace();
		}
	}
}


text:
package org.eclipse.gemini.jpa.test.basic;

import javax.persistence.Persistence;
import javax.persistence.EntityManagerFactory;

import org.junit.*;
import org.osgi.framework.BundleContext;

/**
 * Test class to test static Persistence class using OSGi JPA services
 *
 * @author mkeith
 */
public class TestStaticPersistence extends AccountTest {

    public static final String TEST_NAME = "TestStaticPersistence";
    public static final String PERSISTENCE_UNIT_UNDER_TEST = "Accounts";

    public static EntityManagerFactory emf;
    public static BundleContext ctx;

    /* === Test Methods === */

    @BeforeClass
    public static void classSetUp() {
        sdebug(TEST_NAME, "In setup");
        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_UNDER_TEST);
        sdebug(TEST_NAME, "Got EMF - " + emf);
    }

    @AfterClass
    public static void classCleanUp() throws Exception {
        if (emf != null) {
            emf.close();
            emf = null;
        }
    }

    /* === Subclassed methods === */

    public EntityManagerFactory getEmf() { return emf; }

    public String getTestPersistenceUnitName() { return PERSISTENCE_UNIT_UNDER_TEST; }
}


text:
package org.mini2Dx.core;

import org.mini2Dx.core.game.GameContainer;
import org.mini2Dx.core.util.RollingAverage;
import org.mini2Dx.core.util.RollingMax;
import org.mini2Dx.core.util.ZlibStream;

public abstract class PlatformUtils {

    private long updateSecondStart;
    private long updateStartNanos;
    private int updates;
    private int updatesPerSecond;
    private final RollingAverage averageUpdateDuration = new RollingAverage(GameContainer.TARGET_FPS);
    private final RollingMax maxUpdateDuration = new RollingMax(GameContainer.TARGET_FPS);

    private long interpolateStartNanos;
    private final RollingAverage averageInterpolateDuration = new RollingAverage(GameContainer.TARGET_FPS);
    private final RollingMax maxInterpolateDuration = new RollingMax(GameContainer.TARGET_FPS);

    private long renderStartNanos;
    private final RollingAverage averageRenderDuration = new RollingAverage(GameContainer.TARGET_FPS);
    private final RollingMax maxRenderDuration = new RollingMax(GameContainer.TARGET_FPS);

    private long frameStartNanos;
    private final RollingAverage averageFrameInterval = new RollingAverage(GameContainer.TARGET_FPS);
    private final RollingAverage averageFrameDuration = new RollingAverage(GameContainer.TARGET_FPS);
    private final RollingMax maxFrameDuration = new RollingMax(GameContainer.TARGET_FPS);

    private long frameSecondStart;
    private int frames;
    private int framesPerSecond;

    /**
     * Exits the game
     * @param ignorePlatformRestrictions exit even if platform rules don't permit exiting programmatically. Should be
     *                                   used only for debug purposes and always set to false for release builds.
     */
    public abstract void exit(boolean ignorePlatformRestrictions);

    /**
     * Platform independent version of {@link System#nanoTime()}
     * @see System#nanoTime()
     */
    public abstract long nanoTime();

    /**
     * Platform independent version of {@link System#currentTimeMillis()}
     * @see System#currentTimeMillis()
     */
    public abstract long currentTimeMillis();

    /**
     * Gets the total memory that can be used by the game
     * @return Number of bytes that can be used by the game
     */
    public abstract long getTotalMemory();

    /**
     * Gets the total memory available for the game
     * @return Number of bytes available for the game
     */
    public abstract long getAvailableMemory();

    /**
     * Gets the total memory used by the game
     * @return Number of bytes used by the game
     */
    public abstract long getUsedMemory();

    /**
     * Indicates if the current thread is the game thread
     * @return if the current thread is the game thread
     */
    public abstract boolean isGameThread();

    /**
     * Enables performance mode on the device. Depending on the device, this may be disabled by the OS at any time.
     * This is best used to temporarily boost performance during asset loading. On devices where this is not supported, this does nothing.
     */
    public abstract void enablePerformanceMode();

    /**
     * Cancels performance mode on the device. If performance mode was already cancelled by the OS, this does nothing.
     * On devices where this is not supported, this does nothing.
     */
    public abstract void cancelPerformanceMode();

    /**
     * Internal usage only: marks the beginning of update operations
     */
    public void markUpdateBegin() {
        long time = nanoTime();

        if (time - updateSecondStart >= 1000000000) {
            updatesPerSecond = updates;
            updates = 0;
            updateSecondStart = time;
        }
        updates++;

        updateStartNanos = nanoTime();
    }

    /**
     * Internal usage only: marks the beginning of interpolate operations
     */
    public void markInterpolateBegin() {
        interpolateStartNanos = nanoTime();
    }

    /**
     * Internal usage only: marks the end of interpolate operations
     */
    public void markInterpolateEnd() {
        long time = nanoTime();
        long interpolateDuration = time - interpolateStartNanos;

        averageInterpolateDuration.mark(interpolateDuration);
        maxInterpolateDuration.mark(interpolateDuration);
    }

    /**
     * Internal usage only: marks the beginning of rendering operations
     */
    public void markRenderBegin() {
        renderStartNanos = nanoTime();
    }

    /**
     * Internal usage only: marks the end of rendering operations
     */
    public void markRenderEnd() {
        long time = nanoTime();
        long renderDuration = time - renderStartNanos;

        averageRenderDuration.mark(renderDuration);
        maxRenderDuration.mark(renderDuration);
    }

    /**
     * Internal usage only: marks the end of update operations
     */
    public void markUpdateEnd() {
        long time = nanoTime();
        long updateDuration = time - updateStartNanos;

        averageUpdateDuration.mark(updateDuration);
        maxUpdateDuration.mark(updateDuration);
    }

    /**
     * Internal usage only: marks a new frame
     */
    public void markFrameBegin() {
        long time = nanoTime();

        if(frameStartNanos != 0) {
            averageFrameInterval.mark(time - frameStartNanos);
        }
        frameStartNanos = time;

        if (time - frameSecondStart >= 1000000000) {
            framesPerSecond = frames;
            frames = 0;
            frameSecondStart = time;
        }
        frames++;
    }

    public void markFrameEnd() {
        long time = nanoTime();
        long frameDuration = time - frameStartNanos;

        averageFrameDuration.mark(frameDuration);
        maxFrameDuration.mark(frameDuration);
    }

    /**
     * Returns the number of updates per second
     *
     * @return The number of updates per second
     */
    public int getUpdatesPerSecond() {
        return updatesPerSecond;
    }

    /**
     * Returns the number of frames per second
     *
     * @return the number of frames per second
     */
    public int getFramesPerSecond() {
        return framesPerSecond;
    }

    /**
     * Returns the number of frames that have occurred so far this second
     * @return
     */
    public int getUpdatesThisSecond() {
        return updates;
    }

    /**
     * Returns the average duration of update()
     *
     * @return The average duration in nanoseconds
     */
    public double getAverageUpdateDuration() {
        return averageUpdateDuration.getAverage();
    }

    /**
     * Returns the maximum update() duration in the last second
     * @return The duration in nanoseconds
     */
    public double getMaxUpdateDuration() {
        return maxUpdateDuration.getMax();
    }

    /**
     * Returns the average duration of interpolate()
     *
     * @return The average duration in nanoseconds
     */
    public double getAverageInterpolateDuration() {
        return averageInterpolateDuration.getAverage();
    }

    /**
     * Returns the maximum interpolate() duration in the last second
     * @return The duration in nanoseconds
     */
    public double getMaxInterpolateDuration() {
        return maxInterpolateDuration.getMax();
    }

    /**
     * Returns the average duration of render({@link Graphics})
     *
     * @return The average duration in nanoseconds
     */
    public double getAverageRenderDuration() {
        return averageRenderDuration.getAverage();
    }

    /**
     * Returns the maximum render() duration in the last second
     * @return The duration in nanoseconds
     */
    public double getMaxRenderDuration() {
        return maxRenderDuration.getMax();
    }

    /**
     * Returns the average interval of frames (the delta)
     *
     * @return The average interval in nanoseconds
     */
    public double getAverageFrameInterval() {
        return averageFrameInterval.getAverage();
    }

    /**
     * Returns the average duration of frames (update/interpolate/render/flush)
     *
     * @return The average duration in nanoseconds
     */
    public double getAverageFrameDuration() {
        return averageFrameDuration.getAverage();
    }

    /**
     * Returns the max duration of frames (update/interpolate/render/flush) in the last second
     *
     * @return The duration in nanoseconds
     */
    public double getMaxFrameDuration() {
        return maxFrameDuration.getMax();
    }

    /**
     * Returns a {@link ZlibStream} to decompress data
     * @param compressedData The compressed data as a byte array
     * @return A new {@link ZlibStream} instance
     */
    public abstract ZlibStream decompress(byte [] compressedData);

    /**
     * Converts a timestamp to the specified date format
     * @param millis The timestamp (in millis) to convert
     * @param format The date format (e.g. yyyy-MM-dd HH:mm:ss)
     * @return The timestamp in the date format
     */
    public abstract String timestampToDateFormat(long millis, String format);
}


text:
package com.withwiz.jellyfish.context;

import com.withwiz.jellyfish.registry.DefaultServiceRegistry;
import com.withwiz.jellyfish.registry.IServiceRegistry;

/**
 * Default service context class.<BR/>
 * Created by uni4love on 2014.04.02..
 */
public class DefaultServiceContext extends AGenericServiceContext
{
    /**
     * constructor
     */
    public DefaultServiceContext()
    {
    }

    @Override
    protected IServiceRegistry createRegistry() {
        return new DefaultServiceRegistry();
    }
}


text:
package com.centurylink.mdw.util;

import com.centurylink.mdw.common.MdwException;

public class ServiceLocatorException extends MdwException {

    public ServiceLocatorException(String message){
        super(message);
    }

    public ServiceLocatorException(int code, String message){
        super(code, message);

    }

    public ServiceLocatorException(int code, String message, Throwable cause){
        super(code, message, cause);

    }
}


text:
class IWriter{
public:
	virtual void write(char c) = 0;
};
#endif


text:
import {ExternalExpr} from '@angular/compiler';
import ts from 'typescript';

import {ErrorCode, makeDiagnostic, makeRelatedInformation} from '../../diagnostics';
import {AliasingHost, assertSuccessfulReferenceEmit, Reexport, Reference, ReferenceEmitter} from '../../imports';
import {DirectiveMeta, MetadataReader, MetadataRegistry, MetaKind, NgModuleMeta, PipeMeta} from '../../metadata';
import {ClassDeclaration, DeclarationNode} from '../../reflection';
import {identifierOfNode, nodeNameForError} from '../../util/src/typescript';

import {ComponentScopeKind, ComponentScopeReader, ExportScope, LocalModuleScope, RemoteScope, ScopeData} from './api';
import {DtsModuleScopeResolver} from './dependency';
import {getDiagnosticNode, makeNotStandaloneDiagnostic} from './util';

export interface LocalNgModuleData {
  declarations: Reference<ClassDeclaration>[];
  imports: Reference<ClassDeclaration>[];
  exports: Reference<ClassDeclaration>[];
}

/**
 * A registry which collects information about NgModules, Directives, Components, and Pipes which
 * are local (declared in the ts.Program being compiled), and can produce `LocalModuleScope`s
 * which summarize the compilation scope of a component.
 *
 * This class implements the logic of NgModule declarations, imports, and exports and can produce,
 * for a given component, the set of directives and pipes which are "visible" in that component's
 * template.
 *
 * The `LocalModuleScopeRegistry` has two "modes" of operation. During analysis, data for each
 * individual NgModule, Directive, Component, and Pipe is added to the registry. No attempt is made
 * to traverse or validate the NgModule graph (imports, exports, etc). After analysis, one of
 * `getScopeOfModule` or `getScopeForComponent` can be called, which traverses the NgModule graph
 * and applies the NgModule logic to generate a `LocalModuleScope`, the full scope for the given
 * module or component.
 *
 * The `LocalModuleScopeRegistry` is also capable of producing `ts.Diagnostic` errors when Angular
 * semantics are violated.
 */
export class LocalModuleScopeRegistry implements MetadataRegistry, ComponentScopeReader {
  /**
   * Tracks whether the registry has been asked to produce scopes for a module or component. Once
   * this is true, the registry cannot accept registrations of new directives/pipes/modules as it
   * would invalidate the cached scope data.
   */
  private sealed = false;

  /**
   * A map of components from the current compilation unit to the NgModule which declared them.
   *
   * As components and directives are not distinguished at the NgModule level, this map may also
   * contain directives. This doesn't cause any problems but isn't useful as there is no concept of
   * a directive's compilation scope.
   */
  private declarationToModule = new Map<ClassDeclaration, DeclarationData>();

  /**
   * This maps from the directive/pipe class to a map of data for each NgModule that declares the
   * directive/pipe. This data is needed to produce an error for the given class.
   */
  private duplicateDeclarations =
      new Map<ClassDeclaration, Map<ClassDeclaration, DeclarationData>>();

  private moduleToRef = new Map<ClassDeclaration, Reference<ClassDeclaration>>();

  /**
   * A cache of calculated `LocalModuleScope`s for each NgModule declared in the current program.

   */
  private cache = new Map<ClassDeclaration, LocalModuleScope|null>();

  /**
   * Tracks the `RemoteScope` for components requiring "remote scoping".
   *
   * Remote scoping is when the set of directives which apply to a given component is set in the
   * NgModule's file instead of directly on the component def (which is sometimes needed to get
   * around cyclic import issues). This is not used in calculation of `LocalModuleScope`s, but is
   * tracked here for convenience.
   */
  private remoteScoping = new Map<ClassDeclaration, RemoteScope>();

  /**
   * Tracks errors accumulated in the processing of scopes for each module declaration.
   */
  private scopeErrors = new Map<ClassDeclaration, ts.Diagnostic[]>();

  /**
   * Tracks which NgModules have directives/pipes that are declared in more than one module.
   */
  private modulesWithStructuralErrors = new Set<ClassDeclaration>();

  constructor(
      private localReader: MetadataReader, private fullReader: MetadataReader,
      private dependencyScopeReader: DtsModuleScopeResolver, private refEmitter: ReferenceEmitter,
      private aliasingHost: AliasingHost|null) {}

  /**
   * Add an NgModule's data to the registry.
   */
  registerNgModuleMetadata(data: NgModuleMeta): void {
    this.assertCollecting();
    const ngModule = data.ref.node;
    this.moduleToRef.set(data.ref.node, data.ref);
    // Iterate over the module's declarations, and add them to declarationToModule. If duplicates
    // are found, they're instead tracked in duplicateDeclarations.
    for (const decl of data.declarations) {
      this.registerDeclarationOfModule(ngModule, decl, data.rawDeclarations);
    }
  }

  registerDirectiveMetadata(directive: DirectiveMeta): void {}

  registerPipeMetadata(pipe: PipeMeta): void {}

  getScopeForComponent(clazz: ClassDeclaration): LocalModuleScope|null {
    const scope = !this.declarationToModule.has(clazz) ?
        null :
        this.getScopeOfModule(this.declarationToModule.get(clazz)!.ngModule);
    return scope;
  }

  /**
   * If `node` is declared in more than one NgModule (duplicate declaration), then get the
   * `DeclarationData` for each offending declaration.
   *
   * Ordinarily a class is only declared in one NgModule, in which case this function returns
   * `null`.
   */
  getDuplicateDeclarations(node: ClassDeclaration): DeclarationData[]|null {
    if (!this.duplicateDeclarations.has(node)) {
      return null;
    }

    return Array.from(this.duplicateDeclarations.get(node)!.values());
  }

  /**
   * Collects registered data for a module and its directives/pipes and convert it into a full
   * `LocalModuleScope`.
   *
   * This method implements the logic of NgModule imports and exports. It returns the
   * `LocalModuleScope` for the given NgModule if one can be produced, `null` if no scope was ever
   * defined, or the string `'error'` if the scope contained errors.
   */
  getScopeOfModule(clazz: ClassDeclaration): LocalModuleScope|null {
    return this.moduleToRef.has(clazz) ?
        this.getScopeOfModuleReference(this.moduleToRef.get(clazz)!) :
        null;
  }

  /**
   * Retrieves any `ts.Diagnostic`s produced during the calculation of the `LocalModuleScope` for
   * the given NgModule, or `null` if no errors were present.
   */
  getDiagnosticsOfModule(clazz: ClassDeclaration): ts.Diagnostic[]|null {
    // Required to ensure the errors are populated for the given class. If it has been processed
    // before, this will be a no-op due to the scope cache.
    this.getScopeOfModule(clazz);

    if (this.scopeErrors.has(clazz)) {
      return this.scopeErrors.get(clazz)!;
    } else {
      return null;
    }
  }

  private registerDeclarationOfModule(
      ngModule: ClassDeclaration, decl: Reference<ClassDeclaration>,
      rawDeclarations: ts.Expression|null): void {
    const declData: DeclarationData = {
      ngModule,
      ref: decl,
      rawDeclarations,
    };

    // First, check for duplicate declarations of the same directive/pipe.
    if (this.duplicateDeclarations.has(decl.node)) {
      // This directive/pipe has already been identified as being duplicated. Add this module to the
      // map of modules for which a duplicate declaration exists.
      this.duplicateDeclarations.get(decl.node)!.set(ngModule, declData);
    } else if (
        this.declarationToModule.has(decl.node) &&
        this.declarationToModule.get(decl.node)!.ngModule !== ngModule) {
      // This directive/pipe is already registered as declared in another module. Mark it as a
      // duplicate instead.
      const duplicateDeclMap = new Map<ClassDeclaration, DeclarationData>();
      const firstDeclData = this.declarationToModule.get(decl.node)!;

      // Mark both modules as having duplicate declarations.
      this.modulesWithStructuralErrors.add(firstDeclData.ngModule);
      this.modulesWithStructuralErrors.add(ngModule);

      // Being detected as a duplicate means there are two NgModules (for now) which declare this
      // directive/pipe. Add both of them to the duplicate tracking map.
      duplicateDeclMap.set(firstDeclData.ngModule, firstDeclData);
      duplicateDeclMap.set(ngModule, declData);
      this.duplicateDeclarations.set(decl.node, duplicateDeclMap);

      // Remove the directive/pipe from `declarationToModule` as it's a duplicate declaration, and
      // therefore not valid.
      this.declarationToModule.delete(decl.node);
    } else {
      // This is the first declaration of this directive/pipe, so map it.
      this.declarationToModule.set(decl.node, declData);
    }
  }

  /**
   * Implementation of `getScopeOfModule` which accepts a reference to a class.
   */
  private getScopeOfModuleReference(ref: Reference<ClassDeclaration>): LocalModuleScope|null {
    if (this.cache.has(ref.node)) {
      return this.cache.get(ref.node)!;
    }

    // Seal the registry to protect the integrity of the `LocalModuleScope` cache.
    this.sealed = true;

    // `ref` should be an NgModule previously added to the registry. If not, a scope for it
    // cannot be produced.
    const ngModule = this.localReader.getNgModuleMetadata(ref);
    if (ngModule === null) {
      this.cache.set(ref.node, null);
      return null;
    }

    // Errors produced during computation of the scope are recorded here. At the end, if this array
    // isn't empty then `undefined` will be cached and returned to indicate this scope is invalid.
    const diagnostics: ts.Diagnostic[] = [];

    // At this point, the goal is to produce two distinct transitive sets:
    // - the directives and pipes which are visible to components declared in the NgModule.
    // - the directives and pipes which are exported to any NgModules which import this one.

    // Directives and pipes in the compilation scope.
    const compilationDirectives = new Map<DeclarationNode, DirectiveMeta>();
    const compilationPipes = new Map<DeclarationNode, PipeMeta>();

    const declared = new Set<DeclarationNode>();

    // Directives and pipes exported to any importing NgModules.
    const exportDirectives = new Map<DeclarationNode, DirectiveMeta>();
    const exportPipes = new Map<DeclarationNode, PipeMeta>();

    // The algorithm is as follows:
    // 1) Add all of the directives/pipes from each NgModule imported into the current one to the
    //    compilation scope.
    // 2) Add directives/pipes declared in the NgModule to the compilation scope. At this point, the
    //    compilation scope is complete.
    // 3) For each entry in the NgModule's exports:
    //    a) Attempt to resolve it as an NgModule with its own exported directives/pipes. If it is
    //       one, add them to the export scope of this NgModule.
    //    b) Otherwise, it should be a class in the compilation scope of this NgModule. If it is,
    //       add it to the export scope.
    //    c) If it's neither an NgModule nor a directive/pipe in the compilation scope, then this
    //       is an error.

    //
    let isPoisoned = false;
    if (this.modulesWithStructuralErrors.has(ngModule.ref.node)) {
      // If the module contains declarations that are duplicates, then it's considered poisoned.
      isPoisoned = true;
    }

    // 1) process imports.
    for (const decl of ngModule.imports) {
      const importScope = this.getExportedScope(decl, diagnostics, ref.node, 'import');
      if (importScope !== null) {
        if (importScope === 'invalid' || importScope.exported.isPoisoned) {
          // An import was an NgModule but contained errors of its own. Record this as an error too,
          // because this scope is always going to be incorrect if one of its imports could not be
          // read.
          diagnostics.push(invalidTransitiveNgModuleRef(decl, ngModule.rawImports, 'import'));
          isPoisoned = true;

          if (importScope === 'invalid') {
            continue;
          }
        }

        for (const dep of importScope.exported.dependencies) {
          if (dep.kind === MetaKind.Directive) {
            compilationDirectives.set(dep.ref.node, dep);
          } else if (dep.kind === MetaKind.Pipe) {
            compilationPipes.set(dep.ref.node, dep);
          }
        }

        // Successfully processed the import as an NgModule (even if it had errors).
        continue;
      }

      // The import wasn't an NgModule. Maybe it's a standalone entity?
      const directive = this.fullReader.getDirectiveMetadata(decl);
      if (directive !== null) {
        if (directive.isStandalone) {
          compilationDirectives.set(directive.ref.node, directive);
        } else {
          // Error: can't import a non-standalone component/directive.
          diagnostics.push(makeNotStandaloneDiagnostic(
              this, decl, ngModule.rawImports, directive.isComponent ? 'component' : 'directive'));
          isPoisoned = true;
        }

        continue;
      }

      // It wasn't a directive (standalone or otherwise). Maybe a pipe?
      const pipe = this.fullReader.getPipeMetadata(decl);
      if (pipe !== null) {
        if (pipe.isStandalone) {
          compilationPipes.set(pipe.ref.node, pipe);
        } else {
          diagnostics.push(makeNotStandaloneDiagnostic(this, decl, ngModule.rawImports, 'pipe'));
          isPoisoned = true;
        }

        continue;
      }

      // This reference was neither another NgModule nor a standalone entity. Report it as invalid.
      diagnostics.push(invalidRef(decl, ngModule.rawImports, 'import'));
      isPoisoned = true;
    }

    // 2) add declarations.
    for (const decl of ngModule.declarations) {
      const directive = this.localReader.getDirectiveMetadata(decl);
      const pipe = this.localReader.getPipeMetadata(decl);
      if (directive !== null) {
        if (directive.isStandalone) {
          const refType = directive.isComponent ? 'Component' : 'Directive';
          diagnostics.push(makeDiagnostic(
              ErrorCode.NGMODULE_DECLARATION_IS_STANDALONE,
              decl.getOriginForDiagnostics(ngModule.rawDeclarations!),
              `${refType} ${
                  decl.node.name
                      .text} is standalone, and cannot be declared in an NgModule. Did you mean to import it instead?`));
          isPoisoned = true;
          continue;
        }

        compilationDirectives.set(decl.node, {...directive, ref: decl});

        if (directive.isPoisoned) {
          isPoisoned = true;
        }
      } else if (pipe !== null) {
        if (pipe.isStandalone) {
          diagnostics.push(makeDiagnostic(
              ErrorCode.NGMODULE_DECLARATION_IS_STANDALONE,
              decl.getOriginForDiagnostics(ngModule.rawDeclarations!),
              `Pipe ${
                  decl.node.name
                      .text} is standalone, and cannot be declared in an NgModule. Did you mean to import it instead?`));
          isPoisoned = true;
          continue;
        }
        compilationPipes.set(decl.node, {...pipe, ref: decl});
      } else {
        const errorNode = decl.getOriginForDiagnostics(ngModule.rawDeclarations!);
        diagnostics.push(makeDiagnostic(
            ErrorCode.NGMODULE_INVALID_DECLARATION, errorNode,
            `The class '${decl.node.name.text}' is listed in the declarations ` +
                `of the NgModule '${
                    ngModule.ref.node.name
                        .text}', but is not a directive, a component, or a pipe. ` +
                `Either remove it from the NgModule's declarations, or add an appropriate Angular decorator.`,
            [makeRelatedInformation(
                decl.node.name, `'${decl.node.name.text}' is declared here.`)]));
        isPoisoned = true;
        continue;
      }

      declared.add(decl.node);
    }

    // 3) process exports.
    // Exports can contain modules, components, or directives. They're processed differently.
    // Modules are straightforward. Directives and pipes from exported modules are added to the
    // export maps. Directives/pipes are different - they might be exports of declared types or
    // imported types.
    for (const decl of ngModule.exports) {
      // Attempt to resolve decl as an NgModule.
      const exportScope = this.getExportedScope(decl, diagnostics, ref.node, 'export');
      if (exportScope === 'invalid' || (exportScope !== null && exportScope.exported.isPoisoned)) {
        // An export was an NgModule but contained errors of its own. Record this as an error too,
        // because this scope is always going to be incorrect if one of its exports could not be
        // read.
        diagnostics.push(invalidTransitiveNgModuleRef(decl, ngModule.rawExports, 'export'));
        isPoisoned = true;

        if (exportScope === 'invalid') {
          continue;
        }
      } else if (exportScope !== null) {
        // decl is an NgModule.
        for (const dep of exportScope.exported.dependencies) {
          if (dep.kind == MetaKind.Directive) {
            exportDirectives.set(dep.ref.node, dep);
          } else if (dep.kind === MetaKind.Pipe) {
            exportPipes.set(dep.ref.node, dep);
          }
        }
      } else if (compilationDirectives.has(decl.node)) {
        // decl is a directive or component in the compilation scope of this NgModule.
        const directive = compilationDirectives.get(decl.node)!;
        exportDirectives.set(decl.node, directive);
      } else if (compilationPipes.has(decl.node)) {
        // decl is a pipe in the compilation scope of this NgModule.
        const pipe = compilationPipes.get(decl.node)!;
        exportPipes.set(decl.node, pipe);
      } else {
        // decl is an unknown export.
        const dirMeta = this.fullReader.getDirectiveMetadata(decl);
        const pipeMeta = this.fullReader.getPipeMetadata(decl);
        if (dirMeta !== null || pipeMeta !== null) {
          const isStandalone = dirMeta !== null ? dirMeta.isStandalone : pipeMeta!.isStandalone;
          diagnostics.push(invalidReexport(decl, ngModule.rawExports, isStandalone));
        } else {
          diagnostics.push(invalidRef(decl, ngModule.rawExports, 'export'));
        }
        isPoisoned = true;
        continue;
      }
    }

    const exported: ScopeData = {
      dependencies: [...exportDirectives.values(), ...exportPipes.values()],
      isPoisoned,
    };

    const reexports =
        this.getReexports(ngModule, ref, declared, exported.dependencies, diagnostics);

    // Finally, produce the `LocalModuleScope` with both the compilation and export scopes.
    const scope: LocalModuleScope = {
      kind: ComponentScopeKind.NgModule,
      ngModule: ngModule.ref.node,
      compilation: {
        dependencies: [...compilationDirectives.values(), ...compilationPipes.values()],
        isPoisoned,
      },
      exported,
      reexports,
      schemas: ngModule.schemas,
    };

    // Check if this scope had any errors during production.
    if (diagnostics.length > 0) {
      // Save the errors for retrieval.
      this.scopeErrors.set(ref.node, diagnostics);

      // Mark this module as being tainted.
      this.modulesWithStructuralErrors.add(ref.node);
    }

    this.cache.set(ref.node, scope);
    return scope;
  }

  /**
   * Check whether a component requires remote scoping.
   */
  getRemoteScope(node: ClassDeclaration): RemoteScope|null {
    return this.remoteScoping.has(node) ? this.remoteScoping.get(node)! : null;
  }

  /**
   * Set a component as requiring remote scoping, with the given directives and pipes to be
   * registered remotely.
   */
  setComponentRemoteScope(node: ClassDeclaration, directives: Reference[], pipes: Reference[]):
      void {
    this.remoteScoping.set(node, {directives, pipes});
  }

  /**
   * Look up the `ExportScope` of a given `Reference` to an NgModule.
   *
   * The NgModule in question may be declared locally in the current ts.Program, or it may be
   * declared in a .d.ts file.
   *
   * @returns `null` if no scope could be found, or `'invalid'` if the `Reference` is not a valid
   *     NgModule.
   *
   * May also contribute diagnostics of its own by adding to the given `diagnostics`
   * array parameter.
   */
  private getExportedScope(
      ref: Reference<ClassDeclaration>, diagnostics: ts.Diagnostic[],
      ownerForErrors: DeclarationNode, type: 'import'|'export'): ExportScope|null|'invalid' {
    if (ref.node.getSourceFile().isDeclarationFile) {
      // The NgModule is declared in a .d.ts file. Resolve it with the `DependencyScopeReader`.
      if (!ts.isClassDeclaration(ref.node)) {
        // The NgModule is in a .d.ts file but is not declared as a ts.ClassDeclaration. This is an
        // error in the .d.ts metadata.
        const code = type === 'import' ? ErrorCode.NGMODULE_INVALID_IMPORT :
                                         ErrorCode.NGMODULE_INVALID_EXPORT;
        diagnostics.push(makeDiagnostic(
            code, identifierOfNode(ref.node) || ref.node,
            `Appears in the NgModule.${type}s of ${
                nodeNameForError(ownerForErrors)}, but could not be resolved to an NgModule`));
        return 'invalid';
      }
      return this.dependencyScopeReader.resolve(ref);
    } else {
      // The NgModule is declared locally in the current program. Resolve it from the registry.
      return this.getScopeOfModuleReference(ref);
    }
  }

  private getReexports(
      ngModule: NgModuleMeta, ref: Reference<ClassDeclaration>, declared: Set<DeclarationNode>,
      exported: Array<DirectiveMeta|PipeMeta>, diagnostics: ts.Diagnostic[]): Reexport[]|null {
    let reexports: Reexport[]|null = null;
    const sourceFile = ref.node.getSourceFile();
    if (this.aliasingHost === null) {
      return null;
    }
    reexports = [];
    // Track re-exports by symbol name, to produce diagnostics if two alias re-exports would share
    // the same name.
    const reexportMap = new Map<string, Reference<ClassDeclaration>>();
    // Alias ngModuleRef added for readability below.
    const ngModuleRef = ref;
    const addReexport = (exportRef: Reference<ClassDeclaration>) => {
      if (exportRef.node.getSourceFile() === sourceFile) {
        return;
      }
      const isReExport = !declared.has(exportRef.node);
      const exportName = this.aliasingHost!.maybeAliasSymbolAs(
          exportRef, sourceFile, ngModule.ref.node.name.text, isReExport);
      if (exportName === null) {
        return;
      }
      if (!reexportMap.has(exportName)) {
        if (exportRef.alias && exportRef.alias instanceof ExternalExpr) {
          reexports!.push({
            fromModule: exportRef.alias.value.moduleName!,
            symbolName: exportRef.alias.value.name!,
            asAlias: exportName,
          });
        } else {
          const emittedRef = this.refEmitter.emit(exportRef.cloneWithNoIdentifiers(), sourceFile);
          assertSuccessfulReferenceEmit(emittedRef, ngModuleRef.node.name, 'class');
          const expr = emittedRef.expression;
          if (!(expr instanceof ExternalExpr) || expr.value.moduleName === null ||
              expr.value.name === null) {
            throw new Error('Expected ExternalExpr');
          }
          reexports!.push({
            fromModule: expr.value.moduleName,
            symbolName: expr.value.name,
            asAlias: exportName,
          });
        }
        reexportMap.set(exportName, exportRef);
      } else {
        // Another re-export already used this name. Produce a diagnostic.
        const prevRef = reexportMap.get(exportName)!;
        diagnostics.push(reexportCollision(ngModuleRef.node, prevRef, exportRef));
      }
    };
    for (const {ref} of exported) {
      addReexport(ref);
    }
    return reexports;
  }

  private assertCollecting(): void {
    if (this.sealed) {
      throw new Error(`Assertion: LocalModuleScopeRegistry is not COLLECTING`);
    }
  }
}

/**
 * Produce a `ts.Diagnostic` for an invalid import or export from an NgModule.
 */
function invalidRef(
    decl: Reference<ClassDeclaration>, rawExpr: ts.Expression|null,
    type: 'import'|'export'): ts.Diagnostic {
  const code =
      type === 'import' ? ErrorCode.NGMODULE_INVALID_IMPORT : ErrorCode.NGMODULE_INVALID_EXPORT;
  const resolveTarget = type === 'import' ? 'NgModule' : 'NgModule, Component, Directive, or Pipe';
  const message = `'${decl.node.name.text}' does not appear to be an ${resolveTarget} class.`;
  const library = decl.ownedByModuleGuess !== null ? ` (${decl.ownedByModuleGuess})` : '';
  const sf = decl.node.getSourceFile();

  let relatedMessage: string;

  // Provide extra context to the error for the user.
  if (!sf.isDeclarationFile) {
    // This is a file in the user's program. Highlight the class as undecorated.
    const annotationType = type === 'import' ? '@NgModule' : 'Angular';
    relatedMessage = `Is it missing an ${annotationType} annotation?`;
  } else if (sf.fileName.indexOf('node_modules') !== -1) {
    // This file comes from a third-party library in node_modules.
    relatedMessage =
        `This likely means that the library${library} which declares ${decl.debugName} has not ` +
        'been processed correctly by ngcc, or is not compatible with Angular Ivy. Check if a ' +
        'newer version of the library is available, and update if so. Also consider checking ' +
        'with the library\'s authors to see if the library is expected to be compatible with Ivy.';
  } else {
    // This is a monorepo style local dependency. Unfortunately these are too different to really
    // offer much more advice than this.
    relatedMessage = `This likely means that the dependency${library} which declares ${
        decl.debugName} has not been processed correctly by ngcc.`;
  }

  return makeDiagnostic(
      code, getDiagnosticNode(decl, rawExpr), message,
      [makeRelatedInformation(decl.node.name, relatedMessage)]);
}

/**
 * Produce a `ts.Diagnostic` for an import or export which itself has errors.
 */
function invalidTransitiveNgModuleRef(
    decl: Reference<ClassDeclaration>, rawExpr: ts.Expression|null,
    type: 'import'|'export'): ts.Diagnostic {
  const code =
      type === 'import' ? ErrorCode.NGMODULE_INVALID_IMPORT : ErrorCode.NGMODULE_INVALID_EXPORT;
  return makeDiagnostic(
      code, getDiagnosticNode(decl, rawExpr),
      `This ${type} contains errors, which may affect components that depend on this NgModule.`);
}

/**
 * Produce a `ts.Diagnostic` for an exported directive or pipe which was not declared or imported
 * by the NgModule in question.
 */
function invalidReexport(
    decl: Reference<ClassDeclaration>, rawExpr: ts.Expression|null,
    isStandalone: boolean): ts.Diagnostic {
  // The root error is the same here - this export is not valid. Give a helpful error message based
  // on the specific circumstance.
  let message = `Can't be exported from this NgModule, as `;
  if (isStandalone) {
    // Standalone types need to be imported into an NgModule before they can be re-exported.
    message += 'it must be imported first';
  } else if (decl.node.getSourceFile().isDeclarationFile) {
    // Non-standalone types can be re-exported, but need to be imported into the NgModule first.
    // This requires importing their own NgModule.
    message += 'it must be imported via its NgModule first';
  } else {
    // Local non-standalone types must either be declared directly by this NgModule, or imported as
    // above.
    message +=
        'it must be either declared by this NgModule, or imported here via its NgModule first';
  }
  return makeDiagnostic(
      ErrorCode.NGMODULE_INVALID_REEXPORT, getDiagnosticNode(decl, rawExpr), message);
}

/**
 * Produce a `ts.Diagnostic` for a collision in re-export names between two directives/pipes.
 */
function reexportCollision(
    module: ClassDeclaration, refA: Reference<ClassDeclaration>,
    refB: Reference<ClassDeclaration>): ts.Diagnostic {
  const childMessageText = `This directive/pipe is part of the exports of '${
      module.name.text}' and shares the same name as another exported directive/pipe.`;
  return makeDiagnostic(
      ErrorCode.NGMODULE_REEXPORT_NAME_COLLISION, module.name,
      `
    There was a name collision between two classes named '${
          refA.node.name.text}', which are both part of the exports of '${module.name.text}'.

    Angular generates re-exports of an NgModule's exported directives/pipes from the module's source file in certain cases, using the declared name of the class. If two classes of the same name are exported, this automatic naming does not work.

    To fix this problem please re-export one or both classes directly from this file.
  `.trim(),
      [
        makeRelatedInformation(refA.node.name, childMessageText),
        makeRelatedInformation(refB.node.name, childMessageText),
      ]);
}

export interface DeclarationData {
  ngModule: ClassDeclaration;
  ref: Reference;
  rawDeclarations: ts.Expression|null;
}


text:
Install Basic Networking Tools and Utilities for Debian, Ubuntu, CentOS, and Redhat.

## lsof

Lsof is a Unix-specific diagnostic tool. Its name stands for LiSt Open Files, and it does just that. It lists information about any files that are open, by processes currently running on the system.

## iptables

Administration tools for packet filtering and NAT. These are the user-space administration tools for the Linux kernel's netfilter and iptables. netfilter and iptables provide a framework for stateful and stateless packet filtering, network and port address translation, and other IP packet manipulation. The framework is the successor to ipchains.

## jwhois

Improved Caching Whois client
GNU jwhois is an Internet Whois client that queries hosts for information according to RFC 954 - NICNAME/WHOIS. JWHOIS is configured via a configuration file that contains information about all known Whois servers. Upon execution, the host to query is selected based on the information in the configuration file.

## whois

This is a new whois (RFC 3912) client rewritten from scratch. It is inspired from and compatible with the usual BSD and RIPE whois(1) programs. It is intelligent and can automatically select the appropriate whois server for most queries.

## curl

Get a file from an HTTP, HTTPS or FTP server. Curl is a client to get files from servers using any of the supported protocols. The command is designed to work without user interaction or any kind of interactivity.

## wget

Wget is a network utility to retrieve files from the Web using http(s) and ftp, the two most widely used Internet protocols.
It works non-interactively, so it will work in the background, after having logged off.
The program supports recursive retrieval of web-authoring pages as well as ftp sites -- you can use wget to make mirrors of archives and home pages or to travel the Web like a WWW robot.

## rsync

Rsync is a program that allows files to be copied to and from remote machines in much the same way as rcp.  It has many more options than rcp, and uses the rsync remote-update protocol to greatly speed up file transfers when the destination file already exists.

## jnettop

View hosts/ports taking up the most network traffic jNettop captures traffic coming across the host it is running on and displays streams sorted by bandwidth they use. Result is a nice listing of communication on network by host and port, how many bytes went through this transport and the bandwidth it is consuming.

## nmap

Nmap is a utility for network exploration or security auditing. It supports ping scanning (determine which hosts are up), many port scanning techniques, version detection (determine service protocols and application versions listening behind ports), and TCP/IP fingerprinting (remote host OS or device identification). Nmap also offers flexible target and port specification, decoy/stealth scanning, sunRPC scanning, and more. Most Unix and Windows platforms are supported in both GUI and commandline modes. Several popular handheld devices are also supported, including the Sharp Zaurus and the iPAQ.

## traceroute

Traceroute tracks the route packets taken from an IP network on their way to a given host. It utilizes the IP protocol's time to live (TTL) field and attempts to elicit an ICMP TIME_EXCEEDED response from each gateway along the path to the host.

## ethtool

Display or change Ethernet device settings.

## iproute

Networking and traffic control tools.

## iputils-ping

Tools to test the reachability of network hosts.

## netcat-openbsd

TCP/IP swiss army knife.

## tcpdump

A powerful tool for network monitoring and data acquisition.

## elinks

Advanced text-mode WWW browser.

## lynx

Text-mode WWW Browser.

## Thanks:

  - Tim Smith [tim.smith[AT]webtrends.com]


text:
var re = /foo.bar/;

assertTrue(!!"foo*bar".match(re));
assertTrue(!!"..foo*bar".match(re));

var plain = /foobar/;

assertTrue(!!"foobar".match(plain));
assertTrue(!!"..foobar".match(plain));

var sticky = /foo.bar/y;

assertTrue(!!"foo*bar".match(sticky));
assertEquals(7, sticky.lastIndex);
assertFalse(!!"..foo*bar".match(sticky));

var stickyplain = /foobar/y;

assertTrue(!!"foobar".match(stickyplain));
assertEquals(6, stickyplain.lastIndex);
assertFalse(!!"..foobar".match(stickyplain));

var global = /foo.bar/g;

assertTrue(global.test("foo*bar"));
assertFalse(global.test("..foo*bar"));
global.lastIndex = 0;
assertTrue(global.test("..foo*bar"));

var plainglobal = /foobar/g;

assertTrue(plainglobal.test("foobar"));
assertFalse(plainglobal.test("foobar"));
plainglobal.lastIndex = 0;
assertTrue(plainglobal.test("foobar"));

var stickyglobal = /foo.bar/gy;

assertTrue(stickyglobal.test("foo*bar"));
assertEquals(7, stickyglobal.lastIndex);
assertFalse(stickyglobal.test("..foo*bar"));
stickyglobal.lastIndex = 0;
assertFalse(stickyglobal.test("..foo*bar"));
stickyglobal.lastIndex = 2;
assertTrue(stickyglobal.test("..foo*bar"));
assertEquals(9, stickyglobal.lastIndex);

var stickyplainglobal = /foobar/yg;
assertTrue(stickyplainglobal.sticky);
stickyplainglobal.sticky = false;

assertTrue(stickyplainglobal.test("foobar"));
assertEquals(6, stickyplainglobal.lastIndex);
assertFalse(stickyplainglobal.test("..foobar"));
stickyplainglobal.lastIndex = 0;
assertFalse(stickyplainglobal.test("..foobar"));
stickyplainglobal.lastIndex = 2;
assertTrue(stickyplainglobal.test("..foobar"));
assertEquals(8, stickyplainglobal.lastIndex);

assertEquals("/foo.bar/gy", "" + stickyglobal);
assertEquals("/foo.bar/g", "" + global);

assertTrue(stickyglobal.sticky);
stickyglobal.sticky = false;
assertTrue(stickyglobal.sticky);

var stickyglobal2 = new RegExp("foo.bar", "gy");
assertTrue(stickyglobal2.test("foo*bar"));
assertEquals(7, stickyglobal2.lastIndex);
assertFalse(stickyglobal2.test("..foo*bar"));
stickyglobal2.lastIndex = 0;
assertFalse(stickyglobal2.test("..foo*bar"));
stickyglobal2.lastIndex = 2;
assertTrue(stickyglobal2.test("..foo*bar"));
assertEquals(9, stickyglobal2.lastIndex);

assertEquals("/foo.bar/gy", "" + stickyglobal2);

assertTrue(stickyglobal2.sticky);
stickyglobal2.sticky = false;
assertTrue(stickyglobal2.sticky);

sticky.lastIndex = -1; // Causes sticky regexp to fail fast
assertFalse(sticky.test("..foo.bar"));
assertEquals(0, sticky.lastIndex);

sticky.lastIndex = -1; // Causes sticky regexp to fail fast
assertFalse(!!sticky.exec("..foo.bar"));
assertEquals(0, sticky.lastIndex);

// ES6 draft says: Even when the y flag is used with a pattern, ^ always
// matches only at the beginning of Input, or (if Multiline is true) at the
// beginning of a line.
var hat = /^foo/y;
hat.lastIndex = 2;
assertFalse(hat.test("..foo"));

var mhat = /^foo/my;
mhat.lastIndex = 2;
assertFalse(mhat.test("..foo"));
mhat.lastIndex = 2;
assertTrue(mhat.test(".\nfoo"));


text:
/*
 * Project: B52 reader (https://github.com/FreekDB/b52-reader).
 * License: Apache version 2 (https://www.apache.org/licenses/LICENSE-2.0).
 */

package nl.xs4all.home.freekdb.b52reader.gui;

import com.google.common.collect.ImmutableSet;

import java.awt.Component;
import java.awt.Container;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.IntStream;

import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.text.AbstractDocument;
import javax.swing.text.BadLocationException;

import nl.xs4all.home.freekdb.b52reader.TestUtilities;
import nl.xs4all.home.freekdb.b52reader.datamodel.Article;
import nl.xs4all.home.freekdb.b52reader.general.Configuration;
import nl.xs4all.home.freekdb.b52reader.main.MainCallbacks;

import org.apache.commons.lang3.reflect.FieldUtils;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

import static nl.xs4all.home.freekdb.b52reader.gui.MainGuiTest.FilterTestType.CHANGE_TEXT;
import static nl.xs4all.home.freekdb.b52reader.gui.MainGuiTest.FilterTestType.INSERT_TEXT;
import static nl.xs4all.home.freekdb.b52reader.gui.MainGuiTest.FilterTestType.NO_MATCHES;
import static nl.xs4all.home.freekdb.b52reader.gui.MainGuiTest.FilterTestType.REMOVE_TEXT;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

/**
 * Unit tests for the {@link MainGui} class.
 */
public class MainGuiTest {
    private JFrame mockFrame;
    private Container mockContentPane;
    private ManyBrowsersPanel mockManyBrowsersPanel;
    private MainCallbacks mockMainCallbacks;
    private Configuration mockConfiguration;

    private WindowListener windowListener;
    private boolean shutdownApplicationWasCalled;

    @Before
    public void setUp() throws IllegalAccessException {
        Set<String> urlsWithBrowsers = ImmutableSet.of("u2", "u4", "u6");

        mockFrame = Mockito.mock(JFrame.class);
        mockContentPane = new Container();
        mockManyBrowsersPanel = Mockito.mock(ManyBrowsersPanel.class);
        mockMainCallbacks = Mockito.mock(MainCallbacks.class);
        mockConfiguration = Mockito.mock(Configuration.class);

        Mockito.when(mockFrame.getContentPane()).thenReturn(mockContentPane);

        Mockito.doAnswer(invocationOnMock -> windowListener = invocationOnMock.getArgument(0))
            .when(mockFrame).addWindowListener(Mockito.any(WindowListener.class));

        Mockito.when(mockManyBrowsersPanel.hasBrowserForUrl(Mockito.anyString()))
            .thenAnswer(invocationOnMock -> urlsWithBrowsers.contains(invocationOnMock.<String>getArgument(0)));

        // Initialize the private Container.component field to prevent a null pointer exception later.
        FieldUtils.writeField(mockManyBrowsersPanel, "component", new ArrayList<>(), true);

        Mockito.when(mockMainCallbacks.shutdownApplication(Mockito.anyInt(), Mockito.any()))
            .thenAnswer(invocationOnMock -> {
                shutdownApplicationWasCalled = true;

                return true;
            });

        Mockito.when(mockConfiguration.getBackgroundBrowserMaxCount()).thenReturn(2);
        Mockito.when(mockConfiguration.getBackgroundTimerInitialDelay()).thenReturn(2000);
        Mockito.when(mockConfiguration.getBackgroundTimerDelay()).thenReturn(600);
        Mockito.when(mockConfiguration.getFetchedValue()).thenReturn("fetched");
    }

    @Test
    public void testInitializeBackgroundBrowsersPanel() {
        MainGui mainGui = new MainGui(mockManyBrowsersPanel);
        mainGui.setMainCallbacks(mockMainCallbacks);

        mainGui.initializeBackgroundBrowsersPanel(mockFrame, mockConfiguration);

        assertEquals(1, mockContentPane.getComponentCount());
        assertFalse(mockContentPane.getComponent(0).isVisible());

        assertNotNull(mainGui.getBackgroundBrowsersPanel());
        assertEquals(0, mainGui.getBackgroundBrowsersPanel().getComponentCount());
    }

    @Test
    public void testInitializeGuiSpanTable() throws InvocationTargetException, InterruptedException {
        MainGui mainGui = new MainGui(mockManyBrowsersPanel);
        mainGui.setMainCallbacks(mockMainCallbacks);

        Mockito.when(mockConfiguration.useSpanTable()).thenReturn(true);

        mainGui.initializeBackgroundBrowsersPanel(mockFrame, mockConfiguration);
        mainGui.initializeGui(TestUtilities.getSixTestArticles());

        waitForGuiTasks();

        // Make sure there is enough time for handleBackgroundTasks to be called.
        Thread.sleep(2000);

        assertEquals(3, mockContentPane.getComponentCount());
    }

    @Test
    public void testInitializeGuiCustomRendererTable() throws InvocationTargetException, InterruptedException {
        MainGui mainGui = new MainGui(mockManyBrowsersPanel);
        mainGui.setMainCallbacks(mockMainCallbacks);

        mainGui.initializeBackgroundBrowsersPanel(mockFrame, mockConfiguration);
        mainGui.initializeGui(new ArrayList<>());

        waitForGuiTasks();

        assertEquals(3, mockContentPane.getComponentCount());
    }

    @Test
    public void testFilterInsert() throws BadLocationException, InterruptedException, ReflectiveOperationException {
        testFilter(INSERT_TEXT);
    }

    @Test
    public void testFilterRemove() throws BadLocationException, InterruptedException, ReflectiveOperationException {
        testFilter(REMOVE_TEXT);
    }

    @Test
    public void testFilterChange() throws BadLocationException, InterruptedException, ReflectiveOperationException {
        testFilter(CHANGE_TEXT);
    }

    @Test
    public void testFilterNoMatches() throws BadLocationException, InterruptedException, ReflectiveOperationException {
        testFilter(NO_MATCHES);
    }

    @Test
    public void testClickWithoutSelectedRow() throws InterruptedException, InvocationTargetException {
        testClickInTable(false, false, true, false, 120);
    }

    @Test
    public void testClickInSpanTable() throws InterruptedException, InvocationTargetException {
        // Note: the x coordinates for the mouse events are related to MainGui.setTableColumnWidths.

        testClickInTable(false, false, true, true, 120);
        testClickInTable(true, false, true, true, 120);

        testClickInTable(false, false, true, true, 220);
        testClickInTable(false, true, true, true, 220);
    }

    @Test
    public void testClickInCustomRendererTable() throws InterruptedException, InvocationTargetException {
        // Note: the x coordinates for the mouse events are related to ArticleTableCellRenderer and
        // MainGui.getColumnIndexFromClick.

        testClickInTable(false, false, false, true, 20);
        testClickInTable(true, false, false, true, 20);

        testClickInTable(false, false, false, true, 40);
        testClickInTable(false, true, false, true, 40);

        testClickInTable(false, true, false, true, 80);
    }

    @Test
    public void testFetchedArticlesBrowserMaxCount0() throws InvocationTargetException, InterruptedException {
        testFetchedArticles(true);
    }

    @Test
    public void testFetchedArticlesBrowserMaxCount2() throws InvocationTargetException, InterruptedException {
        testFetchedArticles(false);
    }

    private void testFetchedArticles(boolean zeroBackgroundBrowserMaxCount)
        throws InterruptedException, InvocationTargetException {
        String fetchedValue = "fetched";

        if (zeroBackgroundBrowserMaxCount) {
            Mockito.when(mockConfiguration.getBackgroundBrowserMaxCount()).thenReturn(0);
        }

        MainGui mainGui = new MainGui(mockManyBrowsersPanel);
        mainGui.setMainCallbacks(mockMainCallbacks);

        Mockito.when(mockConfiguration.useSpanTable()).thenReturn(true);
        Mockito.when(mockConfiguration.getFetchedValue()).thenReturn(fetchedValue);

        mainGui.initializeBackgroundBrowsersPanel(mockFrame, mockConfiguration);
        mainGui.initializeGui(TestUtilities.getSixTestArticles());

        waitForGuiTasks();

        JTable table = (JTable) findComponent(mockContentPane, JTable.class);
        assertNotNull(table);

        assertEquals(fetchedValue, table.getModel().getValueAt(2, 0));
    }

    @Test
    public void testShutdownApplication() throws InterruptedException, InvocationTargetException {
        MainGui mainGui = new MainGui(mockManyBrowsersPanel);
        mainGui.setMainCallbacks(mockMainCallbacks);

        mainGui.initializeBackgroundBrowsersPanel(mockFrame, mockConfiguration);
        mainGui.initializeGui(new ArrayList<>());

        waitForGuiTasks();

        windowListener.windowClosing(new WindowEvent(mockFrame, WindowEvent.WINDOW_CLOSING));

        assertTrue(shutdownApplicationWasCalled);
    }

    private void testFilter(FilterTestType testType) throws BadLocationException, InterruptedException,
                                                            ReflectiveOperationException {
        MainGui mainGui = new MainGui(mockManyBrowsersPanel);
        mainGui.setMainCallbacks(mockMainCallbacks);

        Mockito.when(mockConfiguration.useSpanTable()).thenReturn(testType == CHANGE_TEXT);

        mainGui.initializeBackgroundBrowsersPanel(mockFrame, mockConfiguration);
        mainGui.initializeGui(TestUtilities.getSixTestArticles());

        waitForGuiTasks();

        JTable table = (JTable) findComponent(mockContentPane, JTable.class);
        assertNotNull(table);

        assertEquals(mockConfiguration.useSpanTable() ? 12 : 6, table.getRowCount());

        JTextField filterTextField = (JTextField) findComponent(mockContentPane, JTextField.class);
        assertNotNull(filterTextField);
        AbstractDocument document = (AbstractDocument) filterTextField.getDocument();

        document.insertString(0, "title:title1", null);

        assertEquals(mockConfiguration.useSpanTable() ? 2 : 1, table.getRowCount());

        if (testType == REMOVE_TEXT) {
            document.remove(0, document.getLength());
        } else if (testType == CHANGE_TEXT) {
            document.replace(6, 6, "title2", null);

            // Since change is implemented as remove and insert, the fireChangedUpdate method is called with reflection.
            AbstractDocument.DefaultDocumentEvent mockEvent = Mockito.mock(AbstractDocument.DefaultDocumentEvent.class);
            Method method = AbstractDocument.class.getDeclaredMethod("fireChangedUpdate", DocumentEvent.class);
            method.setAccessible(true);
            method.invoke(document, mockEvent);
        } else if (testType == NO_MATCHES) {
            document.insertString(document.getLength(), "-some-nonsense", null);
        }

        checkArticlesInGui(testType, mainGui, table.getRowCount());
    }

    private void checkArticlesInGui(FilterTestType testType, MainGui mainGui, int tableRowCount)
        throws IllegalAccessException {
        int expectedRowCount = mockConfiguration.useSpanTable() ? 2 : 1;

        if (testType == NO_MATCHES) {
            expectedRowCount = 0;
        } else if (testType == REMOVE_TEXT) {
            expectedRowCount = 5;
        }

        assertEquals(expectedRowCount, tableRowCount);

        Object filteredArticlesField = FieldUtils.readField(mainGui, "filteredArticles", true);

        assertTrue(filteredArticlesField instanceof List);
        List filteredArticles = (List) filteredArticlesField;

        if (testType == INSERT_TEXT) {
            assertEquals("u1", ((Article) filteredArticles.get(0)).getUrl());
        } else if (testType == CHANGE_TEXT) {
            assertEquals("u2", ((Article) filteredArticles.get(0)).getUrl());
        } else if (testType == REMOVE_TEXT) {
            IntStream.range(0, filteredArticles.size())
                .forEach(index -> {
                    // Test article 3 (with index 2) is archived and should be filtered out: u1, u2, u4, u5, and u6.
                    String expectedUrl = "u" + (index + (index < 2 ? 1 : 2));
                    assertEquals(expectedUrl, ((Article) filteredArticles.get(index)).getUrl());
                });
        }
    }

    // Wait for other tasks on the event dispatch thread to be completed (like MainGui.finishGuiInitialization).
    private void waitForGuiTasks() throws InterruptedException, InvocationTargetException {
        SwingUtilities.invokeAndWait(() -> mockFrame.getTitle());
    }

    private Component findComponent(Container parent, Class<?> searchClass) {
        Component result = null;

        int componentIndex = 0;
        while (componentIndex < parent.getComponentCount() && result == null) {
            Component component = parent.getComponent(componentIndex);

            if (searchClass.isInstance(component)) {
                result = component;
            } else if (component instanceof Container) {
                result = findComponent((Container) component, searchClass);
            }

            componentIndex++;
        }

        return result;
    }

    private void testClickInTable(boolean firstStarred, boolean firstRead, boolean spanTable, boolean selectRow,
                                  int xMouseEvent)
        throws InterruptedException, InvocationTargetException {
        List<Article> testArticles = TestUtilities.getSixTestArticles();
        testArticles.get(0).setStarred(firstStarred);
        testArticles.get(0).setRead(firstRead);

        MainGui mainGui = new MainGui(mockManyBrowsersPanel);
        mainGui.setMainCallbacks(mockMainCallbacks);

        Mockito.when(mockConfiguration.useSpanTable()).thenReturn(spanTable);

        mainGui.initializeBackgroundBrowsersPanel(mockFrame, mockConfiguration);
        mainGui.initializeGui(testArticles);

        waitForGuiTasks();

        JTable table = (JTable) findComponent(mockContentPane, JTable.class);
        assertNotNull(table);

        if (selectRow) {
            table.getSelectionModel().setValueIsAdjusting(true);
            table.getSelectionModel().setSelectionInterval(1, 1);
            table.getSelectionModel().setValueIsAdjusting(true);
            table.getSelectionModel().setSelectionInterval(0, 0);
        } else {
            table.getSelectionModel().setValueIsAdjusting(true);
            table.clearSelection();
        }

        MouseEvent mouseEvent = new MouseEvent(table, 123456, new Date().getTime(), 0, xMouseEvent, 10,
                                               1, false);

        for (MouseListener mouseListener : table.getMouseListeners()) {
            mouseListener.mouseClicked(mouseEvent);
        }
    }

    enum FilterTestType {
        INSERT_TEXT,
        REMOVE_TEXT,
        CHANGE_TEXT,
        NO_MATCHES
    }
}


text:
<!DOCTYPE html>
<html>
<body>
<script src="../../../resources/testharness.js"></script>
<script src="../../../resources/testharnessreport.js"></script>
<script>

var test = async_test("Test that screen.orientation.lock() throws when the input isn't valid.");

function onOrientationChangeEvent(ev) {
    assert_unreached('Unexpected orientation change');
}

window.screen.orientation.addEventListener('change', test.step_func(onOrientationChangeEvent));

test.step(function() {
    assert_equals(screen.orientation.type, 'portrait-primary');
    assert_throws(new TypeError(), function() {
        screen.orientation.lock('invalid-orientation');
    });

    assert_equals(screen.orientation.type, 'portrait-primary');
    assert_throws(new TypeError(), function() {
        screen.orientation.lock(null);
    });

    assert_equals(screen.orientation.type, 'portrait-primary');
    assert_throws(new TypeError(), function() {
        screen.orientation.lock(undefined);
    });

    assert_equals(screen.orientation.type, 'portrait-primary');
    assert_throws(new TypeError(), function() {
        screen.orientation.lock(undefined);
    });

    assert_equals(screen.orientation.type, 'portrait-primary');
    assert_throws(new TypeError(), function() {
        screen.orientation.lock(123);
    });

    assert_equals(screen.orientation.type, 'portrait-primary');
    assert_throws(new TypeError(), function() {
        screen.orientation.lock(window);
    });

    assert_equals(screen.orientation.type, 'portrait-primary');
    assert_throws(new TypeError(), function() {
        screen.orientation.lock(['portrait-primary']);
    });

    assert_equals(screen.orientation.type, 'portrait-primary');
    assert_throws(new TypeError(), function() {
        screen.orientation.lock(['portrait-primary', 'landscape-primary']);
    });

    assert_equals(screen.orientation.type, 'portrait-primary');
    assert_throws(new TypeError(), function() {
        screen.orientation.lock();
    });
});

// Finish asynchronously to give events a chance to fire.
setTimeout(test.step_func(function() {
    assert_equals(screen.orientation.type, 'portrait-primary');
    screen.orientation.unlock();
    test.done();
}));

</script>
</body>
</html>


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

class Upload extends CI_Controller {

	public function __construct(){
	   parent::__construct();
	   $this->load->helper(array('url', 'form'));
	}

	public function uploadify(){
		$config['upload_path'] = "./uploads/temp/";
		$config['allowed_types'] = 'gif|jpg|png|jpeg';
		$config['max_size'] = 0;
		$this->load->library('upload', $config);

		if (!$this->upload->do_upload("userfile")){
			$response = $this->upload->display_errors();
		}else{
			$response = $this->upload->data();
		}
		$this->output->set_content_type('application/json')->set_output(json_encode($response));
	}
}