text:
package javaguide.ehcache.qualified;

// #qualified
import javax.inject.Inject;
import play.cache.*;
import play.mvc.*;

public class Application extends Controller {

  @Inject
  @NamedCache("session-cache")
  SyncCacheApi cache;

  // ...
}
// #qualified

redpajama_set_name: RedPajamaGithub


text:
package testpkg;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import org.slf4j.event.Level;
import java.net.*;

public class Main {
    public static void main(String[] args) {
        final Logger logger1 = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
        final Logger logger2 = LoggerFactory.getLogger("testpkg.Main");
        final Marker mk1 = MarkerFactory.getMarker("MARK1");
        final Marker mk2 = MarkerFactory.getMarker("MARK2");

        logger1.trace(mk1, "slf4j + logback-classic, {}, {}, {}", 100, Level.TRACE, new InetSocketAddress("localhost", 8080));
        logger1.debug(mk1, "slf4j + logback-classic, {}, {}, {}", 200, Level.DEBUG, new InetSocketAddress("localhost", 8081));
        logger1.info(mk1,  "slf4j + logback-classic, {}, {}, {}", 300, Level.INFO,  new InetSocketAddress("localhost", 8082));
        logger1.warn(mk1,  "slf4j + logback-classic, {}, {}, {}", 400, Level.WARN,  new InetSocketAddress("localhost", 8083));
        logger1.error(mk1, "slf4j + logback-classic, {}, {}, {}", 500, Level.ERROR, new InetSocketAddress("localhost", 8084));

        logger2.trace(mk2, "slf4j + logback-classic, {}, {}, {}", 100, Level.TRACE, new InetSocketAddress("localhost", 8080));
        logger2.debug(mk2, "slf4j + logback-classic, {}, {}, {}", 200, Level.DEBUG, new InetSocketAddress("localhost", 8081));
        logger2.info(mk2,  "slf4j + logback-classic, {}, {}, {}", 300, Level.INFO,  new InetSocketAddress("localhost", 8082));
        logger2.warn(mk2,  "slf4j + logback-classic, {}, {}, {}", 400, Level.WARN,  new InetSocketAddress("localhost", 8083));
        logger2.error(mk2, "slf4j + logback-classic, {}, {}, {}", 500, Level.ERROR, new InetSocketAddress("localhost", 8084));
    }
}


text:
using System.Collections.Generic;
using NDatabase.Tool.Wrappers;
using NUnit.Framework;
using Test.NDatabase.Odb.Test.VO.Login;

namespace Test.NDatabase.Odb.Test.Performance
{
    [TestFixture]
    public class TestLazy : ODBTest
    {
        public const int Size = 4000;

        public static readonly string Filename = "lazy.ndb";

        private object GetInstance()
        {
            var login = new VO.Login.Function("login");
            var logout = new VO.Login.Function("logout");
            var list = new List<VO.Login.Function>();
            list.Add(login);
            list.Add(logout);
            var profile = new Profile("operator", list);
            var user = new User("olivier smadja", "user@ndatabase.net", profile);
            return user;
        }

        /// <summary>
        ///   Test the timeof lazy get
        /// </summary>
        [Test]
        public virtual void Test1()
        {
            DeleteBase(Filename);
            // println("Start inserting " + SIZE + " objects");
            var startinsert = OdbTime.GetCurrentTimeInTicks();
            var odb = Open(Filename);
            for (var i = 0; i < Size; i++)
                odb.Store(GetInstance());
            odb.Close();
            var endinsert = OdbTime.GetCurrentTimeInTicks();
            // println("End inserting " + SIZE + " objects  - " +
            // (endinsert-startinsert) + " ms");
            // println("totalObjects = "+ odb.count(User.class));
            odb = Open(Filename);
            var start1 = OdbTime.GetCurrentTimeInTicks();
            var query = odb.Query<User>();
            var lazyList = query.Execute<User>(false);
            var end1 = OdbTime.GetCurrentTimeInTicks();
            var startget1 = OdbTime.GetCurrentTimeInTicks();
            while (lazyList.HasNext())
            {
                // t1 = OdbTime.getCurrentTimeInMs();
                lazyList.Next();
            }
            // t2 = OdbTime.getCurrentTimeInMs();
            // println(t2-t1);
            var endget1 = OdbTime.GetCurrentTimeInTicks();
            AssertEquals(odb.Query<User>().Count(), lazyList.Count);
            odb.Close();
            var t01 = end1 - start1;
            var tget1 = endget1 - startget1;
            // long t2 = end2-start2;
            // long tget2 = endget2-startget2;
            // println("t1(lazy)="+t1 + " - " +tget1+ "      t2(memory)="+t2 +" - "
            // + tget2);
            // println("t1(lazy)="+t1 + " - " +tget1);
            // assertTrue(t1<t2);
            // println(endinsert-startinsert);
            var c = 501 > tget1;
            Println("Time for " + Size + " lazy gets : " + (tget1));
            if (!c)
                Println("Time for " + Size + " lazy gets : " + (tget1));
            DeleteBase(Filename);
            if (testPerformance && !c)
                Fail("Time for " + Size + " lazy gets : " + (tget1));
        }
    }
}


text:
package energy.usef.cro.config;

import energy.usef.core.config.AbstractConfig;

import java.io.IOException;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.enterprise.context.ApplicationScoped;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Property config class.
 *
 */
@ApplicationScoped
public class ConfigCro extends AbstractConfig {
    private static final Logger LOGGER = LoggerFactory.getLogger(ConfigCro.class);

    /**
     * Default constructor.
     */
    public ConfigCro() {
        try {
            readProperties();
        } catch (IOException e) {
            LOGGER.error("Error while loading the properties: {}.", e.getMessage(), e);
        }
    }

    /**
     * Initialize a bean after the instance has been constructed.
     */
    @PostConstruct
    public void initBean() {
        startConfigWatcher();
    }

    /**
     * Clean up the bean before destroying this instance.
     */
    @PreDestroy
    public void cleanupBean() {
        stopConfigWatcher();
    }

    /**
     * Gets a property value as a {@link String}.
     *
     * @param configParam the configuration parameter
     * @return property value
     */
    public String getProperty(ConfigCroParam configParam) {
        if (properties == null) {
            return null;
        }
        return properties.getProperty(configParam.name());
    }

    /**
     * Gets a property value as an {@link Integer}.
     *
     * @param configParam the configuration parameter
     * @return property value
     */
    public Integer getIntegerProperty(ConfigCroParam configParam) {
        return Integer.parseInt(properties.getProperty(configParam.name()));
    }

}


text:
package effectivejava.chapter8.item52;

import java.math.BigInteger;
import java.util.*;

// Repaired  static classifier method. (Page 240)
public class FixedCollectionClassifier {
    public static String classify(Collection<?> c) {
        return c instanceof Set  ? "Set" :
                c instanceof List ? "List" : "Unknown Collection";
    }

    public static void main(String[] args) {
        Collection<?>[] collections = {
                new HashSet<String>(),
                new ArrayList<BigInteger>(),
                new HashMap<String, String>().values()
        };

        for (Collection<?> c : collections)
            System.out.println(classify(c));
    }
}


text:
using ::testing::Eq;
using ::testing::StrEq;
using ::testing::Test;

using std::istringstream;
using std::ostringstream;

namespace tcframe {

class LinesIOSegmentManipulatorTests : public Test {
protected:
    vector<int> X, Y;
    vector<vector<int>> Z;
    function<int()> size = [] {return 3;};

    LinesIOSegment* segment = LinesIOSegmentBuilder()
            .addVectorVariable(Vector::create(X, "X"))
            .addVectorVariable(Vector::create(Y, "Y"))
            .setSize(size)
            .build();
    LinesIOSegment* segmentWithJaggedVector = LinesIOSegmentBuilder()
            .addVectorVariable(Vector::create(X, "X"))
            .addVectorVariable(Vector::create(Y, "Y"))
            .addJaggedVectorVariable(Matrix::create(Z, "Z"))
            .setSize(size)
            .build();
    LinesIOSegment* segmentWithJaggedVectorOnly = LinesIOSegmentBuilder()
            .addJaggedVectorVariable(Matrix::create(Z, "Z"))
            .setSize(size)
            .build();
    LinesIOSegment* segmentWithoutSize = LinesIOSegmentBuilder()
            .addVectorVariable(Vector::create(X, "X"))
            .addVectorVariable(Vector::create(Y, "Y"))
            .build();
    LinesIOSegment* segmentWithJaggedVectorWithoutSize = LinesIOSegmentBuilder()
            .addVectorVariable(Vector::create(X, "X"))
            .addVectorVariable(Vector::create(Y, "Y"))
            .addJaggedVectorVariable(Matrix::create(Z, "Z"))
            .build();
    LinesIOSegment* segmentWithJaggedVectorWithoutSizeOnly = LinesIOSegmentBuilder()
            .addJaggedVectorVariable(Matrix::create(Z, "Z"))
            .build();

    LinesIOSegmentManipulator manipulator;
};

TEST_F(LinesIOSegmentManipulatorTests, Parsing_Successful) {
    istringstream in("1 2\n3 4\n5 6\n");

    manipulator.parse(segment, &in);
    EXPECT_THAT(X, Eq(vector<int>{1, 3, 5}));
    EXPECT_THAT(Y, Eq(vector<int>{2, 4, 6}));
}

TEST_F(LinesIOSegmentManipulatorTests, Parsing_Successful_CheckLastVariable) {
    istringstream in("1 2\n3 4\n5 6\n");

    EXPECT_THAT(manipulator.parse(segment, &in), Eq("'Y[2]'"));
}

TEST_F(LinesIOSegmentManipulatorTests, Parsing_Failed_MissingVariable) {
    istringstream in("1 2\n3  ");

    try {
        manipulator.parse(segment, &in);
        FAIL();
    } catch (runtime_error& e) {
        EXPECT_THAT(e.what(), StrEq("Cannot parse for 'Y[1]'. Found: <whitespace>"));
    }
}

TEST_F(LinesIOSegmentManipulatorTests, Parsing_Failed_MissingWhitespace) {
    istringstream in("1 2\n3");

    try {
        manipulator.parse(segment, &in);
        FAIL();
    } catch (runtime_error& e) {
        EXPECT_THAT(e.what(), StrEq("Expected: <space> after 'X[1]'"));
    }
}

TEST_F(LinesIOSegmentManipulatorTests, Parsing_Failed_MissingNewline) {
    istringstream in("1 2\n3 4 ");

    try {
        manipulator.parse(segment, &in);
        FAIL();
    } catch (runtime_error& e) {
        EXPECT_THAT(e.what(), StrEq("Expected: <newline> after 'Y[1]'"));
    }
}

TEST_F(LinesIOSegmentManipulatorTests, Parsing_WithJaggedVector_Successful) {
    istringstream in("1 2 10\n3 4\n5 6 20 30\n");

    manipulator.parse(segmentWithJaggedVector, &in);
    EXPECT_THAT(X, Eq(vector<int>{1, 3, 5}));
    EXPECT_THAT(Y, Eq(vector<int>{2, 4, 6}));
    EXPECT_THAT(Z, Eq(vector<vector<int>>{{10}, {}, {20, 30}}));
}

TEST_F(LinesIOSegmentManipulatorTests, Parsing_WithJaggedVector_Only_Successful) {
    istringstream in("10\n\n20 30\n");

    manipulator.parse(segmentWithJaggedVectorOnly, &in);
    EXPECT_THAT(Z, Eq(vector<vector<int>>{{10}, {}, {20, 30}}));
}

TEST_F(LinesIOSegmentManipulatorTests, Parsing_WithJaggedVector_Successful_CheckLastVariable) {
    istringstream in("1 2 10\n3 4\n5 6 20 30\n");

    EXPECT_THAT(manipulator.parse(segmentWithJaggedVector, &in), Eq("'Z[2][1]'"));
}

TEST_F(LinesIOSegmentManipulatorTests, Parsing_WithJaggedVector_Failed_MissingSpaceOrNewline) {
    istringstream in("1 2 10\n3 4\n5 6 20 30");

    try {
        manipulator.parse(segmentWithJaggedVector, &in);
        FAIL();
    } catch (runtime_error& e) {
        EXPECT_THAT(e.what(), StrEq("Expected: <space> or <newline> after 'Z[2][1]'"));
    }
}

TEST_F(LinesIOSegmentManipulatorTests, Parsing_WithoutSize_Successful) {
    istringstream in("1 2\n3 4\n5 6\n");

    manipulator.parse(segmentWithoutSize, &in);
    EXPECT_THAT(X, Eq(vector<int>{1, 3, 5}));
    EXPECT_THAT(Y, Eq(vector<int>{2, 4, 6}));
}

TEST_F(LinesIOSegmentManipulatorTests, Parsing_WithoutSize_Successful_CheckLastVariable) {
    istringstream in("1 2\n3 4\n5 6\n");

    EXPECT_THAT(manipulator.parse(segmentWithoutSize, &in), Eq("'Y[2]'"));
}

TEST_F(LinesIOSegmentManipulatorTests, Parsing_WithoutSize_Failed_MissingVariable) {
    istringstream in("1 2\n3  ");

    try {
        manipulator.parse(segmentWithoutSize, &in);
        FAIL();
    } catch (runtime_error& e) {
        EXPECT_THAT(e.what(), StrEq("Cannot parse for 'Y[1]'. Found: <whitespace>"));
    }
}

TEST_F(LinesIOSegmentManipulatorTests, Parsing_WithoutSize__Failed_MissingWhitespace) {
    istringstream in("1 2\n3");

    try {
        manipulator.parse(segmentWithoutSize, &in);
        FAIL();
    } catch (runtime_error& e) {
        EXPECT_THAT(e.what(), StrEq("Expected: <space> after 'X[1]'"));
    }
}

TEST_F(LinesIOSegmentManipulatorTests, Parsing_WithoutSize_Failed_MissingNewline) {
    istringstream in("1 2\n3 4 ");

    try {
        manipulator.parse(segmentWithoutSize, &in);
        FAIL();
    } catch (runtime_error& e) {
        EXPECT_THAT(e.what(), StrEq("Expected: <newline> after 'Y[1]'"));
    }
}

TEST_F(LinesIOSegmentManipulatorTests, Parsing_WithJaggedVector_WithoutSize_Successful) {
    istringstream in("1 2 10\n3 4\n5 6 20 30\n");

    manipulator.parse(segmentWithJaggedVectorWithoutSize, &in);
    EXPECT_THAT(X, Eq(vector<int>{1, 3, 5}));
    EXPECT_THAT(Y, Eq(vector<int>{2, 4, 6}));
    EXPECT_THAT(Z, Eq(vector<vector<int>>{{10}, {}, {20, 30}}));
}

TEST_F(LinesIOSegmentManipulatorTests, Parsing_WithJaggedVector_WithoutSize_Only_Successful) {
    istringstream in("10\n\n20 30\n");

    manipulator.parse(segmentWithJaggedVectorWithoutSizeOnly, &in);
    EXPECT_THAT(Z, Eq(vector<vector<int>>{{10}, {}, {20, 30}}));
}

TEST_F(LinesIOSegmentManipulatorTests, Parsing_WithJaggedVector_WithoutSize_Successful_CheckLastVariable) {
    istringstream in("1 2 10\n3 4\n5 6 20 30\n");

    EXPECT_THAT(manipulator.parse(segmentWithJaggedVectorWithoutSize, &in), Eq("'Z[2][1]'"));
}

TEST_F(LinesIOSegmentManipulatorTests, Parsing_WithJaggedVector_WithoutSize_Failed_MissingSpaceOrNewline) {
    istringstream in("1 2 10\n3 4\n5 6 20 30");

    try {
        manipulator.parse(segmentWithJaggedVectorWithoutSize, &in);
        FAIL();
    } catch (runtime_error& e) {
        EXPECT_THAT(e.what(), StrEq("Expected: <space> or <newline> after 'Z[2][1]'"));
    }
}

TEST_F(LinesIOSegmentManipulatorTests, Printing_Successful) {
    ostringstream out;

    X = {1, 3, 5};
    Y = {2, 4, 6};

    manipulator.print(segment, &out);
    EXPECT_THAT(out.str(), Eq("1 2\n3 4\n5 6\n"));
}

TEST_F(LinesIOSegmentManipulatorTests, Printing_Failed_SizeMismatch) {
    ostringstream out;

    X = {1, 3, 5};
    Y = {2, 4};

    try {
        manipulator.print(segment, &out);
        FAIL();
    } catch (runtime_error& e) {
        EXPECT_THAT(e.what(), StrEq("Number of elements of vector 'Y' unsatisfied. Expected: 3, actual: 2"));
    }
}

TEST_F(LinesIOSegmentManipulatorTests, Printing_WithJaggedVector_Successful) {
    ostringstream out;

    X = {1, 3, 5};
    Y = {2, 4, 6};
    Z = {{10}, {}, {20, 30}};

    manipulator.print(segmentWithJaggedVector, &out);
    EXPECT_THAT(out.str(), Eq("1 2 10\n3 4\n5 6 20 30\n"));
}

TEST_F(LinesIOSegmentManipulatorTests, Printing_WithJaggedVector_Only_Successful) {
    ostringstream out;

    Z = {{10}, {}, {20, 30}};

    manipulator.print(segmentWithJaggedVectorOnly, &out);
    EXPECT_THAT(out.str(), Eq("10\n\n20 30\n"));
}

TEST_F(LinesIOSegmentManipulatorTests, Printing_WithJaggedVector_Failed_SizeMismatch) {
    ostringstream out;

    X = {1, 3, 5};
    Y = {2, 4, 6};
    Z = {{10}, {}};

    try {
        manipulator.print(segmentWithJaggedVector, &out);
        FAIL();
    } catch (runtime_error& e) {
        EXPECT_THAT(e.what(), StrEq("Number of elements of jagged vector 'Z' unsatisfied. Expected: 3, actual: 2"));
    }
}

TEST_F(LinesIOSegmentManipulatorTests, Printing_WithoutSize_Successful) {
    ostringstream out;

    X = {1, 3, 5};
    Y = {2, 4, 6};

    manipulator.print(segmentWithoutSize, &out);
    EXPECT_THAT(out.str(), Eq("1 2\n3 4\n5 6\n"));
}

TEST_F(LinesIOSegmentManipulatorTests, Printing_WithoutSize_Failed_DifferentSizes) {
    ostringstream out;

    X = {1, 3, 5};
    Y = {2, 4};

    try {
        manipulator.print(segmentWithoutSize, &out);
        FAIL();
    } catch (runtime_error& e) {
        EXPECT_THAT(e.what(), StrEq(
                "Number of elements of vector 'Y' unsatisfied. "
                "Expected: 3 (number of elements of 'X'), "
                "actual: 2"));
    }
}

TEST_F(LinesIOSegmentManipulatorTests, Printing_WithJaggedVector_WithoutSize_Successful) {
    ostringstream out;

    X = {1, 3, 5};
    Y = {2, 4, 6};
    Z = {{10}, {}, {20, 30}};

    manipulator.print(segmentWithJaggedVectorWithoutSize, &out);
    EXPECT_THAT(out.str(), Eq("1 2 10\n3 4\n5 6 20 30\n"));
}

TEST_F(LinesIOSegmentManipulatorTests, Printing_WithJaggedVector_WithoutSize_Only_Successful) {
    ostringstream out;

    Z = {{10}, {}, {20, 30}};

    manipulator.print(segmentWithJaggedVectorWithoutSizeOnly, &out);
    EXPECT_THAT(out.str(), Eq("10\n\n20 30\n"));
}

TEST_F(LinesIOSegmentManipulatorTests, Printing_WithJaggedVector_WithoutSize_Failed_DifferentSizes) {
    ostringstream out;

    X = {1, 3, 5};
    Y = {2, 4, 6};
    Z = {{10}, {}};

    try {
        manipulator.print(segmentWithJaggedVectorWithoutSize, &out);
        FAIL();
    } catch (runtime_error& e) {
        EXPECT_THAT(e.what(),StrEq(
                "Number of elements of jagged vector 'Z' unsatisfied. "
                "Expected: 3 (number of elements of 'X'), "
                "actual: 2"));
    }
}

TEST_F(LinesIOSegmentManipulatorTests, Parsing_ClearSegment_Successful) {
    istringstream in("1 2 10\n3 4\n5 6 20 30\n");

    manipulator.parse(segmentWithJaggedVector, &in);

    in.seekg(0, in.beg);
    manipulator.parse(segmentWithJaggedVector, &in);
    EXPECT_THAT(X, Eq(vector<int>{1, 3, 5}));
    EXPECT_THAT(Y, Eq(vector<int>{2, 4, 6}));
    EXPECT_THAT(Z, Eq(vector<vector<int>>{{10}, {}, {20, 30}}));
}

}


text:
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;

public class Main {

    private static String getHTML(String urlToRead) {
        try {
            println("Requested           '" + urlToRead + "'");
            StringBuilder result = new StringBuilder();
            URL url = new URL(urlToRead);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }
            rd.close();
            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static void writeFile(String fileNameRelative, String writeString) {
        try {
            PrintWriter printWriter = new PrintWriter(getCurrentPath() + "/" + fileNameRelative);
            printWriter.println(writeString);
            printWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String[] readFile(String fileNameRelative) {
        try {
            ArrayList<String> stringArrayList = new ArrayList<>();
            BufferedReader br = new BufferedReader(new FileReader(getCurrentPath() + "/" + fileNameRelative));
            while (true) {
                String line = br.readLine();
                if (line == null) {
                    break;
                } else {
                    stringArrayList.add(line);
                }
            }
            br.close();
            String returnString[] = new String[stringArrayList.size()];
            returnString = stringArrayList.toArray(returnString);
            return returnString;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static String getCurrentPath() {
        Path currentRelativePath = Paths.get("");
        String pathString = currentRelativePath.toAbsolutePath().toString();
        return pathString;
    }

    private static String getMeaningFromRequest(String requestString) {
        int stringStartIndex = requestString.indexOf("
[명사]") + 8;
//        println(stringStartIndex);
        int stringFinishIndex = requestString.indexOf("
", stringStartIndex);
//        println(stringFinishIndex);
        if (stringStartIndex == stringFinishIndex) {
            // empty string or two meanings
            stringStartIndex = requestString.indexOf("
[명사]
") + 12;
            stringFinishIndex = requestString.indexOf("
", stringStartIndex);
            requestString = requestString.substring(stringStartIndex, stringFinishIndex);
            requestString = requestString.replaceAll("\\s\\s", "");
        } else {
            requestString = requestString.substring(stringStartIndex, stringFinishIndex);
        }
        requestString = requestString.replaceAll("\\<.*?\\>", "");
        requestString = requestString.replaceAll("&\\w+;", "");
        if (requestString.startsWith(" [같은 말]")) {
            // has a same meaning
            requestString = " " + requestString.substring(requestString.indexOf("(") + 1, requestString.indexOf(")")) + ".";
        }
        return requestString;
    }

    public static void main(String[] args) {
        String baseUrl = "http://krdic.naver.com/search.nhn?query=";
        String words[] = readFile("words.txt");
        String newline = System.getProperty("line.separator");
        StringBuilder finalStringBuilder = new StringBuilder();
        for (String word : words) {
            String meaning = getMeaningFromRequest(getHTML(baseUrl + word + "&kind=all"));
            println("Word read from file '" + word + "'");
            if (meaning.startsWith("PE HTML PUBLIC")) {
                // no value, exploded
                meaning = "NULL";
            }
            if (meaning.startsWith("\t") || meaning.startsWith(" ")) {
                // for list meanings with 2 spaces on start
                meaning = meaning.substring(1);
            }
            println("Returned            '" + meaning + "'");
            finalStringBuilder.append(word).append(" : ").append(meaning).append(newline);
        }
        writeFile("words_meaning.txt", finalStringBuilder.toString());
    }

    private static void println(Object object) {
        System.out.println(object.toString());
    }
}


text:
// Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See LICENSE in the project root for license information.

/**
 * Responsive Variables
 *
 * All fabric breakpoints used in fabric
 *
 */

/**
 * @namespace fabric
 */
var fabric = fabric || {};
/**
 *
 * @constructor
 */
fabric.ResponsiveVariables = function() {
  this.init();
};

fabric.ResponsiveVariables.prototype = (function() {

  var ResponsiveVariables = {
    "sm-min": 320,
    "md-min": 480,
    "lg-min": 640,
    "xl-min": 1024,
    "xxl-min": 1366,
    "xxxl-min": 1920
  };

  ResponsiveVariables["sm-max"] = minVariables["md-min"] - 1;
  ResponsiveVariables["md-max"] = minVariables["lg-min"] - 1;
  ResponsiveVariables["lg-max"] = minVariables["xl-min"] - 1;
  ResponsiveVariables["xl-max"] = minVariables["xxl-min"] - 1;
  ResponsiveVariables["xxl-max"] = minVariables["xxxl-min"] - 1;

  /**
   * initializes component
   */
  var init = function() {
    return ResponsiveVariables;
  };

  return {
    init: init
  };

}());


text:
{% extends 'dashboard/dashboard_base.html' %}
{% block stage %}

Topic Details

              Title:

              {{ topic.title }}

              Tags:

              {% for tag in topic.tags.all %}{{ tag.title }}{% if forloop.last %}{% else %}, {% endif %}{% endfor %}

              Created By:

              {{ topic.created_by.username }}

              Category:

               {{ topic.category.title }}

              Status:

              {{ topic.status }}

              description:

               {{ topic.description|safe }}

      {% if topic.topic_comments.all %}

Comments({{topic.topic_comments.all|length}})

Comment Details

New Comment

        {% for comment in topic.topic_comments.all %}

              Title:

              {{ comment.comment|safe }}

              Commented By:

              {{ comment.commented_by.username }}

              Commented on:

              {{ comment.updated_on }}

        {% endfor %}

      {% else %}

No Comments Available for record

      {% endif %}

{% endblock %}
{% block extra_js %}

{% endblock %}


text:
"""
Author: Mitchell Blowey

Miscellaneous tools and helper functions.
"""

# Used to simulate 16 bit ones-complement addition, which does not exist in python.
def _carry_around_add(a, b):
	# Start by simply adding together the numbers.
    c = a + b

    # The overflow bits are collected by the expression c >> 16 and added back to the
    # rest of the number, which is obtained by c & 0xffff.
    return (c >> 16) + (c & 0xffff)

# Calculates the ipv4 header checksum using the passed in header, which should be
# the header completely filled in, in byte format.
def chksum(header):
	# Convert the byte format to int
	header = int.from_bytes(header, 'big', signed=False)

	words = []

	# Breaks the header into 8 bit words and adds them to the array.
	while header > 0:
		next_word = header & 0xff
		header = header >> 8

		words.append(next_word)

	# Appends an extra 0 to create an even amount of 8 bit words.
	if len(words) % 2 == 1:
		words.append(0)

	# Calculate the 16 bit ones complement sum
	sum_ = 0
	for i in range(0, len(words), 2):
		word_16_bit = (words[i+1] << 8) + words[i] # Convert two 8 bit words into 16 bit word.
		sum_ = _carry_around_add(sum_, word_16_bit) # Add new 16 bit word to current sum.

	# Return the 16 bit one's complement of the 16 bit one's complement sum.
	return ~sum_ & 0xffff

# Function to print values from a dictionary, such as the dict of attributes from an object.
# Starts_with can be specified if you only want to view the data from one levl ofthe stack,
# e.g. starts_with='ip_' to only view fields that belong to the IP header.
def print_key_val(dictionary, starts_with=''):

    for i in sorted(dictionary.keys()):
    	if i[:len(starts_with)] == starts_with:
    		# Format the results into columns, including a decimal and hex column.
    		print('{0:<15} {1:>15} {2:>15}'.format(i,
    											   str(dictionary[i]),
    											   str(hex(dictionary[i]))
    											   ))


text:
public final class Global {
    private Global() {} // só pra garantir que não haja instâncias dela
    private static int[] vetor;
    public static int[] getVetor() { return vetor; }
    public static void setVetor(int[] vetor) { this.vetor = vetor; }
    //aqui pode colocar vários outros dados se eles forem relacionados
    //o ideal é criar classe globais para cada necessidade
    //nem sempre é necessário usar getter e setter, o campo público pode ser suficiente
    //é possível criar outras operações específicas de acordo com a necessidade
    //por exemplo pode pegar e setar um elemento do vetor
}

//https://pt.stackoverflow.com/q/134576/101


text:
The data values in this folder have been extracted from the SDE on EVE Online.

The files were created by using the .xls/.csv dumps, opening them in a spreadsheet application and apply display formatting on the columns so that a simple copy/paste ends up in a Go array.
Only the necessary columns have been taken, the files are big enough as they are.

All of this is a manual process; The map layout seldom changes and automating this process would take more effort.

Credits for the dumps go to the person behind "Steve Ronuken", who provides the extracts in various forms:
https://www.fuzzwork.co.uk/


text:
<!DOCTYPE html>

<meta charset="utf-8">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="components/materialize/dist/css/materialize.min.css">
<link rel="stylesheet" href="components/DataTables/media/css/dataTables.material.min.css">

<title>Cited by</title>

			Cited by

				I was inspired by Lior Pachter's blog post "A citation is not a citation is not a citation" to create this simple web page. I use the Pubmed API to view and classify the papers citing a given reference.

				I use one of my papers as an example, but feel free to enter your own IDs. And drop me a line if you have any suggestions for improvements!

				<select id="db">
					<option value="pubmed">PubMed</option>
				</select>
				Choose your NCBI database

				<input id="id" type="text" value="24287332">
				Enter your ID

				<button class="btn waves-effect waves-light" type="submit" name="action">
					Go
				</button>

			This paper has XXX citations, of which:

XXX are by co-authors;

XXX are reviews

						Authors
						Title
						Source
						Year
						Category
						Co-Author Count
						Link

Credits

						Built by Max Leiserson

						Last updated: February, 2017

Built with

							Entrez Programming Utilities

							D3.js

							jQuery

							Materialize

				© 2017 Some Rights Reserved.


text:
'use strict';
var chalk = require('chalk');
var logSymbols = require('log-symbols');

/**
 * The MochaReporter.
 *
 * @param {!object} baseReporterDecorator The karma base reporter.
 * @param {!Function} formatError The karma function to format an error.
 * @param {!object} config The karma config.
 * @constructor
 */
var MochaReporter = function (baseReporterDecorator, formatError, config) {
    // extend the base reporter
    baseReporterDecorator(this);

    var self = this;
    var firstRun = true;

    // disable chalk when colors is set to false
    if (config.colors === false) {
        chalk.enabled = false;
    }

    /**
     * Returns a formatted time interval
     *
     * @param {!number} time The time.
     * @returns {string}
     */
    function formatTimeInterval (time) {
        var mins = Math.floor(time / 60000);
        var secs = (time - mins * 60000) / 1000;
        var str = secs + (secs === 1 ? ' sec' : ' secs');

        if (mins) {
            str = mins + (mins === 1 ? ' min ' : ' mins ') + str;
        }

        return str;
    }

    /**
     * Returns the text repeated n times.
     *
     * @param {!string} text The text.
     * @param {!number} n The number of times the string should be repeated.
     * @returns {string}
     */
    function repeatString (text, n) {
        var res = [];
        var i;

        for (i = 0; i < n; i++) {
            res.push(text);
        }

        return res.join('');
    }

    /**
     * Writes the test results to the output
     *
     * @param {!object} suite The test suite
     * @param {number=} depth The indention.
     */
    function print (suite, depth) {
        var keys = Object.keys(suite);
        var length = keys.length;
        var i, item;

        if (firstRun) {
            self.write(chalk.underline.bold('\nStart:') + '\n');
            firstRun = false;
        }

        for (i = 0; i < length; i++) {
            item = suite[keys[i]];

            // start of a new suite
            if (item.isRoot) {
                depth = 1;
            }

            // only print to output once
            if (item.name && !item.printed) {
                // indent
                var line = repeatString('  ', depth) + item.name;

                // it block
                if (item.type === 'it') {
                    if (item.skipped) {
                        // print skipped tests grey
                        line = chalk.gray(line + ' (skipped)');
                    } else {
                        // set color to green or red
                        line = item.success ? chalk.green(line) : chalk.red(line);
                    }
                } else {
                    // print name of a suite block in bold
                    line = chalk.bold(line);
                }

                // use write method of baseReporter
                self.write(line + '\n');

                // set item as printed
                item.printed = true;
            }

            if (item.items) {
                // print all child items
                print(item.items, depth + 1);
            }
        }
    }

    /**
     * Writes the failed test to the output
     *
     * @param {!object} suite The test suite
     * @param {number=} depth The indention.
     */
    function printFailures (suite, depth) {
        var keys = Object.keys(suite);
        var length = keys.length;
        var i, item;

        for (i = 0; i < length; i++) {
            item = suite[keys[i]];

            // start of a new suite
            if (item.isRoot) {
                depth = 1;
            }

            // only print to output when test failed
            if (item.name && !item.success && !item.skipped) {
                // indent
                var line = repeatString('  ', depth) + item.name;

                // it block
                if (item.type === 'it') {
                    // make item name red
                    line = chalk.red(line) + '\n';

                    // add all browser in which the test failed with color yellow
                    for (var bi = 0; bi < item.failed.length; bi++) {
                        var browserName = item.failed[bi];
                        line += repeatString('  ', depth + 1) + chalk.italic.yellow(browserName) + '\n';
                    }

                    // add the error log in red
                    line += chalk.red(formatError((item.log || [])[0], repeatString('  ', depth)));
                }

                // use write method of baseReporter
                self.write(line + '\n');
            }

            if (item.items) {
                // print all child items
                printFailures(item.items, depth + 1);
            }
        }
    }

    /**
     * Returns all properties of the given object
     *
     * @param {!Object} obj
     * @returns {Array}
     */
    function listAllObjectProperties (obj) {
        var objectToInspect;
        var result = [];

        for (objectToInspect = obj; objectToInspect !== null; objectToInspect = Object.getPrototypeOf(objectToInspect)) {
            result = result.concat(Object.getOwnPropertyNames(objectToInspect));
        }

        return result;
    }

    /**
     * Returns if the property is an reserverd object property
     *
     * @param {!Object} obj
     * @param {!String} property
     * @returns {boolean}
     */
    function isReservedProperty (obj, property) {
        return listAllObjectProperties(Object.getPrototypeOf(obj)).indexOf(property) > -1;
    }

    /**
     * Called each time a test is completed in a given browser.
     *
     * @param {!object} browser The current browser.
     * @param {!object} result The result of the test.
     */
    function specComplete (browser, result) {
        // complete path of the test
        var path = [].concat(result.suite, result.description);
        var maxDepth = path.length - 1;

        path.reduce(function (suite, description, depth) {
            if (isReservedProperty(suite, description)) {
                self.write(chalk.yellow('Reserved name for ' + (depth === maxDepth ? 'it' : 'describe') + ' block (' + description + ')! Please use an other name, othwerwhise the result are not printed correctly\n'));
                return {};
            }

            var item = suite[description] || {};
            suite[description] = item;

            item.name = description;
            item.isRoot = depth === 0;
            item.type = 'describe';
            item.skipped = result.skipped;
            item.success = (item.success === undefined ? true : item.success) && result.success;

            // it block
            if (depth === maxDepth) {
                item.type = 'it';
                item.count = item.count || 0;
                item.count++;
                item.failed = item.failed || [];
                item.name = (result.success ? logSymbols.success : logSymbols.error) + ' ' + item.name;
                item.success = result.success;
                item.skipped = result.skipped;
                self.netTime += result.time;

                if (result.skipped) {
                    self.numberOfSkippedTests++;
                }

                if (result.success === false) {
                    // add browser to failed browsers array
                    item.failed.push(browser.name);

                    // add error log
                    item.log = result.log;
                }

                if (config.reportSlowerThan && result.time > config.reportSlowerThan) {
                    // add slow report warning
                    item.name += chalk.yellow((' (slow: ' + formatTimeInterval(result.time) + ')'));
                    self.numberOfSlowTests++;
                }

                if (item.count === self.numberOfBrowsers) {
                    // print results to output when test is run through all browsers
                    print(self.allResults, depth);
                }
            } else {
                item.items = item.items || {};
            }

            return item.items;
        }, self.allResults);
    }

    self.specSuccess = specComplete;
    self.specSkipped = specComplete;
    self.specFailure = specComplete;

    self.onSpecComplete = function (browser, result) {
        specComplete(browser, result);
    };

    self.onRunStart = function (browsers) {
        self._browsers = [];
        self.allResults = {};
        self.totalTime = 0;
        self.netTime = 0;
        self.numberOfSlowTests = 0;
        self.numberOfSkippedTests = 0;
        self.numberOfBrowsers = (browsers || []).length;
    };

    self.onBrowserStart = function (browser) {
        self._browsers.push(browser);
        self.numberOfBrowsers = self._browsers.length;
    };

    self.onRunComplete = function (browsers, results) {
        browsers.forEach(function(browser){
            self.totalTime += browser.lastResult.totalTime;
        });

        self.write(chalk.green('\nFinished in ' + formatTimeInterval(self.totalTime) + ' / ' + formatTimeInterval(self.netTime) + '\n\n'));

        if (browsers.length > 0 && !results.disconnected) {
            self.write(chalk.underline.bold('SUMMARY:') + '\n');
            self.write(chalk.green(logSymbols.success + ' ' + results.success + ' tests completed\n'));

            if (self.numberOfSkippedTests > 0) {
                self.write(chalk.grey(logSymbols.info + ' ' + self.numberOfSkippedTests + ' tests skipped\n'));
            }

            if (self.numberOfSlowTests > 0) {
                self.write(chalk.yellow(logSymbols.warning + ' ' + self.numberOfSlowTests + ' tests slow\n'));
            }

            if (results.failed) {
                self.write(chalk.red(logSymbols.error + ' ' + results.failed + ' tests failed\n'));
                self.write(chalk.underline.bold('\nFAILED TESTS:') + '\n');

                printFailures(self.allResults);
            }
        }
    };
};

// inject karma runner baseReporter and config
MochaReporter.$inject = ['baseReporterDecorator', 'formatError', 'config'];

// PUBLISH DI MODULE
module.exports = {
    'reporter:mocha': ['type', MochaReporter]
};


text:
//=====================================================================
//
//File:      $RCSfile: AllActivityModifier.java,v $
//Version:   $Revision: 1.43 $
//Modified:  $Date: 2013/01/10 23:20:48 $
//
//(c) Copyright 2004-2014 by Mentor Graphics Corp. All rights reserved.
//
//=====================================================================
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License.  You may obtain a copy
// of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   See the
// License for the specific language governing permissions and limitations under
// the License.
//=====================================================================

package org.xtuml.bp.ui.text.activity;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.ui.texteditor.IElementStateListener;

import org.xtuml.bp.als.oal.ParserAllActivityModifier;
import org.xtuml.bp.core.Component_c;
import org.xtuml.bp.core.Domain_c;
import org.xtuml.bp.core.ExternalEntityPackage_c;
import org.xtuml.bp.core.FunctionPackage_c;
import org.xtuml.bp.core.Package_c;
import org.xtuml.bp.core.Parsestatus_c;
import org.xtuml.bp.core.ProvidedOperation_c;
import org.xtuml.bp.core.ProvidedSignal_c;
import org.xtuml.bp.core.RequiredOperation_c;
import org.xtuml.bp.core.RequiredSignal_c;
import org.xtuml.bp.core.Subsystem_c;
import org.xtuml.bp.core.common.ModelRoot;
import org.xtuml.bp.core.common.NonRootModelElement;
import org.xtuml.bp.core.util.UIUtil;
import org.xtuml.bp.ui.text.DocumentProvider;
import org.xtuml.bp.ui.text.IModelElementEditorInputFactory;
import org.xtuml.bp.ui.text.ModelAdapter;
import org.xtuml.bp.ui.text.ModelElementID;
import org.xtuml.bp.ui.text.TextPlugin;
import org.xtuml.bp.ui.text.placeholder.PlaceHolderManager;

public class AllActivityModifier extends ParserAllActivityModifier
{
    private static IModelElementEditorInputFactory activityInputFactory;

    private ActivityEditor.ParseRunnable parseRunner = new ActivityEditor.ParseRunnable();

    public AllActivityModifier(Domain_c parent, IProgressMonitor monitor){
    	super(parent, monitor);
        if(activityInputFactory == null){
        	activityInputFactory = ActivityEditorInputFactory.getDefaultInstance();
        }
    }

    public AllActivityModifier(Component_c parent, IProgressMonitor monitor){
    	super(parent, monitor);
        if(activityInputFactory == null){
        	activityInputFactory = ActivityEditorInputFactory.getDefaultInstance();
        }
    }

    public AllActivityModifier(Package_c parent, IProgressMonitor monitor){
    	super(parent, monitor);
        if(activityInputFactory == null){
        	activityInputFactory = ActivityEditorInputFactory.getDefaultInstance();
        }
    }

    public AllActivityModifier(Subsystem_c parent, IProgressMonitor monitor){
    	super(parent, monitor);
        if(activityInputFactory == null){
        	activityInputFactory = ActivityEditorInputFactory.getDefaultInstance();
        }
    }

    public AllActivityModifier(FunctionPackage_c parent, IProgressMonitor monitor){
    	super(parent, monitor);
        if(activityInputFactory == null){
        	activityInputFactory = ActivityEditorInputFactory.getDefaultInstance();
        }
    }

    public AllActivityModifier(ExternalEntityPackage_c parent, IProgressMonitor monitor){
    	super(parent, monitor);
        if(activityInputFactory == null){
        	activityInputFactory = ActivityEditorInputFactory.getDefaultInstance();
        }
    }

    public AllActivityModifier(ModelRoot modelRoot, Object[] activities, IProgressMonitor monitor)
    {
    	super(modelRoot, activities, monitor);
        if(activityInputFactory == null){
        	activityInputFactory = ActivityEditorInputFactory.getDefaultInstance();
        }
    }

    public AllActivityModifier(NonRootModelElement parent, IProgressMonitor monitor)
    {
    	super(parent, monitor);
        if(activityInputFactory == null){
        	activityInputFactory = ActivityEditorInputFactory.getDefaultInstance();
        }
    }

    public void processAllActivities(int op, boolean disposeBeforeParse, boolean includeSharedFragments) {

		PlaceHolderManager placeHolderManager = PlaceHolderManager.getDefaultInstance();
		placeHolderManager.setParseInProgress(true);

    	super.processAllActivities(op, disposeBeforeParse, includeSharedFragments);

    	placeHolderManager.setParseInProgress(false);
    }

    public void parseAction(Object modelElement)
    {
    	if(!activityInputFactory.isSupported(modelElement)){
    		return;
        }

        int toParse = AllActivityModifier.accessSuc_Pars( false, 0, modelElement );
        if ( toParse == Parsestatus_c.doNotParse )
        {
        	if (modelElement instanceof ProvidedOperation_c) {
        		((ProvidedOperation_c)modelElement).Initializeunparsed();
        	}
        	else if (modelElement instanceof RequiredOperation_c) {
        		((RequiredOperation_c)modelElement).Initializeunparsed();
        	}
        	else if (modelElement instanceof ProvidedSignal_c) {
        		((ProvidedSignal_c)modelElement).Initializeunparsed();
        	}
        	else if (modelElement instanceof RequiredSignal_c) {
        		((RequiredSignal_c)modelElement).Initializeunparsed();
        	}
            return;
        }

       	ActivityEditorInput editorInput = null;
       	try {
			editorInput = (ActivityEditorInput)activityInputFactory.createInstance(modelElement);
		} catch (CoreException e) {
			//TODO: Log exception when test code introduced by 561-2 is fixed
			return;
		}

        final DocumentProvider dp = new DocumentProvider();
        try {
            dp.connect( editorInput );
            dp.resetDocument( editorInput );
        }
        catch ( CoreException ce )
        {
            return;   // ignore
        }
        ActivityAnnotationModel m_myAnnotationModel = (ActivityAnnotationModel)dp.getAnnotationModel(editorInput);
        m_myAnnotationModel.connect(dp.getDocument(editorInput));

        parseRunner.m_ae_input = editorInput;
        parseRunner.m_document = dp.getDocument(editorInput);
        parseRunner.m_myAnnotationModel = m_myAnnotationModel;
        parseRunner.m_modelElement = (NonRootModelElement)modelElement;
        parseRunner.run();

        //
        // doSaveDocument will do the correct thing
        //    to update the Suc_Pars attribute
        //    if the editor was open or not
        //    if there were previously errors or not
    	doSaveDocument(editorInput, dp);
    	dp.disconnect(editorInput);
        if ( m_pm != null ) {
        	m_pm.worked(1);
            UIUtil.dispatchAll();
        }
    }

    private void doSaveDocument(ActivityEditorInput aei, final DocumentProvider dp) {
		class DocumentDirtyStateChanged implements IElementStateListener {
			public void elementDirtyStateChanged(Object element, boolean isDirty) {
				if (!isDirty) {
					ActivityEditorInput aei = (ActivityEditorInput) element;
					dp.getAnnotationModel(aei).disconnect(dp.getDocument(aei));
					dp.removeElementStateListener(this);

				}
			}

			public void elementContentAboutToBeReplaced(Object element) {
			}
			public void elementContentReplaced(Object element) {
			}
			public void elementDeleted(Object element) {
			}
			public void elementMoved(Object originalElement, Object movedElement) {
			}
		}
		DocumentDirtyStateChanged listener = new DocumentDirtyStateChanged();
		dp.addElementStateListener(listener);
		try {
            aei.doSaveDocument(new NullProgressMonitor(), aei.getModelElement(), dp.getDocument(aei), true);
		    dp.saveDocument(new NullProgressMonitor(), aei, dp.getDocument(aei), true);
		}
		catch ( CoreException ce3 )
		{
		    // ignore
		}
	}

	@Override
    public void clearActionPlaceholder(Object o_input)
    {
    	if(!activityInputFactory.isSupported(o_input)){
    		return;
        }

    	NonRootModelElement modelElement = (NonRootModelElement)o_input;
		ModelElementID modelElementID = ModelAdapter.getModelElementAdapter(modelElement).createModelElementID(modelElement);

    	IFile placeHolderFile = PlaceHolderManager.getDefaultInstance().getPlaceholderFile(modelElementID,
    			ActivityEditorInputFactory.PLACEHOLDER_EXTENSION, this, false);

    	if(placeHolderFile != null && placeHolderFile.exists()){

    		try {
				placeHolderFile.deleteMarkers(IMarker.PROBLEM, true, IResource.DEPTH_ZERO);
			} catch (CoreException e) {
				TextPlugin.logError("Error while clearing markers", e); //$NON-NLS-1$
			}

    		PlaceHolderManager.getDefaultInstance().releasePlaceholderFile(modelElementID,
        			ActivityEditorInputFactory.PLACEHOLDER_EXTENSION, this);
    	}
        if ( m_pm != null ) m_pm.worked(1);
    }
}


text:
package no.kjelli.pong.gameobjects.particles;

import no.kjelli.generic.gamewrapper.GameWrapper;
import no.kjelli.generic.gfx.AbstractParticle;
import no.kjelli.generic.gfx.Draw;
import no.kjelli.generic.tweens.GameObjectAccessor;
import no.kjelli.pong.gameobjects.Ball;

import org.newdawn.slick.Color;

import aurelienribon.tweenengine.Tween;
import aurelienribon.tweenengine.equations.Expo;
import aurelienribon.tweenengine.equations.Quad;

public class BallParticleReverse extends AbstractParticle {
	public static final float SPEED = 5f;
	public static final long TIME_TO_LIVE_MAX = 80;
	public Color color;

	public BallParticleReverse(Ball ball) {
		super(ball.getX() - (SPEED * 0.1f * TIME_TO_LIVE_MAX), ball.getY()
				- (SPEED * 0.1f * TIME_TO_LIVE_MAX), ball.getZ(), ball
				.getWidth() + SPEED * 0.2f * TIME_TO_LIVE_MAX, ball.getHeight()
				+ SPEED * 0.2f * TIME_TO_LIVE_MAX, TIME_TO_LIVE_MAX);
		this.color = new Color(ball.getColor());
	}

	@Override
	public void onCreate() {
		super.onCreate();
		int dir = (int) Math.floor(Math.random() * 2) * 2 - 1;
		Tween.to(this, GameObjectAccessor.ROTATION, 1000).target(dir*360)
				.ease(aurelienribon.tweenengine.equations.Circ.OUT)
				.start(GameWrapper.tweenManager);
	}

	@Override
	public void updateParticle() {
		width -= 0.2 * SPEED;
		velocity_x = 0.1 * SPEED;
		height -= 0.2 * SPEED;
		velocity_y = 0.1 * SPEED;
		color.a = 1.0f - (float) timeToLive / TIME_TO_LIVE_MAX;
		move();
	}

	@Override
	public void draw() {
		Draw.rect(this, color);
	}

}


text:
<?php

namespace OC\User;

use OC\Files\Cache\Storage;
use OC\Hooks\Emitter;
use OC\User\Manager;
use OCP\IURLGenerator;
use OCP\IUser;
use OCP\IConfig;
use OCP\Files\NotFoundException;

/**
 * Class representing a deleted user.
 * This class is intended to be used internally.
 */
class DeletedUser implements IUser {
	/** @var Emitter */
	private $emitter;
	/** @var IConfig */
	private $config;
	/** @var IURLGenerator */
	private $urlGenerator;
	/** @var string */
	private $uid;

	public function __construct(Manager $userManager, IConfig $config, IURLGenerator $urlGenerator, $uid) {
		$this->emitter = $userManager;  // use the userManager as event emitter
		// this is required because there could be listeners listening in the
		// userManager class, and we want to trigger the same
		// (this behaviour is copied from \OC\User\Manager::getUserObject)
		$this->config = $config;
		$this->urlGenerator = $urlGenerator;
		$this->uid = $uid;
	}

	public function getAccountId() {
		return $this->uid;
	}

	/**
	 * @return string
	 */
	public function getUID() {
		return $this->uid;
	}

	/**
	 * @return string
	 */
	public function getUserName() {
		return $this->config->getUserValue($this->uid, 'core', 'username', $this->uid);
	}

	public function setUserName($userName) {
		throw new \Exception("Not Implemented", 1);
	}

	/**
	 * Return the uid as displayname. Consider the account table's information deleted.
	 * @return string
	 */
	public function getDisplayName() {
		return $this->uid;
	}

	public function setDisplayName($displayName) {
		throw new \Exception("Not Implemented", 1);
	}

	/**
	 * Consider the user didn't login (return 0)
	 * @return int
	 */
	public function getLastLogin() {
		return 0;
	}

	/**
	 * Match \OC\User\User implementation returning true on first update, but
	 * don't do anything
	 */
	public function updateLastLoginTimestamp() {
		return true;
	}

	/**
	 * This is mostly copied from \OC\User\User, but taking into account the
	 * account info is missing
	 */
	public function delete() {
		if ($this->emitter) {
			$this->emitter->emit('\OC\User', 'preDelete', [$this]);
		}

		// account deletion in the backend must have been performed out of here, otherwise
		// we shouldn't have reached this point. Skip the account deletion in the backend

		// FIXME: Feels like an hack - suggestions?

		// We have to delete the user from all groups
		foreach (\OC::$server->getGroupManager()->getUserGroups($this) as $group) {
			$group->removeUser($this);
		}
		// Delete the user's keys in preferences
		\OC::$server->getConfig()->deleteAllUserValues($this->getUID());

		// Delete all mount points for user
		\OC::$server->getUserStoragesService()->deleteAllMountsForUser($this);
		//Delete external storage or remove user from applicableUsers list
		\OC::$server->getGlobalStoragesService()->deleteAllForUser($this);

		// Delete user files in /data/
		try {
			$userFolder = \OC::$server->getRootFolder()->get("/{$this->uid}");
			$userFolder->delete();
		} catch (NotFoundException $e) {
			// Do nothing if the folder doesn't exist
		}

		// Delete the users entry in the storage table
		Storage::remove('home::' . $this->getUID());
		Storage::remove('object::user:' . $this->getUID());

		\OC::$server->getCommentsManager()->deleteReferencesOfActor('users', $this->getUID());
		\OC::$server->getCommentsManager()->deleteReadMarksFromUser($this);

		if ($this->emitter) {
			$this->emitter->emit('\OC\User', 'postDelete', [$this]);
		}
		return true;
	}

	public function setPassword($password, $recoveryPassword = null) {
		throw new \Exception("Not Implemented", 1);
	}

	public function getHome() {
		throw new \Exception("Not Implemented", 1);
	}

	public function getBackendClassName() {
		throw new \Exception("Not Implemented", 1);
	}

	public function canChangeAvatar() {
		return false;
	}

	public function canChangePassword() {
		return false;
	}

	public function canChangeDisplayName() {
		return false;
	}

	public function isEnabled() {
		return false;
	}

	public function setEnabled($enabled) {
		throw new \Exception("Not Implemented", 1);
	}

	/**
	 * @return string|null
	 */
	public function getEMailAddress() {
		return null;
	}

	public function getAvatarImage($size) {
		throw new \Exception("Not Implemented", 1);
	}

	public function getCloudId() {
		$server = $this->urlGenerator->getAbsoluteURL('/');
		return $this->uid . '@' . \rtrim($this->removeProtocolFromUrl($server), '/');
	}

	/**
	 * Copied from \OC\User\User
	 */
	private function removeProtocolFromUrl($url) {
		if (\strpos($url, 'https://') === 0) {
			return \substr($url, \strlen('https://'));
		} elseif (\strpos($url, 'http://') === 0) {
			return \substr($url, \strlen('http://'));
		}

		return $url;
	}

	public function setEMailAddress($mailAddress) {
		throw new \Exception("Not Implemented", 1);
	}

	public function getQuota() {
		return 'default';
	}

	public function setQuota($quota) {
		throw new \Exception("Not Implemented", 1);
	}

	public function setSearchTerms(array $terms) {
		throw new \Exception("Not Implemented", 1);
	}

	public function getSearchTerms() {
		return [];
	}
}


text:
package eu.scape_project.watch.adaptor.c3po.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import eu.scape_project.watch.adaptor.c3po.common.C3POResponseParser;
import eu.scape_project.watch.adaptor.c3po.common.ProductionProfileStrategy;
import eu.scape_project.watch.adaptor.c3po.common.ProfileVersionReader;
import eu.scape_project.watch.utils.exceptions.PluginException;

/**
 * The c3po client connects to a c3po instance and fetches a profile for the
 * specified collection.
 *
 * @author Petar Petrov <me@petarpetrov.org>
 *
 */
public class C3POClient implements C3POClientInterface {

  /**
   * A default logger.
   */
  private static final Logger LOG = LoggerFactory.getLogger(C3POClient.class);

  /**
   * A short timeout interval for the requests. Amounts to 30 seconds.
   */
  private static final int SHORT_TIMEOUT_INTERVAL = 1000 * 30;

  /*
   * This 10 minute read timeout is used for the getProfile requests. It works
   * for now as the collections are of reasonable size and 10 minutes are
   * sufficient to generate the profile (if this is the first generation
   * request). Even if it occurs, the profile still gets generated and cached on
   * the server, so it will be obtained on the next request. A better solution
   * is of course to support polling on the server side and ask for the status
   * of the generation as initially planned.
   */
  /**
   * A longer timeout interval for the requests. Amounts to 10 minutes.
   */
  protected static final int LONG_TIMEOUT_INTERVAL = 1000 * 60 * 10;

  /**
   * The endpoint of the c3po service.
   */
  protected String apiEndpoint;

  /**
   * The port of the service.
   */
  protected int port;

  public C3POClient() {
  }

  /**
   * Creates a client and sets the endpoint.
   *
   * @param url
   *          the endpoint to use in the client.
   */
  public C3POClient(final String url) {
    this.apiEndpoint = url;
  }

  /**
   * Creates a client and sets the endpoint to the specified url with the
   * specified port in the following form: 'url:port'.
   *
   * @param url
   *          the url of the endpoint.
   * @param port
   *          the port where the service is running.
   */
  public C3POClient(final String url, final int port, final String endpoint) {

    this.apiEndpoint = url;

    if (port >= 0 && port <= 65535) {
      this.port = port;
      this.apiEndpoint = this.apiEndpoint + ":" + port;
    }

    if (endpoint != null) {
      if (endpoint.startsWith("/")) {
        this.apiEndpoint = this.apiEndpoint + endpoint;
      } else {
        this.apiEndpoint = this.apiEndpoint + "/" + endpoint;
      }
    }
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public List<String> getCollectionIdentifiers() throws PluginException {
    final List<String> result = new ArrayList<String>();

    try {
      final String response = this.submitRequest("/collections");

      final C3POResponseParser reader = new C3POResponseParser();
      final List<String> collections = reader.getCollectionsFromResponse(IOUtils.toInputStream(response));

      if (collections == null) {
        throw new PluginException("Could not read response: " + response);
      }

      result.addAll(collections);
    } catch (final ProtocolException e) {
      LOG.error("A protocol error occurred: {}", e.getMessage());
      throw new PluginException("A protocol error occurred (check the url)", e);

    } catch (final IOException e) {
      LOG.error("An io error occurred: {}", e.getMessage());
      throw new PluginException("A io exception occurred (check the connection)", e);
    }

    return result;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public InputStream getCollectionProfile(final String identifier, final Map<String, String> parameters)
    throws PluginException {
    try {
      final String response = this.submitRequest("/export/profile?collection=" + identifier, LONG_TIMEOUT_INTERVAL);

      if (response == null || response.equals("")) {
        throw new PluginException("Bad response from server [" + this.apiEndpoint + "]. Check the logs and retry");
      } else {
        return IOUtils.toInputStream(response);
      }

    } catch (final ProtocolException e) {
      LOG.error("A protocol error occurred: {}", e.getMessage());
      throw new PluginException("A protocol error occurred (check the url)", e);

    } catch (final IOException e) {
      LOG.error("An io error occurred: {}", e.getMessage());
      throw new PluginException("A io exception occurred (check the connection)", e);
    }
  }

  @Override
  public ProfileVersionReader getReader() {
    return new ProductionProfileStrategy();
  }

  /**
   * This method is deprecated and no longer supported.
   *
   * @return throws exception.
   */
  @Override
  @Deprecated
  public String submitCollectionProfileJob(final String identifier, final List<String> properties) {
    throw new UnsupportedOperationException("This method is deprecated and not supported anymore");
  }

  /**
   * This method is deprecated and no longer supported.
   *
   * @return throws exception.
   */
  @Override
  @Deprecated
  public InputStream pollJobResult(final String uuid) {
    throw new UnsupportedOperationException("This method is deprecated and not supported anymore");
  }

  public String getApiEndpoint() {
    return apiEndpoint;
  }

  public void setApiEndpoint(final String apiEndpoint) {
    this.apiEndpoint = apiEndpoint;
  }

  public int getPort() {
    return port;
  }

  public void setPort(final int port) {
    this.port = port;
  }

  /**
   * Submits a c3po request with a short read timeout.
   *
   * @param request
   *          the request to submit.
   * @return the response as a string.
   * @throws IOException
   *           if an error occurs.
   */
  protected String submitRequest(final String request) throws IOException {
    return this.submitRequest(request, SHORT_TIMEOUT_INTERVAL);
  }

  /**
   * Submits a c3po request with the given read timeout.
   *
   * @param request
   *          the request to submit.
   * @return the response as a string.
   * @throws IOException
   *           if an error occurs.
   */
  protected String submitRequest(final String request, final int readTimeOut) throws IOException {
    LOG.debug("Submitting request to c3po: {}", request);

    final URL location = new URL(this.apiEndpoint + request);
    final HttpURLConnection connection = (HttpURLConnection) location.openConnection();

    connection.setDoInput(true);
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Accept", "application/xml");
    connection.setConnectTimeout(SHORT_TIMEOUT_INTERVAL);
    connection.setReadTimeout(readTimeOut);

    return this.readResponse(connection);
  }

  /**
   * Reads the response from the {@link URLConnection}.
   *
   * @param connection
   *          the connection through which the query was made.
   * @return the response as a String.
   */
  protected String readResponse(final URLConnection connection) {
    final StringBuffer response = new StringBuffer("");
    BufferedReader in = null;
    String result = "";
    try {
      in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
      String str;

      while (null != ((str = in.readLine()))) {
        response.append(str + System.getProperty("line.separator"));
      }

      result = response.toString();
      LOG.debug("Received response from c3po: {}", result.substring(0, result.indexOf("\n")) + "... ");
      LOG.trace(result);

    } catch (final IOException e) {
      LOG.error("An error occurred while reading the response", e);

    } finally {
      try {
        if (in != null) {
          in.close();
        }
      } catch (final IOException e) {
        LOG.error("An error occurred while closing the input stream");
      }
    }

    return result;

  }
}


text:
package org.marssa.footprint.datatypes.decimal.volume;

import static javax.measure.unit.NonSI.LITRE;

import java.math.MathContext;

import javax.persistence.Entity;
import javax.xml.bind.annotation.XmlType;

import org.hibernate.annotations.ForeignKey;
import org.marssa.footprint.datatypes.TypeFactory;
import org.marssa.footprint.exceptions.OutOfRange;

@XmlType(name = "Litres", factoryClass = TypeFactory.class, factoryMethod = "getLitresInstance")
@Entity
@ForeignKey(name = "FK_Litres_MDecimal")
public class Litres extends AVolume {

	/**
	 *
	 */
	private static final long serialVersionUID = -7698732720745652902L;

	public Litres(double value) throws OutOfRange {
		super(value, LITRE);
	}
	public Litres(double value, MathContext mc) throws OutOfRange {
		super(value, LITRE, mc);
	}
}


text:
import { Subject } from 'rxjs';
import { filter } from 'rxjs/operators';

export enum LogLevel {
	TRACE,
	DEBUG,
	INFO,
	WARN,
	ERROR,
	FATAL
}

export type Log = { level: LogLevel, operation: () => void };

export class Logger {
	public static LEVEL: LogLevel = LogLevel.DEBUG;
	logs: Subject<{
		level: LogLevel,
		operation: () => void;
	}>;
	prefix: string;

	constructor(prefix: string) {
		this.logs = new Subject();
		this.prefix = prefix;
		this.logs.pipe(filter((log: Log) => log.level >= Logger.LEVEL))
			.subscribe((log) => log.operation());
	}

	trace(msg: string, ...params: Array<any>) {
		this.logs.next({
			level: LogLevel.TRACE,
			operation: () => console.trace(this.prefix + msg, ...params)
		});
	}

	debug(msg: string, ...params: Array<any>) {
		this.logs.next({
			level: LogLevel.DEBUG,
			operation: () => console.log(this.prefix + msg, ...params)
		});
	}

	info(msg: string, ...params: Array<any>) {
		this.logs.next({
			level: LogLevel.INFO,
			operation: () => console.info(this.prefix + msg, ...params)
		});
	}

	warn(msg: string, ...params: Array<any>) {
		this.logs.next({
			level: LogLevel.WARN,
			operation: () => console.warn(this.prefix + msg, ...params)
		});
	}

	error(msg: string, ...params: Array<any>) {
		this.logs.next({
			level: LogLevel.ERROR,
			operation: () => console.error(this.prefix + msg, ...params)
		});
	}
}


text:
package org.apache.wicket.request.parameter;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.List;

import org.apache.wicket.request.Url;
import org.apache.wicket.util.string.StringValue;
import org.junit.jupiter.api.Test;

/**
 * @since 1.5.5
 */
public class CombinedRequestParametersAdapterTest
{
	/**
	 * Tests that org.apache.wicket.request.parameter.CombinedRequestParametersAdapter#getParameterValues(java.lang.String)
	 * will return all values for a given parameter by name.
	 *
	 * https://issues.apache.org/jira/browse/WICKET-4417
	 *
	 * @throws Exception
	 */
	@Test
	public void getParameterValuesSameNameSameValue() throws Exception
	{
		Url url = Url.parse("?param1=value1&param1=value1");
		UrlRequestParametersAdapter urlAdapter = new UrlRequestParametersAdapter(url);
		CombinedRequestParametersAdapter adapter = new CombinedRequestParametersAdapter(urlAdapter);

		List<StringValue> values = adapter.getParameterValues("param1");
		assertEquals(2, values.size());
	}
}


text:
<?php

namespace ByTIC\Payments\Actions\Subscriptions\Charges;

use ByTIC\Payments\Models\Subscriptions\Subscription;

/**
 * Class CalculateNextAttempt
 * @package ByTIC\Payments\Actions\Subscriptions\Charges
 */
class CalculateNextAttempt
{
    /**
     * @param Subscription $subscription
     */
    public static function for($subscription)
    {
        $count = $subscription->charge_attempts > 0 ? $subscription->charge_attempts : 1;
        $subscription->charge_at = static::nextAttempt(
            $subscription->charge_at,
            $count
        );
    }

    /**
     * @param \DateTime $startDate
     * @param $period
     * @param $interval
     */
    protected static function nextAttempt(\DateTime $lastAttempt, $tries)
    {
        switch ($tries) {
            case 1:
                return $lastAttempt->addHours(3);

            case 2:
                return $lastAttempt->addHours(12);

            case 3:
                return $lastAttempt->addDays(1);

            case 4:
                return $lastAttempt->addDays(2);
        }
        return $lastAttempt->addDays($tries - 2);
    }
}


text:
"""Test that each script can be compiled and executed."""
#
# (C) Pywikibot team, 2014
#
# Distributed under the terms of the MIT license.
#
from __future__ import print_function, unicode_literals
__version__ = '$Id$'

import os
import sys

from pywikibot import config

from tests import _root_dir
from tests.aspects import unittest, DefaultSiteTestCase, MetaTestCaseClass, PwbTestCase
from tests.utils import allowed_failure, execute_pwb, add_metaclass

if sys.version_info[0] > 2:
    basestring = (str, )

scripts_path = os.path.join(_root_dir, 'scripts')

# These dependencies are not always the package name which is in setup.py.
# e.g. 'PIL.ImageTk' is a object provided by several different pypi packages,
# and setup.py requests that 'Pillow' is installed to provide 'PIL.ImageTk'.
# Here, it doesnt matter which pypi package was requested and installed.
# Here, the name given to the module which will be imported is required.
script_deps = {
    'script_wui': ['crontab', 'lua'],
    # Note: package 'lunatic-python' provides module 'lua'

    'flickrripper': ['flickrapi'],
    'match_images': ['PIL.ImageTk'],
    'states_redirect': ['pycountry'],
    'patrol': ['mwlib'],
}

if sys.version_info < (2, 7):
    script_deps['replicate_wiki'] = ['argparse']
    script_deps['editarticle'] = ['argparse']

if sys.version_info < (3, 0):
    script_deps['data_ingestion'] = ['unicodecsv']

def check_script_deps(script_name):
    """Detect whether all dependencies are installed."""
    if script_name in script_deps:
        for package_name in script_deps[script_name]:
            try:
                __import__(package_name)
            except ImportError as e:
                print('%s depends on %s, which isnt available:\n%s'
                      % (script_name, package_name, e))
                return False
    return True

failed_dep_script_list = [name
                          for name in script_deps
                          if not check_script_deps(name)]

unrunnable_script_list = [
    'script_wui',   # depends on lua compiling
]

script_list = (['login'] +
               [name[0:-3] for name in os.listdir(scripts_path)  # strip '.py'
                if name.endswith('.py') and
                not name.startswith('_') and  # skip __init__.py and _*
                name != 'login.py'        # this is moved to be first
                ]
               )

runnable_script_list = (['login'] +
                        sorted(set(script_list) -
                               set(['login']) -
                               set(unrunnable_script_list)))

script_input = {
    'catall': 'q\n',  # q for quit
    'editarticle': 'Test page\n',
    'imageuncat': 'q\n',
    'interwiki': 'Test page that should not exist\n',
    'misspelling': 'q\n',
    'pagefromfile': 'q\n',
    'replace': 'foo\nbar\n\n\n',  # match, replacement,
                                  # Enter to begin, Enter for default summary.
    'shell': '\n',  # exits on end of stdin
    'solve_disambiguation': 'Test page\nq\n',
    'upload': 'https://upload.wikimedia.org/wikipedia/commons/8/80/Wikipedia-logo-v2.svg\n\n\n',
}

auto_run_script_list = [
    'blockpageschecker',
    'blockreview',
    'casechecker',
    'catall',
    'category_redirect',
    'cfd',
    'checkimages',
    'clean_sandbox',
    'disambredir',
    'imagerecat',
    'login',
    'lonelypages',
    'misspelling',
    'revertbot',
    'noreferences',
    'nowcommons',
    'patrol',
    'script_wui',
    'shell',
    'states_redirect',
    'unusedfiles',
    'upload',
    'watchlist',
    'welcome',
]

# Expected result for no arguments
# Some of these are not pretty, but at least they are informative
# and not backtraces starting deep in the pywikibot package.
no_args_expected_results = {
    'archivebot': 'NOTE: you must specify a template to run the bot',
    'create_categories': 'No pages to work on',
    # TODO: until done here, remember to set editor = None in user_config.py
    'editarticle': 'Nothing changed',  # This masks related bug 68645 but that
                                       # bug is more broadly about config
                                       # rather than editarticle.
    'freebasemappingupload': 'Cannot find ',
    'harvest_template': 'ERROR: Please specify',
    'illustrate_wikidata': 'I need a generator with pages to work on',
    'imageuncat': 'WARNING: This script is primarily written for Wikimedia Commons',
    # script_input['interwiki'] above lists a title that should not exist
    'interwiki': 'does not exist. Skipping.',
    'login': 'Logged in on ',
    'match_images': 'Require two images to work on.',
    'pagefromfile': 'Please enter the file name',
    'replace': 'Press Enter to use this automatic message',
    'script_wui': 'Pre-loading all relevant page contents',
    'shell': ('>>> ', 'Welcome to the'),
    'spamremove': 'No spam site specified',
    'transferbot': 'Target site not different from source site',  # Bug 68662
    'unusedfiles': ('Working on', None),
    'version': 'unicode test: ',
    'watchlist': 'Retrieving watchlist',

    # The following auto-run and typically cant be validated,
    # however these strings are very likely to exist within
    # the timeout of 5 seconds.
    'revertbot': 'Fetching new batch of contributions',
    'upload': 'ERROR: Upload error',
}

if sys.version_info[0] > 2:
    no_args_expected_results['replicate_wiki'] = 'error: the following arguments are required: destination'
else:
    no_args_expected_results['replicate_wiki'] = 'error: too few arguments'

enable_autorun_tests = (
    os.environ.get('PYWIKIBOT2_TEST_AUTORUN', '0') == '1')

def collector(loader=unittest.loader.defaultTestLoader):
    """Load the default tests."""
    # Note: Raising SkipTest during load_tests will
    # cause the loader to fallback to its own
    # discover() ordering of unit tests.

    if unrunnable_script_list:
        print('Skipping execution of unrunnable scripts:\n  %r'
              % unrunnable_script_list)

    if not enable_autorun_tests:
        print('Skipping execution of auto-run scripts '
              '(set PYWIKIBOT2_TEST_AUTORUN=1 to enable):\n  %r'
              % auto_run_script_list)

    tests = (['test__login_help'] +
             ['test_' + name + '_help'
              for name in sorted(script_list)
              if name != 'login'] +
             ['test__login_simulate'])

    tests += ['test_' + name + '_simulate'
              for name in sorted(script_list)
              if name != 'login' and
              name not in failed_dep_script_list and
              name not in unrunnable_script_list and
              (enable_autorun_tests or name not in auto_run_script_list)]

    test_list = ['tests.script_tests.TestScript.' + name
                 for name in tests]

    tests = loader.loadTestsFromNames(test_list)
    suite = unittest.TestSuite()
    suite.addTests(tests)
    return suite

def load_tests(loader=unittest.loader.defaultTestLoader,
               tests=None, pattern=None):
    """Load the default modules."""
    return collector(loader)

class TestScriptMeta(MetaTestCaseClass):

    """Test meta class."""

    def __new__(cls, name, bases, dct):
        """Create the new class."""
        def test_execution(script_name, args=[], expected_results=None):
            is_autorun = '-help' not in args and script_name in auto_run_script_list

            def test_skip_script(self):
                raise unittest.SkipTest(
                    'Skipping execution of auto-run scripts (set '
                    'PYWIKIBOT2_TEST_AUTORUN=1 to enable) "{0}"'.format(script_name))

            def testScript(self):
                cmd = [script_name]

                if args:
                    cmd += args

                data_in = script_input.get(script_name)

                timeout = 0
                if is_autorun:
                    timeout = 5

                if expected_results and script_name in expected_results:
                    error = expected_results[script_name]
                    if isinstance(error, basestring):
                        stdout = None
                    else:
                        stdout, error = error
                else:
                    stdout = None
                    error = None

                result = execute_pwb(cmd, data_in, timeout=timeout, error=error)

                stderr = result['stderr'].split('\n')
                stderr_sleep = [l for l in stderr
                                if l.startswith('Sleeping for ')]
                stderr_other = [l for l in stderr
                                if not l.startswith('Sleeping for ')]
                if stderr_sleep:
                    print(u'\n'.join(stderr_sleep))

                if result['exit_code'] == -9:
                    print(' killed', end='  ')

                if error:
                    self.assertIn(error, result['stderr'])

                    exit_codes = [0, 1, 2, -9]
                elif not is_autorun:
                    if stderr_other == ['']:
                        stderr_other = None
                    self.assertIsNone(stderr_other)
                    self.assertIn('Global arguments available for all',
                                  result['stdout'])

                    exit_codes = [0]
                else:
                    # auto-run
                    exit_codes = [0, -9]

                    if (not result['stdout'] and not result['stderr']):
                        print(' auto-run script unresponsive after %d seconds'
                              % timeout, end=' ')
                    elif 'SIMULATION: edit action blocked' in result['stderr']:
                        print(' auto-run script simulated edit blocked',
                              end='  ')
                    else:
                        print(' auto-run script stderr within %d seconds: %r'
                              % (timeout, result['stderr']), end='  ')

                self.assertNotIn('Traceback (most recent call last)',
                                 result['stderr'])
                self.assertNotIn('deprecated', result['stderr'].lower())

                # If stdout doesnt include global help..
                if 'Global arguments available for all' not in result['stdout']:
                    # Specifically look for deprecated
                    self.assertNotIn('deprecated', result['stdout'].lower())
                    if result['stdout'] == '':
                        result['stdout'] = None
                    # But also complain if there is any stdout
                    if stdout is not None and result['stdout'] is not None:
                        self.assertIn(stdout, result['stdout'])
                    else:
                        self.assertIsNone(result['stdout'])

                self.assertIn(result['exit_code'], exit_codes)

                sys.stdout.flush()

            if not enable_autorun_tests and is_autorun:
                return test_skip_script
            return testScript

        for script_name in script_list:
            # force login to be the first, alphabetically, so the login
            # message does not unexpectedly occur during execution of
            # another script.
            # unrunnable script tests are disabled by default in load_tests()

            if script_name == 'login':
                test_name = 'test__' + script_name + '_help'
            else:
                test_name = 'test_' + script_name + '_help'
            # it's explicitly using str() because __name__ must be str
            test_name = str(test_name)
            dct[test_name] = test_execution(script_name, ['-help'])
            if script_name in ['version',
                               'script_wui',      # Failing on travis-ci
                               ] + failed_dep_script_list:
                dct[test_name] = unittest.expectedFailure(dct[test_name])
            dct[test_name].__doc__ = 'Test running ' + script_name + ' -help'
            dct[test_name].__name__ = test_name

            # Ideally all scripts should execute -help without
            # connecting to a site.
            # TODO: after bug 68611 and 68664 (and makecat), split -help
            # execution to a separate test class which uses site=False.

            if script_name == 'login':
                test_name = 'test__' + script_name + '_simulate'
            else:
                test_name = 'test_' + script_name + '_simulate'
            # it's explicitly using str() because __name__ must be str
            test_name = str(test_name)
            dct[test_name] = test_execution(script_name, ['-simulate'],
                                            no_args_expected_results)
            if script_name in ['catall',          # stdout user interaction
                               'flickrripper',    # Requires a flickr api key
                               'script_wui',      # Error on any user except DrTrigonBot
                               'upload',          # raises custom ValueError
                               ] + failed_dep_script_list or (
                    (config.family == 'wikipedia' and script_name == 'disambredir') or
                    (config.family != 'wikidata' and script_name == 'checkimages') or
                    (config.family == 'wikipedia' and config.mylang != 'en' and script_name == 'misspelling')):  # T94681
                dct[test_name] = unittest.expectedFailure(dct[test_name])
            elif script_name in ['watchlist',     # T77965
                                 'lonelypages',   # uses exit code 1; T94680
                                 ]:
                dct[test_name] = allowed_failure(dct[test_name])
            dct[test_name].__doc__ = \
                'Test running ' + script_name + ' -simulate.'
            dct[test_name].__name__ = test_name

            # Disable test by default in nosetests
            if script_name in unrunnable_script_list:
                dct[test_name].__test__ = False

            # TODO: Ideally any script not on the auto_run_script_list
            # can be set as 'not a site' test, but that will require
            # auditing all code in main() to ensure it exits without
            # connecting to a site.  There are outstanding bugs about
            # connections during initialisation.
            #
            # dct[test_name].site = True

        return super(TestScriptMeta, cls).__new__(cls, name, bases, dct)

@add_metaclass
class TestScript(DefaultSiteTestCase, PwbTestCase):

    """Test cases for scripts.

    This class sets the nose 'user' attribute on every test, thereby ensuring
    that the test runner has a username for the default site, and so that
    Site.login() is called in the test runner, which means that the scripts
    run in pwb can automatically login using the saved cookies.
    """

    __metaclass__ = TestScriptMeta

    user = True

if __name__ == '__main__':
    try:
        unittest.main()
    except SystemExit:
        pass


text:
package atc

type SetPinCommentRequestBody struct {
	PinComment string `json:"pin_comment"`
}


text:
package hcache.io;

import hcache.io.CdbWriter.CdbHashPointer;

import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.util.UUID;

import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.io.Writable;

import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;

/**
 * Cuts memory usage by 1/256 by writing hash buckets to disk instead of
 * aggregating in memory, then reading/writing one set of buckets at a time to
 * complete the file.
 *
 * @author jay
 *
 * @param <K>
 * @param <V>
 */
public class BigCdbWriter<K extends Writable, V extends Writable> implements
    Closeable {
  // number of slots in the slot table
  // should take the form of 2^x
  public static final int SLOTSIZE = 4096;
  // all 1's, so (n & MAGIC == n % SLOTSIZE)
  public static final int MAGIC = 4095;
  // TODO make SLOTSIZE and MAGIC

  private final Class<K> keyClass;
  private final Class<V> valueClass;
  private final FSDataOutputStream out;

  /*
   * New code: we have 256 slotfiles, and keep a count of how many total entries
   * are in each. later, we reread
   */
  private static final int SLOTFILES = 256;
  private static final int SLOTFMAGIC = 255;
  private static final File tempDir = new File(System.getProperty("cdb.tmpdir",
      "/tmp"));
  private final UUID id;
  private final FSDataOutputStream[] slotsOut = new FSDataOutputStream[SLOTFILES];
  private final File[] slotFiles = new File[SLOTFILES];
  private final int[] entriesPerFile = new int[SLOTFILES];

  /** The number of entries in each hash table. */
  private final int[] tableCount;

  public BigCdbWriter(OutputStream out, Class<K> keyClass, Class<V> valueClass)
      throws IOException {
    this(new FSDataOutputStream(out, null), keyClass, valueClass);
  }

  public BigCdbWriter(FSDataOutputStream out, Class<K> keyClass,
      Class<V> valueClass) throws IOException {
    this.out = out;
    // todo need SLOTSIZE and MAGIC
    this.tableCount = new int[SLOTSIZE];
    this.keyClass = keyClass;
    this.valueClass = valueClass;
    /* Records can't be at position zero, so write one filler byte */
    out.write((byte) -1);
    // initialize slotfiles
    this.id = UUID.randomUUID();
    for (int i = 0; i < SLOTFILES; i++) {
      File slotFile = new File(tempDir, id.toString() + "-" + i);
      slotFiles[i] = slotFile;
      FSDataOutputStream slotOut = new FSDataOutputStream(
          (OutputStream)
          new BufferedOutputStream(
              new FileOutputStream(slotFile)
              ),null);
      slotsOut[i] = slotOut;
    }
  }

  public void write(K key, V value) throws IOException {
    long recordPos = out.getPos();
    /* Write out the key and data . */
    key.write(out);
    value.write(out);
    /* Add the hash pointer to our list. */
    int hash = hash(key);
    /* Add this item to the count. */
    tableCount[(hash & MAGIC)]++;

    // Write to it's slotfile.. this will be re-read and consolidated
    // upon close()
    int slotIdx = hash&SLOTFMAGIC;
    entriesPerFile[slotIdx]++;
    new CdbHashPointer(hash, recordPos).write(slotsOut[slotIdx]);

  }

  public void close() throws IOException {
    // flush outfiles
    for (OutputStream out : slotsOut) {
      out.close();
    }
    // read each slotfile and write its contents, keeping track
    // of slot positions as we go
    long[] slotPos = new long[SLOTSIZE];
    int[] slotLen = new int[SLOTSIZE];
    for (int i = 0 ; i < SLOTFILES ; i++) {
      System.err.println("file " + i);
      int numEntries = entriesPerFile[i];
      SeekableInputStream in =
        new SeekableInputStream(
            new RandomAccessFile(slotFiles[i],"r").getChannel(),
            0,
            ByteBuffer.allocate(8192));
      Multimap<Integer,CdbHashPointer> slots = HashMultimap.create();
      long fileLength = slotFiles[i].length();
      for (int j = 0 ; j < numEntries ; j++) {
        CdbHashPointer row = new CdbHashPointer(0,0);
        row.readFields(in);
        slots.put(row.hash&MAGIC, row);
      }
      // read all, close and delete file
      in.close();
      slotFiles[i].delete();
      for ( int slot : slots.keySet()) {
        long pos = out.getPos();
        int len = tableCount[slot];
        // update footer values
        slotPos[slot] = pos;
        slotLen[slot] = len;
        // build/write the slot table
        CdbHashPointer[] hashTable = new CdbHashPointer[len];
        for (CdbHashPointer hp : slots.get(slot)) {
          /* Locate a free space in the hash table. */
          int where = (hp.hash >>> 8) % len;
          while (hashTable[where] != null)
            if (++where == len)
              where = 0;
          /* Store the hash pointer. */
          hashTable[where] = hp;
        }
        // ok now write it
        for (int j = 0 ; j < len ; j++) {
          hashTable[j].write(out);
        }
      }
    }

    /* Append the slot table as the last few kb of file. */
    for (int i = 0; i < SLOTSIZE; i++) {
      out.writeLong(slotPos[i]);
      out.writeInt(slotLen[i]);
    }

    /* Close the file. */
    out.close();
  }

  // same as HashPartitioner
  static int hash(Writable h) {
    return h.hashCode() & Integer.MAX_VALUE;
  }

}


text:
<!DOCTYPE html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <title></title>
</head>
<body>
  <script>
    document.body.style.backgroundColor = 'rgb(240, 240, 240)';
  </script>
</body>
</html>


text:
from sqlobject import *
from sqlobject.tests.dbtest import *
from test_basic import TestSO1, setupGetters

########################################
## Delete during select
########################################

def testSelect():
    setupGetters(TestSO1)
    for obj in TestSO1.select('all'):
        obj.destroySelf()
    assert list(TestSO1.select('all')) == []

########################################
## Delete many rows at once
########################################

def testDeleteMany():
    setupGetters(TestSO1)
    TestSO1.deleteMany(OR(TestSO1.q.name=="bob", TestSO1.q.name=="fred"))
    assert len(list(TestSO1.select('all'))) == 2

def testDeleteBy():
    setupGetters(TestSO1)
    TestSO1.deleteBy(name="dave")
    assert len(list(TestSO1.select())) == 3

########################################
## Delete without caching
########################################

class NoCache(SQLObject):
    name = StringCol()

def testDestroySelf():
    setupClass(NoCache)
    old = NoCache._connection.cache
    NoCache._connection.cache = cache.CacheSet(cache=False)
    value = NoCache(name='test')
    value.destroySelf()
    NoCache._connection.cache = old

########################################
## Delete from related joins
########################################

class Service(SQLObject):
    groups = RelatedJoin("ServiceGroup")

class ServiceGroup(SQLObject):
    services = RelatedJoin("Service")

def testDeleteRelatedJoins():
    setupClass([Service, ServiceGroup])
    service = Service()
    service_group = ServiceGroup()
    service.addServiceGroup(service_group)
    service.destroySelf()
    service_group = ServiceGroup.get(service_group.id)
    assert len(service_group.services) == 0


text:
package io.sarl.lang.codebuilder.appenders;

import io.sarl.lang.codebuilder.builders.ISarlAgentBuilder;
import io.sarl.lang.codebuilder.builders.ISarlAnnotationTypeBuilder;
import io.sarl.lang.codebuilder.builders.ISarlArtifactBuilder;
import io.sarl.lang.codebuilder.builders.ISarlBehaviorBuilder;
import io.sarl.lang.codebuilder.builders.ISarlCapacityBuilder;
import io.sarl.lang.codebuilder.builders.ISarlClassBuilder;
import io.sarl.lang.codebuilder.builders.ISarlEnumerationBuilder;
import io.sarl.lang.codebuilder.builders.ISarlEventBuilder;
import io.sarl.lang.codebuilder.builders.ISarlInterfaceBuilder;
import io.sarl.lang.codebuilder.builders.ISarlSkillBuilder;
import io.sarl.lang.codebuilder.builders.ISarlSpaceBuilder;
import io.sarl.lang.codebuilder.builders.IScriptBuilder;
import io.sarl.lang.sarl.SarlScript;
import java.io.IOException;
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.xtext.common.types.JvmParameterizedTypeReference;
import org.eclipse.xtext.common.types.access.IJvmTypeProvider;
import org.eclipse.xtext.xbase.compiler.ISourceAppender;
import org.eclipse.xtext.xbase.lib.Pure;

/** Appender of Sarl scripts.
 *
 */
@SuppressWarnings("all")
public class ScriptSourceAppender extends AbstractSourceAppender implements IScriptBuilder {

	private IScriptBuilder builder;

	/** Find the reference to the type with the given name.
	 * @param typeName the fully qualified name of the type
	 * @return the type reference.
	 */
	public JvmParameterizedTypeReference newTypeRef(String typeName) {
		return this.builder.newTypeRef(typeName);
	}

	/** Find the reference to the type with the given name.
	 * @param context the context for the type reference use
	 * @param typeName the fully qualified name of the type
	 * @return the type reference.
	 */
	public JvmParameterizedTypeReference newTypeRef(Notifier context, String typeName) {
		return this.builder.newTypeRef(context, typeName);
	}

	public IJvmTypeProvider getTypeResolutionContext() {
		return this.builder.getTypeResolutionContext();
	}

	public ScriptSourceAppender(IScriptBuilder builder) {
		this.builder = builder;
	}

	public void build(ISourceAppender appender) throws IOException {
		if (!isFinalized()) {
			finalizeScript();
		}
		build(this.builder.getScript(), appender);
	}

	/** Create the internal Sarl script.
	 */
	public void eInit(Resource resource, String packageName, IJvmTypeProvider context) {
		this.builder.eInit(resource, packageName, context);
	}

	/** Replies the Sarl script.
	 */
	@Pure
	public SarlScript getScript() {
		return this.builder.getScript();
	}

	/** Replies the resource to which the script is attached.
	 */
	@Pure
	public Resource eResource() {
		return getScript().eResource();
	}

	/** Finalize the script.
	 *
	 *
The finalization includes:

	 *
The import section is created.

	 *

	 */
	public void finalizeScript() {
		this.builder.finalizeScript();
	}

	/** Replies if the script was finalized.
	 */
	public boolean isFinalized() {
		return this.builder.isFinalized();
	}

	@Override
	@Pure
	public String toString() {
		return this.builder.toString();
	}

	/** Create a SarlEvent builder.
	 * @param name - the name of the SarlEvent.
	 * @return the builder.
	 */
	public ISarlEventBuilder addSarlEvent(String name) {
		 return this.builder.addSarlEvent(name);
	}

	/** Create a SarlCapacity builder.
	 * @param name - the name of the SarlCapacity.
	 * @return the builder.
	 */
	public ISarlCapacityBuilder addSarlCapacity(String name) {
		 return this.builder.addSarlCapacity(name);
	}

	/** Create a SarlAgent builder.
	 * @param name - the name of the SarlAgent.
	 * @return the builder.
	 */
	public ISarlAgentBuilder addSarlAgent(String name) {
		 return this.builder.addSarlAgent(name);
	}

	/** Create a SarlBehavior builder.
	 * @param name - the name of the SarlBehavior.
	 * @return the builder.
	 */
	public ISarlBehaviorBuilder addSarlBehavior(String name) {
		 return this.builder.addSarlBehavior(name);
	}

	/** Create a SarlSkill builder.
	 * @param name - the name of the SarlSkill.
	 * @return the builder.
	 */
	public ISarlSkillBuilder addSarlSkill(String name) {
		 return this.builder.addSarlSkill(name);
	}

	/** Create a SarlSpace builder.
	 * @param name - the name of the SarlSpace.
	 * @return the builder.
	 */
	public ISarlSpaceBuilder addSarlSpace(String name) {
		 return this.builder.addSarlSpace(name);
	}

	/** Create a SarlArtifact builder.
	 * @param name - the name of the SarlArtifact.
	 * @return the builder.
	 */
	public ISarlArtifactBuilder addSarlArtifact(String name) {
		 return this.builder.addSarlArtifact(name);
	}

	/** Create a SarlClass builder.
	 * @param name - the name of the SarlClass.
	 * @return the builder.
	 */
	public ISarlClassBuilder addSarlClass(String name) {
		 return this.builder.addSarlClass(name);
	}

	/** Create a SarlInterface builder.
	 * @param name - the name of the SarlInterface.
	 * @return the builder.
	 */
	public ISarlInterfaceBuilder addSarlInterface(String name) {
		 return this.builder.addSarlInterface(name);
	}

	/** Create a SarlEnumeration builder.
	 * @param name - the name of the SarlEnumeration.
	 * @return the builder.
	 */
	public ISarlEnumerationBuilder addSarlEnumeration(String name) {
		 return this.builder.addSarlEnumeration(name);
	}

	/** Create a SarlAnnotationType builder.
	 * @param name - the name of the SarlAnnotationType.
	 * @return the builder.
	 */
	public ISarlAnnotationTypeBuilder addSarlAnnotationType(String name) {
		 return this.builder.addSarlAnnotationType(name);
	}

}