text:
package com.test.leetcode.medium;

/**
 * Created by ben on 2017/7/12.
 */
public class _11_ContainerWithMostWater {
    public int maxArea(int[] height) {
        if (height.length < 2) return 0;
        int ans = 0;
        int l = 0;
        int r = height.length - 1;
        while (l < r) {
            int v = (r - l) * Math.min(height[l], height[r]);
            if (v > ans) ans = v;
            if (height[l] < height[r]) l++;
            else r--;
        }
        return ans;
    }

    public int maxArea1(int[] height) {
        if (height == null)
            return 0;
        int len = height.length;
        if (len == 1 || len == 0)
            return 0;
        int left = 0;
        int right = len - 1;
        int maxArea = 0;
        while (left < right) {
            int minHeight = (height[left] > height[right]) ? height[right] : height[left];
            int area = minHeight * (right - left);
            maxArea = (maxArea > area) ? maxArea : area;
            //if next left is smaller or equals to left, no need to calculate
            while (height[left] <= minHeight && left < right)
                left++;
            //if next right is smaller or equals to right, no need to calculate
            while (height[right] <= minHeight && left < right)
                right--;
        }
        return maxArea;
    }
}


text:
using namespace std;

typedef _leetcode_listnode<int> ListNode;

class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        if (head == nullptr || head->next == nullptr || k == 1)
            return head;
        ListNode _tmp(0);
        ListNode *p1(&_tmp);
        p1->next = head;
        ListNode *prehead(p1), *tail(p1);
        while (true)
        {
            int position(0);
            while (tail->next != nullptr)
            {
                tail = tail->next;
                ++position;
                if (position == k)
                    break;
            }
            if (position == k)
                tail = lc_reverselist(p1, k);
            else
                return prehead->next;
            p1 = tail;
        }

    }

private:
    ListNode* lc_reverselist(ListNode *head_prev,  int cnt)
    {
        if (cnt == 1)
            return head_prev->next;
        int ccnt(1);
        ListNode *newhead(head_prev->next), *newtail(head_prev->next);
        ListNode *originalhead(head_prev->next->next), *tmp(nullptr);
        newtail->next = nullptr;
        while (ccnt<cnt)
        {
            tmp = originalhead->next;
            originalhead->next = newhead;
            newhead = originalhead;
            originalhead = tmp;
            ++ccnt;
        }
        newtail->next = originalhead;
        head_prev->next = newhead;
        return newtail;
    }
};

int main()
{
    Solution s;
    vector<int> test = { 1, 2, 3, 4, 5 };
    auto l1 = lc_createlist(test, true);
    auto l2 = s.reverseKGroup(l1, 1);
    lc_printlist(l2);
    lc_destroylist(l2);
    system("pause");
    return 0;

}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace OpenConext\EngineBlock\Authentication\Value;

use OpenConext\EngineBlock\Exception\InvalidArgumentException;
use PHPUnit_Framework_TestCase as UnitTest;

class SchacHomeOrganizationTest extends UnitTest
{
    /**
     * @test
     * @group EngineBlock
     * @group Authentication
     * @dataProvider \OpenConext\TestDataProvider::notStringOrEmptyString
     *
     * @param mixed $notStringOrEmptyString
     */
    public function schac_home_organization_must_be_a_non_empty_string($notStringOrEmptyString)
    {
        $this->expectException(InvalidArgumentException::class);

        new SchacHomeOrganization($notStringOrEmptyString);
    }

    /**
     * @test
     * @group EngineBlock
     * @group Authentication
     */
    public function schac_home_organization_can_be_retrieved()
    {
        $schacHomeOrganizationValue = 'OpenConext.org';

        $schacHomeOrganization = new SchacHomeOrganization($schacHomeOrganizationValue);

        $this->assertSame($schacHomeOrganizationValue, $schacHomeOrganization->getSchacHomeOrganization());
    }

    /**
     * @test
     * @group EngineBlock
     * @group Authentication
     */
    public function schac_home_organization_equality_is_determined_based_on_value()
    {
        $base      = new SchacHomeOrganization('OpenConext.org');
        $same      = new SchacHomeOrganization('OpenConext.org');
        $different = new SchacHomeOrganization('BabelFish Inc.');

        $this->assertTrue($base->equals($same));
        $this->assertFalse($base->equals($different));
    }

    /**
     * @test
     * @group EngineBlock
     * @group Authentication
     */
    public function a_schac_home_organization_can_be_cast_to_string()
    {
        $schacHomeOrganization = new SchacHomeOrganization('OpenConext.org');

        $this->assertInternalType('string', (string) $schacHomeOrganization);
    }
}


text:
from ..config import Config
from kao_command.args import Arg

class SetDir:
    """ Command to set the current editor """
    description = "Set the path to the devlog parent directory"
    args = [Arg('path', action='store', help="The Path to the directory where logs will be stored")]

    def run(self, *, path):
        """ Set the Log Directory """
        Config.setLogDir(path)


text:
package com.intellij.openapi.projectRoots.impl;

import com.intellij.openapi.projectRoots.ex.ProjectRoot;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.ArrayUtil;
import com.intellij.util.containers.ContainerUtil;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author mike
 */
class CompositeProjectRoot implements ProjectRoot {
  private final List<ProjectRoot> myRoots = new ArrayList<ProjectRoot>();

  @NotNull
  ProjectRoot[] getProjectRoots() {
    return myRoots.toArray(new ProjectRoot[myRoots.size()]);
  }

  public String getPresentableString() {
    throw new UnsupportedOperationException();
  }

  public VirtualFile[] getVirtualFiles() {
    List<VirtualFile> result = new ArrayList<VirtualFile>();
    for (ProjectRoot root : myRoots) {
      ContainerUtil.addAll(result, root.getVirtualFiles());
    }

    return VfsUtil.toVirtualFileArray(result);
  }

  public String[] getUrls() {
    final List<String> result = new ArrayList<String>();
    for (ProjectRoot root : myRoots) {
      ContainerUtil.addAll(result, root.getUrls());
    }
    return ArrayUtil.toStringArray(result);
  }

  public boolean isValid() {
    return true;
  }

  void remove(ProjectRoot root) {
    myRoots.remove(root);
  }

  @NotNull
  ProjectRoot add(VirtualFile virtualFile) {
    final SimpleProjectRoot root = new SimpleProjectRoot(virtualFile);
    myRoots.add(root);
    return root;
  }

  void add(ProjectRoot root) {
    myRoots.add(root);
  }

  void remove(VirtualFile root) {
    for (Iterator<ProjectRoot> iterator = myRoots.iterator(); iterator.hasNext();) {
      ProjectRoot projectRoot = iterator.next();
      if (projectRoot instanceof SimpleProjectRoot) {
        SimpleProjectRoot r = (SimpleProjectRoot)projectRoot;
        if (r.getFile() != null && r.getFile().equals(root)) {
          iterator.remove();
        }
      }
    }
  }

  void clear() {
    myRoots.clear();
  }

  public void readExternal(Element element) throws InvalidDataException {
    final List children = element.getChildren();
    for (Object aChildren : children) {
      Element e = (Element)aChildren;
      myRoots.add(ProjectRootUtil.read(e));
    }
  }

  public void writeExternal(Element element) throws WriteExternalException {
    for (ProjectRoot root : myRoots) {
      final Element e = ProjectRootUtil.write(root);
      if (e != null) {
        element.addContent(e);
      }
    }
  }

  public void update() {
    for (ProjectRoot root : myRoots) {
      root.update();
    }
  }

}


text:
describe :time_gmt_offset, :shared => true do
  it "returns the offset in seconds between the timezone of time and UTC" do
    with_timezone("AST", 3) do
      Time.new.send(@method).should == 10800
    end
  end
if System.get_property('platform') != 'APPLE'
  it "returns the correct offset for US Eastern time zone around daylight savings time change" do
    with_timezone("EST5EDT") do
      Time.local(2010,3,14,1,59,59).send(@method).should == -5*60*60
      if System.get_property('platform') != 'WINDOWS' && System.get_property('platform') != 'WINDOWS_DESKTOP'
        Time.local(2010,3,14,2,0,0).send(@method).should == -4*60*60
      end
    end
  end
end
  #it "returns the correct offset for Hawaii around daylight savings time change" do
  #  with_timezone("Pacific/Honolulu") do
  #    Time.local(2010,3,14,1,59,59).send(@method).should == -10*60*60
  #    Time.local(2010,3,14,2,0,0).send(@method).should == -10*60*60
  #  end
  #end

  #it "returns the correct offset for New Zealand around daylight savings time change" do
  #  with_timezone("Pacific/Auckland") do
  #    Time.local(2010,4,4,1,59,59).send(@method).should == 13*60*60
  #    Time.local(2010,4,4,3,0,0).send(@method).should == 12*60*60
  #  end
  #end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<billStatus>
  <bill>
    <committeeReports />
    <notes />
    <recordedVotes />
    <cboCostEstimates />
    <actions>
      <actionTypeCounts>
        <introducedInTheHouse>1</introducedInTheHouse>
        <billReferrals>1</billReferrals>
        <introducedInHouse>1</introducedInHouse>
      </actionTypeCounts>
      <actionByCounts>
        <houseOfRepresentatives>3</houseOfRepresentatives>
      </actionByCounts>
      <item>
        <actionCode>H11100</actionCode>
        <text>Referred to the House Committee on Financial Services.</text>
        <links />
        <committee>
          <name>Financial Services Committee</name>
          <systemCode>hsba00</systemCode>
        </committee>
        <actionDate>2017-02-16</actionDate>
        <sourceSystem>
          <name>House floor actions</name>
          2
        </sourceSystem>
        <type>IntroReferral</type>
      </item>
      <item>
        <actionCode>Intro-H</actionCode>
        <text>Introduced in House</text>
        <links />
        <committee />
        <actionDate>2017-02-16</actionDate>
        <sourceSystem>
          <name>Library of Congress</name>
          9
        </sourceSystem>
        <type>IntroReferral</type>
      </item>
      <item>
        <actionCode>1000</actionCode>
        <text>Introduced in House</text>
        <links />
        <committee />
        <actionDate>2017-02-16</actionDate>
        <sourceSystem>
          <name>Library of Congress</name>
          9
        </sourceSystem>
        <type>IntroReferral</type>
      </item>
    </actions>
    <calendarNumbers />
    <updateDate>2017-07-28T07:16:03Z</updateDate>
    <createDate>2017-02-17T04:46:13Z</createDate>
    <summaries>
      <billSummaries>
        <item>
          <lastSummaryUpdateDate>2017-07-08T14:55:51Z</lastSummaryUpdateDate>
          <text><![CDATA[
Master Sergeant Roddie Edmonds Congressional Gold Medal Act

This bill directs the Speaker of the House of Representatives and the President pro tempore of the Senate to arrange for the posthumous award of a Congressional Gold Medal to Roddie Edmonds in recognition of his achievements and heroic actions during World War II.
]]></text>
          <actionDate>2017-02-16</actionDate>
          <versionCode>00</versionCode>
          <name>Introduced in House</name>
          <actionDesc>Introduced in House</actionDesc>
          <updateDate>2017-02-16T05:00:00Z</updateDate>
        </item>
      </billSummaries>
    </summaries>
    <version>1.0.0</version>
    <congress>115</congress>
    <relatedBills>
      <item>
        <number>352</number>
        <congress>115</congress>
        <latestAction>
          <actionDate>2017-02-13</actionDate>
          <text>Read twice and referred to the Committee on Banking, Housing, and Urban Affairs.</text>
        </latestAction>
        <latestTitle>Master Sergeant Roddie Edmonds Congressional Gold Medal Act</latestTitle>
        <type>S</type>
        <relationshipDetails>
          <item>
            <identifiedBy>CRS</identifiedBy>
            <type>Identical bill</type>
          </item>
        </relationshipDetails>
      </item>
    </relatedBills>
    <policyArea>
      <name>Armed Forces and National Security</name>
    </policyArea>
    <constitutionalAuthorityStatementText><![CDATA[
From the Congressional Record Online through the Government Publishing Office [www.gpo.gov]By Mr. DUNCAN of Tennessee:H.R. 1142.Congress has the power to enact this legislation pursuantto the following:Article I, Section 8, Clause 5.[Page H1304]
]]></constitutionalAuthorityStatementText>
    <cosponsors>
      <item>
        <party>R</party>
        <sponsorshipDate>2017-02-16</sponsorshipDate>
        <district>7</district>
        <lastName>CULBERSON</lastName>
        <fullName>Rep. Culberson, John Abney [R-TX-7]</fullName>
        <state>TX</state>
        <bioguideId>C001048</bioguideId>
        <middleName>ABNEY</middleName>
        <firstName>JOHN</firstName>
        <isOriginalCosponsor>True</isOriginalCosponsor>
        <sponsorshipWithdrawnDate />
        <identifiers>
          <lisID>1670</lisID>
          <gpoId>8163</gpoId>
          <bioguideId>C001048</bioguideId>
        </identifiers>
      </item>
      <item>
        <party>R</party>
        <sponsorshipDate>2017-02-16</sponsorshipDate>
        <district>3</district>
        <lastName>Fleischmann</lastName>
        <fullName>Rep. Fleischmann, Charles J. "Chuck" [R-TN-3]</fullName>
        <state>TN</state>
        <bioguideId>F000459</bioguideId>
        <middleName>J. "Chuck"</middleName>
        <firstName>Charles</firstName>
        <isOriginalCosponsor>True</isOriginalCosponsor>
        <sponsorshipWithdrawnDate />
        <identifiers>
          <bioguideId>F000459</bioguideId>
          <lisID>2061</lisID>
          <gpoId>8150</gpoId>
        </identifiers>
      </item>
      <item>
        <party>D</party>
        <sponsorshipDate>2017-04-28</sponsorshipDate>
        <district>5</district>
        <lastName>COOPER</lastName>
        <fullName>Rep. Cooper, Jim [D-TN-5]</fullName>
        <state>TN</state>
        <bioguideId>C000754</bioguideId>
        <middleName>H.</middleName>
        <firstName>JAMES</firstName>
        <isOriginalCosponsor>False</isOriginalCosponsor>
        <sponsorshipWithdrawnDate />
        <identifiers>
          <gpoId>8152</gpoId>
          <bioguideId>C000754</bioguideId>
          <lisID>231</lisID>
        </identifiers>
      </item>
      <item>
        <party>R</party>
        <sponsorshipDate>2017-07-27</sponsorshipDate>
        <district>6</district>
        <lastName>Black</lastName>
        <fullName>Rep. Black, Diane [R-TN-6]</fullName>
        <state>TN</state>
        <bioguideId>B001273</bioguideId>
        <middleName />
        <firstName>Diane</firstName>
        <isOriginalCosponsor>False</isOriginalCosponsor>
        <sponsorshipWithdrawnDate />
        <identifiers>
          <bioguideId>B001273</bioguideId>
          <lisID>2063</lisID>
          <gpoId>8153</gpoId>
        </identifiers>
      </item>
      <item>
        <party>D</party>
        <sponsorshipDate>2017-07-27</sponsorshipDate>
        <district>9</district>
        <lastName>Cohen</lastName>
        <fullName>Rep. Cohen, Steve [D-TN-9]</fullName>
        <state>TN</state>
        <bioguideId>C001068</bioguideId>
        <middleName />
        <firstName>Steve</firstName>
        <isOriginalCosponsor>False</isOriginalCosponsor>
        <sponsorshipWithdrawnDate />
        <identifiers>
          <gpoId>8156</gpoId>
          <bioguideId>C001068</bioguideId>
          <lisID>1878</lisID>
        </identifiers>
      </item>
    </cosponsors>
    <titles>
      <item>
        <title>Master Sergeant Roddie Edmonds Congressional Gold Medal Act</title>
        <titleType>(Extracted from GPO) Short Titles as Introduced</titleType>
        <chamberCode />
        <chamberName />
        <parentTitleType />
      </item>
      <item>
        <title>Master Sergeant Roddie Edmonds Congressional Gold Medal Act</title>
        <titleType>Short Titles as Introduced</titleType>
        <chamberCode />
        <chamberName />
        <parentTitleType />
      </item>
      <item>
        <title>To award a Congressional Gold Medal to Master Sergeant Rodrick "Roddie" Edmonds in recognition of his heroic actions during World War II.</title>
        <titleType>Official Title as Introduced</titleType>
        <chamberCode />
        <chamberName />
        <parentTitleType />
      </item>
      <item>
        <title>Master Sergeant Roddie Edmonds Congressional Gold Medal Act</title>
        <titleType>Display Title</titleType>
        <chamberCode />
        <chamberName />
        <parentTitleType />
      </item>
    </titles>
    <laws />
    <latestAction>
      <text>Referred to the House Committee on Financial Services.</text>
      <actionDate>2017-02-16</actionDate>
      <links />
    </latestAction>
    <billType>HR</billType>
    <introducedDate>2017-02-16</introducedDate>
    <title>Master Sergeant Roddie Edmonds Congressional Gold Medal Act</title>
    <sponsors>
      <item>
        <lastName>DUNCAN</lastName>
        <party>R</party>
        <fullName>Rep. Duncan, John J., Jr. [R-TN-2]</fullName>
        <bioguideId>D000533</bioguideId>
        <firstName>JOHN</firstName>
        <identifiers>
          <gpoId>8149</gpoId>
          <bioguideId>D000533</bioguideId>
          <lisID>322</lisID>
        </identifiers>
        <middleName>J.</middleName>
        <state>TN</state>
        <district>2</district>
        <byRequestType />
      </item>
    </sponsors>
    <billNumber>1142</billNumber>
    <subjects>
      <billSubjects>
        <legislativeSubjects>
          <item>
            <name>Conflicts and wars</name>
          </item>
          <item>
            <name>Congressional tributes</name>
          </item>
          <item>
            <name>Military personnel and dependents</name>
          </item>
        </legislativeSubjects>
        <policyArea>
          <name>Armed Forces and National Security</name>
        </policyArea>
      </billSubjects>
    </subjects>
    <committees>
      <billCommittees>
        <item>
          <chamber>House</chamber>
          <activities>
            <item>
              <date>2017-02-16T15:04:40Z</date>
              <name>Referred to</name>
            </item>
          </activities>
          <type>Standing</type>
          <subcommittees />
          <name>Financial Services Committee</name>
          <systemCode>hsba00</systemCode>
        </item>
      </billCommittees>
    </committees>
    <amendments />
    <originChamber>House</originChamber>
  </bill>
  <dublinCore xmlns:dc="http://purl.org/dc/elements/1.1/">
    <dc:format>text/xml</dc:format>
    <dc:language>EN</dc:language>
    <dc:rights>Pursuant to Title 17 Section 105 of the United States Code, this file is not subject to copyright protection and is in the public domain.</dc:rights>
    <dc:contributor>Congressional Research Service, Library of Congress</dc:contributor>
    <dc:description>This file contains bill summaries and statuses for federal legislation. A bill summary describes the most significant provisions of a piece of legislation and details the effects the legislative text may have on current law and federal programs. Bill summaries are authored by the Congressional Research Service (CRS) of the Library of Congress. As stated in Public Law 91-510 (2 USC 166 (d)(6)), one of the duties of CRS is "to prepare summaries and digests of bills and resolutions of a public general nature introduced in the Senate or House of Representatives". For more information, refer to the User Guide that accompanies this file.</dc:description>
  </dublinCore>
</billStatus>


text:
package no.asgari.civilization.server.exception;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

public class PlayerExistException extends WebApplicationException {
    public PlayerExistException() {
        super(Response.status(Response.Status.BAD_REQUEST)
                .entity("{\"error:\" \"Player already exists!\"}")
                .type(MediaType.APPLICATION_JSON)
                .build());
    }
}


text:
using System;

namespace System.Web.UI {

	[AttributeUsage (AttributeTargets.Property)]
	internal sealed class IgnoreUnknownContentAttribute : Attribute
	{

		public IgnoreUnknownContentAttribute ()
		{
		}
	}
}


text:
using System.Management.Automation;
using Docker.DotNet.Models;

namespace Docker.PowerShell.Cmdlets
{
    public abstract class SingleContainerOperationCmdlet : DkrCmdlet
    {
        #region Parameters

        [Parameter(ParameterSetName = CommonParameterSetNames.Default,
            ValueFromPipeline = true,
                   Position = 0,
                   Mandatory = true)]
        [ValidateNotNullOrEmpty]
        [ArgumentCompleter(typeof(ContainerArgumentCompleter))]
        [Alias("Name", "Id")]
        public string ContainerIdOrName { get; set; }

        [Parameter(ParameterSetName = CommonParameterSetNames.ContainerObject,
            ValueFromPipeline = true,
                   Position = 0,
                   Mandatory = true)]
        [ValidateNotNullOrEmpty]
        public ContainerListResponse Container { get; set; }

        #endregion
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.20"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Luwra: luwra::internal::_MakeIndexSequence< 0, Indices... > Struct Template Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Luwra

Minimal-overhead Lua wrapper for C++

luwra

internal

_MakeIndexSequence< 0, Indices... >

Public Types |
List of all members

luwra::internal::_MakeIndexSequence< 0, Indices... > Struct Template Reference

Public Types

using 	Result = IndexSequence< Indices... >

Member Typedef Documentation

◆ Result

template<size_t... Indices>

          using luwra::internal::_MakeIndexSequence< 0, Indices... >::Result =  IndexSequence<Indices...>

<address class="footer">
Generated by  1.8.20
</address>


text:
'use strict';

const {assert} = require('chai');
const cleanup = require('./clean.js');
const {describe, it, before} = require('mocha');
const {RealmsServiceClient} = require('@google-cloud/game-servers');

const cp = require('child_process');
const uuid = require('uuid');

const execSync = cmd => cp.execSync(cmd, {encoding: 'utf-8'});

const LOCATION = 'us-central1';

describe('Game Servers Delete Realm Test', () => {
  const client = new RealmsServiceClient();
  let realmId;

  before(async () => {
    const projectId = await client.getProjectId();

    // Clean up any stray realms
    await cleanup();

    realmId = `test-${uuid.v4()}`;

    await client.createRealm({
      parent: `projects/${projectId}/locations/${LOCATION}`,
      realmId: realmId,
      realm: {
        timeZone: 'US/Pacific',
        description: 'Test Game Realm',
      },
    });
  });

  it('should delete a realm', async () => {
    const projectId = await client.getProjectId();

    const delete_output = execSync(
      `node delete_realm.js ${projectId} ${LOCATION} ${realmId}`
    );
    assert.match(delete_output, /deleted./);
  });
});


text:
@interface Xcode3VariantGroupLocalizationsInspector : Xcode3LocalizationsInspector
{
}

- (id)conversionFileDataType;
- (id)fileDataType;
- (id)variantGroup;

@end


text:
<?php

/**
 * @see EasyRdf_Exception
 */
require_once "EasyRdf/Exception.php";

/**
 * Class that represents an HTTP 1.0 / 1.1 response message.
 *
 * @package    EasyRdf
 * @copyright  Copyright (c) 2009-2010 Nicholas J Humfrey
 *             Copyright (c) 2005-2009 Zend Technologies USA Inc.
 * @license    http://www.opensource.org/licenses/bsd-license.php
 */
class EasyRdf_Http_Response
{

    /**
     * The HTTP response status code
     *
     * @var int
     */
    private $_status;

    /**
     * The HTTP response code as string
     * (e.g. 'Not Found' for 404 or 'Internal Server Error' for 500)
     *
     * @var string
     */
    private $_message;

    /**
     * The HTTP response headers array
     *
     * @var array
     */
    private $_headers = array();

    /**
     * The HTTP response body
     *
     * @var string
     */
    private $_body;

    /**
     * Constructor.
     *
     * @param  int     $status HTTP Status code
     * @param  array   $headers The HTTP response headers
     * @param  string  $body The content of the response
     * @param  string  $version The HTTP Version (1.0 or 1.1)
     * @param  string  $message The HTTP response Message
     * @return object  EasyRdf_Http_Response
     */
    public function __construct(
        $status, $headers, $body = null,
        $version = '1.1', $message = null
    )
    {
        $this->_status = $status;
        $this->_body = $body;
        $this->_version = $version;
        $this->_message = $message;

        foreach ($headers as $k => $v) {
            $k = ucwords(strtolower($k));
            $this->_headers[$k] = $v;
        }
    }

    /**
     * Check whether the response in successful
     *
     * @return boolean
     */
    public function isSuccessful()
    {
        return ($this->_status >= 200 && $this->_status < 300);
    }

    /**
     * Check whether the response is an error
     *
     * @return boolean
     */
    public function isError()
    {
        return ($this->_status >= 400 && $this->_status < 600);
    }

    /**
     * Check whether the response is a redirection
     *
     * @return boolean
     */
    public function isRedirect()
    {
        return ($this->_status >= 300 && $this->_status < 400);
    }

    /**
     * Get the HTTP response status code
     *
     * @return int
     */
    public function getStatus()
    {
        return $this->_status;
    }

    /**
     * Return a message describing the HTTP response code
     * (Eg. "OK", "Not Found", "Moved Permanently")
     *
     * @return string
     */
    public function getMessage()
    {
        return $this->_message;
    }

    /**
     * Get the response body as string
     *
     * @return string
     */
    public function getBody()
    {
        // Decode the body if it was transfer-encoded
        switch (strtolower($this->getHeader('transfer-encoding'))) {
            // Handle chunked body
            case 'chunked':
                return self::decodeChunkedBody($this->_body);
                break;

            // No transfer encoding, or unknown encoding extension:
            // return body as is
            default:
                return $this->_body;
                break;
        }
    }

    /**
     * Get the HTTP version of the response
     *
     * @return string
     */
    public function getVersion()
    {
        return $this->_version;
    }

    /**
     * Get the response headers
     *
     * @return array
     */
    public function getHeaders()
    {
        return $this->_headers;
    }

    /**
     * Get a specific header as string, or null if it is not set
     *
     * @param string$header
     * @return string|array|null
     */
    public function getHeader($header)
    {
        $header = ucwords(strtolower($header));
        if (array_key_exists($header, $this->_headers)) {
            return $this->_headers[$header];
        } else {
            return null;
        }
    }

    /**
     * Create an EasyRdf_Http_Response object from a HTTP response string
     *
     * @param string $responseStr
     * @return EasyRdf_Http_Response
     */
    public static function fromString($responseStr)
    {
        // First, split body and headers
        $matches = preg_split('|(?:\r?\n){2}|m', $responseStr, 2);
        if ($matches and sizeof($matches) == 2) {
            list ($headerLines, $body) = $matches;
        } else {
            throw new EasyRdf_Exception(
                "Failed to parse HTTP response."
            );
        }

        // Split headers part to lines
        $headerLines = preg_split('|[\r\n]+|m', $headerLines);
        $status = array_shift($headerLines);
        if (preg_match("|^HTTP/([\d\.x]+) (\d+) ([^\r\n]+)|", $status, $m)) {
            $version = $m[1];
            $status = $m[2];
            $message = $m[3];
        } else {
            throw new EasyRdf_Exception(
                "Failed to parse HTTP response status line."
            );
        }

        // Process the rest of the header lines
        $headers = array();
        foreach ($headerLines as $line) {
            if (preg_match("|^([\w-]+):\s+(.+)$|", $line, $m)) {
                $hName = ucwords(strtolower($m[1]));
                $hValue = $m[2];

                if (isset($headers[$hName])) {
                    if (! is_array($headers[$hName])) {
                        $headers[$hName] = array($headers[$hName]);
                    }
                    $headers[$hName][] = $hValue;
                } else {
                    $headers[$hName] = $hValue;
                }
            }
        }

        return new EasyRdf_Http_Response(
            $status, $headers, $body, $version, $message
        );
    }

    /**
     * Decode a "chunked" transfer-encoded body and return the decoded text
     *
     * @param string $body
     * @return string
     */
    public static function decodeChunkedBody($body)
    {
        $decBody = '';

        while (trim($body)) {
            if (preg_match("/^([\da-fA-F]+)[^\r\n]*\r\n/sm", $body, $m)) {
                $length = hexdec(trim($m[1]));
                $cut = strlen($m[0]);
                $decBody .= substr($body, $cut, $length);
                $body = substr($body, $cut + $length + 2);
            } else {
                throw new EasyRdf_Exception(
                    "Failed to decode chunked body in HTTP response."
                );
            }
        }

        return $decBody;
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Example5.java: SPARQL query with JOIN_METHOD</title>
    <link rel="stylesheet" href="gettingStarted.css" type="text/css" />
    <meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
    <link rel="start" href="index.html" title="RDF Graph for Oracle NoSQL Database" />
    <link rel="up" href="quickstart.html" title="Chapter 8. Quick Start for the RDF Graph Feature" />
    <link rel="prev" href="example4.html" title="Example4.java: Query family relationships on a named graph" />
    <link rel="next" href="example5b.html" title="Example5b.java: SPARQL query with ORDERED query option" />

Library Version 12.1.3.5

           Example5.java: SPARQL query with JOIN_METHOD

          Prev
          Chapter 8. Quick Start for the RDF Graph Feature
           Next

 Example5.java: SPARQL query with JOIN_METHOD

            This example shows a SPARQL query with additional
            features including the selection of a join_method
            (JOIN_METHOD={nl, hash}) used to select the join method to
            use in operations over query patterns. It loads the quads
            contained in RDF file example.nt located in the examples
            directory of the RDF Graph feature that assert the
            following:

                    In graph
                    <http://example.org/alice/foaf.rdf>:

                            Alice is a Person.

                            Alice's name is "Alice".

                            Alice knows Bob.

                            Bob has a home page with URL
                            http://example.org/bob.

                            To see more details on Bob, refer to
                            http://example.org/alice/foaf.rdf.

                    In graph
                    <http://example.org/bob/foaf.rdf>:

                            Bob is a Person.

                            Bob's name is "Bob".

                            Bob has a home page with URL
                            http://example.org/bob.

            It then finds all the names of the people in graph
            <http://example.org/alice/foaf.rdf> who knows
            another person, using nested loop join operations to merge
            bindings retrieved between the query patterns in the
            SPARQL query.

import com.hp.hpl.jena.query.*;
import org.openjena.riot.Lang;
import com.hp.hpl.jena.sparql.core.DatasetImpl;
import oracle.rdf.kv.client.jena.*;

public class Example5
{

public static void main(String[] args) throws Exception
  {

String szStoreName  = args[0];
String szHostName   = args[1];
String szHostPort   = args[2];

// Create connection
OracleNoSqlConnection conn
     = OracleNoSqlConnection.createInstance(szStoreName,
                                            szHostName,
                                            szHostPort);

// Create the datasetgraph
OracleGraphNoSql graph = new OracleGraphNoSql(conn);
DatasetGraphNoSql datasetGraph = DatasetGraphNoSql.createFrom(graph);

// Close graph, as it is no longer needed
graph.close();

// Clear dataset
datasetGraph.clearRepository();

Dataset ds = DatasetImpl.wrap(datasetGraph);

// Load data from file into the dataset
DatasetGraphNoSql.load("example.nt", Lang.NQUADS, conn,
                           "http://example.com"); //base URI

// change hint to hash to test hash join, or remove to use default
// join settings
String szQuery =
" PREFIX ORACLE_SEM_FS_NS: "                         +
" <http://oracle.com/semtech#join_method=nl>"        +
" PREFIX foaf: <http://xmlns.com/foaf/0.1/>"         +
" SELECT ?name1 ?name2 "                             +
" WHERE { "                                          +
"   graph <http://example.org/alice/foaf.rdf> { "    +
"     ?person1 foaf:knows ?person2 . "               +
"     ?person1 foaf:name ?name1 . "                  +
"     ?person2 foaf:name ?name2 . "                  +
"   } "                                              +
" } ";

System.out.println("Execute query " + szQuery);

Query query = QueryFactory.create(szQuery);
QueryExecution qexec = QueryExecutionFactory.create(query, ds);

try {
      ResultSet results = qexec.execSelect();
      ResultSetFormatter.out(System.out, results, query);
    }

finally {
      qexec.close();
    }

ds.close();
conn.dispose();
  }
}

            The following are the commands to compile and run
            this example, as well as the expected output of the java
            command.

javac -classpath ./:./jena-core-2.7.4.jar:./jena-arq-2.9.4.jar: \
./sdordfnosqlclient.jar:./kvclient.jar:./xercesImpl-2.10.0.jar: \
./slf4j-api-1.6.4.jar:./slf4j-log4j12-1.6.4.jar:./log4j/1.2.16.jar: \
./jena-iri-0.9.4.jar:./xml-apis-1.4.01.jar Example5.java

javac -classpath ./:./jena-core-2.7.4.jar:./jena-arq-2.9.4.jar: \
./sdordfnosqlclient.jar:./kvclient.jar:./xercesImpl-2.10.0.jar: \
./slf4j-api-1.6.4.jar:./slf4j-log4j12-1.6.4.jar:./log4j/1.2.16.jar: \
./jena-iri-0.9.4.jar:./xml-apis-1.4.01.jar Example5 <store_name> \
<host_name> <host_port>
-------------------
| name1   | name2 |
===================
| "Alice" | "Bob" |
-------------------

            You can test hash join selection by modifying the
            following line in the code. The output of this Java class
            will be the same as the one presented before.

PREFIX ORACLE_SEM_FS_NS: <http://oracle.com/semtech#join_method=hash>

          Prev

            Up

           Next

           Example4.java: Query family relationships on a named graph

            Home

           Example5b.java: SPARQL query with ORDERED query option


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Agaric. mod. Tax. (Koenigstein), Edn 4 686 (1986)

#### Original name
Crepidotus puberulus Peck

### Remarks
null


text:
import base64
import datetime
import getpass
import logging
import os.path
import socket
import sys
import time

from django.conf import settings as django_settings
from django.contrib.auth.models import User
from django.core import mail
from django.core.urlresolvers import reverse
from django.core.signals import got_request_exception
from django.test import TestCase, TransactionTestCase
from django.template import TemplateSyntaxError
from django.utils.encoding import smart_unicode
from django.utils.functional import lazy

from sentry.client.base import SentryClient
from sentry.client.handlers import SentryHandler
from sentry.client.models import get_client
from sentry.conf import settings
from sentry.models import Message, GroupedMessage
from sentry.utils import json
from sentry.utils import transform, get_signature, get_auth_header
from sentry.utils.compat import pickle

from models import TestModel, DuplicateKeyModel
from utils import TestServerThread, conditional_on_module

# class NullHandler(logging.Handler):
#     def emit(self, record):
#         pass
#
# # Configure our "oh shit" handler, so that we dont output a bunch of unused
# # information to stderr
#
# logger = logging.getLogger('sentry.error')
# logger.addHandler(NullHandler())

# Configure our test handler

logger = logging.getLogger('sentry.test')
logger.addHandler(SentryHandler())
logger.setLevel(logging.DEBUG)

class BaseTestCase(TestCase):
    ## Helper methods for posting

    urls = 'tests.urls'

    def _postWithKey(self, data):
        resp = self.client.post(reverse('sentry-store'), {
            'data': base64.b64encode(pickle.dumps(transform(data))),
            'key': settings.KEY,
        })
        return resp

    def _postWithSignature(self, data):
        ts = time.time()
        message = base64.b64encode(json.dumps(transform(data)))
        sig = get_signature(message, ts)

        resp = self.client.post(reverse('sentry-store'), message,
            content_type='application/octet-stream',
            HTTP_AUTHORIZATION=get_auth_header(sig, ts, '_postWithSignature'),
        )
        return resp

class SentryTestCase(BaseTestCase):
    ## Fixture setup/teardown

    def setUp(self):
        self._middleware = django_settings.MIDDLEWARE_CLASSES
        self._handlers = None
        self._level = None
        self.logger = logging.getLogger('sentry')
        self.logger.addHandler(logging.StreamHandler())
        Message.objects.all().delete()
        GroupedMessage.objects.all().delete()

    def tearDown(self):
        self.tearDownHandler()
        django_settings.MIDDLEWARE_CLASSES = self._middleware

    def setUpHandler(self):
        self.tearDownHandler()

        logger = logging.getLogger()
        self._handlers = logger.handlers
        self._level = logger.level

        for h in self._handlers:
            # TODO: fix this, for now, I don't care.
            logger.removeHandler(h)

        logger.setLevel(logging.DEBUG)
        sentry_handler = SentryHandler()
        logger.addHandler(sentry_handler)

    def tearDownHandler(self):
        if self._handlers is None:
            return

        logger = logging.getLogger()
        logger.removeHandler(logger.handlers[0])
        for h in self._handlers:
            logger.addHandler(h)

        logger.setLevel(self._level)
        self._handlers = None

    ## Tests

    def test_logger(self):
        logger = logging.getLogger()

        self.setUpHandler()

        logger.error('This is a test error')
        self.assertEquals(Message.objects.count(), 1)
        self.assertEquals(GroupedMessage.objects.count(), 1)
        last = Message.objects.get()
        self.assertEquals(last.logger, 'root')
        self.assertEquals(last.level, logging.ERROR)
        self.assertEquals(last.message, 'This is a test error')

        logger.warning('This is a test warning')
        self.assertEquals(Message.objects.count(), 2)
        self.assertEquals(GroupedMessage.objects.count(), 2)
        last = Message.objects.all().order_by('-id')[0:1].get()
        self.assertEquals(last.logger, 'root')
        self.assertEquals(last.level, logging.WARNING)
        self.assertEquals(last.message, 'This is a test warning')

        logger.error('This is a test error')
        self.assertEquals(Message.objects.count(), 3)
        self.assertEquals(GroupedMessage.objects.count(), 2)
        last = Message.objects.all().order_by('-id')[0:1].get()
        self.assertEquals(last.logger, 'root')
        self.assertEquals(last.level, logging.ERROR)
        self.assertEquals(last.message, 'This is a test error')

        logger = logging.getLogger('test')
        logger.info('This is a test info')
        self.assertEquals(Message.objects.count(), 4)
        self.assertEquals(GroupedMessage.objects.count(), 3)
        last = Message.objects.all().order_by('-id')[0:1].get()
        self.assertEquals(last.logger, 'test')
        self.assertEquals(last.level, logging.INFO)
        self.assertEquals(last.message, 'This is a test info')

        logger.info('This is a test info with a url', extra=dict(url='http://example.com'))
        self.assertEquals(Message.objects.count(), 5)
        self.assertEquals(GroupedMessage.objects.count(), 4)
        last = Message.objects.all().order_by('-id')[0:1].get()
        self.assertEquals(last.url, 'http://example.com')

        try:
            raise ValueError('This is a test ValueError')
        except ValueError:
            logger.info('This is a test info with an exception', exc_info=True)
            self.assertEquals(Message.objects.count(), 6)
            self.assertEquals(GroupedMessage.objects.count(), 5)
            last = Message.objects.all().order_by('-id')[0:1].get()
            self.assertEquals(last.class_name, 'ValueError')
            self.assertEquals(last.message, 'This is a test info with an exception')
            self.assertTrue(last.data.get('__sentry__', {}).get('exc'))

        self.tearDownHandler()

    # def test_404_middleware(self):
    #     django_settings.MIDDLEWARE_CLASSES = django_settings.MIDDLEWARE_CLASSES + ('sentry.client.middleware.Sentry404CatchMiddleware',)
    #
    #     response = self.client.get("/404/this-page-does-not-exist", REMOTE_ADDR="127.0.0.1:8000")
    #     self.assertTemplateUsed(response, '404.html')
    #
    #     self.assertEquals(Message.objects.count(), 1)
    #     self.assertEquals(GroupedMessage.objects.count(), 1)
    #     last = Message.objects.get()
    #     self.assertEquals(last.logger, 'root')
    #     self.assertEquals(last.class_name, 'Http404')
    #     self.assertEquals(last.level, logging.ERROR)
    #     self.assertEquals(last.message, 'foo')

    def test_api(self):
        try:
            Message.objects.get(id=999999989)
        except Message.DoesNotExist, exc:
            message_id = get_client().create_from_exception()
            error = Message.objects.get(message_id=message_id)
            self.assertTrue(error.data.get('__sentry__', {}).get('exc'))
        else:
            self.fail('Unable to create `Message` entry.')

        try:
            Message.objects.get(id=999999989)
        except Message.DoesNotExist, exc:
            message_id = get_client().create_from_exception()
            error = Message.objects.get(message_id=message_id)
            self.assertTrue(error.data.get('__sentry__', {}).get('exc'))
        else:
            self.fail('Unable to create `Message` entry.')

        self.assertEquals(Message.objects.count(), 2)
        self.assertEquals(GroupedMessage.objects.count(), 2)
        last = Message.objects.all().order_by('-id')[0:1].get()
        self.assertEquals(last.logger, 'root')
        self.assertEquals(last.class_name, 'DoesNotExist')
        self.assertEquals(last.level, logging.ERROR)
        self.assertEquals(last.message, smart_unicode(exc))

        get_client().create_from_text('This is an error', level=logging.DEBUG)

        self.assertEquals(Message.objects.count(), 3)
        self.assertEquals(GroupedMessage.objects.count(), 3)
        last = Message.objects.all().order_by('-id')[0:1].get()
        self.assertEquals(last.logger, 'root')
        self.assertEquals(last.level, logging.DEBUG)
        self.assertEquals(last.message, 'This is an error')

    def test_alternate_database(self):
        settings.DATABASE_USING = 'default'

        try:
            Message.objects.get(id=999999979)
        except Message.DoesNotExist, exc:
            get_client().create_from_exception()
        else:
            self.fail('Unable to create `Message` entry.')

        self.assertEquals(Message.objects.count(), 1)
        self.assertEquals(GroupedMessage.objects.count(), 1)
        last = Message.objects.get()
        self.assertEquals(last.logger, 'root')
        self.assertEquals(last.class_name, 'DoesNotExist')
        self.assertEquals(last.level, logging.ERROR)
        self.assertEquals(last.message, smart_unicode(exc))

        settings.DATABASE_USING = None

    def test_incorrect_unicode(self):
        self.setUpHandler()

        cnt = Message.objects.count()
        value = 'רונית מגן'

        message_id = get_client().create_from_text(value)
        error = Message.objects.get(message_id=message_id)

        self.assertEquals(Message.objects.count(), cnt+1)
        self.assertEquals(error.message, u'רונית מגן')

        logging.info(value)
        self.assertEquals(Message.objects.count(), cnt+2)

        x = TestModel.objects.create(data={'value': value})
        logging.warn(x)
        self.assertEquals(Message.objects.count(), cnt+3)

        try:
            raise SyntaxMessage(value)
        except Exception, exc:
            logging.exception(exc)
            logging.info('test', exc_info=True)
        self.assertEquals(Message.objects.count(), cnt+5)

        self.tearDownHandler()

    def test_correct_unicode(self):
        self.setUpHandler()

        cnt = Message.objects.count()
        value = 'רונית מגן'.decode('utf-8')

        message_id = get_client().create_from_text(value)
        error = Message.objects.get(message_id=message_id)

        self.assertEquals(Message.objects.count(), cnt+1)
        self.assertEquals(error.message, value)

        logging.info(value)
        self.assertEquals(Message.objects.count(), cnt+2)

        x = TestModel.objects.create(data={'value': value})
        logging.warn(x)
        self.assertEquals(Message.objects.count(), cnt+3)

        try:
            raise SyntaxMessage(value)
        except Exception, exc:
            logging.exception(exc)
            logging.info('test', exc_info=True)
        self.assertEquals(Message.objects.count(), cnt+5)

        self.tearDownHandler()

    def test_long_urls(self):
        # Fix: #6 solves URLs > 200 characters
        message_id = get_client().create_from_text('hello world', url='a'*210)
        error = Message.objects.get(message_id=message_id)

        self.assertEquals(error.url, 'a'*200)
        self.assertEquals(error.data['url'], 'a'*210)

    def test_thrashing(self):
        settings.THRASHING_LIMIT = 10
        settings.THRASHING_TIMEOUT = 60

        Message.objects.all().delete()
        GroupedMessage.objects.all().delete()

        message_id = None
        for i in range(0, 10):
            this_message_id = get_client().create_from_text('hi')
            self.assertTrue(this_message_id is not None)
            self.assertNotEquals(this_message_id, message_id)
            message_id = this_message_id

        for i in range(0, 40):
            this_message_id = get_client().create_from_text('hi')
            self.assertEquals(this_message_id, message_id)

        self.assertEquals(Message.objects.count(), settings.THRASHING_LIMIT)

    def test_signals(self):
        try:
            Message.objects.get(id=999999999)
        except Message.DoesNotExist, exc:
            got_request_exception.send(sender=self.__class__, request=None)
        else:
            self.fail('Expected an exception.')

        self.assertEquals(Message.objects.count(), 1)
        self.assertEquals(GroupedMessage.objects.count(), 1)
        last = Message.objects.get()
        self.assertEquals(last.logger, 'root')
        self.assertEquals(last.class_name, 'DoesNotExist')
        self.assertEquals(last.level, logging.ERROR)
        self.assertEquals(last.message, smart_unicode(exc))

    def test_signals_without_request(self):
        try:
            Message.objects.get(id=999999999)
        except Message.DoesNotExist, exc:
            got_request_exception.send(sender=self.__class__, request=None)
        else:
            self.fail('Expected an exception.')

        self.assertEquals(Message.objects.count(), 1)
        self.assertEquals(GroupedMessage.objects.count(), 1)
        last = Message.objects.get()
        self.assertEquals(last.logger, 'root')
        self.assertEquals(last.class_name, 'DoesNotExist')
        self.assertEquals(last.level, logging.ERROR)
        self.assertEquals(last.message, smart_unicode(exc))

    def test_no_thrashing(self):
        prev = settings.THRASHING_LIMIT
        settings.THRASHING_LIMIT = 0

        Message.objects.all().delete()
        GroupedMessage.objects.all().delete()

        for i in range(0, 50):
            get_client().create_from_text('hi')

        self.assertEquals(Message.objects.count(), 50)

        settings.THRASHING_LIMIT = prev

    def test_database_message(self):
        from django.db import connection

        try:
            cursor = connection.cursor()
            cursor.execute("select foo")
        except:
            got_request_exception.send(sender=self.__class__)

        self.assertEquals(Message.objects.count(), 1)
        self.assertEquals(GroupedMessage.objects.count(), 1)

    def test_integrity_message(self):
        DuplicateKeyModel.objects.create()
        try:
            DuplicateKeyModel.objects.create()
        except:
            got_request_exception.send(sender=self.__class__)
        else:
            self.fail('Excepted an IntegrityMessage to be raised.')

        self.assertEquals(Message.objects.count(), 1)
        self.assertEquals(GroupedMessage.objects.count(), 1)

    def test_view_exception(self):
        self.assertRaises(Exception, self.client.get, reverse('sentry-raise-exc'))

        self.assertEquals(GroupedMessage.objects.count(), 1)
        self.assertEquals(Message.objects.count(), 1)
        last = Message.objects.get()
        self.assertEquals(last.logger, 'root')
        self.assertEquals(last.class_name, 'Exception')
        self.assertEquals(last.level, logging.ERROR)
        self.assertEquals(last.message, 'view exception')
        self.assertEquals(last.view, 'tests.views.raise_exc')

    def test_request_middlware_exception(self):
        orig = list(django_settings.MIDDLEWARE_CLASSES)
        django_settings.MIDDLEWARE_CLASSES = orig + ['tests.middleware.BrokenRequestMiddleware',]

        self.assertRaises(ImportError, self.client.get, reverse('sentry'))
        self.assertEquals(Message.objects.count(), 1)
        self.assertEquals(GroupedMessage.objects.count(), 1)
        last = Message.objects.get()
        self.assertEquals(last.logger, 'root')
        self.assertEquals(last.class_name, 'ImportError')
        self.assertEquals(last.level, logging.ERROR)
        self.assertEquals(last.message, 'request')
        self.assertEquals(last.view, 'tests.middleware.process_request')

        django_settings.MIDDLEWARE_CLASSES = orig

    # XXX: Django doesn't handle response middleware exceptions (yet)
    # def test_response_middlware_exception(self):
    #     orig = list(django_settings.MIDDLEWARE_CLASSES)
    #     django_settings.MIDDLEWARE_CLASSES = orig + ['tests.middleware.BrokenResponseMiddleware',]
    #
    #     self.assertRaises(ImportError, self.client.get, reverse('sentry'))
    #     self.assertEquals(Message.objects.count(), 1)
    #     self.assertEquals(GroupedMessage.objects.count(), 1)
    #     last = Message.objects.get()
    #     self.assertEquals(last.logger, 'root')
    #     self.assertEquals(last.class_name, 'ImportError')
    #     self.assertEquals(last.level, logging.ERROR)
    #     self.assertEquals(last.message, 'response')
    #     self.assertEquals(last.view, 'tests.middleware.process_response')
    #
    #     django_settings.MIDDLEWARE_CLASSES = orig

    def test_view_middleware_exception(self):
        orig = list(django_settings.MIDDLEWARE_CLASSES)
        django_settings.MIDDLEWARE_CLASSES = orig + ['tests.middleware.BrokenViewMiddleware',]

        self.assertRaises(ImportError, self.client.get, reverse('sentry'))
        self.assertEquals(Message.objects.count(), 1)
        self.assertEquals(GroupedMessage.objects.count(), 1)
        last = Message.objects.get()
        self.assertEquals(last.logger, 'root')
        self.assertEquals(last.class_name, 'ImportError')
        self.assertEquals(last.level, logging.ERROR)
        self.assertEquals(last.message, 'view')
        self.assertEquals(last.view, 'tests.middleware.process_view')

        django_settings.MIDDLEWARE_CLASSES = orig

    def test_setting_name(self):
        orig_name = settings.NAME
        orig_site = settings.SITE
        settings.NAME = 'foo'
        settings.SITE = 'bar'

        self.assertRaises(Exception, self.client.get, reverse('sentry-raise-exc'))

        self.assertEquals(Message.objects.count(), 1)
        self.assertEquals(GroupedMessage.objects.count(), 1)
        last = Message.objects.get()
        self.assertEquals(last.logger, 'root')
        self.assertEquals(last.class_name, 'Exception')
        self.assertEquals(last.level, logging.ERROR)
        self.assertEquals(last.message, 'view exception')
        self.assertEquals(last.server_name, 'foo')
        self.assertEquals(last.site, 'bar')
        self.assertEquals(last.view, 'tests.views.raise_exc')

        settings.NAME = orig_name
        settings.SITE = orig_site

    def test_exclusion_view_path(self):
        try: Message.objects.get(pk=1341324)
        except: get_client().create_from_exception()

        last = Message.objects.get()

        self.assertEquals(last.view, 'tests.tests.test_exclusion_view_path')

    def test_best_guess_view(self):
        settings.EXCLUDE_PATHS = ['tests.tests']

        try: Message.objects.get(pk=1341324)
        except: get_client().create_from_exception()

        last = Message.objects.get()

        self.assertEquals(last.view, 'tests.tests.test_best_guess_view')

        settings.EXCLUDE_PATHS = []

    def test_exclude_modules_view(self):
        settings.EXCLUDE_PATHS = ['tests.views.decorated_raise_exc']

        self.assertRaises(Exception, self.client.get, reverse('sentry-raise-exc-decor'))

        last = Message.objects.get()

        self.assertEquals(last.view, 'tests.views.raise_exc')

        settings.EXCLUDE_PATHS = []

    def test_varying_messages(self):
        self.assertRaises(Exception, self.client.get, reverse('sentry-raise-exc') + '?message=foo')
        self.assertRaises(Exception, self.client.get, reverse('sentry-raise-exc') + '?message=bar')
        self.assertRaises(Exception, self.client.get, reverse('sentry-raise-exc') + '?message=gra')

        self.assertEquals(GroupedMessage.objects.count(), 1)

    def test_include_modules(self):
        settings.INCLUDE_PATHS = ['django.shortcuts.get_object_or_404']

        self.assertRaises(Exception, self.client.get, reverse('sentry-django-exc'))

        last = Message.objects.get()

        self.assertEquals(last.view, 'django.shortcuts.get_object_or_404')

        settings.INCLUDE_PATHS = []

    def test_template_name_as_view(self):
        self.assertRaises(TemplateSyntaxError, self.client.get, reverse('sentry-template-exc'))

        last = Message.objects.get()

        self.assertEquals(last.view, 'sentry-tests/error.html')

    def test_request_in_logging(self):
        resp = self.client.get(reverse('sentry-log-request-exc'))
        self.assertEquals(resp.status_code, 200)

        last = Message.objects.get()

        self.assertEquals(last.view, 'tests.views.logging_request_exc')
        self.assertEquals(last.data['META']['REMOTE_ADDR'], '127.0.0.1')

    def test_sample_data_in_group(self):
        resp = self.client.get(reverse('sentry-log-request-exc'))
        self.assertEquals(resp.status_code, 200)

        last = GroupedMessage.objects.get()

        self.assertEquals(last.view, 'tests.views.logging_request_exc')
        self.assertEquals(last.data['url'], 'http://testserver' + reverse('sentry-log-request-exc'))

    def test_create_from_record_none_exc_info(self):
        # sys.exc_info can return (None, None, None) if no exception is being
        # handled anywhere on the stack. See:
        #  http://docs.python.org/library/sys.html#sys.exc_info
        client = get_client()
        record = logging.LogRecord(
            'foo',
            logging.INFO,
            pathname=None,
            lineno=None,
            msg='test',
            args=(),
            exc_info=(None, None, None),
        )
        message_id = client.create_from_record(record)
        message = Message.objects.get(message_id=message_id)

        self.assertEquals('test', message.message)

    def test_group_formatting(self):
        logger = logging.getLogger()

        self.setUpHandler()

        logger.error('This is a test %s', 'error')
        self.assertEquals(Message.objects.count(), 1)
        self.assertEquals(GroupedMessage.objects.count(), 1)
        last = Message.objects.get()
        self.assertEquals(last.logger, 'root')
        self.assertEquals(last.level, logging.ERROR)
        self.assertEquals(last.message, 'This is a test error')

        logger.error('This is a test %s', 'message')
        logger.error('This is a test %s', 'foo')

        self.assertEquals(Message.objects.count(), 3)
        self.assertEquals(GroupedMessage.objects.count(), 1)

    def test_uuid(self):
        import uuid

        logger = logging.getLogger()

        self.setUpHandler()

        uuid = uuid.uuid4()

        logger.error('Test', extra={'data': {'uuid': uuid}})
        self.assertEquals(Message.objects.count(), 1)
        self.assertEquals(GroupedMessage.objects.count(), 1)
        last = Message.objects.get()
        self.assertEquals(last.logger, 'root')
        self.assertEquals(last.level, logging.ERROR)
        self.assertEquals(last.message, 'Test')
        self.assertEquals(last.data['uuid'], repr(uuid))

    def test_versions(self):
        import sentry
        resp = self.client.get(reverse('sentry-log-request-exc'))
        self.assertEquals(resp.status_code, 200)

        self.assertEquals(Message.objects.count(), 1)
        self.assertEquals(GroupedMessage.objects.count(), 1)

        last = Message.objects.get()
        self.assertTrue('versions' in last.data['__sentry__'], last.data['__sentry__'])
        self.assertTrue('sentry' in last.data['__sentry__']['versions'], last.data['__sentry__'])
        self.assertEquals(last.data['__sentry__']['versions']['sentry'], sentry.VERSION)
        self.assertTrue('module' in last.data['__sentry__'], last.data['__sentry__'])
        self.assertEquals(last.data['__sentry__']['module'], 'tests')
        self.assertTrue('version' in last.data['__sentry__'], last.data['__sentry__'])
        self.assertEquals(last.data['__sentry__']['version'], '1.0')

        last = GroupedMessage.objects.get()
        self.assertTrue('module' in last.data)
        self.assertEquals(last.data['module'], 'tests')
        self.assertTrue('version' in last.data)
        self.assertEquals(last.data['version'], '1.0')

    def test_404_middleware(self):
        existing = django_settings.MIDDLEWARE_CLASSES

        django_settings.MIDDLEWARE_CLASSES = (
            'sentry.client.middleware.Sentry404CatchMiddleware',
        ) + django_settings.MIDDLEWARE_CLASSES

        resp = self.client.get('/non-existant-page')
        self.assertEquals(resp.status_code, 404)

        self.assertEquals(Message.objects.count(), 1)
        self.assertEquals(GroupedMessage.objects.count(), 1)
        last = Message.objects.get()
        self.assertEquals(last.url, u'http://testserver/non-existant-page')
        self.assertEquals(last.level, logging.INFO)
        self.assertEquals(last.logger, 'http404')

        django_settings.MIDDLEWARE_CLASSES = existing

    def test_response_error_id_middleware(self):
        # TODO: test with 500s
        existing = django_settings.MIDDLEWARE_CLASSES

        django_settings.MIDDLEWARE_CLASSES = (
            'sentry.client.middleware.SentryResponseErrorIdMiddleware',
            'sentry.client.middleware.Sentry404CatchMiddleware',
        ) + django_settings.MIDDLEWARE_CLASSES

        resp = self.client.get('/non-existant-page')
        self.assertEquals(resp.status_code, 404)
        headers = dict(resp.items())
        self.assertTrue(headers.get('X-Sentry-ID'))
        self.assertTrue(Message.objects.filter(message_id=headers['X-Sentry-ID']).exists())

        django_settings.MIDDLEWARE_CLASSES = existing

    def test_extra_storage(self):
        from sentry.utils import MockDjangoRequest

        request = MockDjangoRequest(
            META = {'foo': 'bar'},
        )

        logger = logging.getLogger()

        self.setUpHandler()

        logger.error('This is a test %s', 'error', extra={
            'request': request,
            'data': {
                'baz': 'bar',
            }
        })
        self.assertEquals(Message.objects.count(), 1)
        self.assertEquals(GroupedMessage.objects.count(), 1)
        last = Message.objects.get()
        self.assertEquals(last.logger, 'root')
        self.assertEquals(last.level, logging.ERROR)
        self.assertEquals(last.message, 'This is a test error')
        self.assertTrue('META' in last.data)
        self.assertTrue('foo' in last.data['META'])
        self.assertEquals(last.data['META']['foo'], 'bar')
        self.assertTrue('baz' in last.data)
        self.assertEquals(last.data['baz'], 'bar')

    def test_raw_post_data(self):
        from sentry.utils import MockDjangoRequest

        request = MockDjangoRequest(
            raw_post_data = '{"json": "string"}',
        )

        logger = logging.getLogger()

        self.setUpHandler()

        logger.error('This is a test %s', 'error', extra={
            'request': request,
            'data': {
                'baz': 'bar',
            }
        })
        self.assertEquals(Message.objects.count(), 1)
        self.assertEquals(GroupedMessage.objects.count(), 1)
        last = Message.objects.get()
        self.assertEquals(last.logger, 'root')
        self.assertEquals(last.level, logging.ERROR)
        self.assertEquals(last.message, 'This is a test error')
        self.assertTrue('POST' in last.data)
        self.assertEquals(request.raw_post_data, last.data['POST'])

    def test_score_update(self):
        self.assertRaises(Exception, self.client.get, reverse('sentry-raise-exc'))

        self.assertEquals(GroupedMessage.objects.count(), 1)
        group = GroupedMessage.objects.get()
        self.assertTrue(group.score > 0, group.score)

        # drop the score to ensure its getting re-set
        group.score = 0
        group.save()

        self.assertRaises(Exception, self.client.get, reverse('sentry-raise-exc'))
        self.assertEquals(GroupedMessage.objects.count(), 1)

        group = GroupedMessage.objects.get()
        self.assertTrue(group.score > 0, group.score)

    def test_shorten_lists(self):
        logger = logging.getLogger()

        self.setUpHandler()

        base_list = range(500)

        logger.error('This is a test %s', 'error', extra={'data': {
            'list': base_list,
            'set': set(base_list),
            'tuple': tuple(base_list),
            'frozenset': frozenset(base_list),
        }})
        self.assertEquals(Message.objects.count(), 1)
        self.assertEquals(GroupedMessage.objects.count(), 1)
        last = Message.objects.get()

        # test list length
        self.assertTrue('list' in last.data)
        self.assertEquals(len(last.data['list']), 52) # 20 + 2 extra ele
        self.assertEquals(last.data['list'][-2], '...')
        self.assertEquals(last.data['list'][-1], '(450 more elements)')

        # test set length
        self.assertTrue('set' in last.data)
        self.assertEquals(len(last.data['set']), 52) # 20 + 2 extra ele
        self.assertEquals(last.data['set'][-2], '...')
        self.assertEquals(last.data['set'][-1], '(450 more elements)')

        # test frozenset length
        self.assertTrue('frozenset' in last.data)
        self.assertEquals(len(last.data['frozenset']), 52) # 20 + 2 extra ele
        self.assertEquals(last.data['frozenset'][-2], '...')
        self.assertEquals(last.data['frozenset'][-1], '(450 more elements)')

        # test tuple length
        self.assertTrue('tuple' in last.data)
        self.assertEquals(len(last.data['tuple']), 52) # 20 + 2 extra ele
        self.assertEquals(last.data['tuple'][-2], '...')
        self.assertEquals(last.data['tuple'][-1], '(450 more elements)')

class SentryViewsTest(BaseTestCase):
    fixtures = ['tests/fixtures/views.json']

    def setUp(self):
        self.user = User(username="admin", email="admin@localhost", is_staff=True, is_superuser=True)
        self.user.set_password('admin')
        self.user.save()

    def test_auth(self):
        resp = self.client.get(reverse('sentry'), follow=True)
        self.assertEquals(resp.status_code, 200)
        self.assertTemplateUsed(resp, 'sentry/login.html')

        resp = self.client.post(reverse('sentry-login'), {
            'username': 'admin',
            'password': 'admin',
        }, follow=True)
        self.assertEquals(resp.status_code, 200)
        self.assertTemplateUsed(resp, 'sentry/index.html')

    def test_dashboard(self):
        self.client.login(username='admin', password='admin')
        resp = self.client.get(reverse('sentry') + '?sort=freq', follow=True)
        self.assertEquals(resp.status_code, 200)
        self.assertTemplateUsed(resp, 'sentry/index.html')
        self.assertEquals(len(resp.context['message_list']), 4)
        group = resp.context['message_list'][0]
        self.assertEquals(group.times_seen, 7)
        self.assertEquals(group.class_name, 'AttributeError')

    def test_group_details(self):
        self.client.login(username='admin', password='admin')
        resp = self.client.get(reverse('sentry-group', args=[2]), follow=True)
        self.assertEquals(resp.status_code, 200, resp.content)
        self.assertTemplateUsed(resp, 'sentry/group/details.html')

class SentryRemoteTest(BaseTestCase):

    def setUp(self):
        settings.REMOTE_URL = ['http://localhost:8000%s' % reverse('sentry-store')]
        logger = logging.getLogger('sentry')
        for h in logger.handlers:
            logger.removeHandler(h)
        logger.addHandler(logging.StreamHandler())

    def tearDown(self):
        settings.REMOTE_URL = None

    def test_no_key(self):
        resp = self.client.post(reverse('sentry-store'))
        self.assertEquals(resp.status_code, 400)

    def test_no_data(self):
        resp = self.client.post(reverse('sentry-store'), {
            'key': settings.KEY,
        })
        self.assertEquals(resp.status_code, 400)

    def test_bad_data(self):
        resp = self.client.post(reverse('sentry-store'), {
            'key': settings.KEY,
            'data': 'hello world',
        })
        self.assertEquals(resp.status_code, 403)
        self.assertEquals(resp.content, 'Bad data decoding request (TypeError, Incorrect padding)')

    def test_correct_data(self):
        kwargs = {'message': 'hello', 'server_name': 'not_dcramer.local', 'level': 40, 'site': 'not_a_real_site'}
        resp = self._postWithSignature(kwargs)
        self.assertEquals(resp.status_code, 200)
        instance = Message.objects.get()
        self.assertEquals(instance.message, 'hello')
        self.assertEquals(instance.server_name, 'not_dcramer.local')
        self.assertEquals(instance.level, 40)
        self.assertEquals(instance.site, 'not_a_real_site')

    def test_unicode_keys(self):
        kwargs = {u'message': 'hello', u'server_name': 'not_dcramer.local', u'level': 40, u'site': 'not_a_real_site'}
        resp = self._postWithSignature(kwargs)
        self.assertEquals(resp.status_code, 200, resp.content)
        instance = Message.objects.get()
        self.assertEquals(instance.message, 'hello')
        self.assertEquals(instance.server_name, 'not_dcramer.local')
        self.assertEquals(instance.level, 40)
        self.assertEquals(instance.site, 'not_a_real_site')

    def test_timestamp(self):
        timestamp = datetime.datetime.now() - datetime.timedelta(hours=1)
        kwargs = {u'message': 'hello', 'timestamp': timestamp.strftime('%s.%f')}
        resp = self._postWithSignature(kwargs)
        self.assertEquals(resp.status_code, 200, resp.content)
        instance = Message.objects.get()
        self.assertEquals(instance.message, 'hello')
        self.assertEquals(instance.datetime, timestamp)
        group = instance.group
        self.assertEquals(group.first_seen, timestamp)
        self.assertEquals(group.last_seen, timestamp)

    def test_timestamp_as_iso(self):
        timestamp = datetime.datetime.now() - datetime.timedelta(hours=1)
        kwargs = {u'message': 'hello', 'timestamp': timestamp.strftime('%Y-%m-%dT%H:%M:%S.%f')}
        resp = self._postWithSignature(kwargs)
        self.assertEquals(resp.status_code, 200, resp.content)
        instance = Message.objects.get()
        self.assertEquals(instance.message, 'hello')
        self.assertEquals(instance.datetime, timestamp)
        group = instance.group
        self.assertEquals(group.first_seen, timestamp)
        self.assertEquals(group.last_seen, timestamp)

    def test_ungzipped_data(self):
        kwargs = {'message': 'hello', 'server_name': 'not_dcramer.local', 'level': 40, 'site': 'not_a_real_site'}
        resp = self._postWithSignature(kwargs)
        self.assertEquals(resp.status_code, 200)
        instance = Message.objects.get()
        self.assertEquals(instance.message, 'hello')
        self.assertEquals(instance.server_name, 'not_dcramer.local')
        self.assertEquals(instance.site, 'not_a_real_site')
        self.assertEquals(instance.level, 40)

    def test_byte_sequence(self):
        """
        invalid byte sequence for encoding "UTF8": 0xedb7af
        """
        # TODO:
        # add 'site' to data in fixtures/bad_data.json, then assert it's set correctly below

        fname = os.path.join(os.path.dirname(__file__), 'fixtures/bad_data.json')
        data = open(fname).read()

        resp = self.client.post(reverse('sentry-store'), {
            'data': data,
            'key': settings.KEY,
        })

        self.assertEquals(resp.status_code, 200)

        instance = Message.objects.get()

        self.assertEquals(instance.message, 'invalid byte sequence for encoding "UTF8": 0xeda4ac\nHINT:  This error can also happen if the byte sequence does not match the encoding expected by the server, which is controlled by "client_encoding".\n')
        self.assertEquals(instance.server_name, 'shilling.disqus.net')
        self.assertEquals(instance.level, 40)
        self.assertTrue(instance.data['__sentry__']['exc'])

    def test_legacy_auth(self):
        kwargs = {'message': 'hello', 'server_name': 'not_dcramer.local', 'level': 40, 'site': 'not_a_real_site'}

        resp = self._postWithKey(kwargs)

        self.assertEquals(resp.status_code, 200, resp.content)

        instance = Message.objects.get()

        self.assertEquals(instance.message, 'hello')
        self.assertEquals(instance.server_name, 'not_dcramer.local')
        self.assertEquals(instance.site, 'not_a_real_site')
        self.assertEquals(instance.level, 40)

    def test_signature(self):
        kwargs = {'message': 'hello', 'server_name': 'not_dcramer.local', 'level': 40, 'site': 'not_a_real_site'}

        resp = self._postWithSignature(kwargs)

        self.assertEquals(resp.status_code, 200, resp.content)

        instance = Message.objects.get()

        self.assertEquals(instance.message, 'hello')
        self.assertEquals(instance.server_name, 'not_dcramer.local')
        self.assertEquals(instance.site, 'not_a_real_site')
        self.assertEquals(instance.level, 40)

    def test_broken_cache(self):
        from django.core.cache import cache
        add_func = cache.add
        cache.add = lambda: False

        client = get_client()

        settings.THRASHING_LIMIT = 10
        settings.THRASHING_TIMEOUT = 60

        result = client.check_throttle('foobar')

        self.assertEquals(result, (False, None))

        cache.add = add_func

    # def test_function_exception(self):
    #     try: raise Exception(lambda:'foo')
    #     except: get_client().create_from_exception()
    #
    #     last = Message.objects.get()
    #
    #     self.assertEquals(last.view, 'tests.tests.testFunctionException')

class SentryRemoteServerTest(TransactionTestCase):
    urls = 'tests.urls'

    def setUp(self):
        self.server_thread = None
        logger = logging.getLogger('sentry')
        for h in logger.handlers:
            logger.removeHandler(h)
        logger.addHandler(logging.StreamHandler())

    def tearDown(self):
        self.stop_test_server()
        settings.REMOTE_URL = None

    def start_test_server(self, host='localhost', port=None):
        """Creates a live test server object (instance of WSGIServer)."""
        if not port:
            for port in xrange(8001, 8050):
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
                try:
                    s.bind((host, port))
                except socket.error:
                    port = None
                    continue
                else:
                    break
                finally:
                    s.close()
        if not port:
            raise socket.error('Unable to find an open port to bind server')

        self._orig_remote_url = settings.REMOTE_URL
        settings.REMOTE_URL = ['http://%s:%s/store/' % (host, port)]
        self.server_thread = TestServerThread(self, host, port)
        self.server_thread.start()
        self.server_thread.started.wait()
        if self.server_thread.error:
            raise self.server_thread.error

    def stop_test_server(self):
        if self.server_thread:
            settings.REMOTE_URL = self._orig_remote_url
            self.server_thread.join()

    def test_process(self):
        self.start_test_server()
        message_id = SentryClient().process(message='hello')
        self.stop_test_server()

        self.assertTrue(message_id)
        instance = Message.objects.all().order_by('-id')[0]
        self.assertEquals(instance.message, 'hello')

    def test_external(self):
        self.start_test_server()
        path = reverse('sentry-raise-exc')
        self.stop_test_server()

        self.assertRaises(Exception, self.client.get, path)
        instance = Message.objects.all().order_by('-id')[0]
        self.assertEquals(instance.message, 'view exception')
        self.assertEquals(instance.url, 'http://testserver' + path)

    def test_timestamp(self):
        timestamp = datetime.datetime.now() - datetime.timedelta(hours=1)

        self.start_test_server()
        message_id = SentryClient().process(message='hello', timestamp=timestamp)
        self.stop_test_server()

        self.assertTrue(message_id)
        instance = Message.objects.all().order_by('-id')[0]
        self.assertEquals(instance.message, 'hello')
        self.assertEquals(instance.datetime, timestamp)
        group = instance.group
        self.assertEquals(group.first_seen, timestamp)
        self.assertEquals(group.last_seen, timestamp)

class SentryFeedsTest(BaseTestCase):
    fixtures = ['tests/fixtures/feeds.json']

    def test_message_feed(self):
        response = self.client.get(reverse('sentry-feed-messages'))
        self.assertEquals(response.status_code, 200)
        self.assertTrue(response.content.startswith('<?xml version="1.0" encoding="utf-8"?>'))
        self.assertTrue('<link>http://testserver/</link>' in response.content)
        self.assertTrue('<title>log messages</title>' in response.content)
        self.assertTrue('<link>http://testserver/group/1</link>' in response.content, response.content)
        self.assertTrue('<title>TypeError: exceptions must be old-style classes or derived from BaseException, not NoneType</title>' in response.content)

    def test_summary_feed(self):
        response = self.client.get(reverse('sentry-feed-summaries'))
        self.assertEquals(response.status_code, 200)
        self.assertTrue(response.content.startswith('<?xml version="1.0" encoding="utf-8"?>'))
        self.assertTrue('<link>http://testserver/</link>' in response.content)
        self.assertTrue('<title>log summaries</title>' in response.content)
        self.assertTrue('<link>http://testserver/group/1</link>' in response.content, response.content)
        self.assertTrue('<title>(1) TypeError: exceptions must be old-style classes or derived from BaseException, not NoneType</title>' in response.content)

class SentryMailTest(BaseTestCase):
    fixtures = ['tests/fixtures/mail.json']

    def setUp(self):
        settings.ADMINS = ('%s@localhost' % getpass.getuser(),)

    def test_mail_admins(self):
        group = GroupedMessage.objects.get()
        self.assertEquals(len(mail.outbox), 0)
        group.mail_admins(fail_silently=False)
        self.assertEquals(len(mail.outbox), 1)

        out = mail.outbox[0]

        self.assertTrue('Traceback (most recent call last):' in out.body)
        self.assertTrue("COOKIES:{'commenter_name': 'admin'," in out.body, out.body)
        self.assertEquals(out.subject, '[Django] Error (EXTERNAL IP): /group/1')

    def test_mail_on_creation(self):
        settings.MAIL = True

        self.assertEquals(len(mail.outbox), 0)
        self.assertRaises(Exception, self.client.get, reverse('sentry-raise-exc'))
        self.assertEquals(len(mail.outbox), 1)
        self.assertRaises(Exception, self.client.get, reverse('sentry-raise-exc'))
        self.assertEquals(len(mail.outbox), 1)

        out = mail.outbox[0]

        self.assertTrue('Traceback (most recent call last):' in out.body)
        self.assertTrue("<Request" in out.body)
        self.assertEquals(out.subject, '[example.com] [Django] Error (EXTERNAL IP): /trigger-500')

    def test_mail_on_duplication(self):
        settings.MAIL = True

        self.assertEquals(len(mail.outbox), 0)
        self.assertRaises(Exception, self.client.get, reverse('sentry-raise-exc'))
        self.assertEquals(len(mail.outbox), 1)
        self.assertRaises(Exception, self.client.get, reverse('sentry-raise-exc'))
        self.assertEquals(len(mail.outbox), 1)
        # XXX: why wont this work
        # group = GroupedMessage.objects.update(status=1)
        group = GroupedMessage.objects.all().order_by('-id')[0]
        group.status = 1
        group.save()
        self.assertRaises(Exception, self.client.get, reverse('sentry-raise-exc'))
        self.assertEquals(len(mail.outbox), 2)
        self.assertRaises(Exception, self.client.get, reverse('sentry-raise-exc'))
        self.assertEquals(len(mail.outbox), 2)

        out = mail.outbox[1]

        self.assertTrue('Traceback (most recent call last):' in out.body)
        self.assertTrue("<Request" in out.body)
        self.assertEquals(out.subject, '[example.com] [Django] Error (EXTERNAL IP): /trigger-500')

    def test_url_prefix(self):
        settings.URL_PREFIX = 'http://example.com'

        group = GroupedMessage.objects.get()
        group.mail_admins(fail_silently=False)

        out = mail.outbox[0]

        self.assertTrue('http://example.com/group/2' in out.body, out.body)

class SentryHelpersTest(BaseTestCase):
    def test_get_db_engine(self):
        from sentry.utils import get_db_engine
        _databases = getattr(django_settings, 'DATABASES', {}).copy()
        _engine = django_settings.DATABASE_ENGINE

        django_settings.DATABASE_ENGINE = ''
        django_settings.DATABASES['default'] = {'ENGINE': 'blah.sqlite3'}

        self.assertEquals(get_db_engine(), 'sqlite3')

        django_settings.DATABASE_ENGINE = 'mysql'

        self.assertEquals(get_db_engine(), 'sqlite3')

        django_settings.DATABASES['default'] = {'ENGINE': 'blah.mysql'}

        self.assertEquals(get_db_engine(), 'mysql')

        django_settings.DATABASES = _databases
        django_settings.DATABASE_ENGINE = _engine

    def test_get_versions(self):
        import sentry
        from sentry.utils import get_versions
        versions = get_versions(['sentry'])
        self.assertEquals(versions.get('sentry'), sentry.VERSION)
        versions = get_versions(['sentry.client'])
        self.assertEquals(versions.get('sentry'), sentry.VERSION)

class SentryTransformTest(BaseTestCase):
    def test_bad_string(self):
        x = 'The following character causes problems: \xd4'

        result = transform(x)
        self.assertEquals(result, '(Error decoding value)')

    def test_model_instance(self):
        instance = DuplicateKeyModel(foo='foo')

        result = transform(instance)
        self.assertEquals(result, '<DuplicateKeyModel: foo>')

    def test_handles_gettext_lazy(self):
        def fake_gettext(to_translate):
            return u'Igpay Atinlay'

        fake_gettext_lazy = lazy(fake_gettext, str)

        self.assertEquals(
            pickle.loads(pickle.dumps(
                    transform(fake_gettext_lazy("something")))),
            u'Igpay Atinlay')

class SentryClientTest(BaseTestCase):
    def setUp(self):
        self._client = settings.CLIENT

    def tearDown(self):
        settings.CLIENT = self._client

    def test_get_client(self):
        from sentry.client.log import LoggingSentryClient

        self.assertEquals(get_client().__class__, SentryClient)
        self.assertEquals(get_client(), get_client())

        settings.CLIENT = 'sentry.client.log.LoggingSentryClient'

        self.assertEquals(get_client().__class__, LoggingSentryClient)
        self.assertEquals(get_client(), get_client())

        settings.CLIENT = 'sentry.client.base.SentryClient'

    def test_logging_client(self):
        settings.CLIENT = 'sentry.client.log.LoggingSentryClient'

        client = get_client()

        _foo = {'': None}

        class handler(logging.Handler):
            def emit(self, record):
                _foo[''] = record

        logger = client.logger
        logger.addHandler(handler())

        self.assertRaises(Exception, self.client.get, reverse('sentry-raise-exc'))

        self.assertEquals(_foo[''].getMessage(), 'view exception')
        self.assertEquals(_foo[''].levelno, client.default_level)
        self.assertEquals(_foo[''].class_name, 'Exception')

    @conditional_on_module('djcelery')
    def test_celery_client(self):
        from sentry.client.celery import CelerySentryClient

        self.assertEquals(get_client().__class__, SentryClient)
        self.assertEquals(get_client(), get_client())

        settings.CLIENT = 'sentry.client.celery.CelerySentryClient'

        self.assertEquals(get_client().__class__, CelerySentryClient)
        self.assertEquals(get_client(), get_client())

        self.assertRaises(Exception, self.client.get, reverse('sentry-raise-exc'))

        message = GroupedMessage.objects.get()
        self.assertEqual(message.class_name, 'Exception')
        self.assertEqual(message.message, 'view exception')

        settings.CLIENT = 'sentry.client.base.SentryClient'

    # XXX: need to fix behavior with threads so this test works correctly
    # def test_async_client(self):
    #     from sentry.client.async import AsyncSentryClient
    #
    #     self.assertEquals(get_client().__class__, SentryClient)
    #     self.assertEquals(get_client(), get_client())
    #
    #     settings.CLIENT = 'sentry.client.async.AsyncSentryClient'
    #
    #     self.assertEquals(get_client().__class__, AsyncSentryClient)
    #     self.assertEquals(get_client(), get_client())
    #
    #     self.assertRaises(Exception, self.client.get, reverse('sentry-raise-exc'))
    #
    #     message = GroupedMessage.objects.get()
    #     self.assertEqual(message.class_name, 'Exception')
    #     self.assertEqual(message.message, 'view exception')
    #
    #     settings.CLIENT = 'sentry.client.base.SentryClient'

class SentryCommandTest(BaseTestCase):
    fixtures = ['tests/fixtures/cleanup.json']

    def test_cleanup(self):
        from sentry.scripts.runner import cleanup

        self.assertEquals(Message.objects.count(), 10)

        cleanup(days=1)

        self.assertEquals(Message.objects.count(), 0)

class SentrySearchTest(BaseTestCase):
    @conditional_on_module('haystack')
    def test_build_index(self):
        from sentry.web.views import get_search_query_set
        logger.error('test search error')

        qs = get_search_query_set('error')
        self.assertEquals(qs.count(), 1)
        self.assertEquals(qs[0:1][0].message, 'test search error')


text:
set -e -o pipefail

CHEFDK_VERSION=3.9.0
DOWNLOAD_DIR=/tmp/vagrant-cache/wget
REPO_ROOT=~/vm-setup
CMD_LINE_FLAG=$1

main() {
  setup_chefdk
  if [[ "$CMD_LINE_FLAG" == "--verify-only" ]]; then
    verify_vm
  else
    copy_repo_and_symlink_self
    [[ "$CMD_LINE_FLAG" == "--pull" ]] && update_repo
    update_vm
    [[ "$CMD_LINE_FLAG" == "--provision-only" ]] || verify_vm
  fi
}

setup_chefdk() {
  big_step "Setting up ChefDK..."
  if [[ $(head -n1 /opt/chefdk/version-manifest.txt 2>/dev/null | grep "chefdk $CHEFDK_VERSION") ]]; then
    echo "ChefDK $CHEFDK_VERSION already installed"
  else
    step "Downloading and installing ChefDK $CHEFDK_VERSION"
    curl -L https://omnitruck.chef.io/install.sh | sudo bash -s -- -P chefdk -c stable -v $CHEFDK_VERSION -d /tmp/vagrant-cache
  fi
  # initialize the shell, adding ChefDK binaries to the PATH
  eval "$(chef shell-init bash)"
}

copy_repo_and_symlink_self() {
  big_step "Copying repo into the VM..."
  if mountpoint -q /vagrant; then
    sudo rm -rf $REPO_ROOT
    sudo cp -r /vagrant $REPO_ROOT
    sudo chown -R $USER:$USER $REPO_ROOT
    sudo ln -sf $REPO_ROOT/scripts/update-vm.sh /usr/local/bin/update-vm
    echo "Copied repo to $REPO_ROOT and symlinked the 'update-vm' script"
  else
    echo "Skipped because /vagrant not mounted"
  fi
}

update_vm() {
  big_step "Updating the VM via Chef..."
  cd $REPO_ROOT/cookbooks/vm

  step "install cookbook dependencies"
  berks vendor --delete ./cookbooks

  # disable vmware ohai plugin because it's so painfully slow
  sudo find /opt/chefdk/embedded/ -wholename *ohai* -name vmware.rb -exec mv {} {}.disabled \;

  step "update the system via chef-zero"
  sudo -H chef-client --config-option node_path=/root/.chef/nodes --local-mode --format=doc --force-formatter --log_level=warn --color --runlist=vm
}

verify_vm() {
  big_step "Verifying the VM..."
  cd $REPO_ROOT/cookbooks/vm

  step "run foodcritic linting checks"
  foodcritic -f any .

  step "run serverspec integration tests"
  rspec --require rspec_junit_formatter --format doc --color --tty --format RspecJunitFormatter --out test/junit-report.xml --format html --out test/test-report.html
}

update_repo() {
  big_step "Pulling latest changes from git..."
  cd $REPO_ROOT
  git pull
}

big_step() {
  echo -e "\n=====================================\n>>>>>> $1\n=====================================\n"
}
step() {
  echo -e "\n\n>>>>>> $1\n-------------------------------------\n"
}

# run it!
main


text:
using Dapper;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Dynamic;
using System.Linq;
using System.Reflection;
using System.Text;
using Wicture.DbRESTFul.Converters;

namespace Wicture.DbRESTFul
{
    internal class SQLBuilder
    {
        public string[] TableNames { get; set; }

        private string connectionString;

        public SQLBuilder(string connectionString)
        {
            this.connectionString = connectionString;
        }

        /// <summary>
        /// 生成Insert查询SQL
        /// </summary>
        public string BuildInsertSQL(string tableName, string parameters)
        {
            if (string.IsNullOrEmpty(parameters))
            {
                throw new ArgumentNullException("parameters");
            }

            var objArray = JsonConvert.DeserializeObject(parameters) as JArray;

            if (objArray == null)
            {
                throw new ParameterParseException("Unable to deserialize the parameters.");
            }

            string sql = null;

            foreach (var obj in objArray)
            {
                sql += string.Format("INSERT INTO {0} ", tableName);
                string cols = "(";
                string colsParams = "(";

                foreach (var item in obj as JObject)
                {
                    var v = item.Value.ToObject(typeof(object));
                    cols += "`" + item.Key.ToString() + "`,";
                    colsParams += new ValueObject() { Value = v } + ",";
                }

                sql += cols.Remove(cols.Length - 1) + ") VALUES " + colsParams.Remove(colsParams.Length - 1) + ");";

            }

            return sql;
        }

        /// <summary>
        /// 生成Select查询SQL
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="parameters"></param>
        /// <param name="countSql">查询总数的SQL,只需要传入新建的StringBuilder对象即可</param>
        public string BuildSelectSQL(string tableName, string parameters, StringBuilder countSql = null, Pagination pagination = null)
        {
            if (string.IsNullOrEmpty(parameters))
            {
                return "SELECT * FROM " + tableName;
            }

            var condition = string.Empty;

            var jToken = JObject.Parse(parameters);
            var param = ParameterParser.GetOperationParameter(jToken);
            var selectSQL = GetSelectSQL(param, tableName);

            var hasGroupBy = false;

            if (param.WhereParameter != null) condition += " WHERE " + param.WhereParameter;
            if (param.GroupByParameter != null)
            {
                hasGroupBy = true;

                condition += " GROUP BY " + string.Join(",", param.GroupByParameter.Select(e => "`" + e + "`"));
                if (param.HavingParameter != null) condition += " HAVING " + param.HavingParameter;
            }
            var countStr = condition;
            if (param.OrderParameter != null) condition += " " + param.OrderParameter;
            if (param.PaginationParameter != null)
            {
                condition += " " + param.PaginationParameter;
                if (pagination != null)
                {
                    pagination.index = param.PaginationParameter.Index;
                    pagination.size = param.PaginationParameter.Size;
                }
                if (countSql != null)
                {
                    if (hasGroupBy)
                        countSql.Clear().Append("SELECT COUNT(*) FROM (").Append(selectSQL).Append(countStr).Append(") AS TMPTABLE;");
                    else
                        countSql.Clear().Append("SELECT COUNT(*) FROM ").Append(tableName).Append(countStr);
                }
            }

            return selectSQL + condition;
        }

        /// <summary>
        /// 生成Update查询SQL
        /// </summary>
        public string BuildUpdateSQL(string tableName, string where, string parameters, out object parsedData)
        {
            var condition = string.Empty;
            if (!string.IsNullOrWhiteSpace(where))
            {
                var jToken = JObject.Parse(where);
                var param = ParameterParser.GetOperationParameter(jToken);

                if (param.WhereParameter != null) condition += " WHERE " + param.WhereParameter;
            }
            var obj = JsonConvert.DeserializeObject(parameters) as JObject;
            if (obj == null)
            {
                throw new ParameterParseException("Unable to deserialize the parameters.");
            }

            var data = new ExpandoObject() as IDictionary<string, Object>;

            foreach (var item in obj)
            {
                data.Add(item.Key, (item.Value as JValue).Value);
            }

            var dynamicParameter = new DynamicParameters(data);
            List<string> paramNames = GetParamNames(dynamicParameter);

            var b = new StringBuilder();
            b.Append("UPDATE `").Append(tableName).Append("` SET ");
            b.Append(string.Join(",", paramNames.Select(p => "`" + p + "`= @" + p)));
            b.Append(condition);

            parsedData = data;

            return b.ToString();
        }

        /// <summary>
        /// 生成Delete查询SQL
        /// </summary>
        public string BuildDeleteSQL(string tableName, string parameters)
        {
            if (string.IsNullOrEmpty(parameters))
            {
                return "DELETE FROM " + tableName;
            }

            var condition = string.Empty;
            var jToken = JObject.Parse(parameters);
            var param = ParameterParser.GetOperationParameter(jToken);

            if (param.WhereParameter != null) condition += " WHERE " + param.WhereParameter;

            var b = new StringBuilder();
            b.Append("DELETE FROM ").Append(tableName).Append(condition);

            return b.ToString();
        }

        private string GetSelectSQL(OperationParameter op, string tableName)
        {
            if (op == null || (op.ExcludesColumnParameter == null && op.IncludesColumnParameter == null))
            {
                return string.Format("SELECT * FROM {0}", tableName);
            }

            if (op.ExcludesColumnParameter != null)
            {
                var sql = @"SELECT `COLUMN_NAME`
                        FROM `INFORMATION_SCHEMA`.`COLUMNS`
                        WHERE TABLE_SCHEMA = '{0}' AND `TABLE_NAME`='{1}' {2};";

                var fields = "AND `COLUMN_NAME` NOT IN(" + string.Join(",", op.ExcludesColumnParameter.Select(e => { e.IsStringFormat = true; return "'" + e.ToString() + "'"; })) + ")";

                using (var cnn = new SqlConnection(connectionString))
                {
                    var columns = SqlMapper.Query<string>(cnn, string.Format(sql, cnn.Database, tableName, fields));

                    return string.Format("SELECT {0} FROM {1}", string.Join(",", columns.Select(e => "`" + e + "`")), tableName);
                }
            }
            else
            {
                var hasDistinct = op.IncludesColumnParameter.Any(e => (e is ComplexColumnObject) && (e as ComplexColumnObject).IsDistinct);
                return string.Format(hasDistinct ? "SELECT DISTINCT {0} FROM {1}" : "SELECT {0} FROM {1}", string.Join(",", op.IncludesColumnParameter.Select(e => e.ToString())), tableName);
            }
        }

        private List<string> GetParamNames(object o)
        {
            if (o is DynamicParameters)
            {
                return (o as DynamicParameters).ParameterNames.ToList();
            }

            List<string> paramNames = new List<string>();
            foreach (var prop in o.GetType().GetProperties(BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public))
            {
                paramNames.Add(prop.Name);

                //var attribs = prop.GetCustomAttributes(typeof(IgnorePropertyAttribute), true);
                //var attr = attribs.FirstOrDefault() as IgnorePropertyAttribute;
                //if (attr == null || (attr != null && !attr.Value))
                //{
                //}
            }

            return paramNames;
        }
    }
}


text:
package com.utils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Author Mr.Pro
 * Date   9/24/17 = 4:48 PM
 */
public class JavaCompilerUtils {

    public JavaCompilerUtils(String name) throws ClassNotFoundException {
        Class clazz = this.getClass().getClassLoader().loadClass(name);

        Method[] methods = clazz.getDeclaredMethods();
        List<String> methodList = new ArrayList<>();
        for (Method method : methods){
            String param = new String();
            for (Class paramClass : method.getParameterTypes()){
                param += paramClass.getName()+", ";
            }
            String temp = "";
            if(param.length()>0){
                temp = method.getName()+" ("+param.substring(0, param.length()-2)+")
";
            }else{
                temp = method.getName()+" ()
";
            }
            if(method.getDeclaredAnnotations().length>0){
                Annotation[] t = method.getDeclaredAnnotations();
                for (Annotation tt : t){
                    if (tt.annotationType().equals(java.lang.Deprecated.class)){
                        temp = "@Deprecated "+temp;
                    }
                }
            }
            methodList.add(temp);
        }
        methodList = methodList.stream().sorted().collect(Collectors.toList());
        methodList.forEach(item ->{
            System.out.println(item);
        });

    }

    public static void main(String[] args) throws ClassNotFoundException {
        new JavaCompilerUtils("java.lang.Thread");
    }

}