text:
\hypertarget{classmmasgis_1_1Filter_1_1Filter}{
\section{mmasgis::Filter::Filter Class Reference}
\label{classmmasgis_1_1Filter_1_1Filter}\index{mmasgis::Filter::Filter@{mmasgis::Filter::Filter}}
}
\subsection*{Public Member Functions}
\begin{DoxyCompactItemize}
\item
def \hyperlink{classmmasgis_1_1Filter_1_1Filter_aa286331e2f7ea07b388ef2e80bb7f19d}{\_\-\_\-repr\_\-\_\-}
\item
def \hyperlink{classmmasgis_1_1Filter_1_1Filter_a09c5ab11d9ca8ad6cf82c116903dc766}{\_\-\_\-init\_\-\_\-}
\item
def \hyperlink{classmmasgis_1_1Filter_1_1Filter_a3a749922f6fafac6754f721a7bbe1385}{unpackParameter}
\item
def \hyperlink{classmmasgis_1_1Filter_1_1Filter_a62594f25ca5126737af8eb0fa9941c0c}{save}
\item
def \hyperlink{classmmasgis_1_1Filter_1_1Filter_a54b15fff49eee15194c015a94a654e8f}{test}
\item
def \hyperlink{classmmasgis_1_1Filter_1_1Filter_a3a3258ebcde4ce2f9509bb4f5bdd9da0}{checkTab}
\end{DoxyCompactItemize}
\subsection*{Public Attributes}
\begin{DoxyCompactItemize}
\item
\hyperlink{classmmasgis_1_1Filter_1_1Filter_a12729c4683da208f75a21ad58cc19be5}{db}
\item
\hyperlink{classmmasgis_1_1Filter_1_1Filter_a2a2eee1ab8629d4d4d7a7f584d1f6e58}{Dbquery}
\item
\hyperlink{classmmasgis_1_1Filter_1_1Filter_a3fd36908d325f1493eb8460c431e8ae5}{parameters}
\item
\hyperlink{classmmasgis_1_1Filter_1_1Filter_adedd3507f6aded578277cb77c8444ee4}{tab}
\end{DoxyCompactItemize}

\subsection{Detailed Description}
\begin{DoxyVerb}
permette di definire una serie di condizioni che il pv deve soddisfare, il metodo test applicato
sul singolo pv verifica che questo le rispetti, in particolare la logica dei filtri prevede che
piu' parametri della stessa classe siano  in OR mentre parametri di classi differenti devono
essere in AND
\end{DoxyVerb}

\subsection{Constructor \& Destructor Documentation}
\hypertarget{classmmasgis_1_1Filter_1_1Filter_a09c5ab11d9ca8ad6cf82c116903dc766}{
\index{mmasgis::Filter::Filter@{mmasgis::Filter::Filter}!\_\-\_\-init\_\-\_\-@{\_\-\_\-init\_\-\_\-}}
\index{\_\-\_\-init\_\-\_\-@{\_\-\_\-init\_\-\_\-}!mmasgis::Filter::Filter@{mmasgis::Filter::Filter}}
\subsubsection[{\_\-\_\-init\_\-\_\-}]{\setlength{\rightskip}{0pt plus 5cm}def mmasgis::Filter::Filter::\_\-\_\-init\_\-\_\- (
\begin{DoxyParamCaption}
\item[{}]{self, }
\item[{}]{parametri, }
\item[{}]{tab, }
\item[{}]{db}
\end{DoxyParamCaption}
)}}
\label{classmmasgis_1_1Filter_1_1Filter_a09c5ab11d9ca8ad6cf82c116903dc766}
\begin{DoxyVerb}
@param parametri: [{int:[int]}]::[{class_id:[parameter_id]}] setting del filtro
@param tab: string chiave del Filtro
@param db:queriesDb, stessa istanza di QueriesDb usata da interrogazioni savequery e loadQuery
\end{DoxyVerb}

\subsection{Member Function Documentation}
\hypertarget{classmmasgis_1_1Filter_1_1Filter_aa286331e2f7ea07b388ef2e80bb7f19d}{
\index{mmasgis::Filter::Filter@{mmasgis::Filter::Filter}!\_\-\_\-repr\_\-\_\-@{\_\-\_\-repr\_\-\_\-}}
\index{\_\-\_\-repr\_\-\_\-@{\_\-\_\-repr\_\-\_\-}!mmasgis::Filter::Filter@{mmasgis::Filter::Filter}}
\subsubsection[{\_\-\_\-repr\_\-\_\-}]{\setlength{\rightskip}{0pt plus 5cm}def mmasgis::Filter::Filter::\_\-\_\-repr\_\-\_\- (
\begin{DoxyParamCaption}
\item[{}]{self}
\end{DoxyParamCaption}
)}}
\label{classmmasgis_1_1Filter_1_1Filter_aa286331e2f7ea07b388ef2e80bb7f19d}
\hypertarget{classmmasgis_1_1Filter_1_1Filter_a3a3258ebcde4ce2f9509bb4f5bdd9da0}{
\index{mmasgis::Filter::Filter@{mmasgis::Filter::Filter}!checkTab@{checkTab}}
\index{checkTab@{checkTab}!mmasgis::Filter::Filter@{mmasgis::Filter::Filter}}
\subsubsection[{checkTab}]{\setlength{\rightskip}{0pt plus 5cm}def mmasgis::Filter::Filter::checkTab (
\begin{DoxyParamCaption}
\item[{}]{self, }
\item[{}]{Id, }
\item[{}]{tab, }
\item[{}]{d}
\end{DoxyParamCaption}
)}}
\label{classmmasgis_1_1Filter_1_1Filter_a3a3258ebcde4ce2f9509bb4f5bdd9da0}
\begin{DoxyVerb}
esegue i filtri appartenenti ad un tab
@param Id::int pv_id
@param tab:string specifica il tab di cui eseguire i filtri 'marchi',parametri','potenziali'
@param d:{int:[int]}::{class_id:[parameter_id]}
@return boolean: il valore ritornato e' l'operazione di AND tra i check per ogni classe
\end{DoxyVerb}
 \hypertarget{classmmasgis_1_1Filter_1_1Filter_a62594f25ca5126737af8eb0fa9941c0c}{
\index{mmasgis::Filter::Filter@{mmasgis::Filter::Filter}!save@{save}}
\index{save@{save}!mmasgis::Filter::Filter@{mmasgis::Filter::Filter}}
\subsubsection[{save}]{\setlength{\rightskip}{0pt plus 5cm}def mmasgis::Filter::Filter::save (
\begin{DoxyParamCaption}
\item[{}]{self, }
\item[{}]{Id}
\end{DoxyParamCaption}
)}}
\label{classmmasgis_1_1Filter_1_1Filter_a62594f25ca5126737af8eb0fa9941c0c}
\begin{DoxyVerb}
salva i parametri del filtro sul dbusando come chiave esterna lo id della query
@param Id:int:: query_id
\end{DoxyVerb}
 \hypertarget{classmmasgis_1_1Filter_1_1Filter_a54b15fff49eee15194c015a94a654e8f}{
\index{mmasgis::Filter::Filter@{mmasgis::Filter::Filter}!test@{test}}
\index{test@{test}!mmasgis::Filter::Filter@{mmasgis::Filter::Filter}}
\subsubsection[{test}]{\setlength{\rightskip}{0pt plus 5cm}def mmasgis::Filter::Filter::test (
\begin{DoxyParamCaption}
\item[{}]{self, }
\item[{}]{Id}
\end{DoxyParamCaption}
)}}
\label{classmmasgis_1_1Filter_1_1Filter_a54b15fff49eee15194c015a94a654e8f}
\begin{DoxyVerb}
esegue il test definito dai parametri del filtro sul pv con pv_id Id
@param Id::int pv_id
@return boolean
\end{DoxyVerb}
 \hypertarget{classmmasgis_1_1Filter_1_1Filter_a3a749922f6fafac6754f721a7bbe1385}{
\index{mmasgis::Filter::Filter@{mmasgis::Filter::Filter}!unpackParameter@{unpackParameter}}
\index{unpackParameter@{unpackParameter}!mmasgis::Filter::Filter@{mmasgis::Filter::Filter}}
\subsubsection[{unpackParameter}]{\setlength{\rightskip}{0pt plus 5cm}def mmasgis::Filter::Filter::unpackParameter (
\begin{DoxyParamCaption}
\item[{}]{self, }
\item[{}]{d}
\end{DoxyParamCaption}
)}}
\label{classmmasgis_1_1Filter_1_1Filter_a3a749922f6fafac6754f721a7bbe1385}
\begin{DoxyVerb}ritorna una versione dei parametri del filtro "scompattata", cioe' nel formato[(int,int)]::[(category_id,parameter_id)],
perche' sia compatibile con le funzioni di queriesDb
@return: [(int,int)]::[(category_id,parameter_id)]
\end{DoxyVerb}

\subsection{Member Data Documentation}
\hypertarget{classmmasgis_1_1Filter_1_1Filter_a12729c4683da208f75a21ad58cc19be5}{
\index{mmasgis::Filter::Filter@{mmasgis::Filter::Filter}!db@{db}}
\index{db@{db}!mmasgis::Filter::Filter@{mmasgis::Filter::Filter}}
\subsubsection[{db}]{\setlength{\rightskip}{0pt plus 5cm}{\bf mmasgis::Filter::Filter::db}}}
\label{classmmasgis_1_1Filter_1_1Filter_a12729c4683da208f75a21ad58cc19be5}
\hypertarget{classmmasgis_1_1Filter_1_1Filter_a2a2eee1ab8629d4d4d7a7f584d1f6e58}{
\index{mmasgis::Filter::Filter@{mmasgis::Filter::Filter}!Dbquery@{Dbquery}}
\index{Dbquery@{Dbquery}!mmasgis::Filter::Filter@{mmasgis::Filter::Filter}}
\subsubsection[{Dbquery}]{\setlength{\rightskip}{0pt plus 5cm}{\bf mmasgis::Filter::Filter::Dbquery}}}
\label{classmmasgis_1_1Filter_1_1Filter_a2a2eee1ab8629d4d4d7a7f584d1f6e58}
\hypertarget{classmmasgis_1_1Filter_1_1Filter_a3fd36908d325f1493eb8460c431e8ae5}{
\index{mmasgis::Filter::Filter@{mmasgis::Filter::Filter}!parameters@{parameters}}
\index{parameters@{parameters}!mmasgis::Filter::Filter@{mmasgis::Filter::Filter}}
\subsubsection[{parameters}]{\setlength{\rightskip}{0pt plus 5cm}{\bf mmasgis::Filter::Filter::parameters}}}
\label{classmmasgis_1_1Filter_1_1Filter_a3fd36908d325f1493eb8460c431e8ae5}
\hypertarget{classmmasgis_1_1Filter_1_1Filter_adedd3507f6aded578277cb77c8444ee4}{
\index{mmasgis::Filter::Filter@{mmasgis::Filter::Filter}!tab@{tab}}
\index{tab@{tab}!mmasgis::Filter::Filter@{mmasgis::Filter::Filter}}
\subsubsection[{tab}]{\setlength{\rightskip}{0pt plus 5cm}{\bf mmasgis::Filter::Filter::tab}}}
\label{classmmasgis_1_1Filter_1_1Filter_adedd3507f6aded578277cb77c8444ee4}

The documentation for this class was generated from the following file:\begin{DoxyCompactItemize}
\item
\hyperlink{Filter_8py}{Filter.py}\end{DoxyCompactItemize}


text:
<?php

class Login extends MY_Controller
{
    function index()
    {
        $this->middle = 'login_form';
        $this->layout();
    }

    function logout()
    {
        $this->session->sess_destroy();
        redirect('home');
        $this->index();
    }

    function signup()
    {
        $this->middle = 'signup_form';
        $this->layout();
    }

    function validate_credentials()
    {
        $this->load->library('form_validation');

        $this->form_validation->set_rules('email_address', 'email_address', 'trim|required');
        $this->form_validation->set_rules('password', 'password', 'trim|required');

        if ($this->form_validation->run() == FALSE) {
            $this->middle = 'login_form'; // return page will validation error
            $this->layout();
        } else {
            $this->load->model('members/member_model');
            if ($query = $this->member_model->validate()) {

                $data = array(
                    'username' => $query->username,
                    'id' => $query->id,
                    'password' => $query->password,
                    'first_name' => $query->first_name,
                    'last_name' => $query->last_name,
                    'email_address' => $query->email_address,
                    'is_logged_in' => true
                );

                $this->session->set_userdata($data);

                $this->middle = 'home_view';
                $this->layout();
            } else {
                echo '<script>alert("Incorrect Login Details, Please Try Again.");</script>';
                $this->middle = 'login_form';
                $this->layout();

            }
        }
    }

    function create_member()
    {
        $this->load->library('form_validation');

        $this->form_validation->set_rules('first_name', 'Name', 'trim|required');
        $this->form_validation->set_rules('last_name', 'Last Name', 'trim|required');
        $this->form_validation->set_rules('email_address', 'Email Address', 'trim|required|valid_email');

        $this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[4]');
        $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[4]|max_length[32]');
        $this->form_validation->set_rules('password2', 'Password Confirmation', 'trim|required|matches[password]');

        if ($this->form_validation->run() == FALSE) {
            $this->middle = 'signup_form'; // return page will validation error
            $this->layout();
        } else {
            $this->load->model('members/member_model');
            if ($query = $this->member_model->create_member()) {
                $this->middle = 'signup_successfull';
                $this->layout();
            } else {
                echo '<script>alert("Im sorry, something went wrong. Please Try Again.");</script>';
                $this->middle = 'signup_form';
                $this->layout();
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
using UnityEngine;
using System.Collections;

public class Level4 : RuleManager {

	// Use this for initialization
	void Start () {
        InitializeLevel();
        ballBody.velocity = new Vector2(0,1);
    }

	// Update is called once per frame
	void Update () {

	}
}


text:
class Supertux < Formula
  desc "Classic 2D jump'n run sidescroller game"
  homepage "https://www.supertux.org/"
  url "https://github.com/SuperTux/supertux/releases/download/v0.6.2/SuperTux-v0.6.2-Source.tar.gz"
  sha256 "26a9e56ea2d284148849f3239177d777dda5b675a10ab2d76ee65854c91ff598"
  license "GPL-3.0-or-later"
  revision 1
  head "https://github.com/SuperTux/supertux.git"

  livecheck do
    url "https://github.com/SuperTux/supertux/releases/latest"
    regex(%r{href=.*?/tag/v?(\d+(?:\.\d+)+)["' >]}i)
  end

  bottle do
    cellar :any
    sha256 "2180590875a08d8aa1a03303090ecf34ff3a01bca1084db4b0fba6437090d100" => :catalina
    sha256 "a3e03cceaedb6ab9dec08e4dc01882e259de440132d06f9c1f50cebd8b61c483" => :mojave
    sha256 "6f1c9c50af7ccbe9632e1211b81a6bef05ad7d1e0d9c5c20c88386ab3b07cc30" => :high_sierra
  end

  depends_on "cmake" => :build
  depends_on "pkg-config" => :build
  depends_on "boost"
  depends_on "freetype"
  depends_on "glew"
  depends_on "libogg"
  depends_on "libvorbis"
  depends_on "sdl2"
  depends_on "sdl2_image"
  depends_on "sdl2_mixer"

  def install
    unless build.head?
      # Fix for `external/findlocale/VERSION` is trying to be compiled (on case-insensitive FS)
      # This mimics behaviour of https://github.com/SuperTux/supertux/commit/afbae58a61abf0dab98ffe57401dead8f7f1c0dd
      # Remove in the next release
      File.rename "external/findlocale/VERSION", "external/findlocale/VERSION.txt"
    end

    ENV.cxx11

    args = std_cmake_args
    args << "-DINSTALL_SUBDIR_BIN=bin"
    args << "-DINSTALL_SUBDIR_SHARE=share/supertux"
    # Without the following option, Cmake intend to use the library of MONO framework.
    args << "-DPNG_PNG_INCLUDE_DIR=#{Formula["libpng"].opt_include}"
    system "cmake", ".", *args
    system "make", "install"

    # Remove unnecessary files
    (share/"applications").rmtree
    (share/"pixmaps").rmtree
    (prefix/"MacOS").rmtree
  end

  test do
    (testpath / "config").write "(supertux-config)"
    assert_equal "supertux2 v#{version}", shell_output("#{bin}/supertux2 --userdir #{testpath} --version").chomp
  end
end


text:
package com.java110.store.dao.impl;

import com.alibaba.fastjson.JSONObject;
import com.java110.utils.constant.ResponseConstant;
import com.java110.utils.exception.DAOException;
import com.java110.utils.util.DateUtil;
import com.java110.core.base.dao.BaseServiceDao;
import com.java110.store.dao.IStoreAdsServiceDao;
import org.slf4j.Logger;
import com.java110.core.log.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 商户广告服务 与数据库交互
 * Created by wuxw on 2017/4/5.
 */
@Service("storeAdsServiceDaoImpl")
//@Transactional
public class StoreAdsServiceDaoImpl extends BaseServiceDao implements IStoreAdsServiceDao {

    private static Logger logger = LoggerFactory.getLogger(StoreAdsServiceDaoImpl.class);

    /**
     * 保存商户广告信息 到 instance
     * @param info   bId 信息
     * @throws DAOException DAO异常
     */
    @Override
    public void saveStoreAdsInfo(Map info) throws DAOException {
        logger.debug("保存商户广告信息Instance 入参 info : {}",info);

        int saveFlag = sqlSessionTemplate.insert("storeAdsServiceDaoImpl.saveStoreAdsInfo",info);

        if(saveFlag < 1){
            throw new DAOException(ResponseConstant.RESULT_PARAM_ERROR,"保存商户广告信息Instance数据失败:"+ JSONObject.toJSONString(info));
        }
    }

    /**
     * 查询商户广告信息(instance)
     * @param info bId 信息
     * @return List<Map>
     * @throws DAOException DAO异常
     */
    @Override
    public List<Map> getStoreAdsInfo(Map info) throws DAOException {
        logger.debug("查询商户广告信息 入参 info : {}",info);

        List<Map> businessStoreAdsInfos = sqlSessionTemplate.selectList("storeAdsServiceDaoImpl.getStoreAdsInfo",info);

        return businessStoreAdsInfos;
    }

    /**
     * 修改商户广告信息
     * @param info 修改信息
     * @throws DAOException DAO异常
     */
    @Override
    public void updateStoreAdsInfo(Map info) throws DAOException {
        logger.debug("修改商户广告信息Instance 入参 info : {}",info);

        int saveFlag = sqlSessionTemplate.update("storeAdsServiceDaoImpl.updateStoreAdsInfo",info);

        if(saveFlag < 1){
            throw new DAOException(ResponseConstant.RESULT_PARAM_ERROR,"修改商户广告信息Instance数据失败:"+ JSONObject.toJSONString(info));
        }
    }

     /**
     * 查询商户广告数量
     * @param info 商户广告信息
     * @return 商户广告数量
     */
    @Override
    public int queryStoreAdssCount(Map info) {
        logger.debug("查询商户广告数据 入参 info : {}",info);

        List<Map> businessStoreAdsInfos = sqlSessionTemplate.selectList("storeAdsServiceDaoImpl.queryStoreAdssCount", info);
        if (businessStoreAdsInfos.size() < 1) {
            return 0;
        }

        return Integer.parseInt(businessStoreAdsInfos.get(0).get("count").toString());
    }

}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.media.videoanalyzer.edge.models;

import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;

/** Defines a Spatial Analysis person count operation eventing configuration. */
@Fluent
public final class SpatialAnalysisPersonCountEvent extends SpatialAnalysisOperationEventBase {
    /*
     * The event trigger type.
     */
    @JsonProperty(value = "trigger")
    private SpatialAnalysisPersonCountEventTrigger trigger;

    /*
     * The event or interval output frequency.
     */
    @JsonProperty(value = "outputFrequency")
    private String outputFrequency;

    /**
     * Get the trigger property: The event trigger type.
     *
     * @return the trigger value.
     */
    public SpatialAnalysisPersonCountEventTrigger getTrigger() {
        return this.trigger;
    }

    /**
     * Set the trigger property: The event trigger type.
     *
     * @param trigger the trigger value to set.
     * @return the SpatialAnalysisPersonCountEvent object itself.
     */
    public SpatialAnalysisPersonCountEvent setTrigger(SpatialAnalysisPersonCountEventTrigger trigger) {
        this.trigger = trigger;
        return this;
    }

    /**
     * Get the outputFrequency property: The event or interval output frequency.
     *
     * @return the outputFrequency value.
     */
    public String getOutputFrequency() {
        return this.outputFrequency;
    }

    /**
     * Set the outputFrequency property: The event or interval output frequency.
     *
     * @param outputFrequency the outputFrequency value to set.
     * @return the SpatialAnalysisPersonCountEvent object itself.
     */
    public SpatialAnalysisPersonCountEvent setOutputFrequency(String outputFrequency) {
        this.outputFrequency = outputFrequency;
        return this;
    }

    /** {@inheritDoc} */
    @Override
    public SpatialAnalysisPersonCountEvent setThreshold(String threshold) {
        super.setThreshold(threshold);
        return this;
    }

    /** {@inheritDoc} */
    @Override
    public SpatialAnalysisPersonCountEvent setFocus(SpatialAnalysisOperationFocus focus) {
        super.setFocus(focus);
        return this;
    }
}


text:
module Hutch
  module Config
    # Hutch Schedule work pool size
    number_setting :worker_pool_size, 20

    # Hutch Schedule exceeded checker and poller interval seconds
    # Hutch Worker Pool heartbeat interval (share interval config)
    number_setting :poller_interval, 1

    # Hutch Schedule poller batch size
    number_setting :poller_batch_size, 100

    # Redis url for ratelimit and unique job
    string_setting :redis_url, "redis://127.0.0.1:6379/0"

    # Ratelimit bucket interval
    number_setting :ratelimit_bucket_interval, 1

    # Ratelimit redis backend reconnect attempts
    number_setting :ratelimit_redis_reconnect_attempts, 10

    # Hutch::Worker buffer flush interval in seconds
    # 这个时间长度决定了 woker.buffer_queue 中长周期等待的任务交换给 RabbitMQ 的检查周期, 不适合太过频繁
    number_setting :worker_buffer_flush_interval, 6

    initialize(
      worker_pool_size:  20,
      poller_interval:   1,
      poller_batch_size: 100,
      # @see Redis::Client
      redis_url:                          "redis://127.0.0.1:6379/0",
      ratelimit_bucket_interval:          1,
      ratelimit_redis_reconnect_attempts: 10,
      worker_buffer_flush_interval:       6,
      # need an positive channel_prefetch
      channel_prefetch: 20
    )
    define_methods
  end
end


text:
import atexit
import contextlib
from io import StringIO, BytesIO
import os
import re
import shutil
import subprocess
import sys
import tempfile
import traceback
from unittest import TestCase

from voc.python.blocks import Block as PyBlock
from voc.python.modules import Module as PyModule
from voc.java.constants import ConstantPool, Utf8
from voc.java.klass import ClassFileReader, ClassFileWriter
from voc.java.attributes import Code as JavaCode
from voc.transpiler import Transpiler

# get path to `tests` directory
TESTS_DIR = os.path.dirname(__file__)

# A state variable to determine if the test environment has been configured.
_suite_configured = False

# Temporary directory containing all files generated by this test process
# Set during setUpSuite()
_output_dir = ''

def setUpSuite():
    """Configure the entire test suite.

    This only needs to be run once, prior to the first test.
    """
    global _output_dir
    global _suite_configured
    if _suite_configured:
        return

    _output_dir = tempfile.mkdtemp(dir=TESTS_DIR)
    os.environ['VOC_BUILD_DIR'] = os.path.join(_output_dir, 'build')
    os.environ['VOC_DIST_DIR'] = os.path.join(_output_dir, 'dist')
    proc = subprocess.Popen(
        "ant java",
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        shell=True,
    )

    try:
        out, err = proc.communicate(timeout=15)
    except subprocess.TimeoutExpired:
        proc.kill()
        out, err = proc.communicate()
        raise

    if proc.returncode != 0:
        raise Exception("Error compiling java sources: " + out.decode('ascii'))

    _suite_configured = True

    def remove_output_dir():
        global _output_dir
        shutil.rmtree(_output_dir)

    atexit.register(remove_output_dir)

@contextlib.contextmanager
def capture_output(redirect_stderr=True):
    oldout, olderr = sys.stdout, sys.stderr
    try:
        out = StringIO()
        sys.stdout = out
        if redirect_stderr:
            sys.stderr = out
        else:
            sys.stderr = StringIO()
        yield out
    except:
        if redirect_stderr:
            traceback.print_exc()
        else:
            raise
    finally:
        sys.stdout, sys.stderr = oldout, olderr

def adjust(text, run_in_function=False):
    """Adjust a code sample to remove leading whitespace."""
    lines = text.split('\n')
    if len(lines) == 1:
        return text

    if lines[0].strip() == '':
        lines = lines[1:]
    first_line = lines[0].lstrip()
    n_spaces = len(lines[0]) - len(first_line)

    if run_in_function:
        n_spaces = n_spaces - 4

    final_lines = [line[n_spaces:] for line in lines]

    if run_in_function:
        final_lines = [
            "def test_function():",
        ] + final_lines + [
            "test_function()",
        ]

    return '\n'.join(final_lines)

def runAsPython(test_dir, main_code, extra_code=None, run_in_function=False, args=None):
    """Run a block of Python code with the Python interpreter."""
    # Output source code into test directory
    with open(os.path.join(test_dir, 'test.py'), 'w') as py_source:
        py_source.write(adjust(main_code, run_in_function=run_in_function))

    if extra_code:
        for name, code in extra_code.items():
            path = name.split('.')
            path[-1] = path[-1] + '.py'
            if len(path) != 1:
                try:
                    os.makedirs(os.path.join(test_dir, *path[:-1]))
                except FileExistsError:
                    pass
            with open(os.path.join(test_dir, *path), 'w') as py_source:
                py_source.write(adjust(code))

    if args is None:
        args = []

    proc = subprocess.Popen(
        [sys.executable, "test.py"] + args,
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        cwd=test_dir,
    )
    out = proc.communicate()

    return out[0].decode('utf8')

def compileJava(java_dir, java):
    if not java:
        return None

    sources = []
    with capture_output():
        for descriptor, code in java.items():
            parts = descriptor.split('/')

            class_dir = os.path.sep.join(parts[:-1])
            class_file = os.path.join(class_dir, "%s.java" % parts[-1])

            full_dir = os.path.join(java_dir, class_dir)
            full_path = os.path.join(java_dir, class_file)

            try:
                os.makedirs(full_dir)
            except FileExistsError:
                pass

            with open(full_path, 'w') as java_source:
                java_source.write(adjust(code))

            sources.append(class_file)

    classpath = os.pathsep.join([
        os.path.join('..', 'dist', 'python-java.jar'),
        os.curdir,
    ])
    proc = subprocess.Popen(
        ["javac", "-classpath", classpath] + sources,
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        cwd=java_dir,
    )
    out = proc.communicate()

    return out[0].decode('utf8')

JAVA_EXCEPTION = re.compile(
    '(((Exception in thread "[\w-]+" )?org\.python\.exceptions\.(?P<exception1>[\w]+): (?P<message1>[^\r?\n]+))|' +
    '([^\r\n]*?\r?\n((    |\t)at[^\r\n]*?\r?\n)*' +
    'Caused by: org\.python\.exceptions\.(?P<exception2>[\w]+): (?P<message2>[^\r?\n]+)))\r?\n' +
    '(?P<trace>(\s+at .+\((((.*)(:(\d+))?)|(Native Method))\)\r?\n)+)(.*\r?\n)*' +
    '(Exception in thread "\w+" )?'
)
JAVA_STACK = re.compile('^\s+at (?P<module>.+)\((((?P<file>.*?)(:(?P<line>\d+))?)|(Native Method))\)\r?\n', re.MULTILINE)

# PYTHON_EXCEPTION = re.compile('Traceback \(most recent call last\):\n(  File ".*", line \d+, in .*\n)(    .*\n  File "(?P<file>.*)", line (?P<line>\d+), in .*\n)+(?P<exception>.*): (?P<message>.*\n)')
PYTHON_EXCEPTION = re.compile('Traceback \(most recent call last\):\r?\n(  File "(?P<file>.*)", line (?P<line>\d+), in .*\r?\n    .*\r?\n)+(?P<exception>.*?): (?P<message>.*\r?\n)')
PYTHON_STACK = re.compile('  File "(?P<file>.*)", line (?P<line>\d+), in .*\r?\n    .*\r?\n')

MEMORY_REFERENCE = re.compile('0x[\dabcdef]{4,12}')

def cleanse_java(input, substitutions):
    try:
        # Test the specific message
        out = JAVA_EXCEPTION.sub('### EXCEPTION ###{linesep}\\g<exception2>: \\g<message2>{linesep}\\g<trace>'.format(linesep=os.linesep), input)
        # Test just the exception type
        # out = JAVA_EXCEPTION.sub('### EXCEPTION ###{linesep}\\g<exception2>{linesep}\\g<trace>'.format(linesep=os.linesep), input)
    except:
        # Test the specific message
        out = JAVA_EXCEPTION.sub('### EXCEPTION ###{linesep}\\g<exception1>: \\g<message1>{linesep}\\g<trace>'.format(linesep=os.linesep), input)
        # Test just the exception type
        # out = JAVA_EXCEPTION.sub('### EXCEPTION ###{linesep}\\g<exception1>{linesep}\\g<trace>'.format(linesep=os.linesep), input)

    stack = JAVA_STACK.findall(out)
    out = JAVA_STACK.sub('', out)
    out = '%s%s%s' % (
        out,
        os.linesep.join([
            "    %s:%s" % (s[3], s[5])
            for s in stack[::-1]
            if s[0].startswith('python.') and not s[0].endswith('.<init>')
        ]),
        os.linesep if stack else ''
    )
    out = MEMORY_REFERENCE.sub("0xXXXXXXXX", out)
    out = out.replace("'python.test.__init__'", '***EXECUTABLE***').replace("'python.testdaemon.TestDaemon'", '***EXECUTABLE***')

    if substitutions:
        for to_value, from_values in substitutions.items():
            for from_value in from_values:
                out = out.replace(from_value, to_value)

    out = out.replace('\r\n', '\n')
    return out

def cleanse_python(input, substitutions):
    # Test the specific message
    out = PYTHON_EXCEPTION.sub('### EXCEPTION ###{linesep}\\g<exception>: \\g<message>'.format(linesep=os.linesep), input)
    # Test just the exception type
    # out = PYTHON_EXCEPTION.sub('### EXCEPTION ###{linesep}\\g<exception>{linesep}'.format(linesep=os.linesep), input)
    stack = PYTHON_STACK.findall(input)
    out = '%s%s%s' % (
        out,
        os.linesep.join(
            [
                "    %s:%s" % (s[0], s[1])
                for s in stack
            ]
        ),
        os.linesep if stack else ''
    )
    out = MEMORY_REFERENCE.sub("0xXXXXXXXX", out)
    out = out.replace("'test.py'", '***EXECUTABLE***')

    # Python 3.4.4 changed the message describing strings in exceptions
    out = out.replace(
        'argument must be a string or',
        'argument must be a string, a bytes-like object or'
    )

    if substitutions:
        for to_value, from_values in substitutions.items():
            for from_value in from_values:
                out = out.replace(from_value, to_value)

    out = out.replace('\r\n', '\n')
    return out

class TranspileTestCase(TestCase):

    @classmethod
    def setUpClass(cls):
        global _output_dir
        setUpSuite()
        cls.temp_dir = os.path.join(_output_dir, 'temp')
        classpath = os.path.join('dist', 'python-java-testdaemon.jar')
        cls.jvm = subprocess.Popen(
            ["java", "-classpath", classpath, "python.testdaemon.TestDaemon"],
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            cwd=_output_dir,
        )

    @classmethod
    def tearDownClass(cls):
        if cls.jvm is not None:
            # use communicate here to wait for process to exit
            cls.jvm.communicate("exit".encode("utf-8"))

    def assertBlock(self, python, java):
        self.maxDiff = None
        dump = False

        py_block = PyBlock(parent=PyModule('test', 'test.py'))
        if python:
            python = adjust(python)
            code = compile(python, '<test>', 'exec')
            py_block.extract(code, debug=dump)

        java_code = py_block.transpile()

        out = BytesIO()
        constant_pool = ConstantPool()
        java_code.resolve(constant_pool)

        constant_pool.add(Utf8('test'))
        constant_pool.add(Utf8('Code'))
        constant_pool.add(Utf8('LineNumberTable'))

        writer = ClassFileWriter(out, constant_pool)
        java_code.write(writer)

        debug = StringIO()
        reader = ClassFileReader(BytesIO(out.getbuffer()), constant_pool, debug=debug)
        JavaCode.read(reader, dump=0)

        if dump:
            print(debug.getvalue())

        java = adjust(java)
        self.assertEqual(debug.getvalue(), java[1:])

    def assertCodeExecution(
            self, code,
            message=None,
            extra_code=None,
            run_in_global=True, run_in_function=True,
            args=None, substitutions=None):
        "Run code as native python, and under Java and check the output is identical"
        self.maxDiff = None
        #==================================================
        # Pass 1 - run the code in the global context
        #==================================================
        if run_in_global:
            try:
                self.makeTempDir()
                # Run the code as Python and as Java.
                py_out = runAsPython(self.temp_dir, code, extra_code, False, args=args)
                java_out = self.runAsJava(code, extra_code, False, args=args)
            except Exception as e:
                self.fail(e)
            finally:
                # Clean up the test directory where the class file was written.
                shutil.rmtree(self.temp_dir)
                # print(java_out)

            # Cleanse the Python and Java output, producing a simple
            # normalized format for exceptions, floats etc.
            java_out = cleanse_java(java_out, substitutions)
            py_out = cleanse_python(py_out, substitutions)

            # Confirm that the output of the Java code is the same as the Python code.
            if message:
                context = 'Global context: %s' % message
            else:
                context = 'Global context'
            self.assertEqual(java_out, py_out, context)

        #==================================================
        # Pass 2 - run the code in a function's context
        #==================================================
        if run_in_function:
            try:
                self.makeTempDir()
                # Run the code as Python and as Java.
                py_out = runAsPython(self.temp_dir, code, extra_code, True, args=args)
                java_out = self.runAsJava(code, extra_code, True, args=args)
            except Exception as e:
                self.fail(e)
            finally:
                # Clean up the test directory where the class file was written.
                shutil.rmtree(self.temp_dir)
                # print(java_out)

            # Cleanse the Python and Java output, producing a simple
            # normalized format for exceptions, floats etc.
            java_out = cleanse_java(java_out, substitutions)
            py_out = cleanse_python(py_out, substitutions)

            # Confirm that the output of the Java code is the same as the Python code.
            if message:
                context = 'Function context: %s' % message
            else:
                context = 'Function context'
            self.assertEqual(java_out, py_out, context)

    def assertJavaExecution(
                self, code, out,
                extra_code=None, java=None,
                run_in_global=True, run_in_function=True,
                args=None, substitutions=None):
        """Run code under Java and check the output is as expected"""
        global _output_dir
        self.maxDiff = None
        try:
            #==================================================
            # Prep - compile any required Java sources
            #==================================================
            # Create the temp directory into which code will be placed
            java_dir = os.path.join(_output_dir, 'java')

            try:
                os.makedirs(java_dir)
            except FileExistsError:
                pass

            # Compile the java support code
            java_compile_out = compileJava(java_dir, java)

            if java_compile_out:
                self.fail(java_compile_out)

            # Cleanse the Python output, producing a simple
            # normalized format for exceptions, floats etc.
            py_out = adjust(out)

            #==================================================
            # Pass 1 - run the code in the global context
            #==================================================
            if run_in_global:
                try:
                    self.makeTempDir()
                    # Run the code as Java.
                    java_out = self.runAsJava(code, extra_code, False, args=args)
                except Exception as e:
                    self.fail(e)
                finally:
                    # Clean up the test directory where the class file was written.
                    shutil.rmtree(self.temp_dir)
                    # print(java_out)

                # Cleanse the Java output, producing a simple
                # normalized format for exceptions, floats etc.
                java_out = cleanse_java(java_out, substitutions)

                # Confirm that the output of the Java code is the same as the Python code.
                self.assertEqual(java_out, py_out, 'Global context')

            #==================================================
            # Pass 2 - run the code in a function's context
            #==================================================
            if run_in_function:
                try:
                    self.makeTempDir()
                    # Run the code as Java.
                    java_out = self.runAsJava(code, extra_code, True, args=args)
                except Exception as e:
                    self.fail(e)
                finally:
                    # Clean up the test directory where the class file was written.
                    shutil.rmtree(self.temp_dir)
                    # print(java_out)

                # Cleanse the Java output, producing a simple
                # normalized format for exceptions, floats etc.
                java_out = cleanse_java(java_out, substitutions)

                # Confirm that the output of the Java code is the same as the Python code.
                self.assertEqual(java_out, py_out, 'Function context')

        finally:
            # Clean up the java directory where the class file was written.
            if os.path.exists(java_dir):
                shutil.rmtree(java_dir)

    def makeTempDir(self):
        """Create a "temp" subdirectory in the class's generated temporary directory if it doesn't currently exist."""
        try:
            os.mkdir(self.temp_dir)
        except FileExistsError:
            pass

    def runAsJava(self, main_code, extra_code=None, run_in_function=False, args=None):
        """Run a block of Python code as a Java program."""
        # Output source code into test directory
        transpiler = Transpiler(verbosity=0)

        # Don't redirect stderr; we want to see any errors from the transpiler
        # as top level test failures.
        with capture_output(redirect_stderr=False):
            transpiler.transpile_string("test.py", adjust(main_code, run_in_function=run_in_function))

            if extra_code:
                for name, code in extra_code.items():
                    transpiler.transpile_string("%s.py" % name.replace('.', os.path.sep), adjust(code))

        transpiler.write(self.temp_dir)

        if args is None:
            args = []

        if len(args) == 0:
            # encode to turn str into bytes-like object
            self.jvm.stdin.write(("python.test.__init__\n").encode("utf-8"))
            self.jvm.stdin.flush()
            out = ""
            while True:
                try:
                    line = self.jvm.stdout.readline().decode("utf-8")
                    if line == ".{0}".format(os.linesep):
                        break
                    else:
                        out += line
                except IOError:
                    continue
        else:
            classpath = os.pathsep.join([
                os.path.join('..', 'dist', 'python-java.jar'),
                os.path.join('..', 'java'),
                os.curdir,
            ])
            proc = subprocess.Popen(
                ["java", "-classpath", classpath, "python.test.__init__"] + args,
                stdin=subprocess.PIPE,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT,
                cwd=self.temp_dir
            )
            out = proc.communicate()[0].decode('utf8')

        return out

SAMPLE_DATA = {
    'bool': [
            'True',
            'False',
        ],
    'bytearray': [
            'bytearray()',
            'bytearray(1)',
            'bytearray([1, 2, 3])',
        ],
    'bytes': [
            "b''",
            "b'This is another string of bytes'",
        ],
    'class': [
            'type(1)',
            'type("a")',
            'type(object())',
            'type("MyClass", (object,), {})',
        ],
    'complex': [
            '1j',
            '1+2j',
            '-5j',
        ],
    'dict': [
            "{}",
            "{'a': 1, 'c': 2.3456, 'd': 'another'}",
        ],
    'float': [
            '2.3456',
            '0.0',
            '-3.14159',
        ],
    'frozenset': [
            'frozenset([1, 2])',
            'frozenset()',
        ],
    'int': [
            '3',
            '0',
            '-5',
        ],
    'list': [
            "[]",
            "[3, 4, 5]",
            '[1, 2, 3, 4, 5]',
            "['a','b','c']",
        ],
    'set': [
            "set()",
            "{1, 2.3456, 'another'}",
        ],
    'str': [
            '""',
            '"This is another string"',
            '"One arg: %s"',
            '"Three args: %s | %s | %s"',
        ],
    'tuple': [
            "(1, 2)",
            "(3, 1.2, True, )",
            "(1, 2.3456, 'another')",
        ],
    'None': [
            'None',
        ],
    'NotImplemented': [
            'NotImplemented',
        ],
}

SAMPLE_SUBSTITUTIONS = {
    # Normalize set ordering
    "{1, 2.3456, 'another'}": [
        "{1, 'another', 2.3456}",
        "{2.3456, 1, 'another'}",
        "{2.3456, 'another', 1}",
        "{'another', 1, 2.3456}",
        "{'another', 2.3456, 1}",
    ],
    "{'a', 'b', 'c'}": [
        "{'a', 'c', 'b'}",
        "{'b', 'a', 'c'}",
        "{'b', 'c', 'a'}",
        "{'c', 'a', 'b'}",
        "{'c', 'b', 'a'}",
    ],
    # Normalize dictionary ordering
    "{'a': 1, 'c': 2.3456, 'd': 'another'}": [
        "{'a': 1, 'd': 'another', 'c': 2.3456, }",
        "{'c': 2.3456, 'd': 'another', 'a': 1}",
        "{'c': 2.3456, 'a': 1, 'd': 'another'}",
        "{'d': 'another', 'a': 1, 'c': 2.3456}",
        "{'d': 'another', 'c': 2.3456}, 'a': 1",
    ],
}

def _unary_test(test_name, operation):
    def func(self):
        for value in SAMPLE_DATA[self.data_type]:
            self.assertUnaryOperation(
                x=value,
                operation=operation,
                format=self.format,
                substitutions=SAMPLE_SUBSTITUTIONS
            )
    return func

class UnaryOperationTestCase:
    format = ''

    def run(self, result=None):
        # Override the run method to inject the "expectingFailure" marker
        # when the test case runs.
        for test_name in dir(self):
            if test_name.startswith('test_'):
                expect_failure = hasattr(self, 'not_implemented') and test_name in self.not_implemented
                getattr(self, test_name).__dict__['__unittest_expecting_failure__'] = expect_failure
        return super().run(result=result)

    def assertUnaryOperation(self, **kwargs):
        self.assertCodeExecution("""
            x = %(x)s
            print(%(format)s%(operation)sx)
            """ % kwargs)

    test_unary_positive = _unary_test('test_unary_positive', '+')
    test_unary_negative = _unary_test('test_unary_negative', '-')
    test_unary_not = _unary_test('test_unary_not', 'not ')
    test_unary_invert = _unary_test('test_unary_invert', '~')

def _binary_test(test_name, operation, examples):
    def func(self):
        for value in SAMPLE_DATA[self.data_type]:
            for example in examples:
                self.assertBinaryOperation(
                    x=value,
                    y=example,
                    operation=operation,
                    format=self.format,
                    substitutions=SAMPLE_SUBSTITUTIONS
                )
    return func

class BinaryOperationTestCase:
    format = ''
    y = 3

    def run(self, result=None):
        # Override the run method to inject the "expectingFailure" marker
        # when the test case runs.
        for test_name in dir(self):
            if test_name.startswith('test_'):
                getattr(self, test_name).__dict__['__unittest_expecting_failure__'] = test_name in self.not_implemented
        return super().run(result=result)

    def assertBinaryOperation(self, **kwargs):
        substitutions = kwargs.pop('substitutions')
        self.assertCodeExecution(
            """
            x = %(x)s
            y = %(y)s
            print(%(format)s%(operation)s)
            """ % kwargs, "Error running %(operation)s with x=%(x)s and y=%(y)s" % kwargs,
            substitutions=substitutions
        )

    for datatype, examples in SAMPLE_DATA.items():
        vars()['test_add_%s' % datatype] = _binary_test('test_add_%s' % datatype, 'x + y', examples)
        vars()['test_subtract_%s' % datatype] = _binary_test('test_subtract_%s' % datatype, 'x - y', examples)
        vars()['test_multiply_%s' % datatype] = _binary_test('test_multiply_%s' % datatype, 'x * y', examples)
        vars()['test_floor_divide_%s' % datatype] = _binary_test('test_floor_divide_%s' % datatype, 'x // y', examples)
        vars()['test_true_divide_%s' % datatype] = _binary_test('test_true_divide_%s' % datatype, 'x / y', examples)
        vars()['test_modulo_%s' % datatype] = _binary_test('test_modulo_%s' % datatype, 'x % y', examples)
        vars()['test_power_%s' % datatype] = _binary_test('test_power_%s' % datatype, 'x ** y', examples)
        vars()['test_subscr_%s' % datatype] = _binary_test('test_subscr_%s' % datatype, 'x[y]', examples)
        vars()['test_lshift_%s' % datatype] = _binary_test('test_lshift_%s' % datatype, 'x << y', examples)
        vars()['test_rshift_%s' % datatype] = _binary_test('test_rshift_%s' % datatype, 'x >> y', examples)
        vars()['test_and_%s' % datatype] = _binary_test('test_and_%s' % datatype, 'x & y', examples)
        vars()['test_xor_%s' % datatype] = _binary_test('test_xor_%s' % datatype, 'x ^ y', examples)
        vars()['test_or_%s' % datatype] = _binary_test('test_or_%s' % datatype, 'x | y', examples)

        vars()['test_lt_%s' % datatype] = _binary_test('test_lt_%s' % datatype, 'x < y', examples)
        vars()['test_le_%s' % datatype] = _binary_test('test_le_%s' % datatype, 'x <= y', examples)
        vars()['test_gt_%s' % datatype] = _binary_test('test_gt_%s' % datatype, 'x > y', examples)
        vars()['test_ge_%s' % datatype] = _binary_test('test_ge_%s' % datatype, 'x >= y', examples)
        vars()['test_eq_%s' % datatype] = _binary_test('test_eq_%s' % datatype, 'x == y', examples)
        vars()['test_ne_%s' % datatype] = _binary_test('test_ne_%s' % datatype, 'x != y', examples)

def _inplace_test(test_name, operation, examples):
    def func(self):
        for value in SAMPLE_DATA[self.data_type]:
            for example in examples:
                self.assertInplaceOperation(
                    x=value,
                    y=example,
                    operation=operation,
                    format=self.format,
                    substitutions=SAMPLE_SUBSTITUTIONS,
                )
    return func

class InplaceOperationTestCase:
    format = ''
    y = 3

    def run(self, result=None):
        # Override the run method to inject the "expectingFailure" marker
        # when the test case runs.
        for test_name in dir(self):
            if test_name.startswith('test_'):
                getattr(self, test_name).__dict__['__unittest_expecting_failure__'] = test_name in self.not_implemented
        return super().run(result=result)

    def assertInplaceOperation(self, **kwargs):
        substitutions = kwargs.pop('substitutions')
        self.assertCodeExecution(
            """
            x = %(x)s
            y = %(y)s
            %(operation)s
            print(%(format)sx)
            """ % kwargs, "Error running %(operation)s with x=%(x)s and y=%(y)s" % kwargs,
            substitutions=substitutions
        )

    for datatype, examples in SAMPLE_DATA.items():
        vars()['test_add_%s' % datatype] = _inplace_test('test_add_%s' % datatype, 'x += y', examples)
        vars()['test_subtract_%s' % datatype] = _inplace_test('test_subtract_%s' % datatype, 'x -= y', examples)
        vars()['test_multiply_%s' % datatype] = _inplace_test('test_multiply_%s' % datatype, 'x *= y', examples)
        vars()['test_floor_divide_%s' % datatype] = _inplace_test('test_floor_divide_%s' % datatype, 'x //= y', examples)
        vars()['test_true_divide_%s' % datatype] = _inplace_test('test_true_divide_%s' % datatype, 'x /= y', examples)
        vars()['test_modulo_%s' % datatype] = _inplace_test('test_modulo_%s' % datatype, 'x %= y', examples)
        vars()['test_power_%s' % datatype] = _inplace_test('test_power_%s' % datatype, 'x **= y', examples)
        vars()['test_lshift_%s' % datatype] = _inplace_test('test_lshift_%s' % datatype, 'x <<= y', examples)
        vars()['test_rshift_%s' % datatype] = _inplace_test('test_rshift_%s' % datatype, 'x >>= y', examples)
        vars()['test_and_%s' % datatype] = _inplace_test('test_and_%s' % datatype, 'x &= y', examples)
        vars()['test_xor_%s' % datatype] = _inplace_test('test_xor_%s' % datatype, 'x ^= y', examples)
        vars()['test_or_%s' % datatype] = _inplace_test('test_or_%s' % datatype, 'x |= y', examples)

def _builtin_test(test_name, operation, examples):
    def func(self):
        for function in self.functions:
            for example in examples:
                self.assertBuiltinFunction(
                    x=example,
                    f=function,
                    operation=operation,
                    format=self.format,
                    substitutions=SAMPLE_SUBSTITUTIONS
                )
    return func

class BuiltinFunctionTestCase:
    format = ''

    def run(self, result=None):
        # Override the run method to inject the "expectingFailure" marker
        # when the test case runs.
        for test_name in dir(self):
            if test_name.startswith('test_'):
                getattr(self, test_name).__dict__['__unittest_expecting_failure__'] = test_name in self.not_implemented
        return super().run(result=result)

    def assertBuiltinFunction(self, **kwargs):
        substitutions = kwargs.pop('substitutions')
        self.assertCodeExecution(
            """
            f = %(f)s
            x = %(x)s
            print(%(format)s%(operation)s)
            """ % kwargs, "Error running %(operation)s with f=%(f)s, x=%(x)s" % kwargs,
            substitutions=substitutions
        )

    for datatype, examples in SAMPLE_DATA.items():
        vars()['test_%s' % datatype] = _builtin_test('test_%s' % datatype, 'f(x)', examples)

def _builtin_twoarg_test(test_name, operation, examples1, examples2):
    def func(self):
        for function in self.functions:
            for example1 in examples1:
                for example2 in examples2:
                    self.assertBuiltinTwoargFunction(
                        x=example1,
                        y=example2,
                        f=function,
                        operation=operation,
                        format=self.format,
                        substitutions=SAMPLE_SUBSTITUTIONS
                    )
    return func

class BuiltinTwoargFunctionTestCase:
    format = ''

    def run(self, result=None):
        # Override the run method to inject the "expectingFailure" marker
        # when the test case runs.
        for test_name in dir(self):
            if test_name.startswith('test_'):
                getattr(self, test_name).__dict__['__unittest_expecting_failure__'] = test_name in self.not_implemented
        return super().run(result=result)

    def assertBuiltinTwoargFunction(self, **kwargs):
        substitutions = kwargs.pop('substitutions')
        self.assertCodeExecution(
            """
            f = %(f)s
            x = %(x)s
            y = %(y)s
            print(%(format)s%(operation)s)
            """ % kwargs, "Error running %(operation)s with f=%(f)s, x=%(x)s and y=%(y)s" % kwargs,
            substitutions=substitutions
        )

    for datatype1, examples1 in SAMPLE_DATA.items():
        for datatype2, examples2 in SAMPLE_DATA.items():
            vars()['test_%s_%s' % (datatype1, datatype2)] = _builtin_twoarg_test(
                'test_%s_%s' % (datatype1, datatype2),
                'f(x, y)', examples1, examples2
            )


text:
package common

import com.cjwwdev.auth.backend.BaseAuth
import com.cjwwdev.featuremanagement.services.FeatureService
import com.cjwwdev.http.headers.HttpHeaders
import com.cjwwdev.identifiers.IdentifierValidation
import com.cjwwdev.logging.output.Logger
import com.cjwwdev.request.RequestParsers
import com.cjwwdev.responses.ApiResponse
import models.Session
import org.joda.time.{DateTime, Interval}
import play.api.libs.json._
import play.api.mvc._
import repositories.SessionRepository

import scala.concurrent.{ExecutionContext, Future}

trait BackendController
  extends BaseController
    with RequestParsers
    with IdentifierValidation
    with BaseAuth
    with HttpHeaders
    with ApiResponse
    with Logger {

  implicit val ec: ExecutionContext

  val sessionRepository: SessionRepository
  val featureService: FeatureService

  override protected def applicationVerification(f: => Future[Result])(implicit ec: ExecutionContext, request: Request[_]): Future[Result] = {
    if(featureService.getState(Features.applicationVerification).state) {
      super.applicationVerification(f)
    } else {
      f
    }
  }

  protected def validateSession(id: String)(continue: Session => Future[Result])(implicit format: OFormat[Session], request: Request[_]): Future[Result] = {
    validateAs(SESSION, id) {
      sessionRepository.validateSession(id) flatMap { if(_) {
       sessionRepository.getSession(id) flatMap(_.fold(logWithForbidden(id, "[validateSession] - Session is invalid: action forbidden"))(
         session => if(validateTimestamps(session.modifiedDetails.lastModified)) continue(session) else destroySession(id)
       ))
      } else {
        logWithForbidden(id, "[validateSession] - Session doesn't exist, action forbidden")
      }}
    }
  }

  private def logWithForbidden(sessionId: String, msg: String)(implicit request: Request[_]): Future[Result] = {
    LogAt.warn(msg)
    withFutureJsonResponseBody(FORBIDDEN, msg) { json =>
      Future.successful(Forbidden(json))
    }
  }

  private def destroySession(sessionId: String)(implicit request: Request[_]): Future[Result] = {
    LogAt.warn("[validateSession]: Session has timed out, action forbidden")
    sessionRepository.removeSession(sessionId).flatMap { _ =>
      withFutureJsonResponseBody(FORBIDDEN, s"Session $sessionId has timed out action forbidden") { json =>
        Future.successful(Forbidden(json))
      }
    }
  }

  private val validateTimestamps: DateTime => Boolean = lastModified => !(new Interval(lastModified, DateTime.now).toDuration.getStandardHours >= 1)

  val mapReads: Reads[Map[String, String]] = Reads[Map[String, String]](json => JsSuccess(json.as[Map[String, String]]))

  val DUPLICATE_ERR_CODE = 11000
}


text:
from api.event import Event

class VmStatusChanged(Event):
    """
    Inform users (VM owners logged in GUI) when VM changes its state.
    """
    _name_ = 'vm_status_changed'

    def __init__(self, task_id, vm):
        status_display = vm.status_display(pending=False)
        super(VmStatusChanged, self).__init__(
            task_id,
            vm_hostname=vm.hostname,
            alias=vm.alias,
            status=vm.status,
            status_display=status_display,
            detail=status_display,  # for logging detail
            status_change=str(vm.status_change),
            define_changed=vm.json_changed(),
            locked=vm.locked,
        )


text:
In this project we will be using github, canvas and p5.js for making a space shooter game
Trello will be used for assigning tasks to pairs and pull requests will be used to add the new features as everyone develops them.

# Prerequisites
An http server running on your PC to see the website in localhost instead of opening file in Chrome

###  If you have Atom get this plugin
https://atom.io/packages/atom-live-server

#### If you have npm run this command to get an alternative tool
`npm install http-server -g`

Now run the server in the directory where you have the project and now you can browse the website just like it would be on codepen

All files you will need to use for coding are in js folder, using functions from libraries and built-in from javascript are greatly encouraged.

Try to make code friendly and stylish so the mentors can understand easily


text:
package com.adaptris.core.metadata;

import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import com.adaptris.core.AdaptrisMessage;
import com.adaptris.core.DefaultMessageFactory;

public class MetadataResolverTest {

  private AdaptrisMessage message;

  @Before
  public void setUp() throws Exception {
    message = DefaultMessageFactory.getDefaultInstance().newMessage();
  }

  @Test
  public void testGetNormal() {
    message.addMessageHeader("key1", "value1");
    message.addMessageHeader("key2", "value2");
    message.addMessageHeader("key3", "value3");

    assertEquals("key1", MetadataResolver.resolveKey(message, "key1"));
    assertEquals("key2", MetadataResolver.resolveKey(message, "key2"));
    assertEquals("key3", MetadataResolver.resolveKey(message, "key3"));
  }

  @Test
  public void testGetReferenced() {
    message.addMessageHeader("key1", "value1");
    message.addMessageHeader("key2", "value2");
    message.addMessageHeader("key3", "value3");

    assertEquals("value1", MetadataResolver.resolveKey(message, "$$key1"));
    assertEquals("value2", MetadataResolver.resolveKey(message, "$$key2"));
    assertEquals("value3", MetadataResolver.resolveKey(message, "$$key3"));
  }

}


text:
<?php

namespace Drupal\user\Form;

use Drupal\Core\Entity\ContentEntityConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Provides a confirmation form for cancelling user account.
 */
class UserCancelForm extends ContentEntityConfirmFormBase {

  /**
   * Available account cancellation methods.
   *
   * @var array
   */
  protected $cancelMethods;

  /**
   * The user being cancelled.
   *
   * @var \Drupal\user\UserInterface
   */
  protected $entity;

  /**
   * {@inheritdoc}
   */
  public function getQuestion() {
    if ($this->entity->id() == $this->currentUser()->id()) {
      return $this->t('Are you sure you want to cancel your account?');
    }
    return $this->t('Are you sure you want to cancel the account %name?', ['%name' => $this->entity->label()]);
  }

  /**
   * {@inheritdoc}
   */
  public function getCancelUrl() {
    return $this->entity->urlInfo();
  }

  /**
   * {@inheritdoc}
   */
  public function getDescription() {
    $description = '';
    $default_method = $this->config('user.settings')->get('cancel_method');
    if ($this->currentUser()->hasPermission('administer users') || $this->currentUser()->hasPermission('select account cancellation method')) {
      $description = $this->t('Select the method to cancel the account above.');
    }
    // Options supplied via user_cancel_methods() can have a custom
    // #confirm_description property for the confirmation form description.
    elseif (isset($this->cancelMethods[$default_method]['#confirm_description'])) {
      $description = $this->cancelMethods[$default_method]['#confirm_description'];
    }
    return $description . ' ' . $this->t('This action cannot be undone.');
  }

  /**
   * {@inheritdoc}
   */
  public function getConfirmText() {
    return $this->t('Cancel account');
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $user = $this->currentUser();
    $this->cancelMethods = user_cancel_methods();

    // Display account cancellation method selection, if allowed.
    $admin_access = $user->hasPermission('administer users');
    $form['user_cancel_method'] = [
      '#type' => 'radios',
      '#title' => ($this->entity->id() == $user->id() ? $this->t('When cancelling your account') : $this->t('When cancelling the account')),
      '#access' => $admin_access || $user->hasPermission('select account cancellation method'),
    ];
    $form['user_cancel_method'] += $this->cancelMethods;

    // Allow user administrators to skip the account cancellation confirmation
    // mail (by default), as long as they do not attempt to cancel their own
    // account.
    $override_access = $admin_access && ($this->entity->id() != $user->id());
    $form['user_cancel_confirm'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Require email confirmation to cancel account'),
      '#default_value' => !$override_access,
      '#access' => $override_access,
      '#description' => $this->t('When enabled, the user must confirm the account cancellation via email.'),
    ];
    // Also allow to send account canceled notification mail, if enabled.
    $default_notify = $this->config('user.settings')->get('notify.status_canceled');
    $form['user_cancel_notify'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Notify user when account is canceled'),
      '#default_value' => ($override_access ? FALSE : $default_notify),
      '#access' => $override_access && $default_notify,
      '#description' => $this->t('When enabled, the user will receive an email notification after the account has been canceled.'),
    ];

    // Always provide entity id in the same form key as in the entity edit form.
    $form['uid'] = ['#type' => 'value', '#value' => $this->entity->id()];

    // Store the user permissions so that it can be altered in hook_form_alter()
    // if desired.
    $form['access'] = [
      '#type' => 'value',
      '#value' => $user->hasPermission('administer users'),
    ];

    $form = parent::buildForm($form, $form_state);

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Cancel account immediately, if the current user has administrative
    // privileges, no confirmation mail shall be sent, and the user does not
    // attempt to cancel the own account.
    if (!$form_state->isValueEmpty('access') && $form_state->isValueEmpty('user_cancel_confirm') && $this->entity->id() != $this->currentUser()->id()) {
      user_cancel($form_state->getValues(), $this->entity->id(), $form_state->getValue('user_cancel_method'));

      $form_state->setRedirectUrl($this->entity->urlInfo('collection'));
    }
    else {
      // Store cancelling method and whether to notify the user in
      // $this->entity for
      // \Drupal\user\Controller\UserController::confirmCancel().
      $this->entity->user_cancel_method = $form_state->getValue('user_cancel_method');
      $this->entity->user_cancel_notify = $form_state->getValue('user_cancel_notify');
      $this->entity->save();
      _user_mail_notify('cancel_confirm', $this->entity);
      drupal_set_message($this->t('A confirmation request to cancel your account has been sent to your email address.'));
      $this->logger('user')->notice('Sent account cancellation request to %name %email.', ['%name' => $this->entity->label(), '%email' => '<' . $this->entity->getEmail() . '>']);

      $form_state->setRedirect(
        'entity.user.canonical',
        ['user' => $this->entity->id()]
      );
    }
  }

}


text:
class FluentdController < ApplicationController
  # before_action :find_fluentd, only: [:show, :edit, :update, :destroy, :log, :raw_log, :errors]
  # before_action :check_fluentd_exists, only: [:edit, :log, :raw_log, :errors]

  def show
  end

  def new
    @fluentd = Fluentd.new(variant: params[:variant] || "fluentd")
    @fluentd.load_settings_from_agent_default
  end

  def create
    @fluentd = Fluentd.new(fluentd_params)
    unless @fluentd.save
      return render :new
    end
    redirect_to daemon_path
  end

  def edit
  end

  def update
    # TODO: should restart if changed file path? or just do "dirty" flagged?
    @fluentd.update_attributes(fluentd_params)
    unless @fluentd.save
      return render :edit
    end
    redirect_to daemon_path
  end

  def destroy
    @fluentd.agent.stop if @fluentd.agent.running?
    @fluentd.destroy
    redirect_to root_path, flash: {success: t('messages.destroy_succeed_fluentd_setting', brand: fluentd_ui_brand)}
  end

  def log
  end

  def errors
    @error_duration_days = 5
    @errors = @fluentd.agent.log.errors_since(@error_duration_days.days.ago)
  end

  def raw_log
    send_data @fluentd.agent.log.read, type: "application/octet-stream", filename: File.basename(@fluentd.log_file)
  end

  private

  def fluentd_params
    params.require(:fluentd).permit(:log_file, :pid_file, :config_file, :variant, :api_endpoint)
  end

  def check_fluentd_exists
    unless fluentd_exists?
      redirect_to root_path
    end
  end
end


text:
#import <UIKit/UIKit.h>

@interface WFTableCategoryViewCell : UITableViewCell
{

@private

    UILabel *labelCategoryName;
    UIImageView *imageView;
}

@property (nonatomic, retain) UILabel *labelCategoryName;
@property (nonatomic, retain) UIImageView *imageView;

- (void)setCell:(id)category;

@end


text:
test

Login xxx

        <form role="form">

                Username
                <input type="text" #username id="username" placeholder="Username">

                Password
                <input type="password" #password id="password" placeholder="Password">

            <button type="button" class="btn btn-primary" (click)="onSubmit($event, username.value, password.value)">Submit</button>
        </form>


text:
package org.jboss.arquillian.integration.persistence.testextension.exception;

import org.jboss.arquillian.core.api.Instance;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.core.api.annotation.Observes;
import org.jboss.arquillian.core.spi.EventContext;
import org.jboss.arquillian.persistence.core.event.AfterPersistenceTest;
import org.jboss.arquillian.persistence.core.test.AssertionErrorCollector;
import org.jboss.arquillian.test.spi.annotation.TestScoped;

import static org.assertj.core.api.Assertions.assertThat;

public class ErrorObserver
{
   @Inject @TestScoped
   private Instance<AssertionErrorCollector> assertionErrorCollectorInstance;

   public void collectErrors(@Observes(precedence = 9999) EventContext<AfterPersistenceTest> context)
   {
      context.proceed();
      final ShouldFailWith shouldFailWith = context.getEvent().getTestMethod().getAnnotation(ShouldFailWith.class);
      if (shouldFailWith != null)
      {
         final AssertionErrorCollector errorCollector = assertionErrorCollectorInstance.get();
         final Class<? extends Throwable> expectedError = shouldFailWith.value();
         assertThat(errorCollector.contains(expectedError)).describedAs("Expected " + expectedError.getName() + ", but instead got following errors: " + errorCollector.showAllErrors()).isTrue();
         errorCollector.clear();
      }
   }
}


text:
/**
 * Created by Nidin Vinayakan on 02-10-2015.
 */

import BaseEvent from "../events/BaseEvent";

export default class EventDispatcher {

    eventMaps:any;
    pendingEventMap:any;
    pendingEvents:Array<BaseEvent>;

    constructor() {
        this.eventMaps = {};
        this.pendingEventMap = {};
        this.pendingEvents = [];
    }

    addEventListener(type:string, listener:Function, context?) {
        if(this.eventMaps[type] === undefined){
            this.eventMaps[type] = [];
        }
        this.eventMaps[type].push({method:listener, context:context});
        if(this.pendingEventMap[type] != undefined){
            listener.call(context,this.pendingEvents[this.pendingEventMap[type]]);
        }
    }

    hasEventListener(type:string, listener:Function):boolean {
        if(this.eventMaps[type] === undefined){
            return false;
        }
        return ( this.eventMaps[ type ] !== undefined && this.eventMaps[ type ].indexOf( listener ) !== - 1 );
    }

    removeEventListener(type:string, listener:Function) {
        if(this.eventMaps[type] !== undefined){
            this.eventMaps[type].splice(this.eventMaps[type].indexOf(listener),1);
        }
    }

    dispatchEvent(event:BaseEvent) {
        var listeners = this.eventMaps[event.type];
        if(listeners !== undefined){
            for(var i=0;i<listeners.length;i++){
                var listener = listeners[i];
                listener.method.call(listener.context, event);
            }
        }else{
            this.pendingEventMap[event.type] = this.pendingEvents.push(event) - 1;

        }
    }

}


text:
package com.weilaiweather.android;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.weilaiweather.android.gsons.DailyForecastBean;
import com.weilaiweather.android.gsons.Weather;
import com.weilaiweather.android.services.AutoUpdateService;
import com.weilaiweather.android.util.HttpUtil;
import com.weilaiweather.android.util.Utility;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class WeatherActivity extends AppCompatActivity {

    private static final String TAG = "WeatherActivity";
    private static final String TAG1 = "WeatherActivity1";
    private ScrollView scrollView;
    private TextView textCity;
    private TextView textUpdateText;
    private TextView degreeText;
    private TextView weatherInfoText;
    private LinearLayout forcastLayout;
    private TextView aqiText;
    private TextView pm25Text;
    private TextView comfortText;
    private TextView carWashText;
    private TextView sportText;

    private Button btnHome;
    private ImageView mImageView;
    public SwipeRefreshLayout refreshLayout;
    private String mWeatherId;
    // 滑动菜单功能
    public DrawerLayout drawerLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (Build.VERSION.SDK_INT >= 21){
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        setContentView(R.layout.activity_weather);

        scrollView = (ScrollView) findViewById(R.id.weather_layout);
        textCity = (TextView) findViewById(R.id.title_city);
        textUpdateText = (TextView) findViewById(R.id.title_update_time);
        degreeText = (TextView) findViewById(R.id.degree_text);
        weatherInfoText = (TextView) findViewById(R.id.weather_info_text);
        forcastLayout = (LinearLayout) findViewById(R.id.forcast_layout);
        aqiText = (TextView) findViewById(R.id.aqi_text);
        pm25Text = (TextView) findViewById(R.id.pm25_text);
        comfortText = (TextView) findViewById(R.id.comfort_text);
        carWashText = (TextView) findViewById(R.id.car_wash_text);
        sportText = (TextView) findViewById(R.id.sport_text);
        btnHome = (Button) findViewById(R.id.btn_home);
        mImageView = (ImageView) findViewById(R.id.bing_pic_img);
        refreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

        refreshLayout.setColorSchemeResources(R.color.colorPrimary);

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        String weatherString = prefs.getString("weather", null);
        String bingPic = prefs.getString("bing_pic",null);
        if (bingPic !=null){
            Glide.with(this).load(bingPic).into(mImageView);
        }else{
            loadBingPic();
        }
        Log.e(TAG1, "111"+weatherString);
        if (weatherString != null) {
            // 有缓存时直接解析天气数据
            Weather weather = Utility.handleWeatherResponse(weatherString);
            mWeatherId = weather.getBasic().getId();
            showWeatherInfo(weather);
        } else {
            // 无缓存时从服务器查询数据
            mWeatherId = getIntent().getStringExtra("WeatherId");
            scrollView.setVisibility(View.VISIBLE);
            requestWeather(mWeatherId);
        }
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Log.i(TAG, "onRefresh: "+mWeatherId);
                requestWeather(mWeatherId);
            }
        });
        btnHome.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawerLayout.openDrawer(GravityCompat.START);
            }
        });
    }

    public void requestWeather(String weatherId) {
        String weatherUrl = "https://free-api.heweather.com/v5/weather?city=" + weatherId + "&key=59219d67ae834f5d8eee40683593b909";
        HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(WeatherActivity.this, "获取天气数据失败", Toast.LENGTH_SHORT).show();
                        refreshLayout.setRefreshing(false);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String responseText = response.body().string();
                final Weather wrathers = Utility.handleWeatherResponse(responseText);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (wrathers != null && "ok".equals(wrathers.getStatus())) {
                            SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
                            editor.putString("weather", responseText);
                            editor.apply();
                           showWeatherInfo(wrathers);
                        } else {
                            Toast.makeText(WeatherActivity.this, "获取天气数据失败", Toast.LENGTH_SHORT).show();
                        }
                        refreshLayout.setRefreshing(false);
                    }
                });
                loadBingPic();
            }
        });
    }

    private void showWeatherInfo(Weather weather) {

        String cityName = weather.getBasic().getCity();
        Log.e(TAG, "showWeatherInfo: "+weather.getBasic().getUpdate().getLoc());
        String updateTime = weather.getBasic().getUpdate().getLoc().split(" ")[1];

        String degree = weather.getNow().getTmp() + "℃";
        String weatherInfo = weather.getNow().getCond().getTxt();
        textCity.setText(cityName);
        textUpdateText.setText(updateTime);
        degreeText.setText(degree);
        weatherInfoText.setText(weatherInfo);
        forcastLayout.removeAllViews();
        for (DailyForecastBean d : weather.getDaily_forecast()) {
            View view = LayoutInflater.from(this).inflate(R.layout.forecast_item, forcastLayout, false);
            TextView dateText = (TextView) view.findViewById(R.id.date_text);
            TextView infoText = (TextView) view.findViewById(R.id.info_text);
            TextView maxText = (TextView) view.findViewById(R.id.max_text);
            TextView minText = (TextView) view.findViewById(R.id.min_text);
            dateText.setText(d.getDate());
            infoText.setText(d.getCond().getTxt_d());
            maxText.setText(d.getTmp().getMax());
            minText.setText(d.getTmp().getMin());
            forcastLayout.addView(view);
        }
        if (weather.getAqi() != null) {
            aqiText.setText(weather.getAqi().getCity().getAqi());
            pm25Text.setText(weather.getAqi().getCity().getPm25());
        }
        String comfort = "舒适度" + weather.getSuggestion().getComf().getTxt();
        String carWash = "洗车指数" + weather.getSuggestion().getCw().getTxt();
        String sport = "运动建议" + weather.getSuggestion().getSport().getTxt();
        comfortText.setText(comfort);
        carWashText.setText(carWash);
        sportText.setText(sport);
        scrollView.setVisibility(View.VISIBLE);

        if (weather !=null && "ok".equals(weather.getStatus())){
            // 启动服务
            Intent intent = new Intent(this, AutoUpdateService.class);
            startService(intent);
        }else{
            Toast.makeText(WeatherActivity.this, "获取天气失败", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 加载每日一图
     */
    private void loadBingPic() {
        String requestBingPic = "http://guolin.tech/api/bing_pic";
        HttpUtil.sendOkHttpRequest(requestBingPic, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
               e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String bingPic = response.body().string();
                SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
                editor.putString("bing_pic",bingPic);
                editor.apply();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Glide.with(WeatherActivity.this).load(bingPic).into(mImageView);
                    }
                });
            }
        });
    }
}


text:
"""
Created on Fri Jul 18 18:10:04 2014

@author: Kyle Ellefsen
"""
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import global_vars as g
import pyqtgraph as pg
from skimage.draw import polygon, line
import numpy as np
import os
import time

class ROI(QWidget):
    " This is an ROI.  I need to document it better."
    translated=Signal()
    translate_done=Signal()
    deleteSignal=Signal()
    kind='freehand'
    def __init__(self,window,x,y):
        QWidget.__init__(self)
        self.window=window
        self.window.currentROI=self
        self.view=self.window.imageview.view
        self.path=QPainterPath(QPointF(x,y))
        self.pathitem=QGraphicsPathItem(self.view)
        self.color=Qt.yellow
        self.pathitem.setPen(QPen(self.color))
        self.pathitem.setPath(self.path)
        self.view.addItem(self.pathitem)
        self.mouseIsOver=False
        self.createActions()
        self.beingDragged=False
        self.window.deleteButtonSignal.connect(self.deleteCurrentROI)
        self.window.closeSignal.connect(self.delete)

    def extend(self,x,y):
        self.path.lineTo(QPointF(x,y))
        self.pathitem.setPath(self.path)

    def deleteCurrentROI(self):
        if self.window.currentROI is self:
            self.delete()

    def getTraceWindow(self):
        trace_with_roi = [t for t in g.m.traceWindows if t.hasROI(self)]
        if len(trace_with_roi) == 1:
            return trace_with_roi[0]
        return False

    def delete(self):
        if self in self.window.rois:
            self.window.rois.remove(self)
        self.window.currentROI=None
        self.view.removeItem(self.pathitem)
        trace = self.getTraceWindow()
        if trace:
            a=set([r['roi'] for r in trace.rois])
            b=set(self.window.rois)
            if len(a.intersection(b))==0:
                trace.indexChanged.disconnect(self.window.setIndex)
            trace.removeROI(self)
    def getPoints(self):
        points=[]
        for i in np.arange(self.path.elementCount()):
            e=self.path.elementAt(i)
            x=int(np.round(e.x)); y=int(np.round(e.y))
            if len(points)==0 or points[-1]!=(x,y):
                points.append((x,y))
        self.pts=points
        self.minn=np.min(np.array( [np.array([p[0],p[1]]) for p in self.pts]),0)
        return self.pts
    def getArea(self):
        self.getMask()
        return len(self.mask)
        #cnt=np.array([np.array([np.array([p[1],p[0]])]) for p in self.pts ])
        #area = cv2.contourArea(cnt)
        #return area
    def drawFinished(self):
        self.path.closeSubpath()
        self.draw_from_points(self.getPoints()) #this rounds all the numbers down
        self.window.rois.append(self)
        self.getMask()

    def mouseOver(self,x,y):
        if self.mouseIsOver is False and self.contains(x,y):
            self.mouseIsOver=True
            self.pathitem.setPen(QPen(Qt.red))
        elif self.mouseIsOver and self.contains(x,y) is False:
            self.mouseIsOver=False
            self.pathitem.setPen(QPen(self.color))

    def contextMenuEvent(self, event):
        self.menu = QMenu(self)
        self.menu.addAction(self.copyAct)
        self.menu.addAction(self.deleteAct)
        self.menu.addAction(self.saveAct)
        self.menu.exec_(event.screenPos().toQPoint())

    def copy(self):
        g.m.clipboard=self

    def save(self,filename):
        text=''
        for roi in g.m.currentWindow.rois:
            pts=roi.getPoints()
            text+=type(roi).kind+'\n'
            for pt in pts:
                text+="{0:<4} {1:<4}\n".format(pt[0],pt[1])
            text+='\n'
        f=open(filename,'w')
        f.write(text)
        f.close()

    def save_gui(self):
        filename=g.m.filename
        if filename is not None and os.path.isfile(filename):
            filename= QFileDialog.getOpenFileName(g.m, 'Save ROI', filename, "*.txt")
        else:
            filename= QFileDialog.getOpenFileName(g.m, 'Save ROI', '', '*.txt')
        filename=str(filename)
        if filename != '':
            g.m.filename = filename
            self.save(filename)
        else:
            g.m.statusBar().showMessage('No File Selected')

    def createActions(self):
        self.copyAct = QAction("&Copy", self, triggered=self.copy)
        self.deleteAct = QAction("&Delete", self, triggered=self.delete)
        self.saveAct = QAction("&Save",self,triggered=lambda : self.save_gui)

    def contains(self,x,y):
        return self.path.contains(QPointF(x,y))
    def translate(self,difference,startpt):
        self.path.translate(difference)
        self.pathitem.setPath(self.path)
        self.translated.emit()
    def finish_translate(self):
        self.draw_from_points(self.getPoints())
        self.getMask()
        self.translate_done.emit()
        self.beingDragged=False
    def draw_from_points(self,pts):
        self.pts=pts
        self.path=QPainterPath(QPointF(pts[0][0],pts[0][1]))
        for i in np.arange(len(pts)-1)+1:
            self.path.lineTo(QPointF(pts[i][0],pts[i][1]))
        self.pathitem.setPath(self.path)

    def getMask(self):
        pts=self.pts
        tif=self.window.image
        x=np.array([p[0] for p in pts])
        y=np.array([p[1] for p in pts])
        nDims=len(tif.shape)
        if nDims==4: #if this is an RGB image stack
            tif=np.mean(tif,3)
            mask=np.zeros(tif[0,:,:].shape,np.bool)
        elif nDims==3:
            mask=np.zeros(tif[0,:,:].shape,np.bool)
        if nDims==2: #if this is a static image
            mask=np.zeros(tif.shape,np.bool)

        xx,yy=polygon(x,y,shape=mask.shape)
        mask[xx,yy]=True
        pts_plus=np.array(np.where(mask)).T
        for pt in pts_plus:
            if not self.path.contains(QPointF(pt[0],pt[1])):
                mask[pt[0],pt[1]]=0
        self.minn=np.min(np.array( [np.array([p[0],p[1]]) for p in self.pts]),0)
        self.mask=np.array(np.where(mask)).T-self.minn

def makeROI(kind,pts,window=None):
    if window is None:
        window=g.m.currentWindow
    if kind=='freehand':
        roi=ROI(window,0,0)
    elif kind=='rectangle':
        roi=ROI_rectangle(window,0,0)
    elif kind=='line':
        roi=ROI_line(window,0,0)
    else:
        print("ERROR: THIS TYPE OF ROI COULD NOT BE FOUND: {}".format(kind))
        return None
    roi.draw_from_points(pts)
    roi.drawFinished()
    return roi
def load_roi(filename):
    f = open(filename, 'r')
    text=f.read()
    f.close()
    kind=None
    pts=None
    for line in text.split('\n'):
        if kind is None:
            kind=line
            pts=[]
        elif line=='':
            makeROI(kind,pts)
            kind=None
            pts=None
        else:
            pts.append(tuple(int(i) for i in line.split()))


text: battleship built with phaser


text:
package com.sinotrans.transport.dto;

import com.sinotrans.transport.dto.common.RestResponse;
import com.sinotrans.transport.dto.vo.OrderCountVo;
import com.sinotrans.transport.dto.vo.OrderNoticeVo;

/**
 * Created by emi on 2016/8/16.
 */
public class OrderWaitingResponse extends RestResponse {

    private OrderCountVo countVo;//待审核的进出口数量

    private OrderNoticeVo noticeVo;//未阅读的消息通知vo

    public OrderWaitingResponse(OrderCountVo countVo, OrderNoticeVo noticeVo) {
        this();
        this.countVo = countVo;
        this.noticeVo = noticeVo;
    }

    public OrderWaitingResponse() {
        super();
    }

    public OrderCountVo getCountVo() {
        return countVo;
    }

    public void setCountVo(OrderCountVo countVo) {
        this.countVo = countVo;
    }

    public OrderNoticeVo getNoticeVo() {
        return noticeVo;
    }

    public void setNoticeVo(OrderNoticeVo noticeVo) {
        this.noticeVo = noticeVo;
    }
}